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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! The REWRITE MODE's emission — what a declaration means when it WRAPS a foreign type.
//!
//! The front half is `ingraph_derive`'s `remote` module, which owns the item: the fields an author
//! wrote become a MANIFEST and the item the compiler sees becomes
//! `#[repr(transparent)] struct X(Remote);`. This half is everything that follows from that, and it
//! is one idea repeated: **a manifest column is read through the remote's own accessor and crossed
//! by `Into`, and a wrapper is built through the remote's own constructor.**
//!
//! Every other face is UNCHANGED and that is the design. A column carries a name, a type, a
//! projection and its markers whether it was declared or restated, so the row, the filter, the
//! comparison, the order-by and the wire face read exactly what they read before — see
//! [`RecordModel::remote`](crate::model::RecordModel::remote). What moves is two seams:
//!
//! | seam | ordinary | rewrite |
//! |---|---|---|
//! | READ a column | `record.width` | `record.0.width()`, crossed |
//! | BUILD the value | `Self { width, … }` | `Self(Remote::new(…).with_…(…))` |
//!
//! # The reference family is the LANGUAGE's guarantee, not a layout claim
//!
//! `Deref`, `AsRef`, `Borrow` and their mutable halves all hand back `&self.0`, which is a field
//! access on a 1-tuple. No `transmute` is written and none is needed; the `repr(transparent)` on the
//! wrapper is what makes the two types interchangeable to a caller, and the borrow is ordinary Rust
//! either way. The alternative — asserting size and align and transmuting — was refused on
//! soundness: a `repr(Rust)` layout is not verifiable from outside and `offset_of!` cannot name a
//! private field of a foreign type.
//!
//! `Borrow<Remote>`'s contract — that `Eq`, `Ord` and `Hash` agree between the two — holds for the
//! reason a 1-tuple newtype's always does: the wrapper's derives delegate to its one field, and the
//! author's own `#[derive(…)]` is forwarded onto the wrapper by the rewrite.
//!
//! # `Deref` is the ONLY sound method inheritance, and it is why the wrapper exists
//!
//! A restatement — the shape `derive(Enum)`'s mirror mode takes — cannot inherit a method: it holds
//! its own value and the upstream's is nowhere. A wrapper holds the upstream itself, so `Deref` is
//! real forwarding and every method the remote has is reachable through it, with no per-method
//! declaration and nothing to keep in step across an upstream release.
//!
//! # What the compiler checks, and where the caret lands
//!
//! The manifest is a CLAIM ABOUT AN API — not about a layout, which is unknowable from here — and
//! every part of it is discharged by the compiler at a span this emission puts on the author's own
//! token:
//!
//! | the claim | how it fails |
//! |---|---|
//! | the remote has an accessor per manifest field | no method — at the manifest field |
//! | its return type crosses to the manifest type | [`BRIDGE`]'s named `E0277` — at the manifest field |
//! | an identity field's accessor BORROWS | `E0308` — at the manifest field |
//! | the remote has a constructor of this arity | `E0061` — at the row conversion |
//! | it has a `with_…` per optional field | no method — at the manifest field |
//!
//! The identity row is the one asymmetry and it is forced rather than chosen. This framework's
//! identity seats BORROW — `Identifiable::id_ref(&self) -> &Self::Id`, and `From<&Record>` clones a
//! lineage step out of the record — so an identity column has to be reachable as a reference or
//! those seats cannot be served at all, and a value crossed by `Into` has no address to hand out. A
//! data column has no borrowed seat anywhere and therefore crosses by value. It reads as the
//! accessor law one tier up already reads: identity columns are handled by reference and set at
//! construction, data columns are the ones with a family.
//!
//! # THE CORE IS SHARED, and the identity seat is the one part of it that is not
//!
//! Three declarations take `remote = "…"`: `entity`, `record` and — bearing no id — `fields`. What
//! the first two reach through [`RecordModel`] and the third reaches directly is the SAME core,
//! written once here as free functions over `(subject, remote)`:
//!
//! | the piece | who emits it |
//! |---|---|
//! | [`prelude`] — the bridge marker, its blanket impl and the crossing function | all three |
//! | [`family`] — the reference family and the two `From`s | all three |
//! | [`identity_owner`] — the clone behind a type parameter | the rungs that BEAR an id |
//!
//! The last row is the split, and it is the tier's definition rather than a convenience. A fragment
//! has no identity seat to serve, so it never reads an id out of a remote — and emitting the helper
//! anyway would put a `warning: function \`__ingraph_owned\` is never used` in the declaring crate,
//! MEASURED by compiling an unused item inside an anonymous const and reading `dead_code` back.

