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
//! The union parser's acceptance: what a declaration may say, and every shape it may not.
//!
//! The declarations are written the way a DERIVE takes one — options in the `#[ingraph(…)]` beside
//! the enum — because that is what this word became. The pass is called directly rather than through
//! `host::split`, which is the attribute family's own reader and has nothing left to split here.

use ingraph_codegen::union::UnionModel;
use quote::ToTokens as _;

/// The pass under test.
fn parse(input: &syn::DeriveInput) -> syn::Result<UnionModel> {
  super::parse(input)
}

/// Every member a model kept, as the variant that names it and the type it carries.
fn members(model: &UnionModel) -> Vec<(String, String)> {
  model
    .members
    .iter()
    .map(|member| {
      (
        member.ident.to_string(),
        member.ty.to_token_stream().to_string().replace(' ', ""),
      )
    })
    .collect()
}

/// The refusal a declaration gets, as one string.
fn refusal(input: &syn::DeriveInput) -> String {
  parse(input)
    .expect_err("the declaration is refused")
    .into_iter()
    .map(|error| error.to_string())
    .collect::<Vec<_>>()
    .join(" | ")
}

/// **A union declares NOTHING and is complete.** The member set is the declaration, and the derive
/// reads it off the variants.
#[test]
fn a_bare_union_is_the_types_its_variants_carry() {
  let model = parse(&syn::parse_quote! {
    pub enum Found {
      Media(Media),
      Clip(Clip),
    }
  })
  .expect("one member per variant is the whole shape");

  assert_eq!(model.name, "Found");
  assert_eq!(
    members(&model),
    [
      ("Media".to_owned(), "Media".to_owned()),
      ("Clip".to_owned(), "Clip".to_owned()),
    ]
  );
  assert_eq!(model.error, None);
  assert_eq!(model.error(), "FoundUnwrapError");
}

/// **A member is whatever type the declaration wrote**, this derive having nothing to say about it:
/// a path with segments, a collection, a tuple and a primitive are all one shape here.
#[test]
fn a_member_is_any_type_the_declaration_carries() {
  let model = parse(&syn::parse_quote! {
    enum Held {
      Media(crate::media::Media),
      Bytes(Vec<u8>),
      Pair((u8, u16)),
      Count(u32),
    }
  })
  .expect("a member type is not this derive's business");

  assert_eq!(
    members(&model)
      .into_iter()
      .map(|(_, ty)| ty)
      .collect::<Vec<_>>(),
    ["crate::media::Media", "Vec<u8>", "(u8,u16)", "u32"]
  );
}

/// **A ONE-MEMBER union is legal** — GraphQL's law is *one or more*, so a union with nothing to
/// choose between is a declaration this derive has nothing to object to.
#[test]
fn one_member_is_a_union() {
  let model = parse(&syn::parse_quote! {
    enum Only { Media(Media) }
  })
  .expect("one or more");

  assert_eq!(members(&model).len(), 1);
}

/// **The refusal type takes the name the declaration gives it**, and the default is what a
/// declaration that says nothing gets.
#[test]
fn the_refusal_type_is_named_by_the_declaration_or_by_the_convention() {
  let named = parse(&syn::parse_quote! {
    #[ingraph(unwrap_error(rename = "NoSuchSide"))]
    enum Side { Left(Media), Right(Clip) }
  })
  .expect("a union may name the one type it emits");

  assert_eq!(named.error, Some(syn::parse_quote!(NoSuchSide)));
  assert_eq!(named.error(), "NoSuchSide");

  let defaulted = parse(&syn::parse_quote! {
    enum Side { Left(Media), Right(Clip) }
  })
  .expect("and a declaration that says nothing keeps the convention");

  assert_eq!(defaulted.error, None);
  assert_eq!(defaulted.error(), "SideUnwrapError");
}

/// A rename goes through a string so a RAW identifier stays spellable — the record grammar's rule,
/// reached here through the reader all three derives share.
#[test]
fn a_refusal_may_be_named_with_a_raw_identifier() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(unwrap_error(rename = "r#type"))]
    enum Side { Left(Media), Right(Clip) }
  })
  .expect("`r#type` is an identifier");

  assert_eq!(model.error(), "r#type");
}

/// **The one name the refusal may not take is the union's own** — the two land in one scope, where
/// the expansion would be a second definition of the enum's name.
#[test]
fn refuses_a_refusal_named_after_the_union() {
  let refused = refusal(&syn::parse_quote! {
    #[ingraph(unwrap_error(rename = "Side"))]
    enum Side { Left(Media), Right(Clip) }
  });
  assert!(
    refused.contains("already the union's own name"),
    "{refused}"
  );
}

/// A type name reaches only Rust, so the string has to BE one — the shared reader's rule, and the
/// empty string is refused by it rather than as a special case here.
#[test]
fn refuses_a_refusal_name_that_is_not_an_identifier() {
  for spelling in ["", "Not An Ident", "9Lives"] {
    let refused = refusal(&syn::parse_quote! {
      #[ingraph(unwrap_error(rename = #spelling))]
      enum Side { Left(Media), Right(Clip) }
    });
    assert!(
      refused.contains("must be a valid identifier"),
      "{spelling:?}: {refused}"
    );
  }
}

