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
//! The two INPUT FACES a unit's types wear — `InputType` over the filter's struct and over the
//! order-by's enum — written once for every front end that emits one.
//!
//! # Why the faces are HAND-WRITTEN at all
//!
//! `#[derive(InputObject)]` and `#[derive(OneofObject)]` are attached to a DECLARATION, and both of
//! these types are emitted: their fields carry projections through the marker layer, their names come
//! from a naming tower, and their `__`-pinned Rust idents are not the words a client reads. So what
//! is written here is those derives' own output, at the one place a derive could not be attached.
//!
//! # And why it is ONE emitter for two front ends
//!
//! The STRUCT halves already are — [`super::filter`] and [`super::order_by`] serve a record, an
//! interface and a standalone `#[derive(ingraph::Filter)]` alike. The faces were a record's alone
//! until B-27 asked an interface to publish a root field, which is what a filter and an order-by are
//! spent by. A second copy of forty lines of registry construction is where the two would come to
//! disagree about a byte of somebody's SDL.
//!
//! What a caller supplies is exactly what it knows: the type's Rust name, the name a CLIENT reads,
//! and one row per column already resolved through whichever naming layers that front end has.
//!
//! # The one flag that separates the two
//!
//! `oneof`. A predicate narrows by every field a client writes; an order term names exactly ONE
//! column — and `oneof: true` is what makes *exactly one* the VALIDATOR's rule rather than a
//! resolver's, refused before anything runs, through a literal and through a variable alike.

use quote::quote;

/// What both faces need before they read a single column.
pub struct InputFace<'a> {
  /// Where `ingraph` lives — every framework path an emission writes goes through the shelf.
  pub krate: &'a syn::Path,
  /// The emitted type's RUST name.
  pub name: &'a syn::Ident,
  /// The name a CLIENT reads, already resolved through the caller's own naming tower.
  pub sdl: &'a str,
}

impl InputFace<'_> {
  /// The async-graphql root, through the shelf.
  fn ag(&self) -> proc_macro2::TokenStream {
    crate::emit::framework(self.krate, &[], "async_graphql")
  }

  /// One `MetaInputValue` — the registry entry of ONE input field, with `description` written `None`
  /// because that is where the rule lands: descriptions come from `attrs(desc = …)` and nowhere
  /// else.
  fn meta_input_value(
    &self,
    name: &str,
    ty: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let ag = self.ag();
    quote! {
      #ag::registry::MetaInputValue {
        name: ::std::string::String::from(#name),
        description: ::core::option::Option::None,
        ty: <#ty as #ag::InputType>::create_type_info(__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(),
      }
    }
  }

  /// The registry entries of a face's fields, as ONE expression building the map — written where
  /// `__ingraph_registry` is in scope, which every entry names.
  fn fields_block(
    &self,
    entries: impl Iterator<Item = proc_macro2::TokenStream>,
  ) -> proc_macro2::TokenStream {
    let ag = self.ag();
    let entries: Vec<proc_macro2::TokenStream> = entries.collect();
    quote! {
      {
        let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
        #(#entries)*
        __ingraph_fields
      }
    }
  }

  /// The two `InputType` items every hand-written input face writes the same way: its GraphQL name,
  /// and the registry entry that declares its fields.
  ///
  /// One helper rather than two copies, because the FILTER's entry and the ORDER-BY's differ in
  /// exactly one flag — `oneof` — and a second copy is where that flag would come to differ in
  /// something else.
  ///
  /// `input_fields` is an EXPRESSION rather than the entries, because the two callers reach the map
  /// differently: an order-by builds it here, and a filter reads it back off its own
  /// `ingraph::NullableFace` row so the bare face and its nullable twin publish one list. Both
  /// spellings are evaluated where `__ingraph_registry` is bound.
  fn type_info(
    &self,
    input_fields: &proc_macro2::TokenStream,
    oneof: bool,
  ) -> proc_macro2::TokenStream {
    let ag = self.ag();
    let sdl = self.sdl;
    quote! {
      #[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: #input_fields,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
            oneof: #oneof,
            directive_invocations: ::std::vec::Vec::new(),
          },
        )
      }
    }
  }
}

