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
//! The DELEGATE SEAT's acceptance — one grammar, read once, for the two declarations that spend it.
//!
//! ```text
//! delegate(
//!   fn to_u32(&self) -> Option<u32>,              // plain Rust, forwarded
//!   #[graphql(async_graphql)]                     // …and published
//!   fn is_bayer(&self) -> bool,
//!   #[graphql(async_graphql(rename = "bayer"))]   // …under a word a client writes
//!   fn is_hdr(&self) -> bool,
//! )
//! ```
//!
//! An entry is a FUNCTION — a noun — and `#[graphql(…)]` is an adjective on it rather than a second
//! kind of entry. Everything about the entry is the signature's, unchanged by the attribute.
//!
//! # TWO SPELLINGS, and a block is written in one of them
//!
//! The block above is the SHORTHAND — a list of bare signatures — and it is what every entry written
//! before the seat had a second property says. The FULL FORM names every property of ONE entry:
//!
//! ```text
//! delegate(
//!   #[graphql(async_graphql)]
//!   signature = fn aspect(&self) -> String,
//!   on = self,
//! )
//! ```
//!
//! [`ON`] is why the second spelling exists. A bare signature is a POSITION, and a position beside a
//! named property is a grammar where an author has to know which words may be written loose — so the
//! moment an entry says more than its signature, every property it has is named. The two are not
//! mixed in one block, and a block that mixes them is refused at the token that mixed them, pointing
//! at the full spelling. Nothing is lost by the split: a `delegate(…)` block ACCUMULATES, so an
//! entry that needs a property takes a block of its own beside the shorthand list.
//!
//! # Why the grammar is here and the SENTENCES are not
//!
//! A vocabulary MIRROR forwards onto an upstream value it materialises from a stored word; a FIELD
//! FRAGMENT reaches a method already on `Self` — the value it wraps, or the author's own inherent
//! `impl`. The rules are the same to the letter — the receiver is borrowed, the signature is
//! restated because Rust has no `typeof`, one word per backend, `rename` and nothing else — and only
//! the REASONS differ. A second reading of the rules beside the first is how the two come to
//! disagree about a grammar the ruling says is one, so the reasons arrive as [`Delegation`] and the
//! rules do not move.
//!
//! **ORIGIN is nobody's rule here.** Neither tier asks where the named method came from: every
//! emitted body is method-resolution syntax and rustc answers it, so a name nothing answers to is
//! `E0599` at the restatement. What each tier decides is what an entry BUYS, which is its emission's
//! question rather than this door's.

use ingraph_codegen::{
  delegate::{Delegate, DelegateSkin},
  model::GraphqlKind,
};
use syn::ext::IdentExt as _;

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

/// The word a declaration opens the seat with.
pub(crate) const WORD: &str = "delegate";

/// **`on = self`** — the word that says the named method is the DECLARED type's own.
///
/// # What it moves, and the one thing it does not
///
/// BOTH tiers mint a forwarding method per entry, and for one reason written two ways: the method
/// the entry names lives on a value the declaration is not, so an inherent one is what a caller and
/// a doc page get. A field fragment's mint calls it on the value it HOLDS, otherwise reachable only
/// through `Deref`; a vocabulary mirror's MATERIALIZES the upstream from a stored word and calls it
/// there.
///
/// For a method the author wrote on the DECLARED type that mint is not a convenience but a defect,
/// identically at both: the wrapped or upstream value has no such method (`E0599`), or the author's
/// own inherent one is already there and the two are duplicate definitions (`E0592`). Neither is
/// reachable from the declaration's own tokens — the author cannot edit the expansion — so the door
/// is a word.
///
/// It moves the FORWARDING half and nothing else. A published entry's LIFTED field is emitted
/// exactly as before, because that body is a QUALIFIED call on the declared type — `Self::m(self)`
/// at the fragment, `<Enum>::m(self)` in the mirror's resolver arm — and method resolution answers
/// it the same way whether the method is the author's or a mint's. That is the seat's own letter,
/// that origin is rustc's question rather than this grammar's.
///
/// # The roster is one word, and a second target is a DOOR
///
/// `self` is the whole of what the word admits. What another value would name is a place other than
/// the declared type for the call to land — the wrapped value by name, the materialized upstream, an
/// intermediate a wrapper derefs through — and none of them has a consumer, so none is built. A
/// value outside the roster is refused by name rather than parsed into a model nothing spends.
pub(crate) const ON: &str = "on";