/// The block exists to carry the one option, so writing it without one is refused rather than read
/// as the default.
#[test]
fn refuses_an_error_block_that_names_nothing() {
  for input in [
    syn::parse_quote! {
      #[ingraph(unwrap_error)]
      enum Side { Left(Media) }
    },
    syn::parse_quote! {
      #[ingraph(unwrap_error())]
      enum Side { Left(Media) }
    },
  ] {
    let refused = refusal(&input);
    assert!(
      refused.contains("`unwrap_error(…)` needs `rename = \"…\"`"),
      "{refused}"
    );
  }

  let twice = refusal(&syn::parse_quote! {
    #[ingraph(unwrap_error(rename = "A", rename = "B"))]
    enum Side { Left(Media) }
  });
  assert!(
    twice.contains("declared more than once in `unwrap_error(…)`"),
    "{twice}"
  );
}

#[test]
fn refuses_a_declaration_that_is_not_an_enum() {
  let refused = refusal(&syn::parse_quote! {
    struct Found { media: Media }
  });
  assert!(refused.contains("supports enums only"), "{refused}");
}

#[test]
fn refuses_an_enum_with_no_variants() {
  let refused = refusal(&syn::parse_quote! {
    enum Found {}
  });
  assert!(refused.contains("declares no union"), "{refused}");
  assert!(refused.contains("ONE OR MORE unique member"), "{refused}");
}

/// **A variant with no payload names no member**, and the empty tuple is the same declaration
/// spelled differently. Every offender is named, not just the first.
#[test]
fn refuses_every_variant_that_carries_no_member() {
  let refused = refusal(&syn::parse_quote! {
    enum Found { Media(Media), Bare, Empty() }
  });
  assert!(refused.contains("`Bare` carries none"), "{refused}");
  assert!(refused.contains("`Empty` carries none"), "{refused}");
}

/// **A union alternative is ONE member type**, so a variant holding two is a member type nobody
/// declared.
#[test]
fn refuses_a_variant_carrying_more_than_one_member() {
  let refused = refusal(&syn::parse_quote! {
    enum Found { Media(Media), Both(Media, Clip) }
  });
  assert!(refused.contains("`Both` carries 2"), "{refused}");
  assert!(refused.contains("single-value tuple variant"), "{refused}");
}

/// **The member is POSITIONAL.** A variant's one member is the whole of what it holds, so a field
/// name has nothing to tell it apart from — and the wire shape a declared union renders as takes a
/// single-value tuple variant.
#[test]
fn refuses_a_member_carried_in_a_named_field() {
  let refused = refusal(&syn::parse_quote! {
    enum Found { Media(Media), Clip { clip: Clip } }
  });
  assert!(refused.contains("`Clip` names its payload"), "{refused}");
}

#[test]
fn refuses_a_generic_union() {
  let refused = refusal(&syn::parse_quote! {
    enum Pick<A, B> { Left(A), Right(B) }
  });
  assert!(refused.contains("generic unions"), "{refused}");
  assert!(
    refused.contains("`Pick<A, B>` is one member twice"),
    "{refused}"
  );
}

#[test]
fn refuses_a_lifetime_and_a_where_clause_for_the_same_reason() {
  let by_lifetime = refusal(&syn::parse_quote! {
    enum Found<'a> { Media(&'a Media) }
  });
  assert!(by_lifetime.contains("generic unions"), "{by_lifetime}");

  let by_clause = refusal(&syn::parse_quote! {
    enum Found where Self: Sized { Media(Media) }
  });
  assert!(by_clause.contains("generic unions"), "{by_clause}");
}

/// **Two variants carrying ONE type is GraphQL's own refusal**, quoted rather than invented: a
/// union type must include one or more UNIQUE member types.
#[test]
fn refuses_two_variants_that_carry_one_member_type() {
  let refused = refusal(&syn::parse_quote! {
    enum Found { Media(Media), Cover(Media) }
  });
  assert!(
    refused.contains("`Cover` and `Media` carry ONE member type"),
    "{refused}"
  );
  assert!(refused.contains("UNIQUE member types"), "{refused}");
}

/// **The uniqueness this layer can see is SYNTACTIC, and the limit is measured rather than hidden.**
///
/// A macro holds tokens, so one type reached through two paths is two token streams — and a
/// declaration writing both is accepted here. What refuses it is the wire round's own rendering,
/// where the two paths resolve to one schema member; there is nothing at this layer that could tell
/// them apart.
#[test]
fn one_type_reached_through_two_paths_is_past_what_tokens_can_see() {
  parse(&syn::parse_quote! {
    enum Found { Media(Media), Same(media::Media) }
  })
  .expect("two token streams, and only a type checker knows they are one type");
}

