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
//! The NEAR-MISS line, read off real declarations — one row per POSITION rather than per grammar.
//!
//! [`suggest::tests`](crate::suggest) pins the reader. What is pinned here is the WIRING: that a
//! position hands the engine its own words, that it hands it the right ones, and that the teaching
//! sentence it already had is still there in front of the suggestion.
//!
//! Each test is therefore a MUTATION PROOF as well as an assertion — take the vocabulary off any
//! one of these call sites and exactly one test here goes red, which is what makes the census in
//! the round's PR body a claim somebody can check rather than a list somebody wrote.
//!
//! # The three shapes, and why they are all here
//!
//!   * an ENTRY-NAME position, which reaches the engine through `attribute::unknown`;
//!   * a VALUE-WORD position — a closed vocabulary written after an `=` or inside a block — which
//!     reaches it through `suggest::did_you_mean` in the refusal's own `format!`;
//!   * a DECLARED vocabulary, where the words are the declaration's own variants rather than the
//!     framework's.
//!
//! # The r#type row
//!
//! The last section is the raw-ident tolerance, which is the same law read at a value: a field
//! legally called `r#type` is the column called `type`, and both spellings name it.

use ingraph_codegen::prelude::NodeKind;

use crate::{index, interface, parse, standalone, value};

/// Every refusal a record declaration earned, joined — one compile reports every rule it can still
/// see, and a `syn::Error` renders only the first of a combined one.
fn record(input: syn::DeriveInput) -> String {
  let (host, arguments) = crate::host::split(&input);
  parse::parse(&host, &arguments, NodeKind::Record)
    .expect_err("the declaration is refused")
    .into_iter()
    .map(|e| e.to_string())
    .collect::<Vec<_>>()
    .join("\n")
}

/// The same over a derived index, at the kind the test is about.
fn derived(input: syn::DeriveInput, kind: NodeKind) -> String {
  let (host, arguments) = crate::host::split(&input);
  index::parse(&host, &arguments, kind)
    .expect_err("the declaration is refused")
    .into_iter()
    .map(|e| e.to_string())
    .collect::<Vec<_>>()
    .join("\n")
}

/// The same over an interface.
fn contract(input: syn::DeriveInput) -> String {
  let (host, arguments) = crate::host::split(&input);
  interface::parse(&host, &arguments)
    .expect_err("the declaration is refused")
    .into_iter()
    .map(|e| e.to_string())
    .collect::<Vec<_>>()
    .join("\n")
}

/// The suggestion clause, as every position appends it.
fn suggests(word: &str) -> String {
  format!(" — did you mean `{word}`?")
}

// ---------------------------------------------------------------------------------------------
// ENTRY-NAME POSITIONS
// ---------------------------------------------------------------------------------------------

/// THE RECORD'S HEAD. The teaching sentence survives, and the suggestion is appended to it.
///
/// The word written used to be `persit`, for `persist`, and neither half of that row survived the
/// unwrap: the head's sentence opens on the STORE WORDS now, and `persist` is refused there BY NAME
/// with its migration — which this module's own rule holds outside every vocabulary, a reasoned
/// refusal being worth more than a suggestion. So the row is read off a word the unwrap MOVED to the
/// head instead, which is the same position and the same wiring.
#[test]
fn a_near_miss_at_the_records_head_is_named_and_the_sentence_survives() {
  let refused = record(syn::parse_quote! {
    #[ingraph(tabel = "s")]
    struct S {
      #[ingraph(id)] id: Uuid7,
    }
  });

  assert!(
    refused.contains("unknown `ingraph` record attribute — a record takes its STORE WORDS bare"),
    "the teaching sentence is still there: {refused}"
  );
  assert!(refused.contains(&suggests("table")), "{refused}");
}

/// THE SAME HEAD, at the word the roster had LEFT OUT. `options` is taken by every rung this parser
/// serves and appeared in neither half of the refusal — not the sentence a reader is shown, and not
/// the roster a near miss is measured against — so a declaration writing `option = "…"` got the whole
/// list and no line at all, which is the one thing this vocabulary exists to give.
///
/// Both halves are asserted, because they failed together and a fix to one is not a fix to the
/// other: a word missing from the ROSTER suggests nothing, and a word missing from the SENTENCE is
/// suggested without ever being taught.
#[test]
fn a_near_miss_of_the_options_word_is_named_and_the_sentence_teaches_it() {
  let refused = record(syn::parse_quote! {
    #[ingraph(option = "app::Knobs")]
    struct S {
      #[ingraph(id)] id: Uuid7,
    }
  });

  assert!(refused.contains(&suggests("options")), "{refused}");
  assert!(
    refused.contains("`options = \"…\"`"),
    "the sentence names the word it suggests: {refused}"
  );
}

