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
use darling::util::parse_expr;
use darling::{ast, FromDeriveInput, FromField, FromMeta, FromVariant};
use proc_macro2::{Ident, TokenStream};
use syn::{self, DeriveInput, Expr, ExprArray, ExprPath, Meta, MetaNameValue, Path, Type};

mod message;
mod oneof;
pub mod parse_into_map;
pub mod parse_resource_name;

#[derive(Debug, FromDeriveInput)]
#[darling(attributes(parse))]
pub struct ParseOptions {
    pub ident: Ident,
    pub data: ast::Data<ParseVariant, ParseField>,
    /// Source proto type.
    pub source: Path,
    /// Set to true to implement `From` trait for converting parsed type back into source proto type.
    #[darling(default)]
    pub write: bool,
    /// Used to create tagged unions.
    #[darling(default)]
    pub tagged_union: Option<ParseTaggedUnion>,
}

#[derive(FromMeta, Debug)]
pub struct ParseTaggedUnion {
    pub oneof: Path,
    pub field: Ident,
}

#[derive(Debug, FromField)]
#[darling(attributes(parse))]
pub struct ParseField {
    pub ident: Option<Ident>,
    pub ty: Type,
    /// Source proto field name used for error reporting.
    /// Defaults to the source field name.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub name: Option<Expr>,
    /// Source field name.
    pub source_name: Option<String>,
    /// Skip parsing field.
    #[darling(default)]
    pub skip: bool,
    /// True if the source field should unwrapped from a `Option` type.
    #[darling(default)]
    pub source_option: bool,
    /// True if the source field should be dereferenced from a `Box` type.
    #[darling(default)]
    pub source_box: bool,
    /// Parses enum value from `i32`.
    #[darling(default)]
    pub enumeration: bool,
    /// Parses oneof value.
    #[darling(default)]
    pub oneof: bool,
    /// Parses Protobuf's well-known wrapper type.
    #[darling(default)]
    pub wrapper: bool,
    /// Parse resource fields into this field.
    #[darling(default)]
    pub resource: Option<ResourceOptions>,
    /// Custom expression that returns the default value.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub default: Option<Expr>,
    /// String value will be checked against this regex.
    #[darling(with = parse_expr::preserve_str_literal, map = Some)]
    pub regex: Option<Expr>,
    /// Custom function that parses the source proto field.
    /// The function must have the signature `fn(source: Source) -> RequestResult<Target>`.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub parse_with: Option<Expr>,
    /// Custom function that writes write source proto field.
    /// The function must have the signature `fn(target: Target) -> Source`.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub write_with: Option<Expr>,
    /// Module that contains both `parse_with` and `write_with` functions.
    /// The names of the functions must be `parse` and `write` respectively.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub with: Option<Expr>,
    /// Make this field derived.
    pub derive: Option<DeriveOptions>,
}

#[derive(Debug, FromVariant)]
#[darling(attributes(parse))]
pub struct ParseVariant {
    pub ident: Ident,
    pub fields: ast::Fields<Type>,
    /// Source variant name.
    pub source_name: Option<String>,
    /// Skip parsing variant.
    #[darling(default)]
    pub skip: bool,
    /// True if the source variant should unwrapped from a `Option` type.
    #[darling(default)]
    pub source_option: bool,
    /// True if the source variant should be dereferenced from a `Box` type.
    #[darling(default)]
    pub source_box: bool,
    /// True if the source is an empty unit variant.
    #[darling(default)]
    pub source_empty: bool,
    /// Parses enum value from `i32`.
    #[darling(default)]
    pub enumeration: bool,
    /// Parses Protobuf's well-known wrapper type.
    #[darling(default)]
    pub wrapper: bool,
    /// Custom expression that returns the default value.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub default: Option<Expr>,
    /// String value will be checked against this regex.
    #[darling(with = parse_expr::preserve_str_literal, map = Some)]
    pub regex: Option<Expr>,
    /// Custom function that parses the source proto field.
    /// The function must have the signature `fn(source: Source) -> RequestResult<Target>`.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub parse_with: Option<Expr>,
    /// Custom function that writes write source proto field.
    /// The function must have the signature `fn(target: Target) -> Source`.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub write_with: Option<Expr>,
    /// Module that contains both `parse_with` and `write_with` functions.
    /// The names of the functions must be `parse` and `write` respectively.
    #[darling(with = parse_expr::parse_str_literal, map = Some)]
    pub with: Option<Expr>,
}

