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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Validating a LEAF ERROR's declaration into the model the emitter consumes.
//!
//! ```ignore
//! #[ingraph::mutation_error]
//! pub enum WatchError {
//!   #[ingraph(code = "NOT_A_DIRECTORY", error = "`{0}` is not a directory")]
//!   NotADirectory(PathBuf),
//! }
//! ```
//!
//! Two words per variant and neither is optional. `code` is what a client MATCHES ON and `error` is
//! what a person READS, and an error type exists to be both — so a variant that omits either is
//! refused rather than defaulted.
//!
//! # WHAT THIS PASS CAN SEE
//!
//! Tokens, which is more than most passes in this crate get: a variant's FIELDS are right there, so
//! the template is checked against them here rather than left to fail inside an expansion. A
//! placeholder naming a field the variant does not have, or a position past its last one, is refused
//! at the template literal — which is the token an author has to change.
//!
//! What it cannot see is what those fields' types are, so whether each one can be rendered at all is
//! the compiler's to say, at the `write!` the emission builds.
//!
//! # THE CODE RULES, all four of them
//!
//! | rule | why |
//! |---|---|
//! | mandatory | a variant with no word is a refusal a client cannot tell from its neighbour |
//! | `SCREAMING_SNAKE_CASE` | GraphQL's own convention for a machine-read constant, and what the framework's own vocabulary is spelled in |
//! | no two variants share one | a vocabulary is only a contract while it is injective |
//! | never one of the framework's | a client matching `UNREACHABLE_SOURCE` would be told the wrong thing by an application error |

use ingraph_codegen::error::{
  Binding, BindingAt, ErrorModel, ErrorRoad, RESERVED, Rendering, VariantModel, VariantShape,
};

use crate::{attribute, errors::Errors, value};

#[cfg(test)]
mod tests;

/// Validate a decorated declaration 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,
  arguments: &[syn::Attribute],
  road: ErrorRoad,
) -> syn::Result<ErrorModel> {
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  wordless(arguments, road, &mut errors);
  concrete(&input.generics, road, &mut errors);

  let variants = match arms(input, road) {
    Ok(variants) => variants,
    Err(terminal) => return Err(errors.seal(terminal)),
  };

  // The vocabulary as it is BUILT, so the second variant to write a word is refused at its own
  // `code` and told which variant already holds it.
  let mut minted: Vec<(String, syn::Ident)> = Vec::new();
  let variants = variants
    .iter()
    .map(|variant| arm(variant, road, &mut minted, &mut errors))
    .collect();

  errors.into_result(ErrorModel {
    name: input.ident.clone(),
    road,
    variants,
  })
}

/// This macro takes NO arguments, and the absence is a fact rather than an omission.
///
/// There is no `crate = "…"` word either, alone in this family: the whole expansion names `::core`
/// and nothing else, so where `ingraph` lives is a question it never asks.
fn wordless(arguments: &[syn::Attribute], road: ErrorRoad, errors: &mut Errors) {
  for written in arguments {
    errors.push(syn::Error::new_spanned(
      written,
      format!(
        "`#[ingraph::{word}]` takes no arguments — every word it reads is written on a VARIANT \
         (`code` and `error`). It needs no `crate = \"…\"` either: the whole expansion names \
         `::core` and nothing of this framework's",
        word = road.word(),
      ),
    ));
  }
}

/// A leaf error takes no generic parameter.
fn concrete(generics: &syn::Generics, road: ErrorRoad, errors: &mut Errors) {
  let why = format!(
    "`#[ingraph::{word}]` takes no generic parameter — the expansion writes ONE `Display` over ONE \
     type, and what a parameter would owe that impl (a bound per field a template renders) is a \
     decision this macro would be making on an author's behalf. A generic error writes its own \
     `Display`, which is exactly as legal",
    word = road.word(),
  );
  if !generics.params.is_empty() {
    errors.push(syn::Error::new_spanned(generics, &why));
  } else if let Some(clause) = &generics.where_clause {
    errors.push(syn::Error::new_spanned(clause, why));
  }
}

