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
//! The two SCHEMA POSITIONS a declared union has, and what each one is written as.
//!
//! `union SearchResult = Media | Video` in a RETURN position; `input SearchResultInput @oneOf` in an
//! ARGUMENT position. A declaration asks for one, the other, or both — `graphql(async_graphql(input,
//! output))` — and a declaration that asks for neither gets neither, which is what every union in
//! this tree got before this round and still gets today.
//!
//! Carried by the ONE door, [`UnionModel::emit`], and written from the same model the method face
//! is. The SEAM that face rides — [`Equipped`](super::Equipped), shared with the interface derive —
//! is not touched by any of this: an interface is a member set with a contract over it and has a
//! wire face of its own, so what a UNION renders as hangs off the union's own model, one layer above
//! the emission both member sets reach.
//!
//! # Both faces are HAND-EMITTED, and a derive cannot be what writes them
//!
//! `#[derive(async_graphql::Union)]` and `#[derive(async_graphql::OneofObject)]` are the library's
//! own doors onto these two shapes, and neither is reachable from here. A derive macro may only
//! APPEND — the declaration is the author's item and this expansion never rewrites it — so there is
//! nowhere to put a derive, and `#[cfg_attr]` could not stand in even if there were: that predicate
//! asks whether the DECLARING crate has a feature called `async-graphql`, which is a different
//! manifest and usually no feature at all. `crate::index` states the same wall from the other side
//! and writes its own union out for the same reason.
//!
//! What the hand emission also buys is this crate's posture on prose: `description: None` on every
//! type and every seat, as a FACT of the emission. async-graphql's derives call `get_rustdoc`
//! unconditionally with no key to decline it, so a derived face publishes whatever a declaration
//! happened to document. Nothing here is derived, so nothing here can.
//!
//! # The whole face sits behind the BINDING GATE
//!
//! One `const _: () = { if_async_graphql! { … } };` per backend, so a build of `ingraph` without
//! `async-graphql` expands the lot to nothing. That is also why the wire half is a block of its own
//! rather than a member of the method face's: a gate wrapping one block's ENTIRE body is what makes
//! *expands to nothing at all* true, where a `cfg` sprinkled through a shared block would not.
//!
//! # The INPUT face's seats, and the refusal a member without one earns
//!
//! An `@oneOf` input object is one NULLABLE seat per member, exactly one of them supplied, and each
//! seat's type is the member's OWN input type. So a union declaring `input` demands an
//! `async_graphql::InputType` of every member — and a member without one would otherwise fail deep
//! inside this expansion, at a span its author cannot edit.
//!
//! [`UnionModel::seat_trait`] is what moves that: a marker the expansion declares, blanket-implemented
//! over `InputType`, carrying `#[diagnostic::on_unimplemented]` with this framework's own sentence
//! and `#[diagnostic::do_not_recommend]` on the blanket impl so the report stops at the marker rather
//! than descending into the library's trait. Every member mention in the face goes through it and
//! every one of them is spanned at the MEMBER'S OWN TYPE, which is what collapses the three sites a
//! member is named at into ONE diagnostic: rustc deduplicates diagnostics that are identical in
//! message and span.
//!
//! The OUTPUT face has no marker of its own and its member mentions are spanned the same way, so a
//! member with no `OutputType` is reported at its own token with async-graphql's own sentence. The
//! asymmetry is the ruling's: a union member is ordinarily an OBJECT, which has an output face by
//! being one, and it is the INPUT demand that a declaration is likely not to have met.

use quote::{quote, quote_spanned};
use syn::spanned::Spanned as _;

use super::{UnionModel, UnionSkin};
use crate::model::GraphqlKind;

#[cfg(test)]
mod tests;

