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
//! The bare doors, read — and the PAIRED DECLARATION pins, which are what the ruling asks beyond
//! the by-construction sharing.
//!
//! # What a token-identity pin is worth here
//!
//! The units are shared, so the two doors emit the same tokens BY CONSTRUCTION and the pins can only
//! fail if the two front ends hand the units different ROWS. That is exactly the failure worth
//! pinning: a member named one way here and another way there, a doc sentence built from a different
//! name, a filter projected from a different type. None of those is caught by "the code compiles",
//! and each is a face that has drifted.
//!
//! Both halves are written as SOURCE and read by the real front ends — the record's `parse::parse`
//! and the bare door's `standalone::parse` — so what is compared is the whole path a declaration
//! takes, not two hand-built models.

use ingraph_codegen::model::NodeKind;
use quote::ToTokens;

use super::{Face, emit};

/// The STRUCT-mode model a declaration with NO MARKER reads as.
///
/// The watershed's other two sides are [`element_tests`](super::element_tests)' and
/// [`composed_tests`](super::composed_tests)', so a test here that found either model would be
/// reading a declaration these assertions are not about.
fn structural(mode: super::Mode) -> ingraph_codegen::standalone::StandaloneModel {
  match mode {
    super::Mode::Struct(model) => *model,
    super::Mode::Composed(_) | super::Mode::Element(_) => {
      panic!("a declaration with no marker is the struct mode")
    }
  }
}

/// Tokens with their spacing removed, so a comparison is about content rather than layout.
///
/// The interface suite's own helper, spelled again rather than shared: it is three tokens, and a
/// test helper reaching across a crate boundary would be a dependency edge for nothing.
fn tight(tokens: impl ToTokens) -> String {
  tokens.to_token_stream().to_string().replace(' ', "")
}

/// The BASE name of a written type — `CueSqliteComparison<__INGRAPH_DB__>` is `CueSqliteComparison`.
fn base_of(ty: &syn::Type) -> String {
  match ty {
    syn::Type::Path(path) => path
      .path
      .segments
      .last()
      .map_or_else(String::new, |segment| segment.ident.to_string()),
    _ => String::new(),
  }
}

/// ONE method of an inherent block, by name — how a pin reaches the methods BOTH doors emit inside a
/// block one of them fills with more.
fn method(items: &[syn::Item], name: &str) -> String {
  for item in items {
    let syn::Item::Impl(block) = item else {
      continue;
    };
    for member in &block.items {
      if let syn::ImplItem::Fn(function) = member
        && function.sig.ident == name
      {
        return tight(function);
      }
    }
  }
  panic!("no `{name}` in the emitted block");
}

/// The refusal a declaration was answered with.
///
/// A `match` rather than `expect_err`, because the model carries `syn` types that derive no `Debug`
/// — a plain fact about the model rather than a gap: it is a token bundle, and its `Debug` would be
/// a second rendering of tokens `ToTokens` already renders.
fn refused<T>(result: syn::Result<T>) -> syn::Error {
  match result {
    Ok(_) => panic!("the declaration was accepted where a refusal was expected"),
    Err(refused) => refused,
  }
}

/// A list of items, tightened and concatenated — one string per FACE, so an item that went missing
/// on one side fails the comparison rather than shifting an index.
fn joined(items: &[syn::Item]) -> String {
  items.iter().map(tight).collect()
}

/// The bare door's face, for a declaration written in one piece.
fn bare(input: &syn::DeriveInput, face: Face) -> proc_macro2::TokenStream {
  let model = super::parse(input, face).expect("a declaration the bare door accepts");
  emit(&model, face)
}

/// The grammar word's WHOLE expansion, for a declaration written the way the attribute form takes
/// one.
fn worded(input: &syn::DeriveInput) -> proc_macro2::TokenStream {
  let (host, options) = crate::host::split(input);
  crate::parse::parse(&host, &options, NodeKind::Record)
    .expect("a declaration the grammar word accepts")
    .emit()
}

