tilo-resource-macros 0.5.2

Procedural macros for tilo-resource.
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
668
//! `#[derive(JsonSchema)]`: the schema of a type's serde JSON form, read
//! from the type's definition and the serde attributes that shape it.

use proc_macro2::TokenStream as Tokens;
use quote::quote;
use syn::spanned::Spanned;
use syn::{Attribute, Data, DeriveInput, Fields, Ident, Token};

use crate::krate;

/// How an enum's variants are told apart in JSON.
enum Tagging {
    External,
    Internal(String),
    Adjacent(String, String),
}

#[derive(Default)]
struct ContainerOptions {
    rename_all: Option<String>,
    tag: Option<String>,
    content: Option<String>,
    transparent: bool,
    default: bool,
}

#[derive(Default)]
struct ItemOptions {
    rename: Option<String>,
    rename_all: Option<String>,
    default: bool,
    skip: bool,
}

/// Consume the value of a serde option this derive has no use for, so the
/// rest of the attribute still parses.
fn ignore(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<()> {
    if meta.input.peek(Token![=]) {
        let _: syn::Expr = meta.value()?.parse()?;
    } else if meta.input.peek(syn::token::Paren) {
        let _: proc_macro2::Group = meta.input.parse()?;
    }
    Ok(())
}

fn unsupported(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Error {
    let name = meta
        .path
        .get_ident()
        .map_or_else(|| "this option".to_owned(), |ident| format!("`{ident}`"));
    meta.error(format!(
        "JsonSchema cannot describe serde's {name}; the schema would not match what serde reads"
    ))
}

fn string_value(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<String> {
    if meta.input.peek(syn::token::Paren) {
        return Err(meta
            .error("JsonSchema needs one spelling for reading and writing; use `name = \"...\"`"));
    }
    Ok(meta.value()?.parse::<syn::LitStr>()?.value())
}

fn serde_attrs(
    attrs: &[Attribute],
    mut each: impl FnMut(&syn::meta::ParseNestedMeta<'_>) -> syn::Result<()>,
) -> syn::Result<()> {
    for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) {
        attr.parse_nested_meta(|meta| each(&meta))?;
    }
    Ok(())
}

fn container_options(attrs: &[Attribute]) -> syn::Result<ContainerOptions> {
    let mut options = ContainerOptions::default();
    serde_attrs(attrs, |meta| {
        let path = &meta.path;
        if path.is_ident("rename_all") {
            options.rename_all = Some(string_value(meta)?);
        } else if path.is_ident("tag") {
            options.tag = Some(string_value(meta)?);
        } else if path.is_ident("content") {
            options.content = Some(string_value(meta)?);
        } else if path.is_ident("transparent") {
            options.transparent = true;
        } else if path.is_ident("default") {
            options.default = true;
            ignore(meta)?;
        } else if path.is_ident("remote") && string_value(meta)? == "Self" {
            // The type's own derived code under another name: what serde
            // reads is still the type as written.
        } else if [
            "untagged",
            "from",
            "try_from",
            "into",
            "remote",
            "rename_all_fields",
            "variant_identifier",
            "field_identifier",
        ]
        .iter()
        .any(|name| path.is_ident(name))
        {
            return Err(unsupported(meta));
        } else {
            ignore(meta)?;
        }
        Ok(())
    })?;
    Ok(options)
}

fn item_options(attrs: &[Attribute], variant: bool) -> syn::Result<ItemOptions> {
    let mut options = ItemOptions::default();
    serde_attrs(attrs, |meta| {
        let path = &meta.path;
        if path.is_ident("rename") {
            options.rename = Some(string_value(meta)?);
        } else if variant && path.is_ident("rename_all") {
            options.rename_all = Some(string_value(meta)?);
        } else if path.is_ident("default") {
            options.default = true;
            ignore(meta)?;
        } else if path.is_ident("skip")
            || (variant
                && (path.is_ident("skip_deserializing") || path.is_ident("skip_serializing")))
        {
            options.skip = true;
        } else if [
            "flatten",
            "with",
            "serialize_with",
            "deserialize_with",
            "skip_deserializing",
            "other",
            "untagged",
        ]
        .iter()
        .any(|name| path.is_ident(name))
        {
            return Err(unsupported(meta));
        } else {
            ignore(meta)?;
        }
        Ok(())
    })?;
    Ok(options)
}

/// A field's `#[schema(range(min = …, max = …))]`: the bounds narrowing its
/// type's, either side optional.
#[derive(Default)]
struct Range {
    min: Option<syn::Expr>,
    max: Option<syn::Expr>,
}

fn field_range(attrs: &[Attribute]) -> syn::Result<Option<Range>> {
    let mut found = None;
    for attr in attrs.iter().filter(|attr| attr.path().is_ident("schema")) {
        attr.parse_nested_meta(|meta| {
            if !meta.path.is_ident("range") {
                return Err(meta.error("JsonSchema knows `#[schema(range(min = …, max = …))]`"));
            }
            let mut range = Range::default();
            meta.parse_nested_meta(|bound| {
                let value: syn::Expr = bound.value()?.parse()?;
                if bound.path.is_ident("min") {
                    range.min = Some(value);
                } else if bound.path.is_ident("max") {
                    range.max = Some(value);
                } else {
                    return Err(bound.error("a range has `min` and `max`"));
                }
                Ok(())
            })?;
            if range.min.is_none() && range.max.is_none() {
                return Err(meta.error("a range needs `min`, `max` or both"));
            }
            found = Some(range);
            Ok(())
        })?;
    }
    Ok(found)
}

/// Split an identifier into its lowercase words: `SpliceText` and
/// `splice_text` both become `["splice", "text"]`.
fn words(name: &str) -> Vec<String> {
    let mut words = Vec::new();
    let mut current = String::new();
    for c in name.chars() {
        if c == '_' {
            if !current.is_empty() {
                words.push(std::mem::take(&mut current));
            }
        } else if c.is_uppercase() {
            if !current.is_empty() {
                words.push(std::mem::take(&mut current));
            }
            current.extend(c.to_lowercase());
        } else {
            current.push(c);
        }
    }
    if !current.is_empty() {
        words.push(current);
    }
    words
}

fn capitalized(word: &str) -> String {
    let mut chars = word.chars();
    chars.next().map_or_else(String::new, |first| {
        first.to_uppercase().chain(chars).collect()
    })
}

/// Serde's `rename_all` rules, applied to a variant (`PascalCase`) or a field
/// (`snake_case`) name.
fn rename(name: &str, rule: &str, span: proc_macro2::Span) -> syn::Result<String> {
    let parts = words(name);
    Ok(match rule {
        "lowercase" => name.to_lowercase(),
        "UPPERCASE" => name.to_uppercase(),
        "PascalCase" => parts.iter().map(|word| capitalized(word)).collect(),
        "camelCase" => parts
            .iter()
            .enumerate()
            .map(|(index, word)| {
                if index == 0 {
                    word.clone()
                } else {
                    capitalized(word)
                }
            })
            .collect(),
        "snake_case" => parts.join("_"),
        "SCREAMING_SNAKE_CASE" => parts.join("_").to_uppercase(),
        "kebab-case" => parts.join("-"),
        "SCREAMING-KEBAB-CASE" => parts.join("-").to_uppercase(),
        other => {
            return Err(syn::Error::new(
                span,
                format!("unknown serde rename rule `{other}`"),
            ));
        }
    })
}

/// The JSON name of a field or variant.
fn json_name(ident: &Ident, options: &ItemOptions, rule: Option<&String>) -> syn::Result<String> {
    if let Some(name) = &options.rename {
        return Ok(name.clone());
    }
    let name = ident.to_string();
    let name = name.strip_prefix("r#").unwrap_or(&name).to_owned();
    // Serde renames a variant from its `PascalCase` spelling and a field from
    // its `snake_case` one; `words` splits both, and the rules agree on
    // what each spelling becomes.
    match rule {
        Some(rule) => rename(&name, rule, ident.span()),
        None => Ok(name),
    }
}

/// Serde's `#[serde(rename = "…")]` and `#[serde(rename_all = "…")]`, read
/// by [`Model`](crate::Model) too: a value's JSON form is the one serde
/// reads and writes, whatever key the document stores it under.
#[derive(Default)]
pub(crate) struct WireOptions {
    pub(crate) rename: Option<String>,
    pub(crate) rename_all: Option<String>,
}

/// The serde names `attrs` give a field or a variant.
///
/// Options this derive has no use for are read past; a `rename` that names
/// a different spelling for reading and writing is left alone, since one
/// name is what a surface can publish.
pub(crate) fn wire_options(attrs: &[Attribute]) -> syn::Result<WireOptions> {
    let mut options = WireOptions::default();
    for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) {
        attr.parse_nested_meta(|meta| {
            let path = &meta.path;
            let value = if meta.input.peek(Token![=]) {
                Some(meta.value()?.parse::<syn::LitStr>()?.value())
            } else {
                None
            };
            if path.is_ident("rename") {
                options.rename = value;
            } else if path.is_ident("rename_all") {
                options.rename_all = value;
            } else if meta.input.peek(Token![=]) {
                let _: syn::Expr = meta.value()?.parse()?;
            } else if meta.input.peek(syn::token::Paren) {
                let _: proc_macro2::Group = meta.input.parse()?;
            }
            Ok(())
        })?;
    }
    Ok(options)
}

/// The name `ident` has in serde's JSON form: its `#[serde(rename)]`, else
/// its spelling under `rule` (a container's `#[serde(rename_all)]`).
pub(crate) fn wire_name(
    ident: &Ident,
    attrs: &[Attribute],
    rule: Option<&String>,
) -> syn::Result<String> {
    let options = wire_options(attrs)?;
    let item = ItemOptions {
        rename: options.rename,
        rename_all: None,
        default: false,
        skip: false,
    };
    json_name(ident, &item, rule)
}

/// The `#[serde(rename_all)]` a container declares.
pub(crate) fn wire_rule(attrs: &[Attribute]) -> syn::Result<Option<String>> {
    Ok(wire_options(attrs)?.rename_all)
}

/// Doc comments as one plain line: rustdoc links keep their text.
fn plain_doc(attrs: &[Attribute]) -> String {
    let joined = crate::doc_lines(attrs)
        .into_iter()
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join(" ");
    let mut out = String::with_capacity(joined.len());
    let mut chars = joined.chars().peekable();
    // Brackets inside code (`[at, at+del)`) are text, not links.
    let mut in_code = false;
    while let Some(c) = chars.next() {
        match c {
            '`' => {
                in_code = !in_code;
                out.push(c);
            }
            '[' if !in_code => {}
            ']' if !in_code => {
                // `[text](target)`: drop the target.
                if chars.peek() == Some(&'(') {
                    let mut depth = 0_usize;
                    for next in chars.by_ref() {
                        match next {
                            '(' => depth = depth.saturating_add(1),
                            ')' => {
                                depth = depth.saturating_sub(1);
                                if depth == 0 {
                                    break;
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
            c => out.push(c),
        }
    }
    out
}

/// The table of a set of fields (a `schema::Content`): an object for named
/// fields, the inner schema for a newtype, a fixed-length array for a tuple,
/// `None` for a unit.
fn fields_schema(
    fields: &Fields,
    rule: Option<&String>,
    all_default: bool,
) -> syn::Result<Option<Tokens>> {
    let krate = krate();
    Ok(match fields {
        Fields::Named(named) => {
            let mut properties = Vec::new();
            for field in &named.named {
                let options = item_options(&field.attrs, false)?;
                if options.skip {
                    continue;
                }
                let Some(ident) = &field.ident else { continue };
                let name = json_name(ident, &options, rule)?;
                let ty = &field.ty;
                let doc = plain_doc(&field.attrs);
                let defaulted = options.default || all_default;
                let range = if let Some(Range { min, max }) = field_range(&field.attrs)? {
                    let bound = |value: Option<syn::Expr>| {
                        value.map_or_else(
                            || quote!(::core::option::Option::None),
                            |value| {
                                quote!(::core::option::Option::Some(
                                    #krate::__private::serde_json::json!(#value)
                                ))
                            },
                        )
                    };
                    let (min, max) = (bound(min), bound(max));
                    quote!(::core::option::Option::Some({
                        fn bounds() -> (
                            ::core::option::Option<#krate::__private::serde_json::Value>,
                            ::core::option::Option<#krate::__private::serde_json::Value>,
                        ) {
                            (#min, #max)
                        }
                        bounds as fn() -> _
                    }))
                } else {
                    quote!(::core::option::Option::None)
                };
                properties.push(quote! {
                    #krate::schema::Field {
                        name: #name,
                        schema: <#ty as #krate::JsonSchema>::json_schema,
                        required: !#defaulted && !<#ty as #krate::JsonSchema>::OPTIONAL,
                        doc: #doc,
                        range: #range,
                    }
                });
            }
            Some(quote!(#krate::schema::Content::Object(&[#(#properties),*])))
        }
        Fields::Unnamed(unnamed) => {
            let kept: Vec<_> = unnamed
                .unnamed
                .iter()
                .map(|field| Ok((field, item_options(&field.attrs, false)?)))
                .collect::<syn::Result<Vec<_>>>()?
                .into_iter()
                .filter(|(_, options)| !options.skip)
                .collect();
            match kept.as_slice() {
                [(field, _)] if unnamed.unnamed.len() == 1 => {
                    let ty = &field.ty;
                    Some(quote!(#krate::schema::Content::Newtype(
                        <#ty as #krate::JsonSchema>::json_schema
                    )))
                }
                many => {
                    let len = many.len();
                    Some(quote!(#krate::schema::Content::Tuple(#len)))
                }
            }
        }
        Fields::Unit => None,
    })
}

/// One alternative per variant, tagged as serde tags it (a `schema::Body`).
/// An enum of plain unit variants is a string enumeration.
fn enum_schema(
    input: &DeriveInput,
    data: &syn::DataEnum,
    options: &ContainerOptions,
) -> syn::Result<Tokens> {
    let krate = krate();
    let tagging = match (&options.tag, &options.content) {
        (None, None) => Tagging::External,
        (Some(tag), None) => Tagging::Internal(tag.clone()),
        (Some(tag), Some(content)) => Tagging::Adjacent(tag.clone(), content.clone()),
        (None, Some(_)) => {
            return Err(syn::Error::new(
                input.span(),
                "serde `content` needs a `tag`",
            ));
        }
    };
    let mut variants = Vec::new();
    let mut plain = matches!(tagging, Tagging::External);
    for variant in &data.variants {
        let variant_options = item_options(&variant.attrs, true)?;
        if variant_options.skip {
            continue;
        }
        let name = json_name(
            &variant.ident,
            &variant_options,
            options.rename_all.as_ref(),
        )?;
        let variant_doc = plain_doc(&variant.attrs);
        plain &= matches!(variant.fields, Fields::Unit) && variant_doc.is_empty();
        let tuple = matches!(&variant.fields, Fields::Unnamed(fields) if fields.unnamed.len() != 1);
        if tuple && matches!(tagging, Tagging::Internal(_)) {
            return Err(syn::Error::new(
                variant.span(),
                "serde cannot tag a tuple variant internally",
            ));
        }
        let content = fields_schema(&variant.fields, variant_options.rename_all.as_ref(), false)?
            .map_or_else(
                || quote!(::core::option::Option::None),
                |content| quote!(::core::option::Option::Some(#content)),
            );
        variants.push(quote!(#krate::schema::Variant {
            name: #name,
            doc: #variant_doc,
            content: #content,
        }));
    }
    let tagging = match tagging {
        Tagging::External => quote!(#krate::schema::Tagging::External),
        Tagging::Internal(tag) => quote!(#krate::schema::Tagging::Internal(#tag)),
        Tagging::Adjacent(tag, key) => quote!(#krate::schema::Tagging::Adjacent(#tag, #key)),
    };
    Ok(quote!(#krate::schema::Body::Enum {
        tagging: #tagging,
        plain: #plain,
        variants: &[#(#variants),*],
    }))
}

/// The fields of a struct or variant as `(json name, field type fn)`
/// pairs: the fields serde writes, a tuple's by position.
fn typed_fields(fields: &Fields, rule: Option<&String>) -> syn::Result<Vec<Tokens>> {
    let krate = krate();
    let mut out = Vec::new();
    for (index, field) in fields.iter().enumerate() {
        let options = item_options(&field.attrs, false)?;
        if options.skip {
            continue;
        }
        let name = match &field.ident {
            Some(ident) => json_name(ident, &options, rule)?,
            None => index.to_string(),
        };
        let ty = &field.ty;
        out.push(quote!((
            #name,
            <#ty as #krate::JsonSchema>::field_type
                as fn(&mut #krate::TypeSet) -> #krate::FieldType,
        )));
    }
    Ok(out)
}

/// The body of the derived `JsonSchema::field_type`: a struct with named
/// fields is a record, a newtype or transparent struct is its field's type,
/// an enum is an enum with its cases' fields, anything else no type.
fn field_type_body(input: &DeriveInput, options: &ContainerOptions) -> syn::Result<Tokens> {
    let krate = krate();
    let name = input.ident.to_string();
    let doc = crate::first_doc_line(&input.attrs);
    let rule = options.rename_all.as_ref();
    Ok(match &input.data {
        Data::Struct(data) => {
            let kept: Vec<&syn::Field> = data
                .fields
                .iter()
                .filter(|field| !item_options(&field.attrs, false).is_ok_and(|o| o.skip))
                .collect();
            match (&data.fields, kept.as_slice()) {
                (Fields::Named(_), _) if !options.transparent => {
                    let fields = typed_fields(&data.fields, rule)?;
                    quote!(#krate::surface::resource_of(
                        types,
                        ::core::any::type_name::<Self>(),
                        #name,
                        #doc,
                        &[#(#fields),*],
                    ))
                }
                (_, [field]) if options.transparent || data.fields.len() == 1 => {
                    let ty = &field.ty;
                    quote!(<#ty as #krate::JsonSchema>::field_type(types))
                }
                _ => quote!({
                    let _ = types;
                    #krate::FieldType::Any
                }),
            }
        }
        Data::Enum(data) => {
            let mut cases = Vec::new();
            for variant in &data.variants {
                let variant_options = item_options(&variant.attrs, true)?;
                if variant_options.skip {
                    continue;
                }
                let case = json_name(&variant.ident, &variant_options, rule)?;
                let fields = typed_fields(&variant.fields, variant_options.rename_all.as_ref())?;
                cases.push(quote!((#case, "", &[#(#fields),*])));
            }
            let declared = quote!(#krate::surface::enum_type(
                types,
                ::core::any::type_name::<Self>(),
                #name,
                #doc,
                &[#(#cases),*],
            ));
            // An internally tagged enum writes its case's name under its tag, beside its fields.
            match (&options.tag, &options.content) {
                (Some(tag), None) => quote!({
                    let ty = #declared;
                    types.tag(&ty, #tag);
                    ty
                }),
                _ => declared,
            }
        }
        Data::Union(_) => quote!({
            let _ = types;
            #krate::FieldType::Any
        }),
    })
}

pub fn derive(input: &DeriveInput) -> syn::Result<Tokens> {
    let krate = krate();
    let options = container_options(&input.attrs)?;
    let field_type = field_type_body(input, &options)?;
    let doc = plain_doc(&input.attrs);
    let body = match &input.data {
        Data::Struct(data) => {
            if options.transparent {
                let field = data
                    .fields
                    .iter()
                    .find(|field| !item_options(&field.attrs, false).is_ok_and(|o| o.skip))
                    .ok_or_else(|| {
                        syn::Error::new(input.span(), "a transparent type needs a field")
                    })?;
                let ty = &field.ty;
                quote!(#krate::schema::Body::Transparent(
                    <#ty as #krate::JsonSchema>::json_schema
                ))
            } else {
                fields_schema(&data.fields, options.rename_all.as_ref(), options.default)?
                    .map_or_else(
                        || quote!(#krate::schema::Body::Unit),
                        |content| quote!(#krate::schema::Body::Struct(#content)),
                    )
            }
        }
        Data::Enum(data) => enum_schema(input, data, &options)?,
        Data::Union(_) => {
            return Err(syn::Error::new(
                input.span(),
                "JsonSchema describes structs and enums",
            ));
        }
    };

    let ident = &input.ident;
    let mut generics = input.generics.clone();
    for param in generics.type_params_mut() {
        param.bounds.push(syn::parse_quote!(#krate::JsonSchema));
    }
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    Ok(quote! {
        impl #impl_generics #krate::JsonSchema for #ident #ty_generics #where_clause {
            fn json_schema() -> #krate::__private::serde_json::Value {
                #krate::schema::build(const {
                    &#krate::schema::TypeSchema { doc: #doc, body: #body }
                })
            }

            fn field_type(types: &mut #krate::TypeSet) -> #krate::FieldType {
                #field_type
            }
        }
    })
}