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
//! THE COMPOSED MODE's model: what `#[derive(ingraph::Filter)]` emits when the declaration wears
//! `#[ingraph(composed)]` — the wire face of a filter struct somebody wrote by hand, built out of
//! the fields themselves.
//!
//! # The struct IS the vocabulary, and that is the whole of the mode
//!
//! The other two identities take a declaration and MINT something: the struct mode mints a filter
//! over a row's columns, the element mode mints one over a single value. This one mints no type at
//! all. The subject already IS the filter — its fields are the operator slots, in the order they are
//! written — and what the derive adds is the face a client reaches it through.
//!
//! So the FIELD TABLE has exactly one author. A hand-written face carries the field list three times
//! — once in the registration, once in the parse, once in the render — and keeping the three in step
//! is a discipline rather than a fact. Here the three are one list walked three times, and the list
//! is the `struct` body: a field cannot be registered and not parsed, or rendered under a name the
//! registration never published, because there is nowhere for a second list to live.
//!
//! # TWO kinds of field, and the second one publishes NAMES THIS DECLARATION DOES NOT SPELL
//!
//! An operator SLOT is one name, one wire type, one key in the parsed object. A SPLICED component —
//! `#[ingraph(flatten)]` — is a whole filter face whose own fields become this filter's, so the
//! declaration's field list and the published table are no longer the same length. See
//! [`FlattenFace`], which is where the four faces splice.
//!
//! # What it emits, and what it deliberately does not
//!
//! | item | what it says |
//! |---|---|
//! | `async_graphql::InputType` | the three faces — the registration, the parse and the render |
//! | `async_graphql::InputObjectType` | that the registration above is an input OBJECT |
//! | [`NullableFace`] | the two halves `Nullable<F>`'s single blanket assembles the twin from |
//! | [`GraphqlFilter`] | emptiness, folded field by field |
//!
//! It emits **no constructor, no accessors and no inherent `is_empty`**. The struct is hand written:
//! its `new`, its `with_*` family and whatever inherent reads it publishes are the author's, and a
//! door that also emitted them would be `E0592` against the ones already there. `GraphqlFilter` is
//! the one emptiness answer this door writes, and an inherent `is_empty` beside it still wins method
//! resolution — which is the arrangement every filter kind in `ingraph` already has.
//!
//! **The LOWERING is untouched.** A composed filter reaches a dialect the way it always did, through
//! whatever `ToDatabaseComparison` row its author wrote; this door is about the wire and says nothing
//! about the storage side.
//!
//! # The SHAPE of each slot is resolved by the compiler
//!
//! Which of the four shapes a field is cannot be read off its tokens — `Option<Rate>` and
//! `Option<ScalarFilter<i32>>` are one shape to a parser — so every emitted line goes through
//! [`FilterSlot`]/[`SlotFace`], writes the kind as `_`, and lets inference pick the one row that
//! applies. A field answering none of them is `E0277` carrying that trait's own sentence and naming
//! the field's type; a field answering two is an ambiguity at the declaration rather than a silent
//! choice. See `ingraph`'s `graphql::filter::slot` for the rows and for the emptiness law.
//!
//! [`NullableFace`]: https://docs.rs/ingraph/latest/ingraph/trait.NullableFace.html
//! [`GraphqlFilter`]: https://docs.rs/ingraph/latest/ingraph/trait.GraphqlFilter.html
//! [`FilterSlot`]: https://docs.rs/ingraph/latest/ingraph/trait.FilterSlot.html
//! [`SlotFace`]: https://docs.rs/ingraph/latest/ingraph/trait.SlotFace.html
//! [`FlattenFace`]: https://docs.rs/ingraph/latest/ingraph/trait.FlattenFace.html

use quote::quote;

use crate::name::RustSafeName;

#[cfg(test)]
mod tests;

