Skip to main content

ingraph_codegen/unit/
wire.rs

1//! The two INPUT FACES a unit's types wear — `InputType` over the filter's struct and over the
2//! order-by's enum — written once for every front end that emits one.
3//!
4//! # Why the faces are HAND-WRITTEN at all
5//!
6//! `#[derive(InputObject)]` and `#[derive(OneofObject)]` are attached to a DECLARATION, and both of
7//! these types are emitted: their fields carry projections through the marker layer, their names come
8//! from a naming tower, and their `__`-pinned Rust idents are not the words a client reads. So what
9//! is written here is those derives' own output, at the one place a derive could not be attached.
10//!
11//! # And why it is ONE emitter for two front ends
12//!
13//! The STRUCT halves already are — [`super::filter`] and [`super::order_by`] serve a record, an
14//! interface and a standalone `#[derive(ingraph::Filter)]` alike. The faces were a record's alone
15//! until B-27 asked an interface to publish a root field, which is what a filter and an order-by are
16//! spent by. A second copy of forty lines of registry construction is where the two would come to
17//! disagree about a byte of somebody's SDL.
18//!
19//! What a caller supplies is exactly what it knows: the type's Rust name, the name a CLIENT reads,
20//! and one row per column already resolved through whichever naming layers that front end has.
21//!
22//! # The one flag that separates the two
23//!
24//! `oneof`. A predicate narrows by every field a client writes; an order term names exactly ONE
25//! column — and `oneof: true` is what makes *exactly one* the VALIDATOR's rule rather than a
26//! resolver's, refused before anything runs, through a literal and through a variable alike.
27
28use quote::quote;
29
30/// What both faces need before they read a single column.
31pub struct InputFace<'a> {
32  /// Where `ingraph` lives — every framework path an emission writes goes through the shelf.
33  pub krate: &'a syn::Path,
34  /// The emitted type's RUST name.
35  pub name: &'a syn::Ident,
36  /// The name a CLIENT reads, already resolved through the caller's own naming tower.
37  pub sdl: &'a str,
38}
39
40impl InputFace<'_> {
41  /// The async-graphql root, through the shelf.
42  fn ag(&self) -> proc_macro2::TokenStream {
43    crate::emit::framework(self.krate, &[], "async_graphql")
44  }
45
46  /// One `MetaInputValue` — the registry entry of ONE input field, with `description` written `None`
47  /// because that is where the rule lands: descriptions come from `attrs(desc = …)` and nowhere
48  /// else.
49  fn meta_input_value(
50    &self,
51    name: &str,
52    ty: &proc_macro2::TokenStream,
53  ) -> proc_macro2::TokenStream {
54    let ag = self.ag();
55    quote! {
56      #ag::registry::MetaInputValue {
57        name: ::std::string::String::from(#name),
58        description: ::core::option::Option::None,
59        ty: <#ty as #ag::InputType>::create_type_info(__ingraph_registry),
60        deprecation: #ag::registry::Deprecation::NoDeprecated,
61        default_value: ::core::option::Option::None,
62        visible: ::core::option::Option::None,
63        inaccessible: false,
64        tags: ::std::vec::Vec::new(),
65        is_secret: false,
66        directive_invocations: ::std::vec::Vec::new(),
67      }
68    }
69  }
70
71  /// The registry entries of a face's fields, as ONE expression building the map — written where
72  /// `__ingraph_registry` is in scope, which every entry names.
73  fn fields_block(
74    &self,
75    entries: impl Iterator<Item = proc_macro2::TokenStream>,
76  ) -> proc_macro2::TokenStream {
77    let ag = self.ag();
78    let entries: Vec<proc_macro2::TokenStream> = entries.collect();
79    quote! {
80      {
81        let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
82        #(#entries)*
83        __ingraph_fields
84      }
85    }
86  }
87
88  /// The two `InputType` items every hand-written input face writes the same way: its GraphQL name,
89  /// and the registry entry that declares its fields.
90  ///
91  /// One helper rather than two copies, because the FILTER's entry and the ORDER-BY's differ in
92  /// exactly one flag — `oneof` — and a second copy is where that flag would come to differ in
93  /// something else.
94  ///
95  /// `input_fields` is an EXPRESSION rather than the entries, because the two callers reach the map
96  /// differently: an order-by builds it here, and a filter reads it back off its own
97  /// `ingraph::NullableFace` row so the bare face and its nullable twin publish one list. Both
98  /// spellings are evaluated where `__ingraph_registry` is bound.
99  fn type_info(
100    &self,
101    input_fields: &proc_macro2::TokenStream,
102    oneof: bool,
103  ) -> proc_macro2::TokenStream {
104    let ag = self.ag();
105    let sdl = self.sdl;
106    quote! {
107      #[inline]
108      fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
109        ::std::borrow::Cow::Borrowed(#sdl)
110      }
111
112      fn create_type_info(
113        __ingraph_registry: &mut #ag::registry::Registry,
114      ) -> ::std::string::String {
115        __ingraph_registry.create_input_type::<Self, _>(
116          #ag::registry::MetaTypeId::InputObject,
117          |__ingraph_registry| #ag::registry::MetaType::InputObject {
118            name: ::std::string::String::from(#sdl),
119            description: ::core::option::Option::None,
120            input_fields: #input_fields,
121            visible: ::core::option::Option::None,
122            inaccessible: false,
123            tags: ::std::vec::Vec::new(),
124            rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
125            oneof: #oneof,
126            directive_invocations: ::std::vec::Vec::new(),
127          },
128        )
129      }
130    }
131  }
132}
133
134/// One column, as the FILTER's face reads it.
135pub struct FilterField {
136  /// The name a CLIENT writes this column under — the INPUT position's, which the order-by term
137  /// shares so a document never spells one column two ways.
138  pub field: String,
139  /// The struct MEMBER the parsed value lands in.
140  pub member: syn::Ident,
141  /// The filter this column is guarded by, already projected through the marker layer.
142  pub filter: proc_macro2::TokenStream,
143  /// The CONDITION the column is declared under — see
144  /// [`Condition`](crate::model::Condition). Empty for a column that wrote none, and for every unit
145  /// whose front end has no condition seat.
146  pub gate: proc_macro2::TokenStream,
147}
148
149/// One column, as the ORDER-BY's face reads it.
150pub struct OrderField {
151  /// The name a CLIENT writes this column under — the FILTER's own name for it.
152  pub field: String,
153  /// The enum VARIANT that term parses into.
154  pub variant: syn::Ident,
155  /// Whether the SCHEMA names this term at all — false where `graphql(skip)` withheld the column.
156  ///
157  /// The Rust enum has a variant either way: the order-by type generates FULL, so a Rust caller
158  /// orders by every stored column. What this decides is the FACE — see
159  /// [`order_by_face`], where a withheld term is registered nowhere and parsed by nothing.
160  pub published: bool,
161  /// The CONDITION the column is declared under — see
162  /// [`Condition`](crate::model::Condition). Empty for a column that wrote none, and for every unit
163  /// whose front end has no condition seat.
164  pub gate: proc_macro2::TokenStream,
165}
166
167/// One REVERSE relation position, as the FILTER's face reads it.
168///
169/// Its three legs differ from a column's by ONE fact and it is the BOX: the struct member is
170/// `Option<Box<RelatedFilter<…>>>` because a position naming this record's own kind would make the
171/// struct contain itself, and `Box` has no `InputType` row — so the schema entry, the parse and the
172/// render all name the UNBOXED type and the box is put on and taken off here. That is the same
173/// division the `__` prefix pin states one layer up: a Rust fact does not reach a client.
174pub struct RelationPosition {
175  /// The name a CLIENT writes this position under.
176  pub field: String,
177  /// The struct MEMBER the parsed value lands in.
178  pub member: syn::Ident,
179  /// The UNBOXED filter this position holds — `RelatedFilter<…>` over the far side's own filter.
180  pub held: proc_macro2::TokenStream,
181}
182
183/// The FILTER as an ordinary input object: one NULLABLE field per column, each carrying that
184/// column's own filter, and any number of them supplied.
185///
186/// # `Option<F>` at the field and NOT `Nullable<F>`
187///
188/// Two different absences, and the type says which. `Option` at this position is *the client wrote
189/// no predicate for this column* — an unwritten field narrows nothing — where `Nullable<F>` is the
190/// column's own NULL state and lives inside `F` for a nullable column, carrying `isNull`. The
191/// struct's member is `Option<F>` for exactly that reason and this face parses what the member
192/// holds.
193#[must_use]
194pub fn filter_face(
195  face: &InputFace<'_>,
196  fields: &[FilterField],
197  positions: &[RelationPosition],
198) -> proc_macro2::TokenStream {
199  let (ag, name) = (face.ag(), face.name);
200  let entries = fields.iter().map(|row| {
201    let (field, filter, gate) = (&row.field, &row.filter, &row.gate);
202    let value = face.meta_input_value(field, &quote!(::core::option::Option<#filter>));
203    // The CONDITION, on a STATEMENT and on a struct-expression field — both attribute positions — so
204    // a column the build removed is registered by nobody, parsed by nothing and rendered nowhere.
205    // The SCHEMA follows the build, which is the whole of what `family-wide` means here.
206    quote!(#gate __ingraph_fields.insert(::std::string::String::from(#field), #value);)
207  });
208  // Every field is read, present or absent: `Option<F>::parse(None)` is `Ok(None)`, so a document
209  // that writes two columns of twenty is twenty reads and eighteen empty answers rather than a
210  // walk over whichever keys the object happened to carry. That is what makes an unknown key
211  // ignored and a malformed known one refused, which is async-graphql's own posture for an input
212  // object.
213  let parses = fields.iter().map(|row| {
214    let (field, member, filter, gate) = (&row.field, &row.member, &row.filter, &row.gate);
215    quote! {
216      #gate
217      #member: <::core::option::Option<#filter> as #ag::InputType>::parse(
218        // `.cloned()` as a METHOD, where every path this emission writes is absolute: the two
219        // `Option<&T>` / `Option<&mut T>` inherent impls make the qualified spelling `E0034`, and
220        // a method call is resolved by the receiver's type rather than by a name a declaring
221        // module could shadow. The same shape `map_err` below already takes.
222        #ag::indexmap::IndexMap::get(&__ingraph_object, #field).cloned(),
223      )
224      .map_err(#ag::InputValueError::propagate)?,
225    }
226  });
227  let renders = fields.iter().map(|row| {
228    let (field, member, gate) = (&row.field, &row.member, &row.gate);
229    quote! {
230      #gate
231      __ingraph_map.insert(
232        #ag::Name::new(#field),
233        #ag::InputType::to_value(&self.#member),
234      );
235    }
236  });
237  // The REVERSE relation positions, in the declaration's own order after every column.
238  let position_entries = positions.iter().map(|row| {
239    let (field, held) = (&row.field, &row.held);
240    let value = face.meta_input_value(field, &quote!(::core::option::Option<#held>));
241    quote!(__ingraph_fields.insert(::std::string::String::from(#field), #value);)
242  });
243  let position_parses = positions.iter().map(|row| {
244    let (field, member, held) = (&row.field, &row.member, &row.held);
245    quote! {
246      #member: ::core::option::Option::map(
247        <::core::option::Option<#held> as #ag::InputType>::parse(
248          #ag::indexmap::IndexMap::get(&__ingraph_object, #field).cloned(),
249        )
250        .map_err(#ag::InputValueError::propagate)?,
251        ::std::boxed::Box::new,
252      ),
253    }
254  });
255  // `Value::Null` for the absent case, which is exactly what `<Option<T> as InputType>::to_value`
256  // answers for a `None` — the column legs' own behaviour, written out because the box has to be
257  // stepped through to reach a value the library can render.
258  let position_renders = positions.iter().map(|row| {
259    let (field, member) = (&row.field, &row.member);
260    quote! {
261      __ingraph_map.insert(
262        #ag::Name::new(#field),
263        match &self.#member {
264          ::core::option::Option::Some(__ingraph_position) => {
265            #ag::InputType::to_value(&**__ingraph_position)
266          }
267          ::core::option::Option::None => #ag::Value::Null,
268        },
269      );
270    }
271  });
272  let nullable_face = crate::emit::framework(face.krate, &["graphql"], "NullableFace");
273  // The field list lives on the NULLABLE row and the bare face reads it back, so a nullable column
274  // of this filter publishes the same fields in the same order — one list rather than two kept in
275  // step by hand, which is the discipline `ingraph`'s own registrations already keep.
276  let fields = face.fields_block(entries.chain(position_entries));
277  let info = face.type_info(
278    &quote!(<Self as #nullable_face>::bare_fields(__ingraph_registry)),
279    false,
280  );
281  let sent = crate::emit::framework(face.krate, &["graphql", "filter"], "sent");
282  let sent_ty = crate::emit::framework(face.krate, &["graphql", "filter"], "Sent");
283  quote! {
284    #[automatically_derived]
285    impl #ag::InputType for #name {
286      type RawValueType = Self;
287
288      #info
289
290      /// # The SHORTHAND LAW at a COMPOSITE face, whose answer to two of its four readings is no
291      ///
292      /// Read through the framework's own `sent` so this face answers the law where every other
293      /// one does, and REFUSES two of the readings faithfully rather than by falling off an `if`.
294      ///
295      /// Rule ① wants the one slot a bare value is the `eq` of, and a composite has none: its
296      /// fields are COLUMNS, each with a filter of its own, so `42` names no operand here. A face
297      /// that guessed the first column would silently answer a different question than the one
298      /// asked — which is rule ③'s own posture, a reading refused because no reading is true.
299      ///
300      /// Rule ② is refused for the reason every bare face refuses it: the null test is a TYPE
301      /// here, and `Nullable<Self>` — reached through the row below — is what acts on it.
302      fn parse(
303        value: ::core::option::Option<#ag::Value>,
304      ) -> #ag::InputValueResult<Self> {
305        match #sent(value) {
306          #sent_ty::Longhand(__ingraph_object) => {
307            ::core::result::Result::Ok(Self { #(#parses)* #(#position_parses)* })
308          }
309          #sent_ty::Bare(__ingraph_sent) => {
310            ::core::result::Result::Err(#ag::InputValueError::expected_type(__ingraph_sent))
311          }
312          #sent_ty::Null => {
313            ::core::result::Result::Err(#ag::InputValueError::expected_type(#ag::Value::Null))
314          }
315          #sent_ty::Refused(__ingraph_sent) => {
316            ::core::result::Result::Err(#ag::InputValueError::expected_type(__ingraph_sent))
317          }
318        }
319      }
320
321      fn to_value(&self) -> #ag::Value {
322        #ag::Value::Object(<Self as #nullable_face>::bare_values(self))
323      }
324
325      #[inline]
326      fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
327        ::core::option::Option::Some(self)
328      }
329    }
330
331    #[automatically_derived]
332    impl #ag::InputObjectType for #name {}
333
334    #[automatically_derived]
335    impl #nullable_face for #name {
336      fn bare_fields(
337        __ingraph_registry: &mut #ag::registry::Registry,
338      ) -> #ag::indexmap::IndexMap<::std::string::String, #ag::registry::MetaInputValue> {
339        #fields
340      }
341
342      fn bare_values(&self) -> #ag::indexmap::IndexMap<#ag::Name, #ag::Value> {
343        let mut __ingraph_map = #ag::indexmap::IndexMap::new();
344        #(#renders)*
345        #(#position_renders)*
346        __ingraph_map
347      }
348    }
349  }
350}
351
352/// The ORDER-BY as a `@oneOf` input object: one nullable field per orderable column, exactly one of
353/// them supplied.
354///
355/// The filter's twin, one flag apart. The SHAPE was fixed when the type was declared — an enum of
356/// single-value tuple variants, which is what `OneofObject` takes — and what is written here is that
357/// derive's own output.
358#[must_use]
359pub fn order_by_face(face: &InputFace<'_>, terms: &[OrderField]) -> proc_macro2::TokenStream {
360  let (ag, name) = (face.ag(), face.name);
361  let direction = crate::emit::framework(face.krate, &["graphql"], "OrderDirection");
362  // THE TWO WALKS, and which of them each half of the trait takes. REGISTRATION and PARSE are the
363  // schema's, so they take the published terms alone: a withheld column has no field in the SDL and
364  // no name a request can spell, which is invisible AND unreachable rather than either one.
365  //
366  // `to_value` takes EVERY term, and it has to: the match is over the enum, which generates full, so
367  // a narrowed render would be non-exhaustive. It is also safe to leave total, and that is the
368  // ruling's own observation rather than a hope — the order-by is an INPUT-ONLY type. Its values
369  // arrive from a client and never leave for one, so rendering a variant a client could not have
370  // written publishes nothing; `to_value` exists for the round trip a variable or a default takes
371  // through async-graphql's own machinery, and a term nobody could send is a term that never
372  // reaches it.
373  let published = || terms.iter().filter(|term| term.published);
374  let entries = published().map(|term| {
375    let (field, gate) = (&term.field, &term.gate);
376    let value = face.meta_input_value(field, &quote!(::core::option::Option<#direction>));
377    quote!(#gate __ingraph_fields.insert(::std::string::String::from(#field), #value);)
378  });
379  // `swap_remove` rather than `remove`: the entry is taken and the object is dropped in the same
380  // breath, so the order it leaves behind is nobody's, and indexmap 2 deprecates the ambiguous
381  // spelling — a deprecation warning inside an expansion is one a consumer cannot edit away.
382  let parses = published().map(|term| {
383    let (field, variant, gate) = (&term.field, &term.variant, &term.gate);
384    quote! {
385      #gate
386      if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, #field)
387        && #ag::indexmap::IndexMap::len(&__ingraph_object) == 1
388      {
389        let __ingraph_direction = #ag::InputType::parse(
390          #ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, #field),
391        )
392        .map_err(#ag::InputValueError::propagate)?;
393        return ::core::result::Result::Ok(Self::#variant(__ingraph_direction));
394      }
395    }
396  });
397  let renders = terms.iter().map(|term| {
398    let (variant, field, gate) = (&term.variant, &term.field, &term.gate);
399    quote! {
400      #gate
401      Self::#variant(__ingraph_direction) => {
402        __ingraph_map.insert(
403          #ag::Name::new(#field),
404          #ag::InputType::to_value(__ingraph_direction),
405        );
406      }
407    }
408  });
409  let info = face.type_info(&face.fields_block(entries), true);
410  quote! {
411    #[automatically_derived]
412    impl #ag::InputType for #name {
413      type RawValueType = Self;
414
415      #info
416
417      fn parse(
418        value: ::core::option::Option<#ag::Value>,
419      ) -> #ag::InputValueResult<Self> {
420        if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) = value {
421          #(#parses)*
422          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
423            #ag::Value::Object(__ingraph_object),
424          ));
425        }
426        ::core::result::Result::Err(#ag::InputValueError::expected_type(
427          ::core::option::Option::unwrap_or_default(value),
428        ))
429      }
430
431      fn to_value(&self) -> #ag::Value {
432        let mut __ingraph_map = #ag::indexmap::IndexMap::new();
433        match self {
434          #(#renders)*
435        }
436        #ag::Value::Object(__ingraph_map)
437      }
438
439      #[inline]
440      fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
441        ::core::option::Option::Some(self)
442      }
443    }
444
445    #[automatically_derived]
446    impl #ag::InputObjectType for #name {}
447
448    #[automatically_derived]
449    impl #ag::OneofObjectType for #name {}
450  }
451}