/// The FULL FORM's other property: the signature the entry restates.
const SIGNATURE: &str = "signature";

/// The one target [`ON`] admits.
const SELF: &str = "self";

/// The refusal a block that MIXES the two spellings earns, and the sentence every full-form parse
/// failure lands on.
///
/// A near-miss rather than an unknown word: an author who wrote `delegate(fn m(&self), on = self)`
/// has the right idea and the wrong shape, and the useful answer is the exact spelling that says it.
const FULL_FORM: &str = "`delegate(…)` is written in ONE of two spellings and never half of each. \
                         The SHORTHAND is a list of bare signatures — \
                         `delegate(fn m(&self) -> T, fn n(&self))` — and it says nothing but the \
                         methods. The FULL FORM names every property of ONE entry: \
                         `delegate(signature = fn m(&self) -> T, on = self)`, with any \
                         `#[graphql(…)]` leading it exactly as it leads a bare one. A bare \
                         signature and a named property in one block is neither. Nothing is lost by \
                         the split: the seat ACCUMULATES, so an entry that needs a property takes a \
                         `delegate(…)` block of its own beside the shorthand list";

/// What ONE tier's refusals say, where the rule is shared and the reason is not.
///
/// Two sentences, because two rules are about what a receiver MEANS and that is the one thing a
/// mirror and a wrapper do differently: a mirror stores a word and must materialise, mutate and
/// convert home; a wrapper holds the value and mutates it in place.
pub(crate) struct Delegation<'a> {
  /// Why a delegated method must borrow its receiver.
  pub receiver: &'a str,
  /// Why an exclusive receiver cannot also be published.
  pub exclusive: &'a str,
}

/// The whole `delegate(…)` block, appended to whatever earlier blocks named.
///
/// ACCUMULATED rather than replacing: a second `delegate(…)` names more methods, where every other
/// repeated block in these grammars is a second answer to one question. That is also what makes the
/// two spellings cost nothing to keep apart — an entry needing a property takes a block of its own.
///
/// The spelling is read off the FIRST thing the block says, and off nothing else: a shorthand entry
/// opens with `#` or with `fn`, and neither peeks as a bare identifier, so a leading `<word> =` is
/// the full form unambiguously.
///
/// # Errors
/// Whatever the group, a property or a signature inside it refuses, at its own token.
pub(crate) fn block(
  meta: &syn::meta::ParseNestedMeta<'_>,
  delegates: &mut Vec<Delegate>,
  tier: &Delegation<'_>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let content;
  syn::parenthesized!(content in meta.input);
  if opens_a_property(&content) {
    let (attrs, signature, on_self) = full(&content, errors)?;
    delegated(&attrs, signature, on_self, delegates, tier, errors);
    return Ok(());
  }
  let written = content.parse_terminated(entry, syn::Token![,])?;
  for (attrs, signature) in written {
    delegated(&attrs, signature, None, delegates, tier, errors);
  }
  Ok(())
}

/// Whether the block's first entry is written as a NAMED PROPERTY rather than as a bare signature.
///
/// Read on a FORK, because the answer decides which parser consumes the stream and a peek that had
/// consumed the attributes would leave the shorthand's own reader without them.
fn opens_a_property(content: syn::parse::ParseStream<'_>) -> bool {
  let ahead = content.fork();
  ahead.call(syn::Attribute::parse_outer).is_ok() && names_a_property(&ahead)
}

/// Whether the stream is positioned at `<word> =` — the one shape a property opens with.
///
/// [`syn::Ident`] does not peek a Rust keyword, which is what makes this total rather than a guess:
/// `fn` cannot be read as a property word, and `signature` and [`ON`] cannot be read as the start of
/// a signature.
fn names_a_property(input: syn::parse::ParseStream<'_>) -> bool {
  input.peek(syn::Ident) && input.peek2(syn::Token![=])
}