/// One item of an expansion, by the name it declares — how a pin reaches the ONE face it is about
/// inside an expansion that carries a dozen.
///
/// A `syn::File` parse rather than a substring search, so what is compared is an ITEM and not a
/// window that happens to line up. Two items may share a name — a struct and its inherent `impl` —
/// and both are returned, in emission order, because a face IS its declaration and its methods.
fn items(expansion: &proc_macro2::TokenStream, name: &str) -> Vec<syn::Item> {
  let file: syn::File = syn::parse2(expansion.clone()).expect("an expansion is a file");
  let mut found = Vec::new();
  collect(&file.items, name, &mut found);
  found
}

/// The walk `items` spends — an expansion nests its emission inside `const _: () = { … }` blocks, so
/// the search has to reach through them.
fn collect(items: &[syn::Item], name: &str, found: &mut Vec<syn::Item>) {
  for item in items {
    match item {
      syn::Item::Struct(declared) if declared.ident == name => found.push(item.clone()),
      syn::Item::Enum(declared) if declared.ident == name => found.push(item.clone()),
      // The self type is matched on its BASE — an inherent block over a generic comparison is
      // `impl<DB> CueSqliteComparison<DB>`, whose written self type carries the parameter.
      syn::Item::Impl(block) if block.trait_.is_none() && base_of(&block.self_ty) == name => {
        found.push(item.clone());
      }
      syn::Item::Const(constant) => {
        if let syn::Expr::Block(block) = &*constant.expr {
          let nested: Vec<syn::Item> = block
            .block
            .stmts
            .iter()
            .filter_map(|stmt| match stmt {
              syn::Stmt::Item(item) => Some(item.clone()),
              _ => None,
            })
            .collect();
          collect(&nested, name, found);
        }
      }
      _ => {}
    }
  }
}

/// **THE FILTER FACE IS ONE EMISSION, token for token.**
///
/// The same struct through `#[ingraph::record(…)]` and through `#[derive(ingraph::Filter)]`, with
/// the same words on the same fields. Not "the same shape" and not "the same field names": the two
/// emissions are compared as TOKENS, so a doc line, a visibility or a builder's receiver that moved
/// on one side and not the other fails here.
#[test]
fn the_filter_face_is_one_emission() {
  let word: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    pub struct Cue {
      #[ingraph(id)]
      id: u64,
      #[ingraph(string)]
      title: String,
      #[ingraph(scalar)]
      mark: i64,
    }
  };
  let bare_door: syn::DeriveInput = syn::parse_quote! {
    pub struct Cue {
      id: u64,
      #[ingraph(string)]
      title: String,
      #[ingraph(scalar)]
      mark: i64,
    }
  };

  let worded = joined(&items(&worded(&word), "CueFilter"));
  // A comparison of two empty strings would pass and say nothing, so the FACE is asserted present
  // before it is asserted equal — the failure a name change would otherwise hide.
  assert!(worded.contains("structCueFilter"), "{worded}");
  assert!(worded.contains("fnwith_title"), "{worded}");
  assert_eq!(
    worded,
    joined(&items(&bare(&bare_door, Face::Filter), "CueFilter")),
  );
}

