ingraph_derive/lib.rs
1#![deny(missing_docs)]
2// The docs.rs badge half: `doc_cfg` derives the "Available on crate feature `x` only" banner from
3// the `cfg` a gated item already carries. This crate declares NO features, so it derives nothing
4// today — the attribute is here because the knob that turns it on is, and the two belong together:
5// `docsrs` is set by the `rustdoc-args` in `[package.metadata.docs.rs]` below and by nothing else,
6// so a root that never named `doc_cfg` would leave that cfg dangling. Nightly-only, hence the
7// `cfg_attr`; every stable build compiles a crate that has never heard of `docsrs`.
8#![cfg_attr(docsrs, feature(doc_cfg))]
9//! The macros for [`ingraph`](https://docs.rs/ingraph).
10//!
11//! These expand a declaration into the framework faces a record must implement — `Transformer`,
12//! the per-backend record impls and the query bindings. They generate **framework** faces only:
13//! domain validation, constructor invariants and the error enums that mirror them belong to the
14//! application's own types.
15//!
16//! **Today they expand the key TYPES and the binding that ties them to the record.** [`Record`]
17//! emits `*Key`, `*Lineage`, `impl Transformer for <Record>` and the `Identifiable` supertrait it
18//! cannot be written without — on the record and on the `*Key` both, the two types carrying the same
19//! id column. The rest of the trait layer is still moving, and an expansion naming a half-settled
20//! trait would owe every consumer a revision the moment it settled — so the other impls wait. Those
21//! two are not among them: their faces are the expansion's own output and the record it sits on, so
22//! they name nothing that could settle differently.
23//!
24//! # THE FORM IS AN ATTRIBUTE, because these macros rewrite the item they sit on
25//!
26//! A derive is handed a copy of the declaration and may only APPEND. These need to change it — a
27//! derived index carries an identity it does not mint, as one field whose TYPE is a projection, and
28//! that field has to be in the struct rather than beside it — so the whole family is attribute
29//! macros and the declaration's own options are the attribute's ARGUMENTS:
30//!
31//! ```ignore
32//! #[ingraph::record(sqlite, lineage(fields(media_id)))]
33//! pub struct VideoTrack { … }
34//! ```
35//!
36//! The second thing the form buys is the VISIBILITY CONVENTION: a field written with no visibility
37//! is stamped `pub(crate)` by the macro, and an author's explicit visibility is preserved, so the
38//! rule stops being the author's pen. See [`host`] for the whole of what an echo changes and the
39//! much longer list of what it carries verbatim.
40//!
41//! # ONE NODE HOLDS ONE STORAGE, so the macro IS the storage declaration
42//!
43//! [`operator`] is the node family's base — it subscribes, it computes, it emits, and it owns no
44//! storage — and every other node macro is it plus exactly one store: [`record`] holds rows in the
45//! databases its store words name, [`aggregate`] holds rows a declared FOLD over one upstream's
46//! rows fills, and [`fulltext`], [`vector`] and [`blob`] each hold documents derived from another
47//! node's messages. So there is no word on a declaration that says which storage it has; the
48//! attribute's own name is that word, which is one layer fewer and one contradiction fewer.
49//!
50//! The family splits again one level down, and the axis is the KEY rather than the store. A record,
51//! an aggregate and an operator MINT an id — an aggregate's from the group columns it projects; the
52//! three derived indexes mint none and carry their upstream's key in a field this crate injects.
53//! That is the second thing the attribute form buys, and the reason the three could not arrive
54//! before `upstream(…)` did.
55//!
56//! The two halves of the law are enforced in the two places they can be. The block a node may write
57//! is checked HERE, against the macro it was written under, and every other storage block is
58//! refused by a message naming the declaration that takes it. That a node does not take a SECOND
59//! macro cannot be checked here at all — two macro expansions cannot see each other — so each
60//! storage macro mints the same marker item in the declaring scope and two of them are `E0428` at
61//! the offending type. `tests/storages/` reads the collision back.
62//!
63//! # THE RECORD FAMILY IS A LADDER, and each word names what its rung HAS
64//!
65//! | tier | word | has | lacks |
66//! |---|---|---|---|
67//! | field fragment | [`fields`] | shared fields, declared once, inherited by holders | identity, rows, wire root |
68//! | entity | [`entity`] | id · key · lineage · accessors · filter and comparison faces · a wire face | rows |
69//! | record | [`record`] | everything above **plus the storage essence** — rows, in the databases it names | — |
70//!
71//! [`fields`] is beside the node family rather than in it: a fragment is HELD, so it is not a node
72//! at all — no identity, no storage, no wire root, and therefore no marker and no place in the
73//! one-storage law above. The word used to be `entity`, and the tier's own doc confessed the
74//! mismatch in as many words (*no stable identity is what the tier means*) while `entity` means an
75//! identity-bearing thing everywhere else in this framework — the entity binding, a hit's `entity`
76//! field, `TypedId`'s entity marker. So the word moved up to the rung it always described.
77//!
78//! [`record`] and [`entity`] differ in the STORAGE ESSENCE and in nothing else, which is why a
79//! record names its stores BARE at the head — `#[ingraph::record(sqlite, postgres)]` — rather than
80//! inside a wrapper. An optional axis gets a block (`graphql(…)`); an essence never wraps. A record
81//! naming no store is refused and told the two exits, because a record IS rows.
82//!
83//! Every expansion may use only `ingraph`'s public API, so a hand-written declaration and a
84//! generated one are the same program. The design is recorded in `docs/` (not published).
85//!
86//! # AN EXPANSION ASSUMES THE FRAMEWORK'S TIERS ARE IN PLACE
87//!
88//! `ingraph` is cut into tiers — a vocabulary core, then `engine`, then `runtime`, then `derive` —
89//! and what these macros write reaches into all of them. A declaration's expansion names
90//! `__private::drive`, `__private::source`, `__private::operator`, `__private::resource` and
91//! `__private::retrieve`, and it names them as ABSOLUTE paths carrying no `#[cfg]`, because a
92//! `#[cfg(feature = …)]` written inside an expansion asks whether the DECLARING crate has a feature
93//! by that name rather than whether `ingraph` was built with one.
94//!
95//! So the assumption is not a convention this crate could relax — it is what makes an emitted path
96//! resolve at all, and `ingraph`'s own feature table states it as `derive = […, "runtime"]`. A
97//! consumer taking the attributes as `ingraph::record` inherits the tiers with the word.
98//!
99//! A consumer taking them as `ingraph_derive::record` — which is this crate's own fixture corpus,
100//! and the form a test uses when the MACRO rather than the re-export is its subject — is outside
101//! that implication and names `runtime` on its own `ingraph` dependency. Without it an expansion is
102//! `E0433` at the first shelf path it writes, which is a resolution failure rather than a missing
103//! impl.
104//!
105//! Below the derives sits a small PARSING LAYER the whole crate shares — [`errors`] for reporting
106//! every violation rather than the first, [`attribute`] for the `#[ingraph(…)]` grammar's
107//! structure, [`value`] for typed option values, [`column`] for what an emitted column may be
108//! called. None of it knows what a record is; `Record` is its first consumer, and the derives
109//! that follow are why it is separate.
110//!
111//! The crate is a SHELL: [`parse`] turns the compiler's tokens into an
112//! [`RecordModel`](ingraph_codegen::model::RecordModel) and checks every rule, and
113//! `ingraph-codegen` turns that model back into tokens. Neither half needs the other's machinery,
114//! which is what lets a manifest reach the same emitter later.
115
116use ingraph_codegen::{
117 error::{ErrorModel, ErrorRoad},
118 model::RecordModel,
119};
120
121mod aggregate;
122mod alias;
123mod attribute;
124mod column;
125mod construct;
126mod delegate;
127mod r#enum;
128mod error;
129mod errors;
130mod fields;
131mod flags;
132mod graph;
133mod host;
134mod id;
135mod index;
136mod interface;
137mod journal;
138mod members;
139mod mutation;
140mod newtype;
141mod parse;
142mod remote;
143mod resource;
144mod search;
145mod source;
146mod standalone;
147mod suggest;
148mod tower;
149mod union;
150mod value;
151mod wire;
152
153#[cfg(test)]
154mod fed;
155#[cfg(test)]
156mod indexed_tests;
157#[cfg(test)]
158mod locate_absence_tests;
159#[cfg(test)]
160mod locate_full_form_tests;
161#[cfg(test)]
162mod locate_required_tests;
163#[cfg(test)]
164mod locate_tests;
165#[cfg(test)]
166mod near_miss_tests;
167#[cfg(test)]
168mod notified;
169#[cfg(test)]
170mod page_kind_tests;
171#[cfg(test)]
172mod page_name_tests;
173#[cfg(test)]
174mod plural_tests;
175#[cfg(test)]
176mod skip_tests;
177#[cfg(test)]
178mod sortable_reseat_tests;
179#[cfg(test)]
180mod sortable_tests;
181#[cfg(test)]
182mod tests;
183
184/// Declare a RECORD — an entity holding rows, in the databases its STORE WORDS name.
185///
186/// # Attributes
187///
188/// The FIELD markers:
189///
190/// - `#[ingraph(id)]` on exactly one field — the record's own identity, and the key's last column.
191/// - `#[ingraph(copy)]` on any field — its type is cheap enough to hand back by value.
192/// - `#[ingraph(key(rename = "…"))]` / `#[ingraph(lineage(rename = "…"))]` — what this field's
193/// column is called in that ONE emitted type. Scoped, because the key's columns become the
194/// record table's and the lineage's become the degraded table's, and two tables may name a
195/// column differently. A bare `rename` is refused; so is a scope that has no column for the
196/// field.
197///
198/// One attribute may carry several: `#[ingraph(id, copy)]`. None may be repeated.
199///
200/// The macro's ARGUMENTS are one block per emitted type, options inside:
201///
202/// - `lineage(fields(a, b, …), rename = "Name")` — the fields holding the path from the root, in
203/// ROOT-FIRST order, and what the emitted type is called. Omit the whole block for a root.
204/// - `key(rename = "Name")` — the key type's options. It has no `fields`: `key = lineage ⊕ id` is
205/// a law, not something a declaration restates.
206/// - `implements(<Interface>, …)` — the INTERFACES this record is a member of. It is the AGREEMENT
207/// half of a membership: an interface's own declaration names its members and cannot prove one
208/// consented, the two derives being unable to see each other, so this word emits
209/// `impl Implements<Interface>` and the interface's expansion asserts it. A member-side column
210/// rename — `implements(<Interface>(<field> = <column>))` — is recognised and refused: what reads
211/// one is the interface's row equation, which needs the column as an ident.
212/// - `locate(<word> = "path::To::Family", …)` — the ARTIFACT FAMILIES this record answers an
213/// address for. `derived(…)`'s reverse-container sibling and its mirror image: a reverse position
214/// names a record that points BACK through a `ref`, and an artifact position names an
215/// `#[ingraph::blob]` node DERIVED FROM this one's messages. The LEFT side is the author's own
216/// domain word — `thumb`, `cover`, `poster` — and it is the name the wire field takes; the right
217/// is the path to the family's TYPE, which is where its slot, its store and how its addresses end
218/// all live. The word is on THIS record because the field lands on THIS record's output object,
219/// and a second `#[Object]` block written by the family's own macro is `E0119` three times over.
220/// A position's FULL FORM — `<word>(family = "path::To::Family", data, required)` — carries the
221/// two words the shorthand has nowhere to put: `data`, which ASKS for a second field holding the
222/// bytes inline (the family's own `data` PERMITS them), and `required`, the author's signature
223/// that publishes the address as `BlobLocation!` rather than `BlobLocation`. The ask takes the
224/// same signature at its own grain — `data(rename = "…", required)` — and each word promotes only
225/// its own field. Both are one-way: nullable is what not writing one means, and it is the default
226/// because an artifact is written asynchronously after the entity exists.
227/// - `crate = "path::to::ingraph"` — TOP-LEVEL, since it governs every emission rather than one
228/// type. Where `ingraph` itself lives, for a re-export shim or a renamed dependency. Defaults to
229/// `::ingraph`.
230///
231/// A `rename` is a string parsed into an identifier — the same shape as `crate`'s string parsed
232/// into a path — which is what keeps a raw identifier spellable. Without one, a type takes the
233/// suffix convention: `<Record>Key` and `<Record>Lineage`.
234///
235/// There is no flat shorthand: `lineage(a, b)` is refused. Two grammars would mean two parse
236/// paths, two error surfaces, and a real reading ambiguity the day a struct has a field called
237/// `fields`.
238///
239/// Unmarked fields — data, forward `Option<_>` FKs, `Vec<_>` reverse lookups — are ignored
240/// entirely. Lineage is never inferred from a field's name: `video_id` is a PARENT on a video's
241/// track and a CHILD on the media, and only the declaration knows which.
242///
243/// # A record's storage is its STORE WORDS, bare at the head, and nothing else
244///
245/// `#[ingraph::record(sqlite, postgres(schema = "public"))]`. They sat inside a `persist(…)` wrapper
246/// and they do not any more, and the principle is what moved them: storage is a record's ESSENCE —
247/// a record IS rows, which is the whole of what separates it from an [`entity`] — and an essence
248/// sits bare where an OPTIONAL axis takes a block. `graphql(…)` is optional and keeps its
249/// parentheses. Each store word's own entries are unchanged and still inside it; the unwrap took one
250/// layer off the outside and moved nothing in.
251///
252/// A record naming NO store is refused, and the refusal names both exits: name one, or declare it an
253/// [`entity`], which is this same declaration without the rows.
254///
255/// ONE NODE HOLDS ONE STORAGE, so the MACRO IS the storage declaration: `Record` declares rows, and
256/// an index over those rows or a family of artifacts beside them is a second storage and therefore a
257/// node of its own — a `Fulltext`, `Vector` or `Blob` derive on a type that subscribes to this record
258/// and shares its key, carrying no `id` because the key is not its to mint.
259///
260/// So `fulltext(…)`, `vector(…)` and `blob(…)` are refused, at the block and at the field marker
261/// alike, and each refusal is the MIGRATION: it names the macro the declaration belongs to and
262/// carries what the block carried — a full-text conversion renders a field into one engine's
263/// document, `element` and `filter` describe embeddings rather than rows, and an `extension` is part
264/// of the address a blob node's key renders. Every one of those describes the other node, which is
265/// why none of them travels alone.
266///
267/// A `Vec<u8>` COLUMN is none of this and stays exactly where it was: `#[ingraph(bytes)]` is a value
268/// in this record's own row, one word away from the marker that left.
269///
270/// # A record's data fields ARE its row, and `skip` is the way out
271///
272/// Participation used to be a per-field marker — a field wearing `persist` became a column and a
273/// field without one did not — and it is the DEFAULT now. A record IS rows; its data fields are the
274/// row unless they declare otherwise, which is what `#[ingraph(skip)]` says. Identity is unskippable
275/// on both axes, so a record's `id` and every lineage step are columns by construction.
276///
277/// `persist(…)` survives on a field as what it always ALSO was: the REFINEMENT. `rename = "…"`,
278/// `sortable`, and each database's own `type`, `from`, `into`, `indexed`, `unique`, `copy`, `edge`
279/// and `flatten` all keep their seats. What is gone is the bare word, which would now say
280/// nothing — and it is refused rather than ignored, because silence and a word that means silence
281/// are the same declaration and one of them costs the next reader a lookup.
282///
283/// The LABEL follows the same posture. It is an override where meanings multiply — `Vec<u8>` as
284/// bytes or as a list, a set against a sequence — and a column that writes none is read through
285/// `<T as DefaultMarker>::Marker`, the inference that keeps the common case free of annotation. A
286/// type with no row there is `E0277` NAMING that type; a type NO dialect can hold is ENGINE-RESIDENT
287/// and wears `skip`, which `Carrier`'s own refusal says in as many words.
288///
289/// # The names a statement MINTS are the declaration's too — `alias(…)`, per database
290///
291/// A nested relation renames its row source per level, so the engine mints one name per depth beside
292/// each row's address. Both halves of that mint are a database block's to move:
293///
294/// ```ignore
295/// #[ingraph::record(
296/// sqlite(alias(prefix = "__mine", depth = 16)), // each db independent
297/// postgres(alias(depth = 12)), // defaults are `__ig` and 8
298/// )]
299/// ```
300///
301/// PER DATABASE, because the emitted table already is: `ALIASES` rides one `SqlQuery<Db>` impl, so a
302/// record stored in two databases carries two of them. The user story is per database as well — one
303/// deployment's schema already holds real tables under `__ig`, and the others do not, so the override
304/// belongs on that database and nowhere else.
305///
306/// `prefix` must lead `__`, because the prefix is FENCED as well as minted in: every declared column
307/// and table name inside it stops being spellable, and a bare word would confiscate a namespace this
308/// schema's own author is using. The fence holds the UNION of every declared prefix PLUS `__ig`
309/// wherever any database still defaults — fields are the DOMAIN's, and a column collides in whichever
310/// table would have minted over it. A record that overrode every one of its databases has handed
311/// `__ig*` back.
312///
313/// `depth` is the alias table's LENGTH, so eight is a DEFAULT rather than a wall: a filter nesting
314/// deeper says so once and the engine's refusal — which reports the array's own length — moves with
315/// it. `depth = 0` is refused, an alias array with no depths aliasing nothing.
316///
317/// The progress ledger has no block either, for a different reason: there is nothing left for one to
318/// say. It would name DATABASES alone, and it lives where the row write does — its control tables
319/// live in that engine's pool — so its hosts are the databases the store words already name. Existence
320/// is derived too: a ledger certifies the unit's close, which every stored record has. Writing
321/// `progress(…)` is refused by that reason.
322///
323/// # A collection has no null state
324///
325/// `list(…)` and `set(…)` are the two words that put a field in a COLLECTION POSITION, and a
326/// collection has no null state: an `Option` around one declares the
327/// COLLECTION, and empty and absent are ONE state in both directions. So such a field resolves its
328/// marker, its filter and its comparison exactly as the same field declared bare would — no null
329/// test on its wire face, and no `Nullable` wrapper anywhere below it. *Is it empty* is asked as
330/// `count: { eq: 0 }`, which is a question every backend answers alike. polarsync's schema settles
331/// the same question the same way, translating an `Option<Vec<T>>` field to `Vec<T>`.
332///
333/// It is a ruling about what is DECLARABLE rather than a convenience. Storage keeps one observable
334/// for a collection holding nothing — an edge table with no rows, an array column with no elements —
335/// where the Rust type spells two, and a distinction the storage cannot keep must not be spellable
336/// as though it could. Under the two-state reading the null test rendered against the PARENT table,
337/// which has no such column; under this one there is no null test to render.
338///
339/// The normalisation the ruling implies — an empty collection written as absent, an absent one read
340/// back as empty — belongs to the write and read paths, and rides the storage and query eras with
341/// the rest of them.
342///
343/// **The ruling holds for a column naming NO word, and the two paths reach it differently** — which
344/// is where it has to be decided rather than a duplication. A macro holds tokens, so `Option<Vec<u8>>`
345/// and `Option<Vec<Tag>>` are one shape here and only a declaration can say which is a collection:
346/// the WORD is what this layer can read, so the word is what this layer routes. A column naming none
347/// is routed one layer down instead, by its TYPE — `ingraph`'s blanket over `Option<T>` asks
348/// `Marker::UnderOption` what an `Option` of the inferred reading is, and the FAMILY answers. A
349/// collection answers with itself, so an unmarked `Option<Vec<Tag>>` resolves as the bare `Vec<Tag>`
350/// beside it does; a `Vec<u8>` is a blob and a blob is a value that can be absent, so it keeps the
351/// null test.
352///
353/// Neither path can reach the other's answer, and a column that takes both — a word over a type whose
354/// inference agrees — resolves alike either way.
355///
356/// The `Option` is taken off the type the marker is applied TO, so an alias hiding it
357/// (`type MaybeTags = Option<Vec<String>>`) is refused at the declaration — `MaybeTags:
358/// ListFilterMarker` is unsatisfied — rather than quietly resolving to the wrapped filter. An alias
359/// carrying no word is not refused: the inference reads the TYPE, and an alias is transparent there.
360///
361/// # Expansion
362///
363/// `Foo` with lineage `(a, b)` and id `i` expands to a flat `FooKey { a, b, i }` and a
364/// `FooLineage { a, b }`, each deriving `Debug`, `Clone`, `PartialEq`, `Eq` and `Hash`. A root
365/// record gets its `FooKey` alone — no `FooLineage` type exists for an empty path.
366///
367/// Both types are exactly as visible as `Foo` — a private record's key stays private rather than
368/// leaking into its crate's public API — and both are fully documented, so a crate that denies
369/// `missing_docs` is not handed a type it cannot edit to satisfy the lint.
370///
371/// The RECORD gets an inherent impl too — an accessor family for every field it declares, and
372/// mutators for the ones that do not bear identity. Its `#[ingraph(id)]` field and every lineage
373/// step are set at construction, so they get getters only. There is **no generated constructor**:
374/// a real aggregate has twenty-odd fields, and the application hand-writes a validating one the
375/// macro cannot replicate.
376///
377/// A field is handed out by the shape of its written type — `Vec<T>` as `&[T]` under an `x_slice`
378/// name, `Option<T>` as `Option<&T>`, anything else as `&T`. (Recognised syntactically: a type
379/// alias for either takes the plain borrow.)
380///
381/// The emitted key types' FIELDS are private, and each gets one inherent impl holding a positional
382/// `const fn new` that takes the columns in key order, then one family per column:
383///
384/// | column | accessors | mutators |
385/// |---|---|---|
386/// | plain | `const fn x_ref(&self) -> &T` | `fn set_x(&mut self, T) -> &mut Self` · `fn with_x(mut self, T) -> Self` |
387/// | `#[ingraph(copy)]` | the same `x_ref`, **plus** `const fn x(&self) -> T` | the same pair, both `const` |
388///
389/// `with_*` is `#[must_use]`: it returns the change rather than applying it. There is no builder
390/// and no `Default` — a key has no invariants to guard, and a default key is a nil address.
391///
392/// The marker is ADDITIVE: it adds `x()` and renames nothing, so turning it on or off never breaks
393/// a caller that was borrowing through `x_ref()`.
394///
395/// Each emitted type also gets `From<Record>`, which moves its columns out, and `From<&Record>`,
396/// which clones them — two so the cost is visible at the call site.
397///
398/// The impls sit inside one anonymous `const _: () = { … };` per record, which changes nothing
399/// about reaching them; the structs stay at top level. The FRAMEWORK traits an expansion writes are
400/// the SETTLED ones — the entity binding on every record, each stored database's comparison
401/// lowering, and the crossing from a declaration's filter where it has one; a trait still moving is
402/// not named.
403///
404/// A column's name — the field's own, or its scoped rename — may not take the framework's
405/// `__name__` shape, which is reserved for the columns the framework adds to a table.
406///
407/// Nor may two columns of ONE emitted type resolve to one METHOD name. A column reaches an
408/// accessor or a mutator through a derived shape, so `x` beside a `copy` `set_x` gives that type
409/// two `set_x`, and a `copy` column called `new` gives an emitted key a second constructor. Both
410/// are duplicate definitions inside the expansion, at a span the declaration cannot edit, so they
411/// are refused here instead — with the column named. Near misses are not refused: `new_thing`,
412/// `set` and `x_reference` derive nothing anything else derives, and an unmarked `new` reaches
413/// `new_ref` rather than the constructor.
414///
415/// The record must be a concrete struct with named fields. Generic records are refused: a key
416/// column's type is read straight off the declaration, and a type parameter has none until it is
417/// substituted.
418///
419/// ```ignore
420/// #[ingraph::record(
421/// sqlite,
422/// lineage(fields(media_id, video_id), rename = "TrackScope"),
423/// key(rename = "TrackAddress"),
424/// )]
425/// pub struct VideoTrack {
426/// #[ingraph(id)]
427/// id: Uuid7,
428/// #[ingraph(copy, lineage(rename = "media"))]
429/// media_id: Uuid7,
430/// #[ingraph(key(rename = "video"))]
431/// video_id: Uuid7,
432/// bit_rate: u64,
433/// }
434/// // => pub struct TrackAddress { media_id: Uuid7, video: Uuid7, id: Uuid7 }
435/// // with new(media_id, video, id),
436/// // media_id() -> Uuid7 · media_id_ref() -> &Uuid7 · const set_media_id · const with_media_id
437/// // video_ref() -> &Uuid7 · set_video · with_video
438/// // id_ref() -> &Uuid7 · set_id · with_id
439/// // and From<VideoTrack> / From<&VideoTrack>
440/// // => pub struct TrackScope { media: Uuid7, video_id: Uuid7 } (the same, without the id)
441/// ```
442///
443/// # `remote = "path::To::Type"` — the WRAPPER mode
444///
445/// The one word in this grammar that changes what the DECLARATION IS rather than adding a fact
446/// beside it. Under it the fields written below are a MANIFEST — the shape of a type another crate
447/// owns, restated so this framework can read it — and the item the compiler sees is replaced:
448///
449/// ```ignore
450/// #[ingraph::record(remote = "upstream::Tick", sqlite)]
451/// #[derive(Debug, Clone, PartialEq, Eq)]
452/// pub struct Tick {
453/// #[ingraph(id)]
454/// id: i64,
455/// #[ingraph(copy)]
456/// depth: u16,
457/// }
458/// // => #[repr(transparent)] pub struct Tick(upstream::Tick);
459/// ```
460///
461/// The orphan rule is why it exists: a type another crate owns cannot be given this framework's
462/// faces where it is declared, and a wrapper is the position where it can. The same word is
463/// admitted on [`entity`], which is the rung to take for a type with no rows behind it.
464///
465/// **Every face is unchanged.** A manifest column carries a name, a type, a projection and its
466/// markers exactly as a declared one does, so the key, the lineage, the row, the filter, the
467/// comparison, the order-by and the wire face are the ones written above — including this record's
468/// store words, `key(…)`, `lineage(…)` and every field marker. No new vocabulary is added.
469///
470/// **What moves is two seams.** A column is READ through the remote's own accessor, crossed by
471/// `Into`; and a row is RAISED through the remote's own constructor. So the declaration is a claim
472/// about that type's API, and every part of it is discharged by the compiler at the manifest entry
473/// that made it — no accessor is `E0599` at the field, an unreachable type is `E0277` at the field
474/// carrying this device's own sentence, and an identity column handed back by value is `E0308`
475/// there.
476///
477/// **What is emitted beside the faces:** `AsRef`/`AsMut`, `Deref`/`DerefMut` and
478/// `Borrow`/`BorrowMut` over the wrapped type — all of them `&self.0`, which is why
479/// `#[repr(transparent)]` is the macro's own and a hand-written `#[repr(…)]` is refused — `From` in
480/// both directions, and one reader per manifest field. `Deref` is the method inheritance: every
481/// method the wrapped type has is reachable through it, with nothing to keep in step.
482///
483/// **Readers are by value for data and by reference for identity**, and the asymmetry is forced:
484/// `Identifiable::id_ref` hands an id back BORROWED, so an identity column has to be reachable as a
485/// reference. There are no mutators — a remote's fields are its own — and no `const` reader, a
486/// foreign accessor not being this macro's to declare `const`.
487///
488/// **The hydration builder** is `Remote::new(<the required seats>).with_<optional>(…)`, the split
489/// being `#[ingraph(optional)]`'s: that word already says a column has an empty state, which is
490/// what an options type's optional seat is. A remote that keeps no such family names its own raise
491/// instead — `sqlite(into = "path::to::fn")` replaces the generated body outright, and the read
492/// side is unaffected because accessors are all it needs.
493///
494/// **Two things to know before writing one.** The attribute must sit ABOVE any `#[derive(…)]`: a
495/// derive written first expands against the manifest, and its impls then name fields the rewrite
496/// deleted. And a STORED wrapper needs the bridge in BOTH directions, where an entity needs one —
497/// the write leg crosses a column out and the raise crosses it back in.
498///
499/// **Refusals of its own:** a hand-written `#[repr(…)]`; a manifest field carrying any attribute
500/// but a doc comment, which migrates to that field's reader; `cfg`/`cfg_attr` on a manifest field,
501/// refused with its reason until the models a field's generated family is built from carry a seat
502/// for a condition; the word twice; the word on an [`operator`], which publishes no address to
503/// wrap; and the word beside a fan-in, whose ancestry is a field this macro mints and a wrapper has
504/// no room for.
505#[proc_macro_attribute]
506pub fn record(
507 args: proc_macro::TokenStream,
508 item: proc_macro::TokenStream,
509) -> proc_macro::TokenStream {
510 node(args, item, ingraph_codegen::model::NodeKind::Record)
511}
512
513/// Declare an OPERATOR — a graph node that subscribes, computes, emits, and owns NO storage.
514///
515/// An operator subscribes, computes and emits. It is the BASE of the node family and every storage
516/// derive is it plus one store, which is why this one is spelled by what it does not have: no
517/// a store word, and none of the three blocks an index or an artifact family would take.
518///
519/// ```ignore
520/// #[ingraph::operator(lineage(fields(media_id)))]
521/// pub struct SpeakerTurn {
522/// #[ingraph(id)]
523/// id: Uuid7,
524/// #[ingraph(copy)]
525/// media_id: Uuid7,
526/// speaker: String,
527/// }
528/// ```
529///
530/// # What it shares with [`Record`], and where it stops
531///
532/// Everything about IDENTITY, verbatim: `lineage(fields(…), rename = "…")`, `key(rename = "…")`,
533/// the `id` and `copy` field markers, the scoped renames, the `*Key` and `*Lineage` types with
534/// their accessor families, the entity binding and `implements(…)`. A node's key is a node's key
535/// whether or not anything stores it, and an operator's downstream extends it exactly as a
536/// record's does.
537///
538/// What stops at the storage line stops for one reason: an operator has no rows. So a store word
539/// is refused — naming `Record` as the declaration a node whose messages land in a database takes
540/// — and with the rows go the row types, the comparisons, the order-by and the wire face, none of
541/// which this expansion writes because a wire field with no stored column cannot be populated by a
542/// read. `fulltext(…)`, `vector(…)` and `blob(…)` are refused here for the reason they are refused
543/// on a record: each is a second node's declaration, and the MACRO IS the storage declaration.
544///
545/// The MARKER a storage node mints is the other half of that law, and an operator mints none: with
546/// nothing to hold, it has no second storage to make unspellable.
547///
548/// # `subscribe = "path::To::Upstream"` — the edge
549///
550/// The node whose messages drive this one, spelled as a type path in a STRING, which is this
551/// grammar's rule for every type it names. It is not stringly typed: the macro resolves nothing,
552/// because the upstream is another declaration's and two derives cannot see each other. The path is
553/// EMITTED under a bound that says what a subscribe target has to be, and the compiler resolves it
554/// there — so a path naming nothing is `E0412` and a path naming something that is not a node is
555/// `E0277`, both landing at the string the author wrote.
556///
557/// One entry names ONE upstream, which is the short form. A node that draws from several writes the
558/// CONTAINER instead, and both spellings on one node are refused: a node has one fan-in.
559///
560/// # `subscribe(upstream(…), …)` — the fan-in
561///
562/// ```ignore
563/// #[ingraph::operator(
564/// subscribe(
565/// upstream(node = "media::Frame", key), // THE keyed group
566/// upstream(node = "asr::Segment", key),
567/// upstream(node = "media::Scene"), // an independent flow
568/// upstream(node = "vision::Detector", out = "Boxes"),
569/// ),
570/// )]
571/// ```
572///
573/// Three words per entry. `node = "…"` is the edge, spelled as the short form spells it. `key` says
574/// this upstream is JOINED by key before the body sees it — any number of entries carry it and they
575/// are ONE group, because `key` joins the group rather than opening one. `out = "<Variant>"` says
576/// which product of a multi-product upstream this edge carries, and is QUOTED: it REFERS to an arm
577/// of that upstream's own vocabulary, and this grammar writes every reference in a string.
578///
579/// What the container BUYS is a type: `<Node>In`, one variant per flow — `Paired(…)` carrying the
580/// whole keyed group, and one per independent source, named by the upstream's own last segment or
581/// by the product where `out = "…"` named one. Two edges that would take one name are refused at the
582/// declaration. A container with ONE straight entry emits no type at all, because one upstream is
583/// one message and an enum around it would be a wrapper with one arm.
584///
585/// The PAIRING RUNTIME is not built. `Paired` names the group and the driver's intake does not yet
586/// assemble one, which is stated on the emitted type itself.
587///
588/// # `emits = "A"` / `emits = ["A", "B"]` — the products
589///
590/// SELF-DECLARED, because two derives cannot see each other: a node's downstream cannot tell it
591/// what it produces, and a subscription is a CONNECTION rather than a declaration. Naming several
592/// emits the sum `<Node>Out`, the vocabulary `<Node>OutKind` identifying its arms, and
593/// `<Node>Downstream` — one out-edge slot per product, whose emptiness IS the connection state a
594/// body reads through `emitter.wants(<Node>OutKind::A)`.
595///
596/// Omitting the word says the product is the declared struct, which is what this crate's edges have
597/// always moved. Naming ONE names that one instead. Either way the node states it in a row a
598/// downstream's `In` projects through, so an edge's type is the upstream's word rather than a guess.
599///
600/// # `stream` — the OTHER PAIR, for a fan-out that grows with the input
601///
602/// ```ignore
603/// #[ingraph::operator(stream, subscribe(upstream(node = "media::File")), emits = ["Packet"])]
604/// pub struct Demux { … }
605/// ```
606///
607/// A bare word, and the ONE word this face costs. A declaration that does not write it wears the
608/// BUFFERED compute pair — `Operator` / `AsyncOperator`, an `accept` per delivery whose every
609/// emission is held in an `Emitter` until the call returns — and this buys the STREAMING one:
610/// `StreamOperator` / `AsyncStreamOperator`, one `run` per delivery that streams its outputs through
611/// a bounded `Feed` for that delivery's whole life.
612///
613/// The choice is a question about the FAN-OUT and never about a body's size or its cost. A fan-out
614/// BOUNDED in the input — one, a handful, dozens — is the buffered pair; one that GROWS with the
615/// input's length — a container demuxed to packets, a 2 GB log chunked into windows — is this one,
616/// because millions of emissions held inside ONE call is an out-of-memory abort rather than the
617/// dead-letter the failure lane funds. `StreamOperator`'s own docs carry the law in full.
618///
619/// ## It MULTIPLIES with `async` rather than replacing it, and there is no mode word of its own
620///
621/// `stream` picks the KIND and `async` picks which HALF of it, so the cells are spelled by the two
622/// words a declaration already has:
623///
624/// | words | the face the body wears |
625/// |---|---|
626/// | *(none)* | `Operator` |
627/// | `async` | `AsyncOperator` |
628/// | `stream` | `StreamOperator` |
629/// | `stream, async` | `AsyncStreamOperator` |
630/// | `autonomous` | `AutonomousOperator` |
631/// | `autonomous, async` | `AsyncAutonomousOperator` |
632///
633/// `autonomous` is the section below and it is `stream`'s own axis rather than a third one: a
634/// declaration wears exactly ONE kind, so the two are refused together.
635///
636/// A stream-specific mode word was refused for the reason every second spelling in this grammar is:
637/// the mode vocabulary already exists, and two words on one axis are two authorities for one fact.
638/// There is deliberately no `dispatch` word beside `stream` either — a stream-faced delivery is
639/// SELF-CONTAINED by the face's own definition, so what the lane does per delivery is DERIVED from
640/// the face rather than declared.
641///
642/// ## What the word buys, and what stays a runtime value
643///
644/// The expansion states the FACE as a bound, exactly as `async` does: a `stream` declaration whose
645/// type carries `Operator` instead is `E0277` with the caret on the word, rather than a mount three
646/// expansions away complaining about a trait the author never mentioned. And it states the FACT —
647/// `Declared::Pair`, seated at `Streaming` — which is what puts the node at `Blueprint::stream` and
648/// `Wiring::lane` rather than at `Blueprint::node` and `Wiring::resident`.
649///
650/// What the word does NOT carry is the lane's SEATS: how many deliveries the node holds at once, how
651/// deep each delivery's feed is cut, and which memory probe a feed policy reads. Those are
652/// `StreamOptions` at the launch, because a `FeedPolicy` is a framework-open trait object and an
653/// attribute cannot name a value.
654///
655/// `emits = […]`, `out = "…"`, `subscribe(…)` and the identity words are UNCHANGED beside it: the
656/// products a stream node fans out are the same `<Node>Out` / `<Node>OutKind` / `<Node>Downstream`
657/// family every other node's are, pruned by the same `Wanted` the buffered face reads.
658///
659/// ## Its own refusals
660///
661/// The word twice; the word carrying a value or a block; the word on any declaration but an
662/// `operator`, because every other kind publishes an address and the storing ones land rows through
663/// a write lane the stream lane does not carry; and the word beside `poll(…)`, which is the buffered
664/// pair's — a tick is one call against the node's own value, which the driver LENDS for that call,
665/// and a stream-faced node's bodies are the lane's warm set, each owned by a delivery's run for that
666/// delivery's whole life.
667///
668/// # `autonomous` — THE THIRD KIND, for a node that has to own its own loop
669///
670/// ```ignore
671/// #[ingraph::operator(autonomous, subscribe(upstream(node = "media::Packet")), emits = ["Frame"])]
672/// pub struct Decode { … }
673/// ```
674///
675/// A bare word, `stream`'s own axis, and the whole of what it buys is that the NODE runs the loop:
676/// `fn run(self, ctx: Context, upstreams: Upstreams<In>, downstream: Downstream<Out>) -> Result<Fin,
677/// Error>`, once, for the node's whole life. Select order, arm priority, intake gating, batching,
678/// ack timing and internal workers are all inside that call.
679///
680/// ## Which kind a body is, in one sentence each
681///
682/// | the body | its word | the sentence |
683/// |---|---|---|
684/// | bounded fan-out, a simple serial unit | *(none)* | the framework drives every part of it |
685/// | one delivery is one whole life where the per-delivery parallelism AND the fate bookkeeping are the FRAMEWORK's | `stream` | a demux: the lane holds the warm set, the admission bound and the dead-letter |
686/// | the node takes the wheel and KEEPS THE BOOKS | `autonomous` | a decoder, a resampler, a conform, a heavy embedder |
687///
688/// The three are PEERS. What sends a body to the third row is needing something the first row's
689/// protocol has no place for — reading one upstream before another, refusing to read one at all
690/// this pass, holding an ack until a worker has flushed — and `Operator`'s protocol was not widened
691/// to fit them, on the count that decides it: 105 `accept` bodies in this tree.
692///
693/// ## `self` BY VALUE, and the lifecycle that follows from it
694///
695/// `run` takes the value rather than borrowing it, which is `Source::run`'s shape and its reason:
696/// there is nothing after it. The dividend is the PROLOGUE — a body that owns `self` can take
697/// itself apart INTO the workers it spawns, where a `&mut self` body could only clone or lock.
698///
699/// The phases divide with no ambiguity, and `AutonomousOperator`'s own docs carry the table:
700/// CONSTRUCTION is pure data (no thread, no channel — a built-and-unignited node holds nothing
701/// live, so dropping one in its slot is a no-op); the mount holds the value in its slot and MOVES
702/// it onto the hosting thread at ignition; STARTUP is `run`'s prologue; TEARDOWN is `run`'s
703/// epilogue and is explicit — close the in-queues, let the workers drain their session tails, join
704/// them, then answer the `Fin` — with `Drop` as the idempotent backstop that keeps a panic-unwind
705/// join from deadlocking. `Err` drains the same way before it is dead-lettered, and a respawn is a
706/// factory rebuild rather than a reuse of the husk.
707///
708/// ## What the word buys, and what stays inside `run`
709///
710/// The expansion states the FACE as a bound, exactly as `stream` does: an `autonomous` declaration
711/// whose type carries `Operator` instead is `E0277` with the caret on the word. And it states the
712/// FACT — `Declared::Pair`, seated at `Autonomous` — which is what puts the node at
713/// `Blueprint::autonomous` and `Wiring::autonomous`, and what makes a `#[ingraph::graph]` root
714/// mount one through the same ONE line per field it already emitted.
715///
716/// What the word does NOT carry is anything about the node's own machinery. How many workers it
717/// keeps, how it routes among them, how deep its own queues are cut: all of it is inside `run`,
718/// because the framework knows WHAT nodes exist and HOW they connect and nothing else.
719///
720/// ## Its own refusals
721///
722/// The word twice; the word carrying a value or a block; the word on any declaration but an
723/// `operator`, for `stream`'s reason one kind over — an autonomous mount carries no write lane; and
724/// the word beside `stream`, because the two are values of ONE axis and a declaration wears exactly
725/// one kind.
726///
727/// # `poll(<name>, every = "10m")` — the node's OWN clock
728///
729/// ```ignore
730/// #[ingraph::operator(
731/// subscribe(upstream(node = "media::Frame")),
732/// poll(orphans, every = "10m", light, async(inline)), // reap fast
733/// poll(compaction, cron = "0 3 * * *", tz = "America/New_York", light, async(inline)),
734/// // compact at three
735/// )]
736/// ```
737///
738/// BESIDE the container and never inside it, because a poll source is not an upstream: a tick is a
739/// WAKE. It moves no message, it enters no `In` enum, and what the node does with it is read
740/// through the handles it already holds. That is what makes a reaper, a compactor and a
741/// stuck-watermark healer ordinary declared nodes rather than a side channel beside the graph.
742///
743/// The name is MINTED and therefore bare — it refers to nothing, and it exists so a body can tell
744/// one clock's tick from another's. What it buys is `<Node>Due`, one variant per entry: a tick
745/// arrives carrying a POSITION, the emitted vocabulary translates the position into the word the
746/// declaration wrote, and reordering the entries therefore changes no body. The third of the
747/// rename-proof identity types, beside `<Node>In` and `<Node>Out`.
748///
749/// Exactly ONE of `every = "…"` and `cron = "…"` per entry. `every` is an interval in the
750/// framework's one duration grammar, and it must be positive — a poll that fires as fast as the
751/// machine allows is a spin, refused by name. `cron` is the classic five fields, checked AT
752/// EXPANSION with the offending string quoted; it is wall-clock, so it reads in the system's zone
753/// unless `tz = "<IANA>"` names another. `tz` beside `every` is refused: an interval counts elapsed
754/// time and never asks what o'clock it is.
755///
756/// # `block` · `spawn` · `rayon` · `async(inline)` · `async(spawn)` — WHERE the tick runs
757///
758/// MANDATORY on every entry, with no default. A role is DECLARED rather than inferred, and this is
759/// the campaign's own law applied to execution: what a tick costs the driver is the difference
760/// between a body it awaits, a body it blocks on, and a body it hands to an executor, and none of
761/// the three is the obvious one to assume for a declaration that did not say. `async(inline)` is
762/// what every entry did before the word existed.
763///
764/// The two INLINE words run the body where the driver is and carry its answer back to the taps; the
765/// three DETACHED ones hand it over and answer *dispatched*, so nothing about the outcome is
766/// claimed. `spawn` and `rayon` name the two SHIPPED blocking executors and `async(spawn)` names
767/// whichever `AsyncSpawn` the deployment installed — all three are seams, so a third-party pool is
768/// named at `<Node>Polling::new` and costs no vocabulary word here.
769///
770/// A detached word on a `light` entry is refused: its body would be the node's own value, which the
771/// driver lends per tick and cannot give away.
772///
773/// `concurrent`, bare, lifts the AT-MOST-ONE-IN-FLIGHT default that `spawn` and `rayon` carry —
774/// threads are expensive and an unbounded pile-up is the failure mode a default has to stand
775/// against. A tick skipped by that default is not silent: it becomes `Observation::Lapped` at info.
776/// The word on an inline mode or on `async(spawn)` is a teaching refusal.
777///
778/// # `handler = "app::PromScraper"` · `light` — WHO runs the tick
779///
780/// MANDATORY on every entry, exactly one of the two, and there is no default for the mode word's
781/// reason: who runs a tick is DECLARED rather than inferred. The older spelling — neither word,
782/// meaning the sweep method — is gone, because a declaration that answers *who runs this* by saying
783/// nothing answers it only for a reader who already knows the grammar.
784///
785/// `handler` is refer-quoted, as `write = "…"` is, and the mode word decides which trait the
786/// mount's bound demands: `AsyncTick` for the async words, `Tick` for the sync ones, so a wrong
787/// mount is `E0277` at the declaration. `light` is BARE, because it refers to nothing — it names
788/// the road this framework already owns, the node's own `<Node>Sweeps` method on the operator the
789/// driver lends for the call.
790///
791/// It is the PRESENCE SPLIT's only input. An entry that mounted routes to that citizen and has no
792/// `<Node>Sweeps` method; a `light` entry is one. A node whose every clock mounted a citizen emits
793/// no sweep trait at all — and a node with clocks always emits `<Node>Polling`, sealed and empty
794/// where nothing was granted and nothing mounted.
795///
796/// A node may MIX the two freely, and the anchor law is what a mixed node reads: `<Node>Sweeps`
797/// carries ONE `Info` and ONE `Error` for the whole node, an inline citizen is bound to that same
798/// pair, and where every clock mounted, the FIRST inline citizen anchors it instead (all-detached
799/// answers `()` and `Infallible`). So a mixed node's `light` methods speak the CITIZEN's pair, and
800/// the idiom is a node-wide vocabulary on the anchor:
801///
802/// ```ignore
803/// enum IndexerInfo { Scraped { rows: usize }, Vacuumed { freed: u64 } }
804/// ```
805///
806/// A poll inbound carries NO ack, structurally — an `ack(…)` word inside `poll(…)` is a named
807/// refusal. There is no producer window to release and no cursor to advance, because a tick is not
808/// data; the next tick over an idempotent scan is the retry, the lifecycle taps are the
809/// observation, and the clock is the throttle. A polling node that PUBLISHES keeps the whole ack
810/// protocol as a sender.
811///
812/// # `upstream(…)` at the TOP level is a different question
813///
814/// FUSION — several upstreams jointly making one output, one of them designated the key parent, so
815/// this node's lineage mirrors that parent's key. The words look like the container's and the
816/// question is not: those say how messages ARRIVE, and these say where the identity COMES FROM. An
817/// operator whose every field is read out of ONE upstream message is neither: it is a derived index,
818/// and the macro for one is [`fulltext`], [`vector`] or [`blob`].
819///
820/// # `teardown` — the goodbye, opted into
821///
822/// A bare word, on any node's own attribute. A value a launch constructs is torn down by [`Drop`],
823/// which closes a pool, releases a handle and needs nothing said about it — so the word is for the
824/// values whose goodbye has to be AWAITED: a flush that must reach a store, a device released
825/// politely, a lock removed from a table somebody else will read.
826///
827/// It carries nothing, because what to say is the `AsyncTeardown` impl's. What the word buys HERE is
828/// that the impl is demanded at the declaration: the expansion states the bound, so a type that
829/// opted in without one is `E0277` at its own name rather than a launch that starts and then has
830/// nothing to say at the end. The chain itself is the launch's — the enrolled goodbyes are said
831/// after every party has settled, last enrolled first, and a refusal never interrupts the next one.
832///
833/// # `attributed` — the root projection, opted into
834///
835/// A bare word, on any node's own attribute, and on an axis of its own: `stream`, `autonomous` and
836/// `async` say what a body IS, and this says what the framework does with what the body EMITS. So
837/// it composes with all of them and is refused beside none.
838///
839/// Without it a node's observations are COUNTER-GRADE — a lifecycle tap sees every station with no
840/// content root attached, which is the only thing a node emitting a `String` or a `u64` could
841/// honestly offer. With it the launch installs the framework's own `RootProjection<Out>` on this
842/// node, and its observations become keyable by `(root, node)`: the root is the emitted output's
843/// key FIRST column, read through the `Attributes` impl that output's own declaration emitted
844/// beside it.
845///
846/// It carries nothing, because the projection is that impl rather than anything written here. What
847/// the word buys is the SEAT — `Declared::Attribution` — which is the only road the fact has: a
848/// graph root's expansion writes one line per field and sees a node's output as a type it can name
849/// and cannot test, so whether that output is a declared record has to be stated by the party that
850/// knows. An output NO record declared has no such impl, and the mount is where that is refused, by
851/// `E0277` naming the payload.
852///
853/// An attribution that carries STATE — a journal writer, a queue, a live handle — is not this
854/// word's road: it is a VALUE, no attribute can name one, and it is attached at the launch through
855/// [`Resident::attributing`](ingraph::Resident::attributing) instead.
856///
857/// # `options = "path::To::Knobs"` — what a deployment's section for this node deserializes into
858///
859/// A referring word, so it is written QUOTED like every other in this grammar: it names a type this
860/// declaration did not mint. ABSENT means `()` — a node with no knobs, which is most of them, writes
861/// nothing — and the author's [`AsyncConstructor`](trait@ingraph::AsyncConstructor) still OWNS the
862/// type either way. The two are pinned equal by an emitted equation, so a declaration whose word and
863/// whose constructor disagree is refused where the launch is written rather than deep inside a walk.
864///
865/// What it buys is the ROOT's spine: the emitted options can NAME the path a declaration wrote
866/// instead of projecting `<Node as AsyncConstructor>::Options`, which put a compile-time demand on
867/// every node in a catalog just to spell the type of one section.
868///
869/// It is on EVERY rung rather than this one — [`entity`], [`record`], [`fields`] and the derived
870/// indexes take it in the same words — and it is documented here because an operator is the node
871/// family's base and a reader looking for a node's knobs looks at the base first.
872///
873/// # There is no `receipt = "…"` here — the word is the MESSAGE's
874///
875/// It used to be. The seat shipped keyed on the CONSUMER — *this node hands back a `SceneId`* — and
876/// the subject was wrong: a receipt answers the item that was GIVEN, so every seat on the far end of
877/// one edge answers the same question, and two seats over one message could each declare the
878/// answer's type and disagree about a question neither of them asked.
879///
880/// So the word lives on the declarations that MINT a message — [`entity`], [`record`],
881/// [`aggregate`] — and an operator writing it is refused by name, with the sentence pointing at
882/// those three. An operator computes: it publishes no address, and what goes on its out-edge is its
883/// `Operator::Out` rather than itself, so there is no operator value on any wire for a producer to
884/// be parked on. See [`entity`], where the word is documented.
885///
886/// What an operator DOES with a receipt is state one: `Emitter::receipt_of::<Message>(id)` names the
887/// message it was delivered, and `Emitter::receipt` takes any value at all for a seat answering with
888/// something its message did not declare.
889///
890/// # The `id` an operator still carries
891///
892/// Mandatory and singular, exactly as a record's, and the edge does not relax it here. The ruling —
893/// *id absent on a subscriber means the upstream's key* — is spent by the DERIVED INDEXES, where the
894/// key is carried in a field the macro injects; an operator computes its own fields and keeps its
895/// own identity, so `subscribe` alone buys no relaxation. What a node with no `id` would be is
896/// [`fulltext`]'s tier, and the whole of it is written there.
897#[proc_macro_attribute]
898pub fn operator(
899 args: proc_macro::TokenStream,
900 item: proc_macro::TokenStream,
901) -> proc_macro::TokenStream {
902 node(args, item, ingraph_codegen::model::NodeKind::Operator)
903}
904
905/// Mount a JOURNAL — the canonical record of how far each content ROOT got through each node.
906///
907/// ```ignore
908/// #[ingraph::journal(root = "MediaId", sqlite)]
909/// pub struct VideoJournal;
910/// ```
911///
912/// A journal of FINAL STATES, keyed `(root, node)`, each entry replaced in place — not an append
913/// log. That is the organ's whole semantics, and it is worth stating before anything else because
914/// the word invites the other reading: a journal in the everyday sense ACCUMULATES, and this one
915/// does not. What is kept is where a root GOT TO through a node, one entry per pair, and the next
916/// observation about that pair overwrites the entry rather than adding to a history.
917///
918/// # The host is a MARKER, and what it mounts is an ORDINARY RECORD
919///
920/// The declaration is a unit struct whose NAME is the only thing in it the author chooses. What
921/// replaces it is a four-column record — an attribute macro owns the item it sits on, which is what
922/// makes a one-line mount possible at all — parsed by the same pass [`record`] uses, under the same
923/// kind. So the mounted type has the `*Key` type, the accessor family, the per-database row, the
924/// comparison lowering, the order-by vocabulary and the keyset cursor every declared record has,
925/// **because it is one**: run state stays queryable exactly as anything else a declaration stores.
926///
927/// | column | type | why |
928/// |---|---|---|
929/// | `root` | the type `root = "…"` named | one journal table per ROOT FAMILY, and the root is that family |
930/// | `node` | `String` | `NodeName`'s storable face |
931/// | `station` | `String` | `Station`'s, the framework's own stable word for where a node got to |
932/// | `at` | `Timestamp` | the framework's own instant — feature-free, and stored on every backend |
933///
934/// `root` is the lineage and `node` is the id, so `key = lineage ⊕ id` spells `(root, node)` with
935/// nothing declared for it — and the keyed replace that makes an entry the LAST STATE is the
936/// ordinary write of that key. Nothing about the journal needed a key of its own.
937///
938/// The expansion also writes `impl JournalRow<Root>`, which is the SAME trait the hand path
939/// implements by hand. `of` maps the four things the framework knows onto the four columns; the
940/// `SystemTime` it is handed crosses into `Timestamp` through the fallible conversion, and a
941/// `SystemTime` outside that type's ±9999-year range PANICS rather than being rounded — a journal
942/// row is durable and is read as *when the node got there*, so a substituted instant would record a
943/// moment that never happened.
944///
945/// # THE HAND PATH REMAINS, and every refusal here points at it
946///
947/// This word is SUGAR over `JournalRow`, never a replacement. A deployment that wants its own
948/// columns — a rendered failure, a refusal's content, a timestamp of its own type — declares an
949/// ordinary [`record`] and implements the trait on it, exactly as before, and the two paths are one
950/// seam to every writer the framework has.
951///
952/// # Attributes
953///
954/// The macro's ARGUMENTS, and there are three:
955///
956/// - `root = "<Type>"`, **required** — the chain root this journal is keyed by, spelled as a type in
957/// a string, which is this grammar's rule for every type it names. Nothing here resolves it: the
958/// type is EMITTED, so a path naming nothing is `E0412` at the string the author wrote, and a type
959/// no backend can store is the STORABILITY AUDIT's own refusal at the declaration — a root column
960/// is an ordinary key column and is judged as one.
961/// - the STORE WORDS — where the rows land, passed through to [`record`]'s own grammar VERBATIM.
962/// Every one of them means what it means there: the database blocks, `table = "…"`,
963/// `rename = "…"` and `alias(…)`, with their refusals. Omit them and the mount lands one rung
964/// down, on [`entity`]: the same four columns, the same `(root, node)` key and the same
965/// `JournalRow` impl, with no table anywhere — which is the pure-compute journal a deployment
966/// lands through a lane of its own.
967/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Spent twice
968/// here: the row contract names the framework's trait, and the `at` column is declared as the
969/// framework's instant.
970///
971/// A FIELD takes none, there being no field to write.
972///
973/// # Refusals
974///
975/// The declaration's SHAPE is the marker: a struct with fields, a tuple struct, an enum, a union and
976/// any generic parameter. The field refusal is the teaching one — custom columns are what the hand
977/// path is for, and the message says so rather than reporting a shape error.
978///
979/// A missing `root`. And every other word, by name and in two families. The record's own SHAPE words
980/// — `lineage(…)`, `key(…)`, `graphql(…)`, `implements(…)`, `subscribe`, `upstream(…)` — would each
981/// decide something CANONICAL has already decided, so each refusal names what decided it and points
982/// at the hand path. `fulltext(…)`, `vector(…)` and `blob(…)` are refused for the one-storage law's
983/// reason, exactly as a record refuses them: a journal holds rows, and an index over those rows is a
984/// node of its own.
985#[proc_macro_attribute]
986pub fn journal(
987 args: proc_macro::TokenStream,
988 item: proc_macro::TokenStream,
989) -> proc_macro::TokenStream {
990 let input = syn::parse_macro_input!(item as syn::DeriveInput);
991 let arguments = host::options(args.into());
992 // THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, for `node`'s reason — but the
993 // host is not the same item in the two cases. Accepted, it is the four-column record the word
994 // mounts; REFUSED, it is the author's own marker struct, echoed back unchanged. A refusal may have
995 // named no root at all, so there is no column list to mint, and a guess would put fields of an
996 // invented type in the author's struct beside the message telling them the struct is wrong.
997 match journal::parse(&input, &arguments) {
998 Ok(journal) => {
999 let host = host::echo(&journal.host);
1000 let expansion = journal.model.emit();
1001 quote::quote!(#host #expansion).into()
1002 }
1003 Err(refused) => {
1004 let host = host::echo(&input);
1005 let refusal = refused.to_compile_error();
1006 quote::quote!(#host #refusal).into()
1007 }
1008 }
1009}
1010
1011/// Declare an ENTITY — an identity-bearing node with a wire face and NO rows.
1012///
1013/// ```ignore
1014/// #[ingraph::entity(lineage(fields(media_id)), graphql(async_graphql))]
1015/// pub struct Keyframe {
1016/// #[ingraph(id, copy)]
1017/// id: u32,
1018/// #[ingraph(copy)]
1019/// media_id: i64,
1020/// #[ingraph(skip)]
1021/// clip: Embedding<f32, 4, Clip>,
1022/// }
1023/// ```
1024///
1025/// # The LADDER's middle rung
1026///
1027/// | tier | word | has | lacks |
1028/// |---|---|---|---|
1029/// | field fragment | [`fields`] | shared fields, inherited by holders | identity, rows, wire root |
1030/// | **entity** | **this** | id · key · lineage · accessors · a wire face · election-projectable | rows |
1031/// | record | [`record`] | everything above **plus rows** | — |
1032///
1033/// It shares EVERYTHING about identity with [`record`], verbatim: `lineage(fields(…), rename = "…")`,
1034/// `key(rename = "…")`, the `id` and `copy` field markers, the scoped renames, the `*Key` and
1035/// `*Lineage` types with their accessor families, the entity binding, `implements(…)` and every edge
1036/// word. What stops at the storage line stops for one reason — an entity has no rows — so a store
1037/// word is refused, naming [`record`] as the declaration a node whose messages land in a database
1038/// takes, and with the rows go the row types, the per-database comparisons, the order-by and the
1039/// query face.
1040///
1041/// This is not a new code path. It is the rowless path 22 declarations were already on with no word
1042/// for it: a `record` that wrote no storage block compiled, emitted its key family and its wire face
1043/// and stored nothing. That shape now has its own macro, and [`record`] refuses to be it.
1044///
1045/// # It is DRESSABLE, and that is the whole of what separates it from [`operator`]
1046///
1047/// `graphql(…)` is admitted here and refused on an operator. A dressed entity publishes its ADDRESS,
1048/// which is what a search declaration over it projects through — a hit's key is
1049/// `<<<Upstream as Transformer>::Graphql as Graphql>::Output as GraphqlOutput>::Key`, and an
1050/// undressed upstream binds `Graphql = ()`, for which `Graphql` is not implemented at all. So the
1051/// KEYS tier of every election over an entity stands on this word.
1052///
1053/// What the block may NOT do here is publish a FIELD. A read populates a wire field from a stored
1054/// column, so a field wearing `graphql` on a rowless declaration is refused by name and told the
1055/// exit: make it a [`record`]. The block itself still pays for itself — the address is what it
1056/// publishes.
1057///
1058/// # The two-clock wall, and the `keys` word downstream
1059///
1060/// A dressed election over an entity mounts the KEYS tier ALONE. The hydrated tier projects
1061/// `<Upstream as Hydrates>::Db`, which only a record with a queryable row implements, so a search
1062/// declaration whose upstream is an entity wears `keys` — see [`vector`] and [`fulltext`]. Without
1063/// the word the demand is written and the compiler answers `E0277` at `upstream(node = "…")`, carrying
1064/// `Hydrates`' own sentence and both exits.
1065///
1066/// # Refusals
1067///
1068/// A store word (`sqlite`, `postgres`, `mysql`, `mongo`) and `table = "…"` beside them, each naming
1069/// [`record`]. A per-field storage word — the `persist(…)` refining block, and `skip`, which is the
1070/// answer to a question only a record asks. `fulltext(…)`, `vector(…)` and `blob(…)`, for the
1071/// one-storage law's reason: each is a second node's declaration. And the declaration's own shape,
1072/// exactly as [`record`]'s.
1073///
1074/// # `receipt = "media::SceneId"` — WHAT AN ACKED GIVE OF THIS MESSAGE IS ANSWERED WITH
1075///
1076/// ```ignore
1077/// #[ingraph::entity(receipt = "media::SceneId")]
1078/// pub struct SceneOpen { /* … */ }
1079/// ```
1080///
1081/// A producer that gave one of these through `Feed::give_acked` is parked on its consumer's answer,
1082/// and what it is usually parked for is a DURABLE IDENTITY: a seat upserts the row, the natural key
1083/// it matched keeps the id it already had, and only the seat knows what that id is. The value rides
1084/// back on the ack, and this word is where the two ends of that ack learn to name the same type.
1085///
1086/// **The word is the MESSAGE's and not the consumer's**, which is the ruling this rung is the home
1087/// of. A receipt answers the item that was GIVEN: one message asks one question, and every seat on
1088/// the far end of that edge answers the same one. Keyed on the consumer — which is where the seat
1089/// shipped — two seats over one message each declared the answer's type and could disagree; keyed
1090/// here there is one declaration and nothing to keep in step. [`record`] and [`aggregate`] take the
1091/// word on the same terms, being an entity with rows and a record whose rows are a fold; every other
1092/// kind is refused by name, with the sentence pointing back at these three.
1093///
1094/// Refer-quoted, as `options = "…"` and `subscribe = "…"` are: it names a type this declaration did
1095/// not mint, so nothing here resolves it and the path is emitted verbatim — a path naming nothing is
1096/// the compiler's refusal AT THE STRING, because `LitStr::parse` respanned the tokens onto the
1097/// literal. Written once; twice is refused by name.
1098///
1099/// ## What it buys, and it is one impl
1100///
1101/// `impl Receipts for <Message> { type Receipt = <path>; }`, and with it a producer read that names
1102/// NOTHING: `feed.give_acked(open)?.receipt()` projects through the impl, because `Acked<M>` carries
1103/// the message it was opened with. The consumer's own door still names the message —
1104/// `Emitter::receipt_of::<SceneOpen>(id)` — because an `Emitter<Out>` is typed at what a node
1105/// produces and carries no trace of what it was handed; a body handing it another type is `E0308` on
1106/// its own line, where before the two ends met at runtime as `Unreceipted::Mismatched`, on the
1107/// producer's thread, one edge from the body that caused it.
1108///
1109/// ## Silence costs NOTHING, which is why the seat is a sibling
1110///
1111/// A message that writes no word gets no impl, no seat and no bound. That is the whole reason
1112/// `Receipts` is a trait beside everything rather than a member of anything: associated-type defaults
1113/// are unstable (`E0658`), so a member could not be defaulted, and an undefaulted one would make
1114/// every declaration in this tree write a line to say it is waited on by nobody.
1115///
1116/// Hand-writing the impl is equally legal and equally complete — two roads, one seat — and it is the
1117/// road a GENERIC message has to take: a message carrying a parameter of its own, whose receipt is
1118/// that parameter, has no concrete path a quoted word could name and says
1119/// `impl<S> Receipts for SceneOpen<S> { type Receipt = S; }` instead.
1120///
1121/// # `remote = "path::To::Type"` — the WRAPPER mode
1122///
1123/// Admitted here on exactly [`record`]'s terms, and this is the rung to take for a type with VALUE
1124/// semantics: `#[ingraph::entity(remote = "…")]` restates a foreign type's shape as a manifest and
1125/// replaces the item with `#[repr(transparent)] struct X(Remote);`. The whole mode is documented on
1126/// [`record`], which is where the two seams and the hydration builder are written; what differs
1127/// here is only what always differs between the rungs — an entity has no rows, so it has no raise,
1128/// and the bridge is needed in the READING direction alone.
1129#[proc_macro_attribute]
1130pub fn entity(
1131 args: proc_macro::TokenStream,
1132 item: proc_macro::TokenStream,
1133) -> proc_macro::TokenStream {
1134 node(args, item, ingraph_codegen::model::NodeKind::Entity)
1135}
1136
1137/// Declare an AGGREGATE — a record whose rows are a declared FOLD over one upstream's rows, one row
1138/// per group, recomputed WHOLE on every trigger.
1139///
1140/// ```ignore
1141/// #[ingraph::aggregate(
1142/// upstream(node = "demux::Track"),
1143/// group(codec = "codec"),
1144/// measure(count = counting),
1145/// poll(recount, every = "10m", light),
1146/// sqlite,
1147/// )]
1148/// pub struct CodecCensus {
1149/// #[ingraph(group)] codec: Codec,
1150/// #[ingraph(measure)] count: u64,
1151/// }
1152/// ```
1153///
1154/// # IT MOUNTS A RECORD, and the row it mounts is the one the declaration wrote
1155///
1156/// The columns are the author's, the KEY is the group projection — `key = lineage ⊕ id` over the
1157/// group columns, minted rather than declared — and the store words, the clock and `graphql(…)` are
1158/// carried to the RECORD pass verbatim. So an aggregate has the `*Key` type, the per-database rows,
1159/// the `find_<db>` and `upsert_<db>` doors, the order-by vocabulary, the cursor and the `<Node>Due`
1160/// clock vocabulary that every declared record has, because it IS one.
1161///
1162/// Beside them the expansion writes the one thing a record cannot say: `fold(rows: &[Upstream]) ->
1163/// Vec<Self>`, one row per group, with each measure's citizen called statically. A trigger's body is
1164/// then the three calls the two nodes already published — read the upstream's table, fold, upsert
1165/// each answer — and the keyed replace is what makes running it on every tick safe.
1166///
1167/// # It consumes the upstream's TABLE, not its messages
1168///
1169/// At-least-once delivery plus keyed replace is what makes this framework's writes safe, and it
1170/// makes DUPLICATES normal operation: a fan-out clones per edge, a rewind re-delivers the unacked
1171/// tail, a retry re-sends. No app-visible message id exists to dedup on, so an incremental
1172/// `count += 1` cannot inherit that safety. A trigger therefore reads the upstream's rows, groups
1173/// them, folds each group and upserts one row per group — immune to duplicates by construction,
1174/// self-healing on every tick, and deletion-correct for free.
1175///
1176/// # The three parts, and the two words SQL has no room for
1177///
1178/// | word | it is | notes |
1179/// |---|---|---|
1180/// | `upstream(node = "…")` | the `FROM` | the EDGE alone; a projection here is refused pointing at `group(…)` |
1181/// | `group(<field> = "<upstream field>")` | the `GROUP BY` | also the projection, and the columns the key is minted from |
1182/// | `measure(<field> = <fold>)` | the aggregate functions | a shipped fold BARE, your own QUOTED as its type path |
1183/// | `poll(…)` | the clock | MANDATORY — the trigger is the only thing that writes the rows |
1184/// | the STORE WORDS, bare | where the rows land | a record's own words, carried to the record pass |
1185/// | `graphql(…)` | the wire face | optional, and it publishes through the record path |
1186///
1187/// # Every field wears EXACTLY ONE role
1188///
1189/// `#[ingraph(group)]` says this column keys the folded row; `#[ingraph(measure)]` says a fold fills
1190/// it. A field wearing neither has no place in the row; a field wearing both would be part of the
1191/// key that decides which rows it is folded from. Each word is also its head block's, one word at
1192/// two grains — and the two halves are checked AGAINST each other, so a head and a field that
1193/// disagree are refused rather than resolved by precedence.
1194///
1195/// # Refusals
1196///
1197/// A missing `upstream(…)`, a second one (multi-upstream folding wants a by-key intake this
1198/// framework has not built), a projection entry inside it, a missing or empty `group(…)` or
1199/// `measure(…)`, one field named twice in either, an entry naming a field this declaration does not
1200/// have, an entry whose field wears the OTHER role, a marked field no entry names, a missing
1201/// `poll(…)`, a bare word inside `measure(…)` that names no shipped fold, `#[ingraph(id)]` (the key
1202/// is the group columns), the other kinds' election markers, the record words this grammar decides
1203/// for itself (`lineage`, `key`, `subscribe`), the retired `persist(…)` wrapper, the three other
1204/// storage words, and the declaration's own shape: a non-struct, a positional or unit struct, any
1205/// generic parameter, and a struct with no field.
1206#[proc_macro_attribute]
1207pub fn aggregate(
1208 args: proc_macro::TokenStream,
1209 item: proc_macro::TokenStream,
1210) -> proc_macro::TokenStream {
1211 let input = syn::parse_macro_input!(item as syn::DeriveInput);
1212 let arguments = host::options(args.into());
1213 // THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, for [`node`]'s reason. It is the
1214 // AUTHOR's item either way, unlike [`journal`]'s: this word mints no column, so the declaration
1215 // the compiler sees and the one the record pass reads differ in their `#[ingraph(…)]` markers
1216 // alone — and the echo strips every one of those.
1217 let host = host::echo(&input);
1218 let expansion = aggregate::parse(&input, &arguments)
1219 .and_then(|model| aggregate::mount(&input, model))
1220 .map_or_else(
1221 |refused| refused.to_compile_error(),
1222 |mounted| mounted.emit(),
1223 );
1224 quote::quote!(#host #expansion).into()
1225}
1226
1227/// Declare a FIELD FRAGMENT — a group of fields several declarations hold, written once.
1228///
1229/// ```ignore
1230/// #[ingraph::fields(record, entity, graphql)]
1231/// pub struct Dimensions {
1232/// #[ingraph(copy)]
1233/// width: u32,
1234/// #[ingraph(copy)]
1235/// height: u32,
1236/// }
1237/// ```
1238///
1239/// # A fragment is HELD, and every absence follows from that
1240///
1241/// It is the ladder's bottom rung — 公用字段抽取 — and it is not a node. A holder declares one as an
1242/// ordinary field, its columns land in the holder's row, and its wire presence is a fragment of the
1243/// holder's object. So this derive is FAMILY-LESS, and none of the absences is an era rule waiting
1244/// to lift:
1245///
1246/// | absent | because |
1247/// |---|---|
1248/// | `Identifiable` | it bears no id — that is what the tier MEANS |
1249/// | `Transformer` | that face is a key and the two address types beside it |
1250/// | `Graphql` | a wire face is a queryable ROOT, and a fragment is a fragment |
1251/// | every storage | its columns are the HOLDER's row |
1252///
1253/// A group of fields that does bear an identity is an [`entity`], and one that holds rows besides is
1254/// a [`record`]. Both refusals name both rungs, so a migrating author reads which one they wanted.
1255///
1256/// # The word was `entity`, and the rename is the ladder's
1257///
1258/// The tier's own doc said *no stable identity is what the tier means* while `entity` names an
1259/// identity-bearing thing everywhere else in this framework. The code moved WHOLE; only the word
1260/// changed, and `entity` now names the rung it always described.
1261///
1262/// # ACTIVATION, which is required
1263///
1264/// A fragment is HELD, so what it has to ANSWER is whatever the holding kind asks — and the kinds
1265/// ask different things. Three words say who asks, and a declaration that writes none of them is a
1266/// named refusal:
1267///
1268/// | word | activates |
1269/// |---|---|
1270/// | `record[(<db>, …)]` | the STORAGE faces — the width, the bind, the read, the keyset, the comparison |
1271/// | `entity` | the READ faces — the predicate and the two marker rows a holder resolves a slot through |
1272/// | `graphql[(…)]` | the WIRE face — the object, its crossing, and the filter's input-object registration |
1273///
1274/// The first two are HOST KINDS, and a record activates the read faces too — its own filter being
1275/// that same predicate. The third is not a host kind: it says the declaration has a face a client can
1276/// reach at all. There is no shorthand for both host kinds; write both. The accessor family is the
1277/// tier's own and is emitted either way.
1278///
1279/// `record(sqlite, postgres)` is the record head's own store words one namespace in: it names the
1280/// dialects this fragment is BUILT for and claims no table, the table being the holder's. `entity`
1281/// is BARE — entity-hosting has nothing to configure yet, and `entity(…)` says so by name.
1282/// `graphql(rename = "…", filter(rename = "…"))` names the OBJECT and the BASE the filter's input
1283/// objects compose off — `filter(rename = "Dim")` publishing `DimFilter` beside `DimColumnFilter`,
1284/// per the twin law.
1285///
1286/// # Attributes
1287///
1288/// On the struct, beside the three activations:
1289///
1290/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Present
1291/// because the expansion spends it: a `Vec<_>` field is handed back through `project::Repeated`
1292/// and an `Option<_>` through `project::Optional`.
1293/// - `remote = "path::To::Type"` — the FOREIGN TYPE this fragment wraps. See *The rewrite mode*
1294/// below.
1295/// - `builder(…)` — the wrapped type's construction protocol, which the storage face's hydration
1296/// spends.
1297/// - `cursor[(…)]` — this fragment is a paging position in its own declared order. It needs
1298/// `record`: both halves of what spends the assertion need rows to walk.
1299///
1300/// Every block a node writes — `key(…)`, `lineage(…)`, a store word, `table`, `fulltext(…)`,
1301/// `vector(…)`, `blob(…)` — is refused BY NAME, each message saying what a fragment has instead.
1302///
1303/// On a field: the three projection words (`copy`, `repeated`, `optional`), `builder(…)`, the
1304/// host-kind namespace `record(…)` and the wire face's own `graphql(rename = "…")`. What a field
1305/// says to a host kind goes INSIDE that kind's namespace, which is what keeps one ident from meaning
1306/// two things at two seats — `record(skip)`, `record(skip(default = "…"))`, `record(flatten)` and
1307/// the per-dialect claims are the record field seat's own words, letter for letter one level in.
1308/// The labels and the wire legs are still declared ONCE here and inherited by every holder; what
1309/// reads that inheritance has not arrived, so those are a named refuse-until rather than a fact
1310/// parsed into a model nothing spends. `id` is refused separately and permanently, by the tier's own
1311/// definition.
1312///
1313/// A field's `#[cfg]` is SERVED, family-wide: it takes the accessor, the segment, the bind, the read,
1314/// the filter seat and the place on the wire face, all together. Two things it cannot reach are
1315/// refused by name — a `where` predicate takes no attribute, and a `cursor` fragment's key is every
1316/// declared field, so a member that could vanish would page by a different key.
1317///
1318/// # The rewrite mode
1319///
1320/// ```ignore
1321/// #[ingraph::fields(record, entity, remote = "mediaframe::Dimensions")]
1322/// pub struct Dimensions {
1323/// /// The width in pixels.
1324/// width: u32,
1325/// height: u32,
1326/// }
1327/// ```
1328///
1329/// The fields written above are a MANIFEST — the shape of a type another crate owns, restated so
1330/// this framework can read it — and the item the compiler sees is
1331/// `#[repr(transparent)] pub struct Dimensions(mediaframe::Dimensions);`. The orphan rule is why
1332/// the mode exists: a type another crate owns cannot be given this framework's faces where it is
1333/// declared, and a wrapper is the position where it can.
1334///
1335/// `fields` is the FOURTH declaration to take the word and the first with NO IDENTITY SEAT. Each
1336/// manifest field gets ONE reader — `width(&self) -> u32`, reading `self.0.width()` and crossing it
1337/// by `Into` — with the field's own doc comments migrated onto it, since the rewrite deletes the
1338/// field that held them. There are no mutators (a remote's fields are its own), no `const` reader
1339/// (a foreign accessor is not this macro's to declare `const`), and no borrow reader anywhere: a
1340/// record's rewrite borrows its id column because this framework's identity seats borrow, and a
1341/// fragment has no id.
1342///
1343/// Beside the readers come `Deref`, `DerefMut`, `AsRef`, `AsMut`, `Borrow`, `BorrowMut` and `From`
1344/// in both directions, so the wrapper is usable where the wrapped type was and inherits its methods.
1345/// The macro OWNS the `#[repr(…)]`; an author's own is refused. Every other item attribute —
1346/// `#[derive(…)]`, `#[cfg]`, doc comments — is forwarded onto the wrapper verbatim.
1347///
1348/// # What it emits
1349///
1350/// One inherent impl: the accessor family for every field, and the mutator pair beside each. A
1351/// record withholds the mutators from the fields that bear identity; a fragment has no such field,
1352/// which is why every one of its fields takes both.
1353///
1354/// Beside it are the FACES the activations asked for — the column width, the bind, the read, the
1355/// keyset, the comparison, the predicate, and the fragment's own output object with the predicate's
1356/// input face. There is still no constructor, no `Default`, no identity, no storage of its own and
1357/// no queryable root: what a fragment answers are questions its holder was already asking.
1358///
1359/// # Refusals
1360///
1361/// The declaration's SHAPE is the fragment, so each part of it is checked here rather than left to
1362/// fail inside the expansion: a non-struct, a positional or unit struct, any generic parameter, and
1363/// a struct with no field at all — the tier exists to declare fields a holder inherits, so a
1364/// declaration with none has nothing to inherit. Two more are about the EMISSION: a field whose
1365/// name takes the framework's `__name__` shape, and two fields reaching one method name.
1366#[proc_macro_attribute]
1367pub fn fields(
1368 args: proc_macro::TokenStream,
1369 item: proc_macro::TokenStream,
1370) -> proc_macro::TokenStream {
1371 let input = syn::parse_macro_input!(item as syn::DeriveInput);
1372 let arguments = host::options(args.into());
1373 let parsed = fields::parse(&input, &arguments);
1374 // A REWRITE replaces the item outright — see [`host::transparent`] — and only an ACCEPTED one
1375 // does. A refusal echoes the author's own struct back unchanged, for the reason [`node`] carries:
1376 // the wrapper is built from a path the refusal may be about, and emitting a wrapper over a type
1377 // that resolves to nothing would bury the sentence that named the real mistake.
1378 let host = match parsed.as_ref().ok() {
1379 Some(model) if model.remote.is_some() => {
1380 host::transparent(&input, model.remote.as_ref().expect("a rewrite's own path"))
1381 }
1382 _ => host::echo(&input),
1383 };
1384 let expansion = parsed.as_ref().map_or_else(
1385 syn::Error::to_compile_error,
1386 ingraph_codegen::fields::FieldsModel::emit,
1387 );
1388 quote::quote!(#host #expansion).into()
1389}
1390
1391/// Declare a FULL-TEXT INDEX over another node's messages — an operator holding one document per
1392/// message it saw, searchable by text.
1393///
1394/// ```ignore
1395/// #[ingraph::fulltext(upstream(node = "asr::Segment", title = "speaker", body = "text"))]
1396/// pub struct SearchDocument {
1397/// #[ingraph(searchable)]
1398/// title: String,
1399/// #[ingraph(searchable)]
1400/// body: String,
1401/// }
1402/// // => pub(crate) __ig_key__: <asr::Segment as Transformer>::Key, injected into the struct
1403/// // with new(__ig_key__, title, body) · key_ref() · title_ref() · body_ref() · the mutators
1404/// // and impl Transformer / Identifiable, every member of both projected from the upstream
1405/// ```
1406///
1407/// # Its key is not its to mint, and that is what the tier MEANS
1408///
1409/// A document is one upstream message INDEXED, so it is addressed by that message's key. There is
1410/// no `#[ingraph(id)]` field — one is refused by name — no `*Key` type and no `*Lineage` type; the
1411/// expansion injects ONE field carrying `<Upstream as Transformer>::Key` and answers both address
1412/// members through it. Re-keying the upstream therefore re-keys every index over it, and a drift is
1413/// a compile error rather than a convention.
1414///
1415/// The injected field is why this is an attribute macro. A derive is handed a copy and may only
1416/// append; a field that is not in the source cannot exist under one.
1417///
1418/// # `upstream(…)` is the edge AND the projection
1419///
1420/// - `node = "path::To::Upstream"` — the upstream, as a type path in a string, which is this
1421/// grammar's rule for every type it names. Nothing here resolves it: the path is EMITTED, so a
1422/// path naming nothing is `E0412` and a path naming something that is not a node is `E0277`, both
1423/// at the string the author wrote.
1424/// - `<this declaration's field> = "<the upstream's field>"` — one per field, and EVERY field needs
1425/// one. The emission writes a per-field audit whose body is a direct field read, so a field the
1426/// upstream does not have is `E0609`, one it will not show is `E0616` and one whose type does not
1427/// match is `E0308` — each at the authored string.
1428///
1429/// A DIRECT field read rather than an accessor call: a record's accessor is spelled four ways
1430/// depending on the projection its own declaration asked for, and this expansion cannot see which.
1431/// The field name is the one spelling that does not vary — and the `pub(crate)` stamp is what makes
1432/// reading it legal from the module the index was declared in.
1433///
1434/// # Attributes
1435///
1436/// On the declaration: `upstream(…)`, `dedup(…)`, `crate = "…"`, `graphql(<backend>)` — which
1437/// backends dress this declaration's fusion family — and `rename`, which names the RUST types it
1438/// mints. Every OTHER block a record writes names something a node with no rows and no id of its own
1439/// does not have, and each is refused by name. `fulltext(…)` is refused too, and for good: the
1440/// engines are per FIELD, because a slot is one field in one engine, so a block at the head could
1441/// only name them for the whole declaration.
1442///
1443/// The two naming words are two AXES and never cross. `rename = "ShotSearch"` re-bases the whole
1444/// minted Rust family and `rename(<piece> = "…")` names an individual mint; inside the backend
1445/// block, `prefix = "…"` re-stems that BACKEND's SDL family and `options`/`question`/`engine` name
1446/// one face each with a `rename` row. A skin never renames Rust and a bone never appears in a
1447/// schema.
1448///
1449/// The two WORDS carry the vocabulary law: **`rename` names ONE thing verbatim, `prefix` re-stems a
1450/// FAMILY.** The skin base is pure stem — `prefix = "clips"` mints `ClipsFuseOptions` and its
1451/// siblings, and no emitted type is called `clips` — so that seat takes the second word, and every
1452/// seat naming a real type outright keeps the first.
1453///
1454/// # The wire face is the WORD's, and the Rust surface is not
1455///
1456/// Without `graphql(…)` this declaration still emits everything a program can call: the doors, the
1457/// packages, the evidence, the selector and the `Fusable` binding. What the word adds is one
1458/// backend's WIRE IMPLS over those same types — a backend-only search pipeline needs no block at
1459/// all, and a schema needs one word.
1460///
1461/// On a field, the three projection words (`copy`, `repeated`, `optional`) and `searchable`.
1462///
1463/// # `#[ingraph(searchable)]` — MANDATORY, and repeatable
1464///
1465/// It says a field is what this index SEARCHES. Presence elects; absence leaves the field ordinary
1466/// payload — stored, hydrated, and matched by nothing. At least one field must wear it: a
1467/// declaration marking none is refused by name, an index that searches nothing being an index over
1468/// no subject.
1469///
1470/// It dissolves the posture that preceded it, which was *every projection is searched, so there is
1471/// no WHICH to answer*. There is a WHICH, it is declared, and a document may now carry the columns
1472/// it wants hydrated beside the ones it wants matched.
1473///
1474/// # `keys` — the UPSTREAM's rung, and the tier pair it decides
1475///
1476/// A dressed election answers each road twice: the KEYS tier hands back addresses and touches no
1477/// store, the HYDRATED tier hands back the upstream's whole entities and reads them out of one. The
1478/// hydrated pair projects `<Upstream as Hydrates>::Db`, whose impl only a [`record`] with a
1479/// queryable row emits — so which tiers a declaration can mount is decided by which RUNG of the
1480/// record ladder its upstream sits on, and never by anything this declaration could choose.
1481///
1482/// A RECORD upstream mounts both, unconditionally and with no word to write: rows are a record's
1483/// essence, so storage is guaranteed and hydration can never miss. An [`entity`] upstream mounts the
1484/// keys tier, and this bare word is where it says so — the pure-engine deployment's honest home, a
1485/// search surface over a node whose messages land in no database anywhere.
1486///
1487/// Written with no word, an entity upstream still emits the hydrated demand and the compiler answers
1488/// `E0277` at `upstream(node = "…")` carrying `Hydrates`' own sentence, which names both exits:
1489/// persist the upstream, or wear the word. Nothing here guesses — a macro narrowing the surface to
1490/// whatever happens to compile would be this crate deciding a deployment's storage posture.
1491///
1492/// # THE SEAT LAW: **a seat may sit EMPTY, and a written word must point at something MINTED**
1493///
1494/// Every name seat in this grammar is optional, and silence costs nothing — an unwritten seat is a
1495/// capability nobody has asked for yet, and most declarations write none of them. What is refused is
1496/// a word that reaches no emitted name: `hydrated(rename = "…")` on a declaration wearing `keys`,
1497/// `keys(rename = "…")` on a FANNED election that publishes one leaderboard and no per-store road,
1498/// `engines(rename = "…")` where there is one leg and so no per-leg product, and
1499/// `key(input(rename = "…"))` on a ROOT record, whose address crosses inward as its id and mints no
1500/// argument object.
1501///
1502/// The distinction is what makes this a law rather than a strictness: an empty seat is a promise
1503/// nobody made, and a written word that silently does nothing is an author's belief the schema does
1504/// not share. Each refusal names the WORD, what it would have named, and the shape that publishes
1505/// none of it — so both repairs are visible, the word being one of them.
1506///
1507/// # Refusals
1508///
1509/// A second `upstream(…)`, which is the multi-upstream shape and a round of its own. A missing one, a
1510/// `upstream(…)` with no `node`, an entry naming a field this declaration does not have, a field no
1511/// entry names, and the LIST form `field = ["a", "b"]` — which the ruled grammar has and whose
1512/// combining rule it does not. `subscribe = "…"`, by name, as the spelling that projects nothing.
1513/// A field called `node`, which collides with the upstream entry. A declaration marking nothing
1514/// `searchable`, and a field marked `knn`, which is the `vector` kind's. And the declaration's own
1515/// shape: a non-struct, a positional or unit struct, any generic parameter, and a struct with no
1516/// field.
1517#[proc_macro_attribute]
1518pub fn fulltext(
1519 args: proc_macro::TokenStream,
1520 item: proc_macro::TokenStream,
1521) -> proc_macro::TokenStream {
1522 derived(args, item, ingraph_codegen::model::NodeKind::Fulltext)
1523}
1524
1525/// Declare an EMBEDDING INDEX over another node's messages — an operator holding one document per
1526/// message it saw, searchable by nearness.
1527///
1528/// ```ignore
1529/// #[ingraph::vector(upstream(node = "video::Keyframe", image = "image_embedding", caption = "caption_embedding"))]
1530/// pub struct KeyframeEmbedding {
1531/// #[ingraph(knn)]
1532/// image: Embedding<f32, 768>,
1533/// #[ingraph(knn)]
1534/// caption: Embedding<f32, 768>,
1535/// }
1536/// ```
1537///
1538/// Everything about the tier is [`fulltext`]'s, verbatim: the injected key, the per-field audit, the
1539/// grammar and its refusals — `graphql(<backend>)` and `rename` among them. What differs is the
1540/// ENGINE the documents are written to, which is named on the FIELD beside its election because a
1541/// slot is one field in one engine, and the one word this kind adds.
1542///
1543/// # `#[ingraph(knn)]` — MANDATORY, and repeatable
1544///
1545/// A field's TYPE states its shape, and *this is what a knn runs over* is a ROLE, so the role is
1546/// declared — on the field, which is the thing that has it. At least one field must wear the marker;
1547/// mark several to elect several, and each election becomes a VECTOR COLUMN of this declaration's
1548/// ONE slot, with a `retrieve_keys_by_<field>` / `retrieve_by_<field>` pair of its own. An
1549/// embedding-typed field wearing no marker is ordinary payload — stored, hydrated, and reached by no
1550/// knn.
1551///
1552/// The QUESTION ROAD is a [`tower`]'s, and the marker's `ask` word retired on 2026-08-19. A road
1553/// from what a person typed to what a column can be asked with is declared once, as a tower, and
1554/// reached either by hand — walk it and hand the coordinates to `retrieve_keys_by_<field>` — or by
1555/// a [`search`] recipe's `tower(<arm>(type = "…"))` arm. The word that used to live here erased
1556/// every hop's refusal into one boxed name; a tower's own `<Tower>Error` names the step AND carries
1557/// that step's error type, which is what the move bought.
1558///
1559/// # `knn(searchable(tower = "…"))` — the SUGAR, and the two entries the block holds
1560///
1561/// `knn(…)` takes `semantics(<kind> = "…")`, which decides how this election's answer is scored,
1562/// and `searchable(tower = "path::to::Tower")`, which names the tower a question is walked
1563/// through to reach this column.
1564///
1565/// The second word is PURE SUGAR: it expands to the one-member `#[ingraph::search]` recipe an
1566/// author would otherwise type — `{Index}{Field}Search`, a shared seat whose type is the tower's own
1567/// `<Tower as SearchTower>::Question`, one `shared` arm, and this declaration's `graphql(…)` block
1568/// passed through, so the wire fields `{index}{field}Search` and `{index}{field}SearchKeys` land
1569/// wherever a hand-written recipe's would. Nothing underneath knows which of the two it expanded
1570/// from.
1571///
1572/// It is the shortest road and not the widest one. A weight, a floor, a second member or a second
1573/// seat is a recipe's word, so the moment one is wanted the answer is to write the recipe — which is
1574/// what the refusal inside `searchable(…)` says.
1575///
1576/// The word is the full-text election marker's own spelling, in a second position. It means one
1577/// thing in both — *a question can reach this column* — and what it takes is the difference: nothing
1578/// where a question is already text, a tower where the column holds coordinates.
1579///
1580/// A field marked `searchable` is refused here by name — that is the `fulltext` kind's marker — and
1581/// so is a field marked `knn` whose type holds no coordinates, at the TYPE its author wrote.
1582///
1583/// # `keys` — the UPSTREAM's rung
1584///
1585/// [`fulltext`]'s word, verbatim and for its reason: an [`entity`] upstream holds no rows, so the
1586/// hydrated half of each road has no store to read out of and is not mounted. See there for the
1587/// whole of it, and for what a declaration that omits the word over an entity upstream is refused
1588/// with.
1589#[proc_macro_attribute]
1590pub fn vector(
1591 args: proc_macro::TokenStream,
1592 item: proc_macro::TokenStream,
1593) -> proc_macro::TokenStream {
1594 derived(args, item, ingraph_codegen::model::NodeKind::Vector)
1595}
1596
1597/// Declare an ARTIFACT FAMILY derived from another node's messages — an operator holding one stored
1598/// object per message it saw.
1599///
1600/// ```ignore
1601/// #[ingraph::blob(upstream(node = "video::Keyframe", payload = "pixels"))]
1602/// pub struct Thumbnail {
1603/// #[ingraph(repeated)]
1604/// payload: Vec<u8>,
1605/// }
1606/// ```
1607///
1608/// Everything about the tier is [`fulltext`]'s, verbatim, EXCEPT what a family with no query surface
1609/// cannot spend. The store is named at the HEAD — `fs`, `s3` — because this kind elects nothing and
1610/// its slot is `(declaration × engine)`; beside it ride `extension`, which ends the address this
1611/// node's carried key renders into directories, `data`, which permits the bytes to travel, and
1612/// `slot = "…"`, which names the corpus the objects are stored under (default:
1613/// `snake_case(<declaration name>)`).
1614///
1615/// `rename` and `graphql(…)` are REFUSED here, each with its measurement rather than as a wait: this
1616/// kind lands no type in the declaring scope for a rename to move, and it mints no wire type for a
1617/// backend to dress — its address and its bytes are fields of a RECORD's output object, put there by
1618/// that record's `locate(…)`.
1619#[proc_macro_attribute]
1620pub fn blob(
1621 args: proc_macro::TokenStream,
1622 item: proc_macro::TokenStream,
1623) -> proc_macro::TokenStream {
1624 derived(args, item, ingraph_codegen::model::NodeKind::Blob)
1625}
1626
1627/// The one body every DERIVED-INDEX macro has: parse under this kind, echo the host carrying the key
1628/// the model minted, then emit.
1629///
1630/// The order is the difference from [`node`] and [`equip`], and it is forced: the injected field's
1631/// TYPE is `<Upstream as Transformer>::Key`, so the host cannot be written until the upstream has
1632/// been read out of the declaration.
1633///
1634/// A REFUSED declaration is echoed WITHOUT the field, and the rule is the honest one rather than a
1635/// best effort. The field exists to carry a key from an upstream, and a declaration that was refused
1636/// may have named no upstream at all; a guess would put a field of some invented type in the
1637/// author's struct beside the message telling them the struct is wrong. What does not change is that
1638/// the host is emitted either way — an attribute macro replaces the item it sits on, so a refusal
1639/// that emitted only the error would delete the type and bury its own message under every mention of
1640/// it.
1641fn derived(
1642 args: proc_macro::TokenStream,
1643 item: proc_macro::TokenStream,
1644 kind: ingraph_codegen::model::NodeKind,
1645) -> proc_macro::TokenStream {
1646 let input = syn::parse_macro_input!(item as syn::DeriveInput);
1647 let options = host::options(args.into());
1648 let parsed = index::parse(&input, &options, kind);
1649 let host = match &parsed {
1650 Ok(model) => host::echo_carrying(&input, model.carried_key()),
1651 Err(_) => host::echo(&input),
1652 };
1653 let expansion = parsed.as_ref().map_or_else(
1654 syn::Error::to_compile_error,
1655 ingraph_codegen::index::IndexModel::emit,
1656 );
1657 // THE SUGAR'S ITEMS RIDE BESIDE THE INDEX'S OWN, and they are the recipe macro's own expansion of
1658 // a declaration this crate wrote instead of the author. Nothing here decides anything a
1659 // hand-written `#[ingraph::search]` does not — see `search::sugar`, where the whole of it is.
1660 let forged = parsed
1661 .as_ref()
1662 .map(search::sugar::recipes)
1663 .unwrap_or_default();
1664 quote::quote!(#host #expansion #forged).into()
1665}
1666
1667/// Declare a SHAREABLE RESOURCE — a type several units may hold at once.
1668///
1669/// ```ignore
1670/// #[ingraph::resource]
1671/// pub struct Egemma {
1672/// model: EgemmaModel,
1673/// }
1674///
1675/// impl ingraph::AsyncResource for Egemma {
1676/// type Options = EgemmaOptions;
1677/// type Error = LoadError;
1678///
1679/// async fn build(_ctx: &Resources, options: EgemmaOptions) -> Result<Self, LoadError> { … }
1680/// }
1681/// ```
1682///
1683/// # Sharing is a DOUBLE opt-in, and this word is the first half
1684///
1685/// A unit field written as the plain type is EXCLUSIVE: the unit owns it, the framework knows
1686/// nothing about it, and a `!Send` value is legal there because a resident constructs its operator
1687/// on the engine that runs it and never migrates it. That is the default and it is unchanged.
1688///
1689/// Sharing needs both parties to say so. This word is the RESOURCE AUTHOR's half — *this type is
1690/// meant to be held by several units* — and `model: Shared<Egemma>` on a unit is the MEMBER's. The
1691/// string label a share once needed is dead: the type is the rendezvous.
1692///
1693/// # Three layers, three authors — and this macro is the middle one
1694///
1695/// | layer | written by | what it says |
1696/// |---|---|---|
1697/// | `AsyncResource` | the AUTHOR, by hand | how to build one, and that it crosses threads |
1698/// | this macro | the DECLARATION | the type is a citizen of the walk |
1699/// | `Plan::validate` | the DEPLOYMENT | every demanded resource was declared |
1700///
1701/// The contract is hand-implemented because only the author knows how to load a model — `type
1702/// Options` is the author's own shape, and `build` is `async` because loading one is I/O and
1703/// compute.
1704///
1705/// # RESOURCES ARE THE ENGINES, and kind is said once — here
1706///
1707/// A resource is where a deployment's engines live, so the declaration takes one optional BUILTIN
1708/// KIND WORD: `#[ingraph::resource(tantivy)] pub struct Ft;` names one of the framework's own
1709/// engines, and the expansion writes everything the foreign author writes by hand — the declaration
1710/// re-emitted CARRYING the engine it mints, the `AsyncResource` impl that opens it, and the engine's
1711/// base and faces delegating to it.
1712///
1713/// The vocabulary is CLOSED and each word rides its engine's cargo feature. It is short on purpose:
1714/// a word is a promise that this crate can write the whole binding, which it can only keep for an
1715/// engine it SHIPS. The OPEN half of the axis is the bare form, which is where every other engine
1716/// there is enters — hand-written impls, and no vocabulary to be admitted to.
1717///
1718/// # Attributes
1719///
1720/// On the declaration:
1721///
1722/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Present because
1723/// the expansion spends it: the citizenship impl names the framework's own trait.
1724/// - one BUILTIN KIND WORD — `tantivy` today. Bare; how an engine is TUNED reaches it through the
1725/// `[resources.…]` section its mount names, not through this attribute.
1726/// - `async` — the MODE WORD, and the FOREIGN form's alone: it names which of an engine's two face
1727/// pairs this resource's hand-written impls are. A bare declaration is on the BLOCKING face, which
1728/// is the default nobody writes, and the same lexicon `source(async)`, `handler(async)` and
1729/// `operator(async)` are written in.
1730///
1731/// A kind word and `async` together are REFUSED: a builtin carries its own mode — tantivy is a
1732/// synchronous engine and no word can make it otherwise — so a second opinion beside it could only
1733/// disagree.
1734///
1735/// Every word that would describe HOW a foreign one is built belongs to the `AsyncResource` impl, and
1736/// every word that would describe where its options come from belongs to the launch — so this
1737/// grammar has neither, and an unknown entry is refused by a message saying which of the two it is
1738/// looking for.
1739///
1740/// # What it emits
1741///
1742/// | item | condition |
1743/// |---|---|
1744/// | `impl DeclaredResource for <Type>`, carrying `const SYNC` — the citizenship the walk enumerates, and the mode the declaration recorded | always |
1745/// | the declaration CARRYING the engine the word mints | a kind word |
1746/// | `impl AsyncResource` — `Options` and `Error` projected off the engine's store, `build` its open | a kind word |
1747/// | the engine's BASE (`FulltextEngine`) — eight seats and the address lifecycle, delegating | a kind word |
1748/// | the engine's two faces IN ITS OWN MODE (`FulltextRead` / `FulltextWrite`), delegating | a kind word |
1749/// | `SLOT` and `connection()`, the two doors onto the minted engine | a kind word |
1750///
1751/// No face of the OTHER mode is emitted, and the absence is the honesty rather than an omission: the
1752/// kind word carries the mode knowledge, so an `AsyncFulltextRead` beside a blocking engine would be
1753/// this macro claiming a posture the engine does not have.
1754///
1755/// The FOREIGN form emits the citizenship and nothing else. There is no accessor family, and the
1756/// absence is the tier rather than an omission: a resource is reached through `Shared<R>`, which
1757/// derefs to the type, so what a member can do with one is whatever the author's own inherent impl
1758/// offers. Emitting accessors would put this crate's naming convention on a surface that is somebody
1759/// else's — which is exactly why a kind word gets two doors and a foreign declaration gets none: the
1760/// macro minted that engine, so naming its doors is this crate naming its own.
1761///
1762/// # Refusals
1763///
1764/// The DECLARATION's shape is checked here. A generic parameter is refused, for the reason
1765/// [`ingraph`]'s is — the emission registers ONE type as a citizen, and a parameter is not a type
1766/// until it is substituted. Under the FOREIGN form a tuple struct, a unit struct and an enum are all
1767/// admitted, because nothing in that expansion reads a field or a variant; under a KIND WORD the
1768/// declaration must hold nothing of its own, because the expansion is what puts the engine there.
1769///
1770/// An unknown kind word is refused by a message listing the ones this build knows, and a kind word
1771/// whose engine the `ingraph` dependency did not compile is refused by a `compile_error!` naming the
1772/// feature to add.
1773///
1774/// The CONTRACT is checked by the emission, where the compiler can see it: a declaration with no
1775/// `AsyncResource` impl is `E0277` at the declaration, and so is one whose type is not `Send + Sync` —
1776/// the supertraits being the sharing teeth, biting at the earliest site there is rather than at
1777/// whichever unit reached for the type first.
1778///
1779/// A demanded resource that nobody DECLARED is neither: `AsyncResource` is hand-implemented, so a type
1780/// can satisfy `Shared`'s bound without having joined the walk, and only a plan holds both the
1781/// declared set and the demands. That one is a START-UP refusal, naming the resource and the node.
1782#[proc_macro_attribute]
1783pub fn resource(
1784 args: proc_macro::TokenStream,
1785 item: proc_macro::TokenStream,
1786) -> proc_macro::TokenStream {
1787 let input = syn::parse_macro_input!(item as syn::DeriveInput);
1788 let arguments = host::options(args.into());
1789 let plain = host::echo(&input);
1790 // It does NOT reach `equip`, and the one thing it needs that the four there do not is the whole
1791 // difference: a kind word re-writes the host, so the declaration is emitted in two forms and which
1792 // of them survives is a cargo gate's answer rather than this crate's.
1793 match resource::parse(&input, &arguments) {
1794 Ok(model) => {
1795 let carrying = model
1796 .carried_engine()
1797 .map_or_else(|| plain.clone(), |field| host::echo_carrying(&input, field));
1798 model.expand(&plain, &carrying).into()
1799 }
1800 // THE HOST IS EMITTED ANYWAY, for the reason every macro in this family states: an attribute
1801 // macro replaces the item it sits on, so a refusal that emitted only the error would delete the
1802 // type and bury its own message under every mention of it. The AUTHOR'S OWN host, never a
1803 // carrying one — a refused declaration may be refused precisely for the shape an injection
1804 // needs.
1805 Err(error) => {
1806 let refusal = error.to_compile_error();
1807 quote::quote!(#plain #refusal).into()
1808 }
1809 }
1810}
1811
1812/// Declare a SOURCE's COMMAND FACE — the vocabulary an application can say to one running origin.
1813///
1814/// A mutation node is a struct whose FIELDS are exchanges: one field is one thing an app can say,
1815/// its TYPE says what is sent and what comes back, and the words beside it say who runs it and how
1816/// it fails.
1817///
1818/// ```ignore
1819/// #[ingraph::mutation(graphql(async_graphql))]
1820/// pub struct WatchOps {
1821/// #[ingraph(rename = "addWatch",
1822/// handler(path = "crate::watch::add", async,
1823/// context(resource("crate::Catalog")),
1824/// error(type = "crate::AddWatchError", code = "ADD_FAILED")))]
1825/// add: (AddWatch, AddResponse),
1826///
1827/// #[ingraph(handler(path = "crate::watch::remove",
1828/// error(message = "that watch is not ours", code = "NOT_OURS")))]
1829/// remove: (RemoveWatch, RemoveResponse),
1830///
1831/// #[ingraph(handler = "crate::watch::reindex")] // the plain form
1832/// reindex: (Reindex, ()), // and the exchange that cannot fail
1833/// }
1834/// ```
1835///
1836/// A source mounts it with `mutation(node = "WatchOps")` on its own declaration and names it in its
1837/// `type Mutation` seat; `run` then receives `Control<WatchOpsCommand>` and matches on what was said.
1838///
1839/// # THE HANDLER IS DECLARED HERE, and never on the source
1840///
1841/// The ruling that shaped this word: *don't make the user write handlers on the source side — the
1842/// codegen can assemble them*. So behaviour is declared per FIELD, on the node, and the expansion is
1843/// what wires it up. The consequence is worth stating, because it removed a whole layer: with one
1844/// handler per field there is no way to answer the wrong command, so the runtime check that used to
1845/// look for that mismatch — and the vocabulary it needed — does not exist. The arm is unwritable
1846/// rather than guarded.
1847///
1848/// # THREE SIGNATURES, and the `error(…)` word picks which one
1849///
1850/// | `error(…)` | the handler's signature |
1851/// |---|---|
1852/// | `error(type = "E")` | `fn(…, req: Request) -> Result<Response, E>` |
1853/// | `error(message = "…")` | `fn(…, req: Request) -> Result<Response, ()>` |
1854/// | *omitted* | `fn(…, req: Request) -> Response` — no `Result` at all |
1855///
1856/// A CANNED failure's words live in the declaration: the message and the code are fixed at the word,
1857/// so the body reports only the POSITION it failed at, which is what `Err(())` is. A RICH one's words
1858/// live in the value. `async` on the handler makes each of the three a future; `context(…)` puts the
1859/// granted resources in front of the request, in the order they were written.
1860///
1861/// A `pub` canned handler earns `clippy::result_unit_err`, whose usual advice does not apply here —
1862/// an error type would be carrying words nothing renders — so such a handler is the one place an
1863/// `#[expect(clippy::result_unit_err, reason = "…")]` is the right answer.
1864///
1865/// A signature that does not match is `E0308`/`E0277` **at the handler path word**, which is the
1866/// token the author has to change: the emission binds the call to the exact type the words chose, at
1867/// that word's own span.
1868///
1869/// # THE WIRE FACE, and what a resolver does
1870///
1871/// `graphql(async_graphql)` publishes ONE ROOT FIELD PER EXCHANGE on a minted `<Node>Mutations`
1872/// unit, which a root folds. Each resolver:
1873///
1874/// 1. finds the source's command line — `ctx.data::<Commands<<Node as MutationNode>::Command>>()` —
1875/// FIRST, so a schema that never mounted this node refuses with nothing done;
1876/// 2. takes the granted resources out of `ctx.data::<Shared<R>>()`, in declaration order;
1877/// 3. calls the handler at its declared signature, awaiting it where the `async` word said to;
1878/// 4. renders a failure under the heading its declaration wrote — `"CODE: message"`, or the
1879/// sentence alone where no `code` was written;
1880/// 5. **forwards on success and only on success**, one way, as the command variant this node
1881/// minted. A change that failed has no living application, so nothing is sent — and a source that
1882/// has died answers `UNREACHABLE_SOURCE`, which is the one wire code that says the effect
1883/// HAPPENED and nothing applied it.
1884///
1885/// An exchange whose response is `()` publishes `Boolean!` and answers `true`.
1886///
1887/// An application installs the line the resolvers read with
1888/// `Schema::build(…).data(commands).data(Shared::new(catalog))`, the command type being its own key.
1889///
1890/// # Attributes
1891///
1892/// On the declaration:
1893///
1894/// - `graphql(async_graphql)` — the wires this node is dressed for.
1895/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s.
1896///
1897/// On a field, exactly two words — `rename` is the SKIN and `handler` is the BEHAVIOUR:
1898///
1899/// - `rename = "…"` — the word the wire publishes this exchange under.
1900/// - `handler = "path::to::fn"` — the plain form, for an exchange whose signature has nothing else
1901/// to say.
1902/// - `handler(path = "…" [, async] [, context(resource("…"), …)] [, error({type = "…" ⊻ message =
1903/// "…"} [, code = "…"])])` — the same word with the rest of the signature written out. `error`
1904/// lives INSIDE the block because the block IS the signature, and a failure with no handler to
1905/// belong to is a failure nothing renders.
1906///
1907/// # What it emits
1908///
1909/// | item | content |
1910/// |---|---|
1911/// | the author's host, echoed | unchanged but for the markers this macro consumed, with an annotated `#[allow(dead_code)]` over it |
1912/// | `<Node>Command` | one arm per field, carrying `<FieldTy as Mutation>::Request` |
1913/// | `impl MutationNode for <Node>` | the row a source's `Mutation` seat resolves through |
1914/// | `impl DeclaredMutation for <Node>` | the DECLARATION RECORD — `ALL_SYNC`, and one `Exchange` row per field carrying its handler path, its face, its grants, its rename and its failure |
1915/// | `<Node>Response` / `<Node>Error` | the assembled face's return vocabulary — one arm per exchange, and one per exchange that declared a FAILURE |
1916/// | `<Node>::handle_<node>` | the ASSEMBLED FACE: the node's total capability, in one function |
1917/// | `<Node>Mutations` and its `#[Object]` | only with a `graphql(…)` word — the unit a root folds, and one resolver per exchange |
1918///
1919/// The command arm's payload is a PROJECTION rather than a written type, which makes the emission
1920/// its own assert: a field whose type is not an exchange is `E0277` at the field, naming `Mutation`.
1921///
1922/// The record exists for the reason `Declared`'s does — two expansions cannot read each other's
1923/// tokens, so a source's own expansion reads this declaration through
1924/// `<WatchOps as DeclaredMutation>::…` and never through anything this macro wrote for itself.
1925///
1926/// The host's `#[allow(dead_code)]` is a ruling rather than a workaround: a node is a VOCABULARY and
1927/// not data, so nothing constructs one, and the lint would fire inside an expansion its author
1928/// cannot edit about a shape this macro asked them to write. The attribute carries its own reason.
1929///
1930/// # THE ASSEMBLED FACE, and the OR law that decides its mode
1931///
1932/// `handle_<node>` is the node's TOTAL CAPABILITY in one function: the grants its exchanges were
1933/// granted between them, a `<Node>Command`, and a `Result<<Node>Response, <Node>Error>`. It is
1934/// emitted whether or not the declaration wore a wire word, because it is the node's Rust surface
1935/// and a schema is the binding's.
1936///
1937/// **Its mode is the OR of its handlers'** — every handler blocking assembles a `fn`, and one
1938/// awaited handler makes the whole face an `async fn`. So a deployment controlling a wholly
1939/// synchronous node needs no runtime to say anything to it.
1940///
1941/// The WIRE does not come through it: a schema publishes one root field per exchange and calls that
1942/// exchange's own handler, which is what makes *answering the wrong command* unwritable. What the
1943/// face serves is every OTHER caller — a first-party transport, a test, the source-side party
1944/// holding a command off its own `Control` line.
1945///
1946/// Two consequences worth knowing before writing a declaration:
1947///
1948/// - **every handler path RESOLVES at the declaration.** The face calls them, so a node whose
1949/// `handler = "…"` names nothing is `E0425` where it is declared rather than wherever a binding
1950/// would first have called it.
1951/// - **a declared `error(type = "…")` must render.** Its arm of `<Node>Error` writes the `code`
1952/// heading and then lets the value say the rest, exactly as the wire's own renderer does — so a
1953/// rich failure owes a `Display` and nothing else. A failure whose own `Display` ALREADY carries
1954/// a heading should be declared WITHOUT a `code` word: two headings on one message is two
1955/// vocabularies with nothing telling a reader which is which.
1956///
1957/// # A REQUEST IS `Clone`, and only where a `graphql(…)` word is written
1958///
1959/// The wire's resolver forwards what was ASKED FOR to the living application and the handler takes
1960/// that same request BY VALUE, so it clones before calling. The bound therefore falls on every
1961/// request type of a node dressed for a wire, and on none of a node that is not — the assembled face
1962/// forwards nothing and clones nothing.
1963///
1964/// It costs a declaration almost nothing: a request is a wire input object, a bag of owned decoded
1965/// values with no borrow in it, and `Clone` is the nature of such a thing. The alternatives were
1966/// handing the handler a `&Request` (which contradicts the signature the three tiers are cast to)
1967/// and forwarding the RESPONSE (which contradicts what a command is — the living application
1968/// applies what was asked for). Both were rejected; the reasoning is on the wire emitter's module.
1969///
1970/// # Refusals
1971///
1972/// | written | refused because |
1973/// |---|---|
1974/// | a field with no `handler` | an exchange nobody runs is a command with no behaviour |
1975/// | `error(type = "…", message = "…")` | the two shapes are one word, and both leaves the return type undecided |
1976/// | `error(code = "…")` alone | a code is a HEADING, and this one heads nothing |
1977/// | `error()` | a field that can fail says how; one that cannot omits the word |
1978/// | `rename = Word` | the word names a SCHEMA field, and a schema name is not a Rust identifier |
1979/// | `context(…)` holding anything but `resource("…")` | a handler's context is the resources it was granted, and nothing else reaches one that way |
1980/// | a tuple struct, a unit struct or an enum | a field's NAME is the command's name, the arm it mints and the word the wire publishes |
1981/// | a generic parameter | the expansion mints ONE vocabulary for ONE type |
1982#[proc_macro_attribute]
1983pub fn mutation(
1984 args: proc_macro::TokenStream,
1985 item: proc_macro::TokenStream,
1986) -> proc_macro::TokenStream {
1987 equipped(args, item, host::echo_vocabulary, |input, arguments| {
1988 mutation::parse(input, arguments).as_ref().map_or_else(
1989 syn::Error::to_compile_error,
1990 ingraph_codegen::mutation::MutationModel::emit,
1991 )
1992 })
1993}
1994
1995/// Declare an ORIGIN — and hold its `mutation` word and its `type Mutation` seat to each other.
1996///
1997/// ```ignore
1998/// #[ingraph::source(async, mutation(node = "WatchOps"))]
1999/// pub struct Watch { roots: Vec<PathBuf> }
2000///
2001/// impl AsyncSource for Watch {
2002/// type Options = WatchOptions;
2003/// type Yield = Change;
2004/// type Mutation = WatchOps; // the word above, as a TYPE
2005/// type Error = WatchError;
2006/// async fn build(ctx: &Resources, options: WatchOptions) -> Result<Self, Self::Error> { … }
2007/// async fn run(self, ctx: Context, feed: Feed<Change>, control: Control<WatchOpsCommand>)
2008/// -> Result<Fin, Self::Error> { … }
2009/// }
2010/// ```
2011///
2012/// # THE DOUBLE ENTRY, which is the whole of what this word emits
2013///
2014/// A source's command face is written twice — once as a WORD, which is what a declaration says, and
2015/// once as a TYPE, which is what a [`Control`](../ingraph/struct.Control.html) line resolves through
2016/// — and neither spelling can be dropped: an attribute macro cannot write somebody else's `impl`,
2017/// and an `impl` is not a declaration. So this expansion writes the JOIN between them, and the join
2018/// is checked in BOTH directions:
2019///
2020/// | written | what happens |
2021/// |---|---|
2022/// | the word and the matching seat | it compiles |
2023/// | the word, and a seat naming something else (`()` included) | `E0271` at the WORD |
2024/// | no word, and a seat naming a node | `E0271` at the DECLARATION |
2025/// | no word, and `type Mutation = ()` | it compiles |
2026///
2027/// The third row is what a single-entry design would have lost: a source that mounted a node and
2028/// forgot to say so would publish no wire face, and a missing word looks exactly like a source
2029/// nobody controls.
2030///
2031/// # ONE command face per source
2032///
2033/// `mutation(…)` may be written at most once. A second one is refused with the sentence that names
2034/// the day it arrives — more words go in the NODE, and the mount widens when two vocabularies truly
2035/// diverge — because the wire face is per-FIELD, so N nodes and one node with N fields are the same
2036/// schema and the same author experience.
2037///
2038/// # Attributes
2039///
2040/// - `async` — this origin's body is awaited, so the bound names
2041/// [`AsyncSource`](../ingraph/trait.AsyncSource.html). Without it the bound names
2042/// [`Source`](../ingraph/trait.Source.html), the blocking face, per the dual-mode law's
2043/// word-selects-face rule.
2044/// - `mutation(node = "path::to::Node")` — the mutation node whose fields are this origin's command
2045/// vocabulary. Omitted for an origin nobody controls, whose seat is `()`.
2046/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s.
2047///
2048/// # What it emits
2049///
2050/// | item | content |
2051/// |---|---|
2052/// | the author's host, echoed | unchanged but for the markers this macro consumed |
2053/// | one anonymous `const` | the double entry — a bound over the declared type naming the mounted node, spent at the word |
2054/// | `impl DeclaredOrigin` | the RECORD a launch walk mounts it through — its face as a TYPE, and the node it controls as a word |
2055///
2056/// And nothing else. No command enum, no `MutationNode` row, no resolver: those are the NODE's own
2057/// declaration's, and this one has never seen its tokens.
2058///
2059/// # THE RECORD is what makes a mount declaration-driven
2060///
2061/// A launch walk that mounts an origin sees a TYPE and nothing else, so the record is how the
2062/// `async` word reaches it: `type Mode` selects the driver, and one door then serves both faces —
2063/// `Blueprint::origin::<Watch>("watch")` enters the arrangement and
2064/// `Ignition::origin_declared::<Watch>(…)` puts it on an engine, neither of them naming a face. An
2065/// origin that publishes to nobody is refused before anything ignites, by the pure-leaf rule that
2066/// was already there.
2067///
2068/// It is a PUBLIC seam: a hand-written origin writes the impl in three lines and is mounted the same
2069/// way. Nothing here is obliged to have come through this macro.
2070///
2071/// # ONE OPTIONS SEAT, and it is the face's own
2072///
2073/// The `type Options` above is what a deployment's `[watch]` section holds, and
2074/// `Creation::origin` is what hands it to `build`. There is no second seat to keep in step: an
2075/// origin used to be constructed through
2076/// [`AsyncConstructor`](../ingraph/trait.AsyncConstructor.html) because `build` signed a
2077/// `Context` the create stage has not got, and the window moved to
2078/// [`Resources`](../ingraph/struct.Resources.html) so the face's own door could be the one the
2079/// framework calls.
2080///
2081/// # Refusals
2082///
2083/// | written | refused because |
2084/// |---|---|
2085/// | a second `mutation(…)` | one command face per source — the mount widens the day two vocabularies diverge |
2086/// | `mutation`, `mutation()` or a block with no `node` | an origin nobody controls omits the word; one that is controlled names the node |
2087/// | `mutation(node = Node)` | the word names a TYPE this declaration cannot resolve, so it is quoted |
2088/// | a second `async` | one origin wears one face |
2089/// | a generic parameter | the expansion states ONE bound over ONE origin |
2090#[proc_macro_attribute]
2091pub fn source(
2092 args: proc_macro::TokenStream,
2093 item: proc_macro::TokenStream,
2094) -> proc_macro::TokenStream {
2095 equip(args, item, |input, arguments| {
2096 source::parse(input, arguments).as_ref().map_or_else(
2097 syn::Error::to_compile_error,
2098 ingraph_codegen::source::SourceModel::emit,
2099 )
2100 })
2101}
2102
2103/// Declare a QUESTION PIPELINE — the steps between what a person asked and what an index can be
2104/// asked with.
2105///
2106/// ```ignore
2107/// #[ingraph::tower(question(type = "String"))]
2108/// pub struct ClipText {
2109/// #[ingraph(answer = "Vec<String>")] tokenize: Tokenize,
2110/// #[ingraph(answer = "Vec<f32>", async)] encode: ClipTextTower,
2111/// }
2112/// ```
2113///
2114/// # FIELDS ARE STEPS
2115///
2116/// A field's NAME is the step's name and its TYPE is the server that runs it, in the order the
2117/// fields are written. Nothing here mints a name and nothing overrides one — one name serves the
2118/// steps struct, the tower's options, the arm of the refusal sum and the schema row alike.
2119///
2120/// # THE TWO OVERRIDE WORDS ARE OMISSIBLE
2121///
2122/// A server may declare, ONCE, what it is canonically asked and what it canonically answers:
2123///
2124/// ```ignore
2125/// impl DefaultServe for Tokenize {
2126/// type Question = String;
2127/// type Answer = Vec<String>;
2128/// }
2129///
2130/// #[ingraph::tower] // asked what `Tokenize` is canonically asked
2131/// pub struct Words {
2132/// tokenize: Tokenize, // answers what `Tokenize` canonically answers
2133/// }
2134/// ```
2135///
2136/// The tower's `question(type = "…")` and a step's `answer = "…"` are OVERRIDE words: written, they
2137/// name the type here; omitted, the step's own canonical line is projected in their place. The two
2138/// are independent, so a tower may write one and omit the other, and a tower may write the word on
2139/// the steps that need it and omit it on the steps that do not.
2140///
2141/// A step whose type has no canonical line to read an omitted word off is `E0277` at that step's
2142/// field, and `DefaultServe`'s own note names both roads back. Selection never comes from inference:
2143/// `DefaultServe` takes no parameter, so a step answering several kinds of question is exactly as
2144/// unambiguous omitted as written.
2145///
2146/// # THE HEAD PIN — `answer = "…"` at the TOWER, which decides nothing
2147///
2148/// ```ignore
2149/// #[ingraph::tower(answer = "Vec<f32>")] // ← what this tower is FOR, said at its head
2150/// pub struct ClipText {
2151/// tokenize: Tokenize,
2152/// encode: Encode,
2153/// }
2154/// ```
2155///
2156/// A tower answers what its LAST STEP answers, and this word cannot make it answer anything else. It
2157/// is a DOUBLE ENTRY rather than a third override: the word writes an INTENT down, the chain DERIVES
2158/// an answer, and the expansion demands that the two agree. A tower whose last step moved is `E0271`
2159/// **with the caret on the type the word named**, and the note beside it points at the step's own
2160/// `answer` — so one refusal names both halves.
2161///
2162/// It is OPTIONAL and costs an omitting declaration nothing — no bound, no obligation, not one token
2163/// of expansion. What writing it buys is WHERE a drift is reported: a chain whose end moved is
2164/// caught anyway, by whatever bound named the answer it expected, but that refusal lands wherever
2165/// the tower was BOUND and this one lands at the tower. Both spellings are taken, exactly as the
2166/// question's are: `answer = "…"` and `answer(type = "…")`.
2167///
2168/// # THE CHAIN IS DERIVED, and it is a compile-time theorem
2169///
2170/// One question is written and one answer per step; every question after the first IS the answer
2171/// before it, and the last step's answer is the tower's. So an author never states an adjacency,
2172/// and what the expansion does is DEMAND each hop:
2173///
2174/// ```ignore
2175/// impl SearchTower for ClipText
2176/// where
2177/// Tokenize: Serves<String, Vec<String>>,
2178/// ClipTextTower: AsyncServes<Vec<String>, Vec<f32>>,
2179/// { … }
2180/// ```
2181///
2182/// A step that does not serve the question it is handed is `E0277` **at the impl, with the caret on
2183/// that step's own field**. `cargo check` green is the chain proven connected.
2184///
2185/// # `async` PER STEP, which is what makes a MIXED tower expressible
2186///
2187/// A bare step demands the blocking face; `#[ingraph(async)]` demands the awaited one. So a
2188/// blocking tokenizer feeding an awaited encoder is one tower. Words CHOOSE and bounds PROVE:
2189/// nothing here checks that a step's body is really awaited, and a word that lied names a face the
2190/// type does not wear, which is the same `E0277` on the same field.
2191///
2192/// # THE WALK, and the OR law over its steps
2193///
2194/// Beside the impl, one inherent function:
2195///
2196/// ```ignore
2197/// ClipText::walk(question, &mut tokenize, &mut encode, options).await
2198/// ```
2199///
2200/// The question first, then one `&mut` borrow per step in declaration order, then the tower's own
2201/// options seat. Its FACE is the OR of the steps' — every step blocking walks in a blocking
2202/// function, one awaited step makes the whole walk awaited — which is the mutation node's assembled
2203/// face one layer over. Steps are parameters rather than `&mut self` so a deployment may hold them
2204/// anywhere; a caller holding the struct passes disjoint field borrows.
2205///
2206/// The walk takes the DECLARATION's visibility, and the steps take this family's own convention: a
2207/// field written with no visibility is stamped `pub(crate)`. A tower meant to be walked from
2208/// outside its crate therefore writes `pub` on the steps a caller has to borrow — the same
2209/// one-directional rule every node macro carries, stated here because this is the family whose
2210/// fields a CALLER names.
2211///
2212/// A `pub` tower also publishes its steps' TYPES, and that is a hard error rather than a lint: the
2213/// refusal sum below takes the declaration's visibility and its arms name the step types, so a
2214/// `pub` tower over a private step is `E0446`. Declare the tower at the visibility its steps have.
2215///
2216/// Every hop is served under `None`, so each step runs at its own floor.
2217///
2218/// # THE REFUSAL SUM
2219///
2220/// Beside the walk, one enum: `<Tower>Error`, an arm per step named after the step's own field and
2221/// carrying that step's own error — `ClipTextError::Tokenize(<Tokenize as Serves<…>>::Error)`. A
2222/// projection rather than an erasure, so a step keeps the error type it declared and a caller that
2223/// matched an arm holds it. `Display` names the step that refused; `source` reaches the cause, which
2224/// is the ONE demand this makes of a step's error and lands at that step's field.
2225///
2226/// # Refusals
2227///
2228/// | written | refused because |
2229/// |---|---|
2230/// | `question` naming no type | a word that decided nothing; OMITTING it is the canonical road |
2231/// | `answer` at the tower naming no type | the same, for the head pin: omit it where the tower's answer is simply its chain's |
2232/// | a second `question` or a second head `answer` | one tower has one of each end, and the sugar and the full form fill one seat |
2233/// | a struct with no field | a tower's fields ARE its steps |
2234/// | a tuple struct, a unit struct | a step's name is its field's, and a positional field has none |
2235/// | an enum or a union | variants are a choice between things rather than a chain of them |
2236/// | a generic parameter | the expansion states ONE chain over ONE declaration |
2237/// | `async` carrying anything | it names a face; the body is the step author's |
2238/// | `arm(…)` / `chain(…)` | the RETIRED inline form — bindings live at the search recipe now |
2239/// | `name = "…"` on a step | the retired form's word; the field already is the name |
2240/// | `options` on a step | the seat is the SERVER's own `Serve::Options`, declared once by the type |
2241/// | `expand` naming no type | the framework ships no expander, so there is no bare word to mean |
2242/// | `route = <router>` | the crossing names TWO things; the sugar holds one half of an equality |
2243/// | `route(…)` naming no `router` or no `slot` | both halves of a wiring, or neither |
2244/// | a bare `router` this framework does not ship | MINT BARE, REFER QUOTED — the escape is a quoted path |
2245/// | both fan words on one step | a step opens ONE segment; the two stages are two steps |
2246/// | a second `expand`, or a second `route`, in one tower | one widening family and one lane fan, which is what the fold has a law for |
2247/// | `route` before `expand` | ② runs before ④; a widening after a routing would widen a probe |
2248/// | `async` beside a fan word | a segment's field holds the SEGMENT'S SEAT; a seat has no `serve` call for a face to be about |
2249///
2250/// # THE AMENDMENT, and what a fan-carrying tower walks
2251///
2252/// A tower may contain FANNING SEGMENTS — expansion × lane routing — and every fan folds before the
2253/// tower's mouth, so the outer contract stays 1 → 1. The two words that open one are `expand` and
2254/// `route`, and the walk they emit is:
2255///
2256/// ```text
2257/// [ the steps before the fan ] ─▶ ② widen ─▶ for each ARM: ④ route ─▶ for each LANE: [ the tail ]
2258/// │
2259/// ONE ranked answer ◀── the fold ◀────┘
2260/// ```
2261///
2262/// **A FAN STEP'S FIELD HOLDS THE SEGMENT'S SEAT**, which is fields-are-steps at the two positions
2263/// where the thing mounted is not a server: a widening step holds an `Expansion<Q>` and a crossing
2264/// step holds a `LaneFan<Router>`, both assembled by the deployment — the declaration's `expand`
2265/// word names the expander the deployment DEFAULTS to and its `route` word names the wiring the
2266/// compiler checks. So neither position is a `Serves` hop, a widening has no arm in the refusal sum
2267/// (it cannot fail), and a crossing's arm carries the fan's own `FanError`.
2268///
2269/// **THE WALK OF A WIDENING TOWER IS AWAITED**, whatever its steps say: the expand seam's call face
2270/// is the awaited one, and a blocking expander reaches it through the lift bridge.
2271///
2272/// **THE ANSWER IS THE FUSED LIST** — `Vec<Fused<Root, Evidence>>`, one value, the two parameters
2273/// projected off the tail's own answer through `RankedStream`. The two fold laws are structural: a
2274/// cell's coefficient is `arm × lane` MULTIPLIED at the only door into a cell, and one question's
2275/// expansion family is ONE WITNESS, deduplicated on full `(root, evidence)` identity with the better
2276/// rank surviving.
2277///
2278/// **A tower that opens no segment is untouched by all of it** and expands exactly as it did before
2279/// the amendment, token for token.
2280#[proc_macro_attribute]
2281pub fn tower(
2282 args: proc_macro::TokenStream,
2283 item: proc_macro::TokenStream,
2284) -> proc_macro::TokenStream {
2285 equip(args, item, |input, arguments| {
2286 tower::parse(input, arguments)
2287 .as_ref()
2288 .map_or_else(syn::Error::to_compile_error, |model| {
2289 ingraph_codegen::tower::TowerModel::emit(model)
2290 })
2291 })
2292}
2293
2294/// Declare a SEARCH RECIPE — the members one question is asked across, and the towers that turn it
2295/// into what each of them can be asked with.
2296///
2297/// ```ignore
2298/// #[ingraph::search(shared(text(type = "String")), dedup(hash), limit = 20)]
2299/// pub struct TravelSearch {
2300/// #[ingraph(weight = 1.0, depth = 50, tower(zh(type = "crate::ZhQuery", shared)))]
2301/// subs: Subs,
2302/// #[ingraph(weight = 2.0, depth = 100,
2303/// tower(text(type = "crate::ClipText", shared, floor = "crate::floors::SEM_TEXT")),
2304/// tower(image(type = "crate::ClipImage", shared)))]
2305/// shots: Shots,
2306/// }
2307/// ```
2308///
2309/// # FIELDS ARE MEMBERS
2310///
2311/// A field's NAME is the member's name and its TYPE is the index it reads, in the order they are
2312/// written. So a recipe LISTS what it fuses, and every door it mints has exactly that arity —
2313/// nothing here counts words to decide how many members there are, and nothing trims one away.
2314///
2315/// SEVERAL RECIPES over one set of members are ordinary rather than a special case: two
2316/// declarations naming the same fields at different weights are two semantic wire names, and
2317/// neither knows about the other.
2318///
2319/// # WHAT IT MINTS — the fusion unit, at module scope
2320///
2321/// ```text
2322/// TravelSearchSubsTowerOptions { zh } one member's bound towers
2323/// TravelSearchShotsTowerOptions { text, image }
2324/// TravelSearchFuseOptions { fusion, subs, shots, subs_towers, shots_towers }
2325/// TravelSearchFuseQuestion { question, subs, shots }
2326/// TravelSearchFusedEvidence<…> one variant per member, holding THAT member's own evidence
2327/// TravelSearchFusedError<…> one variant per member, holding THAT member's own refusal
2328/// TravelSearch::fuse(…) the door
2329/// impl DeclaredSearch for TravelSearch
2330/// ```
2331///
2332/// This is #290's machinery, which a GRAPH ROOT minted until the ONE HOME move: the same packages,
2333/// the same reciprocal-rank fold, the same nested evidence. What did not come with it is the
2334/// word-count door law and the modality trims — a recipe LISTS its members, so there is one door of
2335/// exactly this arity and nothing for a trim to select. The root keeps `fuse` as its INDEX TIER word
2336/// and mints no fused door at all.
2337///
2338/// The DECLARED numbers are what a request that named none runs: `weight` is the coefficient an
2339/// unconfigured member takes in the fold, and `depth` is the ceiling its own ask is capped at. The
2340/// declared `limit` rides `DeclaredSearch::LIMIT` rather than the door, which takes the caller's
2341/// budget — the framework's own answer to *how many* is a codegen constant that becomes an SDL
2342/// literal, and no door, seam or fold reads it.
2343///
2344/// # THE MEMBER WORDS — declared defaults, and the tier they sit in
2345///
2346/// `weight = 1.0` is this word's first declaration-side home: it is the member's coefficient in the
2347/// fold, and an omitting member takes the multiplicative identity. `depth = N` is how deep that
2348/// member's route is asked. `floor = "…"` is the const its read is floored at.
2349///
2350/// Every one of them is a PREFERENCE and every one is omissible. The order that resolves them is
2351/// request > this recipe > the election's own field > its container > the framework's own number, so
2352/// an omitted word is a recipe letting the declaration below it answer rather than a recipe with an
2353/// opinion it did not write down.
2354///
2355/// # `tower(<arm>(…))` — a member's ARMS
2356///
2357/// An arm binds one tower to one member and is named by the word that opens it. That name is the
2358/// variant it mints in the member's own question, and it is also the seat it may read: two MEMBERS
2359/// may each carry an arm called `text`, which is what lets one broadcast reach both; one member may
2360/// not carry two.
2361///
2362/// The tower is named as a TYPE PATH and nothing about it is read here. What it is asked, what it
2363/// answers, whether its walk is awaited and what its steps seat are all resolved through
2364/// `SearchTower` and `DeclaredTower`, where the compiler can see them.
2365///
2366/// # `shared` — ONE QUESTION, asked once
2367///
2368/// The head's `shared(<seat>(type = "…"))` declares the seats a caller fills once for the whole
2369/// recipe; an arm's own `shared` says it reads one. A seat feeds the arms that share its NAME, and a
2370/// recipe declaring exactly one seat feeds every `shared` arm from it — the sole-default law the
2371/// resource axis already states. An arm that writes no `shared` is asked its own question.
2372///
2373/// The word also chooses HOW the seat crosses into that arm's question: bare `shared` demands the
2374/// total conversion, `shared(try)` the fallible one, and `shared(with = "…")` /
2375/// `shared(try_with = "…")` name a function of the author's — hooks beat traits, an application that
2376/// owns neither type being unable to write the impl at all.
2377///
2378/// # THE FLOORS ARE CONSTS, and a per-leg one has no home here
2379///
2380/// `floor = "path::to::CONST"` at either grain, never a literal: a floor is a value in the ENGINE's
2381/// own currency, which is an open type this framework never sees, so there is nothing here for a
2382/// number to be parsed into.
2383///
2384/// A member's LEGS are its own declaration's — their names, their engines and their currencies are
2385/// written there — so `floor(…)` naming one is refused. A recipe floors what it can name; a leg
2386/// floor is a request's, where the leg is already addressed.
2387///
2388/// # Refusals
2389///
2390/// | written | refused because |
2391/// |---|---|
2392/// | a seat, an arm, or any word declared twice | one seat is one question, one arm is one tower, one word is one value |
2393/// | `shared(…)` twice at the head | two blocks would be two places for one seat to be named |
2394/// | a seat or an arm naming no type | a word that decided nothing; a member that binds none writes no `tower(…)` |
2395/// | `shared` on an arm the recipe has no seat for | the broadcast is the head's, and an unmatched arm has no sole seat to fall back to |
2396/// | two arms of one name on one member | an arm's name is the variant it mints in that member's question |
2397/// | a struct with no field | a recipe's fields ARE its members |
2398/// | a tuple struct, a unit struct | a member's name is its field's, and a positional field has none |
2399/// | an enum or a union | variants are a choice between things rather than a list of them |
2400/// | a generic parameter | the expansion binds ONE set of members over ONE declaration |
2401/// | `floor` as a literal | an open currency owes no parsing |
2402/// | `floor(…)` as a block | the two-clock wall: a recipe cannot name a member's interior legs |
2403/// | `weight` as an integer, or as a string | a coefficient is a plain decimal, one shape for one number |
2404/// | `weight` with no finite value | it MULTIPLIES every term, so an infinity makes the fold's order an accident |
2405/// | `depth` at the head | it is a member's number; the head's is `limit` |
2406/// | `limit = 0` / `depth = 0` | an answer with no rows is what a caller who wants nothing does not ask for |
2407/// | a `dedup` word this framework has no join for | the mechanism vocabulary is the framework's |
2408#[proc_macro_attribute]
2409pub fn search(
2410 args: proc_macro::TokenStream,
2411 item: proc_macro::TokenStream,
2412) -> proc_macro::TokenStream {
2413 equip(args, item, |input, arguments| {
2414 search::parse(input, arguments).as_ref().map_or_else(
2415 syn::Error::to_compile_error,
2416 ingraph_codegen::search::SearchModel::emit,
2417 )
2418 })
2419}
2420
2421/// Dress an application's own failure type to RENDER — a declared exchange's error, given a code and
2422/// a sentence.
2423///
2424/// ```ignore
2425/// #[ingraph::mutation_error]
2426/// pub enum WatchError {
2427/// #[ingraph(code = "NOT_A_DIRECTORY", error = "`{0}` is not a directory")]
2428/// NotADirectory(PathBuf),
2429/// #[ingraph(code = "ALREADY_WATCHED", error = "{root} is already watched, as watch {id}")]
2430/// AlreadyWatched { root: String, id: u64 },
2431/// }
2432/// ```
2433///
2434/// # A CONVENIENCE AND NOT A SEAM
2435///
2436/// A hand-written error is exactly as legal. Nothing in this framework asks a failure type for more
2437/// than a [`Display`](core::fmt::Display) — that is all `error(type = "…")`'s rendering spends, and
2438/// all the assembled face's error sum spends — so an error that implements it by hand, or through
2439/// somebody else's derive, is a first-class declared failure. What this word buys is the CODE
2440/// DISCIPLINE, which nothing checks for a hand-written one.
2441///
2442/// # Attributes, per VARIANT, and neither is optional
2443///
2444/// - `code = "SCREAMING_SNAKE_CASE"` — what a client MATCHES ON, and the head of everything this
2445/// variant renders as.
2446/// - `error = "…"` — what a person READS. A format string over the variant's own fields: `{0}` and
2447/// `{}` by position, `{name}` by name, `{{` for a literal brace.
2448///
2449/// # What it emits
2450///
2451/// | item | content |
2452/// |---|---|
2453/// | the author's enum, echoed | unchanged but for the markers this macro consumed |
2454/// | `impl Display` | `"CODE: message"`, one arm per variant, from one literal apiece |
2455/// | `impl core::error::Error` | the defaulted `source`, this macro having no way to know which field is a cause |
2456/// | `<Error>::code` | the word this variant is recognised by |
2457///
2458/// The declaration is otherwise untouched: its arms, its payloads, its derives, its visibility.
2459///
2460/// # THE ENUM OWES A `Debug`, and it is the author's to write
2461///
2462/// [`core::error::Error`] has `Debug` as a supertrait, so a declaration wears `#[derive(Debug)]` —
2463/// or an impl of its own. Nothing here emits one, and the omission is the point: a `Debug` this
2464/// macro wrote would collide with the derive most error types already carry (`E0119`), and choosing
2465/// between them by scanning attributes would make the emission depend on which way an author
2466/// happened to spell it. What an author sees if they forget is rustc naming `Debug` under
2467/// *required by a bound in `Error`*, at the enum.
2468///
2469/// A field the template RENDERS owes a [`Display`](core::fmt::Display); one it never names owes
2470/// nothing at all, being bound as `_`.
2471///
2472/// # THE CODE HEADS THE MESSAGE, so a declaration does not head it again
2473///
2474/// An exchange declaring `error(type = "…", code = "…")` puts its own heading in front of whatever
2475/// the value renders as. An error minted here already carries one, so such an exchange writes
2476/// `error(type = "…")` and NO `code` word — two headings on one message is two vocabularies with
2477/// nothing telling a reader which is which.
2478///
2479/// # Refusals
2480///
2481/// | written | refused because |
2482/// |---|---|
2483/// | a variant with no `code` | the code is what a client matches on, and a variant without one is a refusal it cannot tell from its neighbour |
2484/// | a variant with no `error` | a code with no message under it says nothing to a person |
2485/// | `code = "notScreaming"` | a code is a machine-read constant, in GraphQL's own convention for one |
2486/// | two variants under one `code` | a vocabulary is a contract only while it is injective |
2487/// | a `code` that is one of the framework's own | a client matching it is asking about a refusal this framework raises |
2488/// | `{name}` naming no field, or `{7}` past the last one | the template reads the variant's own fields |
2489/// | a struct or a union | an error's VARIANTS are the ways it can fail |
2490/// | a generic parameter | the expansion writes ONE `Display` over ONE type |
2491/// | any argument on the attribute itself | every word is written on a variant |
2492#[proc_macro_attribute]
2493pub fn mutation_error(
2494 args: proc_macro::TokenStream,
2495 item: proc_macro::TokenStream,
2496) -> proc_macro::TokenStream {
2497 equip(args, item, |input, arguments| {
2498 error::parse(input, arguments, ErrorRoad::Mutation)
2499 .as_ref()
2500 .map_or_else(syn::Error::to_compile_error, ErrorModel::emit)
2501 })
2502}
2503
2504/// [`mutation_error`] for the READ path — the same skeleton, over an author's own query failure.
2505///
2506/// ```ignore
2507/// #[ingraph::query_error]
2508/// pub enum LookupError {
2509/// #[ingraph(code = "NO_SUCH_SHELF", error = "there is no shelf called `{0}`")]
2510/// NoSuchShelf(String),
2511/// }
2512/// ```
2513///
2514/// # TWO WORDS FOR ONE EMISSION, and that is deliberate
2515///
2516/// The items are identical, and deduplicating the two macros into one would delete the only thing a
2517/// declaration says by choosing between them: which half of the line this failure belongs to. A
2518/// reader of `#[ingraph::query_error]` knows they are looking at something a read path can raise
2519/// without going to find out. And the day the two roads want different faces — a `ToErrorCode` row
2520/// on one of them, a wire attachment on the other — the word is already written and no declaration
2521/// has to change.
2522///
2523/// Every attribute, every emitted item and every refusal is [`mutation_error`]'s; see it for all of
2524/// them.
2525#[proc_macro_attribute]
2526pub fn query_error(
2527 args: proc_macro::TokenStream,
2528 item: proc_macro::TokenStream,
2529) -> proc_macro::TokenStream {
2530 equip(args, item, |input, arguments| {
2531 error::parse(input, arguments, ErrorRoad::Query)
2532 .as_ref()
2533 .map_or_else(syn::Error::to_compile_error, ErrorModel::emit)
2534 })
2535}
2536
2537/// The one body every macro that EQUIPS a declaration has: echo the host, parse, then emit.
2538///
2539/// The words that reach it — the source, the tower, the search recipe, the two error roads, the
2540/// interface, the graph root and the mutation node — equip something the author wrote and mint no
2541/// field, so what varies between them is only which pass runs and which model emits. TWO member
2542/// sets left it rather than joined it: the vocabulary and the union rewrite nothing, so each is a
2543/// derive and neither has a host to echo. `node` is separate because it carries a
2544/// [`NodeKind`] the others have no use for, and `resource` is separate because a BUILTIN kind word
2545/// mints a field and puts the declaration behind a cargo gate: it emits the host in two forms,
2546/// which is one form more than this body has anywhere to put.
2547///
2548/// THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, for the reason `node` states: an
2549/// attribute macro replaces the item it sits on, so a refusal that emitted only the error would
2550/// delete the type and bury its own message under every mention of it.
2551fn equip(
2552 args: proc_macro::TokenStream,
2553 item: proc_macro::TokenStream,
2554 expand: impl FnOnce(&syn::DeriveInput, &[syn::Attribute]) -> proc_macro2::TokenStream,
2555) -> proc_macro::TokenStream {
2556 equipped(args, item, host::echo, expand)
2557}
2558
2559/// [`equip`] with the ECHO handed in — for the one declaration whose host is not echoed plainly.
2560///
2561/// A mutation node's is not: it is a VOCABULARY rather than data, so nothing constructs one and
2562/// rustc's *never constructed* would be reported inside an expansion its author cannot edit. See
2563/// [`host::echo_vocabulary`], which carries the reason in the attribute it writes.
2564///
2565/// A parameter rather than a second copy of this body, because the body IS the shape: echo, parse,
2566/// emit, in that order, with the host emitted whether or not the declaration is accepted.
2567fn equipped(
2568 args: proc_macro::TokenStream,
2569 item: proc_macro::TokenStream,
2570 echo: fn(&syn::DeriveInput) -> proc_macro2::TokenStream,
2571 expand: impl FnOnce(&syn::DeriveInput, &[syn::Attribute]) -> proc_macro2::TokenStream,
2572) -> proc_macro::TokenStream {
2573 let input = syn::parse_macro_input!(item as syn::DeriveInput);
2574 let arguments = host::options(args.into());
2575 let host = echo(&input);
2576 let expansion = expand(&input, &arguments);
2577 quote::quote!(#host #expansion).into()
2578}
2579
2580/// The one body every node macro has: echo the host, parse under this KIND, then emit.
2581///
2582/// The kind is the only thing that differs between them, which is the split's whole content — one
2583/// grammar, one emitter, and a word deciding which storage block the declaration may write and
2584/// whether the emission mints the one-storage marker.
2585///
2586/// THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, and that is not a detail. An
2587/// attribute macro replaces the item it sits on, so a refusal that emitted only the error would
2588/// delete the type — and every mention of it elsewhere in the crate would become a second error
2589/// burying the first. The refusal rides beside the type it is about.
2590fn node(
2591 args: proc_macro::TokenStream,
2592 item: proc_macro::TokenStream,
2593 kind: ingraph_codegen::model::NodeKind,
2594) -> proc_macro::TokenStream {
2595 let input = syn::parse_macro_input!(item as syn::DeriveInput);
2596 let options = host::options(args.into());
2597 let parsed = parse::parse(&input, &options, kind);
2598 // A FAN-IN carries its ancestry in a field the emitter mints, for `derived`'s reason one tier
2599 // over: which columns a row's ancestry has depends on which upstream produced it, so there is no
2600 // set of columns for the declaration to write. A refused declaration is echoed WITHOUT it, and
2601 // for the same honest reason — the field's type is the lineage the parse would have named.
2602 // A REWRITE replaces the item outright — see [`host::transparent`] — and only an ACCEPTED one
2603 // does. A refusal echoes the author's own struct back unchanged, for the journal's reason: the
2604 // wrapper is built from a path the refusal may be about, and emitting a wrapper over a type that
2605 // resolves to nothing would bury the sentence that named the real mistake.
2606 let host = match parsed.as_ref().ok() {
2607 Some(model) if model.remote.is_some() => {
2608 host::transparent(&input, model.remote.as_ref().expect("a rewrite's own path"))
2609 }
2610 accepted => match accepted.and_then(RecordModel::fanned_lineage) {
2611 Some(field) => host::echo_carrying(&input, field),
2612 None => host::echo(&input),
2613 },
2614 };
2615 let expansion = parsed
2616 .as_ref()
2617 .map_or_else(syn::Error::to_compile_error, RecordModel::emit);
2618 quote::quote!(#host #expansion).into()
2619}
2620
2621/// Declare a FLAGS SET — a closed vocabulary of BITS a column holds a SUBSET of.
2622///
2623/// The vocabulary kind's sister, and the difference is the arity of an answer: an enum column holds
2624/// ONE of the names and a flags column holds any combination of them. So this word buys the
2625/// set-theoretic questions an enum has no way to ask — `hasAll`, `hasAny`, `hasNone`, a boolean per
2626/// declared flag — and the object face that publishes a value's dozen readings.
2627///
2628/// ```ignore
2629/// #[ingraph::flags(u32)]
2630/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2631/// pub enum TrackDisposition {
2632/// /// The default track for its kind.
2633/// Default = 0x1,
2634/// Forced = 0x2,
2635/// HearingImpaired = 1 << 2,
2636/// }
2637/// ```
2638///
2639/// # THIS WORD GOES ABOVE THE DERIVES
2640///
2641/// rustc expands the topmost attribute on an item first, and `derive` takes its turn in that order.
2642/// A derive written ABOVE this word expands against the MANIFEST — the enum that is about to stop
2643/// existing — and lands an impl matching on `TrackDisposition::Default`, a variant the expansion
2644/// replaced with a const. Written below, the derives are forwarded onto the type `bitflags!` mints
2645/// and expand against it.
2646///
2647/// The hazard cannot be detected here: a derive that already expanded is gone from the item's
2648/// attributes by the time this door runs, and is indistinguishable from one nobody wrote.
2649///
2650/// # An ATTRIBUTE, and a manifest that does not survive
2651///
2652/// The expansion is a `bitflags!` struct with `TrackDisposition::DEFAULT`, `::FORCED` and
2653/// `::HEARING_IMPAIRED` on it. The enum above is a MANIFEST: it is read for its names and values and
2654/// then replaced. That is why the word is an attribute rather than a derive — a derive may only
2655/// APPEND, and the type here is minted rather than kept — and it is why the manifest's own lints
2656/// never fire, since rustc never sees an enum to have an opinion about.
2657///
2658/// The manifest is an `enum` because a set of NAMES with VALUES is what an enum spells; a struct
2659/// body cannot hold `NAME = 0x1`, and putting the bits in the attribute would leave a bit's doc
2660/// comment nowhere to go.
2661///
2662/// # The bits are EXPLICIT, and that is this kind's one added refusal
2663///
2664/// A bit with no value is refused. An implicit numbering would come from a bit's POSITION, so
2665/// reordering the declaration — the most ordinary edit there is — would rewrite every stored row in
2666/// silence. The vocabulary kind can default a discriminant because a reordered enum still stores
2667/// what it stored; this one cannot.
2668///
2669/// A value is one bit, inside the declared width, declared once. Composite masks are refused in v1:
2670/// `bitflags` allows them and they would leave the per-flag fan with no single answer to *is it
2671/// set*.
2672///
2673/// # What it emits
2674///
2675/// | item | condition |
2676/// |---|---|
2677/// | the `bitflags!` type, carrying the author's own attributes | always |
2678/// | `FlagsValue`, giving the SDL name and the wire field per bit | always |
2679/// | `FlagsFilterMarker`, giving `FlagsFilter<Self>` | always |
2680/// | `DefaultMarker` / `DefaultVecMarker`, giving `FlagsMarker<Self>` | always |
2681/// | `CursorValue` over the BIT PATTERN, big-endian and width-checked | always |
2682/// | `ColumnKind` and `Assemble` | `ColumnKind` always, `Assemble` behind the SQL family |
2683/// | `sqlx::Type`/`Encode`/`Decode` and `Carrier` | per declared ∩ compiled-in backend |
2684/// | `ToGraphqlOutput` → `FlagsView<Self>`, `ToGraphqlInput` → `FlagsInput<Self>` | behind the BINDING gate |
2685///
2686/// The wire FACE is not among them, which is the biggest saving over the vocabulary kind: a flags
2687/// type's object and operand seats are generic in `ingraph` and read the bit table at runtime, so a
2688/// declaration names which seat each direction takes and the framework writes both.
2689///
2690/// # `graphql(rename = "…")` — WHAT A SCHEMA CALLS THIS SET
2691///
2692/// ```ignore
2693/// #[ingraph::flags(u32, graphql(rename = "TrackDisposition"))]
2694/// pub enum TrackDispositionFlags { Default = 0x1 }
2695/// ```
2696///
2697/// THREE published names come off one word — the object face takes it, the operand scalar is
2698/// `<it>Input` and the filter input object is `<it>Filter` — because all three are composed from the
2699/// single string `FlagsValue::GRAPHQL_NAME` carries. Defaults to the Rust name unraw'd.
2700///
2701/// EMISSION-ONLY: the `bitflags!` type keeps its own name, every bit keeps its `const`, and a stored
2702/// bit pattern has no word for this to move. A schema entity's word is not a Rust identifier, so
2703/// `rename = "type"` is writable here where a BIT's word is not — a bit becomes a `const` a caller
2704/// writes `Self::…` to reach.
2705///
2706/// # `remote = "…"` — MIRRORING a flags set another crate owns
2707///
2708/// ```ignore
2709/// #[ingraph::flags(u32, remote = "upstream::TrackDisposition")]
2710/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2711/// pub enum TrackDisposition {
2712/// Default = 0x1,
2713/// #[ingraph(rename = "HEARING_IMPAIRED")]
2714/// Hi = 1 << 2,
2715/// }
2716/// ```
2717///
2718/// The declaration RESTATES the upstream's bits — names AND numbers, both — and this word adds the
2719/// crossing: `From` in each direction, by `from_bits_retain`, so a bit the declaration never named
2720/// survives the round trip rather than being truncated away. That absorption is what keeps an
2721/// upstream release growing a bit from breaking a build; the strict doors are unmoved, so such a bit
2722/// is still refused at an operand, a stored column and a cursor.
2723///
2724/// **The restatement is checked at COMPILE TIME.** Every restated bit emits
2725/// `const _: () = assert!(Local::X.bits() == Remote::X.bits());`, so an upstream that RENUMBERS one
2726/// is an error at the bit that drifted rather than a mirror that quietly means something else.
2727/// `#[ingraph(rename = "…")]` names the upstream `const` in this mode — a mirror's words are its
2728/// own, a flags column storing its bit pattern — and a `const` the upstream has not got is `E0599`
2729/// at the token that claimed it.
2730///
2731/// A mirror is a flags set in every other respect: the same minted type, the same stored pattern,
2732/// the same two seats. A declaration naming no upstream is untouched by the axis, down to the token.
2733///
2734/// **Its own teeth:** an upstream that is not a `bitflags!` set (`E0277` on `bitflags::Flags`, at
2735/// the `remote = "…"` token); one whose bits are carried at another width (a named `E0277` there);
2736/// a `rename` that is not an identifier (refused at the door). An upstream bit this declaration does
2737/// not restate is NOT refused — it is absorbed on purpose, and what names it is a test-time pin over
2738/// `<Remote as bitflags::Flags>::FLAGS`, the upstream's own table.
2739///
2740/// # Teeth
2741///
2742/// A struct or union rather than an enum; an enum with no variants; a variant carrying data;
2743/// generics; a bit with no value, a value of `0`, a value past the declared width, a value setting
2744/// more than one bit, or an expression this door cannot evaluate; two bits on one value; two bits
2745/// spelling one word or one wire field; a `rename` that is not a GraphQL name, at the bit or at the
2746/// declaration; a width the carrier table does not hold; an `#[ingraph(…)]` left on the item where
2747/// the attribute's own parentheses are.
2748///
2749/// What is NOT refused here is the type's own `Copy`/`Eq`/`Debug`: those are asked by the bounds the
2750/// rows spend, and a declaration missing one gets `E0277` naming the trait at the type — where a
2751/// token-level check would refuse a correct program whose `impl Copy` is hand-written.
2752#[proc_macro_attribute]
2753pub fn flags(
2754 args: proc_macro::TokenStream,
2755 item: proc_macro::TokenStream,
2756) -> proc_macro::TokenStream {
2757 let input = syn::parse_macro_input!(item as syn::DeriveInput);
2758 let options = host::options(args.into());
2759 match flags::parse(&input, &options) {
2760 Ok(model) => model.emit().into(),
2761 // THE TYPE SURVIVES A REFUSAL, for the reason `derived` states: an attribute macro replaces the
2762 // item it sits on, so an expansion that emitted only the error would delete the author's type
2763 // and bury its own message under every mention of it.
2764 Err(refused) => {
2765 let refusal = refused.to_compile_error();
2766 let salvaged = flags::salvage(&input, &options);
2767 quote::quote! { #refusal #salvaged }.into()
2768 }
2769 }
2770}
2771
2772/// Equip a VOCABULARY — a unit-variant enum — with the WHOLE citizenship: the faces a column of it
2773/// needs, and the face a schema needs.
2774///
2775/// A vocabulary is a value, not a node: it owns no storage of its own, subscribes to nothing and
2776/// has no key. What it needs is what a COLUMN of it needs plus the words its faces spell it as, and
2777/// this derive writes exactly that.
2778///
2779/// ```ignore
2780/// #[derive(Debug, Clone, Copy, PartialEq, Eq, ingraph::Enum)]
2781/// #[repr(u8)]
2782/// pub enum Codec { H264, Vp9 }
2783///
2784/// #[ingraph::record(sqlite)]
2785/// pub struct Take {
2786/// #[ingraph(id)] id: i64,
2787/// #[ingraph(r#enum)] codec: Codec, // declares, filters and compares
2788/// }
2789/// ```
2790///
2791/// # ONE DOOR, and the second one was deleted
2792///
2793/// The storage citizenship and the wire face were two words — `#[ingraph::enumeration]` and a
2794/// `GraphqlEnum` derive — on the reading that they are two organs a declaration should be able to
2795/// take one of. They are ONE word now, and each defence of the split fell on re-derivation: schema
2796/// presence is REACHABILITY (an enum no wire type names never enters an SDL, so a second macro was
2797/// never the gatekeeper), unused storage impls on a pure-wire enum are harmless, and the wire face
2798/// sits behind the binding gate regardless. What the split cost was a silent composition-order trap,
2799/// two entry points onto one model, and one set of `#[ingraph(…)]` markers read by two grammars.
2800///
2801/// # A DERIVE, and the test every word in this family is put to
2802///
2803/// Most words here are attribute macros because those words REWRITE the item they sit on — a
2804/// derived index carries a field the declaration did not write, a record's fields take a visibility
2805/// stamp. This one rewrites nothing: it adds impls beside a type, which is what a derive is for.
2806/// Its helper attributes are INERT rather than consumed, which is the property that makes one set of
2807/// variant words readable without an ordering rule.
2808///
2809/// The test is the REWRITE and not the subject, which is why [`Union`](macro@union) followed:
2810/// equipping a payload-carrying enum somebody else declared is the same nothing-rewritten shape, so
2811/// it takes the same form. An INTERFACE does not follow them, and not for want of trying — see that
2812/// word for what it is that differs.
2813///
2814/// # Storage is machine-facing, and the wire is not
2815///
2816/// A DECLARATION THAT SAYS NOTHING IS COMPLETE. Every database stores the DISCRIMINANT, at the
2817/// width the enum's own `#[repr(…)]` names (`i64` without one), and the wire shows the NAME in
2818/// `SCREAMING_SNAKE_CASE`. Nothing has to be written to get either: a column exists for a machine
2819/// and a schema exists for a person. The two meet at the FILTER — an operand crosses as the enum
2820/// itself — so a user's text never reaches an integer column as text.
2821///
2822/// # Attributes
2823///
2824/// On the enum, in the derive's own `#[ingraph(…)]` beside it:
2825///
2826/// - `crate = "path::to::ingraph"` — where `ingraph` lives, for a re-export shim or a renamed
2827/// dependency. Defaults to `::ingraph`, exactly as [`record`]'s does.
2828/// - `sqlite(…)`, `postgres(…)`, `mysql(…)`, `mongo(…)`, `graphql(…)` — ONE BLOCK PER FACE, each
2829/// naming `text` or `integer`. Every one is an OVERRIDE of that face's default, and a face left
2830/// undeclared keeps it.
2831/// - `graphql(rename = "…")` — what a SCHEMA calls this vocabulary, beside the wire face's form and
2832/// answering a different question. Defaults to the Rust name unraw'd; a closed vocabulary moves its
2833/// `enum`, an open one and a mirror move their `scalar`. EMISSION-ONLY — the Rust type, the refusal
2834/// type and every stored word are untouched — and legal in all four cells of the mode table, where
2835/// the FORM words are not. A schema entity's word is not a Rust identifier, so `rename = "type"`
2836/// is writable.
2837/// - `error(rename = "Name")` — what the emitted REFUSAL type is called. `Record`'s `key(…)` block
2838/// in this grammar, and for the same reason: `rename` names the type its block is about. Defaults
2839/// to `<Enum>ParseError`.
2840/// - `remote = "path::to::Upstream"` — this declaration RESTATES that vocabulary rather than being
2841/// one. See *The MIRROR mode* below, which is where the rest of this grammar changes meaning.
2842/// - `delegate(fn name(&self) -> T, …)` — the upstream methods this mirror forwards, each restated
2843/// as a signature. MIRRORS only. The receiver is `&self` or `&mut self`, and an entry may wear
2844/// `#[graphql(<backend>)]` to be PUBLISHED — see *The MIRROR mode* below.
2845///
2846/// On a variant:
2847///
2848/// - `rename = "…"` — the CANONICAL word, which every face that states none defaults from. On a
2849/// MIRROR it names the UPSTREAM VARIANT this one restates: there is no word of this declaration's
2850/// for it to move.
2851/// - `sqlite(rename = "…")` … `graphql(rename = "…")` — what ONE face spells it. Not on a mirror,
2852/// which spells every face alike.
2853/// - `other` — MIRRORS only, and marks the ESCAPE: the one variant carrying a word rather than
2854/// restating a name. Exactly one, or none.
2855///
2856/// ```ignore
2857/// #[derive(Debug, Clone, Copy, PartialEq, Eq, ingraph::Enum)]
2858/// #[ingraph(postgres(text))]
2859/// pub enum Grade {
2860/// #[ingraph(rename = "lo", postgres(rename = "LO"), graphql(rename = "LOW"))]
2861/// Low,
2862/// High,
2863/// }
2864/// ```
2865///
2866/// | form | the face holds | the default |
2867/// |---|---|---|
2868/// | `integer` | the variant's DISCRIMINANT, the declaration's own | every database |
2869/// | `text` | the variant's word in THAT face | the wire |
2870///
2871/// A `#[repr(…)]` is read where it decides a column: `#[repr(u8)]` is a `u8` column on SQLite and
2872/// MySQL and a `SMALLINT` on Postgres, which carries no unsigned type — the framework's own carrier
2873/// widening, restated. Only the widths that table covers may be stored, so `#[repr(u64)]` and its
2874/// neighbours are refused where a face would render one.
2875///
2876/// A variant with no wire rename is `SCREAMING_SNAKE_CASE` of its own name — `Vp9` is `VP9` — which
2877/// is GraphQL's own convention. That casing comes from the SAME function `as_graphql_str` is written
2878/// from, so the word a caller reads in Rust and the value a client writes in a document are one
2879/// string from one table.
2880///
2881/// # What it emits
2882///
2883/// | item | condition |
2884/// |---|---|
2885/// | `EnumFilterMarker`, giving `EnumFilter<Self>` | always |
2886/// | `DefaultMarker`, giving `EnumMarker<Self>` | always |
2887/// | `CursorValue`, over the canonical word | always |
2888/// | `VARIANTS`, `as_str`, `is_<variant>` | always |
2889/// | `<Enum>ParseError` and `FromStr` over the canonical word | always |
2890/// | `as_<face>_str` and `TryFrom<&<Face>Name>` | per TEXT face |
2891/// | `sqlx::Type`, `sqlx::Encode`, `sqlx::Decode`, `Carrier` | per SQL backend, GATED |
2892/// | `EnumType`, `InputType`, `OutputType` | behind the BINDING gate |
2893///
2894/// The storage rows are **per backend and behind that backend's gate**, so they exist for each
2895/// database this build compiled and nowhere else: a declaration in a build with one driver is
2896/// audited against that driver, and a party demanding another's row gets `E0277` where it demands
2897/// it. The FACE is not gated — a word names no driver — and what decides whether a face has one is
2898/// its FORM.
2899///
2900/// The WIRE face is behind the binding gate, so a build of `ingraph` without `async-graphql`
2901/// compiles that half to nothing at all. It is hand-written rather than derived, which is what keeps
2902/// `description: None` a fact of the emission: async-graphql's own derives call `get_rustdoc`
2903/// unconditionally with no key to decline it, so a derived face publishes whatever the declaration
2904/// happened to document, and this crate's rule is that a schema says what a declaration SAYS it
2905/// says. Which SCHEMA a vocabulary reaches is REACHABILITY and nothing else — a schema is walked
2906/// from its roots, so an enum no wire type names is absent from the SDL however many impls it
2907/// carries.
2908///
2909/// The FILTER's wire face is not here and needs no declaration: `EnumFilter<T>` is `ingraph`'s own
2910/// type, so one generic `InputType` row there serves every declared enum at once. What this door
2911/// mints is the half only the declaring crate can — an impl on its own type.
2912///
2913/// The method face is hand-written by this crate rather than derived from anywhere: no
2914/// `derive_more`, so the expansion names no foreign path and the refusal type is the vocabulary's
2915/// own.
2916///
2917/// The REFUSAL is also the one type this expansion puts in the DECLARING scope — everything else
2918/// sits inside an anonymous `const`, where it collides with nothing — which is why it alone takes a
2919/// name. `error(rename = "…")` is the escape when the scope already holds a `<Enum>ParseError`, and
2920/// it moves the TYPE and not the sentence: the message names the vocabulary either way.
2921///
2922/// **No MongoDB storage row.** `MongoCarrier` is the seam it would take, and a MongoDB vocabulary
2923/// writes that one impl by hand until a lane exists that can compile a generated one —
2924/// `mongo(text)` gives it `as_mongo_str` and `TryFrom<&MongoName>` to write it with.
2925///
2926/// # Refusals
2927///
2928/// The declaration's SHAPE is the vocabulary, so each part of it is checked here rather than left
2929/// to fail inside the expansion: a non-enum, an enum with no variants, a variant that carries data,
2930/// and any generic parameter. More come with the faces — a rename under a face that stores the
2931/// discriminant, two variants colliding in ONE face's namespace, two variants deriving one
2932/// `is_<variant>`, and a name outside GraphQL's own Name grammar, asked of the enum itself and of
2933/// every wire rename. One comes with the refusal type: `error(rename = "…")` naming the enum
2934/// itself, which the expansion would land in the same scope twice. A default name colliding with
2935/// something ELSE in that scope is not refused here and cannot be — the scope's contents are not the
2936/// macro's to see — so it stays rustc's duplicate definition, and the rename is what answers it.
2937///
2938/// What is NOT refused here is the enum's own `Copy`/`Eq`: async-graphql's `EnumType` bound demands
2939/// them, so a declaration missing one gets `E0277` naming the trait at the enum in a build carrying
2940/// the binding. A token-level check for a `#[derive(Copy)]` would refuse a declaration whose
2941/// `impl Copy` is hand-written, which is a correct program.
2942///
2943/// # The MIRROR mode
2944///
2945/// `#[ingraph(remote = "…")]` says the declaration RESTATES a vocabulary another crate owns — the
2946/// orphan rule being why the restatement exists at all — and the whole emission changes with it.
2947/// `ingraph-codegen`'s `enumeration::remote` carries the design; what a declaration has to know is
2948/// four things.
2949///
2950/// **The restatement is IDENTIFIERS.** Every word comes from the upstream's own `Display` and
2951/// `FromStr`, through the `remote()` gate this mode always emits, so a mirror takes no per-face
2952/// `rename` and no `text`/`integer` form: an upstream vocabulary spells itself, in one word, in
2953/// every face. That is also why `rename` names an upstream VARIANT here rather than a word.
2954///
2955/// **`#[ingraph(other)]` is the openness, declared.** Its presence says the upstream vocabulary is
2956/// open, and both directions of that claim are settled by the compiler at the site the claim is
2957/// spent: an escape over an upstream whose parse can REFUSE is a named `E0277` at the
2958/// `remote = "…"` token, and NO escape over an upstream that has more variants than this mirror
2959/// names is `E0004` at a `From` whose arms are exhaustive.
2960///
2961/// **The marker takes ONE optional cell, and it says where the totality LIVES.** The bound above
2962/// reads the upstream's `FromStr::Err`, which a crate whose parse is total in behaviour and
2963/// refusable in type fails while handing out a perfectly total gate. `from` names a gate that
2964/// cannot refuse, `try_from` one that can — the conversion family's own pair, and exactly one of
2965/// them:
2966///
2967/// | posture | totality lives in | `FromStr::Err` | `error(rename = "…")` |
2968/// |---|---|---|---|
2969/// | `other` | `<Remote as FromStr>::Err` | `Infallible` | refused |
2970/// | `other(from = "…")` | the gate's SIGNATURE | `Infallible` | refused |
2971/// | `other(try_from = "…")` | nowhere — the door can refuse | `<Enum>ParseError` | LEGAL |
2972///
2973/// The last is HALF-OPEN: open outward, where the `From<Remote>` wildcard still absorbs an upstream
2974/// value this mirror does not restate, and closed inward, where a word neither the parse nor the
2975/// gate accepts is this vocabulary's own refusal. Its gate refuses with `<Remote as FromStr>::Err`
2976/// and no other type. Every posture PARSES FIRST, a gate answering only for what the upstream's own
2977/// parse turned away.
2978///
2979/// **An open mirror ABSORBS what it did not name**, so an upstream release that grows a variant does
2980/// not break a build — and the absence is therefore named at TEST time, by a per-variant round-trip
2981/// pin walking the upstream's roster against `VARIANTS`.
2982///
2983/// **The wire face is a SCALAR**, not a GraphQL `enum`: a mirror's value set is the upstream's, so
2984/// an SDL member list here would publish a set this crate cannot keep true. The reference family —
2985/// `AsRef`, `Deref`, `Borrow` — is absent and cannot be sound: a restatement is not a wrapper, and
2986/// the escape holds a word rather than an upstream value.
2987///
2988/// # `delegate(fn …)`, and the two things an entry may say
2989///
2990/// An entry is a SIGNATURE, restated because Rust has no `typeof`, and this expansion writes the
2991/// body. Two axes move it:
2992///
2993/// **The RECEIVER.** `&self` forwards — materialize the upstream, call, hand the answer back.
2994/// `&mut self` WRITES BACK — materialize, mutate, convert home through this mirror's own `From` —
2995/// which costs two conversions per call and is what makes a mutating upstream method reachable at
2996/// all, a mirror storing a word rather than an upstream value. A consuming `self` and a signature
2997/// with no receiver are refused at the receiver the declaration wrote.
2998///
2999/// **`#[graphql(<backend>)]`,** an outer attribute on the entry, PUBLISHES that method. It is an
3000/// adjective on a noun: the entry is still a function, and the word only says it also reaches a
3001/// schema. `#[graphql(async_graphql(rename = "…"))]` moves the published word, which is the whole of
3002/// v1's knob.
3003///
3004/// ```ignore
3005/// #[ingraph(remote = "upstream::Codec", delegate(
3006/// fn to_u32(&self) -> Option<u32>,
3007/// #[graphql(async_graphql)]
3008/// fn is_lossless(&self) -> bool,
3009/// #[graphql(async_graphql(rename = "intra"))]
3010/// fn is_all_intra(&self) -> bool,
3011/// ))]
3012/// ```
3013///
3014/// **ONE published delegate PROMOTES the output seat**, because a word cannot carry a selection set:
3015/// the mirror renders as an OBJECT under its own name — `text`, the canonical slug, plus one field
3016/// per published method — and the scalar retreats to the INPUT seat under `<Enum>Input`. That is the
3017/// declared union's naming law, for the union's own reason: two schema types on one Rust type, and a
3018/// schema has one namespace for type names. A mirror that publishes nothing is untouched by any of
3019/// it, down to the emitted token.
3020#[proc_macro_derive(Enum, attributes(ingraph))]
3021pub fn r#enum(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
3022 let input = syn::parse_macro_input!(item as syn::DeriveInput);
3023 // NO host is emitted, which is the whole difference from the attribute family: a derive is handed
3024 // a COPY of the declaration and the compiler keeps the original, so a refusal here rides beside
3025 // the type without having to re-emit it — and the `#[ingraph(…)]` markers it reads stay on the
3026 // item, inert, where an attribute macro's echo would have had to strip them.
3027 r#enum::parse(&input)
3028 .as_ref()
3029 .map_or_else(
3030 |refused| refused.to_compile_error(),
3031 ingraph_codegen::enumeration::EnumModel::emit,
3032 )
3033 .into()
3034}
3035
3036/// Equip a DECLARED UNION — an enum whose every variant carries one member type.
3037///
3038/// A union is a CHOICE between types, and the declaration is the choice: one variant per member,
3039/// each carrying that member and nothing else. The derive does not write the enum — the user does,
3040/// or a compiler line that read a schema does — exactly as `Enum` equips a vocabulary somebody
3041/// else declared.
3042///
3043/// ```ignore
3044/// #[derive(ingraph::Union)]
3045/// #[ingraph(graphql(async_graphql(output, input)))]
3046/// pub enum SearchResult {
3047/// Media(Media),
3048/// Video(Video),
3049/// }
3050/// ```
3051///
3052/// # A DERIVE, on [`Enum`](macro@r#enum)'s own doctrine
3053///
3054/// The declaration family are attribute macros because those words REWRITE the item they sit on.
3055/// This one rewrites NOTHING — it adds impls beside a type somebody else wrote — so it is a derive,
3056/// and it gains what a derive gains: a refusal rides BESIDE the declaration instead of replacing it,
3057/// and the `#[ingraph(…)]` markers stay on the item, inert.
3058///
3059/// The INTERFACE beside it stays an attribute, and that is not inertia: an interface is a member set
3060/// with a CONTRACT over it, which is a different declaration with different semantics and a
3061/// different wire. Nothing in this word touches any of the three. What the two DO share is the
3062/// member-set walk and the unwrap face the seam emits, and both are untouched by the form this word
3063/// takes.
3064///
3065/// # Which unions this is for
3066///
3067/// The DECLARED ones: a schema's `union SearchResult = Media | Video`, and its input-position twin.
3068/// The framework's other payload enums are the FAN-IN ones a node with several upstreams gets, and
3069/// those are the node macros' own emission — nobody writes them, so there is nothing to apply a
3070/// derive to.
3071///
3072/// # Attributes
3073///
3074/// On the enum, in the derive's own `#[ingraph(…)]` beside it:
3075///
3076/// - `crate = "path::to::ingraph"` — where `ingraph` lives, for a re-export shim or a renamed
3077/// dependency. Defaults to `::ingraph`, exactly as [`record`]'s does. It was absent while the
3078/// whole emission was `core`; a declared wire face names the shelf and the binding gate, which is
3079/// what bought it.
3080/// - `unwrap_error(rename = "Name")` — what the emitted REFUSAL type is called. `Record`'s `key(…)`
3081/// block in this grammar. Defaults to `<Union>UnwrapError`. The word is `unwrap_error` and not
3082/// `error` because `error` names the CONVERSION CELLS — one per leg, inside a database's block —
3083/// and the old spelling is a named migration refusal.
3084/// - `graphql(<backend>(output, input))` — the SCHEMA POSITIONS this union is rendered at. Both
3085/// words are optional and a block naming neither is refused; a declaration writing no `graphql(…)`
3086/// at all is today's union exactly, with a Rust face and no schema presence.
3087///
3088/// A variant takes no entries at all — a member is addressed by the TYPE it carries.
3089///
3090/// # `input` and `output` are a BACKEND's sub-axis
3091///
3092/// They are entries of `<backend>(…)` rather than of `graphql(…)`, which is the tree's axis law
3093/// unchanged: a DOMAIN block, then a BACKEND block, then that cell's entries. Which positions a type
3094/// is rendered at is a backend's own rendering, as `attrs(…)` and `skip` are on the record's
3095/// grammar. The union is the only declaration consuming the pair today; a second consumer writes the
3096/// same two words at the same depth.
3097///
3098/// # What a schema calls the two faces
3099///
3100/// Both are impls on the ONE Rust type the declaration already named, and a GraphQL schema has ONE
3101/// namespace for type names. So:
3102///
3103/// | declared | the output is called | the input is called |
3104/// |---|---|---|
3105/// | `output` | `SearchResult` | — |
3106/// | `input` | — | `SearchResult` |
3107/// | both | `SearchResult` | `SearchResultInput` |
3108///
3109/// A single face takes the union's own name, having nothing to collide with. Where both are
3110/// rendered the OUTPUT keeps it — it is the name a client writes in a selection set — and the input
3111/// derives `<Union>Input`. `input(rename = "…")` moves that word at either arity, and
3112/// `output(rename = "…")` moves the other — carrying the derived twin with it, so a `Pick` renamed to
3113/// `Sighting` publishes `Sighting` and `SightingInput`. Two faces resolving to ONE word is refused at
3114/// whichever one wrote it.
3115///
3116/// # What it emits
3117///
3118/// One block per member, and a refusal type beside the enum:
3119///
3120/// | item | receiver |
3121/// |---|---|
3122/// | `const fn is_<member>` | `&self` |
3123/// | `unwrap_<member>` · `unwrap_<member>_ref` · `unwrap_<member>_mut` | `self` · `&self` · `&mut self` |
3124/// | `try_unwrap_<member>` · `try_unwrap_<member>_ref` · `try_unwrap_<member>_mut` | the same three |
3125///
3126/// The `unwrap` family panics with a message naming the variant asked for and the one held; the
3127/// `try_unwrap` family answers with `<Union>UnwrapError`, which carries that same pair and reads it
3128/// out through `asked()` and `held()`. Its FIELDS are private, so nothing outside the declaring
3129/// module builds one.
3130///
3131/// The suffixes are `derive_more`'s `#[unwrap(ref, ref_mut)]` semantics restated as this crate's
3132/// own. `derive_more` is not a dependency: its `TryUnwrapError` would put a foreign path in every
3133/// consumer's expanded code and a foreign type in the signatures a caller writes.
3134///
3135/// One consequence is worth knowing before reaching for the owned receiver: `try_unwrap_<member>`
3136/// takes `self`, and on a refusal the value it was called on is DROPPED. One refusal type serves
3137/// all three receivers — a borrowing one has nothing owned to hand back — so there is nowhere for
3138/// it to travel. `is_<member>` is the check that costs nothing.
3139///
3140/// And, per declared position, the impls that position is rendered through — `ContainerType`,
3141/// `OutputType` and `UnionType` for the output; `InputType`, `InputObjectType` and `OneofObjectType`
3142/// for the `@oneOf` input, whose seats are one NULLABLE seat per member named in lower camel case
3143/// off the variant's own spelling. Both are HAND-WRITTEN and both ride the BINDING GATE, so a build
3144/// of `ingraph` without `async-graphql` expands them to nothing at all.
3145///
3146/// Hand-written because a derive may only APPEND: there is nowhere to put
3147/// `#[derive(async_graphql::Union)]` on an enum this word never rewrites, and a `#[cfg_attr]` could
3148/// not stand in — that predicate asks whether the DECLARING crate has a feature called
3149/// `async-graphql`, which is a different manifest and usually no feature at all. It is also what
3150/// keeps `description: None` a fact of the emission, for the reason [`Enum`](macro@r#enum)'s face
3151/// states.
3152///
3153/// **No storage.** A union is not a column: both declared positions are wire shapes, so nothing
3154/// persists one.
3155///
3156/// # Refusals
3157///
3158/// The declaration's SHAPE is the union, so each part of it is checked here rather than left to
3159/// fail inside the expansion: a non-enum, an enum with no variants, a variant carrying no member,
3160/// one carrying several, one carrying its member in a NAMED field, and any generic parameter.
3161///
3162/// Two more are about the member SET. Two variants carrying ONE type break GraphQL's own law —
3163/// *a union type must include one or more unique member types* — and two variants whose words are
3164/// one word derive one method seven times over. A last one comes with the refusal type:
3165/// `unwrap_error(rename = "…")` naming the enum itself, which the expansion would land in the same
3166/// scope twice.
3167///
3168/// The wire word brings its own: `graphql(…)` twice, a backend nobody ships, a backend twice, a
3169/// backend dressing NO position, either position twice, an option on `output`, an entry `input(…)`
3170/// does not take, a rename outside GraphQL's own Name grammar, and a rename onto the word the output
3171/// face already publishes.
3172///
3173/// One refusal is the COMPILER's and is named all the same. A member of a union declaring `input`
3174/// needs an `async_graphql::InputType` of its own, which no macro can see — so the expansion asks
3175/// for it through a marker carrying this framework's sentence, spanned at the member's own type.
3176#[proc_macro_derive(Union, attributes(ingraph))]
3177pub fn union(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
3178 let input = syn::parse_macro_input!(item as syn::DeriveInput);
3179 // NO host is emitted, for the reason `Enum` states: a derive is handed a COPY of the declaration
3180 // and the compiler keeps the original, so a refusal here rides beside the type without having to
3181 // re-emit it.
3182 union::parse(&input)
3183 .as_ref()
3184 .map_or_else(
3185 |refused| refused.to_compile_error(),
3186 ingraph_codegen::union::UnionModel::emit,
3187 )
3188 .into()
3189}
3190
3191/// Equip a NEWTYPE — a type this crate declares that wraps ONE value — with the faces it names.
3192///
3193/// ```ignore
3194/// #[derive(Debug, Clone, PartialEq, ingraph::NewType)]
3195/// #[ingraph(
3196/// graphql(async_graphql(scalar(parse = "Language::parse"), input, output)),
3197/// marker(string),
3198/// filter,
3199/// cursor,
3200/// sqlite,
3201/// )]
3202/// pub struct Language(smol_bytes::Utf8Bytes);
3203/// ```
3204///
3205/// # What each KIT installs
3206///
3207/// Every row below DELEGATES to the wrapped type. Nothing is inferred: a face this declaration does
3208/// not name is a face the expansion does not write.
3209///
3210/// | word | rows |
3211/// |---|---|
3212/// | `graphql(<backend>(scalar(…)))` | the type's own GraphQL scalar — its `parse`, its `is_valid` and its rendering |
3213/// | `graphql(<backend>(input))` | `ToGraphqlInput` — what ONE operand crosses on |
3214/// | `graphql(<backend>(output))` | `ToGraphqlOutput` — what a wire face returns it as |
3215/// | `marker(<family>)` | `DefaultMarker` and `DefaultVecMarker` — the interpretation a FIELD of it is read under |
3216/// | `filter` | the family's filter, reached through a reading this device mints beside the type |
3217/// | `cursor` | `CursorValue` — a keyset position |
3218/// | `sqlite` / `postgres` / `mysql` | that dialect's `Type`, `Encode`, `Decode` and bind, plus the width and the read every dialect shares |
3219///
3220/// # The DOOR is one source, and every READ spends it
3221///
3222/// `scalar(parse = "…")` names a `fn(&str) -> Result<Self, E>` and `scalar(check = "…")` a
3223/// `fn(<the inner type>) -> Result<Self, E>`; a declaration writes at most one. Where one is
3224/// written, EVERY path a value arrives on goes through it — the scalar's `parse` and `is_valid`, the
3225/// cursor's `read_cursor`, and the dialect decode — so a column holding a value this type refuses is
3226/// a decode error rather than a value whose type says it cannot exist.
3227///
3228/// A WRITE spends nothing: the value is one this type already holds, so the wrapped type's own row
3229/// is the whole answer.
3230///
3231/// # The wire block is the union's AXIS, at the union's depth
3232///
3233/// `graphql(<backend>(…))` — a DOMAIN block, then a BACKEND block, then that cell's entries. A wire
3234/// word written one level up is refused as an unknown BACKEND, which is what it is.
3235///
3236/// # Refusals
3237///
3238/// A declaration that is not a struct, or does not hold exactly one field. A `filter` with no
3239/// `marker(<family>)` beside it — the filter kind is the family's, so the word alone names nothing.
3240/// A declaration naming NO kit, whose expansion would be empty. Two doors in one `scalar(…)`. A word
3241/// declared twice at any depth. And every word the roster carries whose kit this round has not
3242/// built, refused BY NAME with what it would install and what to write instead.
3243#[proc_macro_derive(NewType, attributes(ingraph))]
3244pub fn newtype(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
3245 let input = syn::parse_macro_input!(item as syn::DeriveInput);
3246 // NO host is emitted, for the reason `Enum` states: a derive is handed a COPY of the declaration
3247 // and the compiler keeps the original, so a refusal here rides beside the type without having to
3248 // re-emit it.
3249 newtype::parse(&input)
3250 .as_ref()
3251 .map_or_else(
3252 |refused| refused.to_compile_error(),
3253 ingraph_codegen::newtype::NewTypeModel::emit,
3254 )
3255 .into()
3256}
3257
3258/// Equip an ID WRAPPER — a `#[repr(transparent)]` type holding one value — with the whole register
3259/// an address needs.
3260///
3261/// ```ignore
3262/// #[derive(ingraph::Id)]
3263/// #[repr(transparent)]
3264/// pub struct TrackId(uuid::Uuid);
3265/// ```
3266///
3267/// That is the entire declaration. There is no kit word, no `#[derive(Clone, PartialEq, Eq, Hash)]`
3268/// beside it and no hand-written row after it: the type stands at a record's `#[ingraph(id)]`, at an
3269/// aggregate's `#[ingraph(group)]`, in a filesystem path, in a SQL column, on a cursor and in a
3270/// schema, from this word alone.
3271///
3272/// # Named for the trait it ADMITS
3273///
3274/// `#[derive(Clone)]` gives you `Clone`; this gives you [`Id`](ingraph::Id) — the sealed key-field
3275/// vocabulary, entered through its third admission law. It is deliberately not spelled
3276/// `#[ingraph(id)]`: that word is the RECORD's, naming which FIELD of a declaration is its address.
3277///
3278/// # What it writes
3279///
3280/// | face | mechanism |
3281/// |---|---|
3282/// | `DelegatesId` | the transparency assertion, upheld BY CONSTRUCTION rather than asserted |
3283/// | `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash` | delegated to the held value |
3284/// | `Display`, `FromStr` | delegated — the canonical spelling is the inner type's own |
3285/// | `From<Inner>`, `From<Self> for Inner`, `From<Self> for String` | the conversions, and the crossing a TEXT-column comparison asks for |
3286/// | `CursorValue` | delegated — a keyset position |
3287/// | `ColumnKind`, `Carrier<Db>`, `Assemble` | one column, bound and decoded as canonical TEXT |
3288/// | `ToGraphqlInput`, `ToGraphqlOutput` | the identity crossing and the borrow |
3289/// | `ScalarWire`, `CompositeFilterMarker`, `DefaultMarker` | the filter reading, over a minted `<Name>Wire` |
3290/// | `async_graphql::ScalarType` | the scalar itself, under this type's own name |
3291/// | `new`, `into_inner`, `as_inner` | the constructor and the two readings |
3292/// | `from_ref`, `from_slice`, `as_inner_slice` | the free views, `#[repr(transparent)]`'s own dividend |
3293///
3294/// The roster is a MEASUREMENT and not a wish list: it is what `findit`'s `MediaId` and
3295/// `mediagraph`'s `VolumeId` each hand-wrote, independently, impl for impl.
3296///
3297/// # THE ONE OBLIGATION ON THE WRAPPED TYPE: a canonical text form
3298///
3299/// It must implement [`Display`](core::fmt::Display) and [`FromStr`](core::str::FromStr), the
3300/// latter with a refusal that is an [`Error`](core::error::Error). Every row from `Display` down
3301/// spends one or the other — the bind renders, the decode reads back, the scalar does both — and the
3302/// storage pair crosses through `String` rather than through the wrapped type's own column faces,
3303/// which is the road both live registers took and for the reason they took it: `ingraph` ships no
3304/// value-column row for a bare `uuid::Uuid` to delegate to.
3305///
3306/// So `[u8; N]` — a measured member of the vocabulary with neither face — is refused, at the
3307/// declaration, naming what is missing. A digest is a perfectly good key and not a text-shaped
3308/// value; its road is `unsafe impl ingraph::DelegatesId`, which asks for no text at all.
3309///
3310/// # `Ord` is NOT written, and `Copy` is the declaration's own
3311///
3312/// No id duty reads an order — the stored order is the backend's reading of the value and the path
3313/// segment is the framework's own rendering — so a device that minted one would be inventing an
3314/// order for a type whose author may have refused it. `#[derive(PartialOrd, Ord)]` beside this word
3315/// is how a declaration that wants one says so, and `#[derive(Copy)]` resolves against the `Clone`
3316/// this device writes.
3317///
3318/// # THE DOOR HAS NO INVARIANT, and that is a requirement rather than an observation
3319///
3320/// `from_ref` views any `&Inner` as a `&Self`. A wrapper whose values are a CHECKED SUBSET of its
3321/// inner's therefore does not belong here — take `#[derive(ingraph::NewType)]` with
3322/// `scalar(check = "…")` or `scalar(parse = "…")`, where every read path is spent on the door.
3323///
3324/// # Refusals
3325///
3326/// A declaration that is not a struct; one whose field is NAMED, or that holds any number of values
3327/// but one; one carrying no `#[repr(transparent)]`; one that is GENERIC. Each is refused by name,
3328/// with what to write instead — as is every word `#[derive(ingraph::NewType)]` carries that this
3329/// door does not, pointed at the door that has it.
3330#[proc_macro_derive(Id, attributes(ingraph))]
3331pub fn id(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
3332 let input = syn::parse_macro_input!(item as syn::DeriveInput);
3333 // NO host is emitted, for the reason `Enum` states: a derive is handed a COPY of the declaration
3334 // and the compiler keeps the original, so a refusal here rides beside the type without having to
3335 // re-emit it.
3336 id::parse(&input)
3337 .as_ref()
3338 .map_or_else(
3339 |refused| refused.to_compile_error(),
3340 ingraph_codegen::id::IdModel::emit,
3341 )
3342 .into()
3343}
3344
3345/// Declare an INTERFACE — a member set with a contract over it.
3346///
3347/// An interface is a union plus a promise. The union half is the same payload-carrying enum
3348/// [`Union`] equips: one variant per member, each carrying that member and nothing else. The
3349/// promise is `fields(…)` — every member has these fields, at these types.
3350///
3351/// ```ignore
3352/// #[ingraph::interface(
3353/// persist(sqlite, postgres),
3354/// graphql(computed(error = "media::ComputeError")),
3355/// fields(
3356/// title: String,
3357/// mask(type = "Mask", copy, persist(sqlite(type = "u32"), postgres(type = "int4"))),
3358/// created_at(type = "Timestamp", members(Audio(field = "imported_at"))),
3359/// display_label(type = "String", graphql(computed)),
3360/// checksum(type = "u64", graphql(try_computed)),
3361/// ),
3362/// )]
3363/// pub enum Media {
3364/// Video(Video),
3365/// Audio(Audio),
3366/// }
3367/// ```
3368///
3369/// # A field is in ONE of three tiers, and the tier decides whose face carries it
3370///
3371/// | tier | written | every member | the face |
3372/// |---|---|---|---|
3373/// | stored | nothing, or `persist(<db>(type = "…"))` | carries the column | `<I>Fields`, on the member |
3374/// | computed | `graphql(computed)` | DERIVES the value | `<I>Derivations`, on its wire output |
3375/// | try_computed | `graphql(try_computed)` | derives it, fallibly | the same, returning a `Result` |
3376///
3377/// The domain contract is STORED-ONLY. A computed field is a query-layer construct — it is derived
3378/// to be answered, and what answers a query is the wire output — so putting one on the domain trait
3379/// would make every member's domain type owe a method its rows have no column for. `<I>Derivations`
3380/// is DECLARED and implemented nowhere: a member's output type writes the impl by hand, and there
3381/// is no adapter under it, because a hand author writes their own glue.
3382///
3383/// Stored and computed are mutually exclusive in both directions, and each direction has its own
3384/// refusal.
3385///
3386/// # Attributes
3387///
3388/// On the enum:
3389///
3390/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Present here
3391/// where a union has none, because an interface's expansion DOES name framework paths: the
3392/// membership evidence, the storability its equations read a row through, and the backend gates
3393/// they ride.
3394/// - `unwrap_error(rename = "Name")` — what the emitted REFUSAL type is called. Defaults to
3395/// `<Interface>UnwrapError`, which is the union's convention reached through the union's own
3396/// function. `error` names the CONVERSION CELLS instead, and the old spelling is a named
3397/// migration refusal — one word per thing typed.
3398/// - `persist(sqlite, postgres, …)` — which databases the contract's pins are checked at. A
3399/// SELECTION rather than a storage declaration: an interface owns no table. A database block may
3400/// carry `alias(prefix = "__mine")`, which moves the words a union statement INVENTS in that
3401/// database — the discriminant every arm projects and the derived table the outer query names.
3402/// `depth` is refused here: it is the length of an alias table, and an interface has none.
3403/// - `graphql(computed(error = "path::To"))` — the type every fallible computed field answers with.
3404/// ONE cell and DB-LESS, which is this grammar's one ruled exception to database blocks: a
3405/// computed value is derived from the member rather than read out of a row, so the crossing names
3406/// no database.
3407/// - `fields(…)` — the contract. An interface with none is a union, and is refused by that reason.
3408///
3409/// A field is `<name>: <Type>` or `<name>(type = "<Type>", …)`, and the long form takes `copy`,
3410/// `persist(<db>(type = "…"))`, `graphql(…)` and a MEMBER block. The long form's type is written in
3411/// a STRING, as every other `type` in this grammar is; the short form's is the Rust type itself,
3412/// because there it is what the `:` already introduces.
3413///
3414/// # A member may call a stored field something else
3415///
3416/// `created_at(type = "Timestamp", members(Audio(field = "imported_at")))` — the member `Audio` carries this
3417/// field as `imported_at`, in its own struct and in its own row.
3418///
3419/// Declared on the INTERFACE rather than on the member, and the reason is what a macro can see: a
3420/// member-side word would have to reach the interface's expansion across a derive boundary, and the
3421/// only things that cross one are a type and a const — neither of which produces the IDENT a field
3422/// access needs. Written here, every hop is backed by the same derive input, starting with the
3423/// block's key, which is checked token-for-token against the enum's own variants in VERBATIM case.
3424///
3425/// What a block moves is the ACCESS and not the METHOD: a caller writes the interface's name
3426/// whatever member it is holding. `field = "…"` is the only entry it takes; one `members(…)` per
3427/// field, never empty; and `members(…)` on a computed field is refused — a derived value is read
3428/// out of no column at all.
3429///
3430/// # The axis law
3431///
3432/// A DOMAIN block, then a DATABASE block, then that cell's entries — at every level. So a database
3433/// name written where a domain belongs is refused BY NAME rather than as an unknown entry, wherever
3434/// it appears.
3435///
3436/// A field's `members(…)` extends it one step — interface field block ▸ `members(…)` ▸ one block
3437/// per variant ▸ entries — and the step is this grammar's alone: a record grows no member axis,
3438/// having no members.
3439///
3440/// POSITION decides what a key is. Outside `members(…)` every key is a word this grammar owns;
3441/// inside it every key is a VARIANT, matched token-for-token against the enum's own. A variant
3442/// written outside the container is refused BY NAME rather than as an unknown word, and one whose
3443/// spelling collides with a grammar word — or one in lower case — is reachable inside it, where a
3444/// rule reading the first letter had a corner it could not address.
3445///
3446/// # What it emits
3447///
3448/// The union face — `is_<member>`, the `unwrap_<member>` family in all three receivers, and the
3449/// sealed refusal — through the same seam `Union` reaches, so an interface's members are asked for
3450/// exactly as a union's are.
3451///
3452/// # Refusals
3453///
3454/// The SHAPE refusals are the union's family, stated in this declaration's own terms: a non-enum,
3455/// an enum with no variants, a variant carrying no member, one carrying several, one carrying its
3456/// member in a named field, any generic parameter, two variants carrying one type, and two variants
3457/// whose words derive one method.
3458///
3459/// Its own are the contract's: a field declared twice, a field with no type, an entry neither form
3460/// admits, a database name at a domain position, an interface with no `fields(…)` at all, and the
3461/// tier collision in both of its directions. `members(…)` adds five more — a key naming no variant
3462/// (refused by listing the ones there are), one member named twice in one container, a container on
3463/// a computed field, a second container on one field, and one naming nobody. A member block written
3464/// OUTSIDE the container is refused by name, which is a migration rather than an unknown word.
3465///
3466/// A field's `graphql(output(<db>(…)))` is ADMITTED AND REFUSED rather than unknown: it is a real
3467/// entry of the settled design whose consumer is the interface's own output face, whose stored half
3468/// waits on an accessor a member's wire object does not publish yet, so the refusal names the shape
3469/// and says what it arrives with. The four operand and hydration cells beside it are READ — see
3470/// [`interface`]'s own note for which level each sits at and why.
3471#[proc_macro_attribute]
3472pub fn interface(
3473 args: proc_macro::TokenStream,
3474 item: proc_macro::TokenStream,
3475) -> proc_macro::TokenStream {
3476 equip(args, item, |input, arguments| {
3477 interface::parse(input, arguments).as_ref().map_or_else(
3478 syn::Error::to_compile_error,
3479 ingraph_codegen::interface::InterfaceModel::emit,
3480 )
3481 })
3482}
3483
3484/// Declare a GRAPH ROOT — the struct whose fields are an application's nodes.
3485///
3486/// ```ignore
3487/// #[ingraph::graph]
3488/// pub struct Media {
3489/// videos: Video,
3490/// scenes: Scene,
3491/// search: TranscriptText,
3492/// }
3493/// ```
3494///
3495/// The list is the whole declaration. There is no registry a node enrols itself in and nothing on a
3496/// node's own binding points back at a graph: an application writes its nodes once, in the order
3497/// it wants them walked, and this derive turns that order into a walk.
3498///
3499/// # Attributes
3500///
3501/// On the struct, one entry and no other:
3502///
3503/// - `crate = "path::to::ingraph"` — where `ingraph` lives, for a re-export shim or a renamed
3504/// dependency. Defaults to `::ingraph`, exactly as [`record`]'s does.
3505///
3506/// A FIELD takes the words that are the ROOT's to author, and no others: `resource` in its three
3507/// spellings, a `teardown` composed with any of them, `interface`, `fuse`, and `query` — the ROOT
3508/// QUERY's membership. The example above writes none of them, which is the bare shape rather than
3509/// the whole grammar. What a node IS, how it is stored, and whether it says goodbye stay in that
3510/// node's own declaration, because a word here for any of those would be a second author for one
3511/// fact. Every word a field does take is about the LIST instead: which TIER the field sits on, and
3512/// whether THIS deployment publishes its root fields — facts no member's own declaration can hold,
3513/// since a member cannot see the root that mounts it.
3514///
3515/// # What it emits
3516///
3517/// | item | condition |
3518/// |---|---|
3519/// | `type_iter<V: TypeVisitor>(visitor)` — one `next_type::<T>()` per field | always |
3520/// | `<Root>Options` — one section per field, and the doors to state one | always |
3521/// | its `Deserialize` impl | serde is compiled in |
3522/// | `init<Db>(conn)` — create every table this graph declares | the SQL family is compiled in |
3523/// | `validate<Db>(conn)` — audit a live schema against it | the same |
3524///
3525/// The three entries are INHERENT and take the root's own visibility, and so does the spine.
3526/// `type_iter` could not be a trait method: its body discharges one storage-description predicate
3527/// per field, and an impl may not add a where clause to a trait method (`E0276`).
3528///
3529/// # The OPTIONS SPINE, and what its `Option` means
3530///
3531/// `<Root>Options` holds `Option<NodeSection<<T as AsyncConstructor>::Options>>` per field, named by the
3532/// mount. PRESENCE IS ENABLEMENT: a node with no section is a node that never launches, so an
3533/// application may declare a catalog and a deployment may take a subset of it without either
3534/// writing anything about the other. Presence is the ONLY enablement axis: a section that is
3535/// written is a node that runs, and a deployment turns one off by pointing at a different document
3536/// rather than by toggling this one.
3537///
3538/// Every field is `serde(default)` and the type is `deny_unknown_fields`, so a document naming three
3539/// of thirty nodes parses and a misspelled mount is a refusal naming it. The framework reads NO
3540/// file: which format states a deployment, how many layers merge into it and where they live are the
3541/// application's questions.
3542///
3543/// Each field names its node's OWN options through the construction contract, so a declared node
3544/// states how it is BUILT as well as how it is stored — a field whose type implements no
3545/// `AsyncConstructor` is `E0277` where the graph is written, carrying that trait's own sentence. A node
3546/// with nothing to configure writes `type Options = ();`.
3547///
3548/// HANDLES ARE PARAMETERS. `init` and `validate` take the connection they run on, so a graph
3549/// describes what exists and never holds what it is stored in.
3550///
3551/// The two entries ride the SQL family's gate, because their signatures name it; the walk names no
3552/// database and is emitted unconditionally, which is what keeps it the single walk authority in a
3553/// build with no driver at all.
3554///
3555/// # The audit a bound makes, and the one nobody can
3556///
3557/// Each field carries a `Describe<V::Db>` predicate at the walk, so a field whose type is not a node
3558/// this database knows how to create is `E0277` where the graph is written — carrying that
3559/// trait's own sentence, and naming the type and the database.
3560///
3561/// What a field's type SUBSCRIBES to is not checkable here at all. A member's subscriptions are
3562/// written in the member's own declaration, which this derive cannot see, so
3563/// subscribe-completeness is an assembly-time check and is named as one rather than half-attempted.
3564///
3565/// # Refusals
3566///
3567/// The declaration's SHAPE is the graph, so each part of it is checked here rather than left to
3568/// fail inside the expansion: an enum, a positional or unit struct, a struct with no field, and any
3569/// generic parameter. The rest are about the LIST — one type listed twice, two fields naming one
3570/// resource, a member mounted at the RESERVED `resources` or `registry` key, and an entry inside a
3571/// field's `#[ingraph(…)]` that is not one of the words above, which is refused BY NAME against that
3572/// roster.
3573#[proc_macro_attribute]
3574pub fn graph(
3575 args: proc_macro::TokenStream,
3576 item: proc_macro::TokenStream,
3577) -> proc_macro::TokenStream {
3578 equip(args, item, |input, arguments| {
3579 graph::parse(input, arguments).as_ref().map_or_else(
3580 syn::Error::to_compile_error,
3581 ingraph_codegen::graph::GraphModel::emit,
3582 )
3583 })
3584}
3585
3586/// Give a HAND-WRITTEN struct the FILTER face a record's declaration gets — a predicate over its
3587/// fields, each field its type's filter.
3588///
3589/// # The bare door of a unit `#[ingraph::record(…)]` already composes
3590///
3591/// There is ONE emitter. `record` composes this walk and adds what a grammar word adds — the
3592/// storage lowerings, the wire faces, the row equations; this door composes the same walk and adds
3593/// nothing. So a record field's filter and a standalone type's filter cannot drift, and the identity
3594/// is pinned as TOKENS rather than argued.
3595///
3596/// # The vocabulary is the record's, wherever it reaches this face
3597///
3598/// The field grammar is read by the RECORD's own reader, so there is no reduced dialect: the
3599/// interpretation words (`scalar`, `string`, `bytes`, `enum`, `bool`, `duration`, `list(…)`,
3600/// `set(…)`, `label = "…"`), `rename = "…"` and the whole `graphql(…)` family are taken
3601/// here exactly as they are taken there. What a bare struct has no use for — `id`, `key(…)`,
3602/// `lineage(…)`, `copy`, `repeated`, `optional`, `ref = "…"`, and the per-database layout words —
3603/// refuses BY NAME at the token that wrote it, because a door that took a word it does not spend
3604/// would leave an author reading a declaration the expansion does not obey.
3605///
3606/// # The container's own words
3607///
3608/// `crate = "…"`, `filter(rename = "…")`, and — shared with the other two doors —
3609/// `comparison(rename = "…")`, `order_by(rename = "…")`, its DATABASES bare, and the conversion
3610/// hook `filter = "…"`. One `#[ingraph(…)]` serves every derive on the declaration, which is what
3611/// lets all three sit on one struct.
3612///
3613/// # THE ELEMENT MODE — `#[ingraph(operator(<family>))]`
3614///
3615/// The same derive, a second lawful identity, and the MARKER is the watershed: written, this
3616/// declaration is one VALUE rather than a row of columns, and what it earns is a filter of its own
3617/// plus the wire citizenship an operand needs.
3618///
3619/// ```ignore
3620/// #[derive(Debug, Clone, PartialEq, ingraph::Filter)]
3621/// #[ingraph(operator(string))]
3622/// pub struct Tag(String);
3623/// ```
3624///
3625/// | item | what it is |
3626/// |---|---|
3627/// | `TagFilter` | the minted filter — the family's operation set, over `Tag`, owned by THIS crate |
3628/// | `StringFilterMarker` / `DefaultMarker` | the two rows a FIELD of `Tag` resolves through |
3629/// | `GraphqlFilter`, `ToDatabaseComparison` | the emptiness answer and the lowering map, delegated |
3630/// | `ScalarType`, `ToGraphqlInput`, `ToGraphqlOutput` | the element's own wire face and its two crossings, behind the BINDING gate |
3631///
3632/// **Why a minted type rather than the framework's own.** `impl async_graphql::InputType for
3633/// TextFilter<Tag>` is `E0117` in a declaring crate — RFC 2451 does not admit `ForeignTrait for
3634/// ForeignType<Local>` — and `ingraph` cannot write it either, its scalar and byte faces being one
3635/// REGISTRATION PER OPERAND over a set a declarer's types are not in. `TagFilter` is local, so every
3636/// impl above names a local self type and the orphan wall never appears.
3637///
3638/// **The FAMILIES.** `scalar`, `string`, `bytes` and `enum` — the four value readings whose filter
3639/// kind carries an OPERAND PARAMETER for a declared element to sit in. `bool` and `duration` carry
3640/// none, and `list`/`set` are collection POSITIONS rather than elements; each refuses BY NAME at the
3641/// word. A BARE `operator` is the `scalar` family. ONE SHAPE at all four: the table above is what
3642/// every family emits, and the family decides what is IN each item and never which items there are.
3643///
3644/// **`filter(rename = "…")` moves BOTH of the minted type's names** — the Rust one and the input
3645/// object's — at every family alike. `enum` used to move only the Rust one, its door having been a
3646/// type ALIAS with no wire face of its own; the alias has retired and the word means one thing.
3647///
3648/// **The wire form is the INNER type's, under the ELEMENT's name.** `Tag(String)` crosses as a
3649/// string in a scalar named `Tag`; an inner type with no wire face of its own is `E0277` naming that
3650/// type. `graphql(rename = "…")` moves that scalar's name and nothing else — a wire type name is a
3651/// schema commitment, which is why it gets a word of its own rather than riding on a Rust rename. The
3652/// other two modes mint no scalar and refuse the word by name.
3653///
3654/// **Refusals.** A declaration that is not ONE field (a unit struct, two fields, an enum); a family
3655/// word outside the four; `operator(…)` on `#[derive(ingraph::Comparison)]` or
3656/// `#[derive(ingraph::OrderBy)]`, whose faces are over a row's columns and an element has none; the
3657/// container words an element does not spend (the store words, `comparison(rename)`,
3658/// `order_by(rename)`, the conversion hook); `graphql(rename = "…")` in either mode that mints no
3659/// scalar; and an `#[ingraph(…)]` on the element's own field.
3660#[proc_macro_derive(Filter, attributes(ingraph))]
3661pub fn filter(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
3662 standalone(item, standalone::Face::Filter)
3663}
3664
3665/// Give a HAND-WRITTEN struct the COMPARISON face — one predicate type per database it names, each
3666/// field the comparison its column's filter crosses into.
3667///
3668/// See [`macro@Filter`] for the family's law, its vocabulary and its refusals. What this door adds
3669/// is the DATABASE set: `#[ingraph(sqlite, postgres)]` mints one comparison per database,
3670/// named as a record's is, and a declaration naming none gets ONE comparison generic in its dialect.
3671///
3672/// # The conversion hook
3673///
3674/// `#[ingraph(filter = "path::to::Filter")]` names the filter seat this comparison is crossed into
3675/// FROM, and the door emits the map row that says so — `ToDatabaseComparison<Self, Db>`, exactly
3676/// what a record emits for its own emitted filter. Without it, a FIELD-level conversion word refuses
3677/// by name: a conversion refines a crossing, a crossing starts from a seat, and a refinement of
3678/// nothing is not a thing to write.
3679#[proc_macro_derive(Comparison, attributes(ingraph))]
3680pub fn comparison(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
3681 standalone(item, standalone::Face::Comparison)
3682}
3683
3684/// Give a HAND-WRITTEN struct the ORDER-BY face — one term per field, each carrying the direction it
3685/// runs in, plus the two questions every term answers.
3686///
3687/// See [`macro@Filter`] for the family's law, its vocabulary and its refusals.
3688///
3689/// All four halves of the face, where a record gates two: a record's `identity` rides the PAGE's own
3690/// law — a stored id and a SQL clause machine — and neither is a fact a hand-written struct has.
3691/// What is ordered here is the struct's own fields, and every term of it names one.
3692#[proc_macro_derive(OrderBy, attributes(ingraph))]
3693pub fn order_by(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
3694 standalone(item, standalone::Face::OrderBy)
3695}
3696
3697/// The three doors' shared body — read once, emit the face that was asked for.
3698///
3699/// NO host is emitted, which is the derive family's own rule: a derive is handed a COPY of the
3700/// declaration and the compiler keeps the original, so a refusal rides beside the type without
3701/// having to re-emit it — and the `#[ingraph(…)]` markers stay on the item, inert, where an
3702/// attribute macro's echo would have had to strip them. It is also what lets THREE derives read one
3703/// marker set without an ordering rule between them.
3704fn standalone(item: proc_macro::TokenStream, face: standalone::Face) -> proc_macro::TokenStream {
3705 let input = syn::parse_macro_input!(item as syn::DeriveInput);
3706 standalone::parse(&input, face)
3707 .map_or_else(
3708 |refused| refused.to_compile_error(),
3709 |model| standalone::emit(&model, face),
3710 )
3711 .into()
3712}