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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
//! The ONE DOOR onto a FLAGS SET — validating a manifest enum into the model the emitter consumes.
//!
//! # The grammar
//!
//! ```ignore
//! #[ingraph::flags(u32)]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum TrackDisposition {
//!   /// The default track for its kind.
//!   Default = 0x1,
//!   Forced = 0x2,
//!   #[ingraph(rename = "HI")]
//!   HearingImpaired = 1 << 2,
//! }
//! ```
//!
//! An ATTRIBUTE where the vocabulary takes a derive, and a MANIFEST where the vocabulary takes the
//! declaration itself. Both follow from the same fact: `bitflags!` MINTS the flags type, so the item
//! the author writes is consumed rather than kept, and only an attribute may consume one. What the
//! author writes is an `enum` because a set of names with values is what an enum spells — see the
//! emitter's own note for the two alternatives that were weighed and why neither survives a doc
//! comment on a bit.
//!
//! The width is the attribute's own argument rather than a `#[repr(…)]`, and that is the honest
//! placement: `#[repr(u32)]` on the manifest would describe a type that does not survive the
//! expansion, where `flags(u32)` describes the one that does.
//!
//! # `#[ingraph::flags(…)]` GOES ABOVE THE DERIVES, and the order is load-bearing
//!
//! ```ignore
//! #[ingraph::flags(u32)]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum TrackDisposition { … }
//! ```
//!
//! rustc expands the TOPMOST attribute on an item first, and `derive` takes its turn in that same
//! order. A derive written above this word therefore expands against the MANIFEST — the enum that is
//! about to stop existing — and lands a `Debug` impl matching on `TrackDisposition::Default`, a
//! variant the expansion replaced with a const. The error a reader gets says *no associated
//! function or constant named `Default` found for struct*, which is true and unhelpful.
//!
//! Written above, this word expands first, and the derives it forwards land on the type
//! `bitflags!` mints. It is the ordinary hazard of every rewriting attribute and it cannot be
//! detected here: by the time this door runs, a derive that already expanded is gone from the
//! item's attributes and is indistinguishable from one nobody wrote.
//!
//! # One word, TWO shapes
//!
//! `remote = "…"` says the declaration RESTATES a flags set another crate owns rather than being
//! one:
//!
//! ```ignore
//! #[ingraph::flags(u32, remote = "upstream::Disposition")]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum Disposition {
//!   Default = 0x1,
//!   #[ingraph(rename = "HEARING_IMPAIRED")]
//!   Hi = 0x4,
//! }
//! ```
//!
//! and ONE reader here forks on it. A mirror mints the same type, stores the same bit pattern and
//! publishes the same faces — the number is what crosses, and a number is the same number on both
//! sides — so what the word buys is a CROSSING and a per-bit drift pin, both emitted behind
//! everything a declared set already emits. `ingraph-codegen`'s `flags::remote` carries the design.
//!
//! The one reader that forks is `rename`, which names the upstream `const` on a mirror where it
//! moves this declaration's own word on a set of its own. Everything downstream of that — the
//! width, the explicit numbers, the single-bit rule, the collisions — is the same question in both
//! modes and is asked once.
//!
//! # The refusals carry the weight, and one of them is this kind's alone
//!
//! **Auto-numbering is refused.** A bit with no explicit value is a bit whose number would come from
//! its POSITION, and reordering a list of names is the most ordinary edit there is — so an implicit
//! numbering makes reordering a declaration a rewrite of everybody's stored rows, silently. The
//! vocabulary kind can default a discriminant because a reordered enum still stores what it stored;
//! this one cannot, and the refusal is where the difference lives.
//!
//! The rest are the shape rules a manifest has to satisfy for the expansion to mean anything: a bit
//! is ONE bit (v1 declines composite masks, which `bitflags` allows and which would make the
//! per-flag fan ambiguous), inside the declared width, and declared once; a word is a GraphQL name
//! and spells one bit; and the type is a plain, generic-free enum of unit variants.

use std::collections::BTreeMap;

use ingraph_codegen::flags::{BitWidth, FlagBit, FlagsModel};

use crate::{
  attribute::{self, set_once},
  r#enum::listed,
  errors::Errors,
  value, wire,
};

#[cfg(test)]
mod tests;

/// The word this door is spelled with, for the sentences that name it.
const WORD: &str = "#[ingraph::flags(…)]";