/// The FULL FORM: one entry, with every property it has written by name.
///
/// The attribute leads the properties exactly as it leads a bare signature — `#[graphql(…)]` is an
/// adjective on the ENTRY in both spellings, and the entry is what the property list describes.
///
/// A property whose VALUE this pass can step over is RECORDED and the walk continues, so one block
/// reports every offender; one it cannot — a signature that does not parse, a target that is not
/// even a word — is terminal, because a token stream this reader has lost its place in cannot be
/// resynchronised into anything an author would recognise.
///
/// # Errors
/// [`FULL_FORM`] where the block mixes the spellings or names no signature, and whatever a property
/// name, a signature or a separator refuses at its own token.
fn full(
  content: syn::parse::ParseStream<'_>,
  errors: &mut Errors,
) -> syn::Result<(Vec<syn::Attribute>, syn::Signature, Option<syn::Ident>)> {
  // The span a refusal ABOUT THE WHOLE ENTRY reports at, taken before anything is consumed: at the
  // end of the walk the stream is empty and its span is the closing delimiter's, which points past
  // the thing the sentence is about.
  let opens = content.span();
  let attrs = content.call(syn::Attribute::parse_outer)?;
  let mut signature: Option<syn::Signature> = None;
  let mut on: Option<syn::Ident> = None;
  let mut seen: Vec<syn::Ident> = Vec::new();

  while !content.is_empty() {
    if !names_a_property(content) {
      return Err(syn::Error::new(content.span(), FULL_FORM));
    }
    let word = content.parse::<syn::Ident>()?;
    content.parse::<syn::Token![=]>()?;
    let twice = seen.iter().any(|first| first == &word);
    if twice {
      errors.push(syn::Error::new_spanned(
        &word,
        format!(
          "`{word}` is declared more than once in `delegate(…)` — one entry answers each property \
           once, and a second answer to one question is not a second entry: write another \
           `delegate(…)` block, which the seat accumulates onto this one"
        ),
      ));
    }
    seen.push(word.clone());

    if word == SIGNATURE {
      let restated = content.parse::<syn::Signature>()?;
      if !twice {
        signature = Some(restated);
      }
    } else if word == ON {
      let target = target(content)?;
      if !twice {
        if target == SELF {
          on = Some(target);
        } else {
          errors.push(syn::Error::new_spanned(&target, off_the_roster(&target)));
        }
      }
    } else {
      errors.push(syn::Error::new_spanned(
        &word,
        format!(
          "unknown property in `delegate(…)` — the FULL FORM names the entry's SIGNATURE and where \
           its method LIVES, and nothing else. What a client calls a published method is the \
           entry's own `#[graphql(<backend>(rename = \"…\"))]`, which LEADS the properties rather \
           than sitting among them{suggestion}",
          suggestion = crate::suggest::did_you_mean(&word.unraw().to_string(), [SIGNATURE, ON]),
        ),
      ));
      skip_value(content);
    }

    if content.is_empty() {
      break;
    }
    content.parse::<syn::Token![,]>()?;
  }

  let Some(signature) = signature else {
    return Err(syn::Error::new(
      opens,
      format!("`delegate(…)` names no method here — every entry restates one. {FULL_FORM}"),
    ));
  };
  Ok((attrs, signature, on))
}

/// Step over the VALUE of a property this reader has already refused, up to the separator.
///
/// [`attribute::skip_entry`]'s walk over a property list rather than over a nested meta, and it is
/// here for that reader's own reason: one rule broken should cost one error rather than one plus a
/// parse failure at the token after it.
fn skip_value(content: syn::parse::ParseStream<'_>) {
  while !content.is_empty() && !content.peek(syn::Token![,]) {
    if content.parse::<proc_macro2::TokenTree>().is_err() {
      return;
    }
  }
}

/// The value [`ON`] takes — a WORD, read with `parse_any` because the one the roster admits is a
/// Rust keyword.
///
/// # Errors
/// [`off_the_roster`] where the value is not a word at all, which is the one shape this pass cannot
/// step over.
fn target(content: syn::parse::ParseStream<'_>) -> syn::Result<syn::Ident> {
  let at = content.span();
  content
    .call(syn::Ident::parse_any)
    .map_err(|_| syn::Error::new(at, off_the_roster_shape()))
}

/// The refusal a target outside the roster earns, spanned at the word that named it.
fn off_the_roster(target: &syn::Ident) -> String {
  format!(
    "`{ON} = {target}` names no target this seat has. {}",
    off_the_roster_shape()
  )
}

