ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! **THE CONSTRUCTION PROTOCOL** — what it takes to build somebody else's value, described.
//!
//! Every other grammar in this tree describes a type's SHAPE: what columns it has, how each is
//! stored, what a client may ask about one. This one describes a type's CONSTRUCTOR — the sequence
//! of calls that turns a row's worth of values back into the value they came out of — and it exists
//! because the rewrite mode made that sequence somebody else's business. A declaration wrapping
//! `mediaframe::Dimensions` cannot change how `Dimensions` is built; it can only say how it is.
//!
//! # We are the DESCRIBING side, and the vocabulary is chosen from that seat
//!
//! [`bon`](https://docs.rs/bon) and its neighbours are the GENERATING side: their words dress a
//! builder that does not exist yet — the setter's prefix, the doc comment on the state type, the
//! `#[must_use]`. None of those reaches this vocabulary, because there is no artifact here for them
//! to decorate. What DOES reach it is every word that names a call the emission has to write:
//!
//! | word | seat | what it names |
//! |---|---|---|
//! | `builder(entry = "…")` | container | the first call — `new` unless something else |
//! | `builder(finish = "…")` | container | the LAST call; writing one is what makes this a builder |
//! | `builder(fallible)` | container | the terminal step hands back a `Result` |
//! | `builder(on(Type, into))` | container | every field of `Type` reaches a seat taking `impl Into` |
//! | `builder(call(with = "…", value = "…"))` | container | a link no column feeds |
//! | `builder(arg)` | field | a positional argument to the ENTRY |
//! | `builder(finish_arg)` | field | a positional argument to the FINISH |
//! | `builder(with[ = "…"])` | field | a chaining link, `with_<field>` unless renamed |
//! | `builder(set[ = "…"])` | field | an in-place setter, `set_<field>` unless renamed |
//! | `builder(into)` | field | this seat takes `impl Into`, so the argument is PINNED |
//! | `builder(map = "…")` | field | the value crosses through a function instead of `Into` |
//! | `builder(option)` | field | the seat takes the `Option` whole, crossing INSIDE it |
//! | `builder(skip)` | field | this column is not fed back at all |
//!
//! # The DEFAULT LAW is unchanged, and that is the load-bearing promise
//!
//! A declaration writing none of these words builds exactly what it built before the vocabulary
//! existed: `Remote::new(<every required column, in declaration order>)` followed by one
//! `.with_<name>(…)` per `#[ingraph(optional)]` column. That is not a coincidence to be maintained
//! by care — it is [`Construction::default`] and [`Build::default`] resolving to the same two seats
//! the hand-written emission chose, and `ingraph-codegen`'s own golden asserts the token stream is
//! the one it always was.
//!
//! # A WRONG word is settled by the compiler, at the call this writes
//!
//! Nothing here resolves a method: `finish = "buidl"` is a name, and a name that no method answers
//! to is `E0599` at the raise. That is deliberate and it is the same posture the rewrite mode
//! already takes — the manifest is a CLAIM ABOUT AN API this crate cannot see, and the compiler is
//! the only reader that can check one. What this module owns is the claim's SHAPE: that a
//! `finish_arg` has a `finish` to be an argument of, that one field fills one seat, that a word only
//! a wrapper can spend is not written on a declaration that is its own storage.
//!
//! # Where the pieces live
//!
//! The grammar, the parse and the shape refusals are `ingraph_derive`'s `construct` module —
//! exactly one copy, whichever saddle mounts it. This half is the MODEL those produce and the
//! WRITER that spends it, and it is here rather than there because emission lives here and the
//! dependency runs `ingraph-derive` → `ingraph-codegen`. [`crate::remote`] is the first saddle: it
//! gathers one crossed value per manifest column and hands them to [`Construction::call`].

use quote::{format_ident, quote};

/// The local the STATEMENT form binds the value under, inside the expansion's own namespace.
///
/// Held as one constant because two shapes spell it — the `let mut` that opens the block and every
/// step that assigns through it — and a binding that drifted between them would be `E0425` inside
/// an expansion nobody can edit.
const BUILT: &str = "__ingraph_built";