/// The client's name for a slot NO declaration renamed: the household fold — a raw prefix dropped, a
/// trailing underscore eaten, the rest lowerCamel.
///
/// So `not_in` is `notIn`, `starts_with` is `startsWith`, and the two Rust spellings of the keyword
/// slot — `r#in` and `in_` — both land on `in`. It is the SAME fold every other emitted wire member
/// takes: [`crate::emit::wire`] owns it, and this is the door a front end asks it through, so that a
/// composed slot and a record's column cannot come to disagree about what a Rust name looks like on
/// the wire.
///
/// Public because the DUPLICATE refusal needs it. Two fields folding onto one wire name is a
/// declaration this door cannot honour — the second registration would replace the first and the
/// parse would read one key twice — and the only place that can be seen is where the tokens are, so
/// the front end folds every member and compares.
#[must_use]
pub fn wire_name(member: &syn::Ident) -> String {
  crate::emit::wire::wire_member(member)
}

/// WHICH KIND of field one member of a composed filter is.
///
/// The two are told apart by a word rather than by a shape, for the mode's own reason: a field
/// holding a whole filter face is a legal nested SLOT and a legal splice, and which one a
/// declaration means is not readable from the type.
pub enum ComposedKind {
  /// An operator SLOT, carrying what a client calls it — the fold above, or whatever `rename` moved
  /// it to.
  Slot(String),
  /// A SPLICED component: its own fields become this filter's, so it publishes no name of its own
  /// and there is nothing for `rename` to move.
  Spliced,
}

/// ONE field of a composed filter: the member it is held in, its type, and which kind of field it is.
///
/// PLAIN, for [`StandaloneModel`](crate::standalone::StandaloneModel)'s reason — public fields, no
/// constructor, no validation. What is checked is checked at the FRONT END, where the tokens an
/// author wrote are still in hand and a refusal can point at one.
pub struct ComposedField {
  /// The struct field this is read from and written back into.
  pub member: syn::Ident,
  /// The field's own type, which is what the seam resolves the shape from.
  pub ty: syn::Type,
  /// A slot, or a splice.
  pub kind: ComposedKind,
  /// The CONDITION the member is declared under.
  ///
  /// Carried on the field rather than looked up, for [`crate::unit::FilterColumn`]'s reason: this
  /// door is shared, and only some of the front ends that reach it have a condition seat at all. A
  /// hand-written composed struct has none — its members are the author's own item, which rustc
  /// strips before this expansion ever sees it — so [`Condition::always`] is that door's answer and
  /// the emission below is byte-identical to the one before this seat existed.
  ///
  /// Where a front end DOES have one — the fragment tier, whose members it mints — the predicate has
  /// to reach all four walks: the emptiness fold, the parse, the registration and the render. A
  /// member present in three of them and absent from the fourth is an input object whose SDL and
  /// whose reader disagree.
  ///
  /// [`Condition::always`]: crate::model::Condition::always
  pub condition: crate::model::Condition,
}

/// A hand-written FILTER STRUCT, as the composed mode reads it.
pub struct ComposedModel {
  /// The struct the face is OF — and, being the filter itself, the type every emitted impl names.
  pub subject: syn::Ident,
  /// The `ingraph` root the expansion spells its shelf through.
  pub krate: syn::Path,
  /// The input object's name in the schema — the subject's own, or whatever
  /// `filter(rename = "…")` moved it to.
  pub sdl: RustSafeName,
  /// Whether rule ① reaches this face — `composed(shorthand = …)`, and `true` when the declaration
  /// said nothing.
  pub shorthand: bool,
  /// The fields, IN DECLARATION ORDER, which is the order the SDL prints them in: async-graphql
  /// renders an input object's fields in the order the registry received them.
  pub fields: Vec<ComposedField>,
}

impl ComposedModel {
  /// The shelf path one framework item is spelled through.
  fn framework(&self, module: &[&str], item: &str) -> proc_macro2::TokenStream {
    crate::emit::framework(&self.krate, module, item)
  }

