Skip to main content

ingraph_codegen/
options.rs

1//! The OPTIONS SPINE: what a graph root's own name becomes when a deployment configures it.
2//!
3//! ```ignore
4//! #[ingraph::graph]
5//! pub struct Media {
6//!   videos: Video,
7//!   scenes: Scene,
8//! }
9//! ```
10//!
11//! emits, beside the walk, a typed `MediaOptions` — one field per DECLARED node, named by the mount
12//! the declaration wrote, holding that node's own [`AsyncConstructor::Options`] under a section:
13//!
14//! ```ignore
15//! pub struct MediaOptions {
16//!   pub(crate) videos: Option<NodeSection<<Video as AsyncConstructor>::Options>>,
17//!   pub(crate) scenes: Option<NodeSection<<Scene as AsyncConstructor>::Options>>,
18//! }
19//! ```
20//!
21//! # PRESENCE IS ENABLEMENT, and that is what the `Option` is
22//!
23//! An application DECLARES a catalog and a deployment LAUNCHES a subset, so a node with no section
24//! is a node that does not start. The sleeping catalog costs no boilerplate and a node added in code
25//! runs nowhere until somebody names it — which is the design rather than a hazard. Every field is
26//! `serde(default)`, so a document naming three of thirty nodes parses and the other twenty-seven
27//! are absent rather than malformed.
28//!
29//! It is the ONLY enablement axis. A section carries no switch to hold a written node back, because
30//! a configuration file is an immutable artifact: a deployment that wants a node off points at a
31//! different file rather than toggling this one.
32//!
33//! # The RESOURCES ride under ONE key
34//!
35//! A root's `#[ingraph(resource)]` fields are on the same list as its nodes, and the document groups
36//! them: the spine grows one `resources` field holding a `<Root>Resources` block, so a deployment
37//! writes `[resources.egemma]` rather than a section at the top level. That is what makes
38//! `resources` a reserved mount — a node named `resources` would be a second meaning for the same
39//! key, and the derive refuses one. [`crate::catalog`] emits the block; this emits the field that
40//! holds it, and only where the root declares a resource that has a section at all.
41//!
42//! # The REGISTRY seat is the SECOND reserved key, and it is on EVERY root
43//!
44//! Beside `resources` the spine grows one `registry` field, holding [`RegistryOptions`] — the
45//! deployment-wide timing the root-key registry runs under: `[registry]`'s own defaults, and
46//! whatever families it named their own words for under `[registry.<family>]`. Unlike `resources`
47//! it is on every root whether or not one is declared for, because there is no per-root marker that
48//! would make it conditional — every graph gets the registry's defaults, whether or not anything
49//! reads them yet. `registry` is therefore RESERVED the same way `resources` is: a member mounted
50//! there would be a second meaning for the key, and the derive refuses one by name.
51//!
52//! # The RETIRED seat is the THIRD reserved key, and it is CONDITIONAL
53//!
54//! A root that wrote `retired(<engine>)` grows one `retired` field, holding [`RetiredOptions`] — the
55//! connection its retirement ledger is opened on. Unlike `registry` it is conditional, and the
56//! difference is what a ledger IS: the registry runs on every root whether or not a document tunes
57//! it, while a root that declared no ledger has no engine, no connection and no table, so a
58//! `[retired]` section on it would be a document key naming nothing. The NAME is reserved
59//! unconditionally all the same, on `resources`' own posture — a member called `retired` would have
60//! to be renamed the day its root declares a ledger.
61//!
62//! Beside the field the spine grows one associated `const`, `RETIRED_ENGINE`, which is the word's
63//! own answer carried across to whatever builds the store. It is a `const` rather than a field
64//! because an engine is not a thing a document may say: it decides what the program COMPILES, and a
65//! document is read after the program is built.
66//!
67//! # The GENERATIONS seat is the FOURTH, on exactly that shape
68//!
69//! A root that wrote `generations(<engine>)` grows one `generations` field holding
70//! [`GenerationsOptions`] — the connection its current pointers are opened on, and how many
71//! generations a closure keeps — plus one `GENERATIONS_ENGINE` const beside it. Everything the
72//! `retired` seat's two paragraphs argue holds here word for word: conditional FIELD, unconditional
73//! NAME, and the engine as a `const` because a document is read after the program is built.
74//!
75//! [`GenerationsOptions`]: ../../ingraph/struct.GenerationsOptions.html
76//!
77//! # The BRIDGE to the launch floor
78//!
79//! Beside the accessors, the spine emits one `enablement()` — the deployment's sections read into
80//! the launch layer's own `Enablement`, one call per DECLARED mount. That is the whole of how a
81//! document reaches the validate walk: the walk asks about node NAMES, the spine's fields ARE those
82//! names, and a field left `None` is the node this deployment does not launch.
83//!
84//! # ONE schema, and no second document to keep in step
85//!
86//! The field NAMES are the mount names, so a section's key is the same word the declaration wrote —
87//! there is no map from string to node to maintain, and a rename moves both ends at once.
88//! `deny_unknown_fields` is what turns a typo into a refusal naming the field, at deserialization,
89//! where the reader is looking at the file. What a section CONTAINS is the node author's own options
90//! type reached through the trait, so the deployment's schema is the sum of the authors' schemas and
91//! this emitter invents no part of it.
92//!
93//! # The framework does NO file I/O
94//!
95//! What is emitted is a plain `serde::Deserialize` type. Which format a deployment writes, how many
96//! layers it merges, where the file lives and what an environment variable overrides are all the
97//! APPLICATION's business — this crate hands it a type and reads nothing.
98//!
99//! # Two lanes, because a derive is an attribute
100//!
101//! The spine exists in every build: a hand-built options value is how a programmatic deployment
102//! states what it runs, and the launch entry's signature names the type whatever a build compiled.
103//! Only the DERIVE is conditional — an attribute cannot be added by a macro that expands to nothing
104//! — so the declaration is written twice, once inside each half of the `serde` gate, and the gate
105//! slurps tokens rather than parsing them, exactly as the four backend gates do.
106
107use proc_macro2::TokenStream;
108use quote::{format_ident, quote};
109
110use crate::{
111  catalog::{Catalog, ResourceField, default_resources_name},
112  emit::{framework, leading, vendored},
113  graph::{GenerationsSeat, OriginMount, RetiredLedger},
114};
115
116#[cfg(test)]
117mod origin_tests;
118#[cfg(test)]
119mod tests;
120
121/// The mount name the registry seat is emitted under, which no member may take.
122///
123/// [`crate::catalog::RESERVED_MOUNT`]'s sibling and reserved for the same reason one level up: the
124/// spine's `registry` field is graph-level rather than grouped under any node's own section, so a
125/// member of that name would be a second meaning for the key the seat already owns.
126pub const RESERVED_REGISTRY_MOUNT: &str = "registry";
127
128/// The mount name the RETIRED LEDGER's section is emitted under, which no member may take.
129///
130/// [`RESERVED_REGISTRY_MOUNT`]'s sibling, one seat over. Unlike that one the FIELD is conditional —
131/// only a root that wrote `retired(<engine>)` grows it — and the RESERVATION is not: a member named
132/// `retired` on a root that has no ledger today would have to be renamed the day it declares one, so
133/// the word is held for the seat whether or not the seat is occupied. That is the same posture
134/// `resources` takes, whose field is conditional on a root declaring one and whose name is refused
135/// unconditionally.
136pub const RESERVED_RETIRED_MOUNT: &str = "retired";
137
138/// The mount name the GENERATIONS SEAT's section is emitted under, which no member may take.
139///
140/// [`RESERVED_RETIRED_MOUNT`]'s sibling, and held on exactly its terms: the FIELD is conditional on
141/// a root writing `generations(<engine>)` and the RESERVATION is not, because a member named
142/// `generations` on a root that has no seat today would have to be renamed the day it declares one.
143pub const RESERVED_GENERATIONS_MOUNT: &str = "generations";
144
145/// `<Root>Options` — the name a root's own spine takes.
146///
147/// Derived from the USER's root type, so a deployment writes `MediaOptions` for a `Media`: the
148/// framework's own vocabulary moved off `universe`, and the emitted global still reads off whatever
149/// the declaration called itself.
150#[must_use]
151pub fn default_options_name(root: &syn::Ident) -> syn::Ident {
152  format_ident!("{root}Options")
153}
154
155/// One ingraph root's options spine, ready to emit.
156///
157/// It borrows rather than owning, because what it needs is what the root model already holds — the
158/// list and the mount names, in one order — and a second copy of that list is a second thing to keep
159/// in step.
160#[derive(Debug, Clone, Copy)]
161pub struct OptionsSpine<'a> {
162  /// Where `ingraph` lives, as the declaration named it.
163  pub krate: &'a syn::Path,
164  /// The root's own visibility — what the spine and its accessors take.
165  pub vis: &'a syn::Visibility,
166  /// The root type, whose name the spine derives its own from.
167  pub root: &'a syn::Ident,
168  /// The NODES, in declaration order.
169  pub nodes: &'a [syn::Type],
170  /// The mount NAMES beside them, in that same order — the spine's fields, and a document's keys.
171  pub mounts: &'a [syn::Ident],
172  /// The RESOURCES, in declaration order — what the spine's one `resources` field groups.
173  pub resources: &'a [ResourceField],
174  /// The ORIGINS, in declaration order — one section apiece, beside the nodes and under no block.
175  ///
176  /// AT THE TOP LEVEL rather than grouped, which is the difference between this tier and the
177  /// resources: a resource is DEMAND-SCANNED (nothing is enabled by naming one), and an origin is
178  /// ENABLED BY PRESENCE exactly as a node is. So an origin's section says the same thing a node's
179  /// says in the same place, and a document writes `[watch]` beside `[discover]` rather than
180  /// `[origins.watch]` — the reader is told which members run by one flat list.
181  pub origins: &'a [OriginMount],
182  /// The RETIRED LEDGER this root declared, or [`None`] where it declared none — what makes the
183  /// `retired` field and its accessors conditional.
184  pub retired: Option<&'a RetiredLedger>,
185  /// The GENERATIONS SEAT this root declared, or [`None`] where it declared none — what makes the
186  /// `generations` field and its accessors conditional, on [`retired`](Self::retired)'s own terms.
187  pub generations: Option<&'a GenerationsSeat>,
188}
189
190impl OptionsSpine<'_> {
191  /// The spine, once inside each half of the `serde` gate — see the module note for why twice.
192  #[must_use]
193  pub fn emit(&self) -> TokenStream {
194    let krate = self.krate;
195    let deserialized = self.declaration(true);
196    let plain = self.declaration(false);
197    let methods = self.methods();
198    let debug = self.debug();
199    let if_serde = quote!(#krate::__private::gate::if_serde);
200    let if_no_serde = quote!(#krate::__private::gate::if_no_serde);
201    quote! {
202      #if_serde ! { #deserialized }
203      #if_no_serde ! { #plain }
204      #methods
205      #debug
206    }
207  }
208
209  /// The struct itself, with serde's derive and words where this build has serde.
210  fn declaration(&self, deserialized: bool) -> TokenStream {
211    let vis = self.vis;
212    let root = self.root;
213    let name = default_options_name(root);
214    let section = framework(self.krate, &["drive"], "NodeSection");
215    let constructor = framework(self.krate, &["drive"], "AsyncConstructor");
216    let declared = framework(self.krate, &["drive"], "Declared");
217    // The ORIGIN tier's projection: an origin's options are its own face's, reached through the mode
218    // row. A node's come through `AsyncConstructor`, which is the resident construction door and not
219    // an origin's — see `launch::LaunchEntry::origin_predicate` for the round that separated them.
220    let tuned = framework(self.krate, &["drive"], "Tuned");
221
222    let fields = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
223      let doc = leading(&format!(
224        "What this deployment runs `{mount}` with — `None` being the node it does not \
225         start.\n\nThe field NAME is the mount name, so a document's key is the word the \
226         declaration wrote."
227      ));
228      let default = deserialized.then(|| quote!(#[serde(default)]));
229      quote! {
230        #[doc = #doc]
231        #default
232        pub(crate) #mount: ::core::option::Option<
233          #section<<#node as #constructor>::Options, <#node as #declared>::Channels>
234        >,
235      }
236    });
237    let origins = self.origins.iter().map(|origin| {
238      let (mount, ty) = (&origin.mount, &origin.ty);
239      let doc = leading(&format!(
240        "What this deployment runs the ORIGIN `{mount}` with — `None` being the origin it does not \
241         start.\n\nA node's section verbatim, one tier over, and there is no `channels` block \
242         under it: an origin declares no upstream, so it has no inbound edge for a shelf to tune. \
243         Its ONE out-edge is the CONSUMER's, and it is tuned in the consumer's own section."
244      ));
245      let default = deserialized.then(|| quote!(#[serde(default)]));
246      quote! {
247        #[doc = #doc]
248        #default
249        pub(crate) #mount: ::core::option::Option<#section<#tuned<#ty>>>,
250      }
251    });
252    let resources = self.resources_field(deserialized);
253    let registry = self.registry_field(deserialized);
254    let retired = self.retired_field(deserialized);
255    let generations = self.generations_field(deserialized);
256
257    let derives = if deserialized {
258      let deserialize = framework(self.krate, &["serde"], "Deserialize");
259      let serde = vendored(self.krate, "serde");
260      quote! {
261        #[derive(::core::default::Default, #deserialize)]
262        #[serde(crate = #serde, deny_unknown_fields)]
263      }
264    } else {
265      quote!(#[derive(::core::default::Default)])
266    };
267
268    let doc = leading(&format!(
269      "What ONE DEPLOYMENT of [`{root}`] runs — one section per declared node, absent for the ones \
270       it does not start.\n\nPresence is enablement: a node with no section here is a node that \
271       never launches, so an application may declare a catalog and a deployment may take a subset \
272       of it without either writing anything about the other, and a section that IS written is a \
273       node that runs — presence being the only axis there is.\n\nIt \
274       reads no file. Which format states this, how many layers merge into it and where they live \
275       are the application's questions; the framework's answer is a type."
276    ));
277    quote! {
278      #[doc = #doc]
279      #derives
280      #vis struct #name {
281        #(#fields)*
282        #(#origins)*
283        #resources
284        #registry
285        #retired
286        #generations
287      }
288    }
289  }
290
291  /// The `resources` field, where the root declares a document-sourced resource at all.
292  ///
293  /// It is a BLOCK rather than one field per resource, which is the ruled grouping: struct-flat,
294  /// document-nested, so a deployment writes `[resources.egemma]` and every shared citizen's section
295  /// is under one roof. That grouping is also what reserves the word — a member mounted at
296  /// `resources` would be a second meaning for the key, and the derive refuses one by name.
297  ///
298  /// Held BY VALUE and not optionally: the block's own fields are what say which resources this
299  /// deployment configured, and a document that writes no `resources` at all is every one of them
300  /// absent — which is the same statement one nesting level down. Nothing is enabled or disabled by
301  /// it, resources being demand-scanned rather than named.
302  fn resources_field(&self, deserialized: bool) -> TokenStream {
303    if !self.catalog().has_block() {
304      return TokenStream::new();
305    }
306    let block = default_resources_name(self.root);
307    let doc = leading(
308      "What this deployment builds its shared RESOURCES with — one section per document-sourced \
309       resource, under the reserved `resources` key.\n\nEvery section in it is optional and an \
310       absent one is that resource at its options' own `Default`, so a deployment that tunes none \
311       of them writes no `resources` block at all.",
312    );
313    let default = deserialized.then(|| quote!(#[serde(default)]));
314    quote! {
315      #[doc = #doc]
316      #default
317      pub(crate) resources: #block,
318    }
319  }
320
321  /// The `registry` field — ON EVERY ROOT, unlike [`resources_field`](Self::resources_field): there
322  /// is no per-root marker that would make the seat conditional, so every spine carries the registry's
323  /// own defaults whether or not this deployment tunes them.
324  fn registry_field(&self, deserialized: bool) -> TokenStream {
325    let registry = framework(self.krate, &["drive"], "RegistryOptions");
326    let doc = leading(
327      "What this deployment tunes the root-key REGISTRY with — `[registry]`'s own defaults, and \
328       whatever families it named their own words for under `[registry.<family>]`.\n\nEvery knob \
329       has a shipped default, so a document naming none of them still parses.",
330    );
331    let default = deserialized.then(|| quote!(#[serde(default)]));
332    quote! {
333      #[doc = #doc]
334      #default
335      pub(crate) registry: #registry,
336    }
337  }
338
339  /// The `retired` field — ONLY where the root wrote `retired(<engine>)`, which is the difference
340  /// between this seat and [`registry_field`](Self::registry_field).
341  ///
342  /// The registry runs on every root whether or not a document tunes it, so its options are there to
343  /// be defaulted. A LEDGER is not like that: a root that declared none has no engine, no connection
344  /// and no table, so a `[retired]` section on it would be a document key naming nothing — which
345  /// `deny_unknown_fields` then refuses, telling the reader the truth.
346  ///
347  /// Held BY VALUE, on [`resources_field`](Self::resources_field)'s own reasoning: an absent
348  /// section is every knob at its default, which is the same statement one nesting level down.
349  fn retired_field(&self, deserialized: bool) -> TokenStream {
350    if self.retired.is_none() {
351      return TokenStream::new();
352    }
353    let options = framework(self.krate, &["drive"], "RetiredOptions");
354    let doc = leading(
355      "Where this deployment keeps its RETIRED LEDGER — the `[retired]` section.\n\nThe ENGINE is \
356       the declaration's (`retired(<engine>)`); this is where on that engine. A document that names \
357       no connection is a deployment wiring its own store in code.",
358    );
359    let default = deserialized.then(|| quote!(#[serde(default)]));
360    quote! {
361      #[doc = #doc]
362      #default
363      pub(crate) retired: #options,
364    }
365  }
366
367  /// The `retired` accessors and the ENGINE the word named, as a `const`.
368  ///
369  /// The const is what carries the declaration's own decision across to a launch: a deployment
370  /// reads `<Root>Options::RETIRED_ENGINE` and builds the store the word asked for. It is an
371  /// associated `const` rather than a field because it is not a thing a document may say — an engine
372  /// decides what the program COMPILES, and a document is read after the program is built.
373  fn retired_methods(&self) -> TokenStream {
374    let Some(ledger) = self.retired else {
375      return TokenStream::new();
376    };
377    let vis = self.vis;
378    let options = framework(self.krate, &["drive"], "RetiredOptions");
379    let engine = self.retired_engine(ledger);
380    let engine_doc = leading(
381      "WHICH ENGINE this root's retired ledger runs on — the `retired(<engine>)` word, as a \
382       value.\n\nA deployment reads it to build the store: the word is the application's decision \
383       and `[retired].dsn` is the deployment's.",
384    );
385    let with_doc = leading(
386      "Keep the retired ledger at `retired` — the door a deployment states in code rather than in a \
387       document.",
388    );
389    let borrow_doc = leading("Where this deployment keeps its retired ledger.");
390    quote! {
391      #[doc = #engine_doc]
392      #vis const RETIRED_ENGINE: #engine;
393
394      #[doc = #with_doc]
395      #[inline]
396      #[must_use]
397      #vis fn with_retired(mut self, retired: #options) -> Self {
398        self.retired = retired;
399        self
400      }
401
402      #[doc = #borrow_doc]
403      #[inline]
404      #[must_use]
405      #vis const fn retired(&self) -> &#options {
406        &self.retired
407      }
408    }
409  }
410
411  /// The `const`'s TYPE AND ITS VALUE — `RetiredEngine = RetiredEngine::<Arm>`, for the arm
412  /// `ledger`'s word named.
413  ///
414  /// It is the one place the codegen's own database vocabulary crosses into the runtime's engine
415  /// word, so the crossing is [`DatabaseKind::retired_arm`](crate::model::DatabaseKind::retired_arm)
416  /// and never a spelling written twice.
417  ///
418  /// The ledger arrives as an ARGUMENT rather than off `self`, so there is no arm to default to
419  /// where a root declared none: the one caller has already established that it did.
420  fn retired_engine(&self, ledger: &RetiredLedger) -> TokenStream {
421    let ty = framework(self.krate, &["drive"], "RetiredEngine");
422    let arm = format_ident!("{arm}", arm = ledger.engine.retired_arm());
423    quote!(#ty = #ty::#arm)
424  }
425
426  /// The `generations` field — ONLY where the root wrote `generations(<engine>)`, on
427  /// [`retired_field`](Self::retired_field)'s own terms and for its reason: a root that declared no
428  /// seat has no engine, no connection and no pointer table, so a `[generations]` section on it
429  /// would be a document key naming nothing, which `deny_unknown_fields` then refuses.
430  fn generations_field(&self, deserialized: bool) -> TokenStream {
431    if self.generations.is_none() {
432      return TokenStream::new();
433    }
434    let options = framework(self.krate, &["drive"], "GenerationsOptions");
435    let doc = leading(
436      "Where this deployment keeps its CURRENT POINTERS, and how deep its history goes — the \
437       `[generations]` section.\n\nThe ENGINE is the declaration's (`generations(<engine>)`); this \
438       is where on that engine, and how many generations a closure keeps (`keep`, one by default).",
439    );
440    let default = deserialized.then(|| quote!(#[serde(default)]));
441    quote! {
442      #[doc = #doc]
443      #default
444      pub(crate) generations: #options,
445    }
446  }
447
448  /// The `generations` accessors and the ENGINE the word named, as a `const` —
449  /// [`retired_methods`](Self::retired_methods)'s shape, one seat over.
450  fn generations_methods(&self) -> TokenStream {
451    let Some(seat) = self.generations else {
452      return TokenStream::new();
453    };
454    let vis = self.vis;
455    let options = framework(self.krate, &["drive"], "GenerationsOptions");
456    let engine = self.generations_engine(seat);
457    let engine_doc = leading(
458      "WHICH ENGINE this root's current pointers run on — the `generations(<engine>)` word, as a \
459       value.\n\nA deployment reads it to build the store: the word is the application's decision \
460       and `[generations].dsn` is the deployment's.",
461    );
462    let with_doc = leading(
463      "Keep the generations seat at `generations` — the door a deployment states in code rather \
464       than in a document.",
465    );
466    let borrow_doc =
467      leading("Where this deployment keeps its current pointers, and how deep its history goes.");
468    quote! {
469      #[doc = #engine_doc]
470      #vis const GENERATIONS_ENGINE: #engine;
471
472      #[doc = #with_doc]
473      #[inline]
474      #[must_use]
475      #vis fn with_generations(mut self, generations: #options) -> Self {
476        self.generations = generations;
477        self
478      }
479
480      #[doc = #borrow_doc]
481      #[inline]
482      #[must_use]
483      #vis const fn generations(&self) -> &#options {
484        &self.generations
485      }
486    }
487  }
488
489  /// The `const`'s TYPE AND ITS VALUE — `GenerationsEngine = GenerationsEngine::<Arm>`, for the arm
490  /// `seat`'s word named.
491  ///
492  /// [`retired_engine`](Self::retired_engine)'s twin, crossing through
493  /// [`DatabaseKind::generations_arm`](crate::model::DatabaseKind::generations_arm) so the arm is
494  /// the runtime enum's own spelling and never one written twice.
495  ///
496  /// That crossing is PARTIAL where the other is total, and the empty answer is its totality rather
497  /// than a case: the derive refuses `generations(mongo)` by name, so a spine is only ever built
498  /// over a word the runtime enum has. Spelling the fallback keeps a fourth engine added to one enum
499  /// and not the other a MISSING `const` at the declaration rather than a path that does not exist.
500  fn generations_engine(&self, seat: &GenerationsSeat) -> TokenStream {
501    let ty = framework(self.krate, &["drive"], "GenerationsEngine");
502    let Some(arm) = seat.engine.generations_arm() else {
503      return TokenStream::new();
504    };
505    let arm = format_ident!("{arm}");
506    quote!(#ty = #ty::#arm)
507  }
508
509  /// The catalog half of the same list — see [`crate::catalog`].
510  fn catalog(&self) -> Catalog<'_> {
511    Catalog {
512      krate: self.krate,
513      vis: self.vis,
514      root: self.root,
515      resources: self.resources,
516    }
517  }
518
519  /// The `resources` accessors, where the block exists.
520  ///
521  /// A borrow and a builder, exactly as a node's section has: a deployment assembling its options in
522  /// code says `with_resources(…)`, and a reader asks the value what it holds.
523  fn resource_methods(&self) -> TokenStream {
524    if !self.catalog().has_block() {
525      return TokenStream::new();
526    }
527    let vis = self.vis;
528    let block = default_resources_name(self.root);
529    let with_doc = leading(
530      "Build this deployment's shared resources from `resources` — the door a deployment states in \
531       code rather than in a document.",
532    );
533    let borrow_doc = leading("What this deployment builds its shared resources with.");
534    quote! {
535      #[doc = #with_doc]
536      #[inline]
537      #[must_use]
538      #vis fn with_resources(mut self, resources: #block) -> Self {
539        self.resources = resources;
540        self
541      }
542
543      #[doc = #borrow_doc]
544      #[inline]
545      #[must_use]
546      #vis const fn resources(&self) -> &#block {
547        &self.resources
548      }
549    }
550  }
551
552  /// The accessor family: `Default` plus one `with_<mount>` and one borrow per node.
553  ///
554  /// The shape an emitted arguments type already has one crate over — construction is the default
555  /// plus one builder per member — and it is ungated, the two declarations above being the same
556  /// struct under two attribute sets.
557  fn methods(&self) -> TokenStream {
558    let vis = self.vis;
559    let name = default_options_name(self.root);
560    let section = framework(self.krate, &["drive"], "NodeSection");
561    let constructor = framework(self.krate, &["drive"], "AsyncConstructor");
562    let declared = framework(self.krate, &["drive"], "Declared");
563    let tuned = framework(self.krate, &["drive"], "Tuned");
564
565    let methods = self.mounts.iter().zip(self.nodes).map(|(mount, node)| {
566      let with = format_ident!("with_{mount}");
567      let held = quote!(#section<<#node as #constructor>::Options, <#node as #declared>::Channels>);
568      let with_doc = leading(&format!(
569        "Launch `{mount}`, under `section` — the door a deployment states in code rather than in a \
570         document."
571      ));
572      let borrow_doc = leading(&format!(
573        "What `{mount}` is to be launched with, or `None` where this deployment does not start it."
574      ));
575      quote! {
576        #[doc = #with_doc]
577        #[inline]
578        #[must_use]
579        #vis fn #with(mut self, section: #held) -> Self {
580          self.#mount = ::core::option::Option::Some(section);
581          self
582        }
583
584        #[doc = #borrow_doc]
585        #[inline]
586        #[must_use]
587        #vis fn #mount(&self) -> ::core::option::Option<&#held> {
588          self.#mount.as_ref()
589        }
590      }
591    });
592
593    let origins = self.origins.iter().map(|origin| {
594      let (mount, ty) = (&origin.mount, &origin.ty);
595      let with = format_ident!("with_{mount}");
596      let held = quote!(#section<#tuned<#ty>>);
597      let with_doc = leading(&format!(
598        "Mount the origin `{mount}`, under `section` — the door a deployment states in code rather \
599         than in a document."
600      ));
601      let borrow_doc = leading(&format!(
602        "What the origin `{mount}` is to be mounted with, or `None` where this deployment does not \
603         start it."
604      ));
605      quote! {
606        #[doc = #with_doc]
607        #[inline]
608        #[must_use]
609        #vis fn #with(mut self, section: #held) -> Self {
610          self.#mount = ::core::option::Option::Some(section);
611          self
612        }
613
614        #[doc = #borrow_doc]
615        #[inline]
616        #[must_use]
617        #vis fn #mount(&self) -> ::core::option::Option<&#held> {
618          self.#mount.as_ref()
619        }
620      }
621    });
622
623    let enablement = self.enablement();
624    let resources = self.resource_methods();
625    let registry = self.registry_methods();
626    let retired = self.retired_methods();
627    let generations = self.generations_methods();
628    quote! {
629      impl #name {
630        #(#methods)*
631
632        #(#origins)*
633
634        #resources
635
636        #registry
637
638        #retired
639
640        #generations
641
642        #enablement
643      }
644    }
645  }
646
647  /// The `registry` accessors: a borrow and a builder, exactly as [`resource_methods`](Self::resource_methods)
648  /// has — a deployment assembling its options in code says `with_registry(…)`, and a reader asks
649  /// the value what it holds.
650  fn registry_methods(&self) -> TokenStream {
651    let vis = self.vis;
652    let registry = framework(self.krate, &["drive"], "RegistryOptions");
653    let with_doc = leading(
654      "Tune the root-key registry with `registry` — the door a deployment states in code rather \
655       than in a document.",
656    );
657    let borrow_doc = leading("What this deployment tunes the root-key registry with.");
658    quote! {
659      #[doc = #with_doc]
660      #[inline]
661      #[must_use]
662      #vis fn with_registry(mut self, registry: #registry) -> Self {
663        self.registry = registry;
664        self
665      }
666
667      #[doc = #borrow_doc]
668      #[inline]
669      #[must_use]
670      #vis const fn registry(&self) -> &#registry {
671        &self.registry
672      }
673    }
674  }
675
676  /// The BRIDGE: which nodes these options launch, in the launch floor's own word.
677  ///
678  /// One [`Enablement::mounted`] call per DECLARED mount — not per section the document carried —
679  /// so the walk that reads it is told about every node the root declares, including the ones this
680  /// deployment said nothing about. That is what makes the absence readable: a mount whose field is
681  /// `None` states a node that does not launch, and a mount nobody could name at all does not
682  /// exist, the fields being the vocabulary.
683  ///
684  /// It is a CHAIN and not a fold with an accumulator, which keeps the emitted body free of a
685  /// `mut` binding a zero-node root would leave unused.
686  fn enablement(&self) -> TokenStream {
687    let vis = self.vis;
688    let enablement = framework(self.krate, &["drive"], "Enablement");
689    let root = self.root;
690    // BOTH TIERS, and under one call each: a mount is a mount to the launch floor, which asks about
691    // NAMES and never about which door declared one. An origin's absence therefore starves its
692    // consumer exactly as an unmounted node's does, and its presence is what makes it a head the
693    // validate walk has to check the out-edge of.
694    let sections = self
695      .mounts
696      .iter()
697      .chain(self.origins.iter().map(|origin| &origin.mount))
698      .map(|mount| {
699        let key = mount.to_string();
700        quote!(.mounted(#key, ::core::option::Option::as_ref(&self.#mount)))
701      });
702    let doc = leading(&format!(
703      "Which members this deployment of [`{root}`] launches — its nodes and its origins.\n\nPresence \
704       is enablement, and it is the only axis: a mount this document named launches, and a mount it \
705       did not name is not started at all. This is what the launch walk's checks are asked about — \
706       an upstream nothing named starves a channel listener, and the refusal names the section to \
707       write."
708    ));
709    quote! {
710      #[doc = #doc]
711      #[must_use]
712      #vis fn enablement(&self) -> #enablement {
713        #enablement::new() #(#sections)*
714      }
715    }
716  }
717
718  /// A `Debug` reporting each node's PRESENCE, and never the options themselves.
719  ///
720  /// Written rather than derived, and that is the same trade `Shared` and the launch context make:
721  /// a node's options are the author's type, and deriving here would put a `Debug` bound on every
722  /// one of them for the benefit of this line. What a reader of a start-up log actually wants is
723  /// which nodes this deployment launches, which is exactly what the presence of each section says
724  /// — `false` for a node nothing named, `true` for one that runs.
725  fn debug(&self) -> TokenStream {
726    let name = default_options_name(self.root);
727    let fields = self
728      .mounts
729      .iter()
730      .chain(self.origins.iter().map(|origin| &origin.mount))
731      .map(|mount| {
732        let key = mount.to_string();
733        quote! {
734          .field(#key, &::core::option::Option::is_some(&self.#mount))
735        }
736      });
737    // The block's own `Debug` is the same trade one level down — which resources this deployment
738    // wrote a section for, never what is in one.
739    let resources = self
740      .catalog()
741      .has_block()
742      .then(|| quote!(.field("resources", &self.resources)));
743    // The LEDGER's own `Debug` where there is one, on the registry's reasoning below: it is the
744    // framework's type, so printing it whole costs no bound anybody else pays.
745    let retired = self
746      .retired
747      .is_some()
748      .then(|| quote!(.field("retired", &self.retired)));
749    // The GENERATIONS SEAT's, on the same reasoning and under the same condition.
750    let generations = self
751      .generations
752      .is_some()
753      .then(|| quote!(.field("generations", &self.generations)));
754    // The registry's OWN `Debug`, and not presence-only: unlike a node's options, which are the
755    // author's own type and would bound every one of them for one log line, `RegistryOptions` is the
756    // framework's, so printing it whole costs nothing new.
757    quote! {
758      impl ::core::fmt::Debug for #name {
759        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
760          f.debug_struct(::core::stringify!(#name))
761            #(#fields)*
762            #resources
763            .field("registry", &self.registry)
764            #retired
765            #generations
766            .finish()
767        }
768      }
769    }
770  }
771}