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
//! The words a graph root's FIELD takes — the two tier words, the source spellings and the
//! goodbye that compose with one of them, and the MOUNT word both queryable tiers take.
//!
//! ```ignore
//! #[ingraph::graph]
//! pub struct Media {
//!   // a node
//!   videos: Video,
//!   // a node whose own root fields join the graph's root query
//!   #[ingraph(query)]
//!   scenes: Scene,
//!   // an INTERFACE, whose own root fields join the same query
//!   #[ingraph(interface, query)]
//!   media: Screened,
//!   // from the deployment's own document
//!   #[ingraph(resource)]
//!   egemma: Egemma,
//!   // from the application's own hand
//!   #[ingraph(resource(factory))]
//!   pool: Pool,
//!   // from a function the declaration names
//!   #[ingraph(resource(factory = "boot::cache"))]
//!   cache: Cache,
//!   // and either source, with something to say on the way out
//!   #[ingraph(resource(factory = "boot::index", teardown))]
//!   index: Index,
//!   // an ORIGIN — an `#[ingraph::source]` declaration, mounted as a head
//!   #[ingraph(origin)]
//!   watch: Watch,
//! }
//! ```
//!
//! # The field spells the THING, and the word says the KIND
//!
//! A resource field is written exactly as a node field is — the type in the field, and its options
//! reached through the contract rather than named here. That isomorphism is the whole reason the
//! word is a marker: nothing about a resource's own declaration is restated on the root, so a root
//! reads as one list of members and the tiers differ by one word.
//!
//! # `factory` is where the OPTIONS come from, and it takes two forms
//!
//! The bare word names the application's own `prepare` closure — for options that close over
//! something a document cannot hold. The assigned form names a FUNCTION the create walk calls
//! itself, which is what a self-sufficient resource needs: options read from the environment or
//! computed from a path need no `prepare` at all. It is REFER-QUOTED, as every word in this grammar
//! that points at something written elsewhere is.
//!
//! What neither form does is add a second source beside the first. The declaration names ONE, and
//! the launch refuses every other door by name — see the create walk for the sentence a reader gets.
//!
//! # `query` is MEMBERSHIP, and it is a word because a macro cannot see an impl
//!
//! The root query is a FOLD of the units its members emit, and which members have one is a fact this
//! derive cannot read: it holds a field's type PATH and nothing else, and whether that type declared
//! a `graphql(…)` block is written in another declaration's tokens. Projecting every field instead
//! would refuse every graph holding an operator, an index or a journal — none of which has a wire
//! face — so membership is READ OFF THIS DECLARATION, which is the one thing the macro can see.
//!
//! A field wearing the word whose type has no query unit is `E0277` AT THE ROOT, carrying the wire
//! face's own sentence: the projection is what asks, and the compiler is what answers. So the word
//! is a claim the type system checks rather than a second copy of a fact.
//!
//! It is a QUERYABLE TIER's word — a node's, and an interface's. A `resource` is not a queryable
//! member — it is a shared citizen the launch builds — so those two are refused together rather than
//! composed.
//!
//! # `interface` is the SECOND TIER, and what it buys is that the field is not a NODE
//!
//! An interface owns no table, mints no id and has no options section: the node tier's three
//! obligations — the storage-description walk, the create pass's `Creation::node`, and the options
//! spine's per-mount section — are each written about a member an interface is not. So it takes a
//! tier word of its own, exactly as `resource` does, and the word is what keeps it off those three
//! walks.
//!
//! The MOUNT is still `query`, per the B-27 ruling — *the interface mounts with its OWN
//! `#[ingraph(query)]` word on a graph field naming the interface; member mounts are independent* —
//! so mounting a member never mounts the interface and mounting the interface never mounts a member.
//! What the two words are about is different: `interface` says WHICH TIER the field is on, and
//! `query` says whether this deployment publishes its root fields. An `interface` field with no
//! `query` is a declared citizen that publishes nothing, which is the node tier's own arrangement one
//! tier over.
//!
//! The FOLD reaches an interface's unit through `Graphql` DIRECTLY where a node's is reached through
//! `Transformer` first, and that is forced rather than chosen: `Transformer: Identifiable` and an
//! interface cannot implement `Identifiable` — `id_ref` hands back a `&Self::Id`, and an interface's
//! id is a SUM its members' values do not hold one of. That is the same wall the B-27 ruling names as
//! *an interface-owned id is unspellable*, met at the one place it is load-bearing.
//!
//! # `origin` is the FIFTH TIER, and what it buys is that the field is a HEAD
//!
//! An origin is an `#[ingraph::source]` declaration — a body STARTED ONCE that runs until it is
//! spent, told to stop or dead. It implements `DeclaredOrigin` rather than `Declared`, so a field
//! naming one on the node tier is `E0277` at the root before anything about a feed is reached: it
//! owns no table for the storage walk, mints no id, declares no upstream and answers no query. So it
//! takes a tier word of its own, exactly as `interface` and `fuse` do, and the word is what keeps it
//! off those walks and puts it on the two it does join — the options spine (presence is enablement,
//! as everywhere) and the launch.
//!
//! **WHO CONSUMES IT IS NOT WRITTEN HERE.** An origin's one out-edge IS its feed, and the consumer
//! is found the way every other edge in this framework is found: the consuming node's own
//! `subscribe(upstream(node = "…"))` names the origin BY TYPE, and the join searches these very
//! fields. That is the three-author wall again — this pass holds tokens, so it can no more see what
//! a node subscribes to than it can see whether a type is a node — and it is why an origin nobody
//! listens to, an origin two nodes listen to, and a consumer listening by `changes`, `poll` or
//! `transient` are all refused at the LAUNCH, by name, where the identities have been joined.
//!
//! # `teardown` is a SECOND AXIS, not a fourth source
//!
//! Where a resource's options come from and whether the built value has something to say before the
//! process leaves it are unrelated questions, so the goodbye is its own bare word and COMPOSES with
//! either factory form. It is the node side's word at the other tier, and it is the opt-in in the
//! same sense: the launch routes an opted-in resource onto the shutdown's chain — released after
//! every node that held a handle — and leaves every other resource to its own [`Drop`].
//!
//! It is written HERE, on the root's field, rather than on the resource's own declaration, because
//! the root is what mounts the resource into THIS deployment. A library resource that knows how to
//! close itself politely does not join a graph's shutdown chain by accident; the word is what joins
//! it.
//!
//! A `teardown` written on a field that declares a NODE is not a resource word out of place — it is
//! a word this grammar does not have, and it earns the orphan-attribute refusal that every unknown
//! entry on a root's field earns, whose sentence names the spellings that do exist.