use quote::{format_ident, quote, quote_spanned};

use crate::{
  construct::{Cross, Seat, Supplied},
  method::{Family, Member},
  model::{Field, Projection, RecordModel},
};

/// The BRIDGE — the marker every manifest read crosses, so a missing conversion is named.
///
/// A bare `Into` would work and would say the wrong thing: rustc would report
/// `the trait bound \`u16: Into<u32>\` is not satisfied` at a body the author cannot edit, naming a
/// std trait rather than the rule that was broken. Routed through a marker carrying
/// `on_unimplemented`, with `do_not_recommend` on the blanket impl so the report stops at the
/// marker, one sentence reaches the author — and the CALL is spanned at the manifest field, so the
/// caret lands on the line they would fix.
///
/// It is the union seat's shape, and deliberately: that pattern is this tree's answer to *a
/// generated obligation should refuse in the framework's own words*.
const BRIDGE: &str = "__IngraphRemoteBridge";

/// The free function every read is written through — [`BRIDGE`] with both parameters inferred.
///
/// A function rather than the trait method spelled at each site, because the two positions infer
/// from opposite ends: a reader's target is its return type, and a constructor argument's is the
/// remote's own signature. One call shape serves both.
const CROSS: &str = "__ingraph_cross";

/// The free function an IDENTITY read is owned through — a generic `clone` behind a type parameter.
///
/// The rewrite's identity seat hands back a BORROW, so a read that owns the value has to clone it,
/// and a macro cannot know whether the id is `Copy`. Written inline — `Clone::clone(remote.id())`,
/// fully qualified or not — that is `clippy::clone_on_copy` in the consuming crate for every `Copy`
/// id, at a span the author cannot edit. Behind a type parameter it cannot be: inside the function
/// `T` is not known to be `Copy`, and at the call site there is no `clone` to lint.
///
/// It is the same answer [`CROSS`] is, one obligation over — a generated read reaches its value
/// through a function this expansion owns, so the lint surface of the emission is this module's
/// rather than every declaring crate's.
const OWNED: &str = "__ingraph_owned";

/// The ident every manifest read is spelled through, for the emissions that write one.
///
/// A function rather than a `const` another module reads, so the NAME lives at [`CROSS`] and every
/// caller asks for it rather than re-spelling it.
pub(crate) fn cross() -> syn::Ident {
  format_ident!("{CROSS}")
}

