schemars_derive/attr/
schemars_to_serde.rs

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
use quote::ToTokens;
use serde_derive_internals::Ctxt;
use std::collections::HashSet;
use syn::parse::Parser;
use syn::{Attribute, Data, Field, Meta, NestedMeta, Variant};

// List of keywords that can appear in #[serde(...)]/#[schemars(...)] attributes which we want serde_derive_internals to parse for us.
pub(crate) static SERDE_KEYWORDS: &[&str] = &[
    "rename",
    "rename_all",
    "deny_unknown_fields",
    "tag",
    "content",
    "untagged",
    "default",
    "skip",
    "skip_serializing",
    "skip_serializing_if",
    "skip_deserializing",
    "flatten",
    "remote",
    "transparent",
    // Special case - `bound` is removed from serde attrs, so is only respected when present in schemars attr.
    "bound",
    // Special cases - `with`/`serialize_with` are passed to serde but not copied from schemars attrs to serde attrs.
    // This is because we want to preserve any serde attribute's `serialize_with` value to determine whether the field's
    // default value should be serialized. We also check the `with` value on schemars/serde attrs e.g. to support deriving
    // JsonSchema on remote types, but we parse that ourselves rather than using serde_derive_internals.
    "serialize_with",
    "with",
];

// If a struct/variant/field has any #[schemars] attributes, then create copies of them
// as #[serde] attributes so that serde_derive_internals will parse them for us.
pub fn process_serde_attrs(input: &mut syn::DeriveInput) -> Result<(), Vec<syn::Error>> {
    let ctxt = Ctxt::new();
    process_attrs(&ctxt, &mut input.attrs);
    match input.data {
        Data::Struct(ref mut s) => process_serde_field_attrs(&ctxt, s.fields.iter_mut()),
        Data::Enum(ref mut e) => process_serde_variant_attrs(&ctxt, e.variants.iter_mut()),
        Data::Union(ref mut u) => process_serde_field_attrs(&ctxt, u.fields.named.iter_mut()),
    };

    ctxt.check()
}

fn process_serde_variant_attrs<'a>(ctxt: &Ctxt, variants: impl Iterator<Item = &'a mut Variant>) {
    for v in variants {
        process_attrs(&ctxt, &mut v.attrs);
        process_serde_field_attrs(&ctxt, v.fields.iter_mut());
    }
}

fn process_serde_field_attrs<'a>(ctxt: &Ctxt, fields: impl Iterator<Item = &'a mut Field>) {
    for f in fields {
        process_attrs(&ctxt, &mut f.attrs);
    }
}

fn process_attrs(ctxt: &Ctxt, attrs: &mut Vec<Attribute>) {
    // Remove #[serde(...)] attributes (some may be re-added later)
    let (serde_attrs, other_attrs): (Vec<_>, Vec<_>) =
        attrs.drain(..).partition(|at| at.path.is_ident("serde"));
    *attrs = other_attrs;

    let schemars_attrs: Vec<_> = attrs
        .iter()
        .filter(|at| at.path.is_ident("schemars"))
        .collect();

    // Copy appropriate #[schemars(...)] attributes to #[serde(...)] attributes
    let (mut serde_meta, mut schemars_meta_names): (Vec<_>, HashSet<_>) = schemars_attrs
        .iter()
        .flat_map(|at| get_meta_items(&ctxt, at))
        .flatten()
        .filter_map(|meta| {
            let keyword = get_meta_ident(&ctxt, &meta).ok()?;
            if keyword.ends_with("with") || !SERDE_KEYWORDS.contains(&keyword.as_ref()) {
                None
            } else {
                Some((meta, keyword))
            }
        })
        .unzip();

    if schemars_meta_names.contains("skip") {
        schemars_meta_names.insert("skip_serializing".to_string());
        schemars_meta_names.insert("skip_deserializing".to_string());
    }

    // Re-add #[serde(...)] attributes that weren't overridden by #[schemars(...)] attributes
    for meta in serde_attrs
        .into_iter()
        .flat_map(|at| get_meta_items(&ctxt, &at))
        .flatten()
    {
        if let Ok(i) = get_meta_ident(&ctxt, &meta) {
            if !schemars_meta_names.contains(&i)
                && SERDE_KEYWORDS.contains(&i.as_ref())
                && i != "bound"
            {
                serde_meta.push(meta);
            }
        }
    }

    if !serde_meta.is_empty() {
        let new_serde_attr = quote! {
            #[serde(#(#serde_meta),*)]
        };

        let parser = Attribute::parse_outer;
        match parser.parse2(new_serde_attr) {
            Ok(ref mut parsed) => attrs.append(parsed),
            Err(e) => ctxt.error_spanned_by(to_tokens(attrs), e),
        }
    }
}

fn to_tokens(attrs: &[Attribute]) -> impl ToTokens {
    let mut tokens = proc_macro2::TokenStream::new();
    for attr in attrs {
        attr.to_tokens(&mut tokens);
    }
    tokens
}

fn get_meta_items(ctxt: &Ctxt, attr: &Attribute) -> Result<Vec<NestedMeta>, ()> {
    match attr.parse_meta() {
        Ok(Meta::List(meta)) => Ok(meta.nested.into_iter().collect()),
        Ok(_) => {
            ctxt.error_spanned_by(attr, "expected #[schemars(...)] or #[serde(...)]");
            Err(())
        }
        Err(err) => {
            ctxt.error_spanned_by(attr, err);
            Err(())
        }
    }
}

fn get_meta_ident(ctxt: &Ctxt, meta: &NestedMeta) -> Result<String, ()> {
    match meta {
        NestedMeta::Meta(m) => m.path().get_ident().map(|i| i.to_string()).ok_or(()),
        NestedMeta::Lit(lit) => {
            ctxt.error_spanned_by(
                meta,
                format!(
                    "unexpected literal in attribute: {}",
                    lit.into_token_stream()
                ),
            );
            Err(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use syn::DeriveInput;

    #[test]
    fn test_process_serde_attrs() {
        let mut input: DeriveInput = parse_quote! {
            #[serde(rename(serialize = "ser_name"), rename_all = "camelCase")]
            #[serde(default, unknown_word)]
            #[schemars(rename = "overriden", another_unknown_word)]
            #[misc]
            struct MyStruct {
                /// blah blah blah
                #[serde(skip_serializing_if = "some_fn", bound = "removed")]
                field1: i32,
                #[serde(serialize_with = "se", deserialize_with = "de")]
                #[schemars(with = "with", bound = "bound")]
                field2: i32,
                #[schemars(skip)]
                #[serde(skip_serializing)]
                field3: i32,
            }
        };
        let expected: DeriveInput = parse_quote! {
            #[schemars(rename = "overriden", another_unknown_word)]
            #[misc]
            #[serde(rename = "overriden", rename_all = "camelCase", default)]
            struct MyStruct {
                #[doc = r" blah blah blah"]
                #[serde(skip_serializing_if = "some_fn")]
                field1: i32,
                #[schemars(with = "with", bound = "bound")]
                #[serde(bound = "bound", serialize_with = "se")]
                field2: i32,
                #[schemars(skip)]
                #[serde(skip)]
                field3: i32,
            }
        };

        if let Err(e) = process_serde_attrs(&mut input) {
            panic!("process_serde_attrs returned error: {}", e[0])
        };

        assert_eq!(input, expected);
    }
}