use ingraph_codegen::catalog::ResourceSource;

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

/// The `teardown` word's own suite — the compositions, and the two ways of writing it wrong.
///
/// Beside the source suite rather than inside it, which is the shape this workspace keeps for a
/// word that arrives after a grammar has already been proven: the ROSTER a reader walks stays the
/// one it was, and the new axis reads as one file.
#[cfg(test)]
mod fuse_tests;
#[cfg(test)]
mod goodbye_tests;
#[cfg(test)]
mod interface_tests;
#[cfg(test)]
mod origin_tests;
#[cfg(test)]
mod tests;

/// What a `factory = "…"` must be.
const FACTORY_PATH: &str = "`factory = \"…\"` must be a path to an initialization function, in a \
                            string literal — a word that points at something written elsewhere is \
                            quoted";

/// The refusal for a field whose word this grammar does not know.
const UNKNOWN: &str = "unknown entry in `#[ingraph(…)]` on a graph root's field — it takes \
                       `resource`, `resource(factory)`, `resource(factory = \"path::to::fn\")`, a \
                       `teardown` composed with any of them, `interface`, `query`, `fuse`, and \
                       `origin`, and nothing else: what a NODE is, how it is stored, and whether IT \
                       says goodbye are written in that node's OWN declaration";

/// What an `origin` block is refused with, whichever shape it took.
///
/// Every fact an origin states about itself is on its OWN declaration — the face is
/// `#[ingraph::source(async)]`'s word, the command node is `mutation(node = "…")`, and what it
/// produces is the `Yield` seat its body names. So the root's word says WHICH TIER the field is on
/// and nothing else, and there is nothing for a block to carry.
const ORIGIN_IS_BARE: &str = "`origin` is a BARE word — it puts an `#[ingraph::source]` declaration \
                              on this root's origin tier, which is what mounts it as a HEAD whose \
                              one out-edge IS its feed, and it says nothing else. WHICH origin this \
                              is is the field's own type; its face, its command node and what it \
                              produces are written in that source's OWN declaration";

/// What a `fuse` block is refused with, whichever shape it took.
///
/// The word CARRIED a modality until the fused doors moved to `#[ingraph::search]` — `fuse(vector)`
/// and `fuse(fulltext)` trimmed which of a root's three doors a member joined. A recipe LISTS its
/// members, so there is no door left for a trim to select, and the sentence says where the fusion
/// went rather than only that the block is gone.
const FUSE_IS_BARE: &str = "`fuse` is a BARE word — it puts a retrieving declaration on this root's \
                            index tier, which is what keeps it off the node walks, and it says \
                            nothing else. The modality trims `fuse(vector)` / `fuse(fulltext)` are \
                            RETIRED along with the root's own fused doors: a fused read is declared \
                            by `#[ingraph::search]`, where a recipe LISTS the members it fuses and \
                            has no door for a trim to select";

