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
//! Every rule this pass states, each put to a declaration that breaks it — and the shapes it
//! deliberately does NOT refuse.
//!
//! The refusals are asserted here rather than only as fixtures, because a `trybuild` file pins the
//! MESSAGE a user sees and this pins the rule: a pass that stopped checking would still print
//! nothing, and an empty error list is what both look like from the outside.

use ingraph_codegen::{model::GraphqlKind, mutation::DeclaredError};

/// The pass under test, over a declaration written the way the derive took one.
fn parse(input: &syn::DeriveInput) -> syn::Result<ingraph_codegen::mutation::MutationModel> {
  let (host, arguments) = crate::host::split(input);
  super::parse(&host, &arguments)
}

/// Parse a declaration, expecting it to be accepted.
fn accepted(input: proc_macro2::TokenStream) -> ingraph_codegen::mutation::MutationModel {
  parse(&syn::parse2(input).expect("the declaration parses"))
    .expect("the declaration is a mutation node")
}

/// Parse a declaration, expecting the refusal it earns.
fn refused(input: proc_macro2::TokenStream) -> String {
  parse(&syn::parse2(input).expect("the declaration parses"))
    .expect_err("this declaration breaks a rule")
    .into_iter()
    .map(|error| error.to_string())
    .collect::<Vec<_>>()
    .join("\n")
}

/// The whole of the grammar in one declaration: both handler spellings, every word inside the block,
/// and the three failure shapes.
#[test]
fn a_mutation_node_is_its_fields_and_the_words_beside_them() {
  let model = accepted(quote::quote! {
    #[ingraph(graphql(async_graphql))]
    pub struct WatchOps {
      #[ingraph(rename = "addWatch",
                handler(path = "crate::watch::add", async,
                        context(resource("crate::Catalog")),
                        error(type = "crate::AddWatchError", code = "ADD_FAILED")))]
      add: (AddWatch, AddResponse),

      #[ingraph(handler(path = "crate::watch::remove",
                        error(message = "that watch is not ours", code = "NOT_OURS")))]
      remove: (RemoveWatch, RemoveResponse),

      #[ingraph(handler = "crate::watch::reindex")]
      reindex: (Reindex, ()),
    }
  });

  assert_eq!(model.name, "WatchOps");
  assert_eq!(model.graphql, vec![GraphqlKind::AsyncGraphql]);
  assert_eq!(model.exchanges.len(), 3);

  let add = &model.exchanges[0];
  assert_eq!(add.field, "add");
  assert_eq!(
    add.rename.as_ref().map(syn::LitStr::value).as_deref(),
    Some("addWatch")
  );
  assert!(add.handler.awaited);
  assert_eq!(
    quote::ToTokens::to_token_stream(&add.handler.path).to_string(),
    "crate :: watch :: add"
  );
  assert_eq!(add.handler.context.len(), 1);
  assert_eq!(
    quote::ToTokens::to_token_stream(&add.handler.context[0]).to_string(),
    "crate :: Catalog"
  );
  match &add.handler.error {
    Some(DeclaredError::Rich { ty, code }) => {
      assert_eq!(
        quote::ToTokens::to_token_stream(ty).to_string(),
        "crate :: AddWatchError"
      );
      assert_eq!(
        code.as_ref().map(syn::LitStr::value).as_deref(),
        Some("ADD_FAILED")
      );
    }
    other => panic!("a `type` word is the rich shape: {other:?}"),
  }

  let remove = &model.exchanges[1];
  assert!(remove.rename.is_none());
  assert!(!remove.handler.awaited);
  assert!(remove.handler.context.is_empty());
  match &remove.handler.error {
    Some(DeclaredError::Canned { message, code }) => {
      assert_eq!(message.value(), "that watch is not ours");
      assert_eq!(
        code.as_ref().map(syn::LitStr::value).as_deref(),
        Some("NOT_OURS")
      );
    }
    other => panic!("a `message` word is the canned shape: {other:?}"),
  }

  // THE PLAIN FORM, and the exchange that cannot fail — one field spending both.
  let reindex = &model.exchanges[2];
  assert_eq!(
    quote::ToTokens::to_token_stream(&reindex.handler.path).to_string(),
    "crate :: watch :: reindex"
  );
  assert!(!reindex.handler.awaited);
  assert!(reindex.handler.error.is_none());
}

/// The OR law, from the grammar's side: one awaited handler is enough.
#[test]
fn one_awaited_handler_makes_the_node_awaited() {
  let all_blocking = accepted(quote::quote! {
    pub struct Ops {
      #[ingraph(handler = "crate::a")]
      a: (A, ()),
      #[ingraph(handler = "crate::b")]
      b: (B, ()),
    }
  });
  assert!(all_blocking.all_sync());

  let one_awaited = accepted(quote::quote! {
    pub struct Ops {
      #[ingraph(handler = "crate::a")]
      a: (A, ()),
      #[ingraph(handler(path = "crate::b", async))]
      b: (B, ()),
    }
  });
  assert!(!one_awaited.all_sync());
}

