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
//! The leaf-error grammar, and the four code rules.
//!
//! The refusals with a FIXTURE beside them — a missing code, a code that is not screaming, two
//! variants under one word, a word that is the framework's — are also in
//! `tests/refusals/`, where the sentence and the span are pinned against a real compile. What is
//! here is the whole family, including the ones no fixture carries, and the template checking, which
//! is where most of the rules are.

use ingraph_codegen::error::{BindingAt, ErrorRoad, RESERVED, VariantShape};

use super::parse;

/// Split a derive-shaped declaration the way the attribute entry point does, then parse it.
fn read(
  input: &syn::DeriveInput,
  road: ErrorRoad,
) -> syn::Result<ingraph_codegen::error::ErrorModel> {
  let (host, arguments) = crate::host::split(input);
  parse(&host, &arguments, road)
}

/// The refusal a declaration earns, as one string — every rule it broke, newline-separated.
fn refused(input: &syn::DeriveInput) -> String {
  read(input, ErrorRoad::Mutation)
    .err()
    .map(|error| {
      error
        .into_iter()
        .map(|one| one.to_string())
        .collect::<Vec<_>>()
        .join("\n")
    })
    .unwrap_or_else(|| panic!("the declaration was accepted"))
}

/// The model a declaration that is ACCEPTED produces.
fn accepted(input: &syn::DeriveInput) -> ingraph_codegen::error::ErrorModel {
  read(input, ErrorRoad::Mutation).expect("the declaration is accepted")
}

// ───────────────────────────────────────────────────────────────────────────────── what is ACCEPTED

#[test]
fn the_two_words_are_read_off_every_variant() {
  let model = accepted(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOT_A_DIRECTORY", error = "`{0}` is not a directory")]
      NotADirectory(PathBuf),
      #[ingraph(code = "SHUTTING_DOWN", error = "winding down")]
      ShuttingDown,
    }
  });
  assert_eq!(model.name, "WatchError");
  assert_eq!(model.variants.len(), 2);
  assert_eq!(model.variants[0].code.value(), "NOT_A_DIRECTORY");
  assert_eq!(model.variants[0].shape, VariantShape::Tuple);
  assert_eq!(model.variants[1].shape, VariantShape::Unit);
}

/// THE CODE IS FOLDED INTO THE TEMPLATE at this pass, so the one-code-head law is applied in one
/// place and the emission carries one literal.
#[test]
fn the_code_heads_the_template_and_the_placeholder_is_rewritten() {
  let model = accepted(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOT_A_DIRECTORY", error = "`{0}` is not a directory")]
      NotADirectory(PathBuf),
    }
  });
  assert_eq!(
    model.variants[0].rendering.template,
    "NOT_A_DIRECTORY: `{__ingraph_at_0}` is not a directory"
  );
  assert_eq!(model.variants[0].rendering.bound.len(), 1);
  assert_eq!(
    model.variants[0].rendering.bound[0].at,
    BindingAt::Position(0)
  );
}

/// EVERY PLACEHOLDER SHAPE: implicit position, explicit position, name, a format spec, and the two
/// escapes.
#[test]
fn every_placeholder_shape_resolves_to_a_binding() {
  let model = accepted(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "TUPLE", error = "{} then {1} then {0:>4}")]
      Tuple(u8, u8),
      #[ingraph(code = "NAMED", error = "{root} at {depth:?}")]
      Named { root: String, depth: u8 },
      #[ingraph(code = "BRACES", error = "a literal {{ and a }}")]
      Braces,
    }
  });
  assert_eq!(
    model.variants[0].rendering.template,
    "TUPLE: {__ingraph_at_0} then {__ingraph_at_1} then {__ingraph_at_0:>4}"
  );
  // `{}` and `{0}` are the SAME field, so they share ONE binding.
  assert_eq!(model.variants[0].rendering.bound.len(), 2);
  assert_eq!(
    model.variants[1].rendering.template,
    "NAMED: {__ingraph_named_root} at {__ingraph_named_depth:?}"
  );
  assert_eq!(
    model.variants[1].rendering.bound[0].at,
    BindingAt::Named(syn::parse_quote!(root))
  );
  assert_eq!(
    model.variants[2].rendering.template,
    "BRACES: a literal {{ and a }}"
  );
  assert!(model.variants[2].rendering.bound.is_empty());
}