/// WHAT the roster is, in one sentence — shared by the refusal for a word off it and the one for a
/// value that is not a word.
fn off_the_roster_shape() -> String {
  format!(
    "`{ON}` takes `{SELF}`, and `{SELF}` is the whole of it: the word says the entry's method is the \
     DECLARED type's own, so no forwarding half is minted for it. A place other than that type for \
     the call to land — the wrapped value under a name, the materialized upstream, an intermediate a \
     wrapper derefs through — is a door and not a plan, and none of them has a consumer yet. Write \
     `{ON} = {SELF}`, or drop the property: an entry without one forwards exactly as it did"
  )
}

/// ONE entry of a SHORTHAND `delegate(…)` block — whatever attributes it wears, then the signature
/// itself.
///
/// A [`syn::Signature`] carries no attributes of its own, which is what makes the pair explicit
/// here: the WIRE knob is an outer attribute on the entry, so the two halves are parsed side by side
/// and travel together.
///
/// # Errors
/// [`FULL_FORM`] where a NAMED PROPERTY was written among bare signatures — the near-miss this
/// grammar's second spelling makes reachable — and otherwise whatever the attribute list or the
/// signature refuses, at its own token.
pub(crate) fn entry(
  input: syn::parse::ParseStream<'_>,
) -> syn::Result<(Vec<syn::Attribute>, syn::Signature)> {
  let attrs = input.call(syn::Attribute::parse_outer)?;
  if names_a_property(input) {
    return Err(syn::Error::new(input.span(), FULL_FORM));
  }
  let signature = input.parse::<syn::Signature>()?;
  Ok((attrs, signature))
}

/// One entry, validated into the model — or refused, at the token that broke it.
///
/// A signature whose RECEIVER is wrong is dropped rather than carried, since everything downstream
/// of it (the emitted body, the published word, the collision walk) is a claim about a method this
/// declaration cannot have. Its refusal is already recorded, so the declaration still gets every
/// other rule this pass can see violated.
fn delegated(
  attrs: &[syn::Attribute],
  signature: syn::Signature,
  on_self: Option<syn::Ident>,
  delegates: &mut Vec<Delegate>,
  tier: &Delegation<'_>,
  errors: &mut Errors,
) {
  let Some(exclusive) = receiver(&signature, tier, errors) else {
    return;
  };
  let wire = published(attrs, &signature, exclusive, tier, errors);
  delegates.push(Delegate {
    signature,
    exclusive,
    wire,
    on_self,
  });
}

/// The two shapes a delegated signature may take its receiver in, and which one this is.
///
/// `&self` FORWARDS — the emitted body materializes the upstream value and calls the method on it —
/// and `&mut self` WRITES BACK, materializing, mutating and converting home. A consuming `self` has
/// nothing to consume, the mirror being the caller's rather than the upstream's, and a signature
/// with no receiver at all has nothing to forward from. Both are refused HERE, at the receiver the
/// declaration wrote, rather than inside an expansion the declaration cannot edit.
///
/// [`None`] is the refusal, already pushed. [`Some`] carries whether the borrow is EXCLUSIVE, which
/// is the one fact the emission forks its body on.
fn receiver(
  signature: &syn::Signature,
  tier: &Delegation<'_>,
  errors: &mut Errors,
) -> Option<bool> {
  let why = tier.receiver;
  match signature.inputs.first() {
    Some(syn::FnArg::Receiver(syn::Receiver {
      kind: syn::ReceiverKind::Reference(_, _, exclusive),
      ..
    })) => Some(exclusive.is_some()),
    Some(argument) => {
      errors.push(syn::Error::new_spanned(argument, why));
      None
    }
    None => {
      errors.push(syn::Error::new_spanned(&signature.ident, why));
      None
    }
  }
}