/// A node with no wire word is a whole node all the same — the block adds a schema over a surface
/// that is already there.
#[test]
fn a_node_needs_no_wire_word() {
  let model = accepted(quote::quote! {
    pub struct Ops {
      #[ingraph(handler = "crate::a")]
      a: (A, ()),
    }
  });
  assert!(model.graphql.is_empty());
}

/// `crate = "…"` moves where the expansion reaches the framework, exactly as every other grammar
/// here does.
#[test]
fn a_mutation_node_can_name_the_crate() {
  let model = accepted(quote::quote! {
    #[ingraph(crate = "crate::shim")]
    pub struct Ops {
      #[ingraph(handler = "crate::a")]
      a: (A, ()),
    }
  });
  assert_eq!(
    quote::ToTokens::to_token_stream(&model.krate).to_string(),
    "crate :: shim"
  );
}

/// THE FIRST REFUSAL: an exchange nobody runs.
#[test]
fn an_exchange_names_the_handler_that_runs_it() {
  let refusal = refused(quote::quote! {
    pub struct Ops {
      add: (AddWatch, AddResponse),
    }
  });
  assert!(
    refusal.contains("`add` declares no `handler`"),
    "the refusal names the field: {refusal}"
  );
  assert!(
    refusal.contains("handler = \"path::to::fn\""),
    "and offers the plain form: {refusal}"
  );
}

/// The two failure shapes are ONE word, so a field claiming both is refused.
#[test]
fn a_failure_is_a_type_or_a_message_and_never_both() {
  let refusal = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler(path = "crate::a", error(type = "crate::E", message = "oops")))]
      a: (A, ()),
    }
  });
  assert!(
    refusal.contains("two shapes of ONE word"),
    "the refusal states the law: {refusal}"
  );

  // And the other order, because a grammar that only checked one would pass half the cases.
  let reversed = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler(path = "crate::a", error(message = "oops", type = "crate::E")))]
      a: (A, ()),
    }
  });
  assert!(reversed.contains("two shapes of ONE word"), "{reversed}");
}

/// A code is a HEADING, so a code alone heads nothing.
#[test]
fn a_code_alone_heads_nothing() {
  let refusal = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler(path = "crate::a", error(code = "NOPE")))]
      a: (A, ()),
    }
  });
  assert!(
    refusal.contains("heads nothing"),
    "the refusal names the rule: {refusal}"
  );
  assert!(
    refusal.contains("omits `error(…)`"),
    "and names the exit for a field that cannot fail: {refusal}"
  );
}

/// An empty `error()` says nothing, and the two things it could have said are both in the sentence.
#[test]
fn an_empty_error_word_declares_no_failure() {
  for written in [quote::quote!(error()), quote::quote!(error)] {
    let refusal = refused(quote::quote! {
      pub struct Ops {
        #[ingraph(handler(path = "crate::a", #written))]
        a: (A, ()),
      }
    });
    assert!(
      refusal.contains("declares no failure"),
      "`{written}` is refused: {refusal}"
    );
  }
}

/// A `rename` is a SCHEMA word, so it is written in a string and fenced by GraphQL's own grammar.
#[test]
fn a_rename_is_a_word_in_a_string() {
  let refusal = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(rename = addWatch, handler = "crate::a")]
      a: (A, ()),
    }
  });
  assert!(
    refusal.contains("in a string literal"),
    "the refusal names the shape: {refusal}"
  );

  // And a string that is not a GraphQL name is refused where the word settles, not at its shape.
  let fenced = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(rename = "add watch", handler = "crate::a")]
      a: (A, ()),
    }
  });
  assert!(fenced.contains("is not a GraphQL name"), "{fenced}");
}

/// A handler's context is the RESOURCES it was granted, and an entry that is not one is refused
/// rather than ignored.
#[test]
fn a_context_grants_resources_and_nothing_else() {
  let refusal = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler(path = "crate::a", context(crate::Catalog)))]
      a: (A, ()),
    }
  });
  assert!(
    refusal.contains("one `resource(\"…\")` line each"),
    "the refusal names the only legal line: {refusal}"
  );

  // A `resource` written bare, with no path inside it, earns the same sentence.
  let bare = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler(path = "crate::a", context(resource)))]
      a: (A, ()),
    }
  });
  assert!(bare.contains("one `resource(\"…\")` line each"), "{bare}");

  // And so does an empty block, which grants nothing at all.
  let empty = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler(path = "crate::a", context()))]
      a: (A, ()),
    }
  });
  assert!(empty.contains("grants nothing"), "{empty}");
}

