system2-macros 0.1.0

The macros of system2.
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::collections::{HashMap, HashSet};
use syn::ext::IdentExt;
use syn::{Attribute, Data, DeriveInput, Expr, ExprLit, Fields, Ident, Lit, Meta, Variant};
use system2_shared::{choice, score};

struct Derive {
    trait_name: &'static str,
    question: &'static str,
    items: &'static str,
    an_item: &'static str,
    allows_rename: bool,
    max_variants: usize,
    count_message: fn(usize) -> String,
}

const OPTIONS: Derive = Derive {
    trait_name: "Options",
    question: "Choice",
    items: "options",
    an_item: "an option",
    allows_rename: true,
    max_variants: choice::MAX_OPTIONS,
    count_message: choice::count_message,
};

const LEVELS: Derive = Derive {
    trait_name: "Levels",
    question: "Score",
    items: "levels",
    an_item: "a level",
    allows_rename: false,
    max_variants: score::MAX_LEVELS,
    count_message: score::count_message,
};

struct Entry<'a> {
    variant: &'a Ident,
    name: String,

    // the rename, or else the variant, so that an error about the name points at it
    span: Span,
    description: Option<String>,
}

pub(crate) fn options(input: &DeriveInput) -> syn::Result<TokenStream> {
    let entries = entries(input, &OPTIONS)?;

    let mut names = HashSet::new();
    let mut table = Vec::new();

    for entry in &entries {
        let Entry {
            variant,
            name,
            span,
            description,
        } = entry;
        if !names.insert(name) {
            let message = format!(
                "{}: rename one with `#[system2(rename = \"…\")]`",
                choice::duplicate_message(name)
            );
            return Err(syn::Error::new(*span, message));
        }

        // description if its not empty
        let description = match description {
            Some(description) if !description.trim().is_empty() => {
                quote!(::core::option::Option::Some(#description))
            }
            _ => quote!(::core::option::Option::None),
        };

        table.push(quote! {
            ::system2::__private::ChoiceOption {
                name: #name,
                description: #description,
                value: || Self::#variant
            }
        });
    }

    let ident = &input.ident;
    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();

    Ok(quote! {
        impl #impl_generics ::system2::Options for #ident #type_generics #where_clause {
            const OPTIONS: &'static [::system2::__private::ChoiceOption<Self>] = &[#(#table),*];
        }
    })
}

pub(crate) fn levels(input: &DeriveInput) -> syn::Result<TokenStream> {
    let entries = entries(input, &LEVELS)?;

    // the names are the levels only when no variant has a description
    let described = entries.iter().any(|e| e.description.is_some());

    let mut texts = HashMap::new();
    let mut table = Vec::new();

    for entry in &entries {
        let Entry {
            variant,
            name,
            description,
            ..
        } = entry;
        let level = match description {
            Some(description) if description.trim().is_empty() => {
                let message = "the description of a level must not be empty";
                return Err(syn::Error::new(variant.span(), message));
            }
            Some(description) => description,
            // at least one level had a description, so they all should
            None if described => {
                let message = format!(
                    "the level `{variant}` must have a description, because other levels have one: \
                     add a doc comment or `#[system2(description = \"…\")]`"
                );
                return Err(syn::Error::new(variant.span(), message));
            }
            None => name,
        };

        // ensure level is unique
        if let Some(first) = texts.insert(level, variant) {
            let source = if described { "description" } else { "name" };
            let message = format!(
                "each level must have a different {source}, \
                 but `{variant}` has the same {source} as `{first}`"
            );
            return Err(syn::Error::new(variant.span(), message));
        }

        table.push(quote! {
            ::system2::__private::ScoreLevel { level: #level, value: || Self::#variant }
        });
    }

    let ident = &input.ident;
    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();

    Ok(quote! {
        impl #impl_generics ::system2::Levels for #ident #type_generics #where_clause {
            const LEVELS: &'static [::system2::__private::ScoreLevel<Self>] = &[#(#table),*];
        }
    })
}

// validate the entire enum
fn entries<'a>(input: &'a DeriveInput, derive: &Derive) -> syn::Result<Vec<Entry<'a>>> {
    let Derive {
        trait_name,
        question,
        max_variants,
        count_message,
        ..
    } = derive;

    // ensure we are deriving on an enum
    let Data::Enum(data) = &input.data else {
        let message = format!(
            "`#[derive({trait_name})]` needs an enum: use `{question}::with_values` for other types"
        );
        return Err(syn::Error::new(input.ident.span(), message));
    };

    // only include #[system2(...)] attr on variants, not the full enum
    if let Some(attr) = input.attrs.iter().find(|a| a.path().is_ident("system2")) {
        let message = "`#[system2]` must be on a variant, not on the enum";
        return Err(syn::Error::new_spanned(attr, message));
    }

    // ensure we have a valid # of variants
    let count = data.variants.len();
    if count == 0 || count > *max_variants {
        // the first variant over the limit, or else the enum when it has none
        let span = match data.variants.iter().nth(*max_variants) {
            Some(extra) => extra.ident.span(),
            None => input.ident.span(),
        };
        return Err(syn::Error::new(span, count_message(count)));
    }

    // validate each variant and collect into Vec
    data.variants.iter().map(|v| entry(v, derive)).collect()
}

