Skip to main content

ingraph_codegen/
prefix.rs

1//! The EMISSION NAMESPACE: the mark every name this crate mints into somebody else's scope wears,
2//! held as ONE value a front end sets rather than as a constant each mint re-spells.
3//!
4//! # What the seat is FOR, and who the second occupant is
5//!
6//! This crate is *model in, tokens out* — the derive builds a model today, and `ingraph-compiler`
7//! will build one from a manifest. Both of those are `ingraph`'s own front ends and both want
8//! `__ig`. The occupant this seat exists for is the third: a DOMAIN FRAMEWORK that depends on
9//! `ingraph-codegen` directly, builds the same models, and emits them under its own name —
10//! `mediagraph-codegen` is the first, and it passes `__mg`.
11//!
12//! Without the seat that framework's expansions would carry `ingraph`'s mark on every name they put
13//! in an author's scope, which is wrong twice over: the names read as another crate's, and the
14//! FENCE that makes them safe is a fence the other framework's derive is not holding. A namespace
15//! is minted in and refused in by the same party or it is not a namespace at all — see
16//! [`EmissionPrefix::refused`], which is the half a front end spends before it ever reaches a mint.
17//!
18//! # MIXED GRAPHS ARE LEGAL, which is why this is a value and not a feature flag
19//!
20//! One deployment may hold raw-`ingraph` records beside a platform's, and their names are per
21//! DECLARATION rather than per build: a `__ig_key__` field on one record and a `__mg_key__` field
22//! on the next are two expansions of two models, and nothing downstream is entitled to assume a
23//! single mark. A `cfg` or a crate-wide constant would have made that arrangement unrepresentable;
24//! a field on the model makes it the ordinary case.
25//!
26//! # WHAT IS AND IS NOT INSIDE THE SEAT
27//!
28//! The seat covers every name that lands in a SHARED namespace — the declaring module's scope, a
29//! database catalog, a wire face, or an emitted public API. Those are the names a second framework
30//! could stand beside, so those are the names a second framework must be able to move.
31//!
32//! It does NOT cover a name minted inside an anonymous `const _: () = { … }` block or bound by a
33//! `let` in a generated function body. Two expansions cannot see one another's anonymous const, so
34//! there is nothing there for a mark to separate — `__ig_says_goodbye` in
35//! [`crate::emit`] and `__ig_row` in [`crate::aggregate`] are spelled once, collide with nothing,
36//! and stay as they are. The tell is the FRAME: a name in the shared namespace wears `__` at both
37//! ends, and every one of those is threaded here.
38
39use std::borrow::Cow;
40
41use quote::format_ident;
42
43/// The mark a framework's emitted names are minted under — `__ig` for `ingraph` itself.
44///
45/// # It holds the mark WITHOUT the joining underscore
46///
47/// `__ig`, not `__ig_`: the separator belongs to the join rather than to the namespace, because the
48/// two shapes this mints — [`framed`](Self::framed) and [`prefixed`](Self::prefixed) — place it
49/// identically and a mark carrying its own would make one of them spell a double. It is also the
50/// shape the FENCE reads: a declared name is refused for *starting with the mark*, and a fence
51/// holding `__ig_` would let a column called `__ig` itself through.
52///
53/// # `Cow`, because both occupants are real
54///
55/// The framework's own mark is a `&'static str` and costs nothing to carry; a front end computing
56/// one — from a manifest, or from a domain crate's own configuration — owns a `String`. A `Cow`
57/// serves both without making the common case allocate, and [`INGRAPH`](Self::INGRAPH) is `const`
58/// for the same reason.
59#[derive(Debug, Clone, PartialEq, Eq, Hash)]
60pub struct EmissionPrefix(Cow<'static, str>);
61
62impl Default for EmissionPrefix {
63  /// The framework's own, which is what every `ingraph` front end passes and what a model built
64  /// without a thought about namespaces has to be.
65  fn default() -> Self {
66    Self::INGRAPH
67  }
68}
69
70impl EmissionPrefix {
71  /// `ingraph`'s own namespace — the answer every model this repository's derive builds carries.
72  ///
73  /// It reads [`crate::alias::ALIAS_PREFIX`] rather than re-spelling it, so the string lives in one
74  /// place and the alias mint, the companion column and the injected fields cannot drift apart.
75  pub const INGRAPH: Self = Self(Cow::Borrowed(crate::alias::ALIAS_PREFIX));
76
77  /// A domain framework's own mark.
78  ///
79  /// Nothing is checked here: [`refused`](Self::refused) is where the rules are, and it is spent by
80  /// the front end that has a span to report at. A mint that validated would be answering a
81  /// question its caller has already had to answer — the arrangement
82  /// [`crate::alias::alias`] already keeps one module over.
83  pub fn new(mark: impl Into<Cow<'static, str>>) -> Self {
84    Self(mark.into())
85  }
86
87  /// The mark itself, for the two places that need the bare string: the FENCE a front end holds
88  /// declared names to, and the alias mint that spends it as a byte budget.
89  #[must_use]
90  pub fn mark(&self) -> &str {
91    &self.0
92  }
93
94  /// Whether this is the framework's own — the question a front end asks about the SEAT.
95  ///
96  /// It is what says *this model moved nothing*, and it is why a declaration under the default mark
97  /// expands byte for byte as it did before this seat existed.
98  ///
99  /// # It is NOT the question an emission asks before staying silent
100  ///
101  /// That one is
102  /// [`InterfaceModel::mints_the_default_words`](crate::interface::InterfaceModel::mints_the_default_words),
103  /// and it compares against `ingraph`'s own constant rather than against this — because what an
104  /// emission may leave unsaid is decided by what the ENGINE already believes, and the engine holds
105  /// one default whoever built the model. The two coincide for `ingraph`'s front ends and part
106  /// company for a platform's, which is exactly where the distinction earns its keep.
107  #[must_use]
108  pub fn is_default(&self) -> bool {
109    self.0 == Self::INGRAPH.0
110  }
111
112  /// `__ig_<word>__` — a name in the SYNTHESIZED-COLUMN frame.
113  ///
114  /// The shape a framework-invented FIELD or COLUMN wears: the mark in front and `__` behind. Both
115  /// ends are load-bearing. The front is what a fence refuses a declared name for; the back is what
116  /// makes the join INJECTIVE, since the word is then everything between two fixed strings and two
117  /// words cannot reach one name.
118  ///
119  /// A word whose tail looks like `_<digits>__` is the one shape this cannot carry — that is the
120  /// alias mint's own tail, and a framed word ending in one would be reachable by a join as well.
121  /// Where a mint is indexed the digits FUSE into the word (`__ig_ord0__`, never `__ig_ord_0__`).
122  #[must_use]
123  pub fn framed(&self, word: &str) -> String {
124    format!("{}_{word}__", self.0)
125  }
126
127  /// [`framed`](Self::framed) as an identifier, for the fields and items an expansion writes.
128  ///
129  /// # It cannot be spanned here
130  ///
131  /// The call site sets the span, because a framework-minted name has no source to point at and the
132  /// span a diagnostic wants is the DECLARATION's. Every caller today takes `Span::call_site`,
133  /// which is what `format_ident!` gives.
134  #[must_use]
135  pub fn framed_ident(&self, word: &str) -> syn::Ident {
136    format_ident!("{}", self.framed(word))
137  }
138
139  /// `__ig_<word>` — a name in the namespace but OUTSIDE the frame.
140  ///
141  /// The shape for a minted ITEM rather than a column: a marker const, a DDL object, an audit
142  /// function. It wears no tail because there is nothing to keep injective — such a name already
143  /// ends in a word this crate chose, and the frame is the COLUMN law rather than the namespace's.
144  #[must_use]
145  pub fn prefixed(&self, word: &str) -> String {
146    format!("{}_{word}", self.0)
147  }
148
149  /// [`prefixed`](Self::prefixed) as an identifier, spanned at the call site for
150  /// [`framed_ident`](Self::framed_ident)'s reason.
151  #[must_use]
152  pub fn prefixed_ident(&self, word: &str) -> syn::Ident {
153    format_ident!("{}", self.prefixed(word))
154  }
155
156  /// Why this mark cannot be a namespace, or [`None`] where it can.
157  ///
158  /// # The rules are the MINT's, which is why they live beside it rather than in a front end
159  ///
160  /// A mark is spent in three shapes — a framed column, a prefixed item, and a clamped SQL
161  /// alias — and what it must be is decided by what those spend it as. A second copy of these
162  /// rules in whichever crate happens to read the configuration is the copy that drifts the day a
163  /// mint's shape moves. What a front end adds is the SPAN: this answers in prose and knows
164  /// nothing about tokens.
165  ///
166  /// The byte BUDGET is deliberately not here. It is a fact about the alias mint alone — how much
167  /// of a table's own name survives PostgreSQL's sixty-three — and it depends on a depth this seat
168  /// has never heard of; [`crate::alias::refused`] is where the pair is held together.
169  #[must_use]
170  pub fn refused(mark: &str) -> Option<String> {
171    if mark.is_empty() {
172      return Some(
173        "an emission namespace names the mark every framework-minted name wears, and an empty one \
174         names none — the minted names would begin with the declaration's own words, where a \
175         column or an item the author declared collides with one the expansion invented and \
176         neither party is holding a fence"
177          .to_owned(),
178      );
179    }
180    if !mark.starts_with(FRAMEWORK_LEAD) {
181      return Some(format!(
182        "`{mark}` does not begin `{FRAMEWORK_LEAD}` — a namespace is FENCED as well as minted in, \
183         so every column and item name starting with it stops being declarable, and a bare word \
184         would confiscate a namespace this schema's own author is using. Lead with \
185         `{FRAMEWORK_LEAD}`, which is the shape a reader already reads as a framework's"
186      ));
187    }
188    if let Some(stray) = mark
189      .chars()
190      .find(|char| !crate::alias::legal_in_prefix(*char))
191    {
192      return Some(format!(
193        "`{mark}` holds `{stray}`, which a minted name cannot carry — the name is joined with `_`, \
194         spelled as a Rust identifier and read back by eye at a `FROM`, so the namespace is ASCII \
195         letters, digits and `_`. A dialect would quote anything, and what it cannot do is make it \
196         an identifier"
197      ));
198    }
199    None
200  }
201}
202
203/// What every namespace leads with, framework's or platform's — and what a DECLARED
204/// `<db>(alias(prefix = …))` is held to by [`crate::alias::refused`], which reads it from here.
205///
206/// The shape a reader already reads as *not the author's*, and the one rule that keeps two
207/// frameworks' marks inside one reserved region instead of each confiscating a word of the
208/// declaration's own vocabulary. ONE spelling, because the two seats fence the same region: a lead
209/// the platform seat admitted and the alias word refused would be a namespace a model could hold
210/// and no database could mint in.
211pub(crate) const FRAMEWORK_LEAD: &str = "__";
212
213#[cfg(test)]
214mod tests;