/// The declaration's variants — the only shape a leaf error may take.
fn arms(
  input: &syn::DeriveInput,
  road: ErrorRoad,
) -> syn::Result<&syn::punctuated::Punctuated<syn::Variant, syn::Token![,]>> {
  match &input.data {
    syn::Data::Enum(data) => Ok(&data.variants),
    syn::Data::Struct(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "`#[ingraph::{word}]` supports enums only — an error type's VARIANTS are the ways it can \
         fail, and each one is what a `code` names. A failure with exactly one shape is an enum \
         with one variant, which costs a word and buys the vocabulary",
        word = road.word(),
      ),
    )),
  }
}

/// ONE variant, read as the failure it is.
fn arm(
  variant: &syn::Variant,
  road: ErrorRoad,
  minted: &mut Vec<(String, syn::Ident)>,
  errors: &mut Errors,
) -> VariantModel {
  let mut code: Option<syn::LitStr> = None;
  let mut template: Option<syn::LitStr> = None;
  // The two WORDS, whether or not their values could be read. A bad value has already earned its one
  // error, and the missing-word sentences below would be that error's echo — the mutation grammar's
  // own measured law, and the defect this crate's suite caught here too.
  let mut code_at: Option<syn::Path> = None;
  let mut template_at: Option<syn::Path> = None;

  attribute::walk(&variant.attrs, errors, |meta, errors| {
    if meta.path.is_ident("code") {
      code_at = Some(meta.path.clone());
      match value::literal(&meta, CODE_WORD) {
        Ok(word) => attribute::set_once(
          &mut code,
          word,
          &meta.path,
          "`code` is declared more than once on this variant — one failure is recognised by one \
           word",
          errors,
        ),
        Err(e) => refuse_value(&meta, e, errors),
      }
      return Ok(());
    }

    if meta.path.is_ident("error") {
      template_at = Some(meta.path.clone());
      match value::literal(&meta, ERROR_WORD) {
        Ok(sentence) => attribute::set_once(
          &mut template,
          sentence,
          &meta.path,
          "`error` is declared more than once on this variant — one failure reads as one sentence",
          errors,
        ),
        Err(e) => refuse_value(&meta, e, errors),
      }
      return Ok(());
    }

    errors.push(attribute::unknown(
      &meta,
      "unknown entry on a leaf error's variant — it takes `code = \"…\"` (what a client matches on) \
       and `error = \"…\"` (what a person reads), and nothing else",
      &["code", "error"],
    ));
    Ok(())
  });

  let code = match code {
    Some(code) => {
      screaming(&code, errors);
      reserved(&code, errors);
      unique(&code, &variant.ident, minted, errors);
      code
    }
    None => {
      if code_at.is_none() {
        errors.push(syn::Error::new_spanned(
          &variant.ident,
          format!(
            "`{arm}` declares no `code` — every variant of a leaf error carries one, because the \
             code is what a client matches on and the head of everything the variant renders as. \
             Write `#[ingraph(code = \"SOME_WORD\", error = \"…\")]`",
            arm = variant.ident,
          ),
        ));
      }
      // A variant whose code could not be read still becomes a row, so the rest of the declaration
      // is checked rather than abandoned. Nothing is emitted from a refused parse.
      syn::LitStr::new("__INGRAPH_UNDECLARED", variant.ident.span())
    }
  };

  let shape = match &variant.fields {
    syn::Fields::Unit => VariantShape::Unit,
    syn::Fields::Unnamed(_) => VariantShape::Tuple,
    syn::Fields::Named(_) => VariantShape::Named,
  };
  let rendering = match &template {
    Some(template) => rendering(&code, template, variant, road, errors),
    None => {
      if template_at.is_none() {
        errors.push(syn::Error::new_spanned(
          &variant.ident,
          format!(
            "`{arm}` declares no `error` — the word is the sentence this failure renders as, after \
             its code and a colon. A variant with nothing to say to a person is a code with no \
             message under it",
            arm = variant.ident,
          ),
        ));
      }
      Rendering {
        template: code.value(),
        bound: Vec::new(),
      }
    }
  };

  VariantModel {
    name: variant.ident.clone(),
    code,
    rendering,
    shape,
  }
}