#[derive(Debug)]
pub struct ResourceOptions {
    pub fields: ResourceFields,
}

#[derive(Debug, Default)]
pub struct ResourceFields {
    pub name: bool,
    pub create_time: bool,
    pub update_time: bool,
    pub delete_time: bool,
    pub deleted: bool,
    pub etag: bool,
}

#[derive(Debug)]
pub struct DeriveOptions {
    /// The function must have the signature `fn(source: &Source) -> RequestResult<T>`.
    pub func: ExprPath,
    /// Optional field that will be used as the source for the function.
    /// Field name is passed in as the second argument, e.g. `fn(source: &Source, field_name: &str)`.
    pub source_field: Option<ExprPath>,
}

pub fn expand(input: DeriveInput) -> syn::Result<TokenStream> {
    let options = match ParseOptions::from_derive_input(&input) {
        Ok(v) => v,
        Err(err) => {
            return Err(err.into());
        }
    };

    match &options.data {
        ast::Data::Struct(fields) => message::expand(&options, &fields.fields),
        ast::Data::Enum(variants) => oneof::expand(&options, variants),
    }
}

impl FromMeta for DeriveOptions {
    fn from_expr(expr: &Expr) -> darling::Result<Self> {
        Ok(match expr {
            Expr::Path(path) => Self {
                func: path.clone(),
                source_field: None,
            },
            Expr::Tuple(tuple) => {
                if tuple.elems.len() != 2 {
                    return Err(darling::Error::custom("expected tuple of size 2").with_span(tuple));
                }
                let func = match &tuple.elems[0] {
                    Expr::Path(path) => path.clone(),
                    _ => {
                        return Err(darling::Error::custom("expected function path")
                            .with_span(&tuple.elems[0]));
                    }
                };
                let source_field = match &tuple.elems[1] {
                    Expr::Path(path) => Some(path.clone()),
                    _ => {
                        return Err(darling::Error::custom("expected field ident")
                            .with_span(&tuple.elems[1]));
                    }
                };
                Self { func, source_field }
            }
            _ => {
                return Err(darling::Error::custom("expected function path").with_span(expr));
            }
        })
    }
}

impl FromMeta for ResourceOptions {
    fn from_list(items: &[ast::NestedMeta]) -> darling::Result<Self> {
        let mut fields = ResourceFields::default();
        for item in items {
            match item {
                ast::NestedMeta::Meta(meta) => {
                    let ident = meta.path().get_ident().unwrap();
                    match ident.to_string().as_str() {
                        "fields" => {
                            fields = ResourceFields::from_meta(meta)?;
                        }
                        _ => {
                            return Err(
                                darling::Error::custom("unknown resource option").with_span(ident)
                            );
                        }
                    }
                }
                ast::NestedMeta::Lit(lit) => {
                    return Err(darling::Error::custom("unexpected literal").with_span(lit));
                }
            }
        }
        Ok(Self { fields })
    }

    fn from_word() -> darling::Result<Self> {
        Ok(Self {
            fields: ResourceFields {
                name: true,
                create_time: true,
                update_time: true,
                delete_time: true,
                deleted: true,
                etag: true,
            },
        })
    }
}

impl FromMeta for ResourceFields {
    fn from_meta(item: &Meta) -> darling::Result<Self> {
        let mut fields = ResourceFields::default();
        if let Meta::NameValue(MetaNameValue {
            value: Expr::Array(ExprArray { elems, .. }),
            ..
        }) = item
        {
            for e in elems {
                let ident = Ident::from_expr(e)?.to_string();
                match ident.as_str() {
                    "name" => fields.name = true,
                    "create_time" => fields.create_time = true,
                    "update_time" => fields.update_time = true,
                    "delete_time" => fields.delete_time = true,
                    "deleted" => fields.deleted = true,
                    "etag" => fields.etag = true,
                    _ => {
                        return Err(
                            darling::Error::custom("unknown resource field").with_span(item)
                        );
                    }
                }
            }
        } else {
            return Err(darling::Error::custom("expected array of idents").with_span(item));
        }
        Ok(fields)
    }
}