/// What a declaration says about the way its wrapped type is BUILT.
///
/// Every field defaults to the shape the emission had before the vocabulary existed, which is what
/// makes the words free: a declaration that writes no `builder(…)` carries this value, and the
/// writer turns it into the same tokens the hand-written version emitted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Construction {
  /// The `builder(…)` word's own path, or [`None`] where the declaration wrote none.
  ///
  /// Kept for the SPAN, exactly as [`RecordModel::asynchronous`](crate::model::RecordModel) keeps
  /// one: the refusal a construction word earns on a declaration that wraps nothing has to blame
  /// the word, and a defaulted value has no token for a caret to land on. It is also the one
  /// reliable answer to *was anything written* — every other field has a meaningful default.
  pub at: Option<syn::Path>,
  /// The FIRST call — `Remote::<entry>(…)`.
  ///
  /// `new` unless `entry = "…"` named another, which is the house rule stated as a default rather
  /// than assumed: a type that keeps the options family has a `new`, and one that spells its
  /// constructor `from_ratio` says so in one word instead of taking the whole-body escape.
  pub entry: syn::Ident,
  /// The LAST call — `.<finish>(…)` — or [`None`] where the entry hands back the value itself.
  ///
  /// **Its presence is what makes this a BUILDER protocol rather than a constructor.** Without it
  /// the entry's return value IS the remote and every link is a consuming `with_…` on the remote
  /// itself; with it the entry opens a builder, the links refine the builder, and this call closes
  /// it. One word decides between the two, because one word is the whole difference.
  pub finish: Option<syn::Ident>,
  /// `fallible` — the TERMINAL step hands back a `Result`, and the raise carries its `Err`.
  ///
  /// # The terminal step, which is the finish where there is one and the entry otherwise
  ///
  /// The word is read at the step that YIELDS THE VALUE, and the reading is forced by what is
  /// useful rather than chosen for symmetry: the shape that exists in the wild is an infallible
  /// opening (`Remote::builder()`) closed by a validating `build()`, and a word that demanded both
  /// halves be fallible could not describe it at all. A protocol whose ENTRY is the fallible half
  /// writes no `finish`, and the same word reaches it.
  ///
  /// What the `Err` joins is the road the raise already has: `<db>(try_into(error = "…"))`
  /// types the row's `TryFrom` where a declaration named a type, and the boxed
  /// `dyn Error + Send + Sync` is what it is otherwise — so the `?` written here converts through
  /// the same `From` every fallible column conversion already converts through.
  pub fallible: bool,
  /// `on(Type, into)` — the BLANKET, one entry per rule, in the order they were written.
  ///
  /// A rule keyed by the field's declared TYPE rather than by its name, which is bon's own shape
  /// and deliberately so: a remote whose builder was generated with `#[builder(on(String, into))]`
  /// has one fact to restate, and restating it per field is how a manifest and its upstream drift.
  pub blanket: Vec<Blanket>,
  /// `call(with = "…", value = "…")` — the links NO column feeds, in the order they were written.
  ///
  /// The seat for a constructor argument that is not a column of this record: a unit the upstream
  /// demands and the row does not store, a mode word, a capacity hint. Repeatable, because a
  /// protocol may want several and each is one independent fact.
  pub calls: Vec<Injection>,
}

impl Default for Construction {
  fn default() -> Self {
    Self {
      at: None,
      entry: format_ident!("new"),
      finish: None,
      fallible: false,
      blanket: Vec::new(),
      calls: Vec::new(),
    }
  }
}

/// One `on(Type, into)` rule — a crossing stated once for every field of a type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Blanket {
  /// The type the rule is keyed by, as the declaration spelled it.
  pub ty: syn::Type,
}

/// One `call(with = "…", value = "…")` — a link whose value comes from the declaration itself.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Injection {
  /// The method's OWN name, spelled in full.
  ///
  /// Not a field name with `with_` pasted on: there is no field here to derive one from, and the
  /// same is true of the field seat's `with = "…"` — in both positions the value names the method.
  pub method: syn::Ident,
  /// The expression the link is handed, re-parsed from the string that carried it.
  ///
  /// An EXPRESSION rather than a literal, so the seat reaches a constant, a path, a call — whatever
  /// the upstream's argument really is. It is emitted verbatim; what it means is the compiler's.
  pub value: syn::Expr,
}

/// What ONE field says about its own place in the protocol.
///
/// Every part of it is an override: a field writing nothing at all takes the seat the default law
/// gives it, crosses by the bridge, and is fed back like every other column.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Build {
  /// The `builder(…)` block's own path on this field, kept for the span its refusals report at.
  pub at: Option<syn::Path>,
  /// Which seat this field fills, or [`None`] for the one the default law gives it.
  pub seat: Option<Seat>,
  /// How the value crosses, or [`None`] for the bridge with its target inferred.
  pub cross: Option<Cross>,
  /// `option` — the seat takes the `Option` WHOLE, and the crossing happens inside it.
  ///
  /// The gap it closes is `Into`'s own: `Option<A>` does not convert into `Option<B>` however
  /// well `A` converts into `B`, std lifting no conversion through the type. So a manifest column
  /// restated as `Option<u16>` whose remote seat is `Option<Depth>` cannot cross at all by default
  /// — and this word says *cross the item and hand the seat the option*, which is the conversion an
  /// author would have written by hand.
  pub option: bool,
  /// `skip` — this column is NOT fed back into the construction.
  ///
  /// # The round trip becomes the AUTHOR's assertion, and that is the whole cost of the word
  ///
  /// Every other column is read out through an accessor and handed back to the constructor, so the
  /// value that comes out of a row is the value that went in. A skipped one is read out and never
  /// handed back: what fills it on the way in is whatever the remote's own constructor puts there.
  /// Where those agree the round trip holds and the word costs nothing; where they do not, the word
  /// is a declaration that the difference does not matter — which is a claim about the domain that
  /// no compiler can check and every reader of the declaration is entitled to see justified.
  pub skip: bool,
}