/// What `crate = "…"` has to be.
const CRATE_PATH: &str =
  "`#[ingraph::flags(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";

/// What `remote = "…"` has to be.
const REMOTE_PATH: &str = "`#[ingraph::flags(…, remote = \"…\")]` must be a path to the flags set \
                           this one mirrors, in a string literal";

/// The refusal for a mirrored set named twice.
const REMOTE_ONCE: &str =
  "`remote` is declared more than once — one declaration mirrors one flags set";

/// Validate a decorated manifest into the model the emitter consumes.
///
/// `options` is the attribute's own arguments, wrapped back into an `#[ingraph(…)]` by
/// [`host::options`](crate::host::options) so that one grammar reads both entry points.
///
/// # 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,
  options: &[syn::Attribute],
) -> syn::Result<FlagsModel> {
  let mut errors = Errors::default();
  let Options {
    krate,
    width,
    named,
    remote,
    wire_name,
  } = self::options(options, &mut errors);
  let mode = if remote.is_some() {
    Mode::Mirror
  } else {
    Mode::Declared
  };
  // The option block belongs in the ATTRIBUTE's parentheses. An `#[ingraph(…)]` left on the item
  // would be forwarded onto the minted type as an unknown attribute, and its rules would vanish
  // without a word.
  //
  // Spelled HERE rather than through the shared refusal, which hardcodes `#[ingraph::record(…)]`
  // and a store word: a flags author told to write a record's option would be reading a sentence
  // about a different declaration.
  moved_option_block(&input.attrs, &mut errors);
  concrete(&input.generics, &mut errors);
  // The declaration's OWN schema name. Where `graphql(rename = "…")` moved it the LITERAL is what is
  // checked, at its own span; where nothing moved it the name is the Rust one unraw'd. Either way the
  // check is unconditional, the wire seats being emitted unconditionally: a type whose name is
  // outside GraphQL's Name grammar registers a schema no client could name.
  match wire_name.as_ref() {
    Some(word) => wire::refuse_invalid_name(&word.value(), word, &mut errors),
    None => wire::refuse_invalid_name(
      &syn::ext::IdentExt::unraw(&input.ident).to_string(),
      &input.ident,
      &mut errors,
    ),
  }

  let Some(width) = width else {
    // The sentence fires only where NO width-shaped word was written. A word that was written and
    // refused already has its own sentence, at its own span, and adding this one would tell the
    // author the opposite of what they did.
    if !named {
      errors.push(syn::Error::new_spanned(
        &input.ident,
        format!(
          "`{WORD}` names its WIDTH — the integer a column of this type is stored as, and the \
           number of bits a declaration may number. Write `#[ingraph::flags(u32)]`, or any of {}",
          listed(&BitWidth::ALL.map(BitWidth::as_str))
        ),
      ));
    }
    // Nothing below is checkable without one: a bit's range and its single-bit-ness are both
    // questions about a width.
    return Err(
      errors
        .into_result(())
        .expect_err("a declaration with no usable width has always recorded why"),
    );
  };

  let bits = match self::bits(input, width, mode, &mut errors) {
    Ok(bits) => bits,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  collisions(&bits, &mut errors);

  errors.into_result(FlagsModel {
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    vis: input.vis.clone(),
    name: input.ident.clone(),
    width,
    bits,
    attrs: forwarded(&input.attrs),
    remote,
    wire_name: wire_name.map(|word| word.value()),
  })
}

/// Which of the two shapes a declaration is.
///
/// ONE reader forks on it — `rename`, which names a different thing in each mode — and that is the
/// whole of the fork rather than a summary of it: a mirrored flags set stores its own bit pattern,
/// spells its own words and publishes its own faces, so everything else about a declaration is the
/// same question whether or not an upstream is named.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
  /// The declaration IS the flags set.
  Declared,
  /// The declaration RESTATES one, and `remote = "…"` names it.
  Mirror,
}

/// What the attribute's own arguments carry.
struct Options {
  /// `crate = "…"`.
  krate: Option<syn::Path>,
  /// The width, which is the one argument this door REQUIRES.
  width: Option<BitWidth>,
  /// Whether a width-SHAPED word was written at all, carried or not.
  ///
  /// The two are not the same question, and conflating them told an author who wrote `flags(u64)`
  /// that they had named no width — which is false, repeats the same list, and points at the
  /// declaration's name instead of at the word they wrote.
  named: bool,
  /// `remote = "…"` — the upstream flags set this declaration mirrors.
  remote: Option<syn::Path>,
  /// `graphql(rename = "…")` — what a SCHEMA calls this flags set.
  wire_name: Option<syn::LitStr>,
}