/// What one field's `resource` word said: where its options come from, and whether it says goodbye.
#[derive(Debug)]
pub(super) struct Declaration {
  /// The ONE source its declaration named.
  pub(super) source: ResourceSource,
  /// Whether it wrote `teardown`.
  pub(super) teardown: bool,
}

/// What one field's words said about it.
///
/// A struct rather than two readers over the same attribute, because there is ONE walk: a reader per
/// word would push [`UNKNOWN`] for the other one, and a declaration writing both would be told twice
/// that each is unknown.
#[derive(Debug, Default)]
pub(super) struct Words {
  /// The RESOURCE tier word and what it composed — `None` where the field declares no resource.
  pub(super) resource: Option<Declaration>,
  /// The INTERFACE tier word — whether this field names an interface rather than a node.
  pub(super) interface: bool,
  /// Whether this member joins the root query's fold.
  pub(super) query: bool,
  /// Whether this member is on the root's INDEX TIER — the `fuse` word, which is now membership and
  /// nothing else.
  pub(super) fuse: bool,
  /// Whether this member is on the root's ORIGIN TIER — the `origin` word, which is membership and
  /// nothing else, exactly as `interface` and `fuse` are.
  pub(super) origin: bool,
}

/// Read one field's words: which tier it is on — for a resource, whether it says goodbye; for a
/// node, whether it joins the root query.
///
/// Collecting rather than stopping, per this crate's whole posture: a field with a misspelled entry
/// is reported and then read as the node it is otherwise shaped like, so one declaration's problems
/// arrive in one compile.
pub(super) fn words(field: &syn::Field, errors: &mut Errors) -> Words {
  let mut declared = Words::default();

  attribute::walk(&field.attrs, errors, |meta, errors| {
    if meta.path.is_ident("query") {
      if declared.query {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`query` is declared more than once on one field — a member joins the root query once",
        ));
      }
      declared.query = true;
      return Ok(());
    }
    // THE FUSE WORD — a TIER word and nothing else, exactly as `interface` is. It says a field
    // names a retrieving declaration rather than a launchable node, which is what keeps it off the
    // three walks a node joins and on the slot walk the launch drives. Mirrors `query`'s
    // membership-from-declaration precedent and is deliberately NOT `query` itself:
    // queryable-but-not-fused is an ordinary member, and one word for the two facts would make it
    // unexpressible.
    if meta.path.is_ident("fuse") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(syn::Error::new_spanned(&meta.path, FUSE_IS_BARE));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      if core::mem::replace(&mut declared.fuse, true) {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`fuse` is declared more than once on one field — a member is on ONE tier",
        ));
      }
      return Ok(());
    }
    // THE ORIGIN WORD — a TIER word, exactly as `interface` and `fuse` are. It says a field names an
    // `#[ingraph::source]` declaration rather than a launchable node, which is what keeps it off the
    // storage walk, the root query and the create pass's own node predicates, and puts it on the
    // options spine and the launch's origin lines.
    if meta.path.is_ident("origin") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(syn::Error::new_spanned(&meta.path, ORIGIN_IS_BARE));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      if core::mem::replace(&mut declared.origin, true) {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`origin` is declared more than once on one field — a member is on ONE tier",
        ));
      }
      return Ok(());
    }
    if meta.path.is_ident("interface") {
      if attribute::has_value(&meta) {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`interface` is a bare word — WHICH interface this is is the field's own type, and what \
           the interface promises is written in that interface's OWN declaration",
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      if core::mem::replace(&mut declared.interface, true) {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`interface` is declared more than once on one field — a member is on ONE tier",
        ));
      }
      return Ok(());
    }
    if !meta.path.is_ident("resource") {
      errors.push(attribute::unknown(
        &meta,
        UNKNOWN,
        &["query", "resource", "fuse", "origin"],
      ));
      return Ok(());
    }

    let mut source = ResourceSource::Section;
    let mut teardown = false;
    attribute::options(&meta, |inner| {
      if inner.path.is_ident("teardown") {
        if attribute::has_value(&inner) {
          errors.push(syn::Error::new_spanned(
            &inner.path,
            "`teardown` is a bare word — WHAT this resource says on the way out is its own \
             `AsyncResource::goodbye`, so the word states only that this deployment wants it said",
          ));
          attribute::skip_entry(&inner);
          return Ok(());
        }
        if core::mem::replace(&mut teardown, true) {
          errors.push(syn::Error::new_spanned(
            &inner.path,
            "`teardown` is declared more than once on one resource — one declaration says goodbye \
             once",
          ));
        }
        return Ok(());
      }
      if !inner.path.is_ident("factory") {
        errors.push(attribute::unknown(
          &inner,
          "unknown entry in `resource(…)` — it takes `factory`, bare for the application's own \
           `prepare` closure or `factory = \"path::to::fn\"` for a function the create walk calls \
           itself, and `teardown`, which composes with either",
          &["factory", "teardown"],
        ));
        return Ok(());
      }
      if !attribute::has_value(&inner) {
        source = ResourceSource::Prepare;
        return Ok(());
      }
      match value::parse_literal::<syn::Path>(&inner, FACTORY_PATH) {
        Ok(path) => source = ResourceSource::Initializer(path),
        Err(e) => {
          // Swallow what the entry carried, exactly as `attribute::unknown` does and for its
          // reason: one mistake should cost one error rather than one plus a parse failure at the
          // token after it.
          errors.push(e);
          attribute::skip_entry(&inner);
        }
      }
      Ok(())
    })?;

    if declared
      .resource
      .replace(Declaration { source, teardown })
      .is_some()
    {
      errors.push(syn::Error::new_spanned(
        &meta.path,
        "`resource` is declared more than once on one field — a member is one citizen, and its \
         options have ONE source",
      ));
    }
    Ok(())
  });

  // A RESOURCE IS NOT AN INDEX, for the reason it queries nothing: it is a shared citizen the
  // launch builds and hands out, and the index tier is for members that RETRIEVE.
  if declared.fuse && declared.resource.is_some() {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "a `resource` field takes no `fuse` — a resource is a shared citizen the launch builds and \
       hands out, where a fused query joins the rankings of members that RETRIEVE; the two are \
       different tiers of the one list",
    ));
    declared.fuse = false;
  }
  // AN INTERFACE IS NOT AN INDEX EITHER, and the reason is one hop deeper: a contract over members
  // owns no slot, so there is no ranking of its own for a fold to read. Its MEMBERS fuse, each
  // under its own field.
  if declared.fuse && declared.interface {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "an `interface` field takes no `fuse` — an interface is a contract over members and owns no \
       slot, so it has no ranking of its own for a fold to read. The MEMBERS fuse, each under its \
       own field on this root",
    ));
    declared.fuse = false;
  }
  if declared.query && declared.resource.is_some() {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "a `resource` field takes no `query` — a resource is a shared citizen the launch builds and \
       hands out, where a root query folds the fields a NODE answers; the two are different tiers \
       of the one list",
    ));
    declared.query = false;
  }

  // AN ORIGIN ANSWERS NOTHING, which is the `query` pair one tier further over. A root query folds
  // the fields its members answer, and an `#[ingraph::source]` declaration emits no query unit at
  // all: it has no `Graphql` seat for the fold to project through, so the word would be a claim with
  // nothing behind it. What an origin DOES publish a face for is its command node, and that is the
  // source's own `mutation(node = "…")` rather than anything written here.
  if declared.query && declared.origin {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "an `origin` field takes no `query` — an origin is a HEAD that produces into the graph, and \
       it answers nobody: it emits no query unit for a root fold to project. The face it DOES \
       publish is its command node, named by `mutation(node = \"…\")` on the source's own \
       declaration",
    ));
    declared.query = false;
  }

  // THE ORIGIN TIER against the other three, one sentence apiece, because the fix differs. Each is a
  // member claiming to be on two tiers of one list, and `origin` is the word CLEARED — exactly as
  // `fuse` and `interface` are above — so that the field is then read as whatever it is otherwise
  // shaped like, which is this crate's collecting posture rather than a stop at the first mistake.
  if declared.origin && declared.resource.is_some() {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "a field is on ONE tier — `origin` names a source the launch STARTS and puts on an engine of \
       its own, and `resource` names a shared citizen it builds once and hands out; a member \
       wearing both says it is two things",
    ));
    declared.origin = false;
  }
  if declared.origin && declared.interface {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "a field is on ONE tier — `origin` names a running source and `interface` names a contract \
       over members, which is a description rather than a body; a member wearing both says it is \
       two things",
    ));
    declared.origin = false;
  }
  if declared.origin && declared.fuse {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "a field is on ONE tier — `origin` names a source that PRODUCES into the graph, and `fuse` \
       names a retrieving declaration that owns a corpus to be read from; a member wearing both \
       says it is two things",
    ));
    declared.origin = false;
  }

  // The two TIER words together, which is a member claiming to be on two tiers of one list. Refused
  // rather than elected, exactly as the pair above is: an interface owns no table for a resource's
  // factory to build and a resource has no members for a contract to be over.
  if declared.interface && declared.resource.is_some() {
    errors.push(syn::Error::new_spanned(
      &field.ty,
      "a field is on ONE tier — `interface` names a contract over members, and `resource` names a \
       shared citizen the launch builds and hands out; a member wearing both says it is two things",
    ));
    declared.interface = false;
  }

  declared
}