// validate each variant of the enum
fn entry<'a>(variant: &'a Variant, derive: &Derive) -> syn::Result<Entry<'a>> {
    let Derive {
        question,
        items,
        an_item,
        allows_rename,
        ..
    } = derive;
    let ident = &variant.ident;

    // only accept unit variants
    if !matches!(variant.fields, Fields::Unit) {
        let message = format!(
            "the variant `{ident}` must have no fields: \
             use `{question}::with_values` for {items} that hold data"
        );
        return Err(syn::Error::new(ident.span(), message));
    }

    let mut rename = None;
    let mut description = None;
    for attr in variant
        .attrs
        .iter()
        .filter(|a| a.path().is_ident("system2"))
    {
        attr.parse_nested_meta(|meta| {
            // detect which slot to set
            let (key, slot) = match meta.path.get_ident() {
                Some(key) if key == "rename" && *allows_rename => (key, &mut rename),
                Some(key) if key == "description" => (key, &mut description),
                _ => {
                    let keys = if *allows_rename {
                        r#"`rename = "…"` and `description = "…"`"#
                    } else {
                        r#"`description = "…"`"#
                    };
                    let message = format!("{an_item} takes only {keys}");
                    return Err(meta.error(message));
                }
            };

            // prevent duplicate keys
            if slot.is_some() {
                return Err(meta.error(format!("`{key}` must occur one time at most")));
            }

            // only accept string values
            let value: Expr = meta.value()?.parse()?;
            let Expr::Lit(ExprLit {
                lit: Lit::Str(text),
                ..
            }) = value
            else {
                let message = format!("`{key}` must be a string literal");
                return Err(syn::Error::new_spanned(value, message));
            };

            // assign the slot
            *slot = Some(text);

            Ok(())
        })?;
    }

    // prevent `rename=""`
    if let Some(rename) = &rename
        && rename.value().trim().is_empty()
    {
        let message = "the name of an option must not be empty";
        return Err(syn::Error::new(rename.span(), message));
    }

    // use `rename` as the name, falling back to snake_case of original variant name
    let (name, span) = match rename {
        Some(rename) => (rename.value(), rename.span()),
        None => (snake_case(ident), ident.span()),
    };

    // use `description` as the description, falling back to doc comment
    let description = match description {
        Some(description) => Some(description.value()),
        None => doc_comment(&variant.attrs)?,
    };

    Ok(Entry {
        variant: ident,
        name,
        span,
        description,
    })
}

// as serde writes `rename_all = "snake_case"`, so the two derives agree
fn snake_case(ident: &Ident) -> String {
    let mut name = String::new();
    for (i, c) in ident.unraw().to_string().char_indices() {
        if i > 0 && c.is_uppercase() {
            name.push('_');
        }
        name.push(c.to_ascii_lowercase());
    }
    name
}

fn doc_comment(attrs: &[Attribute]) -> syn::Result<Option<String>> {
    let mut lines = Vec::new();
    for attr in attrs.iter().filter(|a| a.path().is_ident("doc")) {
        // only `#[doc = "…"]` holds text, not `#[doc(hidden)]` or `#[doc(alias = "…")]`
        let Meta::NameValue(meta) = &attr.meta else {
            continue;
        };
        let Expr::Lit(ExprLit {
            lit: Lit::Str(text),
            ..
        }) = &meta.value
        else {
            let message = "the doc comment must be a string literal: \
                           give the description with `#[system2(description = \"…\")]`";
            return Err(syn::Error::new_spanned(attr, message));
        };

        // not `lines()`, which gives no line for an empty `///`
        let text = text.value();
        let mut doc_lines: Vec<_> = text.split('\n').map(str::trim).collect();

        // a block comment can start each line after the first with a star, and rustdoc shows
        // none of these stars
        let has_stars = |line: &&str| line.is_empty() || line.starts_with('*');
        if doc_lines.iter().skip(1).all(has_stars) {
            for line in doc_lines.iter_mut().skip(1) {
                *line = line.strip_prefix('*').unwrap_or(line).trim_start();
            }
        }
        lines.extend(doc_lines.into_iter().map(str::to_owned));
    }

    // an empty line ends a paragraph
    let paragraphs: Vec<_> = lines
        .split(String::is_empty)
        .filter(|paragraph| !paragraph.is_empty())
        .map(|paragraph| paragraph.join(" "))
        .collect();
    if paragraphs.is_empty() {
        return Ok(None);
    }

    Ok(Some(paragraphs.join("\n\n")))
}