/// ONE value a raise supplies, as the SADDLE sees it before the protocol does.
///
/// # The shape is what makes the saddle a free function rather than a method
///
/// Two declarations raise a wrapped value now — a `record` out of its stored row, and a field
/// fragment out of the columns it spans — and their models share nothing: a
/// [`Field`](crate::model::Field) carries an identity, a condition and a per-database column, and a
/// fragment's field carries none of the three. What the PROTOCOL needs is smaller than either, and
/// this is exactly that: the four facts [`crossing`] and [`seat`] read, gathered by whichever model
/// has them.
///
/// So the saddle below is written once over these, and the two callers differ only in the walk that
/// fills them. That is the lowering [ingraph#316]'s builder-suite ratification deferred to the
/// fields mount: while one declaration raised, a method on its model was the same thing; with two,
/// a method on one of them is a saddle the other has to reach through a type it is not.
///
/// [ingraph#316]: https://github.com/findit-studio/ingraph/issues/316
pub(crate) struct Ingredient<'a> {
  /// The MANIFEST FIELD's own name — spent on the seat's default method name, and on the SPAN every
  /// obligation the crossing creates is reported at.
  pub(crate) source: &'a syn::Ident,
  /// The type the manifest RESTATED, which is what `into` pins the crossing's target to.
  pub(crate) ty: &'a syn::Type,
  /// Whether the column has an EMPTY STATE — `#[ingraph(optional)]`, read as the options family's
  /// own split rather than off the spelled type, per the standing rule that a macro holds tokens.
  pub(crate) optional: bool,
  /// The `builder(…)` words this field wrote, or the default law where it wrote none.
  pub(crate) build: &'a crate::construct::Build,
  /// The `#[cfg(…)]` this value rides, or empty where it rides none.
  pub(crate) gate: proc_macro2::TokenStream,
  /// The value itself, read out of whatever the raise is raising from.
  pub(crate) value: proc_macro2::TokenStream,
}

