ddd-toolkit-macro 0.5.4

Derive macros for ddd-toolkit-core's ValueObject, Entity, DomainEvent, and AggregateRoot traits.
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
//! **English:**<br>
//! Tests expansion branches directly, including diagnostics that do not
//! run inside the coverage-instrumented process when invoked through trybuild.
//!
//! **日本語:**<br>
//! trybuild 経由ではカバレッジ計測プロセス内で実行されない診断も含め、
//! マクロ展開の分岐を直接検証します。

use crate::{aggregate_root, entity, value_object};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{DeriveInput, Result};

type Expander = fn(DeriveInput) -> Result<TokenStream>;

fn rejects(expand: Expander, cases: &[(&str, &str)]) {
    for (source, expected) in cases {
        let input = syn::parse_str(source).unwrap();
        let error = expand(input).unwrap_err().to_string();
        assert!(error.contains(expected), "{source}: {error}");
    }
}

#[test]
fn value_object_expands_all_shapes_with_validation_and_serde() {
    let shapes = [
        quote!(
            struct Value<T>(T);
        ),
        quote!(
            struct Value<T> {
                value: T,
            }
        ),
        quote!(
            struct Value<T>(T, u32);
        ),
        quote!(
            struct Value<T> {
                value: T,
                count: u32,
            }
        ),
        quote!(
            enum Value<T> {
                Unit,
                Newtype(T),
                Tuple(T, u32),
                Named { value: T },
            }
        ),
    ];
    for shape in shapes {
        for validated in [false, true] {
            for serde in [false, true] {
                let attributes = match (validated, serde) {
                    (false, false) => quote!(),
                    (true, false) => quote!(#[value_object(validate = check, error = Error)]),
                    (false, true) => quote!(#[value_object(serde)]),
                    (true, true) => quote!(#[value_object(validate = check, error = Error, serde)]),
                };
                let input = syn::parse2(quote!(#attributes #shape)).unwrap();
                let output = value_object::expand(input).unwrap().to_string();
                for implementation in [
                    "ValueObject for Value",
                    "Debug for Value",
                    "Clone for Value",
                    "Hash for Value",
                    "as_inner",
                    "into_inner",
                ] {
                    // Generic bounds sit between `impl` and the trait name.
                    assert!(
                        output.contains(implementation),
                        "{implementation}: {output}"
                    );
                }
                assert_eq!(output.contains("try_new"), validated);
                assert_eq!(output.contains("Serialize for Value"), serde);
                assert_eq!(output.contains("Deserialize <"), serde);
                if validated {
                    assert!(output.contains("check (&"));
                    if serde {
                        assert!(output.contains("value object validation failed"));
                    }
                }
            }
        }
    }
}

#[test]
fn trait_only_generates_exactly_one_trait_impl() {
    for (expand, source, expected_inner) in [
        (
            value_object::expand as Expander,
            "#[value_object(trait_only)] struct V<T>(T);",
            Some("T"),
        ),
        (
            value_object::expand,
            "#[value_object(trait_only)] struct V<T> { value: T }",
            Some("T"),
        ),
        (
            value_object::expand,
            "#[value_object(trait_only)] struct V<T>(T, u32);",
            Some("Self"),
        ),
        (
            value_object::expand,
            "#[value_object(trait_only)] struct V<T> { value: T, count: u32 }",
            Some("Self"),
        ),
        (
            value_object::expand,
            "#[value_object(trait_only)] enum V<T> { AB, Ab, Value(T) }",
            Some("Self"),
        ),
        (
            entity::expand,
            "#[entity(trait_only)] struct V<T> where T: Eq { #[entity(id)] key: T, state: u32 }",
            None,
        ),
    ] {
        let output = expand(syn::parse_str(source).unwrap()).unwrap();
        // Count top-level impl tokens without enabling syn's full AST feature.
        let impl_count = output
            .clone()
            .into_iter()
            .filter(
                |token| matches!(token, proc_macro2::TokenTree::Ident(ident) if ident == "impl"),
            )
            .count();
        assert_eq!(impl_count, 1, "{source}");
        let output = output.to_string();
        assert!(output.contains("for V"));
        if let Some(inner) = expected_inner {
            assert!(output.contains(&format!("type Inner = {inner}")));
        } else {
            assert!(output.contains("type Id = T"));
            assert!(output.contains("where T : Eq"));
        }
    }
}

#[test]
fn trait_only_rejects_invalid_options_and_shapes() {
    rejects(
        value_object::expand,
        &[
            (
                "#[value_object(trait_only, trait_only)] struct V(u32);",
                "duplicate trait_only",
            ),
            (
                "#[value_object(trait_only = true)] struct V(u32);",
                "trait_only is a flag",
            ),
            (
                "#[value_object(trait_only, validate = check, error = Error)] struct V(u32);",
                "cannot be combined",
            ),
            (
                "#[value_object(validate = check, error = Error, trait_only)] struct V(u32);",
                "cannot be combined",
            ),
            (
                "#[value_object(trait_only, serde)] struct V(u32);",
                "cannot be combined",
            ),
            (
                "#[value_object(trait_only, error = Error)] struct V(u32);",
                "cannot be combined",
            ),
            (
                "#[value_object(trait_only)] struct V;",
                "at least one field",
            ),
            (
                "#[value_object(trait_only)] enum V {}",
                "at least one variant",
            ),
            (
                "#[value_object(trait_only)] union V { a: u32 }",
                "struct or enum",
            ),
        ],
    );
    rejects(
        entity::expand,
        &[
            (
                "#[entity(trait_only, trait_only)] struct V { #[entity(id)] id: u32 }",
                "duplicate trait_only",
            ),
            (
                "#[entity(trait_only)] #[entity(trait_only)] struct V { #[entity(id)] id: u32 }",
                "duplicate trait_only",
            ),
            (
                "#[entity(trait_only = true)] struct V { #[entity(id)] id: u32 }",
                "trait_only is a flag",
            ),
            (
                "#[entity()] struct V { #[entity(id)] id: u32 }",
                "requires at least one option",
            ),
            ("#[entity(trait_only)] struct V { id: u32 }", "exactly one"),
            (
                "#[entity(trait_only)] struct V { #[entity(id)] a: u32, #[entity(id)] b: u32 }",
                "exactly one",
            ),
            ("#[entity(trait_only)] struct V(u32);", "named-field struct"),
            (
                "struct V { #[entity(trait_only)] id: u32 }",
                "unknown entity attribute",
            ),
        ],
    );
}

#[test]
fn serde_avoids_existing_deserialization_lifetimes() {
    let input = syn::parse2(quote! {
        #[value_object(serde)]
        struct Borrowed<'__ddd_de, '__ddd_dex, T>(&'__ddd_de T, &'__ddd_dex T);
    })
    .unwrap();
    let output = value_object::expand(input).unwrap().to_string();
    assert!(output.contains("'__ddd_dexx"));
    assert!(output.contains("'__ddd_de"));
}

#[test]
fn value_object_reports_invalid_shapes_and_options() {
    rejects(
        value_object::expand,
        &[
            ("struct Empty;", "at least one field"),
            ("struct Empty {}", "at least one field"),
            ("struct Empty();", "at least one field"),
            ("enum Empty {}", "at least one variant"),
            ("union Value { a: u32 }", "struct or enum"),
            ("enum Value { AB, Ab }", "unique after lower-casing"),
            ("#[value_object()] struct V(u32);", "at least one option"),
            (
                "#[value_object(other)] struct V(u32);",
                "unknown value_object attribute",
            ),
            (
                "#[value_object(serde = true)] struct V(u32);",
                "serde is a flag",
            ),
            (
                "#[value_object(serde)] #[value_object(serde)] struct V(u32);",
                "only once",
            ),
            (
                "#[value_object(validate = check)] struct V(u32);",
                "specified together",
            ),
            (
                "#[value_object(error = Error)] struct V(u32);",
                "specified together",
            ),
            (
                "#[value_object(validate = a, validate = b)] struct V(u32);",
                "duplicate validate",
            ),
            (
                "#[value_object(error = A, error = B)] struct V(u32);",
                "duplicate error",
            ),
            (
                "#[value_object(validate = check, error = Error)] struct V(pub u32);",
                "inner fields must not be public",
            ),
            (
                "#[value_object(validate = check, error = Error)] struct V { pub a: u32, b: u32 }",
                "fields must not be public",
            ),
        ],
    );
}

#[test]
fn entity_expansion_uses_only_marked_identity() {
    let input = syn::parse2(quote! {
        struct Item<T> { #[allow(dead_code)] payload: T, #[entity(id)] key: u64 }
    })
    .unwrap();
    let output = entity::expand(input).unwrap().to_string();
    assert!(output.contains("type Id = u64"));
    assert!(output.contains("self . key == other . key"));
    assert!(output.contains("Hash :: hash (& self . key"));
    assert!(!output.contains("self . payload"));
}

#[test]
fn entity_reports_attribute_and_shape_errors() {
    rejects(
        entity::expand,
        &[
            (
                "#[entity(id)] struct V { id: u64 }",
                "placed on a named field",
            ),
            ("struct V(u64);", "requires a named-field struct"),
            ("enum V { A }", "only be derived for a named-field struct"),
            ("struct V { id: u64 }", "exactly one"),
            (
                "struct V { #[entity(id)] a: u64, #[entity(id)] b: u64 }",
                "exactly one",
            ),
            ("struct V { #[entity()] a: u64 }", "requires the id flag"),
            (
                "struct V { #[entity(other)] a: u64 }",
                "unknown entity attribute",
            ),
            ("struct V { #[entity(id = true)] a: u64 }", "id is a flag"),
            (
                "struct V { #[entity(id)] #[entity(id)] a: u64 }",
                "duplicate id",
            ),
        ],
    );
}

#[test]
fn entity_validation_options_reject_unsafe_or_ambiguous_combinations() {
    rejects(
        entity::expand,
        &[
            (
                "#[entity(validate = check)] struct V { #[entity(id)] id: u64 }",
                "specified together",
            ),
            (
                "#[entity(error = Error)] struct V { #[entity(id)] id: u64 }",
                "specified together",
            ),
            (
                "#[entity(validate = a, validate = b)] struct V { #[entity(id)] id: u64 }",
                "duplicate validate",
            ),
            (
                "#[entity(error = A, error = B)] struct V { #[entity(id)] id: u64 }",
                "duplicate error",
            ),
            (
                "#[entity(serde)] #[entity(serde)] struct V { #[entity(id)] id: u64 }",
                "duplicate serde",
            ),
            (
                "#[entity(serde = true)] struct V { #[entity(id)] id: u64 }",
                "serde is a flag",
            ),
            (
                "#[entity(trait_only, serde)] struct V { #[entity(id)] id: u64 }",
                "cannot be combined",
            ),
            (
                "#[entity(trait_only, validate = check, error = Error)] struct V { #[entity(id)] id: u64 }",
                "cannot be combined",
            ),
            (
                "#[entity(validate = check, error = Error)] struct V { #[entity(id)] pub id: u64 }",
                "must not be public",
            ),
            (
                "#[entity(validate = check, error = Error)] struct V { #[entity(id)] id: u64, pub data: u32 }",
                "must not be public",
            ),
        ],
    );
}

#[test]
fn entity_options_expand_independently_and_in_any_order() {
    for options in [
        quote!(validate = check, error = Error),
        quote!(serde),
        quote!(serde, validate = check, error = Error),
    ] {
        let input = syn::parse2(quote! {
            #[entity(#options)]
            struct Item<T> { #[entity(id)] key: u64, payload: T }
        })
        .unwrap();
        let output = entity::expand(input).unwrap().to_string();
        let options = options.to_string();
        assert_eq!(output.contains("try_new"), options.contains("validate"));
        assert_eq!(
            output.contains("Serialize for Item"),
            options.contains("serde")
        );
    }
}

#[test]
fn aggregate_expansion_preserves_event_type_and_drains_queue() {
    for queue in [quote!(Vec<Event>), quote!(::std::vec::Vec<Event>)] {
        let input = syn::parse2(quote! {
            struct Root<Event> { #[allow(dead_code)] id: u64, #[aggregate(events)] pending: #queue }
        })
        .unwrap();
        let output = aggregate_root::expand(input).unwrap().to_string();
        assert!(output.contains("type Event = Event"));
        assert!(output.contains("self . pending . push (event)"));
        assert!(output.contains("mem :: take (& mut self . pending)"));
        assert!(output.contains("Event : :: ddd_toolkit_core :: DomainEvent"));
    }
}

#[test]
fn aggregate_reports_attribute_and_queue_errors() {
    rejects(
        aggregate_root::expand,
        &[
            (
                "#[aggregate(events)] struct V { q: Vec<E> }",
                "placed on an event queue field",
            ),
            ("struct V(Vec<E>);", "requires a named-field struct"),
            ("enum V { A }", "only be derived for a named-field struct"),
            ("struct V { q: Vec<E> }", "exactly one"),
            (
                "struct V { #[aggregate(events)] a: Vec<E>, #[aggregate(events)] b: Vec<E> }",
                "exactly one",
            ),
            (
                "struct V { #[aggregate()] a: Vec<E> }",
                "requires the events flag",
            ),
            (
                "struct V { #[aggregate(other)] a: Vec<E> }",
                "only the events flag",
            ),
            (
                "struct V { #[aggregate(events = true)] a: Vec<E> }",
                "events is a flag",
            ),
        ],
    );
    for queue in [
        "&[E]",
        "fake::Vec<E>",
        "Vec",
        "std::vec::Vec",
        "other::vec::Vec<E>",
        "Vec<E, E>",
        "Vec<'a>",
        "<T as Trait>::Vec<E>",
    ] {
        let source = format!("struct V {{ #[aggregate(events)] q: {queue} }}");
        let expected = if queue == "Vec<E, E>" {
            "exactly one event type"
        } else if queue == "Vec<'a>" {
            "type event argument"
        } else {
            "must have type Vec<Event>"
        };
        rejects(aggregate_root::expand, &[(source.as_str(), expected)]);
    }
}