/// The code as the word a client matches on: uppercase, digits and underscores, opening on a letter.
///
/// A SUPERSET of what the framework's own vocabulary uses — no word there carries a digit — because
/// the code space below the framework's is the application's, and a rule stricter than the reason
/// for it would be this macro narrowing somebody else's namespace. What it does hold to is the shape
/// that makes a word a legal GraphQL Name and a recognisable constant.
fn screaming(code: &syn::LitStr, errors: &mut Errors) {
  let word = code.value();
  let legal = !word.is_empty()
    && word
      .bytes()
      .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
    && word.as_bytes().first().is_some_and(u8::is_ascii_uppercase)
    && !word.ends_with('_');
  if !legal {
    errors.push(syn::Error::new_spanned(
      code,
      format!(
        "`{word}` is not `SCREAMING_SNAKE_CASE` — a code is a machine-read constant, spelled in \
         GraphQL's own convention for one: upper-case letters, digits and underscores, opening on a \
         letter and not closing on an underscore"
      ),
    ));
  }
}

/// The framework's own words are RESERVED, and a declaration that mints one is refused.
fn reserved(code: &syn::LitStr, errors: &mut Errors) {
  let word = code.value();
  if RESERVED.contains(&word.as_str()) {
    errors.push(syn::Error::new_spanned(
      code,
      format!(
        "`{word}` is one of the framework's own wire codes and is reserved — a client matching on \
         it is asking about a refusal this framework raises, and an application error wearing the \
         word would answer that question wrongly. The code space below it is open: mint any other \
         `SCREAMING_SNAKE_CASE` word"
      ),
    ));
  }
}

/// No two variants share a word — a vocabulary is only a contract while it is injective.
fn unique(
  code: &syn::LitStr,
  arm: &syn::Ident,
  minted: &mut Vec<(String, syn::Ident)>,
  errors: &mut Errors,
) {
  let word = code.value();
  match minted.iter().find(|(held, _)| held == &word) {
    Some((_, first)) => errors.push(syn::Error::new_spanned(
      code,
      format!(
        "`{word}` is already the code of `{first}` — two variants under one word would tell a \
         client one thing about two different mistakes, so a vocabulary is a contract only while it \
         is injective"
      ),
    )),
    None => minted.push((word, arm.clone())),
  }
}

/// The template, checked against the variant's own fields and rewritten to name what the emission
/// binds.
///
/// The CODE is folded in here rather than at the emitter, so the whole rendering is one literal and
/// there is exactly one place the one-code-head law is applied.
fn rendering(
  code: &syn::LitStr,
  template: &syn::LitStr,
  variant: &syn::Variant,
  road: ErrorRoad,
  errors: &mut Errors,
) -> Rendering {
  let mut written = String::new();
  let mut bound: Vec<Binding> = Vec::new();
  let mut implicit = 0_usize;
  let text = template.value();
  let mut rest = text.as_str();

  written.push_str(&code.value());
  written.push_str(": ");

  while let Some(at) = rest.find(['{', '}']) {
    let (before, from) = rest.split_at(at);
    written.push_str(before);
    let mut characters = from.chars();
    let opener = characters.next().unwrap_or('{');
    if from.starts_with("{{") || from.starts_with("}}") {
      written.push(opener);
      written.push(opener);
      rest = &from[2..];
      continue;
    }
    if opener == '}' {
      errors.push(syn::Error::new_spanned(template, UNPAIRED));
      return Rendering {
        template: written,
        bound,
      };
    }
    let Some(close) = from.find('}') else {
      errors.push(syn::Error::new_spanned(template, UNCLOSED));
      return Rendering {
        template: written,
        bound,
      };
    };
    let inside = &from[1..close];
    let (named, spec) = inside
      .split_once(':')
      .map_or((inside, ""), |(named, spec)| (named, spec));
    // A placeholder that resolved is REWRITTEN to name the binding the emission introduces; one
    // that did not has already recorded its refusal, and is DROPPED so the rest of the template is
    // still walked and an author sees every one of its problems at once.
    if let Some(at) = placeholder(named, variant, template, road, &mut implicit, errors) {
      let held = hold(&at, &mut bound);
      written.push('{');
      written.push_str(&held.to_string());
      if !spec.is_empty() {
        written.push(':');
        written.push_str(spec);
      }
      written.push('}');
    }
    rest = &from[close + 1..];
  }
  written.push_str(rest);

  Rendering {
    template: written,
    bound,
  }
}