/// BUILD a wrapper from one value per manifest field, through the remote's own CONSTRUCTION
/// PROTOCOL.
///
/// The ORDER the protocol is called in is the DECLARATION's — the one order an author can see, and
/// therefore the one order a positional argument list may be gathered in — so `ingredients` arrives
/// in declared order and this walk does not sort it.
///
/// A field carrying `builder(skip)` is left out: the word says the column is not handed back at all,
/// and what fills it is whatever the remote's own constructor puts there.
///
/// # This is the SADDLE, and [`crate::construct`] is the protocol
///
/// What lives here is the MANIFEST half: how a column's value crosses into the type the remote's own
/// signature spells, and which seat it takes when the declaration named none. What the protocol IS —
/// the entry, the finish, the links, the injections and the two shapes they can be written in — is
/// [`Construction::call`](crate::construct::Construction::call)'s, so both saddles spend one copy of
/// it.
///
/// A remote that keeps no describable protocol at all is still not stuck: the whole-body escape
/// replaces this expression with the author's own function.
pub(crate) fn build(
  remote: &syn::Path,
  construction: &crate::construct::Construction,
  ingredients: &[Ingredient<'_>],
) -> proc_macro2::TokenStream {
  let supplied: Vec<Supplied> = ingredients
    .iter()
    .filter(|one| !one.build.skip)
    .map(|one| Supplied {
      fill: seat(one).filled(one.source),
      // A CALL ARGUMENT is a stable attribute position, so a conditional required field simply
      // leaves the argument list — and the remote's own entry is the arity check, exactly as it is
      // for a manifest that never wrote a condition. A LINK is not one, which is why a gated link
      // unrolls the protocol into statements; see [`Construction::call`].
      gate: one.gate.clone(),
      value: crossing(construction, one),
    })
    .collect();
  let built = construction.call(remote, &supplied);
  quote!(Self(#built))
}

/// WHICH SEAT a manifest column fills — the word it wrote, or the default law.
///
/// The DEFAULT is the OPTIONS FAMILY's own split, read off a word this grammar already has:
/// `#[ingraph(optional)]` says a column has an empty state, which is exactly what an options type's
/// optional seat is, so it reaches a `with_…` link and every other column is a positional argument.
/// Nothing was invented to spell it, and `builder(arg)` / `builder(with)` are how a declaration
/// overrides it for a remote whose split falls elsewhere.
fn seat(ingredient: &Ingredient<'_>) -> Seat {
  ingredient.build.seat.clone().unwrap_or({
    if ingredient.optional {
      Seat::With(None)
    } else {
      Seat::Arg
    }
  })
}

/// ONE column's value, crossed into whatever the remote's own signature spells.
///
/// Four answers, and the precedence between them is the ordinary one — the field's own word beats
/// the declaration's blanket, and the blanket beats the default:
///
/// | written | emitted | why |
/// |---|---|---|
/// | `map = "f"` | `f` | the conversion the bridge cannot reach |
/// | `into`, or a blanket claiming the type | `cross::<Ty, _>` | the seat is `impl Into<…>`, so the target is PINNED |
/// | nothing | `cross` | the bridge, with its target read off the seat |
///
/// `option` is the fourth answer and it composes with the other three rather than replacing one: it
/// says the seat takes the `Option` WHOLE, so whichever crosser was chosen is applied INSIDE it —
/// `Option::map(value, crosser)` — which is the conversion std does not lift and an author would
/// otherwise write by hand. It does not compose with `into`, whose pinned target would be the option
/// rather than its item, and the grammar refuses the pair by name.
///
/// Spanned at the MANIFEST FIELD throughout, so every obligation the crossing creates — the bridge's
/// named `E0277`, a `map` function that does not exist, an item type that does not convert — reports
/// on the line an author would edit.
fn crossing(
  construction: &crate::construct::Construction,
  ingredient: &Ingredient<'_>,
) -> proc_macro2::TokenStream {
  let cross = cross();
  let at = ingredient.source.span();
  let ty = ingredient.ty;
  let value = &ingredient.value;
  let crosser = match &ingredient.build.cross {
    Some(Cross::Map(path)) => quote_spanned!(at=> #path),
    Some(Cross::Into) => quote_spanned!(at=> #cross::<#ty, _>),
    None if construction.blankets(ty) => quote_spanned!(at=> #cross::<#ty, _>),
    None => quote_spanned!(at=> #cross),
  };
  if ingredient.build.option {
    return quote_spanned!(at=> ::core::option::Option::map(#value, #crosser));
  }
  quote_spanned!(at=> #crosser(#value))
}

/// The rewrite's PRELUDE — the bridge marker, its blanket impl and the crossing function, declared
/// once inside the expansion's own const.
///
/// `subject` is the DECLARATION the manifest belongs to and is spent on the two diagnostic strings
/// alone: the sentence names the type whose manifest made the claim, which is what tells an author
/// which declaration to go and edit. `remote` is spent on the note, and on nothing else — the
/// bridge is generic in both directions, so no wrapped type appears in the emitted items.
///
/// A free function over those two rather than a method on one model, because THREE declarations
/// mint this: `entity` and `record` through [`RecordModel::remote_prelude`], and the field-fragment
/// tier through [`crate::fields::FieldsModel`]. One core, so the sentence a missing conversion is
/// reported with cannot come to differ between the rungs that share the device.
pub(crate) fn prelude(subject: &syn::Ident, remote: &syn::Path) -> proc_macro2::TokenStream {
  let bridge = format_ident!("{BRIDGE}");
  let cross = cross();
  let message = format!(
    "`{{Self}}` does not cross into `{{__IngraphTo}}`, which is what `{subject}`'s manifest says \
     this field holds"
  );
  let note = format!(
    "a field of `{subject}` is read through `{}`'s own accessor and crossed by `Into` — so the \
     accessor's return type must convert into the type the manifest gives the field. Restate the \
     field at the type the accessor really hands back, or give the two types a conversion",
    path_text(remote),
  );
  quote! {
    #[diagnostic::on_unimplemented(
      message = #message,
      label = "the remote's accessor hands back a type this field cannot be built from",
      note = #note,
    )]
    trait #bridge<__IngraphTo> {
      fn #cross(self) -> __IngraphTo;
    }

    // Without this the report descends through the blanket impl and names `Into`, which is true
    // and is not the sentence this framework wants to say.
    #[diagnostic::do_not_recommend]
    impl<__IngraphTo, __IngraphFrom> #bridge<__IngraphTo> for __IngraphFrom
    where
      __IngraphFrom: ::core::convert::Into<__IngraphTo>,
    {
      #[inline]
      fn #cross(self) -> __IngraphTo {
        ::core::convert::Into::into(self)
      }
    }

    #[inline]
    fn #cross<__IngraphTo, __IngraphFrom: #bridge<__IngraphTo>>(
      __ingraph_value: __IngraphFrom,
    ) -> __IngraphTo {
      #bridge::#cross(__ingraph_value)
    }
  }
}

/// [`OWNED`] — the clone behind a type parameter, emitted BESIDE the prelude by the rungs that bear
/// an identity.
///
/// Separate from [`prelude`] because what it serves is the identity seat, and a declaration without
/// one never calls it. An unused item inside an anonymous const is `dead_code` in the DECLARING
/// crate — measured, by compiling exactly this shape with no caller — so a tier that bears no id
/// emits no such function rather than an `allow` over one.
pub(crate) fn identity_owner() -> proc_macro2::TokenStream {
  let owned = format_ident!("{OWNED}");
  quote! {
    #[inline]
    fn #owned<__IngraphId: ::core::clone::Clone>(__ingraph_value: &__IngraphId) -> __IngraphId {
      ::core::clone::Clone::clone(__ingraph_value)
    }
  }
}

/// The wrapper's REFERENCE FAMILY and its two conversions — the whole of what makes a wrapper
/// usable where the remote was.
///
/// Six borrows and two moves, and every one of them is `self.0`. The mutable halves are here for
/// the reason the shared ones are: a transparent wrapper that could only be read would make every
/// mutating method of the remote unreachable, and `DerefMut` beside `Deref` is what keeps method
/// inheritance whole rather than half.
///
/// `From` in both directions is the trivial wrap and unwrap. It is what a caller crosses at an
/// API boundary — and it is what the round-trip pin asserts is an identity in both directions.
///
/// Free over `(subject, remote)` for [`prelude`]'s reason: the family is the same eight impls on
/// whichever rung wraps, a wrapper being a 1-tuple whatever faces it goes on to wear.
pub(crate) fn family(subject: &syn::Ident, remote: &syn::Path) -> proc_macro2::TokenStream {
  quote! {
    #[automatically_derived]
    impl ::core::convert::AsRef<#remote> for #subject {
      #[inline]
      fn as_ref(&self) -> &#remote {
        &self.0
      }
    }

    #[automatically_derived]
    impl ::core::convert::AsMut<#remote> for #subject {
      #[inline]
      fn as_mut(&mut self) -> &mut #remote {
        &mut self.0
      }
    }

    #[automatically_derived]
    impl ::core::ops::Deref for #subject {
      type Target = #remote;

      #[inline]
      fn deref(&self) -> &#remote {
        &self.0
      }
    }

    #[automatically_derived]
    impl ::core::ops::DerefMut for #subject {
      #[inline]
      fn deref_mut(&mut self) -> &mut #remote {
        &mut self.0
      }
    }

    #[automatically_derived]
    impl ::core::borrow::Borrow<#remote> for #subject {
      #[inline]
      fn borrow(&self) -> &#remote {
        &self.0
      }
    }

    #[automatically_derived]
    impl ::core::borrow::BorrowMut<#remote> for #subject {
      #[inline]
      fn borrow_mut(&mut self) -> &mut #remote {
        &mut self.0
      }
    }

    #[automatically_derived]
    impl ::core::convert::From<#remote> for #subject {
      #[inline]
      fn from(remote: #remote) -> Self {
        Self(remote)
      }
    }

    #[automatically_derived]
    impl ::core::convert::From<#subject> for #remote {
      #[inline]
      fn from(wrapper: #subject) -> Self {
        wrapper.0
      }
    }
  }
}