/// **THE ORDER-BY FACE IS ONE EMISSION**, for the halves both doors emit: the term enum and the
/// direction every term answers.
///
/// The record's `identity` and its per-database order terms are NOT compared, and the absence is the
/// gate rather than a gap — a record's identity rides the PAGE's law, which needs a stored id and a
/// SQL clause machine, and a hand-written struct has neither to ride.
#[test]
fn the_order_by_enum_is_one_emission() {
  let word: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite)]
    pub struct Cue {
      #[ingraph(id)]
      id: u64,
      #[ingraph(string)]
      title: String,
      #[ingraph(scalar)]
      mark: i64,
    }
  };
  let bare_door: syn::DeriveInput = syn::parse_quote! {
    pub struct Cue {
      id: u64,
      title: String,
      mark: i64,
    }
  };

  let worded = items(&worded(&word), "CueOrderBy");
  let bare = items(&bare(&bare_door, Face::OrderBy), "CueOrderBy");
  assert_eq!(worded.len(), 2, "an order-by is an enum and its methods");
  assert_eq!(bare.len(), 2, "an order-by is an enum and its methods");
  // The ENUM, token for token.
  assert!(
    tight(&worded[0]).contains("enumCueOrderBy"),
    "the enum is present"
  );
  assert_eq!(tight(&worded[0]), tight(&bare[0]));
  // …and the two METHODS both doors emit. Per method rather than per block, because the record's
  // block carries the per-database resolvers and clause builders beside them — the storage extras a
  // grammar word ADDS, which is exactly what a bare door has no table to add.
  assert_eq!(method(&worded, "direction"), method(&bare, "direction"));
  assert_eq!(method(&worded, "identity"), method(&bare, "identity"));
}

/// **THE COMPARISON FACE IS ONE EMISSION**, at a database both doors name.
///
/// The record's comparison is named from its ROW and the bare door's from the SUBJECT, so the two
/// carry different type names by construction — which is why this pin renames the bare door's onto
/// the record's rather than asserting a name it has no reason to share.
#[test]
fn the_comparison_face_is_one_emission() {
  let word: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite)]
    pub struct Cue {
      #[ingraph(id)]
      id: u64,
      #[ingraph(string)]
      title: String,
    }
  };
  let bare_door: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite)]
    pub struct Cue {
      id: u64,
      #[ingraph(string)]
      title: String,
    }
  };

  let worded = items(&worded(&word), "CueSqliteComparison");
  let bare = items(&bare(&bare_door, Face::Comparison), "CueSqliteComparison");
  assert_eq!(worded.len(), 2, "a comparison is a struct and its methods");
  assert_eq!(bare.len(), 2, "a comparison is a struct and its methods");
  assert!(
    tight(&worded[0]).contains("structCueSqliteComparison"),
    "the struct is present"
  );
  assert_eq!(tight(&worded[0]), tight(&bare[0]));
  assert_eq!(tight(&worded[1]), tight(&bare[1]));
}

/// **A RECORD's WORD REFUSES BY NAME.** `id` declares an identity, and a bare struct has none — so
/// the door says which word it refused and where to write it instead, rather than dropping it.
#[test]
fn a_records_word_refuses_by_name() {
  let input: syn::DeriveInput = syn::parse_quote! {
    pub struct Cue {
      #[ingraph(id)]
      id: u64,
    }
  };
  let refused = refused(super::parse(&input, Face::Filter));
  let sentence = refused.to_string();
  assert!(sentence.contains("`id`"), "{sentence}");
  assert!(sentence.contains("RECORD"), "{sentence}");
  assert!(sentence.contains("#[ingraph::record"), "{sentence}");
}

/// **THE ORPHAN FIELD HOOK REFUSES BY NAME** — the dependency rule. A conversion refines a crossing,
/// a crossing starts from a seat, and a field naming one with no seat declared has written a
/// refinement of nothing.
#[test]
fn an_orphan_field_conversion_refuses_by_name() {
  let input: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite)]
    pub struct Cue {
      #[ingraph(sqlite(type = "i64", try_into = "cross"))]
      mark: u64,
    }
  };
  let refused = refused(super::parse(&input, Face::Comparison));
  let sentence = refused.to_string();
  assert!(sentence.contains("try_into"), "{sentence}");
  assert!(
    sentence.contains("filter = \\\"path::to::Filter\\\"") || sentence.contains("filter ="),
    "{sentence}"
  );
}

