ingraph_codegen/element.rs
1//! The ELEMENT MODE's model: what `#[derive(ingraph::Filter)]` emits when the declaration wears
2//! `#[ingraph(operator(<family>))]` — a filter type the DECLARING crate owns, plus the citizenship
3//! its element needs to be an operand at all.
4//!
5//! # The wall this walks around
6//!
7//! A declaring crate's own element could not be filtered under most families, and the reason was the
8//! orphan rule read from one side. `TextFilter<Tag>`, `ScalarFilter<Db>` and `BytesFilter<Sum>` are
9//! FOREIGN types there, so `impl async_graphql::InputType` for any of them is `E0117` — RFC 2451
10//! does not admit `ForeignTrait for ForeignType<Local>`, the trait taking no parameter for a local
11//! type to sit in — and `ingraph` could not write the row either: every one of those faces was one
12//! REGISTRATION PER OPERAND, and the set of a declarer's operands is open.
13//!
14//! The wall is not climbed. This door MINTS `<T>Filter` in the declaring crate, so every impl below
15//! names a local self type and coherence is never in the conversation.
16//!
17//! # The framework has since opened a SECOND road, and this one is not the lesser of the two
18//!
19//! `ingraph`'s three carrier readings — `TextWire`, `ScalarWire`, `BytesWire` — moved every one of
20//! those registrations onto a marker, so a declaring crate can now reach the framework's OWN filter
21//! by writing a reading instead of taking a mint. The two answer different questions and a
22//! declaration picks by what it wants:
23//!
24//! - a MINT gives the element a filter type of its own, with a name and an inherent face the
25//! declaring crate owns, and it is the road for an element that also wants the scalar, the output
26//! crossing and the marker rows this door writes;
27//! - a READING gives the element the framework's own filter under a name the reading chooses, with
28//! no new type at all — one impl where this door emits a dozen.
29//!
30//! Neither is going away, and nothing here changed: this door emits what it always did.
31//!
32//! # What the minted filter HOLDS, and why it is a newtype
33//!
34//! The framework's own filter for the family, at the element — `TagFilter(TextFilter<Tag>)`. The
35//! operation set, the emptiness answer and the lowering map are therefore the framework's, stated
36//! once, and this door adds a face rather than a second implementation of the family. A minted type
37//! whose slots were its own would be the text family's twenty operators written a second time, in a
38//! crate that cannot see when the first ones change.
39//!
40//! # The NULLABLE wall came down, and the ENUM family's ALIAS came down with it
41//!
42//! A newtype's remaining cost used to be the same orphan rule one type over: `Nullable` is the
43//! framework's, so `impl InputType for Nullable<TagFilter>` is `E0117` here, and an `Option<Tag>`
44//! column had no wire face at all. The framework's own answer is `ingraph::NullableFace` — a
45//! delegation trait it writes ONE blanket `Nullable<F>` row over — and this door writes that trait
46//! on the minted filter, whose self type is local. So `Option<Tag>` is spellable now, for the
47//! reason `Option<Codec>` always was, and no family is on the wall.
48//!
49//! The ENUM family used to route AROUND that wall instead of standing off it: its door was a TYPE
50//! ALIAS, `pub type CodecFilter = EnumFilter<Codec>`, so `Nullable<CodecFilter>` was
51//! `Nullable<EnumFilter<Codec>>` and resolved into a row `ingraph` had already written. With the
52//! wall down the detour bought nothing and went on charging three accounts, all of them now closed:
53//!
54//! - **NOMINAL DISTINCTNESS.** An alias is not a type, so an impl written on the door's name was an
55//! impl on `EnumFilter<T>` — `E0119` against the framework's own generic rows, measured in
56//! `ingraph`'s `tests/element_mint_parity.rs`. A row of exactly that shape is how a minted element
57//! reaches a dialect (`tests/nullable_face.rs` writes one for the scalar family), so the enum
58//! family was the one family whose elements could not have a crossing of their own.
59//! - **THE RENAME WORD.** `filter(rename = "…")` moved the RUST name and left the wire name where
60//! `EnumFilter<T>`'s own derivation put it, where the other three families moved both.
61//! - **TWO SHAPES TO MAINTAIN.** Every emission below had to answer *does this family mint*, and
62//! every reader of this file had to carry the answer.
63//!
64//! **The SDL did not move when the alias retired**, and that is arithmetic rather than luck:
65//! `EnumFilter<T>` named itself `<T's schema name>Filter` and a mint names itself
66//! [`RustSafeName::external`], which for an element that renames nothing is the same string. What
67//! the mint adds is that a RENAME now moves it, which is the second account above.
68//!
69//! So there is ONE shape at four doors, and [`ElementModel::emit`] writes it once.
70//!
71//! # WHAT THE MINT HANDS ON, and the two rows that are one decision
72//!
73//! A minted filter is a value somebody else lowers, so the door owes a way OUT of it as well as a
74//! way in. `into_inner` is that way — the held filter taken by value — and it is what every crossing
75//! actually wants: an entry point that lowers a filter consumes it, so a hand-written row reached
76//! through `get` had to clone a value its caller already owned.
77//!
78//! The DECLARED-CONVERTER leg needs one more thing, and it is the same fact stated as a trait:
79//! every crossing entry takes its filter as `TryMapFilter<D, V>` — the wrapper's
80//! (`SqlNullable::<C>::try_from_filter_with`) and, since the byte kinds split, all ten flat ones too
81//! — so an element column with `comparison(<db>(into = "…"))` written on it reaches a bound the mint
82//! has to satisfy, `Option` or not. [`ElementModel::operand_map`] emits that row, delegating through
83//! `into_inner` — which is why the two land together rather than one at a time.
84//!
85//! # The element's OWN citizenship comes with it
86//!
87//! A filter's operand crosses the wire, so the element needs a wire face before its filter can have
88//! one — and that face is the half only the declaring crate can write. It is emitted here for the
89//! same reason `#[derive(ingraph::Enum)]` emits a vocabulary's: it is mechanical from the
90//! declaration, and a door that minted the filter and left the operand to a hand-written `#[Scalar]`
91//! would be a door that does not close.
92//!
93//! The scalar is async-graphql's own attribute over an `impl ScalarType`, which is what a declaring
94//! crate wrote by hand before this door existed — the same tokens, from the same declaration, so the
95//! retirement of a hand impl is a deletion rather than a translation. It also settles the OUTPUT
96//! leg's `boxed-trait` question by not asking it: the attribute runs inside async-graphql and writes
97//! whichever `resolve` shape that build compiled, where an `async fn` written out here would compile
98//! under one of the two.
99//!
100//! # The wire form is the INNER type's, under the ELEMENT's name
101//!
102//! `Tag(String)` crosses as a string, `Db(u32)` as a number, `Sum(Vec<u8>)` as whatever `Vec<u8>`'s
103//! own face renders — the element does not invent a grammar, it names one. The SDL name defaults to
104//! the element's Rust name and is moved by the declaration's own `graphql(rename = "…")`, which is
105//! `#[derive(ingraph::Enum)]`'s word for its reason: a wire type name is a schema commitment, and a
106//! commitment gets a word of its OWN rather than riding on a Rust rename.
107
108use quote::{format_ident, quote};
109use syn::ext::IdentExt as _;
110
111use crate::name::RustSafeName;
112
113#[cfg(test)]
114mod tests;
115
116/// One operator slot of a family: the member the framework's filter holds it in, the name a client
117/// writes, and whether it takes a LIST of operands.
118///
119/// Spelled rather than derived from the member. A wire name is a schema commitment — `in_` is `in`
120/// and `contains_nocase` is `containsNocase` — and a casing function here would be a second author
121/// for a string `ingraph`'s own faces already publish.
122struct Operation {
123 /// The member `ingraph`'s filter holds this operand in, which is also the stem of the accessor
124 /// family this door delegates through.
125 member: &'static str,
126 /// What a client writes.
127 wire: &'static str,
128 /// A LIST slot — `in`/`notIn` — which crosses as a list of operands rather than as one.
129 list: bool,
130}
131
132/// One inline operand slot.
133const fn one(member: &'static str, wire: &'static str) -> Operation {
134 Operation {
135 member,
136 wire,
137 list: false,
138 }
139}
140
141/// One LIST operand slot.
142const fn many(member: &'static str, wire: &'static str) -> Operation {
143 Operation {
144 member,
145 wire,
146 list: true,
147 }
148}
149
150/// The MEMBERSHIP pair every family here ends with, in the order the framework's own faces publish
151/// them.
152const MEMBERSHIP: [Operation; 2] = [many("in_", "in"), many("not_in", "notIn")];
153
154/// The ORDERING + EQUALITY six every family but the enumeration opens with.
155const ORDERED: [Operation; 6] = [
156 one("eq", "eq"),
157 one("ne", "ne"),
158 one("gt", "gt"),
159 one("gte", "gte"),
160 one("lt", "lt"),
161 one("lte", "lte"),
162];
163
164/// A family an ELEMENT may be read under — the word `operator(…)` takes.
165///
166/// FOUR of the framework's eight interpretation words, and the four are measured rather than
167/// chosen. `bool` and `duration` are refused because their filter kinds carry NO OPERAND PARAMETER
168/// — `BooleanFilter`'s operands are `bool` and `DurationFilter`'s are `jiff::SignedDuration`, so
169/// there is no *this kind over the declarer's element* for a minted filter to hold. `list` and `set`
170/// are refused because they are COLLECTION positions rather than elements: what a collection holds
171/// is the question its element answers, and an element mode over one would be asking a declaration
172/// to name itself as its own member.
173///
174/// The refusals are BY NAME at the word, which is what keeps the vocabulary a fact a declaration can
175/// read off a message rather than a list it has to have been told.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub enum ElementFamily {
178 /// A NUMBER: one totally ordered value.
179 Scalar,
180 /// TEXT: one string of characters, with the substring and affix questions.
181 String,
182 /// A BYTE STRING: one opaque run of bytes.
183 Bytes,
184 /// An ENUMERATION: a closed vocabulary, so membership is the whole question.
185 Enum,
186}
187
188impl ElementFamily {
189 /// Every family with an element mode, in the order a refusal lists them.
190 pub const ALL: [Self; 4] = [Self::Scalar, Self::String, Self::Bytes, Self::Enum];
191
192 /// The word a declaration writes inside `operator(…)`.
193 ///
194 /// The interpretation vocabulary's own words, so `operator(string)` and a field's `string` name
195 /// one family — a door with a second spelling would be a second vocabulary to keep in step.
196 pub const fn word(self) -> &'static str {
197 match self {
198 Self::Scalar => "scalar",
199 Self::String => "string",
200 Self::Bytes => "bytes",
201 Self::Enum => "enum",
202 }
203 }
204
205 /// The framework filter the minted type holds.
206 const fn filter(self) -> &'static str {
207 match self {
208 Self::Scalar => "ScalarFilter",
209 Self::String => "TextFilter",
210 Self::Bytes => "BytesFilter",
211 Self::Enum => "EnumFilter",
212 }
213 }
214
215 /// The family trait that carries this element's filter — the map a field's reading resolves
216 /// through.
217 const fn reading(self) -> &'static str {
218 match self {
219 Self::Scalar => "ScalarFilterMarker",
220 Self::String => "StringFilterMarker",
221 Self::Bytes => "BytesFilterMarker",
222 Self::Enum => "EnumFilterMarker",
223 }
224 }
225
226 /// The marker this family's reading is spelled as, which the element's DEFAULT resolves to.
227 const fn marker(self) -> &'static str {
228 match self {
229 Self::Scalar => "ScalarMarker",
230 Self::String => "StringMarker",
231 Self::Bytes => "BytesMarker",
232 Self::Enum => "EnumMarker",
233 }
234 }
235
236 /// This family's operator slots, in the order the framework's own face publishes them — which is
237 /// the order a client reads, the SDL rendering fields as the registry received them.
238 ///
239 /// Answered for EVERY family and SPENT by every one of them: the accessor face, the input
240 /// object's field list and its render are all this list walked. The enumeration's four —
241 /// `eq`, `ne`, `in`, `notIn` — are `EnumFilter<T>`'s own slots in `EnumFilter<T>`'s own order,
242 /// which is what makes the mint's face byte-identical to the alias's on the wire.
243 fn operations(self) -> Vec<Operation> {
244 let mut slots = Vec::new();
245 match self {
246 Self::Scalar => slots.extend(ORDERED),
247 Self::Enum => slots.push(one("eq", "eq")),
248 Self::Bytes | Self::String => {
249 slots.extend(ORDERED);
250 slots.push(one("contains", "contains"));
251 if self == Self::String {
252 slots.push(one("contains_nocase", "containsNocase"));
253 }
254 slots.push(one("not_contains", "notContains"));
255 if self == Self::String {
256 slots.extend([
257 one("not_contains_nocase", "notContainsNocase"),
258 one("starts_with", "startsWith"),
259 one("starts_with_nocase", "startsWithNocase"),
260 one("not_starts_with", "notStartsWith"),
261 one("not_starts_with_nocase", "notStartsWithNocase"),
262 one("ends_with", "endsWith"),
263 one("ends_with_nocase", "endsWithNocase"),
264 one("not_ends_with", "notEndsWith"),
265 one("not_ends_with_nocase", "notEndsWithNocase"),
266 ]);
267 }
268 }
269 }
270 if self == Self::Enum {
271 slots.push(one("ne", "ne"));
272 }
273 slots.extend(MEMBERSHIP);
274 slots
275 }
276}
277
278/// A declared ELEMENT, as the element mode reads it.
279///
280/// PLAIN, for [`StandaloneModel`](crate::standalone::StandaloneModel)'s reason — public fields, no
281/// constructor, no validation. What is checked is checked at the FRONT END, where the tokens an
282/// author wrote are still in hand and a refusal can point at one.
283pub struct ElementModel {
284 /// The declaration's own visibility, which the minted filter takes.
285 pub vis: syn::Visibility,
286 /// The element the faces are OF.
287 pub subject: syn::Ident,
288 /// The `ingraph` root the expansion spells its shelf through.
289 pub krate: syn::Path,
290 /// What the minted filter is called.
291 pub filter: RustSafeName,
292 /// The family this element is read under.
293 pub family: ElementFamily,
294 /// The single field the element holds its value in — positional or named.
295 pub member: syn::Member,
296 /// That field's type, which is what the element crosses the wire AS.
297 pub inner: syn::Type,
298 /// `graphql(rename = "…")` — what a SCHEMA calls this element's scalar, where the declaration
299 /// moved it.
300 ///
301 /// `None` is the Rust name unraw'd, which is what [`ElementModel::sdl`] resolves. EMISSION-ONLY:
302 /// the declared type keeps its name, the minted filter keeps `filter(rename = "…")`, and the two
303 /// crossings are written for the Rust type either way.
304 pub wire_name: Option<String>,
305}
306
307impl ElementModel {
308 /// The shelf path one framework item is spelled through.
309 fn framework(&self, module: &[&str], item: &str) -> proc_macro2::TokenStream {
310 crate::emit::framework(&self.krate, module, item)
311 }
312
313 /// The framework filter this element's minted type holds, at this element.
314 fn held(&self) -> proc_macro2::TokenStream {
315 let kind = self.framework(&["graphql"], self.family.filter());
316 let subject = &self.subject;
317 quote!(#kind<#subject>)
318 }
319
320 /// This element's name as a SCHEMA writes it — the declaration's [`wire_name`](Self::wire_name),
321 /// else the Rust name unraw'd.
322 ///
323 /// The `r#` an unrenamed name drops is Rust's escape for a word that collides with ITS grammar and
324 /// no part of the name.
325 ///
326 /// The knob arrived with the rename-parity ruling, replacing *there is no rename knob, for the
327 /// reason `#[derive(ingraph::Enum)]` has none*. That reason — a wire type name is a schema
328 /// commitment and a Rust rename is not a schema change — is unchanged and is now what the SEPARATE
329 /// word is FOR: `filter(rename = "…")` moves the minted filter's Rust name and the input object it
330 /// publishes, and this moves the scalar, and neither reaches the other's axis.
331 fn sdl(&self) -> String {
332 self
333 .wire_name
334 .clone()
335 .unwrap_or_else(|| self.subject.unraw().to_string())
336 }
337
338 /// The whole element mode, emitted.
339 ///
340 /// ONE SHAPE, at four doors. Half of it belongs to the FILTER — the minted type, its accessor
341 /// face, the emptiness contract, the lowering map, the operand map and the input object — and half
342 /// to the ELEMENT: the readings a field resolves through, and the scalar and the two crossings only
343 /// a declaring crate can write. The family decides what is IN each item and never which items
344 /// there are.
345 pub fn emit(&self) -> proc_macro2::TokenStream {
346 let declaration = self.declaration();
347 let face = self.inherent();
348 let contract = self.emptiness();
349 let lowering = self.lowering();
350 let operands = self.operand_map();
351 let readings = self.readings();
352 let wire = self.wire();
353 quote! {
354 #declaration
355 #face
356 #contract
357 #lowering
358 #operands
359 #readings
360 #wire
361 }
362 }
363
364 /// The filter this door puts the element's name on — a NEWTYPE, at every family.
365 ///
366 /// # The newtype, and its member
367 ///
368 /// A newtype over the framework's own filter for the family, whose member is `pub(crate)` — the
369 /// three-layer naming law's substrate visibility, so a sibling expansion reads it and a downstream
370 /// crate spends the accessor face beside it.
371 ///
372 /// The three derives are CONDITIONAL on the element through the newtype's own field, exactly as
373 /// the held filter's are: an element with no `Debug` mints a filter with none, and nothing here
374 /// demands one.
375 ///
376 /// # The ORPHAN RULE is why it is a newtype, and the wall it used to cost is down
377 ///
378 /// A newtype's whole cost WAS the orphan rule at its NULLABLE twin. `Nullable` is the framework's
379 /// and `TagFilter` is the declarer's, so `impl InputType for Nullable<TagFilter>` is `E0117` in
380 /// the declaring crate and unwritable in `ingraph`, which has never heard of the element — so an
381 /// OPTIONAL column of a minted element had no wire face. The enum family was off that wall by
382 /// ALIASING — `ingraph` carries a generic row over `Nullable<EnumFilter<T>>` and an alias resolves
383 /// INTO it — and every family is off it now through `ingraph::NullableFace`, which
384 /// [`filter_face`](Self::filter_face) writes on the minted type. With the wall down the alias was
385 /// a detour to nowhere, and the module note lists the three accounts it went on charging.
386 ///
387 /// # `filter(rename = "…")` moves BOTH names, at every family
388 ///
389 /// The word is the struct mode's and means the same thing here: the minted type takes the name,
390 /// and [`filter_face`](Self::filter_face) publishes [`RustSafeName::external`] as the SDL name, so
391 /// the schema follows the declaration. An element that renames nothing keeps
392 /// `<Element>Filter` — the convention [`crate::model::default_filter_name`] mints — which is the
393 /// string `EnumFilter<T>`'s own derivation used to produce, so the retirement of the alias moved
394 /// no schema.
395 fn declaration(&self) -> proc_macro2::TokenStream {
396 let vis = &self.vis;
397 let name = self.filter.safe();
398 let held = self.held();
399 let subject = &self.subject;
400 let doc = format!(
401 "The `{}` reading of [`{subject}`], as a client writes one — the framework's own {} filter \
402 over an element this crate declares.",
403 self.family.word(),
404 self.family.word()
405 );
406 // The visibility is the DECLARATION's rather than a fixed `pub`: an element a crate keeps to
407 // itself mints a filter it keeps to itself.
408 quote! {
409 #[doc = #doc]
410 #[derive(Debug, Clone, PartialEq)]
411 #vis struct #name(pub(crate) #held);
412
413 #[automatically_derived]
414 impl ::core::default::Default for #name {
415 #[inline]
416 fn default() -> Self {
417 Self::new()
418 }
419 }
420 }
421 }
422
423 /// The minted filter's own face: the empty filter, the emptiness question, and one accessor family
424 /// per operator the family has.
425 ///
426 /// Every one of them DELEGATES. The held filter answers, so a minted type cannot come to mean
427 /// something the framework's own does not — and an operator renamed upstream is a compile failure
428 /// in the declaring crate rather than a face that quietly lost a slot.
429 fn inherent(&self) -> proc_macro2::TokenStream {
430 let name = self.filter.safe();
431 let held = self.held();
432 let subject = &self.subject;
433 let slots = self.family.operations().into_iter().map(|slot| {
434 let member = format_ident!("{}", slot.member);
435 let with = format_ident!("with_{}", slot.member);
436 let maybe = format_ident!("maybe_{}", slot.member);
437 let read = format!(
438 "The `{}` operand{}, or `None` while the operator is absent.",
439 slot.wire,
440 if slot.list { "s" } else { "" }
441 );
442 let set = format!("Set `{}` to `Some(value)` (consuming).", slot.wire);
443 let assign = format!("Assign the raw `{}` option (consuming).", slot.wire);
444 if slot.list {
445 quote! {
446 #[doc = #read]
447 #[inline]
448 pub fn #member(&self) -> ::core::option::Option<&[#subject]> {
449 self.0.#member()
450 }
451
452 #[doc = #set]
453 #[must_use]
454 #[inline]
455 pub fn #with(self, value: impl ::core::convert::Into<::std::boxed::Box<[#subject]>>) -> Self {
456 Self(self.0.#with(value))
457 }
458
459 #[doc = #assign]
460 #[must_use]
461 #[inline]
462 pub fn #maybe(
463 self,
464 value: ::core::option::Option<impl ::core::convert::Into<::std::boxed::Box<[#subject]>>>,
465 ) -> Self {
466 Self(self.0.#maybe(value))
467 }
468 }
469 } else {
470 quote! {
471 #[doc = #read]
472 #[inline]
473 pub fn #member(&self) -> ::core::option::Option<&#subject> {
474 self.0.#member()
475 }
476
477 #[doc = #set]
478 #[must_use]
479 #[inline]
480 pub fn #with(self, value: #subject) -> Self {
481 Self(self.0.#with(value))
482 }
483
484 #[doc = #assign]
485 #[must_use]
486 #[inline]
487 pub fn #maybe(self, value: ::core::option::Option<#subject>) -> Self {
488 Self(self.0.#maybe(value))
489 }
490 }
491 }
492 });
493 quote! {
494 #[automatically_derived]
495 impl #name {
496 /// The empty filter — no operator set.
497 #[inline]
498 #[must_use]
499 pub const fn new() -> Self {
500 Self(<#held>::new())
501 }
502
503 /// True while NO operator slot is set — so a lowering would emit nothing for this field.
504 #[inline]
505 #[must_use]
506 pub const fn is_empty(&self) -> bool {
507 self.0.is_empty()
508 }
509
510 /// The framework filter this reading holds, for a caller that needs the family's own type.
511 #[inline]
512 #[must_use]
513 pub const fn get(&self) -> &#held {
514 &self.0
515 }
516
517 /// The framework filter this reading holds, TAKEN OUT — the owning projection beside
518 /// `get`.
519 ///
520 /// What a crossing needs. Every entry point that lowers a filter consumes it, so a
521 /// hand-written row reached through `get` had to `.clone()` the held filter to hand it on
522 /// — a copy of a value the caller already owned, and one that put a `Clone` demand on the
523 /// element where the crossing itself has none.
524 #[inline]
525 #[must_use]
526 pub fn into_inner(self) -> #held {
527 self.0
528 }
529
530 #(#slots)*
531 }
532 }
533 }
534
535 /// The emptiness contract, asked where the FILTER ITSELF is a parameter.
536 fn emptiness(&self) -> proc_macro2::TokenStream {
537 let name = self.filter.safe();
538 let contract = self.framework(&["graphql"], "GraphqlFilter");
539 quote! {
540 #[automatically_derived]
541 impl #contract for #name {
542 #[inline]
543 fn is_empty(&self) -> bool {
544 Self::is_empty(self)
545 }
546 }
547 }
548 }
549
550 /// The LOWERING map, delegated to the held filter.
551 ///
552 /// The type-level half and only it, which is the half a minted filter can carry: the VALUE-level
553 /// crossing's self type is the framework's own comparison, so `TryFromFilter<TagFilter> for
554 /// SqlTextComparison<…>` is `E0117` in a declaring crate and unwritable in `ingraph`, which has
555 /// never heard of `TagFilter`. A column of an element reaches a dialect through the held filter's
556 /// own crossing, which is what `into_inner` is for.
557 fn lowering(&self) -> proc_macro2::TokenStream {
558 let name = self.filter.safe();
559 let held = self.held();
560 let backend = self.framework(&["comparison"], "Backend");
561 let map = self.framework(&["comparison"], "ToDatabaseComparison");
562 let value = crate::emit::parameter("V");
563 let db = crate::emit::parameter("DB");
564 quote! {
565 #[automatically_derived]
566 impl<#value, #db> #map<#value, #db> for #name
567 where
568 #db: #backend,
569 #held: #map<#value, #db>,
570 {
571 type Comparison = <#held as #map<#value, #db>>::Comparison;
572 }
573 }
574 }
575
576 /// The OPERAND MAP, delegated to the held filter — the row a DECLARED CONVERTER is spent
577 /// through.
578 ///
579 /// # What it is for, and the leg that could not be walked without it
580 ///
581 /// `graphql(input(comparison(<db>(into = "…"))))` names a function from the DOMAIN operand to the
582 /// STORED one, and the emitted crossing spends it at the wrapper's entry point —
583 /// `SqlNullable::<C>::try_from_filter_with(filter, f)`, whose wrapped filter is the generic
584 /// `F: TryMapFilter<D, V>`. A minted filter is the type in that position for an `Option<element>`
585 /// column, so without this row the declared word reaches a bound the mint does not satisfy, and a
586 /// declaration is refused inside its own expansion at a span its author cannot edit.
587 ///
588 /// It was WRITABLE by hand before — `ingraph`'s `tests/element_nullable_enum.rs` carried exactly
589 /// this impl — and what it cost was one hand-written row per element per stored type, in a crate
590 /// that gets no help spelling it. The mint writes it because the row is mechanical: the held
591 /// filter maps, and the mint hands it the operands.
592 ///
593 /// LOAD-BEARING, measured by deleting it rather than argued: with this emission suppressed and
594 /// that file's hand row gone, its `#[ingraph::record]` is refused inside its own expansion —
595 ///
596 /// ```text
597 /// error[E0277]: the trait bound `CodecFilter: TryMapFilter<_, _>` is not satisfied
598 /// --> ingraph/tests/element_nullable_enum.rs:94:1
599 /// --> ingraph/src/comparison/sql/nullable.rs:95:8
600 /// ```
601 ///
602 /// — at the declaration's own span, naming the seam this row fills.
603 ///
604 /// # It DELEGATES, so the mint cannot come to mean something the framework's own does not
605 ///
606 /// `Mapped` is the held filter's own answer rather than a spelling of this door's — the enum
607 /// family maps into `EnumFilter<V>` and the bytes family into `BytesFilter<V, K, I>`, and a
608 /// projection is what keeps this door out of that decision. The value half is one call through
609 /// `into_inner`, which is the whole reason that projection exists.
610 ///
611 /// # It costs the mint one blanket row of nominal distinctness, deliberately
612 ///
613 /// A declaring crate can no longer write its own `TryMapFilter` over a minted filter — this one
614 /// is `E0119` against it. That is the trade the ruling takes: the hand row this replaces was the
615 /// SAME delegation every time, so what a declarer loses is the ability to write a DIFFERENT
616 /// operand map for an element than the family it declared. The rows a declarer still owns, and
617 /// which no blanket here touches, are the dialect crossings — `TryFromFilter<TagFilter> for
618 /// SqlTextComparison<…>` and its siblings, which name a foreign self type and are the whole of
619 /// what the mint's own name buys.
620 ///
621 /// # WHAT IT NOW CLOSES — the FLAT column's declared leg, on the day `ingraph` generalised
622 ///
623 /// A NON-nullable element column with a declared converter used to stop one type over: the flat
624 /// kinds' entry point was
625 /// `SqlEnumComparison::<V, Db>::try_from_filter_with(filter: EnumFilter<D>, f)` — the filter
626 /// parameter NAMED rather than generic — so a minted filter arriving there was `E0308` whatever it
627 /// implemented, and only the WRAPPER's entry (`SqlNullable`) took `F: TryMapFilter<D, V>`.
628 ///
629 /// Every flat entry takes a BOUND now — `X: TryMapFilter<D, V, Mapped = <the kind's own filter>>`
630 /// — so this row is what a minted filter reaches all ten of them by. Ten and not eight, because
631 /// the byte families split by slot legality: one entry per (kind × dialect), each byte one serving
632 /// `BytesFilter` and `FixedBytesFilter` alike.
633 ///
634 /// The wall that deferred it was the two BYTES kinds READING the filter before mapping it —
635 /// `filter.contains()` against `K::SUBSTRING`, `filter.gt()` against `K::BYTEWISE`. The type split
636 /// deleted the first (a fixed-width filter has no substring field) and the second const with it;
637 /// MongoDB's own two refusals survive, and that entry normalises through the identity map so they
638 /// still run BEFORE the operands convert. `ingraph/tests/flat_crossings.rs` is where the wall was
639 /// measured and where its absence is asserted.
640 ///
641 /// What a declarer still writes by hand is the DEFAULT leg's dialect crossing —
642 /// `TryFromFilter<CodecFilter> for SqlEnumComparison<…>`, which `ingraph-derive`'s
643 /// `tests/fixtures.rs` writes twice — and that row is not a gap: it names a foreign self type, and
644 /// it is the whole of what the mint's own name buys. See the section below.
645 fn operand_map(&self) -> proc_macro2::TokenStream {
646 let name = self.filter.safe();
647 let held = self.held();
648 let subject = &self.subject;
649 let map = self.framework(&["graphql"], "TryMapFilter");
650 let stored = crate::emit::parameter("STORED");
651 let refusal = crate::emit::parameter("REFUSAL");
652 let convert = crate::emit::parameter("CONVERT");
653 quote! {
654 #[automatically_derived]
655 impl<#stored> #map<#subject, #stored> for #name {
656 type Mapped = <#held as #map<#subject, #stored>>::Mapped;
657
658 #[inline]
659 fn try_map_filter<#refusal, #convert>(
660 self,
661 __ingraph_convert: #convert,
662 ) -> ::core::result::Result<Self::Mapped, #refusal>
663 where
664 #convert: ::core::ops::FnMut(#subject) -> ::core::result::Result<#stored, #refusal>,
665 {
666 <#held as #map<#subject, #stored>>::try_map_filter(
667 Self::into_inner(self),
668 __ingraph_convert,
669 )
670 }
671 }
672 }
673 }
674
675 /// The two rows a FIELD of this element resolves through: the family's own map, and the default
676 /// reading a declaration that writes no word takes.
677 fn readings(&self) -> proc_macro2::TokenStream {
678 let name = self.filter.safe();
679 let subject = &self.subject;
680 let reading = self.framework(&["marker"], self.family.reading());
681 let default = self.framework(&["marker"], "DefaultMarker");
682 let marker = self.framework(&["marker"], self.family.marker());
683 quote! {
684 #[automatically_derived]
685 impl #reading for #subject {
686 type Filter = #name;
687 }
688
689 #[automatically_derived]
690 impl #default for #subject {
691 type Marker = #marker<#subject>;
692 }
693 }
694 }
695
696 /// The WIRE half, behind the binding gate: the element's own scalar, the two crossings, and the
697 /// minted filter's input object.
698 ///
699 /// The input object is why the type is minted at all — the same face over the framework's own
700 /// `EnumFilter<Element>` would be `E0119` against `ingraph`'s generic row and `E0117` in the
701 /// declaring crate besides — so it rides here for every family alike.
702 ///
703 /// Inside an anonymous `const`, which is where an emission puts everything it does not owe the
704 /// declaring scope a name for.
705 fn wire(&self) -> proc_macro2::TokenStream {
706 let gate = self.framework(&["gate"], "if_async_graphql");
707 let scalar = self.scalar();
708 let input = self.input_crossing();
709 let output = self.output_crossing();
710 let face = self.filter_face();
711 quote! {
712 const _: () = {
713 #gate! {
714 #scalar
715 #input
716 #output
717 #face
718 }
719 };
720 }
721 }
722
723 /// The ELEMENT's own scalar — the half only the declaring crate can write.
724 ///
725 /// async-graphql's own attribute over an `impl ScalarType`, which is the shape a declaring crate
726 /// wrote by hand before this door existed. Two things follow from spending the library's macro
727 /// rather than writing the two faces out: the OUTPUT leg is whichever `resolve` shape that build
728 /// compiled — the `boxed-trait` fork a hand-written `async fn` can only pick one side of — and the
729 /// registry entry is the library's own, so a schema's scalar entry cannot drift from what that
730 /// version of async-graphql publishes.
731 ///
732 /// The wire GRAMMAR is the inner type's: the element parses whatever its held type parses and
733 /// renders whatever that renders, under a name of its own. So `Tag(String)` is a string named
734 /// `Tag`, and an inner type with no wire face of its own is `E0277` here, naming that type.
735 fn scalar(&self) -> proc_macro2::TokenStream {
736 let subject = &self.subject;
737 let inner = &self.inner;
738 let ag = self.framework(&[], "async_graphql");
739 let shelf = crate::emit::vendored(&self.krate, "async_graphql");
740 let sdl = self.sdl();
741 let build = match &self.member {
742 syn::Member::Named(ident) => quote!(|__ingraph_inner| Self { #ident: __ingraph_inner }),
743 syn::Member::Unnamed(_) => quote!(Self),
744 };
745 let member = &self.member;
746 quote! {
747 #[#ag::Scalar(crate = #shelf, name = #sdl)]
748 impl #ag::ScalarType for #subject {
749 fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
750 ::core::result::Result::map_err(
751 ::core::result::Result::map(
752 <#inner as #ag::InputType>::parse(::core::option::Option::Some(__ingraph_value)),
753 #build,
754 ),
755 #ag::InputValueError::propagate,
756 )
757 }
758
759 fn to_value(&self) -> #ag::Value {
760 <#inner as #ag::InputType>::to_value(&self.#member)
761 }
762 }
763 }
764 }
765
766 /// The INPUT CROSSING's row — what ONE OPERAND of this element looks like on the wire.
767 ///
768 /// The IDENTITY, for the reason a declared vocabulary's is the identity: the row above gives the
769 /// element a wire face of its own, so the form it crosses as IS the type. It is owed by a
770 /// COLLECTION of this element, whose slots ask the element rather than `InputType` — which is what
771 /// lets an operand with no face of its own cross through a carrier, and what makes every element
772 /// owe the row alike.
773 fn input_crossing(&self) -> proc_macro2::TokenStream {
774 let subject = &self.subject;
775 let crossing = self.framework(&["graphql"], "ToGraphqlInput");
776 quote! {
777 #[automatically_derived]
778 impl #crossing for #subject {
779 type Input = Self;
780 type Error = ::core::convert::Infallible;
781
782 #[inline]
783 fn cross(
784 __ingraph_value: Self,
785 ) -> ::core::result::Result<Self, ::core::convert::Infallible> {
786 ::core::result::Result::Ok(__ingraph_value)
787 }
788
789 #[inline]
790 fn carry(__ingraph_value: &Self) -> Self {
791 ::core::clone::Clone::clone(__ingraph_value)
792 }
793 }
794 }
795 }
796
797 /// The OUTPUT CROSSING's row — what a wire face RETURNS a value of this element as.
798 ///
799 /// By REFERENCE, which is what keeps a row's elements free of a clone per response, and the
800 /// identity for the input crossing's reason: the scalar above is already the form a resolver
801 /// renders.
802 fn output_crossing(&self) -> proc_macro2::TokenStream {
803 let subject = &self.subject;
804 let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
805 quote! {
806 #[automatically_derived]
807 impl #crossing for #subject {
808 type Output<'__ingraph> = &'__ingraph Self;
809
810 #[inline]
811 fn to_graphql_output(__ingraph_value: &Self) -> &Self {
812 __ingraph_value
813 }
814 }
815 }
816 }
817
818 /// The minted filter's INPUT OBJECT — the face the whole mode exists to make writable.
819 ///
820 /// A LOCAL self type, so the orphan wall never appears: the same impl over the framework's own
821 /// `TextFilter<Tag>` is `E0117` here, and `ingraph` reaches that type only through a READING — a
822 /// marker the declaring crate owns, which is the module note's second road and not this one.
823 ///
824 /// Its slots are typed `Option<Element>` and read through async-graphql's own wrappers, because
825 /// the element HAS a face by the time this one is registered — so the operand's grammar is stated
826 /// once, in the scalar above, and this face spends it.
827 ///
828 /// The `Nullable` twin comes with it, through the DELEGATION TRAIT — and that is the road this
829 /// note used to record as unbuilt.
830 ///
831 /// The wall was the orphan rule one type over: `Nullable` is the framework's, so
832 /// `impl InputType for Nullable<TagFilter>` names a foreign type parameterised by a local one and
833 /// is `E0117` here, while a per-concrete row in `ingraph` cannot be written for a filter that
834 /// crate has never heard of. What blocked the generic row there was `E0119` against the concrete
835 /// rows its own builtins minted — so those rows moved onto `NullableFace` and the generic one is
836 /// unopposed. This door writes that trait on the MINTED filter, whose self type is local, and an
837 /// `Option<Tag>` column reaches its face through the framework's single blanket.
838 ///
839 /// So `bare_fields` and `bare_values` are where the field list and the render live, and the
840 /// `InputType` pair reads both back off the row: one list, published by the bare face and by its
841 /// nullable twin alike.
842 ///
843 /// # The SHORTHAND LAW reaches a minted face
844 ///
845 /// `parse` reads what arrived through the framework's own `sent`, so a client writes `42` where
846 /// this face means `{ eq: 42 }` exactly as it may at a framework column. The bare value is put
847 /// under the FIRST slot's name and the ordinary reads run over that object, so the operand
848 /// crosses through the same grammar the longhand takes rather than through a second reading of
849 /// it. Rule ② is refused here and acted on by the nullable twin, which is nullability being a
850 /// TYPE said at the parse.
851 fn filter_face(&self) -> proc_macro2::TokenStream {
852 let name = self.filter.safe();
853 let subject = &self.subject;
854 let held = self.held();
855 let ag = self.framework(&[], "async_graphql");
856 let nullable_face = self.framework(&["graphql"], "NullableFace");
857 let sent = self.framework(&["graphql", "filter"], "sent");
858 let sent_ty = self.framework(&["graphql", "filter"], "Sent");
859 let sdl = self.filter.external().to_owned();
860 let slots = self.family.operations();
861 // The slot a BARE value lands in — `eq` at every family, read off the list rather than spelled
862 // here so the shorthand and the registration cannot come to name different slots. `operations`
863 // answers with at least one row for every family, so the `expect` below is unreachable.
864 let bare = slots
865 .first()
866 .expect("an element family publishes at least one operator slot")
867 .wire;
868
869 let fields = slots.iter().map(|slot| {
870 let wire = slot.wire;
871 let ty = Self::slot_type("e!(#subject), slot.list);
872 quote! {
873 __ingraph_fields.insert(
874 ::std::string::String::from(#wire),
875 #ag::registry::MetaInputValue {
876 name: ::std::string::String::from(#wire),
877 description: ::core::option::Option::None,
878 ty: <#ty as #ag::InputType>::create_type_info(__ingraph_registry),
879 deprecation: #ag::registry::Deprecation::NoDeprecated,
880 default_value: ::core::option::Option::None,
881 visible: ::core::option::Option::None,
882 inaccessible: false,
883 tags: ::std::vec::Vec::new(),
884 is_secret: false,
885 directive_invocations: ::std::vec::Vec::new(),
886 },
887 );
888 }
889 });
890
891 let reads = slots.iter().map(|slot| {
892 let wire = slot.wire;
893 let maybe = format_ident!("maybe_{}", slot.member);
894 let ty = Self::slot_type("e!(#subject), slot.list);
895 quote! {
896 __ingraph_held = __ingraph_held.#maybe(
897 ::core::result::Result::map_err(
898 <#ty as #ag::InputType>::parse(
899 #ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
900 ),
901 #ag::InputValueError::propagate,
902 )?,
903 );
904 }
905 });
906
907 let writes = slots.iter().map(|slot| {
908 let wire = slot.wire;
909 let member = format_ident!("{}", slot.member);
910 // Method calls rather than the fully qualified forms the rest of this emission writes:
911 // `Option::cloned` is defined twice — once for `Option<&T>` and once for `Option<&mut T>` —
912 // so the qualified spelling is `E0034` and only the receiver disambiguates it.
913 // The box's own type is SPELLED at the conversion: `Box::from` alone leaves the allocator
914 // parameter free, and three of async-graphql's `Box` rows then apply at once (`E0283`).
915 let held = if slot.list {
916 quote!(self.0.#member().map(<::std::boxed::Box<[#subject]>>::from))
917 } else {
918 quote!(self.0.#member().cloned())
919 };
920 quote! {
921 __ingraph_map.insert(#ag::Name::new(#wire), #ag::InputType::to_value(&#held));
922 }
923 });
924
925 quote! {
926 #[automatically_derived]
927 impl #ag::InputType for #name {
928 type RawValueType = Self;
929
930 #[inline]
931 fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
932 ::std::borrow::Cow::Borrowed(#sdl)
933 }
934
935 fn create_type_info(
936 __ingraph_registry: &mut #ag::registry::Registry,
937 ) -> ::std::string::String {
938 __ingraph_registry.create_input_type::<Self, _>(
939 #ag::registry::MetaTypeId::InputObject,
940 |__ingraph_registry| #ag::registry::MetaType::InputObject {
941 name: ::std::string::String::from(#sdl),
942 description: ::core::option::Option::None,
943 input_fields: <Self as #nullable_face>::bare_fields(__ingraph_registry),
944 visible: ::core::option::Option::None,
945 inaccessible: false,
946 tags: ::std::vec::Vec::new(),
947 rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
948 oneof: false,
949 directive_invocations: ::std::vec::Vec::new(),
950 },
951 )
952 }
953
954 fn parse(
955 __ingraph_value: ::core::option::Option<#ag::Value>,
956 ) -> #ag::InputValueResult<Self> {
957 let __ingraph_object = match #sent(__ingraph_value) {
958 #sent_ty::Longhand(__ingraph_object) => __ingraph_object,
959 // Rule ① — a bare value is this face's `eq`, put under that key so the reads below
960 // cross it through the same grammar the longhand takes rather than through a second
961 // reading of the operand.
962 #sent_ty::Bare(__ingraph_bare) => {
963 let mut __ingraph_object = #ag::indexmap::IndexMap::new();
964 #ag::indexmap::IndexMap::insert(
965 &mut __ingraph_object,
966 #ag::Name::new(#bare),
967 __ingraph_bare,
968 );
969 __ingraph_object
970 }
971 // Rule ② is REFUSED here and acted on by the nullable twin: a `NOT NULL` column has no
972 // null test to set, which is nullability being a TYPE said at the parse.
973 #sent_ty::Null => {
974 return ::core::result::Result::Err(#ag::InputValueError::expected_type(
975 #ag::Value::Null,
976 ));
977 }
978 #sent_ty::Refused(__ingraph_sent) => {
979 return ::core::result::Result::Err(#ag::InputValueError::expected_type(
980 __ingraph_sent,
981 ));
982 }
983 };
984 let mut __ingraph_held = <#held>::new();
985 #(#reads)*
986 ::core::result::Result::Ok(Self(__ingraph_held))
987 }
988
989 fn to_value(&self) -> #ag::Value {
990 #ag::Value::Object(<Self as #nullable_face>::bare_values(self))
991 }
992
993 #[inline]
994 fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
995 ::core::option::Option::Some(self)
996 }
997 }
998
999 #[automatically_derived]
1000 impl #ag::InputObjectType for #name {}
1001
1002 #[automatically_derived]
1003 impl #nullable_face for #name {
1004 fn bare_fields(
1005 __ingraph_registry: &mut #ag::registry::Registry,
1006 ) -> #ag::indexmap::IndexMap<::std::string::String, #ag::registry::MetaInputValue> {
1007 let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
1008 #(#fields)*
1009 __ingraph_fields
1010 }
1011
1012 fn bare_values(&self) -> #ag::indexmap::IndexMap<#ag::Name, #ag::Value> {
1013 let mut __ingraph_map = #ag::indexmap::IndexMap::new();
1014 #(#writes)*
1015 __ingraph_map
1016 }
1017 }
1018 }
1019 }
1020
1021 /// What ONE slot crosses as — an operand, or a list of them.
1022 fn slot_type(subject: &proc_macro2::TokenStream, list: bool) -> proc_macro2::TokenStream {
1023 if list {
1024 quote!(::core::option::Option<::std::boxed::Box<[#subject]>>)
1025 } else {
1026 quote!(::core::option::Option<#subject>)
1027 }
1028 }
1029}