ingraph_codegen/tower.rs
1//! The TOWER declaration's emission: the CONNECTIVITY, which is what makes a question pipeline a
2//! compile-time theorem, and the WALK that spends it.
3//!
4//! ```ignore
5//! #[ingraph::tower(question(type = "String"))]
6//! pub struct ClipText {
7//! #[ingraph(answer = "Vec<String>")] tokenize: Tokenize,
8//! #[ingraph(answer = "Vec<f32>", async)] encode: ClipTextTower,
9//! }
10//!
11//! impl SearchTower for ClipText
12//! where
13//! Tokenize: Serves<String, Vec<String>>, // spanned at `tokenize`
14//! ClipTextTower: AsyncServes<Vec<String>, Vec<f32>>, // spanned at `encode`
15//! {
16//! type Question = String;
17//! type Answer = Vec<f32>;
18//! type Steps = ClipText;
19//! }
20//!
21//! pub enum ClipTextError {
22//! Tokenize(<Tokenize as Serves<String, Vec<String>>>::Error),
23//! Encode(<ClipTextTower as AsyncServes<Vec<String>, Vec<f32>>>::Error),
24//! }
25//! ```
26//!
27//! # THE AMENDMENT: a tower MAY FAN, and every fan folds before the mouth
28//!
29//! The tower law gained its amendment with the search pipeline's design: **a tower may contain
30//! FANNING SEGMENTS — expansion × lane routing — and every fan must fold before the tower's mouth,
31//! so the OUTER contract stays 1 → 1.** A segment is opened by a step word ([`Fan`]) and closed by
32//! the walk, which is why no word names a fold: where it happens is the law's, not an author's.
33//!
34//! **TODAY'S TOWERS ARE THE DEGENERATE CASE**, and that is a fact about this file rather than a
35//! promise: a declaration that writes no fan word has [`StepModel::fan`] [`None`] at every step,
36//! [`TowerModel::fanned`] answers false, and not one line of the emission below asks. The
37//! expansion such a tower gets is the expansion it got before the amendment, token for token.
38//!
39//! **THE FAN WALK IS HERE** — `fanned_body` below emits the nesting: the widening once, the
40//! crossing per arm, the tail per `(arm × lane)` cell, and the fold that closes every segment before
41//! the mouth.
42//!
43//! **AND SO IS THE ASSEMBLY ROW.** `assembly` emits the third impl a declaration states: the GATE
44//! (`check`, one reading per declared stage word, at that step's own field) and the UNIFORM RUN
45//! (`run`, the walk at an arity that does not move with the step count — which is what a search
46//! recipe's resolver can call and `walk` itself never was). The gate is EMITTED and not a roster
47//! row, and that is the fan model's own note read back: what a gate reads is a SEAT, and a seat is a
48//! value no `const` could carry across the expansion wall. A tower that opened no segment emits NO
49//! gate and inherits the row that refuses nothing.
50//!
51//! # ⟂ THE STAGE BEFORE THE FAN: a step that ANNOTATES rather than transforms
52//!
53//! A third step word opens a third stage, and it is the one whose ends are the SAME TYPE.
54//! `annotate(type = "…")` says *this step hands back the question it was given, one fact richer* —
55//! and the fan words downstream READ that fact, which is the whole reason the stage exists and
56//! cannot be an ordinary hop: a step's answer travels downstream, so a datum a WIDENING needs
57//! cannot arrive as the answer of a step that runs after it.
58//!
59//! The seat is [`StepModel::annotation`] and the order is [`Stage::Annotate`], which sorts before
60//! both fan words. Three consequences, all emitted below: the chain's type does NOT move across the
61//! step (`flows`), the walk asks the QUESTION before it calls the operator (`annotating`), and the
62//! step is an ordinary `Serves`/`AsyncServes` hop at both ends — so a `Door` onto a graph resident
63//! mounts here with no bridge and no wrapper, which is what the resident-hop stage was named for.
64//!
65//! # THE CHAIN IS DERIVED, so there is nothing for two words to disagree about
66//!
67//! One question is written — the tower's — and one answer per step. Every question after the first
68//! IS the answer before it, so an author never states an adjacency and the emission never checks
69//! one: what it does is DEMAND each hop, at the type the chain arrived at. A step that does not
70//! serve the question it is handed is `E0277` at the impl, and the predicate carries that step's
71//! own span, so the caret is on the field an author has to change.
72//!
73//! A trivially-false `where` predicate on a concrete impl is a hard error on stable — that is what
74//! puts the refusal AT THE IMPL rather than leaving an impl that silently never applies — and it is
75//! why the connectivity is stated as a `where` clause rather than as a helper call beside it.
76//!
77//! # THE WORD SELECTS THE FACE, one step at a time
78//!
79//! A bare step field binds the blocking [`Serves`]; `#[ingraph(async)]` binds [`AsyncServes`].
80//! This is the fifth position in the framework where a word chooses a face — after
81//! `source(async)`, `handler(async)`, `operator(async)` and `resource(async)` — and it is the first
82//! that is PER FIELD rather than per declaration, which is the whole of what makes a MIXED tower
83//! expressible: a blocking tokenizer and an awaited encoder are one chain.
84//!
85//! Words CHOOSE; bounds PROVE. Nothing here checks that a step's body really is awaited — a word
86//! that lied names a face the type does not wear, and the same `E0277` on the same step field says
87//! so.
88//!
89//! # THE WORDS ARE OMISSIBLE, and what fills their place is a PROJECTION
90//!
91//! `question(type = "…")` and `answer = "…"` are OVERRIDE words. A step's type may carry its own
92//! canonical line — `impl DefaultServe for Tokenize { type Question = …; type Answer = …; }`, the
93//! one-time *what this server is usually asked* — and a declaration that omits a word gets that
94//! line's projection wherever the written type would have gone:
95//!
96//! ```ignore
97//! #[ingraph::tower] // no question: step0's canonical one
98//! pub struct ClipText {
99//! tokenize: Tokenize, // no answer: `<Tokenize as DefaultServe>::Answer`
100//! #[ingraph(async)] encode: ClipTextTower,
101//! }
102//! ```
103//!
104//! **SELECTION NEVER COMES FROM INFERENCE.** `DefaultServe` takes no parameter, so
105//! `<Tokenize as DefaultServe>::Answer` is one concrete type rather than a variable the compiler is
106//! asked to solve for. A step with several `Serves` impls is therefore no more ambiguous omitted
107//! than written — `E0283` is not reachable by this road, and a chain still selects among a step's
108//! impls by the types the declaration arrived at.
109//!
110//! **THE CHAIN'S `where` CLAUSE STILL NAMES FACES AND NOTHING ELSE**, which is what makes the
111//! canonical line free of a mode. `DefaultServe`'s own supertrait is the BASE `Serve` — the seat a
112//! server's knobs sit in — and never a face, so an awaited-only server can declare its canonical
113//! line and a blocking one can declare the same. Landing that supertrait on a face instead would
114//! make the omissible word available only to steps wearing that face, and the shipped towers in
115//! this tree wear the awaited one: a declaration word available in only one mode is a mode-coupled
116//! authoring surface, which is the thing *the word selects the face* exists to prevent.
117//!
118//! What proves the canonical line HONEST is therefore not the supertrait but this emission's own
119//! predicate: an omitted `answer` puts `<Ty as DefaultServe>::Answer` on both sides of the hop, so
120//! a server whose canonical line names a `Q → A` it does not serve is `E0277` at that step's field,
121//! exactly where a written word that lied would be.
122//!
123//! # THE HEAD'S OWN `answer` — the one word here that DECIDES NOTHING
124//!
125//! ```ignore
126//! #[ingraph::tower(question(type = "String"), answer = "Vec<f32>")]
127//! pub struct ClipText { … } // ← what this tower is FOR, said at its head
128//! ```
129//!
130//! A tower's answer is DERIVED — it is the last step's, and no word can make it anything else. So
131//! this word is not a third override beside the two above: what it writes down is an INTENT, and
132//! what the emission does with it is demand that the derivation agree. That is a DOUBLE ENTRY, the
133//! source layer's own shape one axis over: the WORD is what a reader, a manifest front end and a
134//! search recipe's author see, the DERIVATION is what the compiler resolves a binding through, and
135//! neither can mint the other — so the join is written as one bound, and the two are checked against
136//! each other AT THE DECLARATION.
137//!
138//! | written | what happens |
139//! |---|---|
140//! | `answer = "Vec<f32>"` over a chain arriving at `Vec<f32>` | it compiles, and costs nothing |
141//! | `answer = "Vec<f32>"` over a chain arriving at `Vec<f64>` | `E0271` at the WORD |
142//! | no word | nothing is emitted and nothing is checked |
143//!
144//! **WHAT IT BUYS is WHERE the drift is reported, and never whether it is.** A tower whose last step
145//! quietly moved is already caught — by the binding that named the coordinate type it expected —
146//! but that refusal lands in the recipe, at a declaration whose author changed nothing. The pin puts
147//! the same fact at the tower, beside the step that moved. So the two ends of the entry each name
148//! it, which is what `tests/tower_pin` holds.
149//!
150//! **The word is OPTIONAL and a tower that omits it pays nothing**: no bound, no obligation, and not
151//! one token in the expansion. Absence is a road here as it is above — a tower whose answer is
152//! whatever its steps arrive at has an intent nobody needed to write down.
153//!
154//! It is spent through [`SearchTower`]'s own `Answer` seat rather than through a fresh one, which is
155//! what keeps the pin honest for a chain written EITHER way: a written last `answer` and a projected
156//! canonical line are the same associated type by the time this bound is resolved, so a wholly
157//! canonical tower states its intent once here and has every step's line checked against it.
158//!
159//! # THE WALK'S FACE IS THE OR OF ITS STEPS'
160//!
161//! The mutation node's assembled face one layer over, verbatim: a tower whose every step is
162//! blocking walks in a blocking function, and one awaited step makes the whole walk awaited. The
163//! dividend is the same one — a deployment walking a wholly synchronous tower needs no runtime —
164//! and so is the reason it is an OR rather than *always async*: an awaited walk is the more general
165//! and the more expensive shape, and paying for it where nothing awaits would be the framework
166//! choosing a runtime on an application's behalf.
167//!
168//! | the tower's steps | the walk |
169//! |---|---|
170//! | every one blocking | `fn walk(…)` |
171//! | at least one awaited | `async fn walk(…)` |
172//!
173//! # WHY THE STEPS ARE PARAMETERS AND NOT `&mut self`
174//!
175//! `type Steps = ClipText` says the declaration holds its own servers, and a walk taking `&mut
176//! self` would still compile. The parameters are what make the walk callable by a deployment that
177//! holds its steps ANYWHERE — one behind a door, one in a registry, one on the stack — and a caller
178//! that does hold the struct passes `&mut tower.tokenize, &mut tower.encode`, which the borrow
179//! checker takes as the disjoint borrows they are.
180//!
181//! A step's PARAMETER is positional and `__`-pinned, so a field called `question` or `options`
182//! cannot shadow the two seats it sits between. `walk` itself is the declaration's own name and is
183//! the one thing this expansion adds to a declaring scope: a tower whose author already wrote an
184//! inherent `walk` is `E0592` naming both, which is the honest collision rather than a silent
185//! shadow.
186//!
187//! # THE WALK REFUSES IN THE TOWER'S OWN SUM, one arm per step
188//!
189//! A chain of N hops has N error types and one `Result` has one. The answer is a SUM the
190//! declaration mints: `<Tower>Error`, an arm per step named after the step's field, each carrying
191//! that step's own `Serves::Error` / `AsyncServes::Error` PROJECTION. The assembled face's revived
192//! node sum one layer over, at the one grain a tower has.
193//!
194//! A projection rather than an erasure is the whole of what this buys. The alternative — one named,
195//! boxed refusal — costs a bound at every step (`Error + Send + Sync + 'static`) and hands a caller
196//! a `dyn` it can only print; the sum costs nothing at the declaration and hands a caller back the
197//! very type the step declared, so `match` on the arm reaches the error's own data.
198//!
199//! What the sum does demand is one thing, at one place: `source` reaches the cause, so a step's
200//! error has to BE an error. That demand lands at the step's own field, per `Serves::Error`'s own
201//! discipline — bound-free where it is DECLARED, demanded where it is SPENT.
202//!
203//! `<Tower>Error` is minted in the declaring scope, so a tower beside an author's own `<Tower>Error`
204//! is `E0428` naming both — the honest collision the walk's own `E0592` already takes.
205//!
206//! It takes the DECLARATION's visibility, which makes a step's own visibility matter in a way the
207//! walk's parameters did not: an enum arm is exactly as public as its enum, so a `pub` tower over a
208//! private step is `E0446` rather than the `private_interfaces` lint. That is the projection's price
209//! and it is the honest one — a tower published across a crate boundary publishes what its steps
210//! refuse with, because that is what its callers have to match on.
211//!
212//! # THE TOWER'S OWN OPTIONS — one field per step, and the walk is what projects it
213//!
214//! `Serve::Options` is per SERVER and the walk's tail seat is per TOWER, so the declaration mints
215//! the object that joins them: `<Tower>StepOptions`, ONE FIELD PER STEP, each field the projection
216//! `Option<<Step as Serve>::Options>` of that step's own seat. A caller names some, all or none of
217//! them in one value, and the walk hands each hop the field belonging to it:
218//!
219//! ```ignore
220//! pub struct ClipTextStepOptions {
221//! tokenize: Option<<Tokenize as Serve>::Options>, // named through `with_tokenize`
222//! encode: Option<<ClipTextTower as Serve>::Options>, // and read back through `tokenize()`
223//! }
224//!
225//! ClipText::walk(question, &mut tokenize, &mut encode, Some(&options))
226//! ```
227//!
228//! # THE REQUEST'S OWN OPTIONS — one field per WORD, and the walk never learns it exists
229//!
230//! The object above is keyed by STEP and named at INSTALL. Its twin is keyed by the declaration's own
231//! WORDS and named per REQUEST: `<Tower>SearchOptions`, whose rows are the FRAMEWORK's knobs — a walk
232//! budget always, an arm weight where `expand` was written, a lane emphasis where `route(…)` named
233//! the shipped weighted fan.
234//!
235//! ```ignore
236//! pub struct ClipTextSearchOptions {
237//! budget: Option<SearchBudget>, // ALWAYS — no word writes it and no word takes it away
238//! arm_weight: Option<f64>, // `expand = "Synonyms"` minted this
239//! }
240//! ```
241//!
242//! **BOTH OBJECTS EXIST BECAUSE ONLY ONE OF THEM CAN CROSS.** A step's seat is the application's own
243//! type and whether it is `()` is a fact only the compiler holds, so the step-keyed object has no
244//! wire face a macro could mint. Every row of the word-keyed one is a type this framework owns, so
245//! all of it crosses — and the words that key it are HERE, which is why it is minted at the tower
246//! grammar and not at the recipe that publishes it.
247//!
248//! The WALK's arity, parameters and hand-call road are untouched by any of it: the emitted `run`
249//! composes tier three into a step-keyed package (`ArmWeights::over`) or into this read's own minted
250//! router (`with_emphasis`) and hands the walk exactly what it always took.
251//!
252//! **`None` IS A LEVEL, at both grains, and it means the same thing at each**: *this call named
253//! nothing*, under which a step runs at its own floor. A walk handed no options at all hands every
254//! hop `None`; a walk handed options that named nothing FOR ONE STEP hands that hop `None` too. The
255//! walk never invents a default on a step author's behalf, which is why the fields are `Option` and
256//! not the bare seat — a bare one would need `Default`, and a projected seat is bound-free by
257//! `Serve::Options`' own discipline.
258//!
259//! **A `()`-SEATED STEP STILL HAS A FIELD, and that is the half-row law's Rust half.** Whether
260//! `<Step as Serve>::Options` is `()` is a fact only the COMPILER holds — this emission sees a type
261//! and never resolves it — so the struct carries a row for every step and the `()` ones are
262//! zero-sized and unreadable. What a `()` seat publishes NOTHING of is the WIRE row, and that law is
263//! already shipped one emitter over: [`fuse::Row`](crate::fuse::Row) carries a `crosses` flag, its
264//! Rust struct keeps every field, and its `InputObject` face publishes only the rows that cross —
265//! a row that does not is simply [`None`] on the way in. The division here is the same one, with a
266//! harder half for whoever emits the wire face: `fuse`'s non-crossing row is a FRAMEWORK type it
267//! recognises by name, and a step's seat is a projection of somebody else's, so the decision moves
268//! to where the recipe wires the arm.
269//!
270//! A caller who nonetheless names knobs for a `()`-seated step is refused at that step's own
271//! `with_…`, whose parameter IS the seat: *expected `()`, found `Flow`*, with the caret on the knobs
272//! and `note: method defined here` on the step's own field. `tests/tower_knobs` pins it.
273//!
274//! # THE RECORD — `DeclaredTower`, and why the tokens are restated
275//!
276//! A search recipe binding `crate::ClipText` expands in a pass that has never seen these tokens, so
277//! four facts it needs are STATED rather than guessed: `ALL_SYNC` (whether the walk it emits is
278//! awaited), `StepOptions` and `SearchOptions` (the two objects above, which a recipe could otherwise
279//! only reach by mangling a name), and `STEPS` (the roster, in declaration order). The two ENDS are
280//! not restated — the record's supertrait is `SearchTower`, which already carries them.
281//!
282//! [`Serves`]: https://docs.rs/ingraph
283//! [`AsyncServes`]: https://docs.rs/ingraph
284//! [`SearchTower`]: https://docs.rs/ingraph
285
286use quote::{quote, quote_spanned};
287
288use crate::emit::respan;
289
290#[cfg(test)]
291mod tests;
292
293/// ONE STEP of a tower — the field that holds the server, what it answers, and which face it wears.
294///
295/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a
296/// manifest front end later reach the same emitter.
297#[derive(Debug, Clone)]
298pub struct StepModel {
299 /// The field that holds this step's server — the step's ONE name, and the span every refusal
300 /// about this step is reported at.
301 pub field: syn::Ident,
302 /// The server's type, as the field declared it.
303 pub ty: syn::Type,
304 /// What this step ANSWERS — the `answer = "…"` word, and the next step's question.
305 ///
306 /// [`None`] where the word was OMITTED, which is not a gap: the answer is then the step's own
307 /// canonical line, `<Ty as DefaultServe>::Answer`, and the emission spells that projection
308 /// wherever it would have spelled the written type. A tower's chain is derived from these and
309 /// from the tower's own question either way, so nothing here is a pair that could disagree.
310 pub answer: Option<syn::Type>,
311 /// Whether this step wore the `async` word — which is what names the face its hop demands.
312 pub awaited: bool,
313 /// **THE FAN THIS STEP OPENS**, or [`None`] where the step is an ordinary 1 → 1 hop.
314 ///
315 /// A step's POSITION in [`TowerModel::steps`] is the segment's position, and there is no second
316 /// seat that could disagree with it about where a fan starts. What a segment ENDS at is the
317 /// tower's own mouth: the amendment's law is that every fan folds before it, so the fold is a
318 /// fact of the walk rather than a word an author writes, and nothing here names one.
319 pub fan: Option<Fan>,
320 /// ⟂ **WHAT THIS STEP ANNOTATES THE QUESTION WITH** — the `annotate(type = "…")` word's type, or
321 /// [`None`] where the step opens no annotation stage.
322 ///
323 /// A SEPARATE SEAT FROM [`fan`](Self::fan), and that separation is the model refusing to lie
324 /// about itself: [`Fan`] is *one fan segment*, and an annotation neither widens nor crosses. What
325 /// the two seats share is [`Stage`] — the pipeline's ORDER is the one thing all three words are
326 /// about — so [`stage`](Self::stage) reads whichever seat is filled and the order check reads
327 /// only that.
328 ///
329 /// A step fills AT MOST ONE of the two. Both written is refused at the front end, where the
330 /// declaration that wrote them can be pointed at.
331 pub annotation: Option<syn::Type>,
332}
333
334/// ONE ROW OF A TOWER'S REQUEST PACKAGE — the Rust member, the wire word, the type and the sentence
335/// both faces spell.
336///
337/// A record rather than four parallel iterators, for the emitted packages' own reason one emitter
338/// over: the struct field, the accessor trio, the schema entry, the `parse` arm and the `to_value`
339/// arm are FIVE readings of one row, and a row carried as five lists is a row five places could come
340/// to disagree about.
341struct SearchRow {
342 /// The Rust member — what the struct field, the accessors and both wire arms are named after.
343 member: syn::Ident,
344 /// The word a schema publishes it under — the member's own, in the house's camel case.
345 wire: &'static str,
346 /// The row's type, spanned at the word that minted it.
347 ty: proc_macro2::TokenStream,
348 /// What this row IS, as one sentence both the rustdoc and the schema description spend.
349 noun: &'static str,
350 /// WHY a request would name it — the paragraph both the rustdoc and the schema description carry,
351 /// so a client reading the SDL and an author reading the docs are told the same thing.
352 why: &'static str,
353}
354
355impl StepModel {
356 /// **WHICH STAGE THIS STEP OPENS**, or [`None`] where it opens none and is an ordinary hop.
357 ///
358 /// The ONE reader of both segment seats, which is what keeps the order law a single comparison
359 /// over a single roster however many words open a stage.
360 #[must_use]
361 pub fn stage(&self) -> Option<Stage> {
362 match (&self.annotation, &self.fan) {
363 (Some(_), _) => Some(Stage::Annotate),
364 (None, Some(fan)) => Some(fan.stage()),
365 (None, None) => None,
366 }
367 }
368}
369
370/// **WHERE A FAN SEGMENT SITS IN THE PIPELINE'S OWN ORDER** — the ②-before-④ opinion, as data.
371///
372/// The framework owns this opinion now. A question is WIDENED before it is CROSSED, because the
373/// crossing turns a question into probes and a widening is an endomorphism over questions: an
374/// expansion after a routing would have to widen a probe, which is a different type in a different
375/// currency, chosen by whatever store the lane belongs to.
376///
377/// It is [`Ord`] BY DECLARATION ORDER, which is what makes the rule a comparison rather than a pair
378/// of hand-written arms — and what makes the next stage one variant rather than a rewrite. The
379/// resident-hop word the closed design records as stage ⟂ arrived exactly that way: one variant
380/// BEFORE [`Expand`](Self::Expand), and not one line of the check that reads this enum moved.
381#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
382pub enum Stage {
383 /// ⟂ — the question is ANNOTATED: one question in, THE SAME question out, one fact richer.
384 Annotate,
385 /// ② — the question WIDENS: one question in, several questions of the same type out.
386 Expand,
387 /// ④ — the question CROSSES: one question in, one probe per lane out.
388 Route,
389}
390
391impl Stage {
392 /// The WORD a declaration opens this stage with.
393 ///
394 /// Here rather than on [`Fan`], because a refusal about the ORDER names a stage it has no fan in
395 /// hand for: the check reads stages, and a sentence that hard-coded two spellings would start
396 /// lying the round a third stage arrives.
397 #[must_use]
398 pub const fn word(self) -> &'static str {
399 match self {
400 Self::Annotate => "annotate",
401 Self::Expand => "expand",
402 Self::Route => "route",
403 }
404 }
405
406 /// **WHY THIS STAGE RUNS WHERE IT DOES** — the clause an out-of-order refusal quotes.
407 ///
408 /// It hangs on the stage that was written LATE rather than on the pair, because that is what the
409 /// reason is a fact about: a widening comes before a crossing because of what a WIDENING is, and
410 /// an annotation comes before both because of what stages READ. A per-pair table would be `n²`
411 /// sentences for a rule that has `n`.
412 #[must_use]
413 pub const fn why_first(self) -> &'static str {
414 match self {
415 Self::Annotate => {
416 "a question is ANNOTATED before it is anything else, because the stages after it READ what \
417 it wrote — the widening's targets and the crossing's lanes both come off the annotation — \
418 and a step's answer travels downstream only, so a stage that filled the seat later would \
419 fill it for nobody"
420 }
421 Self::Expand => {
422 "a question is WIDENED before it is CROSSED, because a widening is an endomorphism over \
423 QUESTIONS and a crossing turns one into PROBES — so an expansion after a routing would \
424 have to widen a probe, in whatever currency the store behind that lane chose"
425 }
426 Self::Route => {
427 "a question is CROSSED last, because a crossing is what stops there being a question: what \
428 it answers is one probe per lane, and every stage of this pipeline that takes a question \
429 has already run"
430 }
431 }
432 }
433}
434
435/// **WHO CHOOSES THE LANES** — the router a `route(…)` mounted, shipped or the declaring crate's.
436///
437/// # The axis is CLOSED on the framework's side and OPEN past it
438///
439/// A BARE word is one of the routers this framework ships, and that vocabulary is closed for the
440/// reason every bare vocabulary in this grammar is: a word is a promise this crate can write the
441/// whole binding, which it can only keep for a type it SHIPS. A QUOTED PATH is every other router
442/// there is — a type the declaring crate wrote, named the way this grammar names every type it did
443/// not mint, with no vocabulary to be admitted to. MINT BARE, REFER QUOTED, read at one more
444/// position.
445///
446/// # There is no `Owed`-shaped axis here, and that is an ANSWER rather than an omission
447///
448/// The aggregate's fold vocabulary carries one: the framework knows what `summing` reads and what
449/// `counting` does not, so the grammar can refuse an entry that names the wrong thing. This
450/// position has no such fact to check. Every shipped router is built from the ROSTER alone — the
451/// lanes the slot already declares — and the one knob any of them has
452/// (`ScriptWeightedFan`'s emphasis) is the lane emphasis the closed design homed in the tower's own
453/// OPTIONS rather than at this word — and it lands there: the shipped weighted word mints a
454/// `lane_emphasis` row on `<Tower>SearchOptions`, read off the WORD rather than off an axis entry.
455/// So a shipped router owes its entry nothing beyond the wiring
456/// both halves of the entry already name, and an axis answering *nothing, for all three* would be a
457/// seat with one arm.
458///
459/// # The SHIPPED SPELLINGS are the types' own, in snake case
460///
461/// `fan_all`, `script_router`, `script_weighted_fan` — one word per shipped type, mechanically its
462/// name. The measure vocabulary's own note records that this grammar's other closed VALUE
463/// vocabularies are short nouns (`dedup(hash)`, `fold(max)`); a router is a NAMED TYPE a reader
464/// looks up rather than a concept with a short noun, so the spelling that cannot drift from the
465/// type it binds is the type's own. [`SHIPPED`](Self::SHIPPED) and [`shipped`](Self::shipped) are
466/// the whole of the roster, and the near-miss list, the printed roster and the refusal all read off
467/// them.
468#[derive(Debug, Clone)]
469pub enum Router {
470 /// `fan_all` — every lane asked, flat.
471 FanAll,
472 /// `script_router` — the text cut by writing system, and only the lanes it reached asked.
473 ScriptRouter,
474 /// `script_weighted_fan` — every lane asked, the ones the question is written in leaned on.
475 ScriptWeightedFan,
476 /// A router the declaring crate wrote, as `router = "path::to::Router"` named it.
477 ///
478 /// Nothing here resolves it, which is the mechanism rather than a limitation: two macro
479 /// expansions cannot see each other, so the path is EMITTED and rustc resolves it at the span of
480 /// the string its author wrote.
481 Declared(syn::Path),
482}
483
484impl Router {
485 /// The routers this framework ships, in the order a refusal lists them.
486 ///
487 /// The near-miss list for a bare word inside `route(…)` is read off this, so the words a
488 /// suggestion offers and the words a sentence names cannot drift apart.
489 pub const SHIPPED: [&'static str; 3] = ["fan_all", "script_router", "script_weighted_fan"];
490
491 /// The shipped router a bare word names, or [`None`] where the word is none of them.
492 #[must_use]
493 pub fn shipped(word: &str) -> Option<Self> {
494 match word {
495 "fan_all" => Some(Self::FanAll),
496 "script_router" => Some(Self::ScriptRouter),
497 "script_weighted_fan" => Some(Self::ScriptWeightedFan),
498 _ => None,
499 }
500 }
501
502 /// The word this router was written as — a shipped one's own spelling, or the declared path's.
503 #[must_use]
504 pub fn as_written(&self) -> String {
505 match self {
506 Self::FanAll => Self::SHIPPED[0].to_owned(),
507 Self::ScriptRouter => Self::SHIPPED[1].to_owned(),
508 Self::ScriptWeightedFan => Self::SHIPPED[2].to_owned(),
509 Self::Declared(path) => quote::ToTokens::to_token_stream(path).to_string(),
510 }
511 }
512
513 /// **THE TYPE A WORD NAMES**, as the emission spells it — a shipped router's path, or the
514 /// declaring crate's own verbatim.
515 ///
516 /// `question` is what the step is HANDED, and it fills the two shipped routers that carry a
517 /// question parameter. [`ScriptRouter`](Self::ScriptRouter) carries none — it is spelled for text
518 /// and says so in its own `Question = str` — so the argument goes unspent there, which is a fact
519 /// about those three types rather than a case this function invents.
520 ///
521 /// A DECLARED router is emitted exactly as it was written and resolved by rustc at the span of the
522 /// string its author wrote, which is the same mechanism [`Declared`](Self::Declared) states: two
523 /// macro expansions cannot see each other, so nothing here looks a path up.
524 #[must_use]
525 pub fn spelled(
526 &self,
527 krate: &syn::Path,
528 question: &proc_macro2::TokenStream,
529 ) -> proc_macro2::TokenStream {
530 match self {
531 Self::FanAll => quote!(#krate::__private::route::FanAll<#question>),
532 Self::ScriptRouter => quote!(#krate::__private::route::ScriptRouter),
533 Self::ScriptWeightedFan => quote!(#krate::__private::route::ScriptWeightedFan<#question>),
534 Self::Declared(path) => quote!(#path),
535 }
536 }
537}
538
539/// **ONE FAN SEGMENT** — which kind of fan a step opens, and the types the segment is wired with.
540///
541/// The amendment's law in the model: a tower MAY contain fanning segments, every fan folds before
542/// the tower's mouth, and the OUTER contract stays 1 → 1. What is recorded here is the OPENING —
543/// which segments a declaration wrote, what mounts each, and (through the step that holds it) where
544/// it starts. The walk that spends them is the emission's, and the fold is the walk's.
545///
546/// # Every question a fan segment must answer is answered HERE, and none by silence
547///
548/// | the question | where the answer is |
549/// |---|---|
550/// | which KIND of fan | this enum's own variant, and [`stage`](Self::stage) for the order it sits in |
551/// | what MOUNTS it | [`Expand::expander`](Self::Expand) / [`Route::router`](Self::Route) |
552/// | what it is WIRED TO | [`Route::slot`](Self::Route) — and ② is wired to nothing, because an endomorphism crosses no boundary |
553/// | WHERE it opens | the position of the [`StepModel`] that holds it |
554/// | which WORD wrote it | [`word`](Self::word) |
555/// | which FACE it wears | the SEAM's and never the step's `async` word — see below |
556/// | where it FOLDS | the tower's mouth, by the amendment's law; no word names one |
557/// | what a reader ACROSS THE WALL sees | nothing, on purpose — see below |
558/// | what a shipped router OWES its entry | nothing, for all three — see [`Router`] |
559///
560/// # WHAT A READER ACROSS THE EXPANSION WALL SEES, which is STILL NOTHING — and the assembly is why
561///
562/// `DeclaredTower` — the record a search recipe reads a bound tower through — is deliberately not
563/// extended here. Its three facts are what a RECIPE needs to write a binding (the walk's face, the
564/// options object, the roster), and a recipe binds a tower by its outer contract, which the
565/// amendment leaves 1 → 1 exactly as it was.
566///
567/// The assembly has since arrived, which is when that sentence was owed a re-reading, and the answer
568/// held: what the assembly needs is to read a fan step's own FIELD — is an expander mounted, does
569/// this fan have a router — and no roster row could carry that, because a row is a `const` and a
570/// seat is a value. So the gate is EMITTED, where the field is concrete, and what crosses the wall
571/// is the two methods of [`AssembledTower`] rather than a fact about the words. A fan row on the
572/// record would still be a fact nothing reads.
573///
574/// [`AssembledTower`]: https://docs.rs/ingraph
575///
576/// # THE FAN'S FACE IS THE SEAM'S, and the step's own word still means what it meant
577///
578/// A step's `async` names the face THAT STEP'S SERVER wears, and a fan word does not touch it.
579/// What face the FAN itself wears is not an author's to choose: routing is pure computation over a
580/// question and a roster, so `LaneRouter` has one face and it is the blocking one, and the
581/// expansion seam's call seat is the awaited `AsyncQueryExpander` that a blocking expander reaches
582/// through the lift bridge. Neither is a word, so neither is a seat here.
583///
584/// # The two halves are DELIBERATELY UNLIKE, and this model does not make them rhyme
585///
586/// An EXPANDER is a hook — a policy a deployment picks at launch, held erased — so ② names one
587/// type and the declaration's word is the DEFAULT a deployment may override. A ROUTER is a
588/// capability — known at the call, mounted monomorphised — so ④ names the router AND the slot it is
589/// wired to, because what makes a mis-wiring `E0271` at the seat rather than a conversion in the
590/// middle is an EQUALITY between two types this model has to be holding both of.
591#[derive(Debug, Clone)]
592pub enum Fan {
593 /// ② **EXPAND** — the endomorphism: one question in, several questions of the SAME type out.
594 Expand {
595 /// The expander this declaration DEFAULTS to, as `expand(type = "…")` named it.
596 ///
597 /// A path and never a bare word: this framework ships no expander at all, so there is nothing
598 /// for a bare vocabulary to name. A synonym table, a spelling fixer and a translator are all
599 /// the declaring crate's, which is why the seam is public and the escape is the only road.
600 expander: syn::Path,
601 },
602 /// ④ **ROUTE** — the crossing: one question in, one probe per lane out.
603 Route {
604 /// Who chooses the lanes — a shipped router's bare word, or a path to the declaring crate's.
605 router: Router,
606 /// The SLOT whose lanes are asked, as `slot = "…"` named it.
607 ///
608 /// This is the other half of the equality the wiring is checked by: a router mounted here
609 /// answers in `<Slot as LanedStore>::Probe` and anything else is `E0271` at the seat. The slot
610 /// is the pairing `(elected field × engine)` a declaration's own expansion minted, so it is a
611 /// type this declaration did not mint and it arrives QUOTED.
612 slot: syn::Path,
613 },
614}
615
616impl Fan {
617 /// WHICH STAGE this segment is — the ②-before-④ order, read off the fan itself.
618 #[must_use]
619 pub const fn stage(&self) -> Stage {
620 match self {
621 Self::Expand { .. } => Stage::Expand,
622 Self::Route { .. } => Stage::Route,
623 }
624 }
625
626 /// The WORD that wrote this fan, as a declaration spells it.
627 ///
628 /// The STAGE's own, rather than a second table: a refusal about a fan and a refusal about the
629 /// order between two both name a word, and a spelling written twice is a spelling two places
630 /// could disagree about.
631 #[must_use]
632 pub const fn word(&self) -> &'static str {
633 self.stage().word()
634 }
635}
636
637/// A validated tower declaration, ready to emit.
638///
639/// PLAIN, for [`StepModel`]'s reason.
640#[derive(Debug, Clone)]
641pub struct TowerModel {
642 /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
643 /// another.
644 pub krate: syn::Path,
645 /// The declared type — what the connectivity is stated over and what the walk is minted on.
646 pub name: syn::Ident,
647 /// The declaration's own visibility, which the walk takes: a tower nobody outside the crate can
648 /// name has no walk anybody outside it could call.
649 pub vis: syn::Visibility,
650 /// What the WHOLE tower is asked — the `question(type = "…")` word, and the first step's
651 /// question.
652 ///
653 /// [`None`] where the word was OMITTED, on [`StepModel::answer`]'s road: the tower is then asked
654 /// what its FIRST STEP is canonically asked, `<Ty as DefaultServe>::Question`.
655 pub question: Option<syn::Type>,
656 /// **THE HEAD PIN** — the `answer = "…"` word at the tower, and the one word in this model that
657 /// DECIDES NOTHING.
658 ///
659 /// A tower answers what its LAST STEP answers, whatever is written here: this seat holds an
660 /// author's stated INTENT, and what the emission does with it is demand that the derivation agree.
661 /// See the module note for the double entry it is one half of.
662 ///
663 /// [`None`] where the word was omitted, under which nothing is emitted and nothing is demanded —
664 /// so it is the one seat whose absence costs a declaration not one token.
665 pub answer: Option<syn::Type>,
666 /// The steps, in declaration order. NEVER EMPTY: a tower with no step is refused at the front
667 /// end, there being no chain to state and no answer to name.
668 pub steps: Vec<StepModel>,
669}
670
671impl TowerModel {
672 /// The CONNECTIVITY, the HEAD PIN, the TWO OPTIONS OBJECTS, the RECORD, the REFUSAL SUM, the WALK
673 /// and the ASSEMBLY ROW — see the module note for what each says.
674 ///
675 /// The pin comes second because it is a claim ABOUT the impl above it, and it is [`Option`]
676 /// because a tower that wrote no head word emits nothing here at all. The assembly row comes LAST
677 /// because it is the only one that CALLS another: its run is the walk above it at a fixed arity.
678 #[must_use]
679 pub fn emit(&self) -> proc_macro2::TokenStream {
680 let connectivity = self.connectivity();
681 let pin = self.pin();
682 let options = self.options();
683 let asked = self.search_options();
684 let declared = self.declared();
685 let refusal = self.refusal();
686 let rendering = self.rendering();
687 let walk = self.walk();
688 let assembly = self.assembly();
689 quote! {
690 #connectivity
691 #pin
692 #options
693 #asked
694 #declared
695 #refusal
696 #rendering
697 #walk
698 #assembly
699 }
700 }
701
702 /// Whether the walk is AWAITED — the OR law over the steps' own words, AND the widening.
703 ///
704 /// **A WIDENING MAKES A WALK AWAITED WHATEVER ITS STEPS SAY.** The expand seam's call face is the
705 /// awaited [`AsyncQueryExpander`], which is where a deployment's own expander reaches a model; a
706 /// blocking one rides it through the lift bridge and the bridge runs one way, there being no
707 /// `block_on` in this framework. So the segment's face is not an author's word to choose, and this
708 /// is where the OR law reads it — the same law, one more term.
709 ///
710 /// [`AsyncQueryExpander`]: https://docs.rs/ingraph
711 #[must_use]
712 pub fn awaited(&self) -> bool {
713 self.steps.iter().any(|step| step.awaited) || self.expand_at().is_some()
714 }
715
716 /// WHERE THE WIDENING OPENS, or [`None`] where this tower opens none.
717 ///
718 /// One position and never a list: the grammar holds a tower to ONE segment of each kind, so the
719 /// first is the only one.
720 #[must_use]
721 pub fn expand_at(&self) -> Option<usize> {
722 self
723 .fans()
724 .find(|(_, _, fan)| fan.stage() == Stage::Expand)
725 .map(|(at, _, _)| at)
726 }
727
728 /// ⟂ WHERE THE ANNOTATION STAGE OPENS, or [`None`] where this tower opens none.
729 ///
730 /// One position and never a list, for [`expand_at`](Self::expand_at)'s reason at the one word
731 /// whose second occurrence would be dead rather than merely unlawful: fill-if-absent means a
732 /// second stage over the same seat runs only where the first did not fill it, which is nowhere.
733 #[must_use]
734 pub fn annotate_at(&self) -> Option<usize> {
735 self.steps.iter().position(|step| step.annotation.is_some())
736 }
737
738 /// WHERE THE CROSSING OPENS, or [`None`] where this tower opens none.
739 #[must_use]
740 pub fn route_at(&self) -> Option<usize> {
741 self
742 .fans()
743 .find(|(_, _, fan)| fan.stage() == Stage::Route)
744 .map(|(at, _, _)| at)
745 }
746
747 /// **EVERY FAN SEGMENT THIS TOWER OPENS**, in declaration order — the position, and the fan.
748 ///
749 /// The position is the step's own index, which is the segment's: a fan is a fact ABOUT a step, so
750 /// there is one roster and the place a segment starts is where it sits in it.
751 pub fn fans(&self) -> impl Iterator<Item = (usize, &StepModel, &Fan)> {
752 self
753 .steps
754 .iter()
755 .enumerate()
756 .filter_map(|(at, step)| step.fan.as_ref().map(|fan| (at, step, fan)))
757 }
758
759 /// Whether this tower FANS AT ALL — false for every tower written before the amendment, which is
760 /// what makes those the degenerate case rather than a case.
761 #[must_use]
762 pub fn fanned(&self) -> bool {
763 self.steps.iter().any(|step| step.fan.is_some())
764 }
765
766 /// The STEP-KEYED options object's name — the declaration's own, with `StepOptions` after it.
767 ///
768 /// Derived rather than declared, for [`error_name`](Self::error_name)'s reason and with the same
769 /// price: this is one of the names a tower mints in its declaring scope, so a tower beside an
770 /// author's own `<Tower>StepOptions` is `E0428` naming both.
771 ///
772 /// The word STEP is load-bearing rather than decorative. There are two options objects now and
773 /// they are two CLOCKS — this one is keyed by step and named at INSTALL, and
774 /// [`search_options_name`](Self::search_options_name)'s is keyed by the declaration's own words and
775 /// named per REQUEST — so a bare `<Tower>Options` would have been the one name that could not say
776 /// which of them a reader was holding.
777 #[must_use]
778 pub fn step_options_name(&self) -> syn::Ident {
779 quote::format_ident!("{}StepOptions", self.name, span = self.name.span())
780 }
781
782 /// The WORD-KEYED options object's name — the declaration's own, with `SearchOptions` after it.
783 ///
784 /// [`step_options_name`](Self::step_options_name)'s twin at the other clock, minted under the same
785 /// collision rule and for the same reason.
786 #[must_use]
787 pub fn search_options_name(&self) -> syn::Ident {
788 quote::format_ident!("{}SearchOptions", self.name, span = self.name.span())
789 }
790
791 /// **WHETHER THIS DECLARATION'S ④ WORD NAMED THE SHIPPED WEIGHTED FAN** — the one token that mints
792 /// a lane-emphasis row.
793 ///
794 /// TOKEN-KEYED and never type-resolved, which is the whole of why the row is mintable at all: a
795 /// bare word in `route(router = …)` is one of the routers this framework SHIPS, so the emitter
796 /// knows the type, its knob and its constructor. A QUOTED PATH is the declaring crate's own router
797 /// and this answers [`None`] for it — not because such a router has no knobs but because nothing
798 /// here can know what they are, and a published field the emission could never spend is worse than
799 /// no field at all.
800 #[must_use]
801 pub fn weighted_crossing(&self) -> Option<(usize, &StepModel)> {
802 self.fans().find_map(|(at, step, fan)| match fan {
803 Fan::Route {
804 router: Router::ScriptWeightedFan,
805 ..
806 } => Some((at, step)),
807 Fan::Route { .. } | Fan::Expand { .. } => None,
808 })
809 }
810
811 /// The refusal sum's name — the declaration's own, with `Error` after it.
812 ///
813 /// Derived rather than declared, which is the assembled face's rule one layer over: the
814 /// declaration's name IS the vocabulary's name, and a second word for it would be a name two
815 /// spellings could disagree about. Minted at the declaration's own ident, so a tower beside an
816 /// author's existing `<Tower>Error` collides where a reader can see both.
817 #[must_use]
818 pub fn error_name(&self) -> syn::Ident {
819 quote::format_ident!("{}Error", self.name, span = self.name.span())
820 }
821
822 /// A step's ARM in the refusal sum — the field's own name, translated to a variant's casing.
823 ///
824 /// `heck`'s upper camel case rather than a raised initial, which is the assembled face's own
825 /// choice and law: a Rust field name is snake case by the language's convention rather than by
826 /// anybody's word, so re-casing it is a translation and not a rewrite of somebody's name.
827 fn variant(step: &StepModel) -> syn::Ident {
828 use heck::ToUpperCamelCase as _;
829 use syn::ext::IdentExt as _;
830
831 quote::format_ident!(
832 "{}",
833 step.field.unraw().to_string().to_upper_camel_case(),
834 span = step.field.span()
835 )
836 }
837
838 /// One seat of a step's own CANONICAL LINE, spelled as the projection it is.
839 ///
840 /// This is the whole mechanism of the omissible words: a written `answer = "…"` names the type
841 /// itself, and an omitted one names `<Ty as DefaultServe>::Answer`, which is a CONCRETE
842 /// projection rather than a variable the compiler is asked to solve for. Selection therefore
843 /// never comes from inference — a step with several `Serves` impls is still unambiguous, because
844 /// the canonical line is one line per TYPE and names no face.
845 ///
846 /// Spanned at the step's own field, so a type with no canonical line is `E0277` where the type
847 /// was written, and `DefaultServe`'s own `on_unimplemented` note is what names the two roads out.
848 fn canonical(&self, step: &StepModel, seat: &str) -> proc_macro2::TokenStream {
849 let at_field = step.field.span();
850 let ty = &step.ty;
851 let line = respan(
852 {
853 let krate = &self.krate;
854 quote!(#krate::__private::drive::DefaultServe)
855 },
856 at_field,
857 );
858 let seat = quote::format_ident!("{seat}", span = at_field);
859 quote_spanned!(at_field=> <#ty as #line>::#seat)
860 }
861
862 /// What the WHOLE tower is asked — the written word, or the first step's canonical question.
863 ///
864 /// The model is never built empty, so the last fallback is a shape rather than a case.
865 fn asked(&self) -> proc_macro2::TokenStream {
866 match (&self.question, self.steps.first()) {
867 (Some(question), _) => quote!(#question),
868 (None, Some(head)) => self.canonical(head, "Question"),
869 (None, None) => quote!(()),
870 }
871 }
872
873 /// What ONE STEP answers — the written word, or that step's own canonical answer.
874 fn answered(&self, step: &StepModel) -> proc_macro2::TokenStream {
875 step
876 .answer
877 .as_ref()
878 .map_or_else(|| self.canonical(step, "Answer"), |answer| quote!(#answer))
879 }
880
881 /// What the whole tower ANSWERS — the last step's answer, DERIVED and never declared.
882 ///
883 /// Named for what it is rather than for the word beside it, because there IS a word beside it now:
884 /// [`answer`](Self::answer) is an author's stated intent and this is what the chain arrives at, and
885 /// the whole of the head pin is that the second is demanded to be the first.
886 ///
887 /// The model is never built empty, so the fallback is a shape rather than a case: a hand-built
888 /// model with no step would state a tower answering nothing, which is what `()` says.
889 ///
890 /// # A FANNED TOWER ANSWERS THE FUSED LIST, and it is still ONE value
891 ///
892 /// The amendment's outer contract is 1 → 1, so the mouth hands back one thing — and what a fan
893 /// produces before it folds is N ranked streams, so the one thing is what the fold makes of them:
894 /// `Vec<Fused<Root, Evidence>>`. The two parameters are PROJECTED off the tail's own answer through
895 /// [`RankedStream`], because they are the tail author's types and this pass sees only the tokens
896 /// that named them — see [`tail`](Self::tail) for the seam's whole reason.
897 fn derived(&self) -> proc_macro2::TokenStream {
898 let Some(tail) = self.steps.last() else {
899 return quote!(());
900 };
901 let answers = self.flows(self.steps.len() - 1);
902 if !self.fanned() {
903 return answers;
904 }
905 let krate = &self.krate;
906 let at_field = tail.field.span();
907 let stream = respan(quote!(#krate::__private::retrieve::RankedStream), at_field);
908 let fused = respan(quote!(#krate::__private::retrieve::Fused), at_field);
909 quote_spanned! {at_field=>
910 ::std::vec::Vec<#fused<
911 <#answers as #stream>::Root,
912 <#answers as #stream>::Evidence,
913 >>
914 }
915 }
916
917 /// THE TAIL'S OWN ANSWER — what one `(arm × lane)` cell of a fan found, before the fold.
918 ///
919 /// The LAST step's, whatever else the tower does: a fan folds at the mouth, so the value the fold
920 /// is handed is the value the chain arrived at.
921 fn tail(&self) -> proc_macro2::TokenStream {
922 match self.steps.len().checked_sub(1) {
923 Some(last) => self.flows(last),
924 None => quote!(()),
925 }
926 }
927
928 /// What step `at` is HANDED: the tower's own question at the head of the chain, and what the step
929 /// before it HANDS ON everywhere after.
930 fn takes(&self, at: usize) -> proc_macro2::TokenStream {
931 match at
932 .checked_sub(1)
933 .filter(|before| *before < self.steps.len())
934 {
935 Some(before) => self.flows(before),
936 None => self.asked(),
937 }
938 }
939
940 /// **WHAT STEP `at` HANDS ON** — the chain's type on the far side of it, which is the next step's
941 /// question.
942 ///
943 /// For every step but one this is simply what that step ANSWERS. **⟂ is the exception, and being
944 /// the exception is what the stage IS**: an annotation step is asked a question and hands back the
945 /// same question, so the chain's type does not move across it and what it hands on is what it
946 /// took. That is why the seat has no `answer` word to read — there is nothing there a word could
947 /// decide, and the front end refuses one by name rather than accepting a second spelling of the
948 /// type one line above.
949 ///
950 /// It recurses through [`takes`](Self::takes) and terminates on the tower's own question: each
951 /// step asks only about the step BEFORE it, and step `0` asks nothing.
952 fn flows(&self, at: usize) -> proc_macro2::TokenStream {
953 match self.steps.get(at) {
954 Some(step) if step.annotation.is_some() => self.takes(at),
955 Some(step) => self.answered(step),
956 None => quote!(()),
957 }
958 }
959
960 /// The FACE this step's word chose, reached through the shelf.
961 fn face(&self, step: &StepModel) -> proc_macro2::TokenStream {
962 let krate = &self.krate;
963 if step.awaited {
964 quote!(#krate::__private::drive::AsyncServes)
965 } else {
966 quote!(#krate::__private::drive::Serves)
967 }
968 }
969
970 /// The tower's citizenship, and the chain in its `where` clause — one predicate per step, each
971 /// spanned at the field it is about.
972 fn connectivity(&self) -> proc_macro2::TokenStream {
973 let krate = &self.krate;
974 let name = &self.name;
975 let question = self.asked();
976 let answer = self.derived();
977 let hops = self.hops();
978 quote! {
979 impl #krate::__private::retrieve::SearchTower for #name
980 where
981 #(#hops,)*
982 {
983 type Question = #question;
984 type Answer = #answer;
985 type Steps = #name;
986 }
987 }
988 }
989
990 /// **THE CHAIN, AS PREDICATES** — one per step, each spanned at the field it is about.
991 ///
992 /// A function rather than a closure inside [`connectivity`](Self::connectivity) because the chain
993 /// is stated at TWO impls now: the citizenship, which is what it says, and the assembly row, which
994 /// RESTATES it in its own `where` clause so that a tower whose chain is broken earns no second
995 /// diagnostic there. Both spend one derivation, so no two impls can disagree about which hops a
996 /// tower has.
997 fn hops(&self) -> Vec<proc_macro2::TokenStream> {
998 let krate = &self.krate;
999 self
1000 .steps
1001 .iter()
1002 .enumerate()
1003 .flat_map(|(at, step)| {
1004 let at_field = step.field.span();
1005 let ty = &step.ty;
1006 let takes = self.takes(at);
1007 let answers = self.flows(at);
1008 // ⟂ **AN ANNOTATION STEP IS A HOP WITH BOTH ENDS PINNED TO ONE TYPE**, and one more predicate
1009 // beside it. The endomorphism is not an author's claim here — it is the STAGE, so the two ends
1010 // are written from `takes` alone and a server that answers something else is `E0277` at the
1011 // field naming the impl it does not have. The second predicate is what makes fill-if-absent
1012 // real: the question has to be able to SAY whether the caller already filled the seat, and a
1013 // question type that cannot is refused at the step rather than at whatever line first read it.
1014 if let Some(annotation) = &step.annotation {
1015 let seam = respan(
1016 quote!(#krate::__private::retrieve::AnnotatedQuestion),
1017 at_field,
1018 );
1019 let face = respan(self.face(step), at_field);
1020 return vec![
1021 quote_spanned!(at_field=> #ty: #face<#takes, #takes>),
1022 quote_spanned!(at_field=> #takes: #seam<#annotation>),
1023 ];
1024 }
1025 // A FAN STEP IS NOT A HOP, and that is the emission's own finding rather than a choice. Its
1026 // field holds the SEGMENT'S SEAT — the value a deployment assembles an expander or a router
1027 // into — and a seat answers no `Serves` verb, so what is demanded here is the CANONICAL LINE
1028 // that seat states, at both of the chain's ends. A widening's line is the endomorphism
1029 // (`Question = Answer = Q`), so a seat mounted for one question inside a chain carrying
1030 // another is `E0271` naming both, at the field.
1031 if step.fan.is_some() {
1032 let line = respan(
1033 {
1034 let krate = &self.krate;
1035 quote!(#krate::__private::drive::DefaultServe)
1036 },
1037 at_field,
1038 );
1039 // **ONLY THE ENDS A DECLARATION WROTE ARE BOUND**, and that is the language rather than a
1040 // choice: an omitted word makes the end the seat's OWN projection, so binding it would state
1041 // `T: DefaultServe<Answer = <T as DefaultServe>::Answer>` — a predicate that refers to
1042 // itself, which rustc reports as `E0275` *overflow evaluating the requirement* at the
1043 // attribute. What is left when both are omitted is the demand that the seat state a
1044 // canonical line at all, which is the one thing still worth saying.
1045 let mut bindings: Vec<proc_macro2::TokenStream> = Vec::new();
1046 if at > 0 || self.question.is_some() {
1047 bindings.push(quote_spanned!(at_field=> Question = #takes));
1048 }
1049 if step.answer.is_some() {
1050 bindings.push(quote_spanned!(at_field=> Answer = #answers));
1051 }
1052 let stated = if bindings.is_empty() {
1053 quote_spanned!(at_field=> #ty: #line)
1054 } else {
1055 quote_spanned!(at_field=> #ty: #line<#(#bindings),*>)
1056 };
1057 let mut demanded = vec![stated];
1058 // **THE DECLARED DEFAULT IS CHECKED HERE**, even though mounting it is the assembly's. What
1059 // `expand = "…"` names is the expander a deployment gets unless it names another, and the
1060 // one thing this pass can say about it is the one thing that matters: it must be able to
1061 // widen the question this chain is carrying. A table written for some other question type is
1062 // `E0277` at the field, in the round the word was written, rather than at whatever later
1063 // round tries to mount it.
1064 if let Some(Fan::Expand { expander }) = &step.fan {
1065 let krate = &self.krate;
1066 let seam = respan(
1067 quote!(#krate::__private::retrieve::AsyncQueryExpander),
1068 at_field,
1069 );
1070 demanded.push(quote_spanned!(at_field=> #expander: #seam<#takes>));
1071 }
1072 // **THE WIRING'S OWN EQUALITY**, and the reason the crossing names two things rather than
1073 // one: a router answers in some currency and a slot's lanes are asked in some currency, and
1074 // the whole of what makes a mis-wiring a compile error AT THE SEAT is that this predicate is
1075 // holding both halves. A router bolted to the wrong slot is `E0271` here, at the step's own
1076 // field, rather than a conversion failure somewhere in the middle of a read.
1077 if let Some(Fan::Route { router, slot }) = &step.fan {
1078 let krate = &self.krate;
1079 let router = router.spelled(krate, &takes);
1080 let seam = respan(quote!(#krate::__private::route::LaneRouter), at_field);
1081 let laned = respan(quote!(#krate::__private::lane::LanedStore), at_field);
1082 demanded
1083 .push(quote_spanned!(at_field=> #router: #seam<Routed = <#slot as #laned>::Probe>));
1084 }
1085 return demanded;
1086 }
1087 // The FACE is respanned rather than merely minted at the field, for the reason the origin
1088 // layer's double entry respans its own subject: `quote_spanned!` sets the span of the tokens
1089 // it MINTS and an interpolated path keeps the one it was written with, so a predicate whose
1090 // trait path still carried the emitter's span would report the broken hop at the macro
1091 // instead of at the step. Respanning is safe where the span is a real one from the same file,
1092 // which a field's name always is: resolution is unchanged and only the report moves.
1093 let face = respan(self.face(step), at_field);
1094 vec![quote_spanned!(at_field=> #ty: #face<#takes, #answers>)]
1095 })
1096 .collect()
1097 }
1098
1099 /// **THE HEAD PIN** — the word's half of the double entry, and [`None`] where no word was written.
1100 ///
1101 /// One anonymous `const`, the source layer's own shape: a helper whose `where` clause names the
1102 /// answer the WORD claimed, spent over the declared type, so the compiler resolves the tower's own
1103 /// `SearchTower::Answer` — which the chain DERIVED — against it. Agreement compiles to nothing;
1104 /// disagreement is `E0271` naming both types.
1105 ///
1106 /// # Two spans, and each is chosen for what lands on it
1107 ///
1108 /// The CALL carries the word's span, because rustc reports a projection mismatch at the site that
1109 /// instantiated it: the caret has to land on the type an author wrote, that being the one token of
1110 /// this pair a tower's own declaration can change. The declared type is respanned onto the word for
1111 /// the reason the source layer's is — [`quote_spanned!`] sets the span of the tokens it MINTS and
1112 /// an interpolated ident keeps its own, so a turbofish left at the declaration would put the
1113 /// primary caret on the struct and leave the word in a note.
1114 ///
1115 /// The HELPER keeps the emitter's span and is reported at the attribute, which is where its
1116 /// *required by a bound in …* note lands. Its NAME is half the diagnostic and is written as a
1117 /// sentence for that reason: a projection has no `on_unimplemented` to carry one, so the
1118 /// identifier is the only place this join can say what it was checking.
1119 ///
1120 /// # It demands `SearchTower` and nothing beyond it
1121 ///
1122 /// The bound is over the tower's own citizenship, so a tower whose CHAIN is broken has already
1123 /// been refused by [`connectivity`](Self::connectivity) and earns one more `E0277` here saying it
1124 /// is not a search tower. That cost is real and it is paid only by declarations that wrote the
1125 /// word — a tower with no pin emits none of this, so no golden that does not pin can move.
1126 fn pin(&self) -> Option<proc_macro2::TokenStream> {
1127 use syn::spanned::Spanned as _;
1128
1129 let claimed = self.answer.as_ref()?;
1130 let krate = &self.krate;
1131 let at = claimed.span();
1132 let audit = quote::format_ident!("__ingraph_a_tower_answers_the_type_its_answer_word_named");
1133 let spent = respan(
1134 {
1135 let name = &self.name;
1136 quote!(#name)
1137 },
1138 at,
1139 );
1140 let spend = quote_spanned!(at=> const _: fn() = #audit::<#spent>;);
1141 Some(quote! {
1142 const _: () = {
1143 fn #audit<__IgTower>()
1144 where
1145 __IgTower: #krate::__private::retrieve::SearchTower<Answer = #claimed>,
1146 {
1147 }
1148
1149 #spend
1150 };
1151 })
1152 }
1153
1154 /// ONE STEP'S KNOBS SEAT, spelled as the projection it is — `<Ty as Serve>::Options`.
1155 ///
1156 /// The BASE and never a face, which is the whole reason the seat came down there: a projection
1157 /// calls no verb, so naming a face here would decide the step's MODE on the wire's behalf and a
1158 /// tower is kind-agnostic. Spanned at the step's own field, so a type that is no server at all is
1159 /// `E0277` where it was written.
1160 fn seat(&self, step: &StepModel) -> proc_macro2::TokenStream {
1161 let at_field = step.field.span();
1162 let ty = &step.ty;
1163 let base = respan(
1164 {
1165 let krate = &self.krate;
1166 quote!(#krate::__private::drive::Serve)
1167 },
1168 at_field,
1169 );
1170 quote_spanned!(at_field=> <#ty as #base>::Options)
1171 }
1172
1173 /// **THE TOWER'S OWN OPTIONS** — one field per step, and the three ways a caller names one.
1174 ///
1175 /// See the module note for the shape and for why the fields are `Option`. What is here is the
1176 /// SURFACE, and it is the crate's own options discipline rather than a public-field struct: the
1177 /// fields are private, so the only roads to a step's knobs are the two the emission writes, and a
1178 /// value parsed off a wire can be narrowed in place afterwards.
1179 ///
1180 /// | road | shape | who writes it |
1181 /// |---|---|---|
1182 /// | `with_<step>(knobs)` | consuming, takes the seat | a caller BUILDING a request |
1183 /// | `set_<step>(Option)` | in place, takes the option | a holder NARROWING somebody else's |
1184 /// | `<step>()` | `Option<&seat>` | the walk, and anybody reading one back |
1185 ///
1186 /// `set_…` takes an [`Option`] where `with_…` takes the seat, which is [`Flow`]'s own division one
1187 /// layer down: *this call names nothing* has to stay sayable after construction, and that is what
1188 /// a holder narrowing a parsed package needs and a builder never does.
1189 ///
1190 /// # The one collision it can have, and it is the honest one
1191 ///
1192 /// A getter is named after its step, so a tower with a step called `new` mints two `new`s and is
1193 /// `E0592` naming both. The family already takes that trade at `walk` and at `<Tower>Error`; it is
1194 /// stated here because a STEP's name is an author's own word rather than the declaration's.
1195 ///
1196 /// [`Flow`]: https://docs.rs/ingraph
1197 fn options(&self) -> proc_macro2::TokenStream {
1198 use syn::ext::IdentExt as _;
1199
1200 let vis = &self.vis;
1201 let name = self.step_options_name();
1202 let rows = self.steps.iter().map(|step| {
1203 let field = &step.field;
1204 let seat = self.seat(step);
1205 let doc = crate::emit::leading(&format!(
1206 "What the `{field}` step is served with, where this call names it.",
1207 field = step.field,
1208 ));
1209 quote! {
1210 #[doc = #doc]
1211 #field: ::core::option::Option<#seat>
1212 }
1213 });
1214 let nothing = self.steps.iter().map(|step| {
1215 let field = &step.field;
1216 quote!(#field: ::core::option::Option::None,)
1217 });
1218 let knobs = self.steps.iter().map(|step| {
1219 let field = &step.field;
1220 let bare = field.unraw();
1221 let seat = self.seat(step);
1222 let with = quote::format_ident!("with_{bare}", span = step.field.span());
1223 let set = quote::format_ident!("set_{bare}", span = step.field.span());
1224 // The PARAMETER keeps the field's own `r#`, because a step legally called `r#type` unraw'd
1225 // into a parameter position would be the keyword itself. The two GLUED names take the unraw'd
1226 // spelling, since `with_type` is a name and not a keyword.
1227 let named = crate::emit::leading(&format!(
1228 "The same options, naming what the `{field}` step is served with.\n\nA step whose server \
1229 seats `()` takes NO knobs — its seat is the ANSWER *this server is configured with \
1230 nothing* — so this parameter is `()` there and knobs written for one are refused right \
1231 here, at the step's own name.",
1232 field = step.field,
1233 ));
1234 let narrowed = crate::emit::leading(&format!(
1235 "What the `{field}` step is served with, named IN PLACE — including named back to nothing.",
1236 field = step.field,
1237 ));
1238 let read = crate::emit::leading(&format!(
1239 "What this call names for the `{field}` step, or [`None`] where it names nothing — under \
1240 which that step runs at its own floor.",
1241 field = step.field,
1242 ));
1243 quote! {
1244 #[doc = #named]
1245 #[inline]
1246 #[must_use]
1247 #vis fn #with(mut self, #field: #seat) -> Self {
1248 self.#field = ::core::option::Option::Some(#field);
1249 self
1250 }
1251
1252 #[doc = #narrowed]
1253 #[inline]
1254 #vis fn #set(&mut self, #field: ::core::option::Option<#seat>) -> &mut Self {
1255 self.#field = #field;
1256 self
1257 }
1258
1259 #[doc = #read]
1260 #[inline]
1261 #[must_use]
1262 #vis fn #field(&self) -> ::core::option::Option<&#seat> {
1263 ::core::option::Option::as_ref(&self.#field)
1264 }
1265 }
1266 });
1267 let doc = crate::emit::leading(&format!(
1268 "What a caller names for [`{name}`]'s steps — ONE FIELD PER STEP, each that step's own \
1269 `Serve::Options` seat.\n\nEvery field starts at nothing, and nothing is a LEVEL rather than \
1270 a gap: a step this names nothing for is served under `None` and runs at its own floor, which \
1271 is what a step author's own default is for. A step whose server seats `()` takes no knobs at \
1272 all, so its row here is zero-sized and nothing reads it.",
1273 name = self.name,
1274 ));
1275 let fresh = crate::emit::leading(&format!(
1276 "Options that name NOTHING — every step of [`{name}`] at its own floor.",
1277 name = self.name,
1278 ));
1279 let defaulted = crate::emit::leading(&format!(
1280 "The unnamed options — [`{name}::new`], and one source of truth for them.",
1281 name = name,
1282 ));
1283 quote! {
1284 #[doc = #doc]
1285 // THE PACKAGE FAMILY'S OWN THREE, and a tower's options join them rather than standing apart.
1286 //
1287 // MEASURED, at the first real binding: a search recipe seats a bound tower's options on its own
1288 // package — `Option<<Tower as DeclaredTower>::StepOptions>` — and every package in this framework
1289 // is built through one emitter that derives exactly these. A tower whose options derived
1290 // nothing could be walked from Rust and could not be BOUND, and the refusal was an `E0277`
1291 // about `Debug` reported at the recipe's attribute, naming a type the recipe's author never
1292 // wrote.
1293 //
1294 // The demand lands on `Serve::Options`, where a server's own knobs are declared. That is where
1295 // every other options object in this tree already pays it, and a configuration type that
1296 // cannot be compared or printed is the exception rather than the rule.
1297 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
1298 #vis struct #name {
1299 #(#rows,)*
1300 }
1301
1302 impl #name {
1303 #[doc = #fresh]
1304 #[inline]
1305 #[must_use]
1306 #vis const fn new() -> Self {
1307 Self {
1308 #(#nothing)*
1309 }
1310 }
1311
1312 #(#knobs)*
1313 }
1314
1315 #[doc = #defaulted]
1316 impl ::core::default::Default for #name {
1317 #[inline]
1318 fn default() -> Self {
1319 Self::new()
1320 }
1321 }
1322 }
1323 }
1324
1325 /// **THE RECORD** — what this declaration said, for the readers that cannot see these tokens.
1326 ///
1327 /// Four facts and no fifth: the walk's face, the TWO options objects, and the roster. The two ENDS
1328 /// ride the supertrait, so nothing here can disagree with the connectivity about what a tower is
1329 /// asked.
1330 ///
1331 /// It carries NO `where` clause, and that is deliberate: the connectivity states the chain once,
1332 /// and a broken tower that restated it here would report every broken hop twice. What a broken
1333 /// tower gets instead is one refusal saying it is not a search tower — which is the truth the
1334 /// connectivity already reported the reason for.
1335 fn declared(&self) -> proc_macro2::TokenStream {
1336 let krate = &self.krate;
1337 let name = &self.name;
1338 let step_options = self.step_options_name();
1339 let search_options = self.search_options_name();
1340 let all_sync = !self.awaited();
1341 let rows = self.steps.iter().map(|step| {
1342 use syn::ext::IdentExt as _;
1343
1344 let field = step.field.unraw().to_string();
1345 let row = quote!(#krate::__private::retrieve::Step::of(#field));
1346 if step.awaited {
1347 quote!(#row.awaited())
1348 } else {
1349 row
1350 }
1351 });
1352 quote! {
1353 impl #krate::__private::retrieve::DeclaredTower for #name {
1354 type StepOptions = #step_options;
1355 type SearchOptions = #search_options;
1356 const ALL_SYNC: bool = #all_sync;
1357 const STEPS: &'static [#krate::__private::retrieve::Step] = &[
1358 #(#rows),*
1359 ];
1360 }
1361 }
1362 }
1363
1364 /// **THE REQUEST'S OWN OPTIONS** — one row per WORD this declaration wrote, and one that no word
1365 /// has to write.
1366 ///
1367 /// ```ignore
1368 /// pub struct ClipTextSearchOptions {
1369 /// budget: Option<SearchBudget>, // ALWAYS — the framework's universal minimum
1370 /// arm_weight: Option<f64>, // where `expand = "…"` opened a widening
1371 /// lane_emphasis: Option<f64>, // where `route(router = script_weighted_fan, …)` did
1372 /// }
1373 /// ```
1374 ///
1375 /// # It is TOKEN-KEYED, and that is what makes it mintable at all
1376 ///
1377 /// The 2026-08-27 census measured why a request object could not be minted at the RECIPE grain:
1378 /// what crosses the expansion wall is `DeclaredTower` — the two options types, `ALL_SYNC` and the
1379 /// roster — and a `Step` carries a field name and an `async` flag, so nothing a recipe can read
1380 /// says whether the tower it bound widens or crosses. The words are HERE. So the object is minted
1381 /// here, and the recipe publishes it by projection without ever knowing what is in it.
1382 ///
1383 /// # The BUDGET row is unconditional, and it is the keystone's universality read forwards
1384 ///
1385 /// A walk budget means the same thing for every tower ever declared, because it is about the
1386 /// deployment's TIME rather than about the search — so it is not keyed by a word and no word can
1387 /// take it away. It is also what keeps the wire face SPELLABLE: a GraphQL input object may not
1388 /// define zero fields, so a tower whose grammar wrote nothing would otherwise have no face to
1389 /// publish and the recipe's `options` argument would have no type to be.
1390 ///
1391 /// # NO STEP ROWS, ever
1392 ///
1393 /// A step's `Serve::Options` is the application's own type and whether it is `()` is a fact only
1394 /// the compiler holds, so a per-step row cannot be published by a macro that cannot know which
1395 /// rows are empty. That is `<Tower>StepOptions`' whole job and it stays on the install clock.
1396 fn search_options(&self) -> proc_macro2::TokenStream {
1397 let krate = &self.krate;
1398 let vis = &self.vis;
1399 let name = self.search_options_name();
1400 let sdl = name.to_string();
1401 let at = self.name.span();
1402 let budget = respan(quote!(#krate::__private::retrieve::SearchBudget), at);
1403 let mut rows: Vec<SearchRow> = vec![SearchRow {
1404 member: quote::format_ident!("budget", span = at),
1405 wire: "budget",
1406 ty: budget,
1407 noun: "walk budget",
1408 why: "How long this request will wait for the whole walk. The deployment's own wall CAPS it: \
1409 a request asking for less waits less, and one asking for more waits the deployment's \
1410 number.",
1411 }];
1412 if let Some(at_expand) = self.expand_at() {
1413 let at_field = self.steps[at_expand].field.span();
1414 rows.push(SearchRow {
1415 member: quote::format_ident!("arm_weight", span = at_field),
1416 wire: "armWeight",
1417 ty: quote_spanned!(at_field=> ::core::primitive::f64),
1418 noun: "arm weight",
1419 why: "What an arm the expander minted counts for, against the 1.0 of what was actually \
1420 asked. A PREFERENCE, so a request that names it wins outright over the deployment's.",
1421 });
1422 }
1423 if let Some((_, step)) = self.weighted_crossing() {
1424 let at_field = step.field.span();
1425 rows.push(SearchRow {
1426 member: quote::format_ident!("lane_emphasis", span = at_field),
1427 wire: "laneEmphasis",
1428 ty: quote_spanned!(at_field=> ::core::primitive::f64),
1429 noun: "lane emphasis",
1430 why: "What a lane this question is written in counts for, against the 1.0 of every other \
1431 lane. A PREFERENCE, and 1.0 asks every lane flat.",
1432 });
1433 }
1434 let fields = rows.iter().map(
1435 |SearchRow {
1436 member,
1437 ty,
1438 noun,
1439 why,
1440 ..
1441 }| {
1442 let doc = crate::emit::leading(&format!(
1443 "The {noun}, where this request names one.\n\n{why}\n\nAbsent means THIS REQUEST NAMED \
1444 NOTHING, under which the deployment's own value stands.",
1445 ));
1446 quote!(#[doc = #doc] #member: ::core::option::Option<#ty>)
1447 },
1448 );
1449 let nothing = rows
1450 .iter()
1451 .map(|SearchRow { member, .. }| quote!(#member: ::core::option::Option::None,));
1452 let knobs = rows.iter().map(
1453 |SearchRow {
1454 member, ty, noun, ..
1455 }| {
1456 let with = quote::format_ident!("with_{member}", span = member.span());
1457 let set = quote::format_ident!("set_{member}", span = member.span());
1458 let named = crate::emit::leading(&format!("The same request, naming the {noun}."));
1459 let narrowed = crate::emit::leading(&format!(
1460 "The {noun}, named IN PLACE — including named back to nothing.",
1461 ));
1462 let read = crate::emit::leading(&format!(
1463 "The {noun}, or [`None`] where this request named nothing.",
1464 ));
1465 quote! {
1466 #[doc = #named]
1467 #[inline]
1468 #[must_use]
1469 #vis fn #with(mut self, #member: #ty) -> Self {
1470 self.#member = ::core::option::Option::Some(#member);
1471 self
1472 }
1473
1474 #[doc = #narrowed]
1475 #[inline]
1476 #vis fn #set(&mut self, #member: ::core::option::Option<#ty>) -> &mut Self {
1477 self.#member = #member;
1478 self
1479 }
1480
1481 #[doc = #read]
1482 #[inline]
1483 #[must_use]
1484 #vis fn #member(&self) -> ::core::option::Option<&#ty> {
1485 ::core::option::Option::as_ref(&self.#member)
1486 }
1487 }
1488 },
1489 );
1490 let doc = crate::emit::leading(&format!(
1491 "What ONE REQUEST names for [`{name}`] — the tier-three package, keyed by the words this \
1492 declaration wrote.\n\nEvery field starts at nothing, and nothing is a DEFERRAL rather than a \
1493 gap: a row this names nothing for leaves the deployment's own value standing. A PREFERENCE \
1494 row that IS named wins outright; the budget is PROTECTIVE and may only tighten.",
1495 name = self.name,
1496 ));
1497 let fresh = crate::emit::leading(
1498 "A request that names NOTHING — every tier-three row deferred to the \
1499 deployment's.",
1500 );
1501 let defaulted = crate::emit::leading(&format!(
1502 "The unnamed request — [`{name}::new`], and one source of truth for it.",
1503 name = name,
1504 ));
1505 let face = self.search_options_face(&name, &sdl, &rows);
1506 quote! {
1507 #[doc = #doc]
1508 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
1509 #vis struct #name {
1510 #(#fields,)*
1511 }
1512
1513 impl #name {
1514 #[doc = #fresh]
1515 #[inline]
1516 #[must_use]
1517 #vis const fn new() -> Self {
1518 Self {
1519 #(#nothing)*
1520 }
1521 }
1522
1523 #(#knobs)*
1524 }
1525
1526 #[doc = #defaulted]
1527 impl ::core::default::Default for #name {
1528 #[inline]
1529 fn default() -> Self {
1530 Self::new()
1531 }
1532 }
1533
1534 #face
1535 }
1536 }
1537
1538 /// **THE REQUEST PACKAGE'S WIRE FACE** — an ordinary input object, every field nullable and
1539 /// therefore wholly omissible.
1540 ///
1541 /// HAND-WRITTEN rather than derived, and it rides `if_async_graphql!`, which is the emitted
1542 /// packages' own measured shape one emitter over. A derive belongs to the type's own DECLARATION,
1543 /// which is written outside the binding gate — so a `#[derive(InputObject)]` here would demand
1544 /// async-graphql of every tower ever declared, and a tower walked from Rust alone owes a schema
1545 /// nothing.
1546 ///
1547 /// The gate asks `ingraph`'s OWN feature rather than the declaring crate's, which is why it is a
1548 /// macro and not a `#[cfg]`: a `#[cfg(feature = "async-graphql")]` written inside an expansion asks
1549 /// a different manifest.
1550 fn search_options_face(
1551 &self,
1552 name: &syn::Ident,
1553 sdl: &str,
1554 rows: &[SearchRow],
1555 ) -> proc_macro2::TokenStream {
1556 let krate = &self.krate;
1557 let gate = quote!(#krate::__private::gate::if_async_graphql);
1558 let ag = quote!(#krate::__private::async_graphql);
1559 let entries = rows.iter().map(|SearchRow { wire, ty, why, .. }| {
1560 let description = *why;
1561 quote! {
1562 __ingraph_fields.insert(
1563 ::std::string::String::from(#wire),
1564 #ag::registry::MetaInputValue {
1565 name: ::std::string::String::from(#wire),
1566 description: ::core::option::Option::Some(::std::string::String::from(#description)),
1567 ty: <::core::option::Option<#ty> as #ag::InputType>::create_type_info(
1568 __ingraph_registry,
1569 ),
1570 deprecation: #ag::registry::Deprecation::NoDeprecated,
1571 default_value: ::core::option::Option::None,
1572 visible: ::core::option::Option::None,
1573 inaccessible: false,
1574 tags: ::std::vec::Vec::new(),
1575 is_secret: false,
1576 directive_invocations: ::std::vec::Vec::new(),
1577 },
1578 );
1579 }
1580 });
1581 let reads = rows.iter().map(
1582 |SearchRow {
1583 member, wire, ty, ..
1584 }| {
1585 quote! {
1586 // `.cloned()` in METHOD position, and it has to be: `Option::cloned` is `E0034` as a path,
1587 // there being one on `Option<&T>` and one on `Option<&mut T>` with nothing at the call site
1588 // to pick between them.
1589 #member: <::core::option::Option<#ty> as #ag::InputType>::parse(
1590 #ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
1591 )
1592 .map_err(#ag::InputValueError::propagate)?
1593 }
1594 },
1595 );
1596 let writes = rows.iter().map(|SearchRow { member, wire, .. }| {
1597 quote! {
1598 __ingraph_map.insert(
1599 #ag::Name::new(#wire),
1600 #ag::InputType::to_value(&self.#member),
1601 );
1602 }
1603 });
1604 let description = format!(
1605 "What one request names for `{name}` — every row absent by default, and an absent row leaves \
1606 the deployment's own value standing.",
1607 name = self.name,
1608 );
1609 quote! {
1610 #gate! {
1611 const _: () = {
1612 #[automatically_derived]
1613 impl #ag::InputType for #name {
1614 type RawValueType = Self;
1615
1616 #[inline]
1617 fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
1618 ::std::borrow::Cow::Borrowed(#sdl)
1619 }
1620
1621 fn create_type_info(
1622 __ingraph_registry: &mut #ag::registry::Registry,
1623 ) -> ::std::string::String {
1624 __ingraph_registry.create_input_type::<Self, _>(
1625 #ag::registry::MetaTypeId::InputObject,
1626 |__ingraph_registry| #ag::registry::MetaType::InputObject {
1627 name: ::std::string::String::from(#sdl),
1628 description: ::core::option::Option::Some(
1629 ::std::string::String::from(#description),
1630 ),
1631 input_fields: {
1632 let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
1633 #(#entries)*
1634 __ingraph_fields
1635 },
1636 visible: ::core::option::Option::None,
1637 inaccessible: false,
1638 tags: ::std::vec::Vec::new(),
1639 rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
1640 oneof: false,
1641 directive_invocations: ::std::vec::Vec::new(),
1642 },
1643 )
1644 }
1645
1646 fn parse(
1647 __ingraph_value: ::core::option::Option<#ag::Value>,
1648 ) -> #ag::InputValueResult<Self> {
1649 if let ::core::option::Option::Some(#ag::Value::Object(__ingraph_object)) =
1650 __ingraph_value
1651 {
1652 return ::core::result::Result::Ok(Self { #(#reads,)* });
1653 }
1654 ::core::result::Result::Err(#ag::InputValueError::expected_type(
1655 ::core::option::Option::unwrap_or_default(__ingraph_value),
1656 ))
1657 }
1658
1659 fn to_value(&self) -> #ag::Value {
1660 let mut __ingraph_map = #ag::indexmap::IndexMap::new();
1661 #(#writes)*
1662 #ag::Value::Object(__ingraph_map)
1663 }
1664
1665 #[inline]
1666 fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
1667 ::core::option::Option::Some(self)
1668 }
1669 }
1670
1671 #[automatically_derived]
1672 impl #ag::InputObjectType for #name {}
1673 };
1674 }
1675 }
1676 }
1677
1678 /// **THE ASSEMBLY ROW** — the boot gate over a deployment's filled seats, and the uniform run a
1679 /// resolver calls.
1680 ///
1681 /// # It RESTATES the chain in its own `where` clause, where the record deliberately does not
1682 ///
1683 /// [`declared`](Self::declared) carries none, so a broken tower earns exactly one *is not a search
1684 /// tower* beside the hops the connectivity already reported. This impl carries the chain instead,
1685 /// and the difference is what each impl's SIGNATURE names: a record states three seats and can be
1686 /// written unconditionally, where every row here is spelled in the tower's own two ends — so an
1687 /// unconditional one would ask rustc to normalise `<Self as SearchTower>::Question` for a tower
1688 /// whose `SearchTower` impl does not apply, and report the same broken hops a second time under a
1689 /// second heading. The clause is ASSUMED at an impl and PROVEN at a call, so a good tower pays
1690 /// nothing for it and a broken one is refused once, where the fault is.
1691 ///
1692 /// # The RUN is awaited whatever the walk's face is
1693 ///
1694 /// Its caller is a resolver and a resolver is already async, so a blocking tower's `run` wraps its
1695 /// blocking walk here rather than making every caller branch on
1696 /// `DeclaredTower::ALL_SYNC` — the one-call-seat division the expand seam already makes over its
1697 /// own blocking half. `ALL_SYNC` still answers the HAND-CALL road, where a caller spelling `walk`
1698 /// itself needs to know.
1699 fn assembly(&self) -> proc_macro2::TokenStream {
1700 let krate = &self.krate;
1701 let name = &self.name;
1702 let question = self.asked();
1703 let answer = self.derived();
1704 let refusal = self.error_name();
1705 let options = self.step_options_name();
1706 let mut hops = self.canonical_demands();
1707 hops.extend(self.hops());
1708 let awaited = self.awaited().then(|| quote!(.await));
1709 let gate = self.gate();
1710 let borrowed = self.steps.iter().map(|step| {
1711 let field = &step.field;
1712 quote!(&mut __ingraph_steps__.#field,)
1713 });
1714 let asked = self.search_options_name();
1715 let retuned = self.retuned();
1716 let composed = self.composed();
1717 quote! {
1718 impl #krate::__private::retrieve::AssembledTower for #name
1719 where
1720 #(#hops,)*
1721 {
1722 type Refusal = #refusal;
1723
1724 #gate
1725
1726 #[inline]
1727 fn asked_budget(
1728 __ingraph_asked__: ::core::option::Option<&#asked>,
1729 ) -> ::core::option::Option<#krate::__private::jiff::SignedDuration> {
1730 // THE ONE ROW READ FROM OUTSIDE THE WALK, because the wall is built round the whole run
1731 // and cannot be raised from inside it. The COMPOSITION is still `tightened_budget`'s, at
1732 // `walk_within`; this is the projection that gets the number there.
1733 ::core::option::Option::and_then(
1734 ::core::option::Option::and_then(__ingraph_asked__, #asked::budget),
1735 #krate::__private::retrieve::SearchBudget::walk,
1736 )
1737 }
1738
1739 async fn run(
1740 __ingraph_steps__: &mut #name,
1741 question: #question,
1742 options: ::core::option::Option<&#options>,
1743 asked: ::core::option::Option<#asked>,
1744 ) -> ::core::result::Result<#answer, #refusal> {
1745 #retuned
1746 #composed
1747 #name::walk(question, #(#borrowed)* options)#awaited
1748 }
1749 }
1750 }
1751 }
1752
1753 /// ④ **THE REQUEST'S OWN ROUTER, RETUNED** — the lane emphasis laid on the value THIS READ minted,
1754 /// or nothing at all where no word could carry one.
1755 ///
1756 /// # The MINT is what makes per-request configuration free
1757 ///
1758 /// `TowerDoor` builds one exclusive set of steps per read, so the `LaneFan` this run is about to
1759 /// route through is this request's own value and nobody else's. Retuning it is therefore a local
1760 /// write rather than a shared mutation — no lock, no clone of the roster, and nothing held across
1761 /// an `await`.
1762 ///
1763 /// # `LaneRouter` DID NOT MOVE, and that is the road's whole point
1764 ///
1765 /// A per-query emphasis could have been a parameter on the routing trait — a surface end users
1766 /// extend — which would have spent every third-party router's signature for a knob only the shipped
1767 /// routers have. `ScriptWeightedFan::with_emphasis` is the seam instead, and it was already there.
1768 ///
1769 /// # NOTHING IS EMITTED for a router this framework did not ship
1770 ///
1771 /// [`weighted_crossing`](Self::weighted_crossing) answers [`None`] for a quoted path, so the row is
1772 /// never minted and this writes nothing. A published knob the emission could not spend would be
1773 /// worse than the silence.
1774 fn retuned(&self) -> Option<proc_macro2::TokenStream> {
1775 let krate = &self.krate;
1776 let (at, step) = self.weighted_crossing()?;
1777 let at_field = step.field.span();
1778 let field = &step.field;
1779 let asked = self.search_options_name();
1780 let takes = self.takes(at);
1781 let fan = respan(quote!(#krate::__private::route::LaneFan), at_field);
1782 let router = respan(
1783 quote!(#krate::__private::route::ScriptWeightedFan<#takes>),
1784 at_field,
1785 );
1786 Some(quote_spanned! {at_field=>
1787 // TWO STATEMENTS AND NOT ONE, because the mounted router is read through a BORROW of the very
1788 // field the write lands on. The retuned value is built first and the fan is written second.
1789 let __ingraph_retuned__: ::core::option::Option<#router> = match (
1790 ::core::option::Option::and_then(
1791 ::core::option::Option::as_ref(&asked),
1792 #asked::lane_emphasis,
1793 ),
1794 #fan::router(&__ingraph_steps__.#field),
1795 ) {
1796 (
1797 ::core::option::Option::Some(__ingraph_emphasis__),
1798 ::core::option::Option::Some(__ingraph_router__),
1799 ) => ::core::option::Option::Some(<#router>::with_emphasis(
1800 // THE ROSTER IS THE MOUNTED ROUTER'S OWN, carried across unchanged: what a request may
1801 // name is the EMPHASIS, and a rebuilt router that took its lanes from anywhere else would
1802 // be a different router wearing this one's number.
1803 <#router>::new(<#router>::lanes(__ingraph_router__)),
1804 *__ingraph_emphasis__,
1805 )),
1806 _ => ::core::option::Option::None,
1807 };
1808 if let ::core::option::Option::Some(__ingraph_router__) = __ingraph_retuned__ {
1809 #fan::set_router(
1810 &mut __ingraph_steps__.#field,
1811 ::core::option::Option::Some(__ingraph_router__),
1812 );
1813 }
1814 })
1815 }
1816
1817 /// ② **THE REQUEST'S ARM WEIGHT, LAID OVER THE DEPLOYMENT'S** — `ArmWeights::over`, spent once, and
1818 /// the composed package handed to the walk in the deployment's place.
1819 ///
1820 /// # The WALK does not learn that a request exists
1821 ///
1822 /// A widening step's `Serve::Options` IS `ArmWeights`, so the fan walk already reads the tier it is
1823 /// handed at the one place the coefficient is computed. Composing HERE — into a step-keyed package
1824 /// the walk takes exactly as it always did — is what keeps the walk's arity, its parameters and its
1825 /// hand-call road untouched by tier three.
1826 ///
1827 /// # A request that named NOTHING costs nothing
1828 ///
1829 /// The clone happens only inside the `Some` arm, so a read whose request named no weight hands the
1830 /// walk the very borrow the door lent it — absence is identity, at this seat as at the budget's.
1831 fn composed(&self) -> Option<proc_macro2::TokenStream> {
1832 let krate = &self.krate;
1833 let at = self.expand_at()?;
1834 let step = &self.steps[at];
1835 let at_field = step.field.span();
1836 let field = &step.field;
1837 let with = {
1838 use syn::ext::IdentExt as _;
1839 quote::format_ident!("with_{}", step.field.unraw(), span = at_field)
1840 };
1841 let asked = self.search_options_name();
1842 let options = self.step_options_name();
1843 let weights = respan(quote!(#krate::__private::retrieve::ArmWeights), at_field);
1844 Some(quote_spanned! {at_field=>
1845 let __ingraph_composed__: ::core::option::Option<#options> = ::core::option::Option::map(
1846 ::core::option::Option::and_then(
1847 ::core::option::Option::as_ref(&asked),
1848 #asked::arm_weight,
1849 ),
1850 |__ingraph_weight__| {
1851 // TIER THREE OVER TIER TWO, through the one function that spells the preference law.
1852 // Neither side is defaulted on the way: `DEFAULT` is the SHIPPED weights and not a filled
1853 // number, so a deployment that named nothing still loses to a request that did and beats
1854 // one that did not.
1855 let __ingraph_over__ = #weights::over(
1856 &#weights::with_paraphrase(#weights::new(), *__ingraph_weight__),
1857 ::core::option::Option::unwrap_or(
1858 ::core::option::Option::and_then(options, |__ingraph_options__| {
1859 ::core::option::Option::as_ref(&__ingraph_options__.#field)
1860 }),
1861 &#weights::DEFAULT,
1862 ),
1863 );
1864 #options::#with(
1865 match options {
1866 ::core::option::Option::Some(__ingraph_options__) => {
1867 ::core::clone::Clone::clone(__ingraph_options__)
1868 }
1869 ::core::option::Option::None => #options::new(),
1870 },
1871 __ingraph_over__,
1872 )
1873 },
1874 );
1875 let options = match &__ingraph_composed__ {
1876 ::core::option::Option::Some(__ingraph_options__) => {
1877 ::core::option::Option::Some(__ingraph_options__)
1878 }
1879 ::core::option::Option::None => options,
1880 };
1881 })
1882 }
1883
1884 /// **THE CANONICAL LINES THE CHAIN IS SPELLED THROUGH**, stated as predicates — one per step whose
1885 /// end this declaration OMITTED.
1886 ///
1887 /// A `where` clause is ASSUMED at an impl and its own well-formedness is checked in its own
1888 /// environment, so a predicate naming `<Ty as DefaultServe>::Answer` is only well formed where
1889 /// `Ty: DefaultServe` is in that environment. The connectivity does not need these because its
1890 /// refusal IS the missing line — a step with no canonical road is what that impl is there to
1891 /// report. The assembly row restates the chain precisely so that it reports NOTHING, so it states
1892 /// these too and a tower with no canonical line earns its refusal once, at the impl that is about
1893 /// it.
1894 ///
1895 /// It narrows nothing a caller did not already owe: a step that omitted its answer word has its
1896 /// canonical line demanded by the connectivity's own predicates, so this is that same demand
1897 /// written where the compiler can see it. A step whose ends were both WRITTEN appears nowhere
1898 /// here.
1899 fn canonical_demands(&self) -> Vec<proc_macro2::TokenStream> {
1900 let krate = &self.krate;
1901 let mut demanded: Vec<proc_macro2::TokenStream> = Vec::new();
1902 let mut spell = |step: &StepModel| {
1903 let at_field = step.field.span();
1904 let ty = &step.ty;
1905 let line = respan(quote!(#krate::__private::drive::DefaultServe), at_field);
1906 demanded.push(quote_spanned!(at_field=> #ty: #line));
1907 };
1908 // THE HEAD, where the tower wrote no `question` word: what it is asked is the first step's own
1909 // canonical question.
1910 if self.question.is_none()
1911 && let Some(head) = self.steps.first()
1912 {
1913 spell(head);
1914 }
1915 // EVERY STEP whose `answer` word was omitted. An ⟂ step has none by law and spells no canonical
1916 // line — the chain's type does not move across it — so it is not here.
1917 for step in &self.steps {
1918 if step.answer.is_none() && step.annotation.is_none() {
1919 spell(step);
1920 }
1921 }
1922 demanded
1923 }
1924
1925 /// **THE GATE** — one reading per declared fan word, or NOTHING AT ALL for a tower that wrote
1926 /// none.
1927 ///
1928 /// [`None`] is the absence-identity, at the assembly: a tower with no fan word inherits
1929 /// `AssembledTower::check`'s own default, which reads no field and refuses nothing, so a
1930 /// deployment assembling an unfanned tower meets not one token of this machinery.
1931 ///
1932 /// Each reading ASCRIBES the seat before it reads it, which is the walk's own pin at the walk's
1933 /// own price: a field carrying anything but the segment's seat is `E0308` naming both types, at
1934 /// the field. So the gate and the walk agree about what a fan step's field holds by construction
1935 /// rather than by two matching guesses.
1936 ///
1937 /// A CROSSING carries [`LaneFan::check`]'s refusal whole rather than restating it: the roster and
1938 /// both escapes are that seat's own sentence, and a gap that re-worded them would be a second
1939 /// spelling of one vocabulary.
1940 ///
1941 /// [`LaneFan::check`]: https://docs.rs/ingraph
1942 fn gate(&self) -> Option<proc_macro2::TokenStream> {
1943 if !self.fanned() {
1944 return None;
1945 }
1946 let krate = &self.krate;
1947 let name = &self.name;
1948 let tower = name.to_string();
1949 let readings = self.fans().map(|(at, step, fan)| {
1950 let at_field = step.field.span();
1951 let field = &step.field;
1952 let takes = self.takes(at);
1953 let seat = quote_spanned!(at_field=> &__ingraph_steps__.#field);
1954 let unfilled = respan(quote!(#krate::__private::retrieve::UnfilledSeat), at_field);
1955 let named = step.field.to_string();
1956 match fan {
1957 Fan::Expand { expander } => {
1958 let road = respan(quote!(#krate::__private::retrieve::Expansion), at_field);
1959 let declared = spelled("e!(#expander));
1960 quote_spanned! {at_field=>
1961 let __ingraph_road__: &#road<#takes> = #seat;
1962 if !#road::is_mounted(__ingraph_road__) {
1963 ::std::vec::Vec::push(
1964 &mut __ingraph_unfilled__,
1965 #unfilled::widening(#named, #declared),
1966 );
1967 }
1968 }
1969 }
1970 Fan::Route { router, .. } => {
1971 let router = router.spelled(krate, &takes);
1972 let fan = respan(quote!(#krate::__private::route::LaneFan), at_field);
1973 quote_spanned! {at_field=>
1974 let __ingraph_fan__: &#fan<#router> = #seat;
1975 if let ::core::result::Result::Err(__ingraph_missing__) = #fan::check(__ingraph_fan__) {
1976 ::std::vec::Vec::push(
1977 &mut __ingraph_unfilled__,
1978 #unfilled::crossing(#named, __ingraph_missing__),
1979 );
1980 }
1981 }
1982 }
1983 }
1984 });
1985 Some(quote! {
1986 fn check(
1987 __ingraph_steps__: &#name,
1988 ) -> ::core::result::Result<(), #krate::__private::retrieve::SeatsUnfilled> {
1989 let mut __ingraph_unfilled__ = ::std::vec::Vec::new();
1990 #(#readings)*
1991 #krate::__private::retrieve::SeatsUnfilled::checked(#tower, __ingraph_unfilled__)
1992 }
1993 })
1994 }
1995
1996 /// What ONE STEP refuses with — the projection `<Ty as Serves<Q, A>>::Error`, at the face the
1997 /// step's own word chose.
1998 ///
1999 /// A PROJECTION and never an erasure, which is the whole difference this sum makes: nothing here
2000 /// demands that a step's error be boxable, or `Send`, or `'static`, so a step keeps the error type
2001 /// it declared and a caller that matched an arm holds THAT type rather than a `dyn` behind a name.
2002 fn refused_with(&self, at: usize, step: &StepModel) -> proc_macro2::TokenStream {
2003 let at_field = step.field.span();
2004 let ty = &step.ty;
2005 let takes = self.takes(at);
2006 let answers = self.flows(at);
2007 // **A CROSSING REFUSES THE FAN'S OWN SUM**, carried whole. `FanError` already names the three
2008 // causes a routed question has — nothing mounted, a lane this corpus does not hold, and the
2009 // router's own refusal — so an arm that flattened them would be re-stating a vocabulary the
2010 // seat publishes, and a caller that matched this arm would have lost which of them happened.
2011 if let Some(Fan::Route { router, .. }) = &step.fan {
2012 let krate = &self.krate;
2013 let router = router.spelled(krate, &takes);
2014 let seam = respan(quote!(#krate::__private::route::LaneRouter), at_field);
2015 let sum = respan(quote!(#krate::__private::route::FanError), at_field);
2016 return quote_spanned!(at_field=> #sum<<#router as #seam>::Error>);
2017 }
2018 let face = respan(self.face(step), at_field);
2019 quote_spanned!(at_field=> <#ty as #face<#takes, #answers>>::Error)
2020 }
2021
2022 /// **THE STEPS THAT CAN REFUSE** — every step but a widening.
2023 ///
2024 /// A widening CANNOT fail, and that is the expand seam's contract rather than an oversight of this
2025 /// emission: an expander answers a list that may be empty, trouble is digested inside it, and a
2026 /// search that died because its optional widening did would be a worse answer than the unwidened
2027 /// one. So there is no arm for it — an arm nothing can ever construct is a variant a reader has to
2028 /// rule out by hand.
2029 fn refusing(&self) -> impl Iterator<Item = (usize, &StepModel)> {
2030 self
2031 .steps
2032 .iter()
2033 .enumerate()
2034 .filter(|(_, step)| !matches!(step.fan, Some(Fan::Expand { .. })))
2035 }
2036
2037 /// THE REFUSAL SUM — one arm per step, named by the step, carrying that step's own error.
2038 ///
2039 /// See the module note for why a sum rather than an erasure, and [`rendering`](Self::rendering)
2040 /// for the three faces beneath it.
2041 fn refusal(&self) -> proc_macro2::TokenStream {
2042 let vis = &self.vis;
2043 let name = self.error_name();
2044 let arms = self.refusing().map(|(at, step)| {
2045 let variant = Self::variant(step);
2046 let refused_with = self.refused_with(at, step);
2047 let doc = crate::emit::leading(&format!(
2048 "The `{field}` step refused, and this is what it refused with.",
2049 field = step.field,
2050 ));
2051 quote! {
2052 #[doc = #doc]
2053 #variant(#refused_with)
2054 }
2055 });
2056 let doc = crate::emit::leading(&format!(
2057 "How [`{name}`]'s walk refuses — ONE ARM PER STEP, carrying that step's own error.\n\nA \
2058 chain of N hops has N error types and one `Result` has one, so the walk answers this sum: \
2059 the arm NAMES the step that refused, and its payload is the very type that step's `Serves` \
2060 impl declared. Nothing is boxed and nothing is erased, so a caller that matched an arm holds \
2061 the error it was going to inspect anyway.",
2062 name = self.name,
2063 ));
2064 quote! {
2065 #[doc = #doc]
2066 #vis enum #name {
2067 #(#arms),*
2068 }
2069 }
2070 }
2071
2072 /// The refusal sum's own faces: what it prints, what it debugs as, and where the cause is
2073 /// reached.
2074 ///
2075 /// # `Display` NAMES THE STEP; `Debug` CARRIES WHAT IT REFUSED WITH
2076 ///
2077 /// `Display` is a sentence and takes only the arm's name. `Debug` prints the arm AND its payload,
2078 /// which is the shape a derived one has and the shape a caller unwrapping a walk expects — a
2079 /// `.unwrap()` that printed `Tokenize` and nothing else would name the hop and hide the reason.
2080 ///
2081 /// **The payload costs no bound**, and that is measured rather than assumed:
2082 /// [`source`](core::error::Error::source) already coerces every arm's payload to `&dyn Error`, and
2083 /// [`Error`](core::error::Error) has [`Debug`](core::fmt::Debug) as a supertrait — so every step's
2084 /// error is `Debug` before this impl asks. What it does cost is a REPORT: naming a step's error
2085 /// once more is one more place a broken chain is re-derived, so the goldens carry one extra
2086 /// `E0277` per broken hop. The cause is worth the line.
2087 ///
2088 /// The cause travels under [`source`](core::error::Error::source) — the ONE place a step's error
2089 /// is required to BE an error, and it lands at that step's own field.
2090 fn rendering(&self) -> proc_macro2::TokenStream {
2091 let name = self.error_name();
2092 // An arm-less sum is matched through the PLACE rather than through arms — there is no value of
2093 // it, so there is no arm to write. The model is never built empty; this is the shape of that
2094 // fact rather than a case.
2095 let (displayed, debugged, sourced) = if self.refusing().next().is_none() {
2096 (
2097 quote!(match *self {}),
2098 quote!(match *self {}),
2099 quote!(match *self {}),
2100 )
2101 } else {
2102 let displayed = self.refusing().map(|(_, step)| {
2103 let variant = Self::variant(step);
2104 let said = format!(
2105 "the step `{field}` refused the question",
2106 field = step.field
2107 );
2108 quote!(Self::#variant(_) => ::core::fmt::Formatter::write_str(__ingraph_f, #said))
2109 });
2110 let debugged = self.refusing().map(|(_, step)| {
2111 let at_field = step.field.span();
2112 let variant = Self::variant(step);
2113 let printed = variant.to_string();
2114 // SPANNED AT THE STEP, for the reason `source`'s arm is: this is where the payload's own
2115 // `Debug` is spent, and a step whose error cannot be printed should be told so at the field
2116 // that holds it. The demand is already paid — `Error: Debug` — so what the span moves is
2117 // only where a BROKEN CHAIN's re-derivation is reported.
2118 quote_spanned! {at_field=>
2119 Self::#variant(__ingraph_refused__) => ::core::fmt::DebugTuple::finish(
2120 ::core::fmt::DebugTuple::field(
2121 &mut ::core::fmt::Formatter::debug_tuple(__ingraph_f, #printed),
2122 __ingraph_refused__,
2123 ),
2124 )
2125 }
2126 });
2127 let sourced = self.refusing().map(|(_, step)| {
2128 let at_field = step.field.span();
2129 let variant = Self::variant(step);
2130 // SPANNED AT THE STEP, because this coercion is where a step's error is required to BE an
2131 // error: a walk whose refusal could not be asked for its cause would be publishing a
2132 // refusal nobody can inspect. The three impl HEADERS around it keep the emitter's own span
2133 // and are reported at the attribute, which is what an unspanned arm would earn too.
2134 quote_spanned! {at_field=>
2135 Self::#variant(__ingraph_refused__) =>
2136 ::core::option::Option::Some(__ingraph_refused__)
2137 }
2138 });
2139 (
2140 quote!(match self { #(#displayed,)* }),
2141 quote!(match self { #(#debugged,)* }),
2142 quote!(match self { #(#sourced,)* }),
2143 )
2144 };
2145 quote! {
2146 impl ::core::fmt::Display for #name {
2147 fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
2148 #displayed
2149 }
2150 }
2151
2152 impl ::core::fmt::Debug for #name {
2153 fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
2154 #debugged
2155 }
2156 }
2157
2158 impl ::core::error::Error for #name {
2159 fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
2160 #sourced
2161 }
2162 }
2163 }
2164 }
2165
2166 /// THE WALK — the question, the steps, the tail seat, and one hop per step.
2167 fn walk(&self) -> proc_macro2::TokenStream {
2168 let name = &self.name;
2169 let vis = &self.vis;
2170 let question = self.asked();
2171 let answer = self.derived();
2172 let refusal = self.error_name();
2173 let awaited = self.awaited().then(|| quote!(async));
2174
2175 let parameters = self.steps.iter().enumerate().map(|(at, step)| {
2176 let held = held(at, step.field.span());
2177 let ty = &step.ty;
2178 quote!(#held: &mut #ty,)
2179 });
2180 let body = if self.fanned() {
2181 self.fanned_body(&refusal)
2182 } else {
2183 let hops = self
2184 .steps
2185 .iter()
2186 .enumerate()
2187 .map(|(at, step)| self.hop(at, step, &refusal, false));
2188 quote! {
2189 #(#hops)*
2190 ::core::result::Result::Ok(__ingraph_answered__)
2191 }
2192 };
2193 let doc = crate::emit::leading(&self.doc());
2194 let options = self.step_options_name();
2195
2196 quote! {
2197 impl #name {
2198 #[doc = #doc]
2199 #[allow(clippy::too_many_arguments)]
2200 #vis #awaited fn walk(
2201 question: #question,
2202 #(#parameters)*
2203 options: ::core::option::Option<&#options>,
2204 ) -> ::core::result::Result<#answer, #refusal> {
2205 #body
2206 }
2207 }
2208 }
2209 }
2210
2211 /// **THE FAN WALK** — the pre-fan chain once, the family, the lanes, the tail per cell, and the
2212 /// fold that closes every segment before the mouth.
2213 ///
2214 /// ```text
2215 /// [ steps before the fan ] once
2216 /// ② the widening once — the family, the original pinned first
2217 /// for each ARM:
2218 /// [ steps between ② and ④ ] per arm
2219 /// ④ the crossing per arm — one dispatch per lane
2220 /// for each LANE:
2221 /// [ the tail ] per (arm × lane)
2222 /// one grid cell arm × lane, MULTIPLIED
2223 /// the fold once — ONE value out, and the contract stays 1 → 1
2224 /// ```
2225 ///
2226 /// # Either segment may be absent, and neither absence is a second shape
2227 ///
2228 /// A tower that only widens has one lane — [`LaneIdent::UND`], which is what a slot that declared
2229 /// no lanes holds — and a tower that only crosses has one arm, the original's. Both are spelled at
2230 /// the cell rather than branched on here, so the two degenerate fans walk the nesting the full one
2231 /// walks.
2232 ///
2233 /// # EVERY STEP INSIDE A LOOP IS REBORROWED, and every step outside one is not
2234 ///
2235 /// A step is held as `&mut`, and a `&mut` handed to a call inside a loop is moved out of on the
2236 /// first turn. So the hops the fan puts under a loop are emitted as `&mut *step` — and the hops
2237 /// before the fan are emitted exactly as they always were, which is what keeps an UNFANNED tower's
2238 /// expansion the one it had before the amendment, token for token.
2239 ///
2240 /// [`LaneIdent::UND`]: https://docs.rs/ingraph
2241 fn fanned_body(&self, refusal: &syn::Ident) -> proc_macro2::TokenStream {
2242 let krate = &self.krate;
2243 let expand_at = self.expand_at();
2244 let route_at = self.route_at();
2245 // The model is only fanned if one of the two is present, so the fallback is a shape rather than
2246 // a case.
2247 let Some(opens_at) = expand_at.or(route_at) else {
2248 return quote!(::core::result::Result::Ok(__ingraph_answered__));
2249 };
2250 let ends_at = route_at.unwrap_or(self.steps.len());
2251
2252 let lead = (0..opens_at).map(|at| self.hop(at, &self.steps[at], refusal, false));
2253 let per_arm = expand_at
2254 .map(|at| at + 1..ends_at)
2255 .unwrap_or(0..0)
2256 .map(|at| self.hop(at, &self.steps[at], refusal, true));
2257 let per_cell = route_at
2258 .map(|at| at + 1..self.steps.len())
2259 .unwrap_or(0..0)
2260 .map(|at| self.hop(at, &self.steps[at], refusal, true));
2261
2262 let widening = expand_at.map(|at| self.widening(at, &self.steps[at]));
2263 let crossing = route_at.map(|at| self.crossing(at, &self.steps[at], refusal));
2264 let cell = self.cell(expand_at.is_some(), route_at.is_some());
2265 let fold = self.fold();
2266
2267 let arm_taken = expand_at.map(|at| {
2268 let at_field = self.steps[at].field.span();
2269 let arms = Self::named(&self.steps[at], at_field);
2270 quote_spanned! {at_field=>
2271 let (__ingraph_answered__, __ingraph_origin__) =
2272 #krate::__private::retrieve::Expanded::into_components(__ingraph_widened__);
2273 let __ingraph_arm_weight__ = #krate::__private::retrieve::ArmWeights::weight(
2274 ::core::option::Option::unwrap_or(
2275 #arms,
2276 &#krate::__private::retrieve::ArmWeights::DEFAULT,
2277 ),
2278 &__ingraph_origin__,
2279 );
2280 }
2281 });
2282 let lane_taken = route_at.map(|at| {
2283 let at_field = self.steps[at].field.span();
2284 let answers = self.answered(&self.steps[at]);
2285 let probe = respan(quote!(#krate::__private::route::RoutedProbe), at_field);
2286 quote_spanned! {at_field=>
2287 let __ingraph_lane__ = #probe::lane(&__ingraph_probe__);
2288 let __ingraph_lane_weight__ = #probe::weight(&__ingraph_probe__);
2289 let __ingraph_answered__: #answers = __ingraph_probe__;
2290 }
2291 });
2292
2293 // THE NESTING IS BUILT FROM THE INSIDE OUT, one loop at a time, because a `quote!` holds
2294 // BALANCED tokens: a loop cannot be opened in one fragment and closed in another. Each wrap adds
2295 // the run of hops that belongs to ITS depth, which is what keeps the steps between ② and ④
2296 // inside the arm loop and outside the lane one.
2297 let mut nested = quote! {
2298 #lane_taken
2299 #(#per_cell)*
2300 #cell
2301 };
2302 if route_at.is_some() {
2303 nested = quote! {
2304 for __ingraph_probe__ in ::core::iter::IntoIterator::into_iter(__ingraph_probes__) {
2305 #nested
2306 }
2307 };
2308 }
2309 nested = quote! {
2310 #(#per_arm)*
2311 #crossing
2312 #nested
2313 };
2314 if expand_at.is_some() {
2315 nested = quote! {
2316 for (__ingraph_arm__, __ingraph_widened__) in ::core::iter::Iterator::enumerate(
2317 ::core::iter::IntoIterator::into_iter(__ingraph_family__),
2318 ) {
2319 #arm_taken
2320 #nested
2321 }
2322 };
2323 }
2324
2325 quote! {
2326 #(#lead)*
2327 #widening
2328 let mut __ingraph_grid__ = ::std::vec::Vec::new();
2329 #nested
2330 #fold
2331 }
2332 }
2333
2334 /// ② **THE WIDENING** — the family, with the caller's own question at its head.
2335 ///
2336 /// The seat is ASCRIBED before it is spent, which is the whole of what pins a widening step's
2337 /// field to the seat it must hold: a field carrying anything else is `E0308` naming both types, at
2338 /// the field. The awaited call is [`Expansion::expand`]'s own, and the family's element type is
2339 /// ascribed too — a widening is an endomorphism, so a step whose `answer = "…"` named some other
2340 /// type is caught here rather than accepted and dropped.
2341 ///
2342 /// [`Expansion::expand`]: https://docs.rs/ingraph
2343 fn widening(&self, at: usize, step: &StepModel) -> proc_macro2::TokenStream {
2344 let krate = &self.krate;
2345 let at_field = step.field.span();
2346 let held = held(at, at_field);
2347 let takes = self.takes(at);
2348 let answers = self.answered(step);
2349 let taken = if at == 0 {
2350 quote_spanned!(at_field=> question)
2351 } else {
2352 quote_spanned!(at_field=> __ingraph_answered__)
2353 };
2354 let seat = respan(quote!(#krate::__private::retrieve::Expansion), at_field);
2355 let widened = respan(quote!(#krate::__private::retrieve::Expanded), at_field);
2356 quote_spanned! {at_field=>
2357 let __ingraph_asked__: #takes = #taken;
2358 let __ingraph_road__: &#seat<#takes> = #held;
2359 let __ingraph_family__: ::std::vec::Vec<#widened<#answers>> =
2360 #seat::expand(__ingraph_road__, __ingraph_asked__).await;
2361 }
2362 }
2363
2364 /// ④ **THE CROSSING** — one dispatch per lane, with every guardrail the fan seat enforces.
2365 ///
2366 /// The seat is ASCRIBED for the widening's reason and at the widening's cost. The question crosses
2367 /// as a BORROW, which is what lets a router spelled for `str` be asked by a chain carrying a
2368 /// `String`: an argument position is a coercion site, so the step before a crossing owes the
2369 /// router's own question type nothing but a deref.
2370 ///
2371 /// The refusal is MATCHED rather than `?`-ed, on [`hop`](Self::hop)'s own measured reason.
2372 fn crossing(
2373 &self,
2374 at: usize,
2375 step: &StepModel,
2376 refusal: &syn::Ident,
2377 ) -> proc_macro2::TokenStream {
2378 let krate = &self.krate;
2379 let at_field = step.field.span();
2380 let held = held(at, at_field);
2381 let takes = self.takes(at);
2382 let variant = Self::variant(step);
2383 let taken = if at == 0 {
2384 quote_spanned!(at_field=> question)
2385 } else {
2386 quote_spanned!(at_field=> __ingraph_answered__)
2387 };
2388 let Some(Fan::Route { router, .. }) = &step.fan else {
2389 return quote!();
2390 };
2391 let router = router.spelled(krate, &takes);
2392 let seat = respan(quote!(#krate::__private::route::LaneFan), at_field);
2393 quote_spanned! {at_field=>
2394 let __ingraph_asked__: #takes = #taken;
2395 let __ingraph_fan__: &#seat<#router> = #held;
2396 let __ingraph_probes__ = match #seat::route(__ingraph_fan__, &__ingraph_asked__) {
2397 ::core::result::Result::Ok(__ingraph_probes__) => __ingraph_probes__,
2398 ::core::result::Result::Err(__ingraph_refused__) => {
2399 return ::core::result::Result::Err(#refusal::#variant(__ingraph_refused__));
2400 }
2401 };
2402 }
2403 }
2404
2405 /// **ONE GRID CELL** — the tail's stream, filed under its arm and its lane at `arm × lane`.
2406 ///
2407 /// The three constructors are the three shapes a fan has, and the axis a tower did not open is
2408 /// SPELLED rather than filled with a literal: `uncut` names the roster's own default lane and
2409 /// `unwidened` names the sole arm, so a reader of this expansion is told which segment is missing
2410 /// instead of being shown a `1.0` to interpret.
2411 fn cell(&self, widens: bool, crosses: bool) -> proc_macro2::TokenStream {
2412 let krate = &self.krate;
2413 let at_field = self
2414 .steps
2415 .last()
2416 .map_or_else(proc_macro2::Span::call_site, |step| step.field.span());
2417 let stream = respan(quote!(#krate::__private::retrieve::FanStream), at_field);
2418 let ranked = respan(quote!(#krate::__private::retrieve::RankedStream), at_field);
2419 let found = quote_spanned!(at_field=> #ranked::into_ranked(__ingraph_answered__));
2420 let built = match (widens, crosses) {
2421 (true, true) => quote_spanned!(at_field=> #stream::new(
2422 __ingraph_lane__,
2423 __ingraph_arm__,
2424 __ingraph_arm_weight__,
2425 __ingraph_lane_weight__,
2426 #found,
2427 )),
2428 (true, false) => {
2429 quote_spanned!(at_field=> #stream::uncut(__ingraph_arm__, __ingraph_arm_weight__, #found))
2430 }
2431 (false, true) => quote_spanned!(at_field=>
2432 #stream::unwidened(__ingraph_lane__, __ingraph_lane_weight__, #found)
2433 ),
2434 (false, false) => return quote!(),
2435 };
2436 quote_spanned!(at_field=> ::std::vec::Vec::push(&mut __ingraph_grid__, #built);)
2437 }
2438
2439 /// **THE FOLD AT THE MOUTH** — the grid in, the tower's one answer out.
2440 ///
2441 /// The join is the HASHED one, and that is a recorded choice rather than an unexamined default:
2442 /// every root key this framework emits hashes today, which is the same fact
2443 /// [`HashJoin`](https://docs.rs/ingraph) 's own note states. A tower whose root cannot hash needs
2444 /// the `eq` mechanism, and the word that would pick it is a DOOR — the search recipe's own
2445 /// `dedup(…)` at the tower grain — recorded here rather than guessed at now.
2446 ///
2447 /// The fold's `k` is likewise the shipped [`Fusion::rrf`](https://docs.rs/ingraph) and not a knob:
2448 /// the flavour a caller names rides the request road that the recipe already carries, and wiring a
2449 /// second home for it here is the knobs task's, not this one's.
2450 fn fold(&self) -> proc_macro2::TokenStream {
2451 let krate = &self.krate;
2452 let at_field = self
2453 .steps
2454 .last()
2455 .map_or_else(proc_macro2::Span::call_site, |step| step.field.span());
2456 let tail = self.tail();
2457 let stream = respan(quote!(#krate::__private::retrieve::RankedStream), at_field);
2458 let root = quote_spanned!(at_field=> <#tail as #stream>::Root);
2459 let evidence = quote_spanned!(at_field=> <#tail as #stream>::Evidence);
2460 let join = respan(quote!(#krate::__private::retrieve::HashJoin), at_field);
2461 let fold = respan(quote!(#krate::__private::retrieve::fuse_fanned), at_field);
2462 let fusion = respan(quote!(#krate::__private::retrieve::Fusion), at_field);
2463 quote_spanned! {at_field=>
2464 ::core::result::Result::Ok(#fold::<#root, #evidence, #join<#root>>(
2465 __ingraph_grid__,
2466 #fusion::rrf(),
2467 ))
2468 }
2469 }
2470
2471 /// ONE HOP: what it is handed, what it answers, and the refusal it reports under.
2472 ///
2473 /// **BOTH ENDS ARE ASCRIBED, which is the double pin**: the question this hop takes and the
2474 /// answer it gives are written down beside the call, so the obligation the call raises is the
2475 /// exact `Serves<Q, A>` the chain arrived at rather than one with a floating parameter — a step
2476 /// with no impl reports the missing bound instead of *type annotations needed*.
2477 ///
2478 /// The call goes through the TRAIT PATH rather than through a method, which is the ask road's own
2479 /// spelling one layer over and is not a style choice: `step.serve(…)` is `E0599` *no method named
2480 /// `serve`* when a step wears the other face, and a second refusal standing in front of the one
2481 /// the walk is about is exactly the shape that hid a real fixture's pin one round ago.
2482 fn hop(
2483 &self,
2484 at: usize,
2485 step: &StepModel,
2486 refusal: &syn::Ident,
2487 reborrowed: bool,
2488 ) -> proc_macro2::TokenStream {
2489 // ⟂ THE DISPATCH LIVES HERE, at the one function every position in the walk already calls —
2490 // before the fan, between the two segments, inside the cell — so an annotation stage is walked
2491 // wherever a step is walked and no caller learns a third case. The stage law puts a ⟂ step
2492 // before both fan words, so today it only ever lands in the run before the fan; a hand-built
2493 // model that put one elsewhere still gets the hop it declared rather than silence.
2494 if step.annotation.is_some() {
2495 return self.annotating(at, step, refusal, reborrowed);
2496 }
2497 let at_field = step.field.span();
2498 let held = held(at, at_field);
2499 // **INSIDE A FAN'S LOOPS THE BORROW IS REBORROWED**, and outside them it is not. A `&mut` handed
2500 // to a call is moved, so a step under a loop would be gone after the first turn; `&mut *step` is
2501 // the same borrow, taken again. It is spelled only where it is needed, which is what leaves an
2502 // unfanned tower's every hop the tokens it already had.
2503 let held = if reborrowed {
2504 quote_spanned!(at_field=> &mut *#held)
2505 } else {
2506 quote_spanned!(at_field=> #held)
2507 };
2508 let takes = self.takes(at);
2509 let answers = self.answered(step);
2510 let face = respan(self.face(step), at_field);
2511 let variant = Self::variant(step);
2512 // EVERY token of the hop carries the step's span, this one included. An argument left at the
2513 // emitter's own call site is what a trait-resolution failure gets reported at when the
2514 // parameters cannot be inferred — the caret lands on the attribute rather than on the field,
2515 // which is the report a reader cannot act on.
2516 let taken = if at == 0 {
2517 quote_spanned!(at_field=> question)
2518 } else {
2519 quote_spanned!(at_field=> __ingraph_answered__)
2520 };
2521 let landed = step.awaited.then(|| quote_spanned!(at_field=> .await));
2522 let named = Self::named(step, at_field);
2523 // MATCHED RATHER THAN `map_err(…)?`, measured on the goldens: the combinator raises its
2524 // obligation through `Result::map_err`'s own `FnOnce` bound, so a broken hop earned a *required
2525 // by a bound in `Result::<T, E>::map_err`* note pointing a declaration's author into
2526 // `core/src/result.rs`. The match raises the same obligation with nothing of the standard
2527 // library between the step and the report.
2528 quote_spanned! {at_field=>
2529 let __ingraph_asked__: #takes = #taken;
2530 let __ingraph_answered__: #answers = match #face::serve(
2531 #held,
2532 __ingraph_asked__,
2533 #named,
2534 )
2535 #landed
2536 {
2537 ::core::result::Result::Ok(__ingraph_answered__) => __ingraph_answered__,
2538 ::core::result::Result::Err(__ingraph_refused__) => {
2539 return ::core::result::Result::Err(#refusal::#variant(__ingraph_refused__));
2540 }
2541 };
2542 }
2543 }
2544
2545 /// ⟂ **THE ANNOTATION STAGE** — the question asked whether it was already told, and the operator
2546 /// spent only where it was not.
2547 ///
2548 /// ```ignore
2549 /// let __ingraph_asked__: Q = question;
2550 /// let __ingraph_told__ = Option::is_some(&<Q as AnnotatedQuestion<A>>::carried(&__ingraph_asked__));
2551 /// let __ingraph_answered__: Q = if __ingraph_told__ { __ingraph_asked__ } else { /* the hop */ };
2552 /// ```
2553 ///
2554 /// # FILL-IF-ABSENT IS A BRANCH AND NOT A MERGE
2555 ///
2556 /// The caller's own value is not compared, not merged and not overwritten — the question is
2557 /// handed on **untouched**, the same value it arrived as. That is the whole of *never override*:
2558 /// there is no line here that could take a request's own statement and replace it, so the rule is
2559 /// a property of the emission rather than a discipline a stage's author has to keep.
2560 ///
2561 /// **The operator is NOT CONSULTED**, which is a reading rather than an accident. A stage mounted
2562 /// on a resident is *query-time compute over an exclusive model*, and calling one to discard its
2563 /// answer would spend a forward pass the request had already made unnecessary. The alternative —
2564 /// call, then drop — buys exactly one thing, a tap that sees every question, and a stage that
2565 /// wants that can be given it where taps live.
2566 ///
2567 /// # WHY THE TEST IS A `let` AND NOT AN `if` CONDITION
2568 ///
2569 /// [`AnnotatedQuestion::carried`](https://docs.rs/ingraph) borrows the question, and the arm that
2570 /// takes the untouched road MOVES it. Binding the boolean first ends that borrow at the
2571 /// statement's own semicolon, which is a rule about temporaries this emission does not have to
2572 /// reason about twice.
2573 ///
2574 /// The refusal is MATCHED rather than `?`-ed, on [`hop`](Self::hop)'s own measured reason, and the
2575 /// step's face is the step's own word: an LID behind a [`Door`](https://docs.rs/ingraph) wears the
2576 /// awaited one, an in-process detector wears the blocking one, and the stage cares about neither.
2577 fn annotating(
2578 &self,
2579 at: usize,
2580 step: &StepModel,
2581 refusal: &syn::Ident,
2582 reborrowed: bool,
2583 ) -> proc_macro2::TokenStream {
2584 let krate = &self.krate;
2585 let at_field = step.field.span();
2586 let held = held(at, at_field);
2587 let held = if reborrowed {
2588 quote_spanned!(at_field=> &mut *#held)
2589 } else {
2590 quote_spanned!(at_field=> #held)
2591 };
2592 let takes = self.takes(at);
2593 let face = respan(self.face(step), at_field);
2594 let seam = respan(
2595 quote!(#krate::__private::retrieve::AnnotatedQuestion),
2596 at_field,
2597 );
2598 let variant = Self::variant(step);
2599 let taken = if at == 0 {
2600 quote_spanned!(at_field=> question)
2601 } else {
2602 quote_spanned!(at_field=> __ingraph_answered__)
2603 };
2604 let landed = step.awaited.then(|| quote_spanned!(at_field=> .await));
2605 let named = Self::named(step, at_field);
2606 let annotation = step.annotation.as_ref();
2607 quote_spanned! {at_field=>
2608 let __ingraph_asked__: #takes = #taken;
2609 let __ingraph_told__ = ::core::option::Option::is_some(
2610 &<#takes as #seam<#annotation>>::carried(&__ingraph_asked__),
2611 );
2612 let __ingraph_answered__: #takes = if __ingraph_told__ {
2613 __ingraph_asked__
2614 } else {
2615 match #face::serve(
2616 #held,
2617 __ingraph_asked__,
2618 #named,
2619 )
2620 #landed
2621 {
2622 ::core::result::Result::Ok(__ingraph_answered__) => __ingraph_answered__,
2623 ::core::result::Result::Err(__ingraph_refused__) => {
2624 return ::core::result::Result::Err(#refusal::#variant(__ingraph_refused__));
2625 }
2626 }
2627 };
2628 }
2629 }
2630
2631 /// **WHAT THIS CALL NAMED FOR ONE STEP** — the projection out of the tower's own options object.
2632 ///
2633 /// The tower's options are per TOWER and a seat is per SERVER, so what a step is handed is ITS OWN
2634 /// field and nothing else. `and_then` folds the two absences into the one that reaches the step —
2635 /// no options at all, and options that named nothing for this step, are the same fact from a
2636 /// step's side: *this call named nothing*.
2637 ///
2638 /// The field is read directly rather than through the getter, this expansion and the struct being
2639 /// one scope; the getter is for everybody else.
2640 ///
2641 /// It is a function rather than a line inside the hop because a FAN SEGMENT reads one too: a
2642 /// widening's row is the arm weight, so the projection is spent at a position that serves no verb.
2643 fn named(step: &StepModel, at_field: proc_macro2::Span) -> proc_macro2::TokenStream {
2644 let field = &step.field;
2645 quote_spanned! {at_field=>
2646 ::core::option::Option::and_then(options, |__ingraph_options__| {
2647 ::core::option::Option::as_ref(&__ingraph_options__.#field)
2648 })
2649 }
2650 }
2651
2652 /// A type as the DOC spells it: the written word, or the canonical line in the short form a
2653 /// reader would write by hand.
2654 ///
2655 /// The emitted projection goes through `__private`, which is a shelf path and not a sentence. A
2656 /// doc line is read by the author, so what it shows is `<Tokenize as DefaultServe>::Answer` — the
2657 /// same fact in the spelling the declaration's own crate would use.
2658 fn written(step: &StepModel, seat: &str) -> String {
2659 let ty = &step.ty;
2660 format!("<{} as DefaultServe>::{seat}", spelled("e!(#ty)))
2661 }
2662
2663 /// The walk's own doc line — the chain an author reads back, and the face the OR law chose.
2664 fn doc(&self) -> String {
2665 let chain = self
2666 .steps
2667 .iter()
2668 .map(|step| {
2669 let ty = &step.ty;
2670 format!(
2671 "| `{field}` | `{ty}` | {face} | `{answer}` |",
2672 field = step.field,
2673 ty = spelled("e!(#ty)),
2674 face = if step.awaited { "awaited" } else { "blocking" },
2675 answer = step.answer.as_ref().map_or_else(
2676 || Self::written(step, "Answer"),
2677 |answer| spelled("e!(#answer)),
2678 ),
2679 )
2680 })
2681 .collect::<Vec<_>>()
2682 .join("\n");
2683 let asked = match (&self.question, self.steps.first()) {
2684 (Some(question), _) => spelled("e!(#question)),
2685 (None, Some(head)) => Self::written(head, "Question"),
2686 (None, None) => "()".to_owned(),
2687 };
2688 format!(
2689 "Walk this tower — [`{name}`]'s question pipeline, from `{question}` to `{answer}` in one \
2690 {face}function.\n\nThe question comes FIRST, then one `&mut` borrow per step in declaration \
2691 order, then [`{options}`]({options}) — the tower's own options, out of which each hop is \
2692 handed ITS OWN field. The face is {face}because {why} — the OR law.\n\n| step | server | \
2693 face | answers |\n|---|---|---|---|\n{chain}\n\nA hop this call named nothing for is served \
2694 under `None` and runs at its own floor, and `None` for the whole seat names nothing for any \
2695 of them.\n\n# Errors\n\nThe step that refused, as the arm of [`{error}`]({error}) named \
2696 after it.",
2697 name = self.name,
2698 error = self.error_name(),
2699 options = self.step_options_name(),
2700 question = asked,
2701 answer = self.steps.last().map_or_else(
2702 || "()".to_owned(),
2703 |step| step.answer.as_ref().map_or_else(
2704 || Self::written(step, "Answer"),
2705 |answer| spelled("e!(#answer)),
2706 ),
2707 ),
2708 face = if self.awaited() {
2709 "awaited "
2710 } else {
2711 "blocking "
2712 },
2713 why = if self.awaited() {
2714 "at least one step is awaited"
2715 } else {
2716 "every step is blocking"
2717 },
2718 )
2719 }
2720}
2721
2722/// A TYPE as a reader writes it, off the tokens it was parsed from.
2723///
2724/// `quote!`'s own rendering spaces every token, so `Vec < String >` is what a doc line would carry
2725/// otherwise. This is a doc-line spelling and never an identity: two types that print the same are
2726/// still whatever the compiler resolves them to.
2727fn spelled(tokens: &proc_macro2::TokenStream) -> String {
2728 tokens
2729 .to_string()
2730 .replace(" < ", "<")
2731 .replace(" >", ">")
2732 .replace(" :: ", "::")
2733 .replace(" , ", ", ")
2734}
2735
2736/// A step's parameter name in the walk — `__`-pinned so that a field called `question` or `options`
2737/// cannot shadow the two seats it sits between.
2738///
2739/// Positional rather than named after the field, per the tower core's own spelling: what a caller
2740/// reads is the doc table above, which names every step, and what the compiler reports is a
2741/// position.
2742///
2743/// Minted AT THE STEP'S FIELD, because an argument is where a trait-resolution failure is reported:
2744/// a parameter left at the emitter's own call site puts the caret on the attribute.
2745fn held(at: usize, at_field: proc_macro2::Span) -> syn::Ident {
2746 quote::format_ident!("__ingraph_step{at}__", span = at_field)
2747}