/// A NAME WRITTEN TWICE mints ONE binding — the pattern binds a field once however often it is read.
#[test]
fn a_field_read_twice_is_bound_once() {
  let model = accepted(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "TWICE", error = "{root} and again {root}")]
      Twice { root: String },
    }
  });
  assert_eq!(model.variants[0].rendering.bound.len(), 1);
}

/// AN EMPTY ENUM is accepted and states the honest nothing — an error with no way to fail.
#[test]
fn an_error_with_no_variants_is_accepted() {
  let model = accepted(&syn::parse_quote! {
    pub enum Never {}
  });
  assert!(model.variants.is_empty());
}

/// BOTH ROADS read one grammar, and the word is carried into the model.
#[test]
fn both_roads_read_the_same_declaration() {
  let written: syn::DeriveInput = syn::parse_quote! {
    pub enum LookupError {
      #[ingraph(code = "NO_SUCH_SHELF", error = "no shelf called `{0}`")]
      NoSuchShelf(String),
    }
  };
  assert_eq!(
    read(&written, ErrorRoad::Mutation).expect("accepted").road,
    ErrorRoad::Mutation
  );
  assert_eq!(
    read(&written, ErrorRoad::Query).expect("accepted").road,
    ErrorRoad::Query
  );
}

// ───────────────────────────────────────────────────────────────────────────── the FOUR code rules

#[test]
fn a_variant_with_no_code_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(error = "nothing names this")]
      Unnamed,
    }
  });
  assert!(
    refusal.contains("`Unnamed` declares no `code`"),
    "{refusal}"
  );
}

#[test]
fn a_code_that_is_not_screaming_is_refused() {
  for word in [
    "notScreaming",
    "lower_case",
    "_LEADING",
    "TRAILING_",
    "",
    "9LIVES",
  ] {
    let written: syn::DeriveInput = syn::parse_quote! {
      pub enum WatchError {
        #[ingraph(code = #word, error = "a sentence")]
        Arm,
      }
    };
    let refusal = refused(&written);
    assert!(
      refusal.contains("is not `SCREAMING_SNAKE_CASE`"),
      "`{word}`: {refusal}"
    );
  }
}

/// DIGITS ARE LEGAL, and the rule is a SUPERSET of what the framework's own words use — the code
/// space below the framework's belongs to the application.
#[test]
fn a_code_may_carry_digits() {
  let model = accepted(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "HTTP_404", error = "gone")]
      Gone,
    }
  });
  assert_eq!(model.variants[0].code.value(), "HTTP_404");
}

#[test]
fn two_variants_under_one_code_are_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "SAME", error = "one")]
      First,
      #[ingraph(code = "SAME", error = "two")]
      Second,
    }
  });
  assert!(
    refusal.contains("`SAME` is already the code of `First`"),
    "{refusal}"
  );
}

#[test]
fn a_framework_code_is_refused() {
  for word in RESERVED {
    let written: syn::DeriveInput = syn::parse_quote! {
      pub enum WatchError {
        #[ingraph(code = #word, error = "a sentence")]
        Arm,
      }
    };
    let refusal = refused(&written);
    assert!(
      refusal.contains("is one of the framework's own wire codes and is reserved"),
      "`{word}`: {refusal}"
    );
  }
}

/// EVERY RESERVED WORD IS ONE THIS CRATE CAN RENDER, which is what the refusal above spends.
///
/// The list is `ingraph-codegen`'s, and it has to be: a proc macro's emitter runs before — and
/// without — the crate it generates code for, so it cannot read [`ErrorCode`] at all. That the two
/// halves AGREE is pinned in `ingraph`'s own `graphql::code` fixture, which is the file a round that
/// adds a word already has to touch and therefore the place the pin catches such a round. What is
/// asserted here is the half this crate can see: each reserved word is a real one, reachable through
/// `ingraph` and spelled the same way.
#[test]
fn every_reserved_word_is_one_the_framework_publishes() {
  let published: Vec<&str> = [
    ingraph::ErrorCode::RepeatedOrderSubject,
    ingraph::ErrorCode::AmbiguousPageDirection,
    ingraph::ErrorCode::UnusableCursor,
    ingraph::ErrorCode::StoreRefused,
    ingraph::ErrorCode::UnsupportedFilter,
    ingraph::ErrorCode::UnrenderableOrder,
    ingraph::ErrorCode::UnpageableOrder,
    ingraph::ErrorCode::UnreadableRow,
    ingraph::ErrorCode::OversizedSkip,
    ingraph::ErrorCode::UnwrittenArtifact,
    ingraph::ErrorCode::UnusableAddress,
    ingraph::ErrorCode::UnreachableSource,
    ingraph::ErrorCode::UnreachableNode,
    ingraph::ErrorCode::RequestDropped,
    ingraph::ErrorCode::RequestTimedOut,
  ]
  .iter()
  .map(|code| code.as_str())
  .collect();
  for word in RESERVED {
    assert!(
      published.contains(word),
      "`{word}` is reserved and this framework publishes no such code"
    );
  }
}