/// A FIELD's own attribute list, whose vocabulary is the markers AND the label words.
#[test]
fn a_near_miss_of_a_field_marker_is_named() {
  let refused = record(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(optionel)] a: String,
    }
  });

  assert!(refused.contains(&suggests("optional")), "{refused}");
}

/// The same position, reaching the LABEL half of its list — one call, two word sources.
#[test]
fn a_near_miss_of_a_label_word_at_the_field_head_is_named() {
  let refused = record(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(durtion)] a: Duration,
    }
  });

  assert!(refused.contains(&suggests("duration")), "{refused}");
}

/// A COLLECTION's ELEMENT — the ruling's own example, `sortble`, whose word is the collection's
/// field-intent one rather than a family.
#[test]
fn the_rulings_own_example_suggests_sortable() {
  let refused = record(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(list(string, sortble))] a: Vec<String>,
    }
  });

  assert!(
    refused.contains("is not an interpretation this framework names"),
    "the element sentence is still there: {refused}"
  );
  assert!(refused.contains(&suggests("sortable")), "{refused}");
}

/// A DATABASE position, whose words are the shipped backends.
#[test]
fn a_near_miss_of_a_database_word_is_named() {
  let refused = record(syn::parse_quote! {
    #[ingraph(postgress)]
    struct S {
      #[ingraph(id)] id: Uuid7,
    }
  });

  assert!(refused.contains(&suggests("postgres")), "{refused}");
}

/// A COLUMN's database block, three levels in — the deepest hand-written vocabulary in the record
/// grammar.
#[test]
fn a_near_miss_inside_a_columns_database_block_is_named() {
  let refused = record(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(sqlite(indexd))] a: String,
    }
  });

  assert!(refused.contains(&suggests("indexed")), "{refused}");
}

/// The same block, over `unique` — the word that joined `indexed` in the same position and takes
/// the same near-miss engine.
#[test]
fn a_near_miss_of_the_unique_word_is_named() {
  let refused = record(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(sqlite(uniqe))] a: String,
    }
  });

  assert!(refused.contains(&suggests("unique")), "{refused}");
}

/// A DERIVED INDEX's head, whose word list depends on the KIND: `dedup` is offered to a full-text
/// declaration and withheld from an artifact family, which retrieves nothing.
#[test]
fn a_near_miss_at_an_index_head_is_offered_only_the_words_that_kind_takes() {
  let searchable = derived(
    syn::parse_quote! {
      #[ingraph(upstream(node = "asr::Segment", body = "text"), dedupe(hash))]
      struct D {
        #[ingraph(searchable)] body: String,
      }
    },
    NodeKind::Fulltext,
  );
  assert!(searchable.contains(&suggests("dedup")), "{searchable}");
}

/// #256's D2 AT THE HEAD, pinned as the residue it is rather than claimed as a gap that was closed.
///
/// The same misspelling on a `blob` earns NO refusal at all: an artifact family names its engines at
/// the head, every word the framework does not own is one of them, and `dedupe` is therefore a
/// legal declaration for an engine nothing binds. It still fails — at the type layer, through the
/// `Bound` sentence — and that is later than a typo deserves, which is exactly what the constraint
/// this round inherited says cannot be fixed without the projection through the member.
#[test]
fn an_engine_position_has_no_vocabulary_to_be_near_because_it_is_open() {
  let input: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(upstream(node = "video::Keyframe", payload = "pixels"), dedupe(hash))]
    struct B {
      #[ingraph(repeated)] payload: Vec<u8>,
    }
  };
  let (host, arguments) = crate::host::split(&input);
  let model = index::parse(&host, &arguments, NodeKind::Blob)
    .expect("a word the framework does not own is an ENGINE, however it was spelled");

  let stores: Vec<String> = model
    .stores
    .iter()
    .map(|engine| engine.word.to_string())
    .collect();
  assert_eq!(stores, ["dedupe"], "the typo became an engine word");
}