/// Walk the attribute's arguments.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
  let mut krate = None;
  let mut width = None;
  let mut named = false;
  let mut remote = None;
  let mut wire_name = None;

  attribute::walk(attrs, errors, |meta, errors| {
    if meta.path.is_ident("crate") {
      match value::parse_literal::<syn::Path>(&meta, CRATE_PATH) {
        Ok(path) => set_once(&mut krate, path, &meta.path, CRATE_ONCE, errors),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // The word that picks the MODE. A PATH rather than a literal, for the vocabulary mirror's
    // reason: the emission names the upstream type in half a dozen positions, and re-parsing it once
    // here is what makes a value that cannot BE a type a refusal at this token rather than a syntax
    // error inside an expansion.
    if meta.path.is_ident("remote") {
      match value::parse_literal::<syn::Path>(&meta, REMOTE_PATH) {
        Ok(path) => set_once(&mut remote, path, &meta.path, REMOTE_ONCE, errors),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // THE WIRE FACE'S OWN BLOCK, and the only thing in it is a NAME. A flags column stores its bit
    // PATTERN in every database, so there is no per-face storage family here for the block to be a
    // member of — which is why it holds one word where the vocabulary kind's `graphql(…)` holds that
    // word beside a form. The spelling is the same on purpose: `graphql(rename = "…")` is *what a
    // schema calls this declaration* at every door that has one.
    if meta.path.is_ident("graphql") {
      return attribute::named_block(
        &meta,
        &mut wire_name,
        "graphql",
        "schema type",
        errors,
        |option| value::literal(option, attribute::SDL_NAME),
      );
    }

    if let Some(word) = meta.path.get_ident().map(ToString::to_string) {
      if let Some(carried) = BitWidth::named(&word) {
        named = true;
        set_once(
          &mut width,
          carried,
          &meta.path,
          "the width is declared more than once — one column has one width",
          errors,
        );
        return Ok(());
      }
      // A width-SHAPED word this kind does not carry gets the table's own sentence rather than the
      // grammar's, because what is wrong with `u64` is not that it is unrecognised.
      if UNCARRIED.contains(&word.as_str()) {
        named = true;
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`{word}` is not a width a flags set can be stored at — the framework's carrier table \
             covers {}, and no wider: MySQL alone has a native `u64` and no dialect carries a \
             128-bit integer. The SIGNED widths are absent for a different reason — a flag is a \
             BIT, and `iN`'s top bit is negative, so it is one bit no declaration could write",
            listed(&BitWidth::ALL.map(BitWidth::as_str))
          ),
        ));
        return Ok(());
      }
    }

    errors.push(attribute::unknown(
      &meta,
      &format!(
        "unknown entry in `{WORD}` — a flags declaration takes its WIDTH ({}), plus \
         `graphql(rename = \"…\")`, `remote = \"…\"` and `crate = \"…\"`",
        listed(&BitWidth::ALL.map(BitWidth::as_str))
      ),
      &["crate", "remote", "graphql"]
        .into_iter()
        .chain(BitWidth::ALL.map(BitWidth::as_str))
        .collect::<Vec<_>>(),
    ));
    Ok(())
  });

  Options {
    krate,
    width,
    named,
    remote,
    wire_name,
  }
}

/// The integer words a reader is likely to write and this kind does not carry, so that each gets the
/// TABLE's sentence rather than *unknown entry*.
const UNCARRIED: [&str; 9] = [
  "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize",
];

/// Flags sets are concrete, for the vocabulary kind's reason: every row the emitter writes names the
/// type ITSELF, and `bitflags!` mints a plain struct with no parameter to substitute.
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
  const WHY: &str = "generic flags sets are not supported — the expansion is one `bitflags!` type \
                     with one bit table, and a parameter has no type until it is substituted";
  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 manifest's bits — the only shape a flags declaration may take.