// ──────────────────────────────────────────────────────────────── the rest of the refusal family

#[test]
fn a_variant_with_no_error_word_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "SILENT")]
      Silent,
    }
  });
  assert!(
    refusal.contains("`Silent` declares no `error`"),
    "{refusal}"
  );
}

#[test]
fn a_placeholder_naming_no_field_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "{missing} is not here")]
      Arm { root: String },
    }
  });
  assert!(
    refusal.contains("`Arm` has no field called `missing`"),
    "{refusal}"
  );
}

#[test]
fn a_position_past_the_last_field_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "{3} is not here")]
      Arm(u8),
    }
  });
  assert!(
    refusal.contains("names field 3 of `Arm`, which has 1"),
    "{refusal}"
  );
}

/// A POSITIONAL PLACEHOLDER over a NAMED variant is refused — the fields have names, and reading
/// them by position would be reading a declaration in an order it never fixed.
#[test]
fn a_position_over_a_named_variant_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "{0} is not how this is read")]
      Arm { root: String },
    }
  });
  assert!(
    refusal.contains("a positional placeholder reads a TUPLE variant"),
    "{refusal}"
  );
}

/// A UNIT VARIANT has nothing to interpolate, and a template that tries is refused.
#[test]
fn a_placeholder_on_a_unit_variant_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "{0} has nowhere to come from")]
      Arm,
    }
  });
  assert!(refusal.contains("which has 0"), "{refusal}");
}

#[test]
fn an_unclosed_or_unpaired_brace_is_refused() {
  let unclosed = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "a {0 that never closes")]
      Arm(u8),
    }
  });
  assert!(unclosed.contains("never closed"), "{unclosed}");

  let unpaired = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "a } that opens nothing")]
      Arm(u8),
    }
  });
  assert!(unpaired.contains("opens nothing"), "{unpaired}");
}

#[test]
fn a_struct_and_a_union_are_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub struct WatchError {
      root: String,
    }
  });
  assert!(refusal.contains("supports enums only"), "{refusal}");
}

#[test]
fn a_generic_parameter_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError<T> {
      #[ingraph(code = "NOPE", error = "{0}")]
      Arm(T),
    }
  });
  assert!(refusal.contains("takes no generic parameter"), "{refusal}");
}

#[test]
fn an_argument_on_the_attribute_is_refused() {
  let written: syn::DeriveInput = syn::parse_quote! {
    #[ingraph(crate = "other::ingraph")]
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "one")]
      Arm,
    }
  };
  let refusal = refused(&written);
  assert!(refusal.contains("takes no arguments"), "{refusal}");
}

#[test]
fn an_unknown_entry_on_a_variant_is_refused() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "NOPE", error = "one", rename = "two")]
      Arm,
    }
  });
  assert!(
    refusal.contains("unknown entry on a leaf error's variant"),
    "{refusal}"
  );
}

#[test]
fn each_word_is_written_at_most_once() {
  let twice_coded = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "ONE", code = "TWO", error = "one")]
      Arm,
    }
  });
  assert!(
    twice_coded.contains("`code` is declared more than once"),
    "{twice_coded}"
  );

  let twice_worded = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "ONE", error = "one", error = "two")]
      Arm,
    }
  });
  assert!(
    twice_worded.contains("`error` is declared more than once"),
    "{twice_worded}"
  );
}

/// A BAD VALUE earns ONE error and never its own echo — the mutation grammar's own measured law,
/// applied to this grammar's two words.
#[test]
fn a_bad_value_earns_one_error() {
  let refusal = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = NOT_A_STRING, error = "one")]
      Arm,
    }
  });
  assert_eq!(refusal.lines().count(), 1, "{refusal}");
  assert!(refusal.contains("in a string literal"), "{refusal}");

  let worded = refused(&syn::parse_quote! {
    pub enum WatchError {
      #[ingraph(code = "ONE", error = not_a_string)]
      Arm,
    }
  });
  assert_eq!(worded.lines().count(), 1, "{worded}");
  assert!(
    worded.contains("is the sentence this failure renders as"),
    "{worded}"
  );
}