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
//! **THE CONSTRUCTION PROTOCOL's grammar** — one reader for every saddle that has to build a value
//! it did not declare.
//!
//! The MODEL and the WRITER are `ingraph_codegen::construct`; this is the front half — the words,
//! the parse, and the refusals that are about a declaration's SHAPE rather than about an API this
//! crate cannot see. It lives in one module rather than beside its first consumer because the suite
//! is a FAMILY FACILITY: the rewrite mode's raise mounts it today, a field fragment's assembly
//! mounts it next, and a grammar copied to a second mount is a grammar whose two copies disagree by
//! the third round.
//!
//! # TWO SEATS, ONE WORD
//!
//! `builder(…)` is written on the DECLARATION for facts about the protocol, and on a FIELD for that
//! column's place in it. The same word at both levels is what makes the facility readable as one
//! thing — and it is why the field words live inside a block rather than bare beside `copy` and
//! `optional`: `skip`, `into` and `option` all already mean something in a neighbouring scope of
//! this grammar (`skip` is *no column in any database*, `<db>(into = "…")` is the
//! whole-body escape, and `optional` is the projection a near-miss reader would offer for
//! `option`), and three collisions in one vocabulary is a grammar teaching its own author the wrong
//! thing.
//!
//! # WHAT IS CHECKED HERE, and what the compiler is left to check
//!
//! Everything in this module is a rule about the DECLARATION: that a `finish_arg` has a `finish` to
//! be an argument of, that one field fills one seat, that a `call` naming a method also names what
//! to hand it, that a word only a wrapper can spend is not written where nothing is wrapped. Every
//! rule about the REMOTE — that the entry exists, that the finish exists, that a seat takes what it
//! is handed — is discharged by the compiler at the call [`ingraph_codegen::construct`] writes, at a
//! span the emission puts on the author's own token. That split is the rewrite mode's own and this
//! vocabulary does not move it: a macro holding tokens cannot resolve a method, and a grammar that
//! pretended to would be checking a copy of the upstream rather than the upstream.

use ingraph_codegen::construct::{Blanket, Build, Construction, Cross, Injection, Seat};
use quote::ToTokens as _;

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

/// The word both seats are written under.
pub(crate) const WORD: &str = "builder";

/// The CONTAINER's own vocabulary, in the order a refusal offers it.
const CONTAINER: [&str; 5] = ["entry", "finish", "fallible", "on", "call"];

/// The FIELD's vocabulary, in the order a refusal offers it.
const FIELD: [&str; 8] = [
  "arg",
  "finish_arg",
  "with",
  "set",
  "into",
  "map",
  "option",
  "skip",
];

/// The three SEAT words, which is the set a field picks exactly one of.
const SEATS: [&str; 4] = ["arg", "finish_arg", "with", "set"];

/// The refusal a value that should have named a Rust method does not.
const METHOD: &str = "must name a METHOD, as a plain identifier in a string literal";