/// …and the TWIN, so what fails above is the DEPENDENCY and not the spelling: the same field under a
/// declared hook is accepted.
#[test]
fn the_same_conversion_under_a_hook_is_accepted() {
  let input: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite, filter = "CueFilter")]
    pub struct Cue {
      #[ingraph(sqlite(type = "i64", try_into = "cross"))]
      mark: u64,
    }
  };
  super::parse(&input, Face::Comparison).expect("a conversion under a hook is legal");
}

/// **A DATABASE THE CONTAINER DID NOT NAME REFUSES BY NAME** — a per-database refinement refines a
/// comparison, and the comparisons are the ones the container names.
///
/// The second half used to be the word the container wrote them under, `persist`. The container
/// names its databases BARE now, so the sentence points at the HEAD instead — which is the more
/// useful half anyway: it names the line to add the missing word to.
#[test]
fn a_field_naming_an_undeclared_database_refuses() {
  let input: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite)]
    pub struct Cue {
      #[ingraph(postgres(type = "i64"))]
      mark: u64,
    }
  };
  let refused = refused(super::parse(&input, Face::Comparison));
  let sentence = refused.to_string();
  assert!(sentence.contains("postgres"), "{sentence}");
  assert!(sentence.contains("the head's store words"), "{sentence}");
}

/// **A NEAR-MISS IS AN UNKNOWN ENTRY**, not a silent acceptance: the container's vocabulary is
/// closed, and a word one letter off names nothing.
#[test]
fn a_wrong_container_word_refuses() {
  let input: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(filters(rename = "CueWhere"))]
    pub struct Cue {
      mark: u64,
    }
  };
  let sentence = refused(super::parse(&input, Face::Filter)).to_string();
  assert!(sentence.contains("unknown entry"), "{sentence}");
  assert!(sentence.contains("filter(rename"), "{sentence}");
}

/// **THE TWO `filter` WORDS ARE TWO WORDS.** `filter(rename = "…")` moves the emitted type and
/// `filter = "…"` names the crossing's seat, and which one was written is decided by what follows
/// the word rather than by an order rule.
#[test]
fn the_two_filter_words_are_told_apart_by_their_shape() {
  let renamed: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(filter(rename = "CueWhere"))]
    pub struct Cue {
      mark: u64,
    }
  };
  let model = structural(super::parse(&renamed, Face::Filter).expect("a rename block"));
  assert_eq!(model.filter.safe().to_string(), "CueWhere");
  assert!(model.hook.is_none());

  let hooked: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(sqlite, filter = "CueWhere")]
    pub struct Cue {
      mark: u64,
    }
  };
  let model = structural(super::parse(&hooked, Face::Comparison).expect("a hook"));
  assert_eq!(model.filter.safe().to_string(), "CueFilter");
  assert_eq!(tight(model.hook.as_ref().expect("a hook")), "CueWhere");
}

/// **THE SHAPE IS CHECKED AT THE DOOR**, where the tokens an author wrote are still in hand: a
/// positional struct has no member name for a face to take, and a generic one would have to thread
/// its parameter through every emitted `where` clause.
#[test]
fn the_declarations_shape_is_refused_at_the_door() {
  let positional: syn::DeriveInput = syn::parse_quote!(
    pub struct Cue(u64);
  );
  let sentence = refused(super::parse(&positional, Face::Filter)).to_string();
  assert!(sentence.contains("NAMED fields"), "{sentence}");

  let generic: syn::DeriveInput = syn::parse_quote! {
    pub struct Cue<T> {
      mark: T,
    }
  };
  let sentence = refused(super::parse(&generic, Face::OrderBy)).to_string();
  assert!(sentence.contains("CONCRETE"), "{sentence}");

  let vocabulary: syn::DeriveInput = syn::parse_quote! {
    pub enum Cue {
      One,
    }
  };
  let sentence = refused(super::parse(&vocabulary, Face::Comparison)).to_string();
  assert!(sentence.contains("structs only"), "{sentence}");
}