/// AN INTERFACE's own head — the second front end, proving the wiring is not the record grammar's
/// alone.
#[test]
fn a_near_miss_at_an_interfaces_head_is_named() {
  let refused = contract(syn::parse_quote! {
    #[ingraph(feilds(id: Uuid7))]
    enum Media {
      Video(Video),
    }
  });

  assert!(refused.contains(&suggests("fields")), "{refused}");
}

/// A word that is near NOTHING leaves the refusal exactly as it was — the other half of the
/// contract, and the one a too-loose cutoff would break.
#[test]
fn a_word_near_nothing_adds_no_line() {
  let refused = record(syn::parse_quote! {
    #[ingraph(hippopotamus)]
    struct S {
      #[ingraph(id)] id: Uuid7,
    }
  });

  assert!(
    refused.contains("unknown `ingraph` record attribute"),
    "{refused}"
  );
  assert!(!refused.contains("did you mean"), "{refused}");
}

/// A position that takes NO words says nothing, however near the word looks to a neighbour's.
#[test]
fn a_position_with_no_vocabulary_adds_no_line() {
  // A membership block takes nothing inside it, and `feild` is one edit from a word two grammars
  // over — which is exactly the suggestion an empty vocabulary must not make.
  let refused = record(syn::parse_quote! {
    #[ingraph(sqlite, implements(media::Media(feild = "x")))]
    struct S {
      #[ingraph(id)] id: Uuid7,
    }
  });

  assert!(!refused.contains("did you mean"), "{refused}");
}

// ---------------------------------------------------------------------------------------------
// VALUE-WORD POSITIONS
// ---------------------------------------------------------------------------------------------

/// A CLOSED VOCABULARY written after an `=`: the tracing level, whose five words are the
/// framework's own.
#[test]
fn a_near_miss_of_a_tracing_level_is_named() {
  let refused = record(syn::parse_quote! {
    #[ingraph(sqlite, tracing(level = debgu))]
    struct S {
      #[ingraph(id)] id: Uuid7,
    }
  });

  assert!(
    refused.contains("is not a level this framework names"),
    "the teaching sentence is still there: {refused}"
  );
  assert!(refused.contains(&suggests("debug")), "{refused}");
}

/// A CLOSED VOCABULARY written BARE inside a block: the dedup mechanism.
#[test]
fn a_near_miss_of_a_dedup_mechanism_is_named() {
  let refused = derived(
    syn::parse_quote! {
      #[ingraph(upstream(node = "asr::Segment", body = "text"), dedup(hasg))]
      struct D {
        #[ingraph(searchable)] body: String,
      }
    },
    NodeKind::Fulltext,
  );

  assert!(refused.contains("is not a dedup mechanism"), "{refused}");
  assert!(refused.contains(&suggests("hash")), "{refused}");
}

/// The ELEMENT FAMILY a standalone element is read under — the third front end.
#[test]
fn a_near_miss_of_an_element_family_is_named() {
  let input: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(operator(strng))]
    struct Volume(u8);
  };
  let Err(refused) = standalone::parse(&input, standalone::Face::Filter) else {
    panic!("the declaration is refused");
  };
  let refused = refused
    .into_iter()
    .map(|e| e.to_string())
    .collect::<Vec<_>>()
    .join("\n");

  assert!(
    refused.contains("is not a family an ELEMENT may be read under"),
    "{refused}"
  );
  assert!(refused.contains(&suggests("string")), "{refused}");
}

/// THE ONE DECLARED VOCABULARY: a member key is one of the enum's own variants, and a near miss of
/// one is answered against the list the same `DeriveInput` carries.
#[test]
fn a_near_miss_of_a_member_variant_is_named() {
  let refused = contract(syn::parse_quote! {
    #[ingraph(fields(title(type = "String", members(Vide(field = "name")))))]
    enum Media {
      Video(Video),
      Audio(Audio),
    }
  });

  assert!(
    refused.contains("is not a member variant of this interface"),
    "{refused}"
  );
  assert!(refused.contains(&suggests("Video")), "{refused}");
}

// ---------------------------------------------------------------------------------------------
// THE r#type ROW
// ---------------------------------------------------------------------------------------------

