ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
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
//! Validating a payload-carrying enum into the union model the emitter consumes.
//!
//! ```text
//! #[derive(ingraph::Union)]
//! #[ingraph(
//!   crate = "path::to::ingraph",
//!   unwrap_error(rename = "NoSuchSide"),
//!   graphql(async_graphql(output, input(rename = "SideChoice"))),
//! )]
//! ```
//!
//! Everything else here is SHAPE, and the shape is [`crate::members`]' — a union's declaration IS
//! its member set, which is the same Rust shape an INTERFACE declares, so one walk enforces both
//! and each derive states its own law. What this module owns of that is [`FAMILY`]: the sentences
//! GraphQL's own type validation supplies, quoted rather than paraphrased — *A Union type must
//! include one or more unique member types* is the empty union's refusal and the duplicated
//! member's both.
//!
//! # A DERIVE, where the interface beside it is an attribute
//!
//! `#[derive(ingraph::Enum)]`'s own doctrine, applied: the declaration family are attribute macros
//! because those words REWRITE the item they sit on, and this one rewrites NOTHING — it adds impls
//! beside a type somebody else wrote. So the options are read off the `#[ingraph(…)]` beside the
//! enum rather than out of a macro's arguments, and they stay on the item, inert, where an attribute
//! macro's echo would have had to strip them.
//!
//! An INTERFACE is not migrating with it and the reason is not inertia: its emission is a contract
//! over the members, which is a different declaration with different semantics and a different wire,
//! and nothing in this round touches any of the three.
//!
//! # `graphql(<backend>(input, output))` — the SUB-AXIS, and it is general
//!
//! `input` and `output` are the two SCHEMA POSITIONS, and they are entries of a BACKEND's block
//! rather than of the `graphql(…)` domain above it: which positions a type is rendered at is a
//! backend's own rendering, exactly as `attrs(…)` and `skip` are on the record's grammar. The axis
//! law is the tree's — a DOMAIN block, then a BACKEND block, then that cell's entries — and today
//! the union is the only declaration that consumes this pair. A grammar that grows a second consumer
//! writes the same two words at the same depth.

use ingraph_codegen::{
  model::GraphqlKind,
  union::{UnionInput, UnionModel, UnionOutput, UnionSkin},
};

use crate::{
  attribute,
  errors::Errors,
  members::{self, Family},
  value,
};

#[cfg(test)]
mod graphql_tests;
#[cfg(test)]
mod tests;

/// The union's own words for the rules [`crate::members`] enforces.
const FAMILY: Family = Family {
  derive: "#[derive(ingraph::Union)]",
  noun: "union",
  possessive: "A union's",
  not_an_enum: "a union IS its member set, one variant per member, and a struct declares no \
                alternatives at all",
  empty: "GraphQL's own law is that a union type must include ONE OR MORE unique member types, and \
          Rust's is that an enum with no variants has no value to be",
  several: "A union is a choice BETWEEN member types, so an alternative holding two of them is a \
            member type nobody declared; the wire shape a declared union renders as takes a \
            single-value tuple variant, at both positions a schema has for one. Declare the pair \
            as a type of its own and carry that",
  positional: "A variant's one member is the whole of what it holds, so there is nothing for a \
               field name to tell it apart from, and the wire shape a declared union renders as \
               takes a single-value tuple variant.",
  variant_entry: "a variant takes none. A member is named by the TYPE it carries, and nothing in \
                  this half spells a word for one",
  duplicate: "GraphQL's law is that a union type must include one or more UNIQUE member types, so \
              a schema built from this would name that member twice and no query could say which \
              variant it meant",
  generic: "a union's members are the TYPES its variants carry, and a parameter is not one until \
            it is substituted; the uniqueness a member set must have cannot be decided before \
            that, since `Pick<A, B>` is one member twice at `A = B`",
};

/// The two SCHEMA POSITIONS a backend block may dress a union for.
const POSITIONS: [&str; 2] = ["output", "input"];

/// Validate a decorated enum into the model the emitter consumes.
///
/// # Errors
/// A [`syn::Error`] carrying EVERY rule the pass could still see violated, each spanned at the
/// token that violated it, so one compile reports the whole declaration's problems.
pub(crate) fn parse(input: &syn::DeriveInput) -> syn::Result<UnionModel> {
  let mut errors = Errors::default();
  let Options {
    krate,
    error,
    graphql,
  } = options(&input.attrs, &mut errors);
  members::concrete(&FAMILY, &input.generics, &mut errors);

  let members = match members::members(&FAMILY, input, &mut errors) {
    Ok(members) => members,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  members::collisions(&FAMILY, &members, &mut errors);

  let model = UnionModel {
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    vis: input.vis.clone(),
    name: input.ident.clone(),
    members,
    error,
    graphql,
  };
  emitted_names(&model, &mut errors);
  errors.into_result(model)
}

/// What the enum-level attribute can say.
#[derive(Default)]
struct Options {
  /// `crate = "…"` — where `ingraph` lives, for the paths the WIRE half emits.
  krate: Option<syn::Path>,
  /// `unwrap_error(rename = "…")` — what the emitted refusal type is called.
  error: Option<syn::Ident>,
  /// `graphql(…)` — which backends dress this union, and at which positions.
  graphql: Vec<UnionSkin>,
}

/// Walk the enum-level attribute.
///
/// The refusal knob is [`members::refusal_knob`]'s, which is also where the migration off the old
/// `error` spelling is stated: that word names CONVERSION CELLS now, one per leg inside a database's
/// block, and a knob sharing it would be told apart by depth alone.
///
/// `crate = "…"` is here because the WIRE ROUND bought it. While the whole emission was `core` there
/// was nothing for the option to move and it was refused as an unknown entry; a declared face names
/// `#krate::__private::async_graphql` and the gate it rides, so the option is read now. It is read
/// UNCONDITIONALLY, `graphql(…)` or not: which crate an expansion is rooted at is a constant of the
/// grammar rather than an entry whose meaning depends on its neighbours, which is how
/// `#[derive(ingraph::Enum)]` takes it too.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
  let mut options = Options::default();
  let mut graphql_at: Option<syn::Path> = None;

  attribute::walk(attrs, errors, |meta, errors| {
    if let Some(walked) = members::refusal_knob(&meta, &mut options.error, errors) {
      return walked;
    }

    // `crate` is a keyword; syn's nested-meta path parser takes it with `Ident::parse_any`, so it
    // arrives here as an ordinary one-segment path.
    if meta.path.is_ident("crate") {
      match value::parse_literal::<syn::Path>(&meta, CRATE_PATH) {
        Ok(path) => {
          attribute::set_once(&mut options.krate, path, &meta.path, CRATE_ONCE, errors);
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    if meta.path.is_ident("graphql") {
      if graphql_at.is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`graphql(…)` is declared more than once — one block holds every backend, and a second \
           one could only repeat or contradict the first",
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      graphql_at = Some(meta.path.clone());
      return backends(&meta, &mut options.graphql, errors);
    }

    errors.push(attribute::unknown(
      &meta,
      "unknown entry in `#[ingraph(…)]` on a union — it takes `unwrap_error(rename = \"…\")`, \
       `graphql(…)` and `crate = \"…\"`. A union declares no storage and no words: its members are \
       TYPES, and what a declaration adds to them is which SCHEMA POSITIONS the union is rendered at",
      &["unwrap_error", "graphql", "crate"],
    ));
    Ok(())
  });

  options
}

/// What `crate = "…"` has to be.
const CRATE_PATH: &str =
  "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";

/// The refusal for a crate named twice.
const CRATE_ONCE: &str = "`crate` is declared more than once — one declaration names one crate";

/// The `graphql(…)` block — one entry per backend this union is dressed for.
fn backends(
  meta: &syn::meta::ParseNestedMeta<'_>,
  graphql: &mut Vec<UnionSkin>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let walked = attribute::options(meta, |inner| {
    let Some(kind) = crate::parse::graphql_kind(&inner.path) else {
      errors.push(attribute::unknown(
        &inner,
        "unknown backend in `graphql(…)` — a wire face is one backend's impls, and a word naming \
         none of them names no skin",
        &GraphqlKind::ALL.map(GraphqlKind::as_str),
      ));
      return Ok(());
    };
    if graphql.iter().any(|skin| skin.kind == kind) {
      errors.push(syn::Error::new_spanned(
        &inner.path,
        format!(
          "`{kind}` is declared more than once in `graphql(…)` — one word per backend, because a \
           backend has ONE skin and a second word could only re-describe it",
          kind = kind.as_str(),
        ),
      ));
      attribute::skip_entry(&inner);
      return Ok(());
    }
    graphql.push(positions(&inner, kind, errors));
    Ok(())
  });

  if graphql.is_empty() {
    errors.push(syn::Error::new_spanned(
      &meta.path,
      format!(
        "`graphql` names no backend — write `graphql({first}(output))`. Without the block a union \
         keeps its whole Rust surface — the member questions, the unwrap family and the refusal are \
         all there — and what the block adds is a schema over it",
        first = GraphqlKind::ALL[0].as_str(),
      ),
    ));
  }
  walked
}

/// ONE backend's block: which of the two schema positions it dresses this union for.
fn positions(
  meta: &syn::meta::ParseNestedMeta<'_>,
  kind: GraphqlKind,
  errors: &mut Errors,
) -> UnionSkin {
  let mut output: Option<syn::Path> = None;
  let mut input: Option<syn::Path> = None;
  let mut rename: Option<syn::LitStr> = None;
  let mut output_rename: Option<syn::LitStr> = None;

  let walked = attribute::options(meta, |entry| {
    if entry.path.is_ident("output") {
      attribute::set_once(
        &mut output,
        entry.path.clone(),
        &entry.path,
        &declared_twice("output"),
        errors,
      );
      // ONE option, and it is the same one the input face takes. Which face keeps the union's OWN
      // name when both are rendered is settled — the output does, being what a client writes in a
      // selection set — and that is a fact about the DEFAULT rather than a reason this face cannot be
      // named. A declaration whose scope already publishes a `Frame` needs the escape here exactly as
      // much as the input twin does.
      return attribute::options(&entry, |option| {
        if option.path.is_ident("rename") {
          return face_name(
            &option,
            &mut output_rename,
            "`rename` is declared more than once in `output(…)` — one option, one value",
            errors,
          );
        }
        errors.push(attribute::unknown(
          &option,
          "unknown entry in `output(…)` — it takes `rename = \"…\"` and nothing else. What this \
           face publishes is the union's MEMBERS, which the declaration already named, so the one \
           thing left to say is what a client calls the union itself",
          &["rename"],
        ));
        Ok(())
      });
    }

    if entry.path.is_ident("input") {
      attribute::set_once(
        &mut input,
        entry.path.clone(),
        &entry.path,
        &declared_twice("input"),
        errors,
      );
      return attribute::options(&entry, |option| {
        if option.path.is_ident("rename") {
          return face_name(
            &option,
            &mut rename,
            "`rename` is declared more than once in `input(…)` — one option, one value",
            errors,
          );
        }
        errors.push(attribute::unknown(
          &option,
          "unknown entry in `input(…)` — it takes `rename = \"…\"` and nothing else",
          &["rename"],
        ));
        Ok(())
      });
    }

    errors.push(attribute::unknown(
      &entry,
      "unknown entry in a union's backend block — it takes `output` and `input`, the two positions \
       a schema has for a declared union, and nothing else",
      &POSITIONS,
    ));
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }

  if output.is_none() && input.is_none() {
    errors.push(syn::Error::new_spanned(
      &meta.path,
      format!(
        "`{kind}` dresses this union for no position — write `{kind}(output)`, `{kind}(input)` or \
         both. A backend block naming neither is a face nothing renders, and an entry nobody reads \
         is a rule its author believes they declared",
        kind = kind.as_str(),
      ),
    ));
  }

  UnionSkin {
    kind,
    output: output.is_some().then_some(UnionOutput {
      rename: output_rename,
    }),
    input: input.is_some().then_some(UnionInput { rename }),
  }
}

/// ONE face's `rename = "…"` — the word a SCHEMA calls that face, read the same way at both
/// positions.
///
/// STRING-kind and fenced by GraphQL's own Name grammar, because nothing in Rust is called this: both
/// faces are impls on the enum the declaration already named, so a Rust keyword is an ordinary word
/// here. One reader for the pair rather than two, which is what keeps the second face from wording
/// the rule differently from the first.
fn face_name(
  option: &syn::meta::ParseNestedMeta<'_>,
  slot: &mut Option<syn::LitStr>,
  twice: &str,
  errors: &mut Errors,
) -> syn::Result<()> {
  match value::literal(option, attribute::SDL_NAME) {
    Ok(word) => {
      crate::wire::refuse_invalid_name(&word.value(), &word, errors);
      attribute::set_once(slot, word, &option.path, twice, errors);
    }
    Err(e) => errors.push(e),
  }
  Ok(())
}

/// The refusal a position declared twice earns — one word per position, because a schema renders a
/// union at each of them once and a second word could only re-describe the first.
fn declared_twice(position: &str) -> String {
  format!(
    "`{position}` is declared more than once — one word per position, and a schema renders a union \
     at each of them once"
  )
}

/// The names this expansion puts into scopes it does not own, and the ones they may not take.
///
/// Two scopes and two rules. The REFUSAL type lands in the DECLARING scope, so it may not be called
/// what the enum is called; the INPUT object lands in the SCHEMA, so it may not be called what the
/// OUTPUT face is called. Both are asked of the MODEL rather than rebuilt here, for the reason the
/// vocabulary's own check asks its own: a derived name spelled on this side is a second copy of what
/// the emitter writes, and two copies of a derived name is how one of them drifts.
///
/// The refusal half fires only on a DECLARED rename, and that is arithmetic rather than a choice —
/// the default is `<Union>UnwrapError`, which is strictly longer than the enum's own name and so can
/// never be it. The schema half is the same arithmetic one layer over: the derived input name is the
/// output's word plus `Input`, which the output's own word never is. So a collision here needs a
/// WRITTEN word, at one face or the other, and the sentence is anchored at whichever one the
/// declaration wrote — the input's where it wrote both, that being the face the law says has
/// somewhere else to go.
fn emitted_names(model: &UnionModel, errors: &mut Errors) {
  if let Some(at) = model.error.as_ref()
    && model.error() == model.name
  {
    errors.push(syn::Error::new(
      at.span(),
      format!(
        "the refusal type would be named `{name}`, which is already the union's own name — the \
         expansion declares it beside the enum, so it needs a name of its own",
        name = model.name
      ),
    ));
  }

  for skin in &model.graphql {
    let Some(at) = skin
      .input
      .as_ref()
      .and_then(|input| input.rename.as_ref())
      .or_else(|| {
        skin
          .output
          .as_ref()
          .and_then(|output| output.rename.as_ref())
      })
    else {
      continue;
    };
    if skin.output.is_none() || skin.input_sdl(&model.name) != skin.output_sdl(&model.name) {
      continue;
    }
    errors.push(syn::Error::new(
      at.span(),
      format!(
        "the input object would be called `{name}`, which is what this union's OUTPUT face already \
         publishes — a schema has ONE namespace for type names, so the two faces of one union need \
         two of them",
        name = skin.output_sdl(&model.name)
      ),
    ));
  }
}