/// One column, as the FILTER's face reads it.
pub struct FilterField {
  /// The name a CLIENT writes this column under — the INPUT position's, which the order-by term
  /// shares so a document never spells one column two ways.
  pub field: String,
  /// The struct MEMBER the parsed value lands in.
  pub member: syn::Ident,
  /// The filter this column is guarded by, already projected through the marker layer.
  pub filter: proc_macro2::TokenStream,
  /// The CONDITION the column is declared under — see
  /// [`Condition`](crate::model::Condition). Empty for a column that wrote none, and for every unit
  /// whose front end has no condition seat.
  pub gate: proc_macro2::TokenStream,
}

/// One column, as the ORDER-BY's face reads it.
pub struct OrderField {
  /// The name a CLIENT writes this column under — the FILTER's own name for it.
  pub field: String,
  /// The enum VARIANT that term parses into.
  pub variant: syn::Ident,
  /// Whether the SCHEMA names this term at all — false where `graphql(skip)` withheld the column.
  ///
  /// The Rust enum has a variant either way: the order-by type generates FULL, so a Rust caller
  /// orders by every stored column. What this decides is the FACE — see
  /// [`order_by_face`], where a withheld term is registered nowhere and parsed by nothing.
  pub published: bool,
  /// The CONDITION the column is declared under — see
  /// [`Condition`](crate::model::Condition). Empty for a column that wrote none, and for every unit
  /// whose front end has no condition seat.
  pub gate: proc_macro2::TokenStream,
}

/// One REVERSE relation position, as the FILTER's face reads it.
///
/// Its three legs differ from a column's by ONE fact and it is the BOX: the struct member is
/// `Option<Box<RelatedFilter<…>>>` because a position naming this record's own kind would make the
/// struct contain itself, and `Box` has no `InputType` row — so the schema entry, the parse and the
/// render all name the UNBOXED type and the box is put on and taken off here. That is the same
/// division the `__` prefix pin states one layer up: a Rust fact does not reach a client.
pub struct RelationPosition {
  /// The name a CLIENT writes this position under.
  pub field: String,
  /// The struct MEMBER the parsed value lands in.
  pub member: syn::Ident,
  /// The UNBOXED filter this position holds — `RelatedFilter<…>` over the far side's own filter.
  pub held: proc_macro2::TokenStream,
}