/// The DECLARATION's `builder(…)` — the protocol's own facts.
///
/// # Errors
/// Whatever the nested walk hit. An entry the block does not take is RECORDED and the walk
/// continues, so one declaration reports every offender.
pub(crate) fn container(
  meta: &syn::meta::ParseNestedMeta<'_>,
  slot: &mut Option<Construction>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let mut declared = Construction {
    at: Some(meta.path.clone()),
    ..Construction::default()
  };
  let mut entry_at: Option<syn::Path> = None;
  let mut finish_at: Option<syn::Path> = None;
  let mut fallible_at: Option<syn::Path> = None;
  let walked = attribute::options(meta, |inner| {
    if inner.path.is_ident("entry") {
      match value::parse_literal::<syn::Ident>(&inner, &format!("`entry = \"…\"` {METHOD}")) {
        Ok(name) => {
          if entry_at.is_none() {
            declared.entry = name;
          }
          attribute::set_once(
            &mut entry_at,
            inner.path.clone(),
            &inner.path,
            "`entry` is declared more than once — one protocol opens with one call",
            errors,
          );
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if inner.path.is_ident("finish") {
      match value::parse_literal::<syn::Ident>(&inner, &format!("`finish = \"…\"` {METHOD}")) {
        Ok(name) => {
          if finish_at.is_none() {
            declared.finish = Some(name);
          }
          attribute::set_once(
            &mut finish_at,
            inner.path.clone(),
            &inner.path,
            "`finish` is declared more than once — one protocol closes with one call",
            errors,
          );
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if inner.path.is_ident("fallible") {
      attribute::skip_entry(&inner);
      attribute::set_once(
        &mut fallible_at,
        inner.path.clone(),
        &inner.path,
        "`fallible` is declared more than once — one word, one protocol",
        errors,
      );
      declared.fallible = true;
      return Ok(());
    }
    if inner.path.is_ident("on") {
      match blanket(&inner) {
        Ok(rule) => declared.blanket.push(rule),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if inner.path.is_ident("call") {
      match injection(&inner, errors) {
        Ok(call) => declared.calls.push(call),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &inner,
      "unknown entry in `builder(…)` on a declaration — it takes `entry = \"…\"`, \
       `finish = \"…\"`, `fallible`, `on(<Type>, into)` and `call(with = \"…\", value = \"…\")`. \
       The per-column words — `arg`, `with`, `set`, `map` and the rest — are written in a \
       `builder(…)` on the FIELD they are about",
      &CONTAINER,
    ));
    Ok(())
  });
  attribute::set_once(
    slot,
    declared,
    &meta.path,
    "`builder` is declared more than once — one declaration describes one protocol",
    errors,
  );
  walked
}

/// A FIELD's `builder(…)` — which seat this column fills, and how its value crosses.
///
/// # Errors
/// Whatever the nested walk hit, for [`container`]'s reason.
pub(crate) fn field(
  meta: &syn::meta::ParseNestedMeta<'_>,
  slot: &mut Option<Build>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let mut declared = Build {
    at: Some(meta.path.clone()),
    ..Build::default()
  };
  // The SEAT words, gathered rather than settled one at a time: they are mutually exclusive, and a
  // refusal that names the pair has to have seen both.
  let mut seats: Vec<(&'static str, syn::Path)> = Vec::new();
  let mut cross_at: Option<syn::Path> = None;
  let mut option_at: Option<syn::Path> = None;
  let mut skip_at: Option<syn::Path> = None;
  let walked = attribute::options(meta, |inner| {
    if let Some(word) = SEATS.into_iter().find(|word| inner.path.is_ident(word)) {
      match seat(&inner, word) {
        Ok(taken) => {
          if seats.is_empty() {
            declared.seat = Some(taken);
          }
          seats.push((word, inner.path.clone()));
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if inner.path.is_ident("into") {
      attribute::skip_entry(&inner);
      set_cross(
        &mut declared,
        &mut cross_at,
        Cross::Into,
        &inner.path,
        errors,
      );
      return Ok(());
    }
    if inner.path.is_ident("map") {
      match value::parse_literal::<syn::Path>(
        &inner,
        "`map = \"…\"` names the FUNCTION this column's value crosses through — a `fn(T) -> U`, as \
         a path in a string literal",
      ) {
        Ok(path) => set_cross(
          &mut declared,
          &mut cross_at,
          Cross::Map(path),
          &inner.path,
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if inner.path.is_ident("option") {
      attribute::skip_entry(&inner);
      attribute::set_once(
        &mut option_at,
        inner.path.clone(),
        &inner.path,
        "`option` is declared more than once on this field — one word, one column",
        errors,
      );
      declared.option = true;
      return Ok(());
    }
    if inner.path.is_ident("skip") {
      attribute::skip_entry(&inner);
      attribute::set_once(
        &mut skip_at,
        inner.path.clone(),
        &inner.path,
        "`skip` is declared more than once in `builder(…)` on this field — one word, one column",
        errors,
      );
      declared.skip = true;
      return Ok(());
    }
    errors.push(attribute::unknown(
      &inner,
      "unknown entry in `builder(…)` on a field — it takes one SEAT word (`arg`, `finish_arg`, \
       `with[ = \"…\"]`, `set[ = \"…\"]`), one CROSSING word (`into`, `map = \"…\"`), and the two \
       that stand on their own: `option` and `skip`. `entry`, `finish`, `fallible`, `on` and \
       `call` are facts about the whole protocol and are written on the DECLARATION",
      &FIELD,
    ));
    Ok(())
  });
  refuse_two_seats(&seats, errors);
  refuse_a_skipped_seat(skip_at.as_ref(), &seats, errors);
  refuse_a_pinned_option(option_at.as_ref(), cross_at.as_ref(), &declared, errors);
  attribute::set_once(
    slot,
    declared,
    &meta.path,
    "`builder` is declared more than once on this field — one column fills one seat",
    errors,
  );
  walked
}

/// One SEAT word, with the rename it may carry.
///
/// `arg` and `finish_arg` are positions rather than names and take no value; `with` and `set` name
/// a method, and take the method's own name where the default one is wrong.
///
/// # Errors
/// [`METHOD`] where a rename is not a method name, and a named refusal where a position was given
/// one.
fn seat(meta: &syn::meta::ParseNestedMeta<'_>, word: &'static str) -> syn::Result<Seat> {
  match word {
    "arg" | "finish_arg" => {
      if attribute::has_value(meta) || attribute::has_block(meta) {
        return Err(attribute::named(
          meta,
          format!(
            "`{word}` names a POSITION in an argument list, not a method — there is nothing here \
             to rename. The words that take a name are `with = \"…\"` and `set = \"…\"`"
          ),
        ));
      }
      attribute::skip_entry(meta);
      Ok(if word == "arg" {
        Seat::Arg
      } else {
        Seat::FinishArg
      })
    }
    _ => {
      if !attribute::has_value(meta) {
        attribute::skip_entry(meta);
        return Ok(if word == "with" {
          Seat::With(None)
        } else {
          Seat::Set(None)
        });
      }
      let name = value::parse_literal::<syn::Ident>(meta, &format!("`{word} = \"…\"` {METHOD}"))?;
      Ok(if word == "with" {
        Seat::With(Some(name))
      } else {
        Seat::Set(Some(name))
      })
    }
  }
}

/// Fill the CROSSING slot once — `into` and `map` are two answers to one question.
fn set_cross(
  declared: &mut Build,
  at: &mut Option<syn::Path>,
  cross: Cross,
  path: &syn::Path,
  errors: &mut Errors,
) {
  if at.is_none() {
    declared.cross = Some(cross);
  }
  attribute::set_once(
    at,
    path.clone(),
    path,
    "a column crosses ONE way — `into` pins the bridge's target and `map = \"…\"` replaces the \
     bridge with a function of your own, and a field that wrote both has said two things about one \
     argument",
    errors,
  );
}

/// `on(<Type>, into)` — read from the entry's RAW TOKENS rather than as nested meta.
///
/// The type has to be a real [`syn::Type`], and a meta path cannot be one: `Option<u8>` and
/// `[u8; 4]` are types this rule may legitimately be keyed by, and neither parses as the
/// `::`-separated path a nested-meta walk reads. So the group is taken verbatim and parsed here.
///
/// # Errors
/// A named refusal where the entry is not `(<Type>, into)`.
fn blanket(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<Blanket> {
  const SHAPE: &str = "`on(…)` states a crossing for every column of ONE TYPE, and is written \
                       `on(<Type>, into)` — the type first, then the word";

  if !attribute::has_block(meta) {
    return Err(attribute::named(meta, SHAPE.to_owned()));
  }
  let tokens = attribute::verbatim(meta)?;
  let at = tokens.clone();
  let rule = syn::parse2::<Rule>(tokens).map_err(|_| syn::Error::new_spanned(&at, SHAPE))?;
  if rule.words.len() != 1 || rule.words[0] != "into" {
    return Err(syn::Error::new_spanned(
      &at,
      format!(
        "{SHAPE}. `into` is the only crossing a blanket states today: it says every column of the \
         type reaches a seat spelled `impl Into<…>`, which is the one fact a per-type rule can \
         carry — a `map` function is per column and belongs on the column"
      ),
    ));
  }
  Ok(Blanket { ty: rule.ty })
}

/// The `(<Type>, into)` shape, as a parse.
struct Rule {
  ty: syn::Type,
  words: Vec<syn::Ident>,
}

impl syn::parse::Parse for Rule {
  fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
    let ty = input.parse::<syn::Type>()?;
    let mut words = Vec::new();
    while input.parse::<Option<syn::Token![,]>>()?.is_some() {
      if input.is_empty() {
        break;
      }
      words.push(input.parse::<syn::Ident>()?);
    }
    if input.is_empty() {
      return Ok(Self { ty, words });
    }
    Err(input.error("a trailing token"))
  }
}

/// `call(with = "…", value = "…")` — a link no column feeds.
///
/// # Errors
/// A named refusal where either half is missing: a method with nothing to hand it is not a call,
/// and a value with no method to hand it to has nowhere to go.
fn injection(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> syn::Result<Injection> {
  // The tail every sentence below ends on, so a `call` that is wrong in two ways is told its shape
  // once rather than lead with the same clause twice.
  const SHAPE: &str = "a `call` names the method and what to hand it, and is written \
                       `call(with = \"with_thing\", value = \"<expr>\")`";

  let mut method: Option<syn::Ident> = None;
  let mut supplied: Option<syn::Expr> = None;
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    return Err(attribute::named(
      meta,
      format!("`call(…)` is a link this declaration supplies rather than a column — {SHAPE}"),
    ));
  }
  meta.parse_nested_meta(|inner| {
    if inner.path.is_ident("with") {
      match value::parse_literal::<syn::Ident>(&inner, &format!("`with = \"…\"` {METHOD}")) {
        Ok(name) => attribute::set_once(
          &mut method,
          name,
          &inner.path,
          "`with` is declared more than once in `call(…)` — one entry, one method",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if inner.path.is_ident("value") {
      match value::parse_literal::<syn::Expr>(
        &inner,
        "`value = \"…\"` is the EXPRESSION this link is handed, in a string literal — a literal, a \
         path, a call, whatever the upstream's argument really is",
      ) {
        Ok(expr) => attribute::set_once(
          &mut supplied,
          expr,
          &inner.path,
          "`value` is declared more than once in `call(…)` — one link carries one argument",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &inner,
      &format!("unknown entry in `call(…)` — {SHAPE}"),
      &["with", "value"],
    ));
    Ok(())
  })?;
  match (method, supplied) {
    (Some(method), Some(value)) => Ok(Injection { method, value }),
    (Some(_), None) => Err(syn::Error::new_spanned(
      &meta.path,
      format!(
        "`call(…)` names a method and hands it nothing — a link with no argument is a call this \
         emission has no way to write: {SHAPE}"
      ),
    )),
    (None, _) => Err(syn::Error::new_spanned(
      &meta.path,
      format!("`call(…)` supplies a value and names no method to hand it to: {SHAPE}"),
    )),
  }
}

/// **ONE COLUMN FILLS ONE SEAT** — two seat words on one field are refused, naming both.
fn refuse_two_seats(seats: &[(&'static str, syn::Path)], errors: &mut Errors) {
  let [(first, _), (second, at), ..] = seats else {
    return;
  };
  errors.push(syn::Error::new_spanned(
    at,
    format!(
      "`{first}` and `{second}` are both declared on this field, and each names a DIFFERENT place \
       in the protocol — a column's value is handed over once. `arg` and `finish_arg` are \
       positions in the two argument lists; `with` is a link that consumes and returns the value \
       and `set` is one that mutates it in place"
    ),
  ));
}

/// **A SKIPPED COLUMN HAS NO SEAT**, so a seat word beside `skip` is refused rather than ignored.
fn refuse_a_skipped_seat(
  skip: Option<&syn::Path>,
  seats: &[(&'static str, syn::Path)],
  errors: &mut Errors,
) {
  let (Some(skip), Some((word, _))) = (skip, seats.first()) else {
    return;
  };
  errors.push(syn::Error::new_spanned(
    skip,
    format!(
      "`skip` says this column is NOT handed back to the construction at all, and `{word}` says \
       which call it is handed to — one of them is not true. Delete whichever states the wrong \
       thing; a skipped column is filled by whatever the wrapped type's own constructor puts \
       there, which is a round trip only its author can vouch for"
    ),
  ));
}

/// **`into` PINS A TARGET AND `option` CROSSES INSIDE ONE**, which are two different arguments.
fn refuse_a_pinned_option(
  option: Option<&syn::Path>,
  cross: Option<&syn::Path>,
  declared: &Build,
  errors: &mut Errors,
) {
  let (Some(option), Some(_), Some(Cross::Into)) = (option, cross, declared.cross.as_ref()) else {
    return;
  };
  errors.push(syn::Error::new_spanned(
    option,
    "`into` pins the crossing's target to the type this field restates, and `option` says the \
     crossing happens INSIDE the option rather than over it — so together they pin the option \
     where the item is what crosses. Where the seat really is `impl Into<Option<…>>`, `into` \
     alone says so; where it takes the option and the ITEM has to cross, `option` alone does",
  ));
}

/// **A CONSTRUCTION WORD IS A WRAPPER'S WORD** — every one of them is refused where nothing is
/// wrapped.
///
/// An ordinary declaration IS its fields: a raise builds it with a struct literal, and there is no
/// call sequence for a word to describe. So a `builder(…)` written on one is not a word with no
/// effect — it is a protocol its author believes they declared, which is the standing reason this
/// grammar refuses rather than ignores.
///
/// The sentence names the ESCAPE as well as the rule, because the author who reaches for these
/// words on an own declaration is usually one field away from the mode that serves them.
pub(crate) fn refuse_without_a_remote(
  remote: Option<&syn::Path>,
  construction: Option<&syn::Path>,
  fields: impl Iterator<Item = syn::Path>,
  noun: &str,
  errors: &mut Errors,
) {
  if remote.is_some() {
    return;
  }
  for at in construction.cloned().into_iter().chain(fields) {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{WORD}(…)` describes how a type SOMEBODY ELSE declared is built, and this {noun} is its \
         own fields — a raise writes the struct literal, and there is no call sequence for these \
         words to describe. They belong on a declaration carrying `remote = \"…\"`"
      ),
    ));
  }
}

/// **A `finish_arg` NEEDS A `finish`** — the argument list it names does not otherwise exist.
///
/// The one cross-seat rule in the suite, and it is checked at the ASSEMBLY rather than at either
/// walk because neither half can see the other: the word is on a field and what it refers to is on
/// the declaration.
pub(crate) fn refuse_a_homeless_argument(
  construction: &Construction,
  fields: &[(syn::Ident, Build)],
  errors: &mut Errors,
) {
  if construction.finish.is_some() {
    return;
  }
  for (name, build) in fields {
    if !matches!(build.seat, Some(Seat::FinishArg)) {
      continue;
    }
    let at = build
      .at
      .as_ref()
      .map_or_else(|| name.to_token_stream(), quote::ToTokens::to_token_stream);
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`finish_arg` puts `{name}` in the argument list of the protocol's CLOSING call, and this \
         declaration has no closing call — without `builder(finish = \"…\")` the entry hands back \
         the value itself and there is one argument list. Write the `finish`, or make this an \
         `arg`"
      ),
    ));
  }
}

/// **`option` IS ABOUT AN OPTION**, so it is refused on a column that has no empty state.
///
/// The word says the seat takes the option WHOLE and the crossing happens inside it, which is a
/// sentence about a column that can be absent. A column that cannot has nothing for the crossing to
/// reach inside, and the emitted `Option::map` would be `E0599` inside an expansion. `optional` is
/// this grammar's own word for the empty state and it is the one the check reads — never the field's
/// spelled type, per the standing rule that a macro holds tokens and `type Maybe = Option<T>` is why
/// a spelling cannot be trusted.
pub(crate) fn refuse_a_whole_non_option(
  optional: bool,
  build: Option<&Build>,
  errors: &mut Errors,
) {
  let Some(build) = build else { return };
  if optional || !build.option {
    return;
  }
  let at = build.at.as_ref().expect("a parsed block keeps its word");
  errors.push(syn::Error::new_spanned(
    at,
    "`option` says the seat takes this column's `Option` WHOLE — crossing the item rather than the \
     option — and this column has no empty state to take. `optional` is what declares one, and it \
     is read rather than the field's spelled type: a macro holds tokens, and a type alias hiding an \
     `Option` is exactly why a spelling is not trusted here",
  ));
}

#[cfg(test)]
mod tests;