/// WHICH call a field's value reaches, and under what name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Seat {
  /// `arg` — a positional argument to the entry.
  Arg,
  /// `finish_arg` — a positional argument to the finish.
  FinishArg,
  /// `with` / `with = "…"` — a CONSUMING link, `with_<field>` unless the word renamed it.
  With(Option<syn::Ident>),
  /// `set` / `set = "…"` — an IN-PLACE setter, `set_<field>` unless the word renamed it.
  ///
  /// bon has no equivalent and this vocabulary does, because the types being described are real:
  /// an upstream that grew `&mut` setters before it grew a builder is the ordinary case, and a
  /// grammar that could not name one would send it to the whole-body escape over punctuation.
  Set(Option<syn::Ident>),
}

/// HOW a field's value reaches its seat.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Cross {
  /// `into` — the seat takes `impl Into<…>`, so the argument's type is PINNED to the field's own.
  ///
  /// Inference is what needs the word. The bridge takes its target from the position it lands in,
  /// and a position spelled `impl Into<X>` is an anonymous type parameter rather than a type — so
  /// `bridge(value)` there asks the compiler to pick some `T: Into<X>` out of the whole program and
  /// it correctly refuses (`E0283`). Pinning the target to the type the manifest restated resolves
  /// it, and the remaining `T: Into<X>` obligation is the upstream's own signature doing its job.
  Into,
  /// `map = "…"` — the value crosses through the named function instead of through the bridge.
  ///
  /// The last 1% the bridge cannot reach: two types with no conversion between them, a lossy
  /// narrowing an author is willing to declare, a unit change. It OVERRIDES a blanket that would
  /// otherwise have claimed the field, which is the precedence a per-field word always has over a
  /// per-type one.
  Map(syn::Path),
}

/// ONE value the protocol carries, already crossed, with the seat it fills and its gate.
///
/// A saddle's whole contribution: [`crate::remote`] reads a manifest column, crosses it, resolves
/// the seat, and hands over one of these. The writer below knows nothing about manifests, columns
/// or rows — which is what lets a second saddle hand it a fragment's fields without a second copy
/// of the shapes.
pub struct Supplied {
  /// Which call this value reaches, resolved to a name.
  pub fill: Filled,
  /// The `#[cfg(…)]` this value rides, or empty where it rides none.
  pub gate: proc_macro2::TokenStream,
  /// The expression, crossed and ready to be an argument.
  pub value: proc_macro2::TokenStream,
}

/// A [`Seat`] with every name resolved — what the writer actually spells.
pub enum Filled {
  /// A positional argument to the entry.
  Entry,
  /// A positional argument to the finish.
  Finish,
  /// A consuming link, under this name.
  Link(syn::Ident),
  /// An in-place setter, under this name.
  Setter(syn::Ident),
}

impl Seat {
  /// This seat with its name resolved against the column that fills it.
  ///
  /// The two default names are the options family's own — `with_<column>` and `set_<column>` —
  /// read off [`Member`](crate::method::Member) rather than pasted here, so the names this writer
  /// spells are the names the framework's own family would have minted.
  #[must_use]
  pub fn filled(&self, column: &syn::Ident) -> Filled {
    match self {
      Self::Arg => Filled::Entry,
      Self::FinishArg => Filled::Finish,
      Self::With(renamed) => Filled::Link(
        renamed
          .clone()
          .unwrap_or_else(|| crate::method::Member::With.name(column)),
      ),
      Self::Set(renamed) => Filled::Setter(
        renamed
          .clone()
          .unwrap_or_else(|| crate::method::Member::Set.name(column)),
      ),
    }
  }
}