/// The FILTER as an ordinary input object: one NULLABLE field per column, each carrying that
/// column's own filter, and any number of them supplied.
///
/// # `Option<F>` at the field and NOT `Nullable<F>`
///
/// Two different absences, and the type says which. `Option` at this position is *the client wrote
/// no predicate for this column* — an unwritten field narrows nothing — where `Nullable<F>` is the
/// column's own NULL state and lives inside `F` for a nullable column, carrying `isNull`. The
/// struct's member is `Option<F>` for exactly that reason and this face parses what the member
/// holds.
#[must_use]
pub fn filter_face(
  face: &InputFace<'_>,
  fields: &[FilterField],
  positions: &[RelationPosition],
) -> proc_macro2::TokenStream {
  let (ag, name) = (face.ag(), face.name);
  let entries = fields.iter().map(|row| {
    let (field, filter, gate) = (&row.field, &row.filter, &row.gate);
    let value = face.meta_input_value(field, &quote!(::core::option::Option<#filter>));
    // The CONDITION, on a STATEMENT and on a struct-expression field — both attribute positions — so
    // a column the build removed is registered by nobody, parsed by nothing and rendered nowhere.
    // The SCHEMA follows the build, which is the whole of what `family-wide` means here.
    quote!(#gate __ingraph_fields.insert(::std::string::String::from(#field), #value);)
  });
  // Every field is read, present or absent: `Option<F>::parse(None)` is `Ok(None)`, so a document
  // that writes two columns of twenty is twenty reads and eighteen empty answers rather than a
  // walk over whichever keys the object happened to carry. That is what makes an unknown key
  // ignored and a malformed known one refused, which is async-graphql's own posture for an input
  // object.
  let parses = fields.iter().map(|row| {
    let (field, member, filter, gate) = (&row.field, &row.member, &row.filter, &row.gate);
    quote! {
      #gate
      #member: <::core::option::Option<#filter> as #ag::InputType>::parse(
        // `.cloned()` as a METHOD, where every path this emission writes is absolute: the two
        // `Option<&T>` / `Option<&mut T>` inherent impls make the qualified spelling `E0034`, and
        // a method call is resolved by the receiver's type rather than by a name a declaring
        // module could shadow. The same shape `map_err` below already takes.
        #ag::indexmap::IndexMap::get(&__ingraph_object, #field).cloned(),
      )
      .map_err(#ag::InputValueError::propagate)?,
    }
  });
  let renders = fields.iter().map(|row| {
    let (field, member, gate) = (&row.field, &row.member, &row.gate);
    quote! {
      #gate
      __ingraph_map.insert(
        #ag::Name::new(#field),
        #ag::InputType::to_value(&self.#member),
      );
    }
  });
  // The REVERSE relation positions, in the declaration's own order after every column.
  let position_entries = positions.iter().map(|row| {
    let (field, held) = (&row.field, &row.held);
    let value = face.meta_input_value(field, &quote!(::core::option::Option<#held>));
    quote!(__ingraph_fields.insert(::std::string::String::from(#field), #value);)
  });
  let position_parses = positions.iter().map(|row| {
    let (field, member, held) = (&row.field, &row.member, &row.held);
    quote! {
      #member: ::core::option::Option::map(
        <::core::option::Option<#held> as #ag::InputType>::parse(
          #ag::indexmap::IndexMap::get(&__ingraph_object, #field).cloned(),
        )
        .map_err(#ag::InputValueError::propagate)?,
        ::std::boxed::Box::new,
      ),
    }
  });
  // `Value::Null` for the absent case, which is exactly what `<Option<T> as InputType>::to_value`
  // answers for a `None` — the column legs' own behaviour, written out because the box has to be
  // stepped through to reach a value the library can render.
  let position_renders = positions.iter().map(|row| {
    let (field, member) = (&row.field, &row.member);
    quote! {
      __ingraph_map.insert(
        #ag::Name::new(#field),
        match &self.#member {
          ::core::option::Option::Some(__ingraph_position) => {
            #ag::InputType::to_value(&**__ingraph_position)
          }
          ::core::option::Option::None => #ag::Value::Null,
        },
      );
    }
  });
  let nullable_face = crate::emit::framework(face.krate, &["graphql"], "NullableFace");
  // The field list lives on the NULLABLE row and the bare face reads it back, so a nullable column
  // of this filter publishes the same fields in the same order — one list rather than two kept in
  // step by hand, which is the discipline `ingraph`'s own registrations already keep.
  let fields = face.fields_block(entries.chain(position_entries));
  let info = face.type_info(
    &quote!(<Self as #nullable_face>::bare_fields(__ingraph_registry)),
    false,
  );
  let sent = crate::emit::framework(face.krate, &["graphql", "filter"], "sent");
  let sent_ty = crate::emit::framework(face.krate, &["graphql", "filter"], "Sent");
  quote! {
    #[automatically_derived]
    impl #ag::InputType for #name {
      type RawValueType = Self;

      #info

      /// # The SHORTHAND LAW at a COMPOSITE face, whose answer to two of its four readings is no
      ///
      /// Read through the framework's own `sent` so this face answers the law where every other
      /// one does, and REFUSES two of the readings faithfully rather than by falling off an `if`.
      ///
      /// Rule ① wants the one slot a bare value is the `eq` of, and a composite has none: its
      /// fields are COLUMNS, each with a filter of its own, so `42` names no operand here. A face
      /// that guessed the first column would silently answer a different question than the one
      /// asked — which is rule ③'s own posture, a reading refused because no reading is true.
      ///
      /// Rule ② is refused for the reason every bare face refuses it: the null test is a TYPE
      /// here, and `Nullable<Self>` — reached through the row below — is what acts on it.
      fn parse(
        value: ::core::option::Option<#ag::Value>,
      ) -> #ag::InputValueResult<Self> {
        match #sent(value) {
          #sent_ty::Longhand(__ingraph_object) => {
            ::core::result::Result::Ok(Self { #(#parses)* #(#position_parses)* })
          }
          #sent_ty::Bare(__ingraph_sent) => {
            ::core::result::Result::Err(#ag::InputValueError::expected_type(__ingraph_sent))
          }
          #sent_ty::Null => {
            ::core::result::Result::Err(#ag::InputValueError::expected_type(#ag::Value::Null))
          }
          #sent_ty::Refused(__ingraph_sent) => {
            ::core::result::Result::Err(#ag::InputValueError::expected_type(__ingraph_sent))
          }
        }
      }

      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)
      }
    }

    #[automatically_derived]
    impl #ag::InputObjectType for #name {}

    #[automatically_derived]
    impl #nullable_face for #name {
      fn bare_fields(
        __ingraph_registry: &mut #ag::registry::Registry,
      ) -> #ag::indexmap::IndexMap<::std::string::String, #ag::registry::MetaInputValue> {
        #fields
      }

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

/// The ORDER-BY as a `@oneOf` input object: one nullable field per orderable column, exactly one of
/// them supplied.
///
/// The filter's twin, one flag apart. The SHAPE was fixed when the type was declared — an enum of
/// single-value tuple variants, which is what `OneofObject` takes — and what is written here is that
/// derive's own output.
#[must_use]
pub fn order_by_face(face: &InputFace<'_>, terms: &[OrderField]) -> proc_macro2::TokenStream {
  let (ag, name) = (face.ag(), face.name);
  let direction = crate::emit::framework(face.krate, &["graphql"], "OrderDirection");
  // THE TWO WALKS, and which of them each half of the trait takes. REGISTRATION and PARSE are the
  // schema's, so they take the published terms alone: a withheld column has no field in the SDL and
  // no name a request can spell, which is invisible AND unreachable rather than either one.
  //
  // `to_value` takes EVERY term, and it has to: the match is over the enum, which generates full, so
  // a narrowed render would be non-exhaustive. It is also safe to leave total, and that is the
  // ruling's own observation rather than a hope — the order-by is an INPUT-ONLY type. Its values
  // arrive from a client and never leave for one, so rendering a variant a client could not have
  // written publishes nothing; `to_value` exists for the round trip a variable or a default takes
  // through async-graphql's own machinery, and a term nobody could send is a term that never
  // reaches it.
  let published = || terms.iter().filter(|term| term.published);
  let entries = published().map(|term| {
    let (field, gate) = (&term.field, &term.gate);
    let value = face.meta_input_value(field, &quote!(::core::option::Option<#direction>));
    quote!(#gate __ingraph_fields.insert(::std::string::String::from(#field), #value);)
  });
  // `swap_remove` rather than `remove`: the entry is taken and the object is dropped in the same
  // breath, so the order it leaves behind is nobody's, and indexmap 2 deprecates the ambiguous
  // spelling — a deprecation warning inside an expansion is one a consumer cannot edit away.
  let parses = published().map(|term| {
    let (field, variant, gate) = (&term.field, &term.variant, &term.gate);
    quote! {
      #gate
      if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, #field)
        && #ag::indexmap::IndexMap::len(&__ingraph_object) == 1
      {
        let __ingraph_direction = #ag::InputType::parse(
          #ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, #field),
        )
        .map_err(#ag::InputValueError::propagate)?;
        return ::core::result::Result::Ok(Self::#variant(__ingraph_direction));
      }
    }
  });
  let renders = terms.iter().map(|term| {
    let (variant, field, gate) = (&term.variant, &term.field, &term.gate);
    quote! {
      #gate
      Self::#variant(__ingraph_direction) => {
        __ingraph_map.insert(
          #ag::Name::new(#field),
          #ag::InputType::to_value(__ingraph_direction),
        );
      }
    }
  });
  let info = face.type_info(&face.fields_block(entries), true);
  quote! {
    #[automatically_derived]
    impl #ag::InputType for #name {
      type RawValueType = Self;

      #info

      fn parse(
        value: ::core::option::Option<#ag::Value>,
      ) -> #ag::InputValueResult<Self> {
        if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) = value {
          #(#parses)*
          return ::core::result::Result::Err(#ag::InputValueError::expected_type(
            #ag::Value::Object(__ingraph_object),
          ));
        }
        ::core::result::Result::Err(#ag::InputValueError::expected_type(
          ::core::option::Option::unwrap_or_default(value),
        ))
      }

      fn to_value(&self) -> #ag::Value {
        let mut __ingraph_map = #ag::indexmap::IndexMap::new();
        match self {
          #(#renders)*
        }
        #ag::Value::Object(__ingraph_map)
      }

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

    #[automatically_derived]
    impl #ag::InputObjectType for #name {}

    #[automatically_derived]
    impl #ag::OneofObjectType for #name {}
  }
}