fn bits(
  input: &syn::DeriveInput,
  width: BitWidth,
  mode: Mode,
  errors: &mut Errors,
) -> syn::Result<Vec<FlagBit>> {
  let syn::Data::Enum(data) = &input.data else {
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "`{WORD}` supports enums only — the manifest is a set of NAMES with VALUES, which is what \
         an enum spells and what a struct body cannot hold. The expansion is a `bitflags!` struct \
         either way; the enum is what the author writes, not what they get"
      ),
    ));
  };

  if data.variants.is_empty() {
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "an enum with no variants declares no flags — there is no bit to store, no field for a \
         client to ask for, and the emitted filter would guard a column whose every value is \
         empty. `{WORD}` has nothing to emit for one"
      ),
    ));
  }

  let mut parsed = Vec::with_capacity(data.variants.len());
  for variant in &data.variants {
    if !matches!(variant.fields, syn::Fields::Unit) {
      errors.push(syn::Error::new_spanned(
        &variant.ident,
        format!(
          "`{WORD}` takes UNIT variants only — `{}` carries data. A bit is a NAME and a NUMBER; \
           there is no payload a stored bit could hold",
          variant.ident
        ),
      ));
      continue;
    }
    let Some(value) = self::value(variant, width, errors) else {
      continue;
    };
    let mut bit = FlagBit {
      ident: variant.ident.clone(),
      rename: None,
      upstream: None,
      value,
      attrs: forwarded(&variant.attrs),
    };
    rename(variant, &mut bit, mode, errors);
    parsed.push(bit);
  }
  Ok(parsed)
}

/// One bit's VALUE — explicit, one bit, inside the declared width.
///
/// The three refusals here are what a flags set has instead of a vocabulary's numbering, and each
/// one guards a different silent outcome: an implicit number changes when the list is reordered, a
/// composite mask makes the per-flag fan ambiguous, and a value past the width would be truncated
/// into a bit the declaration did not write.
fn value(variant: &syn::Variant, width: BitWidth, errors: &mut Errors) -> Option<u128> {
  let Some((_, expression)) = &variant.discriminant else {
    errors.push(syn::Error::new_spanned(
      &variant.ident,
      format!(
        "`{}` names no bit — a flags declaration writes every value EXPLICITLY. An implicit \
         numbering would come from a bit's POSITION, so reordering the declaration would rewrite \
         every stored row, silently. Write `{} = <bit>` and give it the number it already has in \
         your data",
        variant.ident, variant.ident
      ),
    ));
    return None;
  };

  let Some(value) = literal(expression) else {
    errors.push(syn::Error::new_spanned(
      expression,
      "a bit's value is an integer LITERAL or a shift of one — `0x4`, `0b100`, `4` or `1 << 2`. \
       This door has to prove the value is a single bit inside the declared width, and an \
       expression it cannot evaluate is one it cannot prove anything about",
    ));
    return None;
  };

  if value == 0 {
    errors.push(syn::Error::new_spanned(
      expression,
      format!(
        "`{}` is `0`, which sets no bit — a value with no bit is not a flag, it is the EMPTY set, \
         and every flags type already has one of those",
        variant.ident
      ),
    ));
    return None;
  }
  if value > width.ceiling() {
    errors.push(syn::Error::new_spanned(
      expression,
      format!(
        "`{value:#x}` does not fit `{}` — this declaration numbers {} bits, so the highest one is \
         `{:#x}`",
        width.as_str(),
        width.count(),
        1u128 << (width.count() - 1)
      ),
    ));
    return None;
  }
  if value.count_ones() > 1 {
    errors.push(syn::Error::new_spanned(
      expression,
      format!(
        "`{value:#x}` sets {} bits — a declared flag is ONE bit. A composite mask has no per-flag \
         boolean a client could ask for and no single answer to *is it set*; write the bits it \
         combines and let a caller ask for them together",
        value.count_ones()
      ),
    ));
    return None;
  }
  Some(value)
}

/// The integer an expression names, where it names one this door can evaluate.
///
/// Literals and shifts of literals, and no wider grammar. A `const` from elsewhere would be a value
/// this pass cannot see, and a value it cannot see is one whose single-bit-ness it would have to
/// take on faith — which is precisely the guarantee the whole kind rests on.
fn literal(expression: &syn::Expr) -> Option<u128> {
  match expression {
    syn::Expr::Paren(inner) => literal(&inner.expr),
    syn::Expr::Group(inner) => literal(&inner.expr),
    syn::Expr::Lit(syn::ExprLit {
      lit: syn::Lit::Int(int),
      ..
    }) => int.base10_parse::<u128>().ok(),
    syn::Expr::Binary(syn::ExprBinary {
      left,
      op: syn::BinOp::Shl(_),
      right,
      ..
    }) => {
      let base = literal(left)?;
      let shift = literal(right)?;
      u32::try_from(shift)
        .ok()
        .and_then(|shift| base.checked_shl(shift))
    }
    _ => None,
  }
}

