Skip to main content

ingraph_codegen/
remote.rs

1//! The REWRITE MODE's emission — what a declaration means when it WRAPS a foreign type.
2//!
3//! The front half is `ingraph_derive`'s `remote` module, which owns the item: the fields an author
4//! wrote become a MANIFEST and the item the compiler sees becomes
5//! `#[repr(transparent)] struct X(Remote);`. This half is everything that follows from that, and it
6//! is one idea repeated: **a manifest column is read through the remote's own accessor and crossed
7//! by `Into`, and a wrapper is built through the remote's own constructor.**
8//!
9//! Every other face is UNCHANGED and that is the design. A column carries a name, a type, a
10//! projection and its markers whether it was declared or restated, so the row, the filter, the
11//! comparison, the order-by and the wire face read exactly what they read before — see
12//! [`RecordModel::remote`](crate::model::RecordModel::remote). What moves is two seams:
13//!
14//! | seam | ordinary | rewrite |
15//! |---|---|---|
16//! | READ a column | `record.width` | `record.0.width()`, crossed |
17//! | BUILD the value | `Self { width, … }` | `Self(Remote::new(…).with_…(…))` |
18//!
19//! # The reference family is the LANGUAGE's guarantee, not a layout claim
20//!
21//! `Deref`, `AsRef`, `Borrow` and their mutable halves all hand back `&self.0`, which is a field
22//! access on a 1-tuple. No `transmute` is written and none is needed; the `repr(transparent)` on the
23//! wrapper is what makes the two types interchangeable to a caller, and the borrow is ordinary Rust
24//! either way. The alternative — asserting size and align and transmuting — was refused on
25//! soundness: a `repr(Rust)` layout is not verifiable from outside and `offset_of!` cannot name a
26//! private field of a foreign type.
27//!
28//! `Borrow<Remote>`'s contract — that `Eq`, `Ord` and `Hash` agree between the two — holds for the
29//! reason a 1-tuple newtype's always does: the wrapper's derives delegate to its one field, and the
30//! author's own `#[derive(…)]` is forwarded onto the wrapper by the rewrite.
31//!
32//! # `Deref` is the ONLY sound method inheritance, and it is why the wrapper exists
33//!
34//! A restatement — the shape `derive(Enum)`'s mirror mode takes — cannot inherit a method: it holds
35//! its own value and the upstream's is nowhere. A wrapper holds the upstream itself, so `Deref` is
36//! real forwarding and every method the remote has is reachable through it, with no per-method
37//! declaration and nothing to keep in step across an upstream release.
38//!
39//! # What the compiler checks, and where the caret lands
40//!
41//! The manifest is a CLAIM ABOUT AN API — not about a layout, which is unknowable from here — and
42//! every part of it is discharged by the compiler at a span this emission puts on the author's own
43//! token:
44//!
45//! | the claim | how it fails |
46//! |---|---|
47//! | the remote has an accessor per manifest field | no method — at the manifest field |
48//! | its return type crosses to the manifest type | [`BRIDGE`]'s named `E0277` — at the manifest field |
49//! | an identity field's accessor BORROWS | `E0308` — at the manifest field |
50//! | the remote has a constructor of this arity | `E0061` — at the row conversion |
51//! | it has a `with_…` per optional field | no method — at the manifest field |
52//!
53//! The identity row is the one asymmetry and it is forced rather than chosen. This framework's
54//! identity seats BORROW — `Identifiable::id_ref(&self) -> &Self::Id`, and `From<&Record>` clones a
55//! lineage step out of the record — so an identity column has to be reachable as a reference or
56//! those seats cannot be served at all, and a value crossed by `Into` has no address to hand out. A
57//! data column has no borrowed seat anywhere and therefore crosses by value. It reads as the
58//! accessor law one tier up already reads: identity columns are handled by reference and set at
59//! construction, data columns are the ones with a family.
60//!
61//! # THE CORE IS SHARED, and the identity seat is the one part of it that is not
62//!
63//! Three declarations take `remote = "…"`: `entity`, `record` and — bearing no id — `fields`. What
64//! the first two reach through [`RecordModel`] and the third reaches directly is the SAME core,
65//! written once here as free functions over `(subject, remote)`:
66//!
67//! | the piece | who emits it |
68//! |---|---|
69//! | [`prelude`] — the bridge marker, its blanket impl and the crossing function | all three |
70//! | [`family`] — the reference family and the two `From`s | all three |
71//! | [`identity_owner`] — the clone behind a type parameter | the rungs that BEAR an id |
72//!
73//! The last row is the split, and it is the tier's definition rather than a convenience. A fragment
74//! has no identity seat to serve, so it never reads an id out of a remote — and emitting the helper
75//! anyway would put a `warning: function \`__ingraph_owned\` is never used` in the declaring crate,
76//! MEASURED by compiling an unused item inside an anonymous const and reading `dead_code` back.
77
78use quote::{format_ident, quote, quote_spanned};
79
80use crate::{
81  construct::{Cross, Seat, Supplied},
82  method::{Family, Member},
83  model::{Field, Projection, RecordModel},
84};
85
86/// The BRIDGE — the marker every manifest read crosses, so a missing conversion is named.
87///
88/// A bare `Into` would work and would say the wrong thing: rustc would report
89/// `the trait bound \`u16: Into<u32>\` is not satisfied` at a body the author cannot edit, naming a
90/// std trait rather than the rule that was broken. Routed through a marker carrying
91/// `on_unimplemented`, with `do_not_recommend` on the blanket impl so the report stops at the
92/// marker, one sentence reaches the author — and the CALL is spanned at the manifest field, so the
93/// caret lands on the line they would fix.
94///
95/// It is the union seat's shape, and deliberately: that pattern is this tree's answer to *a
96/// generated obligation should refuse in the framework's own words*.
97const BRIDGE: &str = "__IngraphRemoteBridge";
98
99/// The free function every read is written through — [`BRIDGE`] with both parameters inferred.
100///
101/// A function rather than the trait method spelled at each site, because the two positions infer
102/// from opposite ends: a reader's target is its return type, and a constructor argument's is the
103/// remote's own signature. One call shape serves both.
104const CROSS: &str = "__ingraph_cross";
105
106/// The free function an IDENTITY read is owned through — a generic `clone` behind a type parameter.
107///
108/// The rewrite's identity seat hands back a BORROW, so a read that owns the value has to clone it,
109/// and a macro cannot know whether the id is `Copy`. Written inline — `Clone::clone(remote.id())`,
110/// fully qualified or not — that is `clippy::clone_on_copy` in the consuming crate for every `Copy`
111/// id, at a span the author cannot edit. Behind a type parameter it cannot be: inside the function
112/// `T` is not known to be `Copy`, and at the call site there is no `clone` to lint.
113///
114/// It is the same answer [`CROSS`] is, one obligation over — a generated read reaches its value
115/// through a function this expansion owns, so the lint surface of the emission is this module's
116/// rather than every declaring crate's.
117const OWNED: &str = "__ingraph_owned";
118
119/// The ident every manifest read is spelled through, for the emissions that write one.
120///
121/// A function rather than a `const` another module reads, so the NAME lives at [`CROSS`] and every
122/// caller asks for it rather than re-spelling it.
123pub(crate) fn cross() -> syn::Ident {
124  format_ident!("{CROSS}")
125}
126
127/// ONE value a raise supplies, as the SADDLE sees it before the protocol does.
128///
129/// # The shape is what makes the saddle a free function rather than a method
130///
131/// Two declarations raise a wrapped value now — a `record` out of its stored row, and a field
132/// fragment out of the columns it spans — and their models share nothing: a
133/// [`Field`](crate::model::Field) carries an identity, a condition and a per-database column, and a
134/// fragment's field carries none of the three. What the PROTOCOL needs is smaller than either, and
135/// this is exactly that: the four facts [`crossing`] and [`seat`] read, gathered by whichever model
136/// has them.
137///
138/// So the saddle below is written once over these, and the two callers differ only in the walk that
139/// fills them. That is the lowering [ingraph#316]'s builder-suite ratification deferred to the
140/// fields mount: while one declaration raised, a method on its model was the same thing; with two,
141/// a method on one of them is a saddle the other has to reach through a type it is not.
142///
143/// [ingraph#316]: https://github.com/findit-studio/ingraph/issues/316
144pub(crate) struct Ingredient<'a> {
145  /// The MANIFEST FIELD's own name — spent on the seat's default method name, and on the SPAN every
146  /// obligation the crossing creates is reported at.
147  pub(crate) source: &'a syn::Ident,
148  /// The type the manifest RESTATED, which is what `into` pins the crossing's target to.
149  pub(crate) ty: &'a syn::Type,
150  /// Whether the column has an EMPTY STATE — `#[ingraph(optional)]`, read as the options family's
151  /// own split rather than off the spelled type, per the standing rule that a macro holds tokens.
152  pub(crate) optional: bool,
153  /// The `builder(…)` words this field wrote, or the default law where it wrote none.
154  pub(crate) build: &'a crate::construct::Build,
155  /// The `#[cfg(…)]` this value rides, or empty where it rides none.
156  pub(crate) gate: proc_macro2::TokenStream,
157  /// The value itself, read out of whatever the raise is raising from.
158  pub(crate) value: proc_macro2::TokenStream,
159}
160
161/// BUILD a wrapper from one value per manifest field, through the remote's own CONSTRUCTION
162/// PROTOCOL.
163///
164/// The ORDER the protocol is called in is the DECLARATION's — the one order an author can see, and
165/// therefore the one order a positional argument list may be gathered in — so `ingredients` arrives
166/// in declared order and this walk does not sort it.
167///
168/// A field carrying `builder(skip)` is left out: the word says the column is not handed back at all,
169/// and what fills it is whatever the remote's own constructor puts there.
170///
171/// # This is the SADDLE, and [`crate::construct`] is the protocol
172///
173/// What lives here is the MANIFEST half: how a column's value crosses into the type the remote's own
174/// signature spells, and which seat it takes when the declaration named none. What the protocol IS —
175/// the entry, the finish, the links, the injections and the two shapes they can be written in — is
176/// [`Construction::call`](crate::construct::Construction::call)'s, so both saddles spend one copy of
177/// it.
178///
179/// A remote that keeps no describable protocol at all is still not stuck: the whole-body escape
180/// replaces this expression with the author's own function.
181pub(crate) fn build(
182  remote: &syn::Path,
183  construction: &crate::construct::Construction,
184  ingredients: &[Ingredient<'_>],
185) -> proc_macro2::TokenStream {
186  let supplied: Vec<Supplied> = ingredients
187    .iter()
188    .filter(|one| !one.build.skip)
189    .map(|one| Supplied {
190      fill: seat(one).filled(one.source),
191      // A CALL ARGUMENT is a stable attribute position, so a conditional required field simply
192      // leaves the argument list — and the remote's own entry is the arity check, exactly as it is
193      // for a manifest that never wrote a condition. A LINK is not one, which is why a gated link
194      // unrolls the protocol into statements; see [`Construction::call`].
195      gate: one.gate.clone(),
196      value: crossing(construction, one),
197    })
198    .collect();
199  let built = construction.call(remote, &supplied);
200  quote!(Self(#built))
201}
202
203/// WHICH SEAT a manifest column fills — the word it wrote, or the default law.
204///
205/// The DEFAULT is the OPTIONS FAMILY's own split, read off a word this grammar already has:
206/// `#[ingraph(optional)]` says a column has an empty state, which is exactly what an options type's
207/// optional seat is, so it reaches a `with_…` link and every other column is a positional argument.
208/// Nothing was invented to spell it, and `builder(arg)` / `builder(with)` are how a declaration
209/// overrides it for a remote whose split falls elsewhere.
210fn seat(ingredient: &Ingredient<'_>) -> Seat {
211  ingredient.build.seat.clone().unwrap_or({
212    if ingredient.optional {
213      Seat::With(None)
214    } else {
215      Seat::Arg
216    }
217  })
218}
219
220/// ONE column's value, crossed into whatever the remote's own signature spells.
221///
222/// Four answers, and the precedence between them is the ordinary one — the field's own word beats
223/// the declaration's blanket, and the blanket beats the default:
224///
225/// | written | emitted | why |
226/// |---|---|---|
227/// | `map = "f"` | `f` | the conversion the bridge cannot reach |
228/// | `into`, or a blanket claiming the type | `cross::<Ty, _>` | the seat is `impl Into<…>`, so the target is PINNED |
229/// | nothing | `cross` | the bridge, with its target read off the seat |
230///
231/// `option` is the fourth answer and it composes with the other three rather than replacing one: it
232/// says the seat takes the `Option` WHOLE, so whichever crosser was chosen is applied INSIDE it —
233/// `Option::map(value, crosser)` — which is the conversion std does not lift and an author would
234/// otherwise write by hand. It does not compose with `into`, whose pinned target would be the option
235/// rather than its item, and the grammar refuses the pair by name.
236///
237/// Spanned at the MANIFEST FIELD throughout, so every obligation the crossing creates — the bridge's
238/// named `E0277`, a `map` function that does not exist, an item type that does not convert — reports
239/// on the line an author would edit.
240fn crossing(
241  construction: &crate::construct::Construction,
242  ingredient: &Ingredient<'_>,
243) -> proc_macro2::TokenStream {
244  let cross = cross();
245  let at = ingredient.source.span();
246  let ty = ingredient.ty;
247  let value = &ingredient.value;
248  let crosser = match &ingredient.build.cross {
249    Some(Cross::Map(path)) => quote_spanned!(at=> #path),
250    Some(Cross::Into) => quote_spanned!(at=> #cross::<#ty, _>),
251    None if construction.blankets(ty) => quote_spanned!(at=> #cross::<#ty, _>),
252    None => quote_spanned!(at=> #cross),
253  };
254  if ingredient.build.option {
255    return quote_spanned!(at=> ::core::option::Option::map(#value, #crosser));
256  }
257  quote_spanned!(at=> #crosser(#value))
258}
259
260/// The rewrite's PRELUDE — the bridge marker, its blanket impl and the crossing function, declared
261/// once inside the expansion's own const.
262///
263/// `subject` is the DECLARATION the manifest belongs to and is spent on the two diagnostic strings
264/// alone: the sentence names the type whose manifest made the claim, which is what tells an author
265/// which declaration to go and edit. `remote` is spent on the note, and on nothing else — the
266/// bridge is generic in both directions, so no wrapped type appears in the emitted items.
267///
268/// A free function over those two rather than a method on one model, because THREE declarations
269/// mint this: `entity` and `record` through [`RecordModel::remote_prelude`], and the field-fragment
270/// tier through [`crate::fields::FieldsModel`]. One core, so the sentence a missing conversion is
271/// reported with cannot come to differ between the rungs that share the device.
272pub(crate) fn prelude(subject: &syn::Ident, remote: &syn::Path) -> proc_macro2::TokenStream {
273  let bridge = format_ident!("{BRIDGE}");
274  let cross = cross();
275  let message = format!(
276    "`{{Self}}` does not cross into `{{__IngraphTo}}`, which is what `{subject}`'s manifest says \
277     this field holds"
278  );
279  let note = format!(
280    "a field of `{subject}` is read through `{}`'s own accessor and crossed by `Into` — so the \
281     accessor's return type must convert into the type the manifest gives the field. Restate the \
282     field at the type the accessor really hands back, or give the two types a conversion",
283    path_text(remote),
284  );
285  quote! {
286    #[diagnostic::on_unimplemented(
287      message = #message,
288      label = "the remote's accessor hands back a type this field cannot be built from",
289      note = #note,
290    )]
291    trait #bridge<__IngraphTo> {
292      fn #cross(self) -> __IngraphTo;
293    }
294
295    // Without this the report descends through the blanket impl and names `Into`, which is true
296    // and is not the sentence this framework wants to say.
297    #[diagnostic::do_not_recommend]
298    impl<__IngraphTo, __IngraphFrom> #bridge<__IngraphTo> for __IngraphFrom
299    where
300      __IngraphFrom: ::core::convert::Into<__IngraphTo>,
301    {
302      #[inline]
303      fn #cross(self) -> __IngraphTo {
304        ::core::convert::Into::into(self)
305      }
306    }
307
308    #[inline]
309    fn #cross<__IngraphTo, __IngraphFrom: #bridge<__IngraphTo>>(
310      __ingraph_value: __IngraphFrom,
311    ) -> __IngraphTo {
312      #bridge::#cross(__ingraph_value)
313    }
314  }
315}
316
317/// [`OWNED`] — the clone behind a type parameter, emitted BESIDE the prelude by the rungs that bear
318/// an identity.
319///
320/// Separate from [`prelude`] because what it serves is the identity seat, and a declaration without
321/// one never calls it. An unused item inside an anonymous const is `dead_code` in the DECLARING
322/// crate — measured, by compiling exactly this shape with no caller — so a tier that bears no id
323/// emits no such function rather than an `allow` over one.
324pub(crate) fn identity_owner() -> proc_macro2::TokenStream {
325  let owned = format_ident!("{OWNED}");
326  quote! {
327    #[inline]
328    fn #owned<__IngraphId: ::core::clone::Clone>(__ingraph_value: &__IngraphId) -> __IngraphId {
329      ::core::clone::Clone::clone(__ingraph_value)
330    }
331  }
332}
333
334/// The wrapper's REFERENCE FAMILY and its two conversions — the whole of what makes a wrapper
335/// usable where the remote was.
336///
337/// Six borrows and two moves, and every one of them is `self.0`. The mutable halves are here for
338/// the reason the shared ones are: a transparent wrapper that could only be read would make every
339/// mutating method of the remote unreachable, and `DerefMut` beside `Deref` is what keeps method
340/// inheritance whole rather than half.
341///
342/// `From` in both directions is the trivial wrap and unwrap. It is what a caller crosses at an
343/// API boundary — and it is what the round-trip pin asserts is an identity in both directions.
344///
345/// Free over `(subject, remote)` for [`prelude`]'s reason: the family is the same eight impls on
346/// whichever rung wraps, a wrapper being a 1-tuple whatever faces it goes on to wear.
347pub(crate) fn family(subject: &syn::Ident, remote: &syn::Path) -> proc_macro2::TokenStream {
348  quote! {
349    #[automatically_derived]
350    impl ::core::convert::AsRef<#remote> for #subject {
351      #[inline]
352      fn as_ref(&self) -> &#remote {
353        &self.0
354      }
355    }
356
357    #[automatically_derived]
358    impl ::core::convert::AsMut<#remote> for #subject {
359      #[inline]
360      fn as_mut(&mut self) -> &mut #remote {
361        &mut self.0
362      }
363    }
364
365    #[automatically_derived]
366    impl ::core::ops::Deref for #subject {
367      type Target = #remote;
368
369      #[inline]
370      fn deref(&self) -> &#remote {
371        &self.0
372      }
373    }
374
375    #[automatically_derived]
376    impl ::core::ops::DerefMut for #subject {
377      #[inline]
378      fn deref_mut(&mut self) -> &mut #remote {
379        &mut self.0
380      }
381    }
382
383    #[automatically_derived]
384    impl ::core::borrow::Borrow<#remote> for #subject {
385      #[inline]
386      fn borrow(&self) -> &#remote {
387        &self.0
388      }
389    }
390
391    #[automatically_derived]
392    impl ::core::borrow::BorrowMut<#remote> for #subject {
393      #[inline]
394      fn borrow_mut(&mut self) -> &mut #remote {
395        &mut self.0
396      }
397    }
398
399    #[automatically_derived]
400    impl ::core::convert::From<#remote> for #subject {
401      #[inline]
402      fn from(remote: #remote) -> Self {
403        Self(remote)
404      }
405    }
406
407    #[automatically_derived]
408    impl ::core::convert::From<#subject> for #remote {
409      #[inline]
410      fn from(wrapper: #subject) -> Self {
411        wrapper.0
412      }
413    }
414  }
415}
416
417impl RecordModel {
418  /// The rewrite's PRELUDE, on a rung that BEARS an identity — [`prelude`], and the identity owner
419  /// beside it.
420  ///
421  /// Empty for an ordinary declaration, which is what makes the mode free: a model with no remote
422  /// emits not one token of this module.
423  pub(crate) fn remote_prelude(&self) -> proc_macro2::TokenStream {
424    let Some(remote) = &self.remote else {
425      return proc_macro2::TokenStream::new();
426    };
427    let bridge = prelude(&self.record, remote);
428    let owner = identity_owner();
429    quote! {
430      #bridge
431      #owner
432    }
433  }
434
435  /// The wrapper's REFERENCE FAMILY — [`family`], over this record's own name.
436  pub(crate) fn remote_family(&self) -> proc_macro2::TokenStream {
437    self
438      .remote
439      .as_ref()
440      .map_or_else(proc_macro2::TokenStream::new, |remote| {
441        family(&self.record, remote)
442      })
443  }
444
445  /// The wrapper's own inherent impl: ONE reader per manifest field, and no mutator.
446  ///
447  /// Three differences from the ordinary family, each forced by what a wrapper is:
448  ///
449  /// * **no mutators.** A remote's fields are its own; nothing here can assign into one, and a
450  ///   `with_…` that rebuilt the whole value would be a constructor wearing a setter's name.
451  /// * **no `const`.** The body calls a foreign accessor, and a foreign accessor is not this
452  ///   emission's to declare `const`.
453  /// * **by value for data, by reference for identity** — see the module note's last table.
454  ///
455  /// The field's own doc comments ride the reader. They were written about a field the rewrite
456  /// deletes, and the reader is where that field's meaning is still answerable.
457  pub(crate) fn remote_methods(&self) -> proc_macro2::TokenStream {
458    let record = &self.record;
459    let vis = &self.vis;
460    let cross = cross();
461    let families = self.fields.iter().map(|field| {
462      let column = &field.column;
463      let name = &column.source;
464      let ty = &column.ty;
465      let docs = &field.docs;
466      let at = name.span();
467      let subject = format!("`{name}` field of this [`{record}`]");
468      let Family { value, borrow, .. } = wrapped_family(field);
469      // The CONDITION, and the one artifact the field's DECORATION stands in on. A manifest field is
470      // deleted by the rewrite, so the reader is where its `#[cfg_attr]` lands for the same reason
471      // its doc comments do — that is the artifact a reader still asks the field's question at.
472      let gate = field.condition.gate();
473      let decorations = field.condition.decorations();
474      // The identity seat: the remote's accessor is taken to BORROW, so the reader is the borrow and
475      // a `copy` field's by-value reader is the dereference beside it.
476      let borrow = borrow.map(|borrow| {
477        let doc = crate::emit::leading(&format!("The {subject}, by reference."));
478        let read = quote_spanned!(at=> self.0.#name());
479        quote! {
480          #gate
481          #(#docs)*
482          #(#decorations)*
483          #[doc = #doc]
484          #[inline]
485          #vis fn #borrow(&self) -> &#ty {
486            #read
487          }
488        }
489      });
490      let value = value.map(|value| {
491        let doc = crate::emit::leading(&format!("The {subject}."));
492        let read = if field.identity {
493          quote_spanned!(at=> *self.0.#name())
494        } else {
495          quote_spanned!(at=> #cross(self.0.#name()))
496        };
497        quote! {
498          #gate
499          #(#docs)*
500          #(#decorations)*
501          #[doc = #doc]
502          #[inline]
503          #vis fn #value(&self) -> #ty {
504            #read
505          }
506        }
507      });
508      quote! {
509        #value
510        #borrow
511      }
512    });
513    quote! {
514      impl #record {
515        #(#families)*
516      }
517    }
518  }
519
520  /// ONE manifest column's value, OWNED, read off a binding that holds the wrapper.
521  ///
522  /// The seam every emission outside this module reaches the rewrite through — the key conversions,
523  /// the row's write leg — so there is exactly one place that decides what reading a wrapped column
524  /// means.
525  pub(crate) fn remote_read(
526    &self,
527    binding: &syn::Ident,
528    source: &syn::Ident,
529  ) -> proc_macro2::TokenStream {
530    let at = source.span();
531    if self.identity_bearing(source) {
532      // Through [`OWNED`] rather than `Clone::clone` spelled here: the accessor hands back a BORROW
533      // and the read owns it, and a clone written at this site is `clone_on_copy` in the consuming
534      // crate for every `Copy` id — at a span the author cannot edit. Behind the function's own type
535      // parameter there is no `Copy` for the lint to see.
536      let owned = format_ident!("{OWNED}");
537      quote_spanned!(at=> #owned(#binding.0.#source()))
538    } else {
539      let cross = cross();
540      quote_spanned!(at=> #cross(#binding.0.#source()))
541    }
542  }
543
544  /// The wrapper's own `id_ref` body — the borrowed identity seat, read straight off the remote.
545  pub(crate) fn remote_id_ref(&self) -> proc_macro2::TokenStream {
546    let source = &self.key.id.source;
547    quote_spanned!(source.span()=> self.0.#source())
548  }
549
550  /// BUILD a wrapper from one value per manifest field — this rung's WALK over the shared saddle.
551  ///
552  /// `values` is keyed by the field's own name, in whatever order the caller gathered them; what
553  /// this hands the saddle is the DECLARATION's order, which is the one order an author can see and
554  /// therefore the one order a positional argument list may be gathered in. A field the caller
555  /// supplied no value for is skipped — the caller has already refused a row that cannot rebuild the
556  /// record — so a short argument list is `E0061` naming the arity.
557  ///
558  /// Everything below the gathering is [`build`]'s: the crossing, the seat's default law, and the
559  /// call the protocol writes. What is left here is the part that is a RECORD's — that a value comes
560  /// from a stored row, that the condition seat is a field's `cfg`, and that the empty state is the
561  /// `optional` projection — which is exactly the part a fragment answers differently.
562  pub(crate) fn remote_build(
563    &self,
564    values: &[(syn::Ident, proc_macro2::TokenStream)],
565  ) -> proc_macro2::TokenStream {
566    let remote = self.remote.as_ref().expect("a rewrite's own path");
567    let of = |field: &Field| {
568      values
569        .iter()
570        .find(|(name, _)| name == &field.column.source)
571        .map(|(_, value)| value)
572    };
573    let ingredients: Vec<Ingredient<'_>> = self
574      .fields
575      .iter()
576      .filter_map(|field| {
577        Some(Ingredient {
578          source: &field.column.source,
579          ty: &field.column.ty,
580          optional: matches!(field.column.project, Projection::Optional),
581          build: &field.build,
582          gate: field.condition.gate(),
583          value: of(field)?.clone(),
584        })
585      })
586      .collect();
587    build(remote, &self.construction, &ingredients)
588  }
589
590  /// Whether a field of this declaration BEARS IDENTITY — the id, or a step of the lineage path.
591  ///
592  /// Asked of the field list rather than of the key, because the key's columns carry their scoped
593  /// names and this question is about the record's own.
594  fn identity_bearing(&self, source: &syn::Ident) -> bool {
595    self
596      .fields
597      .iter()
598      .any(|field| &field.column.source == source && field.identity)
599  }
600}
601
602/// A path as a reader would write it — for a message naming the remote.
603fn path_text(path: &syn::Path) -> String {
604  quote!(#path)
605    .to_string()
606    .replace(" :: ", "::")
607    .replace(" <", "<")
608    .replace("< ", "<")
609    .replace(" >", ">")
610}
611
612/// One manifest field's METHOD FAMILY — the names its reader occupies, and nothing else.
613///
614/// Shared with the emission's own name enumeration, exactly as `Column::family` is: a check over
615/// these names is a check over the names really emitted rather than over a second reading of the
616/// rule.
617pub(crate) fn wrapped_family(field: &Field) -> Family {
618  let name = &field.column.source;
619  Family {
620    // A data column reaches its value by crossing, and there is no borrow to hand out. An identity
621    // column takes the by-value reader only where `copy` already asked for one.
622    value: (!field.identity || field.column.project.copies()).then(|| Member::Value.name(name)),
623    borrow: field.identity.then(|| Member::Borrow.name(name)),
624    slice: None,
625    set: None,
626    with: None,
627  }
628}
629
630#[cfg(test)]
631mod tests;