Skip to main content

ingraph_codegen/
source.rs

1//! The SOURCE declaration's emission: the DOUBLE ENTRY, which is the whole of what a source
2//! declaration writes.
3//!
4//! ```ignore
5//! #[ingraph::source(async, mutation(node = "WatchOps"))]
6//! pub struct Watch { … }
7//!
8//! impl AsyncSource for Watch {
9//!   type Mutation = WatchOps;      // the TYPE half — the author's own hand
10//!   …
11//! }
12//! ```
13//!
14//! # Two entries for one fact, and the emission is what holds them together
15//!
16//! A source's command face is written TWICE, and neither spelling can be dropped. The WORD is what
17//! the declaration says — it is what a manifest front end, a schema walk and a reader see — and the
18//! TYPE is what the compiler resolves a [`Control`](../../ingraph/struct.Control.html) line through.
19//! Two macro expansions cannot read each other's tokens and an attribute macro cannot write somebody
20//! else's `impl`, so the word cannot mint the type and the type cannot mint the word.
21//!
22//! What this emission writes is the JOIN: one bound, stated over the declared type, naming the node
23//! the word named. So the two entries are checked against each other at the declaration, in BOTH
24//! directions:
25//!
26//! | written | what happens |
27//! |---|---|
28//! | `mutation(node = "WatchOps")` and `type Mutation = WatchOps` | it compiles |
29//! | `mutation(node = "WatchOps")` and `type Mutation = ()` (or another node) | `E0271` at the WORD |
30//! | no word and `type Mutation = WatchOps` | `E0271` at the DECLARATION |
31//! | no word and `type Mutation = ()` | it compiles |
32//!
33//! The third row is the one a single-entry design would have lost: a source that mounted a node and
34//! forgot to say so would publish no wire face and no reader would ever know, because a missing word
35//! looks exactly like a source nobody controls. The bound is what makes silence impossible.
36//!
37//! # The FACE is the `async` word's, and the word is what names the trait
38//!
39//! `#[ingraph::source]` binds [`Source`](../../ingraph/trait.Source.html) and
40//! `#[ingraph::source(async)]` binds [`AsyncSource`](../../ingraph/trait.AsyncSource.html) — the
41//! dual-mode law's word-selects-face rule, applied at the one position that has to name a trait to
42//! state anything at all. A declaration whose word and whose `impl` disagree is `E0277` at the
43//! declaration, naming the face it does not wear, which is what
44//! [`Source`](../../ingraph/trait.Source.html)'s own `on_unimplemented` note is written for.
45//!
46//! # THE RECORD a launch walk mounts it through
47//!
48//! Beside the entry, one impl:
49//!
50//! ```ignore
51//! impl DeclaredOrigin for Watch {
52//!   type Mode = Block;                                  // the `async` word, as a TYPE
53//!   const MOUNTS: Option<&'static str> = Some("WatchOps");
54//! }
55//! ```
56//!
57//! `Declared`'s own arrangement for the origin layer: a walk that mounts an origin sees a type, so
58//! the declaration STATES what it is and the walk NAMES it through a projection. The `Mode` seat is
59//! what makes one mount door serve both faces, and the string is for a reader rather than for the
60//! compiler — what resolves the mount is the seat the double entry is stated over.
61//!
62//! # NOTHING ELSE is emitted
63//!
64//! No command enum (the node's own declaration mints it), no `MutationNode` row (the node's), no
65//! resolver (the node's binding pass). The host is echoed, one anonymous `const` is written beside
66//! it, and the record above.
67
68use quote::{quote, quote_spanned};
69use syn::spanned::Spanned as _;
70
71#[cfg(test)]
72mod tests;
73
74/// A validated source declaration, ready to emit.
75///
76/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a manifest
77/// front end later reach the same emitter.
78#[derive(Debug, Clone)]
79pub struct SourceModel {
80  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
81  /// another.
82  pub krate: syn::Path,
83  /// The declared type — the origin the double entry is stated over.
84  pub name: syn::Ident,
85  /// Whether the declaration wore the `async` word, which is what names the face the bound binds.
86  pub awaited: bool,
87  /// The `mutation(node = "…")` word, or nothing — which is the source nobody controls.
88  ///
89  /// Carried as the PATH the word held rather than as a literal, because what the emission does with
90  /// it is name a type. Its tokens keep the literal's own span, which is what puts a mismatch's
91  /// `E0271` on the word an author has to change.
92  pub node: Option<syn::Path>,
93}
94
95impl SourceModel {
96  /// The double entry and the DECLARATION RECORD — see the module note.
97  #[must_use]
98  pub fn emit(&self) -> proc_macro2::TokenStream {
99    let entry = self.entry();
100    let declared = self.declared();
101    quote! {
102      #entry
103      #declared
104    }
105  }
106
107  /// THE RECORD a launch walk mounts this origin through.
108  ///
109  /// [`MutationModel`](crate::mutation::MutationModel)'s own arrangement one layer over: a walk that
110  /// mounts an origin sees a TYPE, so the declaration states its face and the node it controls, and
111  /// the walk names them through a projection. The `Mode` seat is what makes ONE mount door serve
112  /// both faces — a caller does not choose which, and cannot.
113  ///
114  /// The mounted node is carried as the PATH the word wrote, and only as that: what the compiler
115  /// resolves is the `Mutation` seat the double entry above is stated over, and this string is for a
116  /// reader, a manifest front end and a refusal's sentence.
117  fn declared(&self) -> proc_macro2::TokenStream {
118    let krate = &self.krate;
119    let name = &self.name;
120    let mode = if self.awaited {
121      quote!(#krate::__private::operator::Async)
122    } else {
123      quote!(#krate::__private::operator::Block)
124    };
125    let mounts = match &self.node {
126      Some(node) => {
127        let word = quote!(#node).to_string().replace(' ', "");
128        quote!(::core::option::Option::Some(#word))
129      }
130      None => quote!(::core::option::Option::None),
131    };
132    quote! {
133      impl #krate::__private::source::DeclaredOrigin for #name {
134        type Mode = #mode;
135        const MOUNTS: ::core::option::Option<&'static str> = #mounts;
136      }
137    }
138  }
139
140  /// The DOUBLE ENTRY — one anonymous `const`, whichever way the declaration was written.
141  fn entry(&self) -> proc_macro2::TokenStream {
142    let krate = &self.krate;
143    let name = &self.name;
144    let face = if self.awaited {
145      quote!(#krate::__private::source::AsyncSource)
146    } else {
147      quote!(#krate::__private::source::Source)
148    };
149
150    // The helper's NAME is half the diagnostic: rustc prints the obligation it came from, so a
151    // sentence spelled as an identifier is what a reader sees under the `E0271` — which is the only
152    // place this join has to say anything, there being no `on_unimplemented` for a projection.
153    let (audit, mounted, at) = match &self.node {
154      Some(node) => (
155        quote::format_ident!("__ingraph_a_source_mounts_the_node_its_mutation_word_named"),
156        quote!(#node),
157        node.span(),
158      ),
159      None => (
160        quote::format_ident!("__ingraph_a_source_with_no_mutation_word_has_no_command_face"),
161        quote!(()),
162        name.span(),
163      ),
164    };
165
166    // The CALL is what carries the span, and not the helper: rustc reports a projection mismatch at
167    // the site that instantiated it, so the word an author has to change is where the error lands.
168    //
169    // The ORIGIN's own name is respanned to that word too, and it has to be: `quote_spanned!` sets
170    // the span of the tokens it MINTS, and an interpolated ident keeps the one it was written with
171    // — so the turbofish would otherwise carry the declaration's span and put the primary caret on
172    // `struct Watch;` while the word an author has to change sat in a note. Respanning is safe
173    // where the span is a real one from the same file, which both of these are: resolution is
174    // unchanged and only the report moves.
175    let spent = syn::Ident::new(&name.to_string(), at);
176    let spend = quote_spanned!(at=> const _: fn() = #audit::<#spent>;);
177    quote! {
178      const _: () = {
179        fn #audit<__IgSource>()
180        where
181          __IgSource: #face<Mutation = #mounted>,
182        {
183        }
184
185        #spend
186      };
187    }
188  }
189}