impl RecordModel {
  /// The rewrite's PRELUDE, on a rung that BEARS an identity — [`prelude`], and the identity owner
  /// beside it.
  ///
  /// Empty for an ordinary declaration, which is what makes the mode free: a model with no remote
  /// emits not one token of this module.
  pub(crate) fn remote_prelude(&self) -> proc_macro2::TokenStream {
    let Some(remote) = &self.remote else {
      return proc_macro2::TokenStream::new();
    };
    let bridge = prelude(&self.record, remote);
    let owner = identity_owner();
    quote! {
      #bridge
      #owner
    }
  }

  /// The wrapper's REFERENCE FAMILY — [`family`], over this record's own name.
  pub(crate) fn remote_family(&self) -> proc_macro2::TokenStream {
    self
      .remote
      .as_ref()
      .map_or_else(proc_macro2::TokenStream::new, |remote| {
        family(&self.record, remote)
      })
  }

  /// The wrapper's own inherent impl: ONE reader per manifest field, and no mutator.
  ///
  /// Three differences from the ordinary family, each forced by what a wrapper is:
  ///
  /// * **no mutators.** A remote's fields are its own; nothing here can assign into one, and a
  ///   `with_…` that rebuilt the whole value would be a constructor wearing a setter's name.
  /// * **no `const`.** The body calls a foreign accessor, and a foreign accessor is not this
  ///   emission's to declare `const`.
  /// * **by value for data, by reference for identity** — see the module note's last table.
  ///
  /// The field's own doc comments ride the reader. They were written about a field the rewrite
  /// deletes, and the reader is where that field's meaning is still answerable.
  pub(crate) fn remote_methods(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    let vis = &self.vis;
    let cross = cross();
    let families = self.fields.iter().map(|field| {
      let column = &field.column;
      let name = &column.source;
      let ty = &column.ty;
      let docs = &field.docs;
      let at = name.span();
      let subject = format!("`{name}` field of this [`{record}`]");
      let Family { value, borrow, .. } = wrapped_family(field);
      // The CONDITION, and the one artifact the field's DECORATION stands in on. A manifest field is
      // deleted by the rewrite, so the reader is where its `#[cfg_attr]` lands for the same reason
      // its doc comments do — that is the artifact a reader still asks the field's question at.
      let gate = field.condition.gate();
      let decorations = field.condition.decorations();
      // The identity seat: the remote's accessor is taken to BORROW, so the reader is the borrow and
      // a `copy` field's by-value reader is the dereference beside it.
      let borrow = borrow.map(|borrow| {
        let doc = crate::emit::leading(&format!("The {subject}, by reference."));
        let read = quote_spanned!(at=> self.0.#name());
        quote! {
          #gate
          #(#docs)*
          #(#decorations)*
          #[doc = #doc]
          #[inline]
          #vis fn #borrow(&self) -> &#ty {
            #read
          }
        }
      });
      let value = value.map(|value| {
        let doc = crate::emit::leading(&format!("The {subject}."));
        let read = if field.identity {
          quote_spanned!(at=> *self.0.#name())
        } else {
          quote_spanned!(at=> #cross(self.0.#name()))
        };
        quote! {
          #gate
          #(#docs)*
          #(#decorations)*
          #[doc = #doc]
          #[inline]
          #vis fn #value(&self) -> #ty {
            #read
          }
        }
      });
      quote! {
        #value
        #borrow
      }
    });
    quote! {
      impl #record {
        #(#families)*
      }
    }
  }