/// Two variants whose words are one word: seven duplicate definitions inside the expansion, at a
/// span the declaration cannot edit.
#[test]
fn refuses_two_variants_that_derive_one_word() {
  let refused = refusal(&syn::parse_quote! {
    enum Found { Vp9(Media), VP9(Clip) }
  });
  assert!(refused.contains("both derive `is_vp9`"), "{refused}");
}

/// An entry nobody reads is a rule its author believes they declared, so an unrecognised one is
/// refused rather than ignored — and the sentence names what this level does take.
#[test]
fn refuses_an_entry_a_union_does_not_take() {
  let on_the_enum = refusal(&syn::parse_quote! {
    #[ingraph(persist(sqlite))]
    enum Found { Media(Media) }
  });
  assert!(on_the_enum.contains("unknown entry"), "{on_the_enum}");
  assert!(
    on_the_enum.contains("`unwrap_error(rename = \"…\")`, `graphql(…)` and `crate = \"…\"`"),
    "{on_the_enum}"
  );

  let on_a_variant = refusal(&syn::parse_quote! {
    enum Found {
      #[ingraph(rename = "media")]
      Media(Media),
    }
  });
  assert!(
    on_a_variant.contains("on a union's variant — a variant takes none"),
    "{on_a_variant}"
  );
}

/// One compile reports the whole declaration, which is what the accumulating error layer buys: the
/// grammar mistake and the shape mistake are both here, from one pass.
#[test]
fn one_pass_reports_the_grammar_and_the_shape_together() {
  let refused = refusal(&syn::parse_quote! {
    #[ingraph(persist(sqlite))]
    enum Found { Bare }
  });
  assert!(refused.contains("unknown entry"), "{refused}");
  assert!(refused.contains("`Bare` carries none"), "{refused}");
}

/// **`crate = "…"` is READ, and the WIRE ROUND is what bought it.**
///
/// It was refused as an unknown entry while the whole emission was `core` — an option nobody reads
/// is a rule its author believes they declared — and a declared face names the shelf and the binding
/// gate. Read UNCONDITIONALLY, `graphql(…)` or not, because which crate an expansion is rooted at is
/// a constant of the grammar rather than an entry whose meaning depends on its neighbours.
#[test]
fn the_crate_the_expansion_is_rooted_at_is_the_declarations_to_move() {
  let moved = parse(&syn::parse_quote! {
    #[ingraph(crate = "shim::ingraph")]
    enum Found { Media(Media) }
  })
  .expect("the wire round bought this option");
  assert_eq!(moved.krate, syn::parse_quote!(shim::ingraph));

  let defaulted = parse(&syn::parse_quote! {
    enum Found { Media(Media) }
  })
  .expect("and a declaration that says nothing keeps the convention");
  assert_eq!(defaulted.krate, syn::parse_quote!(::ingraph));

  let twice = refusal(&syn::parse_quote! {
    #[ingraph(crate = "a::b", crate = "c::d")]
    enum Found { Media(Media) }
  });
  assert!(
    twice.contains("`crate` is declared more than once"),
    "{twice}"
  );
}

/// The parser keeps the RUST spelling and hands the emitter an unraw'd word — the `r#` is Rust's
/// escape and no part of the name.
#[test]
fn a_raw_variant_keeps_its_spelling_and_loses_its_escape() {
  let model = parse(&syn::parse_quote! {
    enum Found { r#type(Media) }
  })
  .expect("a raw identifier is a variant like any other");
  let member = &model.members[0];

  assert_eq!(member.ident.to_string(), "r#type");
  assert_eq!(member.name(), "type");
  assert_eq!(member.word(), "type");
}

/// **The old spelling is a NAMED MIGRATION**, not an unknown word: `error` names the CONVERSION
/// CELLS now — one per leg, inside a database's block — so a knob sharing it would be told apart by
/// depth alone.
///
/// Stated once for both member sets, because the refusal is the SEAM's own emission and both take
/// one word for it.
#[test]
fn refuses_the_old_spelling_of_the_refusals_knob_by_naming_the_new_one() {
  let moved = refusal(&syn::parse_quote! {
    #[ingraph(error(rename = "NoSuchSide"))]
    enum Side { Left(Media), Right(Clip) }
  });

  assert!(
    moved.contains("`error` names CONVERSION CELLS now"),
    "{moved}"
  );
  assert!(moved.contains("`unwrap_error(rename = \"…\")`"), "{moved}");
}

/// **THE OPTIONS ARE ON THE ITEM, and a derive is what makes that the only place they can be.**
///
/// The attribute form took them inside its own parentheses and refused a `#[ingraph(…)]` beside the
/// declaration by name; this word has no parentheses of its own, so the block IS the grammar and the
/// migration refusal has nothing left to refuse. What the pass must not do is quietly ignore the
/// block, which is what this reads back.
#[test]
fn the_options_are_read_off_the_item_the_derive_sits_on() {
  let model = parse(&syn::parse_quote! {
    #[ingraph(unwrap_error(rename = "Nope"))]
    enum SearchResult { Media(Media) }
  })
  .expect("a derive's options are the block beside the declaration");

  assert_eq!(model.error(), "Nope");
}