/// A field legally called `r#type` is nameable under BOTH spellings, and both read as the same
/// raw identifier — which is what the emission has to spell, `type` being unwritable bare.
///
/// MEASURED rather than assumed, and the measurement corrected the finding this row came from:
/// `"r#type"` already parsed, because `syn`'s `Ident` reader compares the ESCAPED spelling against
/// the keyword list and `r#type` is not one of them. It was `"type"` alone that was refused — the
/// word an author reaches for, the schema and the database both calling the column that.
#[test]
fn a_keyword_column_is_nameable_under_both_spellings() {
  for written in ["type", "r#type"] {
    let literal = syn::LitStr::new(written, proc_macro2::Span::call_site());
    let read = value::named_field(&literal, "unreachable").expect("a keyword names a field");

    assert_eq!(read.to_string(), "r#type", "written as {written:?}");
    assert_eq!(
      read,
      syn::Ident::new_raw("type", proc_macro2::Span::call_site()),
      "written as {written:?}"
    );
  }
}

/// An ordinary name is untouched by the tolerance — it is not read as raw, and a raw one is not
/// what the emission spells for it.
#[test]
fn an_ordinary_column_stays_an_ordinary_identifier() {
  let literal = syn::LitStr::new("format", proc_macro2::Span::call_site());
  let read = value::named_field(&literal, "unreachable").expect("a word names a field");

  assert_eq!(read.to_string(), "format");
}

/// THE FENCE, unmoved: what no spelling could make an identifier is still refused, with the
/// position's own sentence.
#[test]
fn a_value_that_names_no_field_is_still_refused() {
  for written in ["", "9lives", "a::b", "self", "crate"] {
    let literal = syn::LitStr::new(written, proc_macro2::Span::call_site());
    let refused = value::named_field(&literal, "the position's own sentence")
      .expect_err("no spelling makes this a field name");

    assert_eq!(refused.to_string(), "the position's own sentence");
  }
}

/// The tolerance READ THROUGH THE GRAMMAR, at the position the finding named: an artifact family
/// whose suffix is decided by a column called `type`.
#[test]
fn an_artifact_familys_suffix_column_may_be_a_keyword() {
  for written in [r#"from = "type""#, r#"from = "r#type""#] {
    let head: proc_macro2::TokenStream =
      format!(r#"fs, extension({written}, any_of = ["png", "jpg"])"#)
        .parse()
        .expect("a head");
    let input: syn::DeriveInput = syn::parse_quote! {
      #[ingraph(upstream(node = "video::Keyframe", payload = "pixels"), #head)]
      struct Thumbnail {
        #[ingraph(repeated)] payload: Vec<u8>,
      }
    };
    let (host, arguments) = crate::host::split(&input);
    let model = index::parse(&host, &arguments, NodeKind::Blob)
      .unwrap_or_else(|e| panic!("`{written}` names the column: {e}"));

    let column = match model.extension.as_ref().expect("an extension") {
      ingraph_codegen::extension::Extension::Column(column) => column,
      other => panic!("a column road, not {other:?}"),
    };
    let field = match &column.source {
      ingraph_codegen::extension::ExtensionSource::Text { field } => field,
      other => panic!("the string road, not {other:?}"),
    };
    assert_eq!(field.to_string(), "r#type", "written as {written}");
  }
}

/// The ENUM road's half of the same law.
#[test]
fn an_enum_roads_column_may_be_a_keyword() {
  let input: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(
      upstream(node = "video::Keyframe", payload = "pixels"),
      fs,
      extension(from(field = "type", type = "app::Format"))
    )]
    struct Thumbnail {
      #[ingraph(repeated)] payload: Vec<u8>,
    }
  };
  let (host, arguments) = crate::host::split(&input);
  let model =
    index::parse(&host, &arguments, NodeKind::Blob).expect("a keyword names the enum column");

  let column = match model.extension.as_ref().expect("an extension") {
    ingraph_codegen::extension::Extension::Column(column) => column,
    other => panic!("a column road, not {other:?}"),
  };
  match &column.source {
    ingraph_codegen::extension::ExtensionSource::Enumerated { field, .. } => {
      assert_eq!(field.to_string(), "r#type");
    }
    other => panic!("the enum road, not {other:?}"),
  }
}