  /// ONE manifest column's value, OWNED, read off a binding that holds the wrapper.
  ///
  /// The seam every emission outside this module reaches the rewrite through — the key conversions,
  /// the row's write leg — so there is exactly one place that decides what reading a wrapped column
  /// means.
  pub(crate) fn remote_read(
    &self,
    binding: &syn::Ident,
    source: &syn::Ident,
  ) -> proc_macro2::TokenStream {
    let at = source.span();
    if self.identity_bearing(source) {
      // Through [`OWNED`] rather than `Clone::clone` spelled here: the accessor hands back a BORROW
      // and the read owns it, and a clone written at this site is `clone_on_copy` in the consuming
      // crate for every `Copy` id — at a span the author cannot edit. Behind the function's own type
      // parameter there is no `Copy` for the lint to see.
      let owned = format_ident!("{OWNED}");
      quote_spanned!(at=> #owned(#binding.0.#source()))
    } else {
      let cross = cross();
      quote_spanned!(at=> #cross(#binding.0.#source()))
    }
  }

  /// The wrapper's own `id_ref` body — the borrowed identity seat, read straight off the remote.
  pub(crate) fn remote_id_ref(&self) -> proc_macro2::TokenStream {
    let source = &self.key.id.source;
    quote_spanned!(source.span()=> self.0.#source())
  }

  /// BUILD a wrapper from one value per manifest field — this rung's WALK over the shared saddle.
  ///
  /// `values` is keyed by the field's own name, in whatever order the caller gathered them; what
  /// this hands the saddle is the DECLARATION's order, which is the one order an author can see and
  /// therefore the one order a positional argument list may be gathered in. A field the caller
  /// supplied no value for is skipped — the caller has already refused a row that cannot rebuild the
  /// record — so a short argument list is `E0061` naming the arity.
  ///
  /// Everything below the gathering is [`build`]'s: the crossing, the seat's default law, and the
  /// call the protocol writes. What is left here is the part that is a RECORD's — that a value comes
  /// from a stored row, that the condition seat is a field's `cfg`, and that the empty state is the
  /// `optional` projection — which is exactly the part a fragment answers differently.
  pub(crate) fn remote_build(
    &self,
    values: &[(syn::Ident, proc_macro2::TokenStream)],
  ) -> proc_macro2::TokenStream {
    let remote = self.remote.as_ref().expect("a rewrite's own path");
    let of = |field: &Field| {
      values
        .iter()
        .find(|(name, _)| name == &field.column.source)
        .map(|(_, value)| value)
    };
    let ingredients: Vec<Ingredient<'_>> = self
      .fields
      .iter()
      .filter_map(|field| {
        Some(Ingredient {
          source: &field.column.source,
          ty: &field.column.ty,
          optional: matches!(field.column.project, Projection::Optional),
          build: &field.build,
          gate: field.condition.gate(),
          value: of(field)?.clone(),
        })
      })
      .collect();
    build(remote, &self.construction, &ingredients)
  }

  /// Whether a field of this declaration BEARS IDENTITY — the id, or a step of the lineage path.
  ///
  /// Asked of the field list rather than of the key, because the key's columns carry their scoped
  /// names and this question is about the record's own.
  fn identity_bearing(&self, source: &syn::Ident) -> bool {
    self
      .fields
      .iter()
      .any(|field| &field.column.source == source && field.identity)
  }
}

/// A path as a reader would write it — for a message naming the remote.
fn path_text(path: &syn::Path) -> String {
  quote!(#path)
    .to_string()
    .replace(" :: ", "::")
    .replace(" <", "<")
    .replace("< ", "<")
    .replace(" >", ">")
}

/// One manifest field's METHOD FAMILY — the names its reader occupies, and nothing else.
///
/// Shared with the emission's own name enumeration, exactly as `Column::family` is: a check over
/// these names is a check over the names really emitted rather than over a second reading of the
/// rule.
pub(crate) fn wrapped_family(field: &Field) -> Family {
  let name = &field.column.source;
  Family {
    // A data column reaches its value by crossing, and there is no borrow to hand out. An identity
    // column takes the by-value reader only where `copy` already asked for one.
    value: (!field.identity || field.column.project.copies()).then(|| Member::Value.name(name)),
    borrow: field.identity.then(|| Member::Borrow.name(name)),
    slice: None,
    set: None,
    with: None,
  }
}

#[cfg(test)]
mod tests;