/// A `handler(…)` block with no `path` names nothing that could run.
#[test]
fn a_handler_block_names_its_path() {
  let refusal = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler(async, error(message = "oops")))]
      a: (A, ()),
    }
  });
  assert!(
    refusal.contains("names no `path`"),
    "the refusal names the missing word: {refusal}"
  );

  // A path written bare earns ONE sentence in either spelling, because the quoting rule belongs to
  // the word rather than to the block it was written in.
  for written in [
    quote::quote!(handler = crate::a),
    quote::quote!(handler(path = crate::a)),
  ] {
    let bare = refused(quote::quote! {
      pub struct Ops {
        #[ingraph(#written)]
        a: (A, ()),
      }
    });
    assert!(
      bare.contains("named in a string literal"),
      "`{written}`: {bare}"
    );
    // And ONE, which is what the entry-swallow buys: no `expected ,` behind it, and no second rule
    // about the words the aborted walk never reached.
    assert_eq!(bare.lines().count(), 1, "`{written}`: {bare}");
  }
}

/// ONE RULE, ONE ERROR — a value that could not be read never earns a second sentence about the
/// word it was written under still being missing.
#[test]
fn a_bad_value_earns_one_error_and_never_its_own_echo() {
  for (written, sentence) in [
    (
      quote::quote!(handler(path = crate::a, error(type = crate::E))),
      "`error(type = \"…\")` names the error",
    ),
    (
      quote::quote!(handler(path = "crate::a", error(message = oops))),
      "`error(message = \"…\")` is the whole sentence",
    ),
    (
      quote::quote!(handler(
        path = "crate::a",
        error(message = "oops", code = NOPE)
      )),
      "`error(code = \"…\")` is the heading",
    ),
  ] {
    let refusal = refused(quote::quote! {
      pub struct Ops {
        #[ingraph(#written)]
        a: (A, ()),
      }
    });
    assert!(refusal.contains(sentence), "`{written}`: {refusal}");
    // The FIRST case writes two bad values and earns two sentences; the other two write one apiece.
    // Neither ever earns the missing-word or empty-block echo behind it.
    for echo in ["names no `path`", "declares no failure", "heads nothing"] {
      assert!(
        !refusal.contains(echo),
        "`{written}` echoed `{echo}`: {refusal}"
      );
    }
  }
}

/// A positional field has no name, and a name is what a command IS.
#[test]
fn a_mutation_node_is_a_struct_with_named_fields() {
  let positional = refused(quote::quote! {
    pub struct Ops(AddWatch, AddResponse);
  });
  assert!(positional.contains("named fields"), "{positional}");

  let variants = refused(quote::quote! {
    pub enum Ops {
      Add(AddWatch),
    }
  });
  assert!(variants.contains("structs only"), "{variants}");
}

/// A GENERIC declaration is refused: the expansion mints ONE vocabulary for ONE type.
#[test]
fn a_mutation_node_takes_no_generic_parameter() {
  let refusal = refused(quote::quote! {
    pub struct Ops<R> {
      #[ingraph(handler = "crate::a")]
      a: (R, ()),
    }
  });
  assert!(refusal.contains("no generic parameter"), "{refusal}");
}

/// An unknown entry names where the fact it was reaching for actually lives.
#[test]
fn an_unknown_entry_names_where_the_fact_belongs() {
  let head = refused(quote::quote! {
    #[ingraph(source = "crate::Watch")]
    pub struct Ops {
      #[ingraph(handler = "crate::a")]
      a: (A, ()),
    }
  });
  assert!(
    head.contains("that source's own `mutation(node = \"…\")` word"),
    "the head's refusal points at the source: {head}"
  );

  let field = refused(quote::quote! {
    pub struct Ops {
      #[ingraph(handler = "crate::a", error(message = "oops"))]
      a: (A, ()),
    }
  });
  assert!(
    field.contains("lives INSIDE the handler block"),
    "a field's refusal points into the block: {field}"
  );
}

/// One field is ONE thing an app can say, so every word on it is written once.
#[test]
fn every_word_is_written_once() {
  for (written, sentence) in [
    (
      quote::quote!(handler = "crate::a", handler = "crate::b"),
      "one field is ONE thing an app can say",
    ),
    (
      quote::quote!(rename = "a", rename = "b", handler = "crate::a"),
      "one field, one published word",
    ),
    (
      quote::quote!(handler(path = "crate::a", async, async)),
      "one handler wears one face",
    ),
    (
      quote::quote!(handler(path = "crate::a", path = "crate::b")),
      "one exchange runs one function",
    ),
    (
      quote::quote!(handler(
        path = "crate::a",
        error(message = "a", code = "A", code = "B")
      )),
      "one failure renders under one heading",
    ),
  ] {
    let refusal = refused(quote::quote! {
      pub struct Ops {
        #[ingraph(#written)]
        a: (A, ()),
      }
    });
    assert!(refusal.contains(sentence), "`{written}`: {refusal}");
  }
}