impl Construction {
  /// Whether this field's declared TYPE is claimed by a blanket rule.
  ///
  /// Compared as TOKENS, which is the only comparison available: a macro holds spellings and
  /// `syn::Type` has no semantic equality — `u32` and a `type Width = u32` are the same type to the
  /// compiler and two different tokens here. The rule is stated in the declaration's own spelling
  /// and matched against the declaration's own spelling, so the two agree by construction, and a
  /// blanket that names an alias the fields do not use simply claims nothing.
  #[must_use]
  pub fn blankets(&self, ty: &syn::Type) -> bool {
    let written = quote!(#ty).to_string();
    self.blanket.iter().any(|rule| {
      let rule = &rule.ty;
      quote!(#rule).to_string() == written
    })
  }

  /// THE CALL — the whole expression that yields the built value.
  ///
  /// `host` is the type the entry is called on. `supplied` is one entry per value, IN THE ORDER
  /// THE DECLARATION WROTE THEM, which is the one order an author can see and therefore the one
  /// order a positional argument list may be gathered in.
  ///
  /// # Two shapes, and the second is only reached when it has to be
  ///
  /// A CHAIN is what a protocol is: `Remote::new(a, b).with_c(c).build()`. It is also not an
  /// attribute position — `.with_a(…) #[cfg(…)] .with_b(…)` is not Rust — and it has no place to
  /// put a `&mut` setter's statement. So a protocol carrying a GATED link or a SETTER is unrolled
  /// into a block binding, and one carrying neither stays the chain it always was, token for token.
  #[must_use]
  pub fn call(&self, host: &syn::Path, supplied: &[Supplied]) -> proc_macro2::TokenStream {
    let entry = &self.entry;
    let arguments = supplied
      .iter()
      .filter(|one| matches!(one.fill, Filled::Entry))
      .map(|one| {
        let (gate, value) = (&one.gate, &one.value);
        quote!(#gate #value)
      });
    let mut head = quote!(#host::#entry(#(#arguments),*));
    // The `?` rides the TERMINAL step, which is the entry only where no finish closes the protocol.
    if self.fallible && self.finish.is_none() {
      head = quote!(#head?);
    }
    let finish = self.finish.as_ref().map(|finish| {
      let arguments = supplied
        .iter()
        .filter(|one| matches!(one.fill, Filled::Finish))
        .map(|one| {
          let (gate, value) = (&one.gate, &one.value);
          quote!(#gate #value)
        });
      let call = quote!(.#finish(#(#arguments),*));
      if self.fallible { quote!(#call?) } else { call }
    });

    // The LINKS, columns first and injections after: a column is a fact about the row and an
    // injection is a fact about the declaration, and a reader following the argument list should
    // reach the end of the row before the declaration's own additions begin.
    let links: Vec<(&proc_macro2::TokenStream, Link<'_>)> = supplied
      .iter()
      .filter_map(|one| match &one.fill {
        Filled::Link(method) => Some((&one.gate, Link::Chained(method, &one.value))),
        Filled::Setter(method) => Some((&one.gate, Link::InPlace(method, &one.value))),
        Filled::Entry | Filled::Finish => None,
      })
      .collect();
    let injected: Vec<proc_macro2::TokenStream> = self
      .calls
      .iter()
      .map(|call| {
        let (method, value) = (&call.method, &call.value);
        quote!(.#method(#value))
      })
      .collect();

    let unrolled = links
      .iter()
      .any(|(gate, link)| !gate.is_empty() || matches!(link, Link::InPlace(..)));
    if !unrolled {
      let chained = links.iter().map(|(_, link)| link.chained());
      return quote!(#head #(#chained)* #(#injected)* #finish);
    }
    let built = format_ident!("{BUILT}");
    let steps = links.iter().map(|(gate, link)| {
      let step = link.statement(&built);
      quote! {
        #gate
        #step
      }
    });
    quote! {
      {
        let mut #built = #head;
        #(#steps)*
        #(#built = #built #injected;)*
        #built #finish
      }
    }
  }
}

/// One refinement step, in whichever of its two spellings the protocol needs.
enum Link<'a> {
  /// A consuming `with_…`, which is a chain link and an assignment by turns.
  Chained(&'a syn::Ident, &'a proc_macro2::TokenStream),
  /// An in-place `set_…`, which is only ever a statement.
  InPlace(&'a syn::Ident, &'a proc_macro2::TokenStream),
}

impl Link<'_> {
  /// The link as a CHAIN element — the shape a protocol with nothing to unroll keeps.
  fn chained(&self) -> proc_macro2::TokenStream {
    match self {
      Self::Chained(method, value) | Self::InPlace(method, value) => quote!(.#method(#value)),
    }
  }

  /// The link as a STATEMENT over the binding — the shape a gate or a setter forces.
  fn statement(&self, built: &syn::Ident) -> proc_macro2::TokenStream {
    match self {
      Self::Chained(method, value) => quote! {
        {
          #built = #built.#method(#value);
        }
      },
      Self::InPlace(method, value) => quote! {
        {
          #built.#method(#value);
        }
      },
    }
  }
}

#[cfg(test)]
mod tests;