/// One bit's `#[ingraph(rename = "…")]`, and the refusal for anything else written there.
///
/// # One word, two readings, and the MODE picks
///
/// A DECLARED flags set owns its words, so the knob moves the one word every face spells this bit
/// with. A MIRROR owns its words too — a flags column stores its bit PATTERN, so the text form is
/// this declaration's table and never the upstream's — which leaves the knob nothing to move and
/// exactly one thing a restatement can get wrong: WHICH upstream `const` this bit claims to be.
///
/// That is the vocabulary mirror's reading of the same word, reached from the other side. There a
/// restatement's words come from the upstream and the identifier is the only local thing; here the
/// words are local and the upstream identifier is the only foreign one. Both end at *`rename` names
/// the upstream*, and neither has two sources for one grammar.
fn rename(variant: &syn::Variant, bit: &mut FlagBit, mode: Mode, errors: &mut Errors) {
  attribute::walk(&variant.attrs, errors, |meta, errors| {
    if meta.path.is_ident("rename") {
      if mode == Mode::Mirror {
        match value::parse_literal::<syn::Ident>(
          &meta,
          "`rename = \"…\"` must be an identifier, in a string literal — on a mirror it names the \
           UPSTREAM `const` this bit restates, not a word: a flags set stores its bit PATTERN, so \
           the words are this declaration's own",
        ) {
          Ok(named) => set_once(
            &mut bit.upstream,
            named,
            &meta.path,
            "`rename` is declared more than once — one bit restates one upstream `const`",
            errors,
          ),
          Err(e) => errors.push(e),
        }
        return Ok(());
      }
      match value::literal(
        &meta,
        "`rename = \"…\"` must be a string literal — the word this bit is spelled with",
      ) {
        Ok(word) => {
          // ONE rename, because there is one word: a flags column stores its bit pattern, so the
          // wire is the only face with a name and the per-face blocks a vocabulary carries would
          // each move nothing.
          //
          // TWO grammars, and this kind is the only one that needs the second. Every other rename
          // in this crate becomes a string LITERAL; this one becomes the emitted `const`'s
          // identifier as well, so a word that is a Rust KEYWORD — `type`, `const`, `move` — would
          // reach `bitflags!` as `const type = 0x2u32;` and fail as a syntax error inside somebody
          // else's expansion, at a span the declaration cannot edit.
          wire::refuse_invalid_name(&word.value(), &word, errors);
          // Asked only of a word the FIRST grammar admitted, so one bad word earns one sentence.
          // Every GraphQL name is already a legal Rust identifier except for Rust's own keywords,
          // which is exactly the set this check exists for.
          if wire::is_graphql_name(&word.value())
            && syn::parse_str::<syn::Ident>(&word.value()).is_err()
          {
            errors.push(syn::Error::new_spanned(
              &word,
              format!(
                "`{}` is not usable as a Rust identifier, and a flag's word becomes one — this \
                 kind emits it as the `const` a caller writes `Self::{}` to reach. Rust's own \
                 keywords are the set this rules out",
                word.value(),
                word.value()
              ),
            ));
          }
          set_once(
            &mut bit.rename,
            word.value(),
            &meta.path,
            "`rename` is declared more than once — one declaration names one word",
            errors,
          );
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &meta,
      "unknown entry in `#[ingraph(…)]` on a flag — a bit takes `rename = \"…\"` and nothing \
       else. A flags column stores its BIT PATTERN in every database, so the wire is the only \
       face with a word for a per-face block to move",
      &["rename"],
    ));
    Ok(())
  });
}

/// The refusal for an option block left on the ITEM, where this door's options are its own
/// arguments.
///
/// The tokens are legal, so nothing else would report it: the block would ride the forwarding law
/// onto the minted type as an attribute nobody registered, and whatever it declared would be lost.
fn moved_option_block(attrs: &[syn::Attribute], errors: &mut Errors) {
  for attr in attrs.iter().filter(|attr| attr.path().is_ident("ingraph")) {
    errors.push(syn::Error::new_spanned(
      attr,
      "this declaration's options are the MACRO's arguments — write them inside the attribute's \
       own parentheses, as `#[ingraph::flags(u32)]`. A separate `#[ingraph(…)]` beside it is the \
       derive family's spelling, and nothing reads it here",
    ));
  }
}

/// Everything the author wrote that is not this door's, in the order they wrote it.
///
/// The attribute family's forwarding law: what an author wrote about their type stays true of the
/// type the door mints, and a bit's doc comment reaches the `const` `bitflags!` declares.
fn forwarded(attrs: &[syn::Attribute]) -> Vec<syn::Attribute> {
  attrs
    .iter()
    .filter(|attr| !attr.path().is_ident("ingraph"))
    .cloned()
    .collect()
}

/// The three collisions an expansion cannot survive: one bit declared twice, one WORD spelling two
/// bits, and one wire FIELD answering for two.
///
/// All three are duplicate definitions or a schema with two fields of one name, at a span the
/// declaration cannot edit — so they are refused here, with both bits named.
fn collisions(bits: &[FlagBit], errors: &mut Errors) {
  let mut values: BTreeMap<u128, &syn::Ident> = BTreeMap::new();
  for bit in bits {
    if let Some(first) = values.get(&bit.value) {
      errors.push(syn::Error::new_spanned(
        &bit.ident,
        format!(
          "`{}` and `{first}` are both bit `{:#x}` — two names for one bit is one value that reads \
           back as two flags, and a client asking for either would be asking the same question",
          bit.ident, bit.value
        ),
      ));
    } else {
      values.insert(bit.value, &bit.ident);
    }
  }

  for (what, spelled) in [
    ("word", bits.iter().map(FlagBit::word).collect::<Vec<_>>()),
    ("wire field", bits.iter().map(FlagBit::field).collect()),
  ] {
    let mut taken: BTreeMap<&str, &syn::Ident> = BTreeMap::new();
    for (bit, word) in bits.iter().zip(&spelled) {
      if let Some(first) = taken.get(word.as_str()) {
        errors.push(syn::Error::new_spanned(
          &bit.ident,
          format!(
            "`{}` and `{first}` are both `{word}` as a {what} — a flags set spells each bit once, \
             or a text form read back names two of them",
            bit.ident
          ),
        ));
      } else {
        taken.insert(word, &bit.ident);
      }
    }
  }
}

/// The TYPE, and only the type, for a declaration that was REFUSED.
///
/// An attribute macro replaces the item it sits on, so an expansion that emitted only the error
/// would delete the author's type and bury its own message under every mention of it. This is the
/// same rule the derived-index family states, answered the one way this kind can answer it: the
/// `bitflags!` struct is minted with whatever bits the manifest spelled, so `Self::FORCED` still
/// resolves while the reader reads the refusal about some other bit.
///
/// It evaluates NOTHING. Every value is forwarded as the author's own expression under a cast to the
/// width, because this path runs precisely when evaluation failed — and a bit whose expression is
/// wrong will say so at its own span, in the author's own tokens, rather than through a number
/// invented here.
pub(crate) fn salvage(
  input: &syn::DeriveInput,
  options: &[syn::Attribute],
) -> proc_macro2::TokenStream {
  use quote::quote;

  let mut sink = Errors::default();
  let Options { krate, width, .. } = self::options(options, &mut sink);
  let krate = krate.unwrap_or_else(|| syn::parse_quote!(::ingraph));
  let primitive = quote::format_ident!("{}", width.unwrap_or(BitWidth::U32).as_str());
  let vis = &input.vis;
  let name = &input.ident;
  let attrs = forwarded(&input.attrs);

  let bits = match &input.data {
    syn::Data::Enum(data) => data
      .variants
      .iter()
      .filter(|variant| matches!(variant.fields, syn::Fields::Unit))
      .filter_map(|variant| {
        let (_, expression) = variant.discriminant.as_ref()?;
        let constant = quote::format_ident!(
          "{}",
          heck::ToShoutySnakeCase::to_shouty_snake_case(
            syn::ext::IdentExt::unraw(&variant.ident)
              .to_string()
              .as_str()
          )
        );
        let forwarded = forwarded(&variant.attrs);
        Some(quote! {
          #(#forwarded)*
          const #constant = (#expression) as ::core::primitive::#primitive;
        })
      })
      .collect::<Vec<_>>(),
    _ => Vec::new(),
  };

  quote! {
    #krate::__private::bitflags::bitflags! {
      #(#attrs)*
      #vis struct #name: ::core::primitive::#primitive {
        #(#bits)*
      }
    }
  }
}