  /// The whole composed mode, emitted.
  ///
  /// The emptiness answer is OUTSIDE the binding gate and the three wire faces are inside it, which
  /// is the split the slot seam is built along: *is anything set* is the same question on every
  /// backend and a build with no binding still has lowerings that ask it.
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let emptiness = self.emptiness();
    let gate = self.framework(&["gate"], "if_async_graphql");
    let face = self.input_type();
    let object = self.input_object();
    let nullable = self.nullable_face();
    quote! {
      #emptiness

      const _: () = {
        #gate! {
          #face
          #object
          #nullable
        }
      };
    }
  }

  /// The EMPTINESS answer, folded field by field.
  ///
  /// A SLOT asks its own row through `FilterSlot<_>`, so the fold-in a nested filter gets and the
  /// plain `is_none` an operand gets are the seam's rulings rather than this emitter's — and a field
  /// type that is not a slot shape at all is `E0277` here, at the declaration, carrying that trait's
  /// own sentence.
  ///
  /// A SPLICED component asks `GraphqlFilter` directly, because it has no `Option` for a row to be
  /// written over: its fields are this filter's fields and each of THOSE carries the absence. That is
  /// the same fold-in one indirection shorter, and it is what a hand-written face writes for its own
  /// flattened component.
  ///
  /// An empty struct never reaches this: the front end refuses one, because a filter with no field is
  /// a predicate that can ask nothing and an input object with no field is not valid SDL.
  fn emptiness(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let contract = self.framework(&["graphql"], "GraphqlFilter");
    let slot = self.framework(&["graphql"], "FilterSlot");
    let folded = self.fields.iter().map(|field| {
      let (member, ty) = (&field.member, &field.ty);
      let asked = match field.kind {
        ComposedKind::Slot(_) => quote!(<#ty as #slot<_>>::is_empty(&self.#member)),
        ComposedKind::Spliced => quote!(<#ty as #contract>::is_empty(&self.#member)),
      };
      // A TERM of a `&&` chain is the one seat in this file an attribute cannot sit in, so the fork
      // is moved one grain out. A member the build removed asks nothing, and *nothing asked* is
      // `true` — the identity of the conjunction, which is what makes the absent arm the same
      // sentence as having no such field at all.
      field.condition.either(&asked, &quote!(true))
    });
    quote! {
      #[automatically_derived]
      impl #contract for #subject {
        fn is_empty(&self) -> bool {
          #(#folded)&&*
        }
      }
    }
  }

  /// The THREE FACES: the registration, the parse and the render.
  ///
  /// # The SHORTHAND LAW reaches a composed face, unless the declaration declines it
  ///
  /// `parse` reads what arrived through the framework's own `sent`, so a client writes `"30000/1001"`
  /// where this face means `{ eq: "30000/1001" }` exactly as it may at a framework column. The bare
  /// value is put under the FIRST PUBLISHED name and the ordinary reads run over that object, so the
  /// operand crosses through the same grammar the longhand takes rather than through a second
  /// reading of it.
  ///
  /// That name is read off the face's own published TABLE rather than spelled here, so the shorthand
  /// and the registration cannot come to name different slots — including when the first field is a
  /// SPLICE, whose names this declaration does not write down.
  ///
  /// `composed(shorthand = false)` declines rule ① instead, and the refusal is the framework's own
  /// sentence naming this filter and its operators. A filter whose vocabulary is a relation has no
  /// slot a bare value obviously means — see `refuse_bare`, where the reason is written down.
  ///
  /// Rule ② is refused here and acted on by the nullable twin, which is nullability being a TYPE
  /// said at the parse.
  ///
  /// # The SPLICES are read LAST, after every slot has been read off the borrow
  ///
  /// A spliced component's parser takes the HOST's whole object, so its read is the one that cannot
  /// share the borrow the others hold. Ordering the struct literal that way is also what a
  /// hand-written flattened face does, and it keeps the first refusal a client sees the first slot's
  /// rather than the component's.
  fn input_type(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let ag = self.framework(&[], "async_graphql");
    let nullable_face = self.framework(&["graphql"], "NullableFace");
    let face = self.framework(&["graphql"], "SlotFace");
    let flat = self.framework(&["graphql"], "FlattenFace");
    let sent = self.framework(&["graphql", "filter"], "sent");
    let sent_ty = self.framework(&["graphql", "filter"], "Sent");
    let sdl = self.sdl.external();

    // A STRUCT LITERAL's field is a legal attribute position, so the gate rides each read and the
    // literal contracts with the struct it is building.
    let slots = self.fields.iter().filter_map(|field| {
      let (member, ty, gate) = (&field.member, &field.ty, field.condition.gate());
      match &field.kind {
        ComposedKind::Slot(wire) => {
          Some(quote!(#gate #member: <#ty as #face<_>>::read::<Self>(&__ingraph_object, #wire)?))
        }
        ComposedKind::Spliced => None,
      }
    });
    let splices = self.fields.iter().filter_map(|field| {
      let (member, ty, gate) = (&field.member, &field.ty, field.condition.gate());
      match &field.kind {
        ComposedKind::Slot(_) => None,
        ComposedKind::Spliced => {
          Some(quote!(#gate #member: <#ty as #flat>::flat_read::<Self>(&__ingraph_object)?))
        }
      }
    });

    let reading = if self.shorthand {
      let shorthand = self.framework(&["graphql", "filter"], "shorthand");
      quote! {
        #sent_ty::Longhand(__ingraph_object) => __ingraph_object,
        // Rule ① — a bare value is this face's FIRST PUBLISHED field, put under that key so the
        // reads below cross it through the same grammar the longhand takes.
        #sent_ty::Bare(__ingraph_bare) => #shorthand::<Self>(__ingraph_bare),
        // Rule ② is REFUSED here and acted on by the nullable twin: a `NOT NULL` column has no
        // null test to set, which is nullability being a TYPE said at the parse.
        #sent_ty::Null => {
          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
            #ag::Value::Null,
          ));
        }
        #sent_ty::Refused(__ingraph_sent) => {
          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
            __ingraph_sent,
          ));
        }
      }
    } else {
      let refuse_bare = self.framework(&["graphql", "filter"], "refuse_bare");
      quote! {
        #sent_ty::Longhand(__ingraph_object) => __ingraph_object,
        // Rule ② is REFUSED here and acted on by the nullable twin, exactly as it is where rule ①
        // is taken: declining the shorthand says nothing about the null test.
        #sent_ty::Null => {
          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
            #ag::Value::Null,
          ));
        }
        // `composed(shorthand = false)`. A bare value and a refused one get ONE sentence, because
        // what this face has to say about both is the same thing: it takes an object naming an
        // operator.
        #sent_ty::Bare(__ingraph_sent) | #sent_ty::Refused(__ingraph_sent) => {
          return ::core::result::Result::Err(#refuse_bare::<Self>(&__ingraph_sent));
        }
      }
    };

    quote! {
      #[automatically_derived]
      impl #ag::InputType for #subject {
        type RawValueType = Self;

        #[inline]
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          ::std::borrow::Cow::Borrowed(#sdl)
        }

        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          __ingraph_registry.create_input_type::<Self, _>(
            #ag::registry::MetaTypeId::InputObject,
            |__ingraph_registry| #ag::registry::MetaType::InputObject {
              name: ::std::string::String::from(#sdl),
              description: ::core::option::Option::None,
              input_fields: <Self as #nullable_face>::bare_fields(__ingraph_registry),
              visible: ::core::option::Option::None,
              inaccessible: false,
              tags: ::std::vec::Vec::new(),
              rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
              oneof: false,
              directive_invocations: ::std::vec::Vec::new(),
            },
          )
        }

        fn parse(
          __ingraph_value: ::core::option::Option<#ag::Value>,
        ) -> #ag::InputValueResult<Self> {
          let __ingraph_object = match #sent(__ingraph_value) {
            #reading
          };
          ::core::result::Result::Ok(Self { #(#slots,)* #(#splices,)* })
        }

        fn to_value(&self) -> #ag::Value {
          #ag::Value::Object(<Self as #nullable_face>::bare_values(self))
        }

        #[inline]
        fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
          ::core::option::Option::Some(self)
        }
      }
    }
  }

  /// That the registration above is an input OBJECT.
  fn input_object(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let ag = self.framework(&[], "async_graphql");
    quote! {
      #[automatically_derived]
      impl #ag::InputObjectType for #subject {}
    }
  }

  /// The NULLABLE ROW — the two pieces `Nullable<F>`'s single blanket assembles this filter's twin
  /// from, and the two the bare face above reads back off.
  ///
  /// So the field table is walked THREE times from one list: here for the registration and the
  /// render, and in `parse` for the read. Nullability is a TYPE in this crate, so a face with no
  /// `NullableFace` leaves every `Option<ThisFilter>` column unspellable — which is the gap this row
  /// closes for a hand-written struct exactly as `filter_input_object!` closes it for a registered
  /// one.
  ///
  /// # The registration is folded through ONE door, and that is where a SPLICE can collide
  ///
  /// The entries are built in declaration order — a slot contributes one, a splice contributes the
  /// component's whole list — and handed to `flatten::table`, which refuses a name carried twice. A
  /// splice's names are not visible where the tokens are, so that is the only place the collision can
  /// be answered; the door is the same for a face that splices nothing, so there is one sentence
  /// rather than two.
  ///
  /// The RENDER needs no such door: it walks the same list in the same order, and what the
  /// registration accepted is what it writes.
  fn nullable_face(&self) -> proc_macro2::TokenStream {
    let subject = &self.subject;
    let ag = self.framework(&[], "async_graphql");
    let nullable_face = self.framework(&["graphql"], "NullableFace");
    let face = self.framework(&["graphql"], "SlotFace");
    let flat = self.framework(&["graphql"], "FlattenFace");
    let table = self.framework(&["graphql", "filter", "flatten"], "table");
    let sdl = self.sdl.external();

    // Both walks are STATEMENTS, so the predicate rides them verbatim: a member the build removed
    // registers no input value and renders no key, which is the same list contracting in all four
    // places.
    let entries = self.fields.iter().map(|field| {
      let (ty, gate) = (&field.ty, field.condition.gate());
      match &field.kind {
        ComposedKind::Slot(wire) => quote! {
          #gate
          ::std::vec::Vec::push(
            &mut __ingraph_entries,
            (
              ::std::string::String::from(#wire),
              #ag::registry::MetaInputValue {
                name: ::std::string::String::from(#wire),
                description: ::core::option::Option::None,
                ty: <#ty as #face<_>>::slot_type(__ingraph_registry),
                deprecation: #ag::registry::Deprecation::NoDeprecated,
                default_value: ::core::option::Option::None,
                visible: ::core::option::Option::None,
                inaccessible: false,
                tags: ::std::vec::Vec::new(),
                is_secret: false,
                directive_invocations: ::std::vec::Vec::new(),
              },
            ),
          );
        },
        ComposedKind::Spliced => quote! {
          #gate
          ::core::iter::Extend::extend(
            &mut __ingraph_entries,
            <#ty as #flat>::flat_fields(__ingraph_registry),
          );
        },
      }
    });

    let values = self.fields.iter().map(|field| {
      let (member, ty, gate) = (&field.member, &field.ty, field.condition.gate());
      match &field.kind {
        ComposedKind::Slot(wire) => quote! {
          #gate
          #ag::indexmap::IndexMap::insert(
            &mut __ingraph_map,
            #ag::Name::new(#wire),
            <#ty as #face<_>>::write(&self.#member),
          );
        },
        ComposedKind::Spliced => quote! {
          #gate
          ::core::iter::Extend::extend(
            &mut __ingraph_map,
            <#ty as #flat>::flat_values(&self.#member),
          );
        },
      }
    });

    quote! {
      #[automatically_derived]
      impl #nullable_face for #subject {
        fn bare_fields(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> #ag::indexmap::IndexMap<::std::string::String, #ag::registry::MetaInputValue> {
          let mut __ingraph_entries = ::std::vec::Vec::new();
          #(#entries)*
          #table(#sdl, __ingraph_entries)
        }

        fn bare_values(
          &self,
        ) -> #ag::indexmap::IndexMap<#ag::Name, #ag::Value> {
          let mut __ingraph_map = #ag::indexmap::IndexMap::new();
          #(#values)*
          __ingraph_map
        }
      }
    }
  }
}

/// The schema name a composed declaration takes when it renames nothing: its OWN, unraw'd.
///
/// The subject IS the filter here, where the other two identities MINT one and name it
/// `<Subject>Filter` — so a struct called `RateFilter` publishes `RateFilter` and a suffix bolted on
/// here would publish `RateFilterFilter`.
#[must_use]
pub fn default_sdl_name(subject: &syn::Ident) -> RustSafeName {
  RustSafeName::from_ident(subject)
}