Skip to main content

ingraph_codegen/
launch.rs

1//! THE LAUNCH ENTRY: the one door a deployment of a graph root goes through.
2//!
3//! ```ignore
4//! #[ingraph::graph]
5//! pub struct Media {
6//!   videos: Video,
7//!   scenes: Scene,
8//! }
9//! ```
10//!
11//! emits, beside the options spine, `Media::launch` — the ruled sequence walked once, in order:
12//! VALIDATE, then CREATE, then WIRE, then IGNITE, and an [`App<Media>`][`App`] at the end of it.
13//!
14//! The running world is the FRAMEWORK's type and not an emitted one — every indexer's lifecycle is
15//! the same lifecycle — so what this entry contributes is the type parameter: the root it was
16//! emitted for is what the world is `App` OF, which is the seat a later round's emitted faces hang
17//! off.
18//!
19//! # PARSE is the caller's, and that is the framework reading no file
20//!
21//! The sequence's first step does not appear here, because the options arrive already typed: an
22//! application picks its format, merges whatever layers it has and hands over a `MediaOptions`. What
23//! this entry spends is that value, and it is spent WHOLE — the sections move into their nodes'
24//! constructions, so a deployment's options are consumed by the launch they describe.
25//!
26//! # What the emission can say, and what it must be handed
27//!
28//! A root declares a LIST: mount names and node types, in one order. That list is exactly what the
29//! create walk's third step needs, so the node pass is emitted here in full — one
30//! [`Creation::node`] call per declared mount, in declaration order, each with its own section and
31//! its own bare-options probe.
32//!
33//! The RESOURCES are the same kind of list, and the catalog round made them one: a root's
34//! `#[ingraph(resource)]` fields say which resources exist, under which mount, and from which one
35//! source — so the entry drives them itself, before anything else is built, exactly as the ruled
36//! sequence orders it. The only ones it does NOT drive are the `factory` resources, whose options
37//! close over something the application holds; those stay `prepare`'s, which still runs before the
38//! first node.
39//!
40//! Every other step needs a fact the root's own declaration does not carry, and the three-author
41//! wall is why: what a node SUBSCRIBES to is written in that node's declaration, which this derive
42//! cannot see. So the topology, the write lanes and the engines all enter as parameters, and each
43//! one is the narrowest shape that carries what it must:
44//!
45//! | step | who states it | how it arrives |
46//! |---|---|---|
47//! | parse | the application | already typed, as `<Root>Options` |
48//! | validate | the DECLARATIONS' topology + this deployment's enablement | a [`Plan`], whose enablement AND catalog the entry replaces with the root's own |
49//! | create — declared resources | THIS EMISSION | one call per `resource` field, from the source its declaration names |
50//! | create — `factory` resources, slots | the party that can NAME them | `prepare`, driven against the walk |
51//! | create — nodes AND origins | THIS EMISSION | one call per declared mount |
52//! | wire + ignite | the party that can name the operators' types | `wire`, handed the built nodes and the wiring walk |
53//! | sources last | the ENTRY | [`Ignition::into_app`] is never the closure's to call |
54//!
55//! # THE ORIGIN TIER is five lines, and only the CONVERGED door writes them
56//!
57//! A `#[ingraph(origin)]` field names a source mounted as a HEAD whose one out-edge IS its feed. The
58//! converged door writes the whole of it: `Blueprint::origin` declares it, `Creation::node` builds
59//! it from its own section, `Wiring::bridge` opens its edge from the PRODUCER's end, `Wiring::enrol`
60//! registers it, and `Ignition::origin_kept` puts it on an engine with that edge as its feed.
61//!
62//! `launch_wired` writes ONE of them — the construction — and stops there, which is the same
63//! division it already keeps: the caller states the plan and holds the wiring walk, so the closure
64//! that already names the operators' types is the party that spells the bridge. The origin therefore
65//! comes out of that door in the bag, built and unmounted.
66//!
67//! The last row is the one worth reading twice. `wire` hands back an [`Ignition`], not an [`App`],
68//! so a caller may register bodies, teardowns and sources on it and cannot spend the moment they
69//! start: SOURCES LAST stays structural through the emitted door exactly as it is inside the
70//! ignition itself.
71//!
72//! # THE PRE-IGNITION UNWIND is emitted here, because the values are the WALK's
73//!
74//! A launch that refuses before anything ignited is holding everything it has built so far, and the
75//! ruling says those values SAY their goodbyes rather than merely dropping. Nothing about that is
76//! the framework's to do alone: the values live in this entry's own locals, which is precisely what
77//! *ownership never left the launch walk* means. So the walk is emitted in fallible PHASES, each
78//! with ONE refusal arm that hands its walk and a [`Staging`] ledger to that walk's own `unwind`:
79//!
80//! | phase | what the ledger reaches | who says it |
81//! |---|---|---|
82//! | resources, `prepare`, the node pass | the bag's filled slots | [`Creation::unwind`] |
83//! | the wiring pass | each wired-but-unignited party's operator, or the value the wiring never reached | [`Wiring::unwind`] |
84//!
85//! Two shapes make that work and neither is decoration. The node bag is declared EMPTY and filled
86//! slot by slot, because a struct literal's earlier temporaries are dropped by the very `?` that
87//! abandons it — there would be nothing left to say goodbye to. And every per-mount holder is
88//! declared BEFORE the phase that fills it, so one arm reaches all of them rather than one arm per
89//! step. Each phase's outcome is bound to a local before it is matched, because the block borrows
90//! the walk the unwind then consumes.
91//!
92//! The IGNITION pass keeps its `?`: by then the framework owns the failure — see `Ignition::unwind`,
93//! which states what it does and does not reach.
94//!
95//! [`Creation::node`]: ../../ingraph/struct.Creation.html#method.node
96//! [`Creation::unwind`]: ../../ingraph/struct.Creation.html#method.unwind
97//! [`Wiring::unwind`]: ../../ingraph/struct.Wiring.html#method.unwind
98//! [`Staging`]: ../../ingraph/struct.Staging.html
99//! [`Ignition`]: ../../ingraph/struct.Ignition.html
100//! [`Ignition::into_app`]: ../../ingraph/struct.Ignition.html#method.into_app
101//! [`Plan`]: ../../ingraph/struct.Plan.html
102//! [`App`]: ../../ingraph/struct.App.html
103
104use proc_macro2::TokenStream;
105use quote::{format_ident, quote};
106
107use crate::{
108  catalog::{Catalog, ResourceField, ResourceSource, default_resources_name},
109  emit::{framework, leading, parameter},
110  graph::{FusedMember, OriginMount},
111  options::default_options_name,
112};
113
114/// The two goodbye arms' own suite — the resource word's routing and the pre-ignition unwind.
115/// Beside the entry's suite for the ROSTERS' sake, exactly as `emit`'s own topic suites sit.
116#[cfg(test)]
117mod goodbye_tests;
118#[cfg(test)]
119mod origin_tests;
120#[cfg(test)]
121mod tests;
122
123/// `<Root>Nodes` — the name the create walk's product takes.
124///
125/// The options spine's own rule one organ over: the type is derived from the USER's root, so a
126/// `Media` configured by a `MediaOptions` builds a `MediaNodes`.
127#[must_use]
128pub fn default_nodes_name(root: &syn::Ident) -> syn::Ident {
129  format_ident!("{root}Nodes")
130}
131
132/// One ingraph root's launch entry, ready to emit.
133///
134/// It borrows for [`OptionsSpine`](crate::options::OptionsSpine)'s reason: what it needs is the list
135/// the root model already holds, and a second copy of that list is a second thing to keep in step.
136#[derive(Debug, Clone, Copy)]
137pub struct LaunchEntry<'a> {
138  /// Where `ingraph` lives, as the declaration named it.
139  pub krate: &'a syn::Path,
140  /// The root's own visibility — what the entry and the node bag take.
141  pub vis: &'a syn::Visibility,
142  /// The root type, whose name both emitted names derive from.
143  pub root: &'a syn::Ident,
144  /// The NODES, in declaration order.
145  pub nodes: &'a [syn::Type],
146  /// The mount NAMES beside them, in that same order — the sections' keys, and the names a refusal
147  /// reports a node under.
148  pub mounts: &'a [syn::Ident],
149  /// The RESOURCES, in declaration order — the create walk's FIRST step.
150  pub resources: &'a [ResourceField],
151  /// The SLOT-BEARING members, in declaration order — LAYER TWO's list and the sole-default law's.
152  ///
153  /// A fused member is a retrieving declaration, so it is the tier that owns corpora: what the
154  /// launch reads off each one is `Habitats::make` (the homes it makes, in the targets its own legs
155  /// name), `Habitats::TARGETS` (those same targets as demands, which is what mounts them) and
156  /// `Habitats::UNBOUND` (the corpora whose legs named nothing, which the deployment's catalog
157  /// binds). Empty is the ordinary state of a graph that retrieves nothing, and it is what makes all
158  /// three emissions disappear rather than emit a loop over no members.
159  pub fused: &'a [FusedMember],
160  /// The ORIGINS, in declaration order — the tier whose members are HEADS the graph does not feed.
161  ///
162  /// Five lines apiece and no more, which is what an origin's whole shape costs: declared onto the
163  /// blueprint through `Blueprint::origin` (a head, whose effect is pure), built from its own
164  /// section by the same `Creation::node` a node goes through, its ONE out-edge opened from the
165  /// producer's end by `Wiring::bridge`, enrolled, and put on an engine by `Ignition::origin_kept`
166  /// with that edge as its FEED.
167  ///
168  /// Empty is the ordinary state, and it is what makes every line of this tier disappear.
169  pub origins: &'a [OriginMount],
170}
171
172impl LaunchEntry<'_> {
173  /// EVERY MEMBER THE CREATE WALK BUILDS, in declaration order within each tier — the nodes, then
174  /// the origins.
175  ///
176  /// One iterator because the BAG is one bag: the slot a built member lands in, the taker that
177  /// empties it and the `Debug` row that reports it are the same three lines for either tier. What
178  /// the two differ by is the DOOR each is built through — see [`built`](Self::built) — and
179  /// everything AFTER the build: declaring, wiring, igniting, which are written apart.
180  fn built_members(&self) -> impl Iterator<Item = (&syn::Ident, &syn::Type)> {
181    self.mounts.iter().zip(self.nodes).chain(
182      self
183        .origins
184        .iter()
185        .map(|origin| (&origin.mount, &origin.ty)),
186    )
187  }
188
189  /// THE CREATE WALK'S OWN LINES, one per built member: a node's through `Creation::node`, an
190  /// origin's through `Creation::origin`.
191  ///
192  /// # Two doors, and the same walk either side of them
193  ///
194  /// A node states its construction through `AsyncConstructor`; an origin states it through its OWN
195  /// face — `Source::build` or `AsyncSource::build` — reached under the mode its declaration named.
196  /// Both lines read the same section shape, spend the same bare-options probe and stop at the same
197  /// first refusal, so what differs is the door's name and the projection the probe is spelled over.
198  ///
199  /// The origin's line WAS the node's. `build` signed a `Context` — a running body's window the
200  /// create stage has not got — so the walk could not reach it, the road detoured origin
201  /// construction through `AsyncConstructor`, and every origin on it wrote a second options seat that
202  /// nothing read. The window is `&Resources` on both faces now, and the second seat went with the
203  /// detour.
204  fn built(&self, creation: &TokenStream, section: &TokenStream) -> Vec<TokenStream> {
205    let krate = self.krate;
206    // The probes are reached through the SHELF like every other framework name: a `#[macro_export]`
207    // macro lives at the crate root, and `drive` re-exports it so that the module path the shelf
208    // mirrors exists — the four gates' own arrangement, one organ over.
209    let bare = framework(krate, &["drive"], "bare_options");
210    let bare_origin = framework(krate, &["drive"], "bare_origin_options");
211
212    let nodes = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
213      let key = mount.to_string();
214      quote! {
215        __ingraph_nodes.#mount = #creation::node::<#node>(
216          &mut __ingraph_creation,
217          #key,
218          ::core::option::Option::map(options.#mount, #section::unshelved),
219          #bare!(#node),
220        ).await?;
221      }
222    });
223    let origins = self.origins.iter().map(|origin| {
224      let (mount, ty) = (&origin.mount, &origin.ty);
225      let key = mount.to_string();
226      quote! {
227        __ingraph_nodes.#mount = #creation::origin::<#ty>(
228          &mut __ingraph_creation,
229          #key,
230          ::core::option::Option::map(options.#mount, #section::unshelved),
231          #bare_origin!(#ty),
232        ).await?;
233      }
234    });
235    nodes.chain(origins).collect()
236  }
237
238  /// The node bag and the entry that fills it.
239  #[must_use]
240  pub fn emit(&self) -> TokenStream {
241    let bag = self.bag();
242    let takers = self.takers();
243    let debug = self.debug();
244    let entry = self.entry();
245    let converged = self.converged();
246    quote! {
247      #bag
248      #takers
249      #debug
250      #entry
251      #converged
252    }
253  }
254
255  /// `<Root>Nodes` — one slot per declared mount, `None` for the ones this deployment does not
256  /// launch.
257  fn bag(&self) -> TokenStream {
258    let vis = self.vis;
259    let root = self.root;
260    let name = default_nodes_name(root);
261    let fields = self.built_members().map(|(mount, node)| {
262      let doc = leading(&format!(
263        "The member this deployment built at `{mount}` — `None` where it does not launch one."
264      ));
265      quote! {
266        #[doc = #doc]
267        pub(crate) #mount: ::core::option::Option<#node>,
268      }
269    });
270    let doc = leading(&format!(
271      "What one launch of [`{root}`] BUILT — one slot per declared node and one per declared \
272       ORIGIN, filled for the ones this deployment runs.\n\nIt is the create walk's product and the \
273       wiring stage's input: a member comes out of it once, by the mount name its section was \
274       written under, and goes into the resident that will run it — or, for an origin, onto the \
275       engine its own life runs on. A slot left `None` is presence-is-enablement arriving at the \
276       far end — nobody named that member, so nothing was built for it, and there is nothing to \
277       wire."
278    ));
279    quote! {
280      #[doc = #doc]
281      #vis struct #name {
282        #(#fields)*
283      }
284    }
285  }
286
287  /// One `take_<mount>` per node — the door the wiring closure spends a built value through.
288  ///
289  /// A TAKE rather than a borrow, because a resident OWNS the operator it runs: the value has to
290  /// leave the bag, and it may leave it once. `Assembly::take_cadences` is the same verb one stage
291  /// on, for the same reason.
292  fn takers(&self) -> TokenStream {
293    let vis = self.vis;
294    let name = default_nodes_name(self.root);
295    let takers = self.built_members().map(|(mount, node)| {
296      let take = format_ident!("take_{mount}");
297      let doc = leading(&format!(
298        "Take the member built at `{mount}`, leaving the slot empty — `None` where this deployment \
299         does not launch it, and `None` again on a second ask."
300      ));
301      quote! {
302        #[doc = #doc]
303        #[inline]
304        #vis fn #take(&mut self) -> ::core::option::Option<#node> {
305          ::core::option::Option::take(&mut self.#mount)
306        }
307      }
308    });
309    quote! {
310      impl #name {
311        #(#takers)*
312      }
313    }
314  }
315
316  /// A `Debug` reporting which slots are FILLED, and never the nodes themselves.
317  ///
318  /// The options spine's trade, made again for the same reason: a node is the author's type, and
319  /// deriving here would put a `Debug` bound on every one of them for the benefit of this line. What
320  /// a start-up log wants is which nodes this deployment built, which is exactly what the presence
321  /// of each slot says.
322  fn debug(&self) -> TokenStream {
323    let name = default_nodes_name(self.root);
324    let fields = self.built_members().map(|(mount, _ty)| {
325      let key = mount.to_string();
326      quote!(.field(#key, &::core::option::Option::is_some(&self.#mount)))
327    });
328    quote! {
329      impl ::core::fmt::Debug for #name {
330        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
331          f.debug_struct(::core::stringify!(#name))
332            #(#fields)*
333            .finish()
334        }
335      }
336    }
337  }
338
339  /// The catalog half of this root's list — see [`crate::catalog`].
340  fn catalog(&self) -> Catalog<'_> {
341    Catalog {
342      krate: self.krate,
343      vis: self.vis,
344      root: self.root,
345      resources: self.resources,
346    }
347  }
348
349  /// THE CREATE WALK'S FIRST STEP: every resource whose source the DECLARATION names, built before
350  /// anything else and in declaration order.
351  ///
352  /// Two sources land here and one does not. A `#[ingraph(resource)]` field is built from the
353  /// deployment's own section, falling back to the options' `Default` where the document wrote none
354  /// — the same probe a bare node section runs at, spelled at the one kind of site that can answer
355  /// it. A `factory = "path::fn"` field is built from what that function returns, called by this
356  /// walk. A bare `factory` field is neither: its options are the application's to hand over, so it
357  /// belongs to `prepare`, which runs immediately after this and still before the first node.
358  ///
359  /// Both closures are THUNKS because the walk is lazy: a resource nothing enabled demands is never
360  /// built, so its section is never read and its initializer is never called.
361  ///
362  /// The section values are destructured out of the options FIRST, under prefixed bindings. A move
363  /// out of one field leaves the rest of the options whole for the node pass, and the prefix is what
364  /// keeps a resource mounted at `options` or `plan` from shadowing the entry's own parameters.
365  fn resource_pass(&self) -> TokenStream {
366    if self.resources.is_empty() {
367      return TokenStream::new();
368    }
369    let krate = self.krate;
370    let creation = framework(krate, &["drive"], "Creation");
371    let bare = framework(krate, &["drive"], "bare_resource_options");
372
373    let binding = |mount: &syn::Ident| format_ident!("__ingraph_resource_{mount}");
374    let catalog = self.catalog();
375    let taken = catalog.has_block().then(|| {
376      let block = default_resources_name(self.root);
377      let fields = catalog.sections().map(|field| {
378        let (mount, held) = (&field.mount, binding(&field.mount));
379        quote!(#mount: #held,)
380      });
381      quote! {
382        let #block { #(#fields)* } = options.resources;
383      }
384    });
385
386    let built = self
387      .resources
388      .iter()
389      .filter(|field| field.source.is_walked())
390      .map(|field| {
391        let ty = &field.ty;
392        let sourced = match &field.source {
393          ResourceSource::Section => {
394            let held = binding(&field.mount);
395            quote!(move || ::core::option::Option::or_else(#held, || #bare!(#ty)))
396          }
397          ResourceSource::Initializer(path) => quote!(|| ::core::option::Option::Some(#path())),
398          // Filtered out above: a bare `factory` is the application's own door.
399          ResourceSource::Prepare => TokenStream::new(),
400        };
401        // THE `teardown` WORD, cashed: the only difference the word makes anywhere is which of the
402        // two doors this line names, and the one it names is what puts the built handle in the
403        // context's own release list — said LAST of everything the launch built.
404        let door = if field.teardown {
405          quote!(declared_resource_saying_goodbye)
406        } else {
407          quote!(declared_resource)
408        };
409        quote! {
410          #creation::#door::<#ty, _>(&mut __ingraph_creation, #sourced).await?;
411        }
412      });
413
414    quote! {
415      #taken
416      #(#built)*
417    }
418  }
419
420  /// **LAYER TWO** — one call per slot-bearing member, run after the resources are built and before
421  /// the first node.
422  ///
423  /// # The completeness law, as a position in the walk
424  ///
425  /// Every mounted target's homes are made HERE, each on the face its own resource declared, and the
426  /// whole set finishes before anything is constructed, wired or ignited. So a mixed node — a
427  /// `title` in a blocking full-text mount, an `embedding` in an awaited remote one — has both sides
428  /// made, and neither is skipped for the other being present: the union of the members' steps is
429  /// the cover.
430  ///
431  /// The BARRIER is structural rather than a discipline: this sits inside the create walk's own
432  /// fallible phase, so a refusal takes the same arm every other create failure takes and everything
433  /// already built says its goodbyes. A launch that served first would have a request reach a corpus
434  /// that does not exist yet.
435  ///
436  /// # Why the loop is over MEMBERS and not over RESOURCES
437  ///
438  /// The root holds a list of member types and a list of resource types, and the PAIRING between
439  /// them is a fact of neither: which targets a declaration's legs point at is written in the
440  /// DECLARATION. A `resources × members` loop here would demand that every mounted target be a
441  /// home for every member, which is false of every mixed deployment there is. So the step is
442  /// emitted where the pairing is known and the root drives one call per member — with one visitor
443  /// per target even so, the create walk keeping the machines it builds.
444  fn habitat_pass(&self) -> TokenStream {
445    if self.fused.is_empty() {
446      return TokenStream::new();
447    }
448    let krate = self.krate;
449    let habitats = framework(krate, &["drive"], "Habitats");
450    let steps = self.fused.iter().map(|member| {
451      let ty = &member.ty;
452      quote! {
453        <#ty as #habitats>::make(&mut __ingraph_creation).await?;
454      }
455    });
456    quote!(#(#steps)*)
457  }
458
459  /// **THE UNBOUND CORPORA**, stated on the plan before the validate walk — the sole-default law's
460  /// own input.
461  ///
462  /// A leg that WROTE `resource = "…"` is bound at the word and states nothing here. This is the
463  /// other case: a corpus that needs a resource of a KIND and named none, which only the
464  /// deployment's own catalog can settle — exactly one kind-compatible resource declared and the leg
465  /// takes it, zero or several and the launch refuses listing the candidates.
466  ///
467  /// It is what makes those laws reachable from an EMITTED launch. The resolution has been in the
468  /// launch floor since the binding round and had no caller but a hand-wired arrangement, which by
469  /// this crate's own rule made it a promise rather than a rule; this is the caller.
470  fn binding_pass(&self, plan: &TokenStream) -> TokenStream {
471    if self.fused.is_empty() {
472      return TokenStream::new();
473    }
474    let krate = self.krate;
475    let habitats = framework(krate, &["drive"], "Habitats");
476    let rows = self.fused.iter().map(|member| {
477      let ty = &member.ty;
478      quote! {
479        for __ingraph_corpus in <#ty as #habitats>::UNBOUND {
480          __ingraph_plan = #plan::binding(
481            __ingraph_plan,
482            ::core::convert::Into::into(__ingraph_corpus),
483          );
484        }
485      }
486    });
487    quote!(#(#rows)*)
488  }
489
490  /// **THE MOUNTS**, stated on the plan before the validate walk — every target this root's members
491  /// point at, and the reason a read-only deployment gets a store at all.
492  ///
493  /// A resource is built for whoever holds a `Shared<R>`, and the launch can see one kind of holder:
494  /// a node with such a field. The other kind is the WIRE — a search resolver the application hands
495  /// the handle to after the launch, which appears in no list this entry reads. Without this pass a
496  /// deployment that only READS its corpora asks for nothing, gets no store, and has layer two make
497  /// no homes; the first query then opens an index nobody has created.
498  ///
499  /// The declaration is the party that knows, because the pairing lives there and nowhere else —
500  /// `Habitats::TARGETS`, the same rows `make` spends one step apiece on. A write mount and a
501  /// read-only mount state it identically: whether some node happens to land into a target is not a
502  /// fact about whether that target has to exist.
503  ///
504  /// What stays lazy is the resource NOTHING points at: a model behind a `Shared<R>` field on a node
505  /// this deployment does not launch is still never built.
506  fn mount_pass(&self, plan: &TokenStream) -> TokenStream {
507    if self.fused.is_empty() {
508      return TokenStream::new();
509    }
510    let krate = self.krate;
511    let habitats = framework(krate, &["drive"], "Habitats");
512    let rows = self.fused.iter().map(|member| {
513      let ty = &member.ty;
514      quote! {
515        for __ingraph_mount in <#ty as #habitats>::TARGETS {
516          __ingraph_plan = #plan::mounting(__ingraph_plan, __ingraph_mount());
517        }
518      }
519    });
520    quote!(#(#rows)*)
521  }
522
523  /// `mut` where there is a MEMBER whose unbound corpora could be stated on the plan — the same rule
524  /// [`mutable`](Self::mutable) keeps one stage on, and for the same reason: an emitted `mut` nobody
525  /// spends is a warning in somebody else's crate.
526  ///
527  /// The hand-wired door has no use for it: there the plan is a PARAMETER, so what varies is whether
528  /// it is rebound at all — see [`entry`](Self::entry).
529  fn mutable_plan(&self) -> TokenStream {
530    if self.fused.is_empty() {
531      TokenStream::new()
532    } else {
533      quote!(mut)
534    }
535  }
536
537  /// The NODE BAG, empty — one `None` per declared mount, filled in as the create walk builds.
538  ///
539  /// The bag is declared BEFORE the fallible steps and filled slot by slot, rather than written as
540  /// one struct literal over N calls, and that is the pre-ignition unwind's whole precondition: a
541  /// literal's earlier temporaries are dropped by the `?` that abandons it, so the values a refusal
542  /// leaves behind would be gone before anything could say goodbye to them. Filled in place, they
543  /// are still the walk's, and [`staged_from_bag`](Self::staged_from_bag) is what reaches them.
544  fn empty_bag(&self) -> TokenStream {
545    let bag = default_nodes_name(self.root);
546    let slots = self
547      .built_members()
548      .map(|(mount, _ty)| quote!(#mount: ::core::option::Option::None,));
549    quote!(#bag { #(#slots)* })
550  }
551
552  /// `mut` where there is a MEMBER to spend it on — a node or an origin.
553  ///
554  /// A root whose fields are all resources builds nothing, so its bag is never assigned into — and
555  /// an emitted `mut` nobody uses is a warning in somebody else's crate, which is the one thing an
556  /// expansion may not leave behind.
557  fn mutable(&self) -> TokenStream {
558    if self.mounts.is_empty() && self.origins.is_empty() {
559      TokenStream::new()
560    } else {
561      quote!(mut)
562    }
563  }
564
565  /// `mut` where there is a GOODBYE LEDGER to push to — the NODE tier alone.
566  ///
567  /// [`mutable`](Self::mutable)'s narrower twin, and the two differ for a reason worth stating
568  /// rather than deriving: an origin is never STAGED. `Staging::declared` is written over
569  /// `Declared`, whose `TEARDOWN` word and `goodbye` an origin has neither of — `#[ingraph::source]`
570  /// emits no teardown seat, so an origin's whole wind-down is its own [`Drop`], which is the
571  /// shipped posture for every value that enrols in no other. So a root with origins and no nodes
572  /// has a bag that IS assigned into and a ledger that is not.
573  fn mutable_staged(&self) -> TokenStream {
574    if self.mounts.is_empty() {
575      TokenStream::new()
576    } else {
577      quote!(mut)
578    }
579  }
580
581  /// THE CREATE WALK'S OWN LEDGER: every node the bag still holds, in declaration order.
582  ///
583  /// Declaration order IS enrolment order, and the chain says its list backwards — so nothing here
584  /// reverses anything.
585  fn staged_from_bag(&self) -> TokenStream {
586    let krate = self.krate;
587    let bag = default_nodes_name(self.root);
588    let staging = framework(krate, &["drive"], "Staging");
589    let taken = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
590      let take = format_ident!("take_{mount}");
591      let key = mount.to_string();
592      quote! {
593        if let ::core::option::Option::Some(__ingraph_value) =
594          #bag::#take(&mut __ingraph_nodes)
595        {
596          #staging::declared::<#node>(&mut __ingraph_staged, #key, __ingraph_value);
597        }
598      }
599    });
600    let mutable = self.mutable_staged();
601    quote! {
602      {
603        let #mutable __ingraph_staged = #staging::new();
604        #(#taken)*
605        __ingraph_staged
606      }
607    }
608  }
609
610  /// THE WIRING WALK'S LEDGER: each mount's wired-but-unignited party, or the value the wiring
611  /// never reached.
612  ///
613  /// One or the other and never both — a node leaves the bag exactly when its resident is made — so
614  /// the two arms of the match are the two places one mount's value can be at the moment a wiring
615  /// step refuses. A party that WAS wired is staged as its operator alone: the rest of the resident
616  /// goes first, which is what lets the resource a goodbye reaches for be one handle closer to
617  /// releasable.
618  fn staged_from_bodies(&self) -> TokenStream {
619    let krate = self.krate;
620    let bag = default_nodes_name(self.root);
621    let staging = framework(krate, &["drive"], "Staging");
622    let taken = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
623      let mounted = self.mounted(node);
624      let body = format_ident!("__ingraph_body_{mount}");
625      let take = format_ident!("take_{mount}");
626      let key = mount.to_string();
627      quote! {
628        match ::core::option::Option::take(&mut #body) {
629          ::core::option::Option::Some(__ingraph_body) => {
630            // WHERE the value has got to by now is the CELL's business: inside a resident at the
631            // buffered pair, in a lane mount's warm set at the streaming one.
632            #mounted::stage(&mut __ingraph_staged, #key, __ingraph_body);
633          }
634          ::core::option::Option::None => {
635            if let ::core::option::Option::Some(__ingraph_value) =
636              #bag::#take(&mut __ingraph_nodes)
637            {
638              #staging::declared::<#node>(&mut __ingraph_staged, #key, __ingraph_value);
639            }
640          }
641        }
642      }
643    });
644    let mutable = self.mutable_staged();
645    quote! {
646      {
647        let #mutable __ingraph_staged = #staging::new();
648        #(#taken)*
649        __ingraph_staged
650      }
651    }
652  }
653
654  /// `<Root>::launch` — the ruled sequence, walked once.
655  fn entry(&self) -> TokenStream {
656    let krate = self.krate;
657    let vis = self.vis;
658    let root = self.root;
659    let options = default_options_name(root);
660    let bag = default_nodes_name(root);
661
662    let app = framework(krate, &["drive"], "App");
663    let constructor = framework(krate, &["drive"], "AsyncConstructor");
664    let creation = framework(krate, &["drive"], "Creation");
665    let ignition = framework(krate, &["drive"], "Ignition");
666    let launch_error = framework(krate, &["drive"], "LaunchError");
667    let plan = framework(krate, &["drive"], "Plan");
668    let wired = framework(krate, &["drive"], "Wired");
669    let wiring = framework(krate, &["drive"], "Wiring");
670    let registries = framework(krate, &["drive"], "Registries");
671
672    let prepare = parameter("PREPARE");
673    let wire = parameter("WIRE");
674
675    // One `AsyncConstructor::Error` predicate per declared node, discharged at the call site exactly as
676    // the walk's `Describe` predicates are: a root nobody launches carries no obligation, and a node
677    // whose error cannot be erased is refused where the launch is written.
678    let errors = self.nodes.iter().map(|node| {
679      quote! {
680        <#node as #constructor>::Error:
681          ::core::error::Error + ::core::marker::Send + ::core::marker::Sync + 'static,
682      }
683    });
684
685    // THE ORIGINS OWE THE SAME THING THROUGH THEIR OWN ROW. A hand-wired door builds every member
686    // the create walk can build — an origin is constructed from its own section exactly as a node is
687    // — and leaves the ARRANGEMENT to the caller, who states the plan and holds the wiring walk. So
688    // the origin comes out of this door in the bag, and the closure that already names the
689    // operators' types is the party that spells `Wiring::bridge` and `Ignition::origin_bridged` over
690    // it. `launch`/`launch_with` are where the framework does that itself.
691    //
692    // What it takes to BUILD one is the row and the erasable error under it, and no more: this door
693    // ignites nothing, so the `Produced`/`Ordered` mobility the converged road asks for is not owed
694    // here. `Lived<Mode>` is what carries the construction, so it is named even though this door
695    // never drives the life — the two verbs are one row, per the trait's own note.
696    let lived = framework(krate, &["drive"], "Lived");
697    let declared_origin = framework(krate, &["source"], "DeclaredOrigin");
698    let died = framework(krate, &["drive"], "Died");
699    let origin_errors = self.origins.iter().map(|origin| {
700      let ty = &origin.ty;
701      quote! {
702        #ty: #declared_origin + #lived<<#ty as #declared_origin>::Mode>,
703        #died<#ty>:
704          ::core::error::Error + ::core::marker::Send + ::core::marker::Sync + 'static,
705      }
706    });
707
708    // The same predicate for the RESOURCES, and for the same reason: the create walk erases a
709    // resource's own refusal into the launch family, so a resource whose error cannot be erased is
710    // refused where the launch is written rather than inside the walk.
711    let resource = framework(krate, &["resource"], "AsyncResource");
712    let resource_errors = self.resources.iter().map(|field| {
713      let ty = &field.ty;
714      quote! {
715        <#ty as #resource>::Error:
716          ::core::error::Error + ::core::marker::Send + ::core::marker::Sync + 'static,
717      }
718    });
719
720    let resources = self.resource_pass();
721    let habitat = self.habitat_pass();
722    let bindings = self.binding_pass(&plan);
723    let mounts = self.mount_pass(&plan);
724    // THE PLAN IS REBOUND ONLY WHERE THERE IS SOMETHING TO STATE ON IT. A root that retrieves
725    // nothing states no corpus, so the parameter goes straight into the walk and this door's
726    // expansion is what it always was — an emitted rename nobody spends would be noise in somebody
727    // else's crate, which is the same rule the `mut` above keeps.
728    let (held, hold) = if self.fused.is_empty() {
729      (quote!(plan), TokenStream::new())
730    } else {
731      (
732        quote!(__ingraph_plan),
733        quote!(let mut __ingraph_plan = plan;),
734      )
735    };
736
737    let section = framework(krate, &["drive"], "NodeSection");
738    let built = self.built(&creation, &section);
739    let empty = self.empty_bag();
740    let mutable = self.mutable();
741    let staged = self.staged_from_bag();
742
743    // THE ORIGIN PARAGRAPH IS CONDITIONAL, for the same reason the emitted `mut` is: a root that
744    // mounts no origin should carry no sentence about one, and a doc attribute is a token like any
745    // other — an unconditional paragraph would put this tier's vocabulary in every expansion.
746    let origins = if self.origins.is_empty() {
747      String::new()
748    } else {
749      "\n\nAn `#[ingraph(origin)]` field is BUILT by this door and mounted by nobody: the \
750       arrangement is the caller's `plan` here, so the origin comes out in the node bag and the \
751       `wire` closure — which already names the operators' types — is what opens its edge and puts \
752       it on an engine. `launch` is the door that does the whole of it."
753        .to_owned()
754    };
755    let doc = leading(&format!(
756      "Launch this deployment of [`{root}`] — validate, create, wire, ignite.\n\n`options` is what \
757       this deployment RUNS and `plan` is what the declarations SAY: the entry replaces the plan's \
758       enablement with the options' own, so presence-is-enablement enters here and nowhere \
759       else.\n\n`prepare` drives the create walk's first two steps — the resources an enabled node \
760       demands, and the slots they open — because naming a resource type or a slot's declaration is \
761       something only the party that has them can do. It runs BEFORE any node is built, which is \
762       the ruled order: a construction reaching `ctx.shared::<R>()` finds what this put \
763       there.\n\n`wire` is handed the built nodes and the wiring walk, and gives back the ignition \
764       it filled. It spans the wiring and the engines because both name the operators' types, which \
765       an emission cannot. What it does NOT hold is the moment the sources start: this entry spends \
766       that, so SOURCES LAST stays a fact of the door rather than a rule a caller keeps.{origins}\n\n# \
767       Errors\n\nEvery refusal of the sequence, under one type: the validate walk's whole \
768       collected list, or the first failure of any walk after it — a resource that would not load, \
769       a node that would not build, an edge that would not connect, an engine that would not start."
770    ));
771
772    let syncs = self.nodes.iter().map(|node| {
773      let mounted = self.mounted(node);
774      quote!(#mounted::SYNC)
775    });
776    let all_sync = leading(
777      "Whether EVERY node this root mounts is on the blocking face — the deployment's own \
778       syncness, folded from one row per mount, read through the MOUNT CELL that node's own two \
779       words selected.\n\nIt is a proof and not a switch: nothing in the launch reads it, and \
780       nothing can, because stable Rust cannot pick an impl by a const. What it is for is an \
781       ASSERTION — `const _: () = assert!(Root::ALL_SYNC);` in a deployment that means to have no \
782       awaited body in it, and a diagnostic anywhere the question is worth printing.\n\nIt reads \
783       BOTH PAIRS, which is why it is spelled through the cell: `Driven::SYNC` is the buffered \
784       pair's row and a `stream` declaration has not got one, so a fold spelled through that trait \
785       alone did not compile for a root with a streaming node in it. `Streams::SYNC` is the same \
786       fact one pair over.\n\nNo row of it can lie, and it takes two facts to say why. The const \
787       is set by the blanket rows and by nothing an author can write, so a node cannot state a \
788       syncness its face does not have; and the face itself is pinned against the words the \
789       declaration wrote by the `Mount` bound the launch spends beside it, so a mount whose body \
790       awaits and whose declaration stayed bare does not compile at all.",
791    );
792
793    quote! {
794      impl #root {
795        #[doc = #all_sync]
796        #vis const ALL_SYNC: bool = true #(&& #syncs)*;
797
798        #[doc = #doc]
799        #vis async fn launch_wired<#prepare, #wire>(
800          options: #options,
801          plan: #plan,
802          prepare: #prepare,
803          wire: #wire,
804        ) -> ::core::result::Result<#app<Self>, #launch_error>
805        where
806          #prepare: ::core::ops::AsyncFnOnce(
807            &mut #creation<'_>,
808          ) -> ::core::result::Result<(), #launch_error>,
809          #wire: ::core::ops::FnOnce(
810            #bag,
811            #wiring<'_>,
812          ) -> ::core::result::Result<#ignition, #launch_error>,
813          #(#errors)*
814          #(#origin_errors)*
815          #(#resource_errors)*
816        {
817          let __ingraph_enablement = #options::enablement(&options);
818          // THE ROOT-KEY REGISTRIES, built from this deployment's own `[registry]` section — and
819          // read HERE rather than at the wiring walk, because the per-mount sections below are
820          // MOVED out of `options` one field at a time and a borrow of a partly-moved value is not
821          // a borrow.
822          let __ingraph_registries = ::std::sync::Arc::new(
823            #registries::new(::core::clone::Clone::clone(#options::registry(&options))),
824          );
825          // THE SOLE-DEFAULT LAW'S INPUT, stated before the walk that resolves it: every corpus
826          // whose leg named no resource, read off the member that owns it — and beside it every
827          // target those legs DID name, which is what makes this deployment mount them.
828          #hold
829          #bindings
830          #mounts
831          let __ingraph_wired = #plan::validate(
832            #plan::with_resources(
833              #plan::with_enablement(#held, __ingraph_enablement),
834              Self::resources(),
835            ),
836          )?;
837          let mut __ingraph_creation = #wired::create(&__ingraph_wired);
838          let #mutable __ingraph_nodes = #empty;
839          // THE PRE-IGNITION UNWIND, create half: one arm for the whole fallible walk, so a
840          // refusal at any step reaches the values every step before it built. The outcome is
841          // BOUND rather than matched in place — the block borrows the walk it refuses about, and
842          // the unwind consumes it.
843          let __ingraph_created = async {
844            #resources
845            prepare(&mut __ingraph_creation).await?;
846            // LAYER TWO, before the first node: a construction reaching a corpus finds it made.
847            #habitat
848            #(#built)*
849            ::core::result::Result::<(), #launch_error>::Ok(())
850          }.await;
851          if let ::core::result::Result::Err(__ingraph_error) = __ingraph_created {
852            return ::core::result::Result::Err(
853              #creation::unwind(__ingraph_creation, #staged, __ingraph_error),
854            );
855          }
856          let __ingraph_ignition = wire(
857            __ingraph_nodes,
858            {
859              // The hand-wiring closure is handed a walk that ALREADY carries this deployment's
860              // registries, so a by-hand arrangement coordinates through the same tables an
861              // emitted one does without having to know they exist.
862              let mut __ingraph_wiring = #creation::wire(__ingraph_creation);
863              #wiring::set_registries(&mut __ingraph_wiring, __ingraph_registries);
864              __ingraph_wiring
865            },
866          )?;
867          ::core::result::Result::Ok(#ignition::into_app::<Self>(__ingraph_ignition))
868        }
869      }
870    }
871  }
872}
873
874/// **THE CONVERGENCE** — the door a deployment goes through when nothing is wired by hand.
875///
876/// `launch_wired` above takes the topology, the create hook and the wiring closure as parameters,
877/// because a root's own declaration states none of the three. The facts trait is what changed that:
878/// a node STATES its effect, its lane, its edges and its options type, and the root NAMES them
879/// through `<Field as Declared>::…`. So the plan is no longer handed over — it is JOINED here — and
880/// the wiring closure is no longer needed, because the one thing it could do that this cannot is
881/// attach a value only the author can name.
882///
883/// # What still needs a hand, and it is exactly one thing
884///
885/// `prepare`. A bare `factory` resource's options close over something the application holds — a
886/// live handle, a socket, a directory it just made — and no declaration can state a value. So there
887/// are two doors here and not one: [`launch`] for a deployment that needs no hand at all, and
888/// `launch_with` for one whose resources take the application's own. They are the same walk;
889/// the first calls the second with a closure that does nothing.
890///
891/// # What the wiring closure could do that this cannot
892///
893/// Attach a WRITE LANE, a poll context or a journal to a resident. Each of them changes the
894/// resident's TYPE and each is a value the author's own code holds, so a walk that has only the
895/// declarations cannot name one. A node declaring `AsyncLands` therefore comes out of this door carrying
896/// no lane, exactly as it does out of `Wiring::resident` — the launch floor's own honest posture,
897/// one layer up. `launch_wired` stays for the deployments that have one to attach.
898impl LaunchEntry<'_> {
899  /// The two converged doors, and the walk they share.
900  fn converged(&self) -> TokenStream {
901    let krate = self.krate;
902    let vis = self.vis;
903    let root = self.root;
904    let options = default_options_name(root);
905    let bag = default_nodes_name(root);
906
907    let app = framework(krate, &["drive"], "App");
908    let blueprint = framework(krate, &["drive"], "Blueprint");
909    let creation = framework(krate, &["drive"], "Creation");
910    let declared = framework(krate, &["drive"], "Declared");
911    let ignition = framework(krate, &["drive"], "Ignition");
912    // The equation's own name is spelled inside `predicates`; the walk below spends the rest.
913    let launch_error = framework(krate, &["drive"], "LaunchError");
914    let plan = framework(krate, &["drive"], "Plan");
915    let wired = framework(krate, &["drive"], "Wired");
916    let wiring = framework(krate, &["drive"], "Wiring");
917    let registries = framework(krate, &["drive"], "Registries");
918    let produced_of = framework(krate, &["drive"], "Produced");
919    let prepare = parameter("PREPARE");
920
921    let predicates = self.predicates();
922    let resources = self.resource_pass();
923    let habitat = self.habitat_pass();
924    let bindings = self.binding_pass(&plan);
925    let mounts = self.mount_pass(&plan);
926    let mutable_plan = self.mutable_plan();
927
928    // ONE LINE PER FIELD, AND IT MOUNTS EITHER KIND. The door is not named here — the CELL is, and
929    // the cell is what the node's own `stream` word selected: `Blueprint::node` for a buffered
930    // declaration and `Blueprint::stream` for a streaming one. This expansion cannot see the word
931    // and does not have to.
932    let handles = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
933      let mounted = self.mounted(node);
934      let handle = format_ident!("__ingraph_at_{mount}");
935      let key = mount.to_string();
936      quote! {
937        let #handle = #mounted::declare(&mut __ingraph_blueprint, #key);
938      }
939    });
940
941    // THE ORIGINS, declared through their own door and with NO cell in front of it. A node's line is
942    // addressed to `Worn<Pair, Mode>` because the pair word lives on the node's own declaration and
943    // this expansion cannot see it; an origin has no pair axis at all — the mode axis it does have
944    // is already collapsed inside `Lived<M>`, which `Blueprint::origin` and `Ignition::origin_kept`
945    // are each written once over — so there is nothing here for a cell to dispatch on and the door
946    // is named directly.
947    let origin_handles = self.origins.iter().map(|origin| {
948      let (mount, ty) = (&origin.mount, &origin.ty);
949      let handle = format_ident!("__ingraph_at_{mount}");
950      let key = mount.to_string();
951      quote! {
952        let #handle = #blueprint::origin::<#ty>(&mut __ingraph_blueprint, #key);
953      }
954    });
955
956    let section = framework(krate, &["drive"], "NodeSection");
957    // THE PER-NODE STREAM SEATS, taken before the sections are moved out — the `channels` block's
958    // own arrangement, one row over. `None` is what a section that wrote none states and what a
959    // buffered mount always gets, so a deployment with no streaming node in it builds no seats at
960    // all.
961    let seats = self.mounts.iter().map(|mount| {
962      let seat = format_ident!("__ingraph_seats_{mount}");
963      quote! {
964        let #seat = ::core::option::Option::map(
965          ::core::option::Option::and_then(
966            ::core::option::Option::as_ref(&options.#mount),
967            #section::stream,
968          ),
969          ::core::clone::Clone::clone,
970        );
971      }
972    });
973
974    // THE SHELF, read before the sections are moved out: a `channels` block a deployment wrote is
975    // what wins over the author's declared default and over the framework's shipped constant, and
976    // this is the road that layer travels. A node whose section says nothing is left to the two
977    // layers under it.
978    let channels = framework(krate, &["drive"], "Channels");
979    let tuned = self.mounts.iter().map(|mount| {
980      let key = mount.to_string();
981      quote!(.mounted(#key, ::core::option::Option::as_ref(&options.#mount)))
982    });
983
984    // ONE LINE PER MEMBER THE CREATE WALK BUILDS, origins among them — each through its own tier's
985    // door, per `built`. Construction is where the two tiers read the same section and spend the same
986    // probe, and nothing about the difference between them is reached yet.
987    let built = self.built(&creation, &section);
988    let empty = self.empty_bag();
989    let mutable = self.mutable();
990    let staged_bag = self.staged_from_bag();
991    let staged_bodies = self.staged_from_bodies();
992
993    // The per-mount holders, declared BEFORE the wiring's own fallible walk so that ONE arm can
994    // reach every one of them — the same precondition the empty bag serves one stage earlier.
995    let holders = self.mounts.iter().map(|mount| {
996      let body = format_ident!("__ingraph_body_{mount}");
997      let feed = format_ident!("__ingraph_feed_{mount}");
998      let intake = format_ident!("__ingraph_intake_{mount}");
999      quote! {
1000        let mut #body = ::core::option::Option::None;
1001        let mut #feed = ::core::option::Option::None;
1002        let mut #intake = ::core::option::Option::None;
1003      }
1004    });
1005
1006    // ONE HOLDER PER ORIGIN, carrying all three things its ignition needs at once — the built value,
1007    // the far half of its out-edge, and its enrolment. They travel together because they are taken
1008    // together: the enrolment is minted on the WIRING walk (the ignition has no registry to ask) and
1009    // spent on the ignition one, and an enrolment made for an origin whose value or edge turned out
1010    // to be absent would be a party the shutdown waits on and nothing ever settles.
1011    let origin_holders = self.origins.iter().map(|origin| {
1012      let mount = &origin.mount;
1013      let bridge = format_ident!("__ingraph_bridge_{mount}");
1014      quote!(let mut #bridge = ::core::option::Option::None;)
1015    });
1016
1017    // THE INTAKE PASS, and it is a pass of its own rather than the first two lines of the next one.
1018    //
1019    // An edge is OPENED by whichever side reaches it first, and its type is the CONSUMER's input.
1020    // A producer whose downstream set has several products cannot open one — which product an edge
1021    // carries is written in the consumer's own declaration, and this walk holds names rather than
1022    // types — so it seats the product that consumer's inbox already named. That is only possible if
1023    // every mounted node's receiving halves have been taken before any node is wired, which is what
1024    // this pass is: field order stops being load-bearing, and a demultiplexer declared before its
1025    // subscribers mounts exactly as one declared after them does.
1026    //
1027    // The bag is NOT drawn from here. A refusal in the pass below has to find every unwired node's
1028    // value still in it — that is what the pre-ignition unwind stages goodbyes from — so the value
1029    // stays where it was and only the edges are opened. The two are the same set: `Creation::node`
1030    // fills the bag exactly for the nodes this deployment launches, and `Mount::intake` answers
1031    // `None` for exactly the ones it does not.
1032    let intakes = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
1033      let mounted = self.mounted(node);
1034      let handle = format_ident!("__ingraph_at_{mount}");
1035      let intake = format_ident!("__ingraph_intake_{mount}");
1036      quote! {
1037        // THE CONTAINER ENTRY. What comes back is the RECEIVING HALVES in the shape this node's own
1038        // cell takes them in — ONE inbox at the two driven pairs, and the whole N-edge `Upstreams`
1039        // set at the autonomous one, position by declaration order. This expansion cannot see which
1040        // shape its node wants and does not have to: `Mount::Intake` is the cell answering on the
1041        // declaration's behalf.
1042        #intake = #mounted::intake(&mut __ingraph_wiring, #handle)?;
1043      }
1044    });
1045
1046    let wire = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
1047      let mounted = self.mounted(node);
1048      let handle = format_ident!("__ingraph_at_{mount}");
1049      let body = format_ident!("__ingraph_body_{mount}");
1050      let feed = format_ident!("__ingraph_feed_{mount}");
1051      let intake = format_ident!("__ingraph_intake_{mount}");
1052      let seat = format_ident!("__ingraph_seats_{mount}");
1053      let take = format_ident!("take_{mount}");
1054      quote! {
1055        if let ::core::option::Option::Some(__ingraph_operator) = #bag::#take(&mut __ingraph_nodes) {
1056          if let ::core::option::Option::Some(__ingraph_intake) =
1057            ::core::option::Option::take(&mut #intake)
1058          {
1059            // A node the graph itself feeds has no door for anybody else to open — a HEAD is the
1060            // one that is fed from outside, and having no declared source IS what makes it one. It
1061            // publishes into slot zero, which is the one edge a head has.
1062            if <#node as #declared>::UPSTREAMS.is_empty() {
1063              #feed = #wiring::outbox::<#mounted::In>(
1064                &mut __ingraph_wiring,
1065                #handle,
1066              )?;
1067            }
1068            #body = #mounted::wire(
1069              &mut __ingraph_wiring,
1070              #handle,
1071              __ingraph_operator,
1072              __ingraph_intake,
1073              #seat,
1074            )?;
1075          }
1076        }
1077      }
1078    });
1079
1080    // **THE BRIDGE**, opened on the wiring walk and from the PRODUCER's end. Which consumer an
1081    // origin feeds is written in that consumer's own `subscribe(…)` and joined into the plan by type
1082    // identity, so this expansion never names it: `Wiring::bridge` reads the origin's ONE channel
1083    // out-edge off the arrangement and answers the sending half under the origin's own `Produced`
1084    // projection.
1085    //
1086    // The value is taken out of the bag HERE rather than at the ignition, and the order inside the
1087    // block is the reason: an origin whose edge could not be opened — its consumer dark, or itself
1088    // not launched — must leave its value where the pre-ignition unwind can still find it, and must
1089    // not enrol a party that will never settle. So the edge is asked for FIRST and the take happens
1090    // only once all three parts exist.
1091    let bridges = self.origins.iter().map(|origin| {
1092      let (mount, ty) = (&origin.mount, &origin.ty);
1093      let handle = format_ident!("__ingraph_at_{mount}");
1094      let bridge = format_ident!("__ingraph_bridge_{mount}");
1095      let take = format_ident!("take_{mount}");
1096      let key = mount.to_string();
1097      let produced = quote!(#produced_of<#ty>);
1098      quote! {
1099        if let ::core::option::Option::Some(__ingraph_consumer) =
1100          #wiring::bridge::<#produced>(&mut __ingraph_wiring, #handle)?
1101        {
1102          if let ::core::option::Option::Some(__ingraph_origin) =
1103            #bag::#take(&mut __ingraph_nodes)
1104          {
1105            #bridge = ::core::option::Option::Some((
1106              __ingraph_origin,
1107              __ingraph_consumer,
1108              #wiring::enrol(&mut __ingraph_wiring, #key),
1109            ));
1110          }
1111        }
1112      }
1113    });
1114
1115    let ignite = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
1116      let mounted = self.mounted(node);
1117      let body = format_ident!("__ingraph_body_{mount}");
1118      let feed = format_ident!("__ingraph_feed_{mount}");
1119      // BOTH WORDS ARE THE DOOR'S OWN BUSINESS: the cell reads `<#node as Declared>::Pair` and
1120      // `::Mode` off the declaration this expansion cannot see, so what is written here is one
1121      // line that starts a THREAD under a buffered body and hands a mounted LANE to the app's
1122      // cupboard for a streaming one — the party that drives a lane being the party that holds it.
1123      quote! {
1124        if let ::core::option::Option::Some(__ingraph_feeder) = #feed {
1125          #mounted::feeder(&mut __ingraph_ignition, __ingraph_feeder);
1126        }
1127        if let ::core::option::Option::Some(__ingraph_body) = #body {
1128          #mounted::ignite(&mut __ingraph_ignition, __ingraph_body)?;
1129        }
1130      }
1131    });
1132
1133    // **THE ORIGINS, LAST OF ALL** — after every node this deployment runs has its engine, so a
1134    // producer that is STARTED ONCE and runs on its own never waits on a consumer that has not been
1135    // spawned yet. Nothing depends on this for correctness — the edge is bounded and a full one is
1136    // ordinary backpressure — and it is the same *last on, first off* the whole stage is arranged
1137    // around: an origin hears the wind-down at `App::shutdown`'s first step, before a source stops
1138    // admitting and before the framework lets go of any edge.
1139    //
1140    // `origin_kept` rather than `origin_bridged` because a `Bridged` owns a `Stopper` and a stopper
1141    // SAYS THE STOP AS IT GOES: an expansion has nowhere to put a returned handle, so a walk that
1142    // dropped one would wind down the origin it had just started. The world keeps it, and
1143    // `App::origin::<S>()` is where a deployment reaches it.
1144    let origin_ignite = self.origins.iter().map(|origin| {
1145      let (mount, ty) = (&origin.mount, &origin.ty);
1146      let bridge = format_ident!("__ingraph_bridge_{mount}");
1147      let key = mount.to_string();
1148      quote! {
1149        if let ::core::option::Option::Some(
1150          (__ingraph_origin, __ingraph_consumer, __ingraph_party)
1151        ) = #bridge {
1152          #ignition::origin_kept::<#ty>(
1153            &mut __ingraph_ignition,
1154            #key,
1155            __ingraph_origin,
1156            __ingraph_consumer,
1157            // THE COMMAND LINE'S DEPTH, and it governs that line ALONE: a bridged feed is bounded by
1158            // the EDGE, resolved from the declarations and this deployment's own document like every
1159            // other edge. What is left for a number is the door an application says things to the
1160            // origin down, and a door's depth is the framework's shipped answer — a queue of callers
1161            // who are all waiting, where depth buys latency rather than throughput.
1162            #wiring::DOOR_CAPACITY,
1163            __ingraph_party,
1164          )?;
1165        }
1166      }
1167    });
1168
1169    // Conditional, for the reason the hand-wired door's own paragraph is: a root that mounts no
1170    // origin carries no sentence about one.
1171    let origins = if self.origins.is_empty() {
1172      String::new()
1173    } else {
1174      "\n\nAn `#[ingraph(origin)]` field is mounted here too, and is mounted LAST: a source is a \
1175       HEAD the graph does not feed, so what it gets is an engine of its own and its one out-edge \
1176       as its feed. See `App::origin` for the two ends this world then keeps — and note that it \
1177       KEEPS them, because letting go of that handle is telling the origin to wind down."
1178        .to_owned()
1179    };
1180    let plain_doc = leading(&format!(
1181      "**Launch this deployment of [`{root}`] — and wire NOTHING by hand.**\n\nThe whole ruled \
1182       sequence from one value: the arrangement is joined from what each declared node states about \
1183       itself, the deployment's own sections decide who runs, the resources an enabled node demands \
1184       are built before the first construction, the edges are opened and the engines \
1185       started.{origins}\n\nWhat \
1186       comes back is the running world, with an intake door onto every head — see [`App::feeder`]. \
1187       Use [`launch_with`](Self::launch_with) where a `factory` resource's options are the \
1188       application's own to hand over.\n\n# Errors\n\nEvery refusal of the sequence, under one type: \
1189       an upstream this root does not mount, the validate walk's whole collected list, or the first \
1190       failure of any walk after it."
1191    ));
1192    let hooked_doc = leading(&format!(
1193      "Launch this deployment of [`{root}`], giving the create walk the application's own \
1194       hand.\n\n[`launch`](Self::launch)'s walk exactly, with `prepare` run after the declared \
1195       resources are built and BEFORE the first node — which is the ruled order, and what makes a \
1196       construction reaching `ctx.shared::<R>()` find what this put there. It is where a bare \
1197       `#[ingraph(resource(factory))]` gets its options, because those close over a value the \
1198       application holds and no declaration can state one.\n\n# Errors\n\nSee \
1199       [`launch`](Self::launch)."
1200    ));
1201
1202    quote! {
1203      impl #root {
1204        #[doc = #plain_doc]
1205        #vis async fn launch(
1206          options: #options,
1207        ) -> ::core::result::Result<#app<Self>, #launch_error>
1208        where
1209          #predicates
1210        {
1211          Self::launch_with(options, async |_| ::core::result::Result::Ok(())).await
1212        }
1213
1214        #[doc = #hooked_doc]
1215        #vis async fn launch_with<#prepare>(
1216          options: #options,
1217          prepare: #prepare,
1218        ) -> ::core::result::Result<#app<Self>, #launch_error>
1219        where
1220          #prepare: ::core::ops::AsyncFnOnce(
1221            &mut #creation<'_>,
1222          ) -> ::core::result::Result<(), #launch_error>,
1223          #predicates
1224        {
1225          // THE ARRANGEMENT, joined: one call per mounted field, in declaration order, and the
1226          // edges appear by themselves — each node's declared upstreams are looked up among these
1227          // very fields by type identity.
1228          let mut __ingraph_blueprint = #blueprint::new();
1229          #(#handles)*
1230          #(#origin_handles)*
1231          let #mutable_plan __ingraph_plan = #blueprint::into_plan(__ingraph_blueprint)?;
1232          // THE SOLE-DEFAULT LAW'S INPUT, stated before the walk that resolves it: every corpus
1233          // whose leg named no resource, read off the member that owns it — and beside it every
1234          // target those legs DID name, which is what makes this deployment mount them.
1235          #bindings
1236          #mounts
1237
1238          let __ingraph_enablement = #options::enablement(&options);
1239          // THE ROOT-KEY REGISTRIES, built from this deployment's own `[registry]` section — and
1240          // read HERE rather than at the wiring walk, because the per-mount sections below are
1241          // MOVED out of `options` one field at a time and a borrow of a partly-moved value is not
1242          // a borrow.
1243          let __ingraph_registries = ::std::sync::Arc::new(
1244            #registries::new(::core::clone::Clone::clone(#options::registry(&options))),
1245          );
1246          let __ingraph_channels = #channels::new() #(#tuned)*;
1247          #(#seats)*
1248          let __ingraph_wired = #plan::validate(
1249            #plan::with_channels(
1250              #plan::with_resources(
1251                #plan::with_enablement(__ingraph_plan, __ingraph_enablement),
1252                Self::resources(),
1253              ),
1254              __ingraph_channels,
1255            ),
1256          )?;
1257          let mut __ingraph_creation = #wired::create(&__ingraph_wired);
1258          // THE BAG, empty and filled in place — see `LaunchEntry::empty_bag` for why a struct
1259          // literal could not have been the shape.
1260          let #mutable __ingraph_nodes = #empty;
1261          // THE PRE-IGNITION UNWIND, create half. The outcome is BOUND rather than matched in
1262          // place: the block borrows the walk it refuses about, and the unwind consumes it.
1263          let __ingraph_created = async {
1264            #resources
1265            prepare(&mut __ingraph_creation).await?;
1266            // LAYER TWO, before the first node: a construction reaching a corpus finds it made.
1267            #habitat
1268            #(#built)*
1269            ::core::result::Result::<(), #launch_error>::Ok(())
1270          }.await;
1271          if let ::core::result::Result::Err(__ingraph_error) = __ingraph_created {
1272            return ::core::result::Result::Err(
1273              #creation::unwind(__ingraph_creation, #staged_bag, __ingraph_error),
1274            );
1275          }
1276
1277          let mut __ingraph_wiring = #creation::wire(__ingraph_creation);
1278          // BEFORE ANY BODY IS WIRED: a resident takes its handle as it is built, so this reaches
1279          // the walk ahead of the first one.
1280          #wiring::set_registries(&mut __ingraph_wiring, __ingraph_registries);
1281          #(#holders)*
1282          #(#origin_holders)*
1283          // THE PRE-IGNITION UNWIND, wiring half: the parties this walk WIRED and never ignited,
1284          // beside whatever it never reached.
1285          let __ingraph_connected = (|| -> ::core::result::Result<(), #launch_error> {
1286            #(#intakes)*
1287            #(#wire)*
1288            #(#bridges)*
1289            ::core::result::Result::Ok(())
1290          })();
1291          if let ::core::result::Result::Err(__ingraph_error) = __ingraph_connected {
1292            return ::core::result::Result::Err(
1293              #wiring::unwind(__ingraph_wiring, #staged_bodies, __ingraph_error),
1294            );
1295          }
1296          let mut __ingraph_ignition = #wiring::into_assembly(__ingraph_wiring).ignite();
1297          #(#ignite)*
1298          #(#origin_ignite)*
1299          ::core::result::Result::Ok(#ignition::into_app::<Self>(__ingraph_ignition))
1300        }
1301      }
1302    }
1303  }
1304
1305  /// The MOUNT CELL `node` declared, as the type its own two words select.
1306  ///
1307  /// `Worn<<#node as Declared>::Pair, <#node as Declared>::Mode>` — the PAIR word and the MODE
1308  /// word, both of which live on the node's OWN declaration and are invisible to this expansion,
1309  /// read back through the seats they set. It is what lets one emitted line per field mount either
1310  /// kind: a `stream` declaration seats `Streaming` and a bare one seats `Buffered`, and each cell
1311  /// knows its own two doors.
1312  ///
1313  /// Two ordinary projections, which is what the pair seat's becoming a TYPE bought. It was a const,
1314  /// bridged through a `Pair<STREAMS>` carrier and writable only where `#node` is concrete, because
1315  /// a const argument may not depend on a generic parameter on stable — see `Word` for the mode
1316  /// axis, which really does carry a const and keeps its bridge.
1317  fn cell(&self, node: &syn::Type) -> TokenStream {
1318    let krate = self.krate;
1319    let declared = framework(krate, &["drive"], "Declared");
1320    let worn = framework(krate, &["drive"], "Worn");
1321    quote!(#worn<<#node as #declared>::Pair, <#node as #declared>::Mode>)
1322  }
1323
1324  /// [`cell`](Self::cell) as a QUALIFIED PATH — `<Worn<…> as Mount<#node>>`, what every per-node
1325  /// line the launch emits is addressed to.
1326  fn mounted(&self, node: &syn::Type) -> TokenStream {
1327    let krate = self.krate;
1328    let mount = framework(krate, &["drive"], "Mount");
1329    let cell = self.cell(node);
1330    quote!(<#cell as #mount<#node>>)
1331  }
1332
1333  /// What each declared node owes, discharged AT THE CALL SITE.
1334  ///
1335  /// The same posture the hand-wired door's `AsyncConstructor::Error` predicate already keeps, widened to
1336  /// everything this walk spends: a root nobody launches carries no obligation, and a node that
1337  /// cannot be launched is refused where the launch is written rather than where the root is
1338  /// declared.
1339  ///
1340  /// The equation is the one to read twice. `AsyncConstructor<Options = <#node as Declared>::Options>`
1341  /// pins the type the AUTHOR's constructor takes to the path the DECLARATION named — the `options`
1342  /// word and the impl beside it, made to agree by the compiler. A declaration that lets them drift
1343  /// is `E0271`, at the launch, naming both types.
1344  ///
1345  /// # THE MOUNT IS ONE LINE, and the five it replaced are implied by it
1346  ///
1347  /// `Worn<…>: Mount<#node>` is the whole of what the mount costs. The face the declaration's words
1348  /// select, and the `Send` / `Clone` / `Error` obligations on the three messages it carries, are
1349  /// bounds on `Mount`'s own associated types — so they hold wherever the row does, and a predicate
1350  /// spelling them again here would be one fact written at two altitudes. What stays is the half
1351  /// `Mount` says nothing about: the node's CONSTRUCTION.
1352  fn predicates(&self) -> TokenStream {
1353    let krate = self.krate;
1354    let constructor = framework(krate, &["drive"], "AsyncConstructor");
1355    let declared = framework(krate, &["drive"], "Declared");
1356    let mount = framework(krate, &["drive"], "Mount");
1357    let resource = framework(krate, &["resource"], "AsyncResource");
1358
1359    let nodes = self.nodes.iter().map(|node| {
1360      let cell = self.cell(node);
1361      quote! {
1362        #node: #declared
1363          + #constructor<Options = <#node as #declared>::Options>
1364          + ::core::marker::Send
1365          + 'static,
1366        #cell: #mount<#node>,
1367        <#node as #constructor>::Error:
1368          ::core::error::Error + ::core::marker::Send + ::core::marker::Sync + 'static,
1369      }
1370    });
1371    let resources = self.resources.iter().map(|field| {
1372      let ty = &field.ty;
1373      quote! {
1374        <#ty as #resource>::Error:
1375          ::core::error::Error + ::core::marker::Send + ::core::marker::Sync + 'static,
1376      }
1377    });
1378    let origins = self
1379      .origins
1380      .iter()
1381      .map(|origin| self.origin_predicate(origin));
1382    quote!(#(#nodes)* #(#resources)* #(#origins)*)
1383  }
1384
1385  /// What ONE ORIGIN owes, discharged at the call site exactly as a node's obligations are.
1386  ///
1387  /// # It is the node predicate with the CELL taken out, and that is the whole difference
1388  ///
1389  /// A node's row is `Declared + AsyncConstructor<Options = <N as Declared>::Options>` plus
1390  /// `Worn<Pair, Mode>: Mount<N>`, and the mount row is what implies the face and the three
1391  /// messages' own obligations. An origin has no such row to lean on — there is no pair axis for a
1392  /// cell to be indexed by — so the two facts a cell would have carried are spelled here instead:
1393  /// [`DeclaredOrigin`], which is the record `#[ingraph::source]` emits, and `Lived<Mode>`, which is
1394  /// the FACE the declaration's own `async` word selected. Nothing an author can write fills a
1395  /// `Lived` row — `Source` and `AsyncSource` do — so a declaration whose word disagrees with its
1396  /// body is `E0277` here, naming the trait it does not implement.
1397  ///
1398  /// The three messages are then named through the projections the origin layer already publishes:
1399  /// what it PRODUCES crosses onto its engine and down its edge, what it is TOLD crosses down its
1400  /// command line, and what its DEATH is reported as reaches the taps as an erased error.
1401  ///
1402  /// There is NO options equation. A node's `Options = <N as Declared>::Options` pins the
1403  /// constructor's type to the path its declaration named, because two declarations state it and
1404  /// they can drift; an origin states it in ONE place — its own face's `Source::Options` — and the
1405  /// section this spine emits for it is written off that same projection, so the two agree by
1406  /// construction rather than by a predicate.
1407  ///
1408  /// # THE CONSTRUCTION SEAM IS THE FACE'S OWN, and the row that drives is the row that opens
1409  ///
1410  /// `Lived<Mode>` carries BOTH verbs: `Lived::open` is `Source::build` under the mode the
1411  /// declaration named, and `Lived::live` is `Source::run` under it. So the row already spelled for
1412  /// the drive is the whole of what a construction needs as well, and this predicate names no second
1413  /// construction trait — `Creation::origin` is bounded on exactly the row above.
1414  ///
1415  /// That closes a debt this comment used to record. `build` signed a `Context` — a RUNNING body's
1416  /// window, whose wind-down line the mount has not minted at the create stage — so nothing in the
1417  /// framework could call it, and this road detoured origin construction through `AsyncConstructor`,
1418  /// the door `Creation::node` takes. The visible cost was TWO options seats per origin, one of which
1419  /// nothing read. `build`'s window is `&Resources` on both faces now, the detour is retired, and
1420  /// `AsyncConstructor` is left where it belongs — the RESIDENT construction door.
1421  ///
1422  /// `Died<#ty>` is therefore the ONE error predicate, and it is one because the face says so: an
1423  /// origin refuses a construction and a death in a single currency, so the erasure a start-up
1424  /// refusal needs and the erasure a tap needs are one obligation written once.
1425  ///
1426  /// [`DeclaredOrigin`]: ../../ingraph/trait.DeclaredOrigin.html
1427  fn origin_predicate(&self, origin: &OriginMount) -> TokenStream {
1428    let krate = self.krate;
1429    let ty = &origin.ty;
1430    let declared_origin = framework(krate, &["source"], "DeclaredOrigin");
1431    let lived = framework(krate, &["drive"], "Lived");
1432    let produced = framework(krate, &["drive"], "Produced");
1433    let ordered = framework(krate, &["drive"], "Ordered");
1434    let died = framework(krate, &["drive"], "Died");
1435    quote! {
1436      #ty: #declared_origin
1437        + #lived<<#ty as #declared_origin>::Mode>
1438        + ::core::marker::Send
1439        + 'static,
1440      #produced<#ty>: ::core::marker::Send,
1441      #ordered<#ty>: ::core::marker::Send,
1442      #died<#ty>: ::core::error::Error + ::core::marker::Send + ::core::marker::Sync + 'static,
1443    }
1444  }
1445}