Skip to main content

ingraph_codegen/
composed.rs

1//! THE COMPOSED MODE's model: what `#[derive(ingraph::Filter)]` emits when the declaration wears
2//! `#[ingraph(composed)]` — the wire face of a filter struct somebody wrote by hand, built out of
3//! the fields themselves.
4//!
5//! # The struct IS the vocabulary, and that is the whole of the mode
6//!
7//! The other two identities take a declaration and MINT something: the struct mode mints a filter
8//! over a row's columns, the element mode mints one over a single value. This one mints no type at
9//! all. The subject already IS the filter — its fields are the operator slots, in the order they are
10//! written — and what the derive adds is the face a client reaches it through.
11//!
12//! So the FIELD TABLE has exactly one author. A hand-written face carries the field list three times
13//! — once in the registration, once in the parse, once in the render — and keeping the three in step
14//! is a discipline rather than a fact. Here the three are one list walked three times, and the list
15//! is the `struct` body: a field cannot be registered and not parsed, or rendered under a name the
16//! registration never published, because there is nowhere for a second list to live.
17//!
18//! # TWO kinds of field, and the second one publishes NAMES THIS DECLARATION DOES NOT SPELL
19//!
20//! An operator SLOT is one name, one wire type, one key in the parsed object. A SPLICED component —
21//! `#[ingraph(flatten)]` — is a whole filter face whose own fields become this filter's, so the
22//! declaration's field list and the published table are no longer the same length. See
23//! [`FlattenFace`], which is where the four faces splice.
24//!
25//! # What it emits, and what it deliberately does not
26//!
27//! | item | what it says |
28//! |---|---|
29//! | `async_graphql::InputType` | the three faces — the registration, the parse and the render |
30//! | `async_graphql::InputObjectType` | that the registration above is an input OBJECT |
31//! | [`NullableFace`] | the two halves `Nullable<F>`'s single blanket assembles the twin from |
32//! | [`GraphqlFilter`] | emptiness, folded field by field |
33//!
34//! It emits **no constructor, no accessors and no inherent `is_empty`**. The struct is hand written:
35//! its `new`, its `with_*` family and whatever inherent reads it publishes are the author's, and a
36//! door that also emitted them would be `E0592` against the ones already there. `GraphqlFilter` is
37//! the one emptiness answer this door writes, and an inherent `is_empty` beside it still wins method
38//! resolution — which is the arrangement every filter kind in `ingraph` already has.
39//!
40//! **The LOWERING is untouched.** A composed filter reaches a dialect the way it always did, through
41//! whatever `ToDatabaseComparison` row its author wrote; this door is about the wire and says nothing
42//! about the storage side.
43//!
44//! # The SHAPE of each slot is resolved by the compiler
45//!
46//! Which of the four shapes a field is cannot be read off its tokens — `Option<Rate>` and
47//! `Option<ScalarFilter<i32>>` are one shape to a parser — so every emitted line goes through
48//! [`FilterSlot`]/[`SlotFace`], writes the kind as `_`, and lets inference pick the one row that
49//! applies. A field answering none of them is `E0277` carrying that trait's own sentence and naming
50//! the field's type; a field answering two is an ambiguity at the declaration rather than a silent
51//! choice. See `ingraph`'s `graphql::filter::slot` for the rows and for the emptiness law.
52//!
53//! [`NullableFace`]: https://docs.rs/ingraph/latest/ingraph/trait.NullableFace.html
54//! [`GraphqlFilter`]: https://docs.rs/ingraph/latest/ingraph/trait.GraphqlFilter.html
55//! [`FilterSlot`]: https://docs.rs/ingraph/latest/ingraph/trait.FilterSlot.html
56//! [`SlotFace`]: https://docs.rs/ingraph/latest/ingraph/trait.SlotFace.html
57//! [`FlattenFace`]: https://docs.rs/ingraph/latest/ingraph/trait.FlattenFace.html
58
59use quote::quote;
60
61use crate::name::RustSafeName;
62
63#[cfg(test)]
64mod tests;
65
66/// The client's name for a slot NO declaration renamed: the household fold — a raw prefix dropped, a
67/// trailing underscore eaten, the rest lowerCamel.
68///
69/// So `not_in` is `notIn`, `starts_with` is `startsWith`, and the two Rust spellings of the keyword
70/// slot — `r#in` and `in_` — both land on `in`. It is the SAME fold every other emitted wire member
71/// takes: [`crate::emit::wire`] owns it, and this is the door a front end asks it through, so that a
72/// composed slot and a record's column cannot come to disagree about what a Rust name looks like on
73/// the wire.
74///
75/// Public because the DUPLICATE refusal needs it. Two fields folding onto one wire name is a
76/// declaration this door cannot honour — the second registration would replace the first and the
77/// parse would read one key twice — and the only place that can be seen is where the tokens are, so
78/// the front end folds every member and compares.
79#[must_use]
80pub fn wire_name(member: &syn::Ident) -> String {
81  crate::emit::wire::wire_member(member)
82}
83
84/// WHICH KIND of field one member of a composed filter is.
85///
86/// The two are told apart by a word rather than by a shape, for the mode's own reason: a field
87/// holding a whole filter face is a legal nested SLOT and a legal splice, and which one a
88/// declaration means is not readable from the type.
89pub enum ComposedKind {
90  /// An operator SLOT, carrying what a client calls it — the fold above, or whatever `rename` moved
91  /// it to.
92  Slot(String),
93  /// A SPLICED component: its own fields become this filter's, so it publishes no name of its own
94  /// and there is nothing for `rename` to move.
95  Spliced,
96}
97
98/// ONE field of a composed filter: the member it is held in, its type, and which kind of field it is.
99///
100/// PLAIN, for [`StandaloneModel`](crate::standalone::StandaloneModel)'s reason — public fields, no
101/// constructor, no validation. What is checked is checked at the FRONT END, where the tokens an
102/// author wrote are still in hand and a refusal can point at one.
103pub struct ComposedField {
104  /// The struct field this is read from and written back into.
105  pub member: syn::Ident,
106  /// The field's own type, which is what the seam resolves the shape from.
107  pub ty: syn::Type,
108  /// A slot, or a splice.
109  pub kind: ComposedKind,
110  /// The CONDITION the member is declared under.
111  ///
112  /// Carried on the field rather than looked up, for [`crate::unit::FilterColumn`]'s reason: this
113  /// door is shared, and only some of the front ends that reach it have a condition seat at all. A
114  /// hand-written composed struct has none — its members are the author's own item, which rustc
115  /// strips before this expansion ever sees it — so [`Condition::always`] is that door's answer and
116  /// the emission below is byte-identical to the one before this seat existed.
117  ///
118  /// Where a front end DOES have one — the fragment tier, whose members it mints — the predicate has
119  /// to reach all four walks: the emptiness fold, the parse, the registration and the render. A
120  /// member present in three of them and absent from the fourth is an input object whose SDL and
121  /// whose reader disagree.
122  ///
123  /// [`Condition::always`]: crate::model::Condition::always
124  pub condition: crate::model::Condition,
125}
126
127/// A hand-written FILTER STRUCT, as the composed mode reads it.
128pub struct ComposedModel {
129  /// The struct the face is OF — and, being the filter itself, the type every emitted impl names.
130  pub subject: syn::Ident,
131  /// The `ingraph` root the expansion spells its shelf through.
132  pub krate: syn::Path,
133  /// The input object's name in the schema — the subject's own, or whatever
134  /// `filter(rename = "…")` moved it to.
135  pub sdl: RustSafeName,
136  /// Whether rule ① reaches this face — `composed(shorthand = …)`, and `true` when the declaration
137  /// said nothing.
138  pub shorthand: bool,
139  /// The fields, IN DECLARATION ORDER, which is the order the SDL prints them in: async-graphql
140  /// renders an input object's fields in the order the registry received them.
141  pub fields: Vec<ComposedField>,
142}
143
144impl ComposedModel {
145  /// The shelf path one framework item is spelled through.
146  fn framework(&self, module: &[&str], item: &str) -> proc_macro2::TokenStream {
147    crate::emit::framework(&self.krate, module, item)
148  }
149
150  /// The whole composed mode, emitted.
151  ///
152  /// The emptiness answer is OUTSIDE the binding gate and the three wire faces are inside it, which
153  /// is the split the slot seam is built along: *is anything set* is the same question on every
154  /// backend and a build with no binding still has lowerings that ask it.
155  pub fn emit(&self) -> proc_macro2::TokenStream {
156    let emptiness = self.emptiness();
157    let gate = self.framework(&["gate"], "if_async_graphql");
158    let face = self.input_type();
159    let object = self.input_object();
160    let nullable = self.nullable_face();
161    quote! {
162      #emptiness
163
164      const _: () = {
165        #gate! {
166          #face
167          #object
168          #nullable
169        }
170      };
171    }
172  }
173
174  /// The EMPTINESS answer, folded field by field.
175  ///
176  /// A SLOT asks its own row through `FilterSlot<_>`, so the fold-in a nested filter gets and the
177  /// plain `is_none` an operand gets are the seam's rulings rather than this emitter's — and a field
178  /// type that is not a slot shape at all is `E0277` here, at the declaration, carrying that trait's
179  /// own sentence.
180  ///
181  /// A SPLICED component asks `GraphqlFilter` directly, because it has no `Option` for a row to be
182  /// written over: its fields are this filter's fields and each of THOSE carries the absence. That is
183  /// the same fold-in one indirection shorter, and it is what a hand-written face writes for its own
184  /// flattened component.
185  ///
186  /// An empty struct never reaches this: the front end refuses one, because a filter with no field is
187  /// a predicate that can ask nothing and an input object with no field is not valid SDL.
188  fn emptiness(&self) -> proc_macro2::TokenStream {
189    let subject = &self.subject;
190    let contract = self.framework(&["graphql"], "GraphqlFilter");
191    let slot = self.framework(&["graphql"], "FilterSlot");
192    let folded = self.fields.iter().map(|field| {
193      let (member, ty) = (&field.member, &field.ty);
194      let asked = match field.kind {
195        ComposedKind::Slot(_) => quote!(<#ty as #slot<_>>::is_empty(&self.#member)),
196        ComposedKind::Spliced => quote!(<#ty as #contract>::is_empty(&self.#member)),
197      };
198      // A TERM of a `&&` chain is the one seat in this file an attribute cannot sit in, so the fork
199      // is moved one grain out. A member the build removed asks nothing, and *nothing asked* is
200      // `true` — the identity of the conjunction, which is what makes the absent arm the same
201      // sentence as having no such field at all.
202      field.condition.either(&asked, &quote!(true))
203    });
204    quote! {
205      #[automatically_derived]
206      impl #contract for #subject {
207        fn is_empty(&self) -> bool {
208          #(#folded)&&*
209        }
210      }
211    }
212  }
213
214  /// The THREE FACES: the registration, the parse and the render.
215  ///
216  /// # The SHORTHAND LAW reaches a composed face, unless the declaration declines it
217  ///
218  /// `parse` reads what arrived through the framework's own `sent`, so a client writes `"30000/1001"`
219  /// where this face means `{ eq: "30000/1001" }` exactly as it may at a framework column. The bare
220  /// value is put under the FIRST PUBLISHED name and the ordinary reads run over that object, so the
221  /// operand crosses through the same grammar the longhand takes rather than through a second
222  /// reading of it.
223  ///
224  /// That name is read off the face's own published TABLE rather than spelled here, so the shorthand
225  /// and the registration cannot come to name different slots — including when the first field is a
226  /// SPLICE, whose names this declaration does not write down.
227  ///
228  /// `composed(shorthand = false)` declines rule ① instead, and the refusal is the framework's own
229  /// sentence naming this filter and its operators. A filter whose vocabulary is a relation has no
230  /// slot a bare value obviously means — see `refuse_bare`, where the reason is written down.
231  ///
232  /// Rule ② is refused here and acted on by the nullable twin, which is nullability being a TYPE
233  /// said at the parse.
234  ///
235  /// # The SPLICES are read LAST, after every slot has been read off the borrow
236  ///
237  /// A spliced component's parser takes the HOST's whole object, so its read is the one that cannot
238  /// share the borrow the others hold. Ordering the struct literal that way is also what a
239  /// hand-written flattened face does, and it keeps the first refusal a client sees the first slot's
240  /// rather than the component's.
241  fn input_type(&self) -> proc_macro2::TokenStream {
242    let subject = &self.subject;
243    let ag = self.framework(&[], "async_graphql");
244    let nullable_face = self.framework(&["graphql"], "NullableFace");
245    let face = self.framework(&["graphql"], "SlotFace");
246    let flat = self.framework(&["graphql"], "FlattenFace");
247    let sent = self.framework(&["graphql", "filter"], "sent");
248    let sent_ty = self.framework(&["graphql", "filter"], "Sent");
249    let sdl = self.sdl.external();
250
251    // A STRUCT LITERAL's field is a legal attribute position, so the gate rides each read and the
252    // literal contracts with the struct it is building.
253    let slots = self.fields.iter().filter_map(|field| {
254      let (member, ty, gate) = (&field.member, &field.ty, field.condition.gate());
255      match &field.kind {
256        ComposedKind::Slot(wire) => {
257          Some(quote!(#gate #member: <#ty as #face<_>>::read::<Self>(&__ingraph_object, #wire)?))
258        }
259        ComposedKind::Spliced => None,
260      }
261    });
262    let splices = self.fields.iter().filter_map(|field| {
263      let (member, ty, gate) = (&field.member, &field.ty, field.condition.gate());
264      match &field.kind {
265        ComposedKind::Slot(_) => None,
266        ComposedKind::Spliced => {
267          Some(quote!(#gate #member: <#ty as #flat>::flat_read::<Self>(&__ingraph_object)?))
268        }
269      }
270    });
271
272    let reading = if self.shorthand {
273      let shorthand = self.framework(&["graphql", "filter"], "shorthand");
274      quote! {
275        #sent_ty::Longhand(__ingraph_object) => __ingraph_object,
276        // Rule ① — a bare value is this face's FIRST PUBLISHED field, put under that key so the
277        // reads below cross it through the same grammar the longhand takes.
278        #sent_ty::Bare(__ingraph_bare) => #shorthand::<Self>(__ingraph_bare),
279        // Rule ② is REFUSED here and acted on by the nullable twin: a `NOT NULL` column has no
280        // null test to set, which is nullability being a TYPE said at the parse.
281        #sent_ty::Null => {
282          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
283            #ag::Value::Null,
284          ));
285        }
286        #sent_ty::Refused(__ingraph_sent) => {
287          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
288            __ingraph_sent,
289          ));
290        }
291      }
292    } else {
293      let refuse_bare = self.framework(&["graphql", "filter"], "refuse_bare");
294      quote! {
295        #sent_ty::Longhand(__ingraph_object) => __ingraph_object,
296        // Rule ② is REFUSED here and acted on by the nullable twin, exactly as it is where rule ①
297        // is taken: declining the shorthand says nothing about the null test.
298        #sent_ty::Null => {
299          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
300            #ag::Value::Null,
301          ));
302        }
303        // `composed(shorthand = false)`. A bare value and a refused one get ONE sentence, because
304        // what this face has to say about both is the same thing: it takes an object naming an
305        // operator.
306        #sent_ty::Bare(__ingraph_sent) | #sent_ty::Refused(__ingraph_sent) => {
307          return ::core::result::Result::Err(#refuse_bare::<Self>(&__ingraph_sent));
308        }
309      }
310    };
311
312    quote! {
313      #[automatically_derived]
314      impl #ag::InputType for #subject {
315        type RawValueType = Self;
316
317        #[inline]
318        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
319          ::std::borrow::Cow::Borrowed(#sdl)
320        }
321
322        fn create_type_info(
323          __ingraph_registry: &mut #ag::registry::Registry,
324        ) -> ::std::string::String {
325          __ingraph_registry.create_input_type::<Self, _>(
326            #ag::registry::MetaTypeId::InputObject,
327            |__ingraph_registry| #ag::registry::MetaType::InputObject {
328              name: ::std::string::String::from(#sdl),
329              description: ::core::option::Option::None,
330              input_fields: <Self as #nullable_face>::bare_fields(__ingraph_registry),
331              visible: ::core::option::Option::None,
332              inaccessible: false,
333              tags: ::std::vec::Vec::new(),
334              rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
335              oneof: false,
336              directive_invocations: ::std::vec::Vec::new(),
337            },
338          )
339        }
340
341        fn parse(
342          __ingraph_value: ::core::option::Option<#ag::Value>,
343        ) -> #ag::InputValueResult<Self> {
344          let __ingraph_object = match #sent(__ingraph_value) {
345            #reading
346          };
347          ::core::result::Result::Ok(Self { #(#slots,)* #(#splices,)* })
348        }
349
350        fn to_value(&self) -> #ag::Value {
351          #ag::Value::Object(<Self as #nullable_face>::bare_values(self))
352        }
353
354        #[inline]
355        fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
356          ::core::option::Option::Some(self)
357        }
358      }
359    }
360  }
361
362  /// That the registration above is an input OBJECT.
363  fn input_object(&self) -> proc_macro2::TokenStream {
364    let subject = &self.subject;
365    let ag = self.framework(&[], "async_graphql");
366    quote! {
367      #[automatically_derived]
368      impl #ag::InputObjectType for #subject {}
369    }
370  }
371
372  /// The NULLABLE ROW — the two pieces `Nullable<F>`'s single blanket assembles this filter's twin
373  /// from, and the two the bare face above reads back off.
374  ///
375  /// So the field table is walked THREE times from one list: here for the registration and the
376  /// render, and in `parse` for the read. Nullability is a TYPE in this crate, so a face with no
377  /// `NullableFace` leaves every `Option<ThisFilter>` column unspellable — which is the gap this row
378  /// closes for a hand-written struct exactly as `filter_input_object!` closes it for a registered
379  /// one.
380  ///
381  /// # The registration is folded through ONE door, and that is where a SPLICE can collide
382  ///
383  /// The entries are built in declaration order — a slot contributes one, a splice contributes the
384  /// component's whole list — and handed to `flatten::table`, which refuses a name carried twice. A
385  /// splice's names are not visible where the tokens are, so that is the only place the collision can
386  /// be answered; the door is the same for a face that splices nothing, so there is one sentence
387  /// rather than two.
388  ///
389  /// The RENDER needs no such door: it walks the same list in the same order, and what the
390  /// registration accepted is what it writes.
391  fn nullable_face(&self) -> proc_macro2::TokenStream {
392    let subject = &self.subject;
393    let ag = self.framework(&[], "async_graphql");
394    let nullable_face = self.framework(&["graphql"], "NullableFace");
395    let face = self.framework(&["graphql"], "SlotFace");
396    let flat = self.framework(&["graphql"], "FlattenFace");
397    let table = self.framework(&["graphql", "filter", "flatten"], "table");
398    let sdl = self.sdl.external();
399
400    // Both walks are STATEMENTS, so the predicate rides them verbatim: a member the build removed
401    // registers no input value and renders no key, which is the same list contracting in all four
402    // places.
403    let entries = self.fields.iter().map(|field| {
404      let (ty, gate) = (&field.ty, field.condition.gate());
405      match &field.kind {
406        ComposedKind::Slot(wire) => quote! {
407          #gate
408          ::std::vec::Vec::push(
409            &mut __ingraph_entries,
410            (
411              ::std::string::String::from(#wire),
412              #ag::registry::MetaInputValue {
413                name: ::std::string::String::from(#wire),
414                description: ::core::option::Option::None,
415                ty: <#ty as #face<_>>::slot_type(__ingraph_registry),
416                deprecation: #ag::registry::Deprecation::NoDeprecated,
417                default_value: ::core::option::Option::None,
418                visible: ::core::option::Option::None,
419                inaccessible: false,
420                tags: ::std::vec::Vec::new(),
421                is_secret: false,
422                directive_invocations: ::std::vec::Vec::new(),
423              },
424            ),
425          );
426        },
427        ComposedKind::Spliced => quote! {
428          #gate
429          ::core::iter::Extend::extend(
430            &mut __ingraph_entries,
431            <#ty as #flat>::flat_fields(__ingraph_registry),
432          );
433        },
434      }
435    });
436
437    let values = self.fields.iter().map(|field| {
438      let (member, ty, gate) = (&field.member, &field.ty, field.condition.gate());
439      match &field.kind {
440        ComposedKind::Slot(wire) => quote! {
441          #gate
442          #ag::indexmap::IndexMap::insert(
443            &mut __ingraph_map,
444            #ag::Name::new(#wire),
445            <#ty as #face<_>>::write(&self.#member),
446          );
447        },
448        ComposedKind::Spliced => quote! {
449          #gate
450          ::core::iter::Extend::extend(
451            &mut __ingraph_map,
452            <#ty as #flat>::flat_values(&self.#member),
453          );
454        },
455      }
456    });
457
458    quote! {
459      #[automatically_derived]
460      impl #nullable_face for #subject {
461        fn bare_fields(
462          __ingraph_registry: &mut #ag::registry::Registry,
463        ) -> #ag::indexmap::IndexMap<::std::string::String, #ag::registry::MetaInputValue> {
464          let mut __ingraph_entries = ::std::vec::Vec::new();
465          #(#entries)*
466          #table(#sdl, __ingraph_entries)
467        }
468
469        fn bare_values(
470          &self,
471        ) -> #ag::indexmap::IndexMap<#ag::Name, #ag::Value> {
472          let mut __ingraph_map = #ag::indexmap::IndexMap::new();
473          #(#values)*
474          __ingraph_map
475        }
476      }
477    }
478  }
479}
480
481/// The schema name a composed declaration takes when it renames nothing: its OWN, unraw'd.
482///
483/// The subject IS the filter here, where the other two identities MINT one and name it
484/// `<Subject>Filter` — so a struct called `RateFilter` publishes `RateFilter` and a suffix bolted on
485/// here would publish `RateFilterFilter`.
486#[must_use]
487pub fn default_sdl_name(subject: &syn::Ident) -> RustSafeName {
488  RustSafeName::from_ident(subject)
489}