impl UnionModel {
  /// The wire faces this declaration asked for, one gated block per backend.
  ///
  /// Called by [`emit`](UnionModel::emit) and reached no other way. EMPTY for a union that wrote no
  /// `graphql(…)` block, which is what keeps the method face's *this expansion is `core` and nothing
  /// else* true of every declaration that says nothing.
  pub(super) fn graphql_faces(&self) -> proc_macro2::TokenStream {
    let skins = self.graphql.iter().map(|skin| self.skin(skin));
    quote!(#(#skins)*)
  }

  /// ONE backend's block: the marker the input face needs, then whichever of the two faces was
  /// declared.
  fn skin(&self, skin: &UnionSkin) -> proc_macro2::TokenStream {
    let gate = self.framework(&["gate"], "if_async_graphql");
    let (seats, input) = match skin.input {
      Some(_) => (self.seat_trait(), self.input_face(skin)),
      None => (quote!(), quote!()),
    };
    let output = if skin.output.is_some() {
      self.output_face(skin)
    } else {
      quote!()
    };
    match skin.kind {
      GraphqlKind::AsyncGraphql => quote! {
        const _: () = {
          #gate! {
            #seats
            #output
            #input
          }
        };
      },
    }
  }

  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
  /// them.
  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
    crate::emit::framework(&self.krate, module, name)
  }

  /// The vendored library itself, which every name below hangs off.
  fn async_graphql(&self) -> proc_macro2::TokenStream {
    self.framework(&[], "async_graphql")
  }

  /// The OUTPUT face: `union X = A | B`, and the three impls async-graphql renders one through.
  ///
  /// `ContainerType` collects the selection set against the MEMBER the value is holding, which is
  /// what a union resolves as — the arms have no fields of their own, so `resolve_field` answers
  /// `None` and the collection delegates. `introspection_type_name` is what tells a client which
  /// arm it got, per member and off the member's own `type_name`.
  fn output_face(&self, skin: &UnionSkin) -> proc_macro2::TokenStream {
    let name = &self.name;
    let ag = self.async_graphql();
    let sdl = skin.output_sdl(name);
    let variants = self.members.iter().map(|member| &member.ident);
    let names = self.members.iter().map(|member| {
      let ty = &member.ty;
      quote_spanned!(ty.span()=> <#ty as #ag::OutputType>::type_name())
    });
    let arms = self.members.iter().map(|member| {
      let ident = &member.ident;
      let ty = &member.ty;
      let named = quote_spanned!(ty.span()=> <#ty as #ag::OutputType>::type_name());
      quote!(Self::#ident(_) => #named,)
    });
    let registered = self.members.iter().map(|member| {
      let ty = &member.ty;
      quote_spanned! {ty.span()=>
        <#ty as #ag::OutputType>::create_type_info(__ingraph_registry);
      }
    });
    quote! {
      #[automatically_derived]
      impl #ag::resolver_utils::ContainerType for #name {
        async fn resolve_field(
          &self,
          _ctx: &#ag::Context<'_>,
        ) -> #ag::ServerResult<::core::option::Option<#ag::Value>> {
          ::core::result::Result::Ok(::core::option::Option::None)
        }

        fn collect_all_fields<'__ingraph_member>(
          &'__ingraph_member self,
          __ingraph_ctx: &#ag::ContextSelectionSet<'__ingraph_member>,
          __ingraph_fields: &mut #ag::resolver_utils::Fields<'__ingraph_member>,
        ) -> #ag::ServerResult<()> {
          match self {
            #(Self::#variants(__ingraph_arm) => #ag::resolver_utils::ContainerType::collect_all_fields(
              __ingraph_arm,
              __ingraph_ctx,
              __ingraph_fields,
            ),)*
          }
        }
      }

      #[automatically_derived]
      impl #ag::OutputType for #name {
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          ::std::borrow::Cow::Borrowed(#sdl)
        }

        fn introspection_type_name(&self) -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          match self { #(#arms)* }
        }

        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          __ingraph_registry.create_output_type::<Self, _>(
            #ag::registry::MetaTypeId::Union,
            |__ingraph_registry| {
              #(#registered)*
              #ag::registry::MetaType::Union {
                name: ::std::string::String::from(#sdl),
                description: ::core::option::Option::None,
                possible_types: {
                  let mut __ingraph_arms = #ag::indexmap::IndexSet::new();
                  #(__ingraph_arms.insert(::std::borrow::Cow::into_owned(#names));)*
                  __ingraph_arms
                },
                visible: ::core::option::Option::None,
                inaccessible: false,
                tags: ::std::vec::Vec::new(),
                rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
                directive_invocations: ::std::vec::Vec::new(),
              }
            },
          )
        }

        async fn resolve(
          &self,
          __ingraph_ctx: &#ag::ContextSelectionSet<'_>,
          _field: &#ag::Positioned<#ag::parser::types::Field>,
        ) -> #ag::ServerResult<#ag::Value> {
          #ag::resolver_utils::resolve_container(__ingraph_ctx, self).await
        }
      }

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

  /// The marker every seat of the input face is asked for through — the NAMED REFUSAL a member with
  /// no input face earns.
  ///
  /// Three operations rather than a bare bound, and that is what makes the refusal SINGULAR: a bare
  /// marker would leave the face's own `create_type_info`, `parse` and `to_value` naming
  /// `InputType` directly, so a member without one would collect this sentence AND three of
  /// async-graphql's. Routed through the marker and spanned at the member's own type, all four sites
  /// report the same message at the same span, and rustc emits such a diagnostic once.
  ///
  /// `do_not_recommend` on the blanket impl is the other half: without it the report descends
  /// through the impl and names `InputType`, which is true and is not the sentence this framework
  /// wants to say.
  fn seat_trait(&self) -> proc_macro2::TokenStream {
    let ag = self.async_graphql();
    let seat = self.seat_marker();
    let name = &self.name;
    let message = format!(
      "`{{Self}}` is a member of `{name}`, which declares a GraphQL INPUT face, and has no \
       `async_graphql::InputType` of its own"
    );
    let note = format!(
      "an `@oneOf` input object's seats ARE its members' own input types, so every member of \
       `{name}` needs one — give this member an input face, or drop `input` from its \
       `graphql(async_graphql(…))` block and declare `{name}` for output alone"
    );
    quote! {
      #[diagnostic::on_unimplemented(
        message = #message,
        label = "this member has no GraphQL input face",
        note = #note,
      )]
      trait #seat: ::core::marker::Sized {
        fn __ingraph_seat_type(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String;

        // The refusal is ALREADY the union's, which is why the parse carries the union's type: a
        // caller propagating afterwards would name `InputValueError<Member>`, whose own inherent
        // impl is bounded on `InputType` — one more demand at the member, outside this marker and
        // in the library's words.
        fn __ingraph_seat_parse<__IngraphUnion: #ag::InputType>(
          __ingraph_value: ::core::option::Option<#ag::Value>,
        ) -> ::core::result::Result<Self, #ag::InputValueError<__IngraphUnion>>;

        fn __ingraph_seat_value(&self) -> #ag::Value;
      }

      #[diagnostic::do_not_recommend]
      impl<__IngraphMember: #ag::InputType> #seat for __IngraphMember {
        #[inline]
        fn __ingraph_seat_type(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          // NULLABLE, which is the whole of what `@oneOf` asks of a seat: every one of them is
          // optional and exactly one is supplied.
          <::core::option::Option<Self> as #ag::InputType>::create_type_info(__ingraph_registry)
        }

        #[inline]
        fn __ingraph_seat_parse<__IngraphUnion: #ag::InputType>(
          __ingraph_value: ::core::option::Option<#ag::Value>,
        ) -> ::core::result::Result<Self, #ag::InputValueError<__IngraphUnion>> {
          <Self as #ag::InputType>::parse(__ingraph_value)
            .map_err(#ag::InputValueError::propagate)
        }

        #[inline]
        fn __ingraph_seat_value(&self) -> #ag::Value {
          <Self as #ag::InputType>::to_value(self)
        }
      }
    }
  }

  /// What that marker is called. Inside the anonymous `const`, so it collides with nothing.
  fn seat_marker(&self) -> syn::Ident {
    quote::format_ident!("__IngraphSeat")
  }

  /// The INPUT face: an `@oneOf` input object, one nullable seat per member.
  ///
  /// `oneof: true` in the meta type is what publishes the directive, and the `parse` below is what
  /// HOLDS it at runtime for the arm a request took: the validator refuses a document naming two
  /// seats or none before anything runs, and this reads the one it admitted.
  fn input_face(&self, skin: &UnionSkin) -> proc_macro2::TokenStream {
    let name = &self.name;
    let ag = self.async_graphql();
    let seat = self.seat_marker();
    let sdl = skin.input_sdl(name);
    let fields = self.members.iter().map(|member| {
      let ty = &member.ty;
      let word = super::seat(&member.ident);
      let seated = quote_spanned! {ty.span()=>
        <#ty as #seat>::__ingraph_seat_type(__ingraph_registry)
      };
      quote! {
        __ingraph_fields.insert(
          ::std::string::String::from(#word),
          #ag::registry::MetaInputValue {
            name: ::std::string::String::from(#word),
            description: ::core::option::Option::None,
            ty: #seated,
            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(),
          },
        );
      }
    });
    let reads = self.members.iter().map(|member| {
      let ident = &member.ident;
      let ty = &member.ty;
      let word = super::seat(&member.ident);
      let seated = quote_spanned! {ty.span()=>
        <#ty as #seat>::__ingraph_seat_parse::<Self>(
          #ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, #word),
        )
      };
      quote! {
        // EXACTLY ONE KEY, which is the whole of what `@oneOf` means.
        if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, #word)
          && __ingraph_object.len() == 1
        {
          let __ingraph_chosen = #seated?;
          return ::core::result::Result::Ok(Self::#ident(__ingraph_chosen));
        }
      }
    });
    let writes = self.members.iter().map(|member| {
      let ident = &member.ident;
      let ty = &member.ty;
      let word = super::seat(&member.ident);
      let seated = quote_spanned! {ty.span()=>
        <#ty as #seat>::__ingraph_seat_value(__ingraph_chosen)
      };
      quote! {
        Self::#ident(__ingraph_chosen) => {
          __ingraph_map.insert(#ag::Name::new(#word), #seated);
        }
      }
    });
    quote! {
      #[automatically_derived]
      impl #ag::InputType for #name {
        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: {
                let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
                #(#fields)*
                __ingraph_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: true,
              directive_invocations: ::std::vec::Vec::new(),
            },
          )
        }

        fn parse(
          __ingraph_value: ::core::option::Option<#ag::Value>,
        ) -> #ag::InputValueResult<Self> {
          if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) =
            __ingraph_value
          {
            #(#reads)*
            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(__ingraph_value),
          ))
        }

        fn to_value(&self) -> #ag::Value {
          let mut __ingraph_map = #ag::indexmap::IndexMap::new();
          match self { #(#writes)* }
          #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 {}
    }
  }
}