#[cfg(test)]
mod tests {
    use super::{doc_comment, levels, options, snake_case};
    use proc_macro2::TokenStream;
    use quote::{format_ident, quote};
    use syn::{DeriveInput, Ident, Variant, parse_quote};

    fn message(result: syn::Result<TokenStream>) -> String {
        result.unwrap_err().to_string()
    }

    fn many(count: usize) -> DeriveInput {
        let variants = (1..=count).map(|i| format_ident!("V{i}"));
        syn::parse2(quote!(enum Many { #(#variants),* })).unwrap()
    }

    #[test]
    fn snake_case_writes_names_as_serde_does() {
        let cases: [(Ident, &str); 6] = [
            (parse_quote!(Crash), "crash"),
            (parse_quote!(WrongResult), "wrong_result"),
            (parse_quote!(HTTPError), "h_t_t_p_error"),
            (parse_quote!(Level2A), "level2_a"),
            (parse_quote!(r#type), "type"),
            (parse_quote!(r#fn), "fn"),
        ];
        for (variant, name) in cases {
            assert_eq!(snake_case(&variant), name);
        }
    }

    #[test]
    fn doc_comment_joins_the_lines_as_rustdoc_shows_them() {
        let cases: [(Variant, Option<&str>); 10] = [
            (parse_quote!(Crash), None),
            (
                parse_quote! {
                    ///
                    #[doc(hidden)]
                    Crash
                },
                None,
            ),
            (
                parse_quote! {
                    #[doc(hidden)]
                    /// The code panics.
                    Crash
                },
                Some("The code panics."),
            ),
            (
                parse_quote! {
                    /// The code panics
                    /// for some input.
                    Crash
                },
                Some("The code panics for some input."),
            ),
            (
                parse_quote! {
                    /// The code panics.
                    ///
                    ///
                    /// It does not return.
                    Crash
                },
                Some("The code panics.\n\nIt does not return."),
            ),
            (
                parse_quote! {
                    /** The code panics
                    for some input. */
                    Crash
                },
                Some("The code panics for some input."),
            ),
            (
                parse_quote! {
                    /** The code panics
                     * for some input. */
                    Crash
                },
                Some("The code panics for some input."),
            ),
            (
                parse_quote! {
                    /**
                     * The code panics.
                     *
                     * It does not return.
                     */
                    Crash
                },
                Some("The code panics.\n\nIt does not return."),
            ),
            (
                parse_quote! {
                    /** The code panics for:
                     * each empty input
                    and each long input. */
                    Crash
                },
                Some("The code panics for: * each empty input and each long input."),
            ),
            (
                parse_quote! {
                    /// * The code panics.
                    Crash
                },
                Some("* The code panics."),
            ),
        ];
        for (variant, text) in cases {
            assert_eq!(doc_comment(&variant.attrs).unwrap().as_deref(), text);
        }
    }

    #[test]
    fn options_writes_a_name_and_a_description_for_each_variant() {
        let tokens = options(&parse_quote! {
            enum Problem {
                /// The code panics.
                Crash,
                Style,
            }
        });

        let table = quote! {
            impl ::system2::Options for Problem {
                const OPTIONS: &'static [::system2::__private::ChoiceOption<Self>] = &[
                    ::system2::__private::ChoiceOption {
                        name: "crash",
                        description: ::core::option::Option::Some("The code panics."),
                        value: || Self::Crash
                    },
                    ::system2::__private::ChoiceOption {
                        name: "style",
                        description: ::core::option::Option::None,
                        value: || Self::Style
                    }
                ];
            }
        };
        assert_eq!(tokens.unwrap().to_string(), table.to_string());
    }

    #[test]
    fn levels_writes_a_level_for_each_variant() {
        let tokens = levels(&parse_quote! {
            enum Severity {
                /// Nothing breaks.
                Minor,
                /// Data is lost.
                Critical,
            }
        });

        let table = quote! {
            impl ::system2::Levels for Severity {
                const LEVELS: &'static [::system2::__private::ScoreLevel<Self>] = &[
                    ::system2::__private::ScoreLevel {
                        level: "Nothing breaks.",
                        value: || Self::Minor
                    },
                    ::system2::__private::ScoreLevel {
                        level: "Data is lost.",
                        value: || Self::Critical
                    }
                ];
            }
        };
        assert_eq!(tokens.unwrap().to_string(), table.to_string());
    }

    #[test]
    fn options_refuses_a_bad_enum() {
        let cases = [
            (
                quote! { struct Problem; },
                "`#[derive(Options)]` needs an enum: use `Choice::with_values` for other types",
            ),
            (
                quote! { enum Problem { Crash(u8) } },
                "the variant `Crash` must have no fields: \
                 use `Choice::with_values` for options that hold data",
            ),
            (
                quote! { enum Problem {} },
                "a Choice must have 1 to 255 options, not 0",
            ),
            (
                quote! { #[system2(rename = "problem")] enum Problem { Crash } },
                "`#[system2]` must be on a variant, not on the enum",
            ),
            (
                quote! { enum Problem { #[system2(name = "crash")] Crash } },
                r#"an option takes only `rename = "…"` and `description = "…"`"#,
            ),
            (
                quote! {
                    enum Problem {
                        #[system2(rename = "panic")]
                        #[system2(rename = "crash")]
                        Crash
                    }
                },
                "`rename` must occur one time at most",
            ),
            (
                quote! { enum Problem { #[system2(rename)] Crash } },
                "expected `=`",
            ),
            (
                quote! { enum Problem { #[system2(rename = )] Crash } },
                "unexpected end of input, expected an expression",
            ),
            (
                quote! {
                    enum Problem {
                        #[system2(description = json!({ "what": "A panic." }))]
                        Crash
                    }
                },
                "`description` must be a string literal",
            ),
            (
                quote! { enum Problem { #[doc = include_str!("crash.md")] Crash } },
                "the doc comment must be a string literal: \
                 give the description with `#[system2(description = \"…\")]`",
            ),
            (
                quote! { enum Problem { #[system2(rename = " ")] Crash } },
                "the name of an option must not be empty",
            ),
            (
                quote! { enum Problem { HandOff, #[system2(rename = "hand_off")] Escalate } },
                "each option must have a different name, but two options have the name `hand_off`: \
                 rename one with `#[system2(rename = \"…\")]`",
            ),
        ];
        for (tokens, text) in cases {
            assert_eq!(message(options(&syn::parse2(tokens).unwrap())), text);
        }
        assert_eq!(
            message(options(&many(256))),
            "a Choice must have 1 to 255 options, not 256"
        );
    }

    #[test]
    fn options_takes_1_to_255_variants() {
        for count in [1, 255] {
            assert!(options(&many(count)).is_ok(), "{count}");
        }
    }

    #[test]
    fn levels_refuses_a_bad_enum() {
        let cases = [
            (
                quote! { struct Severity; },
                "`#[derive(Levels)]` needs an enum: use `Score::with_values` for other types",
            ),
            (
                quote! { enum Severity { Minor { count: u8 } } },
                "the variant `Minor` must have no fields: \
                 use `Score::with_values` for levels that hold data",
            ),
            (
                quote! { enum Severity {} },
                "a Score must have 1 to 10 levels, not 0",
            ),
            (
                quote! { enum Severity { #[system2(rename = "minor")] Minor } },
                r#"a level takes only `description = "…"`"#,
            ),
            (
                quote! { enum Severity { /** Nothing breaks. */ Minor, Major } },
                "the level `Major` must have a description, because other levels have one: \
                 add a doc comment or `#[system2(description = \"…\")]`",
            ),
            (
                quote! {
                    enum Severity {
                        /** Nothing breaks. */
                        #[system2(description = " ")]
                        Minor
                    }
                },
                "the description of a level must not be empty",
            ),
            (
                quote! {
                    enum Severity {
                        /** Bad. */
                        Minor,
                        #[system2(description = "Bad.")]
                        Major
                    }
                },
                "each level must have a different description, \
                 but `Major` has the same description as `Minor`",
            ),
            (
                quote! { enum Severity { AB, A_b } },
                "each level must have a different name, but `A_b` has the same name as `AB`",
            ),
        ];
        for (tokens, text) in cases {
            assert_eq!(message(levels(&syn::parse2(tokens).unwrap())), text);
        }
        assert_eq!(
            message(levels(&many(11))),
            "a Score must have 1 to 10 levels, not 11"
        );
    }

    #[test]
    fn levels_takes_1_to_10_variants() {
        for count in [1, 10] {
            assert!(levels(&many(count)).is_ok(), "{count}");
        }
    }
}