/// `#[graphql(<backend>)]` — the INCREMENTAL knob that publishes one delegated method.
///
/// An adjective on a noun, which is what keeps the grammar one list: an entry is a FUNCTION, and the
/// attribute says that function also reaches a schema. Everything about the entry — its name, its
/// receiver, its return type — is the signature's, unchanged by the attribute's presence.
///
/// Four refusals, each at the token that earned it:
///
/// - **any other attribute** on an entry — a `delegate(…)` entry is not an item, and an attribute
///   this grammar does not read would be a rule its author believes they declared;
/// - **`#[graphql]` naming no backend** — a wire face is one backend's impls, which is the union's
///   own empty-block law one declaration over;
/// - **a backend named twice** — one word per backend, a second being a re-description of the first;
/// - **`#[graphql(…)]` on `&mut self`** — a resolver READS, and an exclusive receiver's body writes
///   a new value back into the row it was called on.
fn published(
  attrs: &[syn::Attribute],
  signature: &syn::Signature,
  exclusive: bool,
  tier: &Delegation<'_>,
  errors: &mut Errors,
) -> Vec<DelegateSkin> {
  let mut wire = Vec::new();

  for attr in attrs {
    if !attr.path().is_ident("graphql") {
      errors.push(syn::Error::new_spanned(
        attr,
        "a `delegate(…)` entry takes one attribute — `#[graphql(…)]`, which publishes the method — \
         and nothing else. The entry is a SIGNATURE rather than an item: it declares no code for \
         another attribute to be about, and the emitted method's own attributes are this \
         expansion's",
      ));
      continue;
    }
    if matches!(attr.meta, syn::Meta::Path(_)) {
      errors.push(syn::Error::new_spanned(attr, graphql_names_no_backend()));
      continue;
    }
    let mut written = 0_usize;
    let walked = attr.parse_nested_meta(|inner| {
      written += 1;
      let Some(kind) = crate::parse::graphql_kind(&inner.path) else {
        errors.push(attribute::unknown(
          &inner,
          "unknown backend in `#[graphql(…)]` — a published method is one backend's field, and a \
           word naming none of them names no face",
          &GraphqlKind::ALL.map(GraphqlKind::as_str),
        ));
        attribute::skip_entry(&inner);
        return Ok(());
      };
      if wire.iter().any(|skin: &DelegateSkin| skin.kind == kind) {
        errors.push(syn::Error::new_spanned(
          &inner.path,
          format!(
            "`{kind}` is declared more than once — one word per backend, because a backend \
             publishes this method once and a second word could only re-describe it",
            kind = kind.as_str(),
          ),
        ));
        attribute::skip_entry(&inner);
        return Ok(());
      }
      wire.push(DelegateSkin {
        kind,
        rename: renamed(&inner, kind, errors),
      });
      Ok(())
    });
    if let Err(e) = walked {
      errors.push(e);
    }
    // An EMPTY `#[graphql()]`, which the walk above never reaches its closure for. A word that named
    // no backend already has its own sentence, and a second one here would be two refusals for one
    // mistake.
    if written == 0 {
      errors.push(syn::Error::new_spanned(attr, graphql_names_no_backend()));
    }
  }

  if exclusive && !wire.is_empty() {
    errors.push(syn::Error::new_spanned(&signature.ident, tier.exclusive));
    wire.clear();
  }

  wire
}

/// The refusal a `#[graphql]` naming no backend earns — the union's empty-face-block law, one
/// declaration over.
fn graphql_names_no_backend() -> String {
  format!(
    "`#[graphql]` names no backend — write `#[graphql({first})]`. Without a backend word the \
     attribute publishes nothing, and an entry nobody reads is a rule its author believes they \
     declared",
    first = GraphqlKind::ALL[0].as_str(),
  )
}

/// ONE backend's cell: `rename = "…"` and nothing else, which is v1's whole knob.
///
/// The word goes to the wire's own floor — GraphQL's Name grammar — because it is what a client
/// writes rather than anything Rust reads.
fn renamed(
  meta: &syn::meta::ParseNestedMeta<'_>,
  kind: GraphqlKind,
  errors: &mut Errors,
) -> Option<syn::LitStr> {
  let mut rename = None;
  let walked = attribute::options(meta, |option| {
    if option.path.is_ident("rename") {
      match value::literal(&option, attribute::SDL_NAME) {
        Ok(word) => {
          wire::refuse_invalid_name(&word.value(), &word, errors);
          attribute::set_once(
            &mut rename,
            word,
            &option.path,
            "`rename` is declared more than once — one option, one value",
            errors,
          );
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      &format!(
        "unknown entry in `{kind}(…)` on a delegated method — it takes `rename = \"…\"` and nothing \
         else. What a published method's field IS comes from the signature, so the one thing left \
         to say is what a client calls it",
        kind = kind.as_str(),
      ),
      &["rename"],
    ));
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }
  rename
}