ingraph_codegen/construct.rs
1//! **THE CONSTRUCTION PROTOCOL** — what it takes to build somebody else's value, described.
2//!
3//! Every other grammar in this tree describes a type's SHAPE: what columns it has, how each is
4//! stored, what a client may ask about one. This one describes a type's CONSTRUCTOR — the sequence
5//! of calls that turns a row's worth of values back into the value they came out of — and it exists
6//! because the rewrite mode made that sequence somebody else's business. A declaration wrapping
7//! `mediaframe::Dimensions` cannot change how `Dimensions` is built; it can only say how it is.
8//!
9//! # We are the DESCRIBING side, and the vocabulary is chosen from that seat
10//!
11//! [`bon`](https://docs.rs/bon) and its neighbours are the GENERATING side: their words dress a
12//! builder that does not exist yet — the setter's prefix, the doc comment on the state type, the
13//! `#[must_use]`. None of those reaches this vocabulary, because there is no artifact here for them
14//! to decorate. What DOES reach it is every word that names a call the emission has to write:
15//!
16//! | word | seat | what it names |
17//! |---|---|---|
18//! | `builder(entry = "…")` | container | the first call — `new` unless something else |
19//! | `builder(finish = "…")` | container | the LAST call; writing one is what makes this a builder |
20//! | `builder(fallible)` | container | the terminal step hands back a `Result` |
21//! | `builder(on(Type, into))` | container | every field of `Type` reaches a seat taking `impl Into` |
22//! | `builder(call(with = "…", value = "…"))` | container | a link no column feeds |
23//! | `builder(arg)` | field | a positional argument to the ENTRY |
24//! | `builder(finish_arg)` | field | a positional argument to the FINISH |
25//! | `builder(with[ = "…"])` | field | a chaining link, `with_<field>` unless renamed |
26//! | `builder(set[ = "…"])` | field | an in-place setter, `set_<field>` unless renamed |
27//! | `builder(into)` | field | this seat takes `impl Into`, so the argument is PINNED |
28//! | `builder(map = "…")` | field | the value crosses through a function instead of `Into` |
29//! | `builder(option)` | field | the seat takes the `Option` whole, crossing INSIDE it |
30//! | `builder(skip)` | field | this column is not fed back at all |
31//!
32//! # The DEFAULT LAW is unchanged, and that is the load-bearing promise
33//!
34//! A declaration writing none of these words builds exactly what it built before the vocabulary
35//! existed: `Remote::new(<every required column, in declaration order>)` followed by one
36//! `.with_<name>(…)` per `#[ingraph(optional)]` column. That is not a coincidence to be maintained
37//! by care — it is [`Construction::default`] and [`Build::default`] resolving to the same two seats
38//! the hand-written emission chose, and `ingraph-codegen`'s own golden asserts the token stream is
39//! the one it always was.
40//!
41//! # A WRONG word is settled by the compiler, at the call this writes
42//!
43//! Nothing here resolves a method: `finish = "buidl"` is a name, and a name that no method answers
44//! to is `E0599` at the raise. That is deliberate and it is the same posture the rewrite mode
45//! already takes — the manifest is a CLAIM ABOUT AN API this crate cannot see, and the compiler is
46//! the only reader that can check one. What this module owns is the claim's SHAPE: that a
47//! `finish_arg` has a `finish` to be an argument of, that one field fills one seat, that a word only
48//! a wrapper can spend is not written on a declaration that is its own storage.
49//!
50//! # Where the pieces live
51//!
52//! The grammar, the parse and the shape refusals are `ingraph_derive`'s `construct` module —
53//! exactly one copy, whichever saddle mounts it. This half is the MODEL those produce and the
54//! WRITER that spends it, and it is here rather than there because emission lives here and the
55//! dependency runs `ingraph-derive` → `ingraph-codegen`. [`crate::remote`] is the first saddle: it
56//! gathers one crossed value per manifest column and hands them to [`Construction::call`].
57
58use quote::{format_ident, quote};
59
60/// The local the STATEMENT form binds the value under, inside the expansion's own namespace.
61///
62/// Held as one constant because two shapes spell it — the `let mut` that opens the block and every
63/// step that assigns through it — and a binding that drifted between them would be `E0425` inside
64/// an expansion nobody can edit.
65const BUILT: &str = "__ingraph_built";
66
67/// What a declaration says about the way its wrapped type is BUILT.
68///
69/// Every field defaults to the shape the emission had before the vocabulary existed, which is what
70/// makes the words free: a declaration that writes no `builder(…)` carries this value, and the
71/// writer turns it into the same tokens the hand-written version emitted.
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct Construction {
74 /// The `builder(…)` word's own path, or [`None`] where the declaration wrote none.
75 ///
76 /// Kept for the SPAN, exactly as [`RecordModel::asynchronous`](crate::model::RecordModel) keeps
77 /// one: the refusal a construction word earns on a declaration that wraps nothing has to blame
78 /// the word, and a defaulted value has no token for a caret to land on. It is also the one
79 /// reliable answer to *was anything written* — every other field has a meaningful default.
80 pub at: Option<syn::Path>,
81 /// The FIRST call — `Remote::<entry>(…)`.
82 ///
83 /// `new` unless `entry = "…"` named another, which is the house rule stated as a default rather
84 /// than assumed: a type that keeps the options family has a `new`, and one that spells its
85 /// constructor `from_ratio` says so in one word instead of taking the whole-body escape.
86 pub entry: syn::Ident,
87 /// The LAST call — `.<finish>(…)` — or [`None`] where the entry hands back the value itself.
88 ///
89 /// **Its presence is what makes this a BUILDER protocol rather than a constructor.** Without it
90 /// the entry's return value IS the remote and every link is a consuming `with_…` on the remote
91 /// itself; with it the entry opens a builder, the links refine the builder, and this call closes
92 /// it. One word decides between the two, because one word is the whole difference.
93 pub finish: Option<syn::Ident>,
94 /// `fallible` — the TERMINAL step hands back a `Result`, and the raise carries its `Err`.
95 ///
96 /// # The terminal step, which is the finish where there is one and the entry otherwise
97 ///
98 /// The word is read at the step that YIELDS THE VALUE, and the reading is forced by what is
99 /// useful rather than chosen for symmetry: the shape that exists in the wild is an infallible
100 /// opening (`Remote::builder()`) closed by a validating `build()`, and a word that demanded both
101 /// halves be fallible could not describe it at all. A protocol whose ENTRY is the fallible half
102 /// writes no `finish`, and the same word reaches it.
103 ///
104 /// What the `Err` joins is the road the raise already has: `<db>(try_into(error = "…"))`
105 /// types the row's `TryFrom` where a declaration named a type, and the boxed
106 /// `dyn Error + Send + Sync` is what it is otherwise — so the `?` written here converts through
107 /// the same `From` every fallible column conversion already converts through.
108 pub fallible: bool,
109 /// `on(Type, into)` — the BLANKET, one entry per rule, in the order they were written.
110 ///
111 /// A rule keyed by the field's declared TYPE rather than by its name, which is bon's own shape
112 /// and deliberately so: a remote whose builder was generated with `#[builder(on(String, into))]`
113 /// has one fact to restate, and restating it per field is how a manifest and its upstream drift.
114 pub blanket: Vec<Blanket>,
115 /// `call(with = "…", value = "…")` — the links NO column feeds, in the order they were written.
116 ///
117 /// The seat for a constructor argument that is not a column of this record: a unit the upstream
118 /// demands and the row does not store, a mode word, a capacity hint. Repeatable, because a
119 /// protocol may want several and each is one independent fact.
120 pub calls: Vec<Injection>,
121}
122
123impl Default for Construction {
124 fn default() -> Self {
125 Self {
126 at: None,
127 entry: format_ident!("new"),
128 finish: None,
129 fallible: false,
130 blanket: Vec::new(),
131 calls: Vec::new(),
132 }
133 }
134}
135
136/// One `on(Type, into)` rule — a crossing stated once for every field of a type.
137#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct Blanket {
139 /// The type the rule is keyed by, as the declaration spelled it.
140 pub ty: syn::Type,
141}
142
143/// One `call(with = "…", value = "…")` — a link whose value comes from the declaration itself.
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub struct Injection {
146 /// The method's OWN name, spelled in full.
147 ///
148 /// Not a field name with `with_` pasted on: there is no field here to derive one from, and the
149 /// same is true of the field seat's `with = "…"` — in both positions the value names the method.
150 pub method: syn::Ident,
151 /// The expression the link is handed, re-parsed from the string that carried it.
152 ///
153 /// An EXPRESSION rather than a literal, so the seat reaches a constant, a path, a call — whatever
154 /// the upstream's argument really is. It is emitted verbatim; what it means is the compiler's.
155 pub value: syn::Expr,
156}
157
158/// What ONE field says about its own place in the protocol.
159///
160/// Every part of it is an override: a field writing nothing at all takes the seat the default law
161/// gives it, crosses by the bridge, and is fed back like every other column.
162#[derive(Clone, Debug, Default, PartialEq, Eq)]
163pub struct Build {
164 /// The `builder(…)` block's own path on this field, kept for the span its refusals report at.
165 pub at: Option<syn::Path>,
166 /// Which seat this field fills, or [`None`] for the one the default law gives it.
167 pub seat: Option<Seat>,
168 /// How the value crosses, or [`None`] for the bridge with its target inferred.
169 pub cross: Option<Cross>,
170 /// `option` — the seat takes the `Option` WHOLE, and the crossing happens inside it.
171 ///
172 /// The gap it closes is `Into`'s own: `Option<A>` does not convert into `Option<B>` however
173 /// well `A` converts into `B`, std lifting no conversion through the type. So a manifest column
174 /// restated as `Option<u16>` whose remote seat is `Option<Depth>` cannot cross at all by default
175 /// — and this word says *cross the item and hand the seat the option*, which is the conversion an
176 /// author would have written by hand.
177 pub option: bool,
178 /// `skip` — this column is NOT fed back into the construction.
179 ///
180 /// # The round trip becomes the AUTHOR's assertion, and that is the whole cost of the word
181 ///
182 /// Every other column is read out through an accessor and handed back to the constructor, so the
183 /// value that comes out of a row is the value that went in. A skipped one is read out and never
184 /// handed back: what fills it on the way in is whatever the remote's own constructor puts there.
185 /// Where those agree the round trip holds and the word costs nothing; where they do not, the word
186 /// is a declaration that the difference does not matter — which is a claim about the domain that
187 /// no compiler can check and every reader of the declaration is entitled to see justified.
188 pub skip: bool,
189}
190
191/// WHICH call a field's value reaches, and under what name.
192#[derive(Clone, Debug, PartialEq, Eq)]
193pub enum Seat {
194 /// `arg` — a positional argument to the entry.
195 Arg,
196 /// `finish_arg` — a positional argument to the finish.
197 FinishArg,
198 /// `with` / `with = "…"` — a CONSUMING link, `with_<field>` unless the word renamed it.
199 With(Option<syn::Ident>),
200 /// `set` / `set = "…"` — an IN-PLACE setter, `set_<field>` unless the word renamed it.
201 ///
202 /// bon has no equivalent and this vocabulary does, because the types being described are real:
203 /// an upstream that grew `&mut` setters before it grew a builder is the ordinary case, and a
204 /// grammar that could not name one would send it to the whole-body escape over punctuation.
205 Set(Option<syn::Ident>),
206}
207
208/// HOW a field's value reaches its seat.
209#[derive(Clone, Debug, PartialEq, Eq)]
210pub enum Cross {
211 /// `into` — the seat takes `impl Into<…>`, so the argument's type is PINNED to the field's own.
212 ///
213 /// Inference is what needs the word. The bridge takes its target from the position it lands in,
214 /// and a position spelled `impl Into<X>` is an anonymous type parameter rather than a type — so
215 /// `bridge(value)` there asks the compiler to pick some `T: Into<X>` out of the whole program and
216 /// it correctly refuses (`E0283`). Pinning the target to the type the manifest restated resolves
217 /// it, and the remaining `T: Into<X>` obligation is the upstream's own signature doing its job.
218 Into,
219 /// `map = "…"` — the value crosses through the named function instead of through the bridge.
220 ///
221 /// The last 1% the bridge cannot reach: two types with no conversion between them, a lossy
222 /// narrowing an author is willing to declare, a unit change. It OVERRIDES a blanket that would
223 /// otherwise have claimed the field, which is the precedence a per-field word always has over a
224 /// per-type one.
225 Map(syn::Path),
226}
227
228/// ONE value the protocol carries, already crossed, with the seat it fills and its gate.
229///
230/// A saddle's whole contribution: [`crate::remote`] reads a manifest column, crosses it, resolves
231/// the seat, and hands over one of these. The writer below knows nothing about manifests, columns
232/// or rows — which is what lets a second saddle hand it a fragment's fields without a second copy
233/// of the shapes.
234pub struct Supplied {
235 /// Which call this value reaches, resolved to a name.
236 pub fill: Filled,
237 /// The `#[cfg(…)]` this value rides, or empty where it rides none.
238 pub gate: proc_macro2::TokenStream,
239 /// The expression, crossed and ready to be an argument.
240 pub value: proc_macro2::TokenStream,
241}
242
243/// A [`Seat`] with every name resolved — what the writer actually spells.
244pub enum Filled {
245 /// A positional argument to the entry.
246 Entry,
247 /// A positional argument to the finish.
248 Finish,
249 /// A consuming link, under this name.
250 Link(syn::Ident),
251 /// An in-place setter, under this name.
252 Setter(syn::Ident),
253}
254
255impl Seat {
256 /// This seat with its name resolved against the column that fills it.
257 ///
258 /// The two default names are the options family's own — `with_<column>` and `set_<column>` —
259 /// read off [`Member`](crate::method::Member) rather than pasted here, so the names this writer
260 /// spells are the names the framework's own family would have minted.
261 #[must_use]
262 pub fn filled(&self, column: &syn::Ident) -> Filled {
263 match self {
264 Self::Arg => Filled::Entry,
265 Self::FinishArg => Filled::Finish,
266 Self::With(renamed) => Filled::Link(
267 renamed
268 .clone()
269 .unwrap_or_else(|| crate::method::Member::With.name(column)),
270 ),
271 Self::Set(renamed) => Filled::Setter(
272 renamed
273 .clone()
274 .unwrap_or_else(|| crate::method::Member::Set.name(column)),
275 ),
276 }
277 }
278}
279
280impl Construction {
281 /// Whether this field's declared TYPE is claimed by a blanket rule.
282 ///
283 /// Compared as TOKENS, which is the only comparison available: a macro holds spellings and
284 /// `syn::Type` has no semantic equality — `u32` and a `type Width = u32` are the same type to the
285 /// compiler and two different tokens here. The rule is stated in the declaration's own spelling
286 /// and matched against the declaration's own spelling, so the two agree by construction, and a
287 /// blanket that names an alias the fields do not use simply claims nothing.
288 #[must_use]
289 pub fn blankets(&self, ty: &syn::Type) -> bool {
290 let written = quote!(#ty).to_string();
291 self.blanket.iter().any(|rule| {
292 let rule = &rule.ty;
293 quote!(#rule).to_string() == written
294 })
295 }
296
297 /// THE CALL — the whole expression that yields the built value.
298 ///
299 /// `host` is the type the entry is called on. `supplied` is one entry per value, IN THE ORDER
300 /// THE DECLARATION WROTE THEM, which is the one order an author can see and therefore the one
301 /// order a positional argument list may be gathered in.
302 ///
303 /// # Two shapes, and the second is only reached when it has to be
304 ///
305 /// A CHAIN is what a protocol is: `Remote::new(a, b).with_c(c).build()`. It is also not an
306 /// attribute position — `.with_a(…) #[cfg(…)] .with_b(…)` is not Rust — and it has no place to
307 /// put a `&mut` setter's statement. So a protocol carrying a GATED link or a SETTER is unrolled
308 /// into a block binding, and one carrying neither stays the chain it always was, token for token.
309 #[must_use]
310 pub fn call(&self, host: &syn::Path, supplied: &[Supplied]) -> proc_macro2::TokenStream {
311 let entry = &self.entry;
312 let arguments = supplied
313 .iter()
314 .filter(|one| matches!(one.fill, Filled::Entry))
315 .map(|one| {
316 let (gate, value) = (&one.gate, &one.value);
317 quote!(#gate #value)
318 });
319 let mut head = quote!(#host::#entry(#(#arguments),*));
320 // The `?` rides the TERMINAL step, which is the entry only where no finish closes the protocol.
321 if self.fallible && self.finish.is_none() {
322 head = quote!(#head?);
323 }
324 let finish = self.finish.as_ref().map(|finish| {
325 let arguments = supplied
326 .iter()
327 .filter(|one| matches!(one.fill, Filled::Finish))
328 .map(|one| {
329 let (gate, value) = (&one.gate, &one.value);
330 quote!(#gate #value)
331 });
332 let call = quote!(.#finish(#(#arguments),*));
333 if self.fallible { quote!(#call?) } else { call }
334 });
335
336 // The LINKS, columns first and injections after: a column is a fact about the row and an
337 // injection is a fact about the declaration, and a reader following the argument list should
338 // reach the end of the row before the declaration's own additions begin.
339 let links: Vec<(&proc_macro2::TokenStream, Link<'_>)> = supplied
340 .iter()
341 .filter_map(|one| match &one.fill {
342 Filled::Link(method) => Some((&one.gate, Link::Chained(method, &one.value))),
343 Filled::Setter(method) => Some((&one.gate, Link::InPlace(method, &one.value))),
344 Filled::Entry | Filled::Finish => None,
345 })
346 .collect();
347 let injected: Vec<proc_macro2::TokenStream> = self
348 .calls
349 .iter()
350 .map(|call| {
351 let (method, value) = (&call.method, &call.value);
352 quote!(.#method(#value))
353 })
354 .collect();
355
356 let unrolled = links
357 .iter()
358 .any(|(gate, link)| !gate.is_empty() || matches!(link, Link::InPlace(..)));
359 if !unrolled {
360 let chained = links.iter().map(|(_, link)| link.chained());
361 return quote!(#head #(#chained)* #(#injected)* #finish);
362 }
363 let built = format_ident!("{BUILT}");
364 let steps = links.iter().map(|(gate, link)| {
365 let step = link.statement(&built);
366 quote! {
367 #gate
368 #step
369 }
370 });
371 quote! {
372 {
373 let mut #built = #head;
374 #(#steps)*
375 #(#built = #built #injected;)*
376 #built #finish
377 }
378 }
379 }
380}
381
382/// One refinement step, in whichever of its two spellings the protocol needs.
383enum Link<'a> {
384 /// A consuming `with_…`, which is a chain link and an assignment by turns.
385 Chained(&'a syn::Ident, &'a proc_macro2::TokenStream),
386 /// An in-place `set_…`, which is only ever a statement.
387 InPlace(&'a syn::Ident, &'a proc_macro2::TokenStream),
388}
389
390impl Link<'_> {
391 /// The link as a CHAIN element — the shape a protocol with nothing to unroll keeps.
392 fn chained(&self) -> proc_macro2::TokenStream {
393 match self {
394 Self::Chained(method, value) | Self::InPlace(method, value) => quote!(.#method(#value)),
395 }
396 }
397
398 /// The link as a STATEMENT over the binding — the shape a gate or a setter forces.
399 fn statement(&self, built: &syn::Ident) -> proc_macro2::TokenStream {
400 match self {
401 Self::Chained(method, value) => quote! {
402 {
403 #built = #built.#method(#value);
404 }
405 },
406 Self::InPlace(method, value) => quote! {
407 {
408 #built.#method(#value);
409 }
410 },
411 }
412 }
413}
414
415#[cfg(test)]
416mod tests;