/// ONE placeholder, resolved against the variant's own fields.
fn placeholder(
  named: &str,
  variant: &syn::Variant,
  template: &syn::LitStr,
  road: ErrorRoad,
  implicit: &mut usize,
  errors: &mut Errors,
) -> Option<BindingAt> {
  let arity = variant.fields.len();
  if named.is_empty() || named.bytes().all(|byte| byte.is_ascii_digit()) {
    let at = if named.is_empty() {
      let at = *implicit;
      *implicit += 1;
      at
    } else {
      named.parse::<usize>().ok()?
    };
    if !matches!(variant.fields, syn::Fields::Unnamed(_)) || at >= arity {
      errors.push(syn::Error::new_spanned(
        template,
        format!(
          "`{{{named}}}` names field {at} of `{arm}`, which has {arity} — a positional placeholder \
           reads a TUPLE variant's fields, and a variant with named fields is read by those names",
          arm = variant.ident,
        ),
      ));
      return None;
    }
    return Some(BindingAt::Position(at));
  }

  let held = variant
    .fields
    .iter()
    .find_map(|field| field.ident.clone().filter(|ident| ident == named));
  if held.is_none() {
    errors.push(syn::Error::new_spanned(
      template,
      format!(
        "`{arm}` has no field called `{named}` — a leaf error's template reads the variant's own \
         fields, by name where it has them and by position (`{{0}}`) where it does not. \
         `#[ingraph::{word}]` checks that here rather than leaving it to fail inside the expansion",
        arm = variant.ident,
        word = road.word(),
      ),
    ));
  }
  held.map(BindingAt::Named)
}

/// The binding one field is introduced under, minted once however many times a template names it.
fn hold(at: &BindingAt, bound: &mut Vec<Binding>) -> syn::Ident {
  if let Some(held) = bound
    .iter()
    .find(|binding| &binding.at == at)
    .map(|binding| binding.held.clone())
  {
    return held;
  }
  let held = match at {
    BindingAt::Position(position) => quote::format_ident!("__ingraph_at_{position}"),
    BindingAt::Named(name) => quote::format_ident!("__ingraph_named_{name}"),
  };
  bound.push(Binding {
    held: held.clone(),
    at: at.clone(),
  });
  held
}

/// Record a refusal about an entry's VALUE, and swallow the entry it was written in.
///
/// The mutation grammar's own law, applied here for its own reason: a value reader leaves the token
/// it could not read where it found it, so a walk that resumed there would earn syn's `expected ,`
/// at the same column and then a second rule about the word it never reached.
fn refuse_value(meta: &syn::meta::ParseNestedMeta<'_>, error: syn::Error, errors: &mut Errors) {
  errors.push(error);
  attribute::skip_entry(meta);
}

/// The refusal a `code` that is not a written word earns.
const CODE_WORD: &str =
  "`code = \"…\"` is the word a client matches this failure by, in a string literal";

/// The refusal an `error` that is not a written sentence earns.
const ERROR_WORD: &str =
  "`error = \"…\"` is the sentence this failure renders as, in a string literal";

/// The refusal a template with a `}` nothing opened earns.
const UNPAIRED: &str = "this template holds a `}` that opens nothing — a literal brace is written \
                        `}}`, exactly as it is in any format string";

/// The refusal a template with an unclosed `{` earns.
const UNCLOSED: &str = "this template holds a `{` that is never closed — a placeholder is \
                        `{0}`, `{name}` or `{}`, and a literal brace is written `{{`";