teleparse-macros 0.1.0

Proc-macro crate for teleparse
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
use quote::ToTokens;

use crate::*;

pub fn expand(input: &mut syn::DeriveInput) -> syn::Result<TokenStream2> {
    let root_attr = parse_root_attributes(input)?;

    let teleparse = crate_ident();

    let (extra_derive, output) = match &mut input.data {
        syn::Data::Struct(data) => (
            None,
            expand_struct(&input.vis, input.ident.clone(), data, &root_attr)?,
        ),
        syn::Data::Enum(data) => (
            Some(quote! {#[derive(#teleparse::ToSpan)]}),
            expand_enum(&input.vis, input.ident.clone(), data, &root_attr)?,
        ),
        _ => syn_error!(
            input,
            "derive_syntax can only be used with structs or enums"
        ),
    };

    let root_test = if !root_attr.root || root_attr.no_test {
        None
    } else {
        Some(root::expand_test(&input.ident))
    };

    let output = quote! {
        #extra_derive
        #input
        #output
        #root_test
    };

    Ok(output)
}

fn expand_struct(
    vis: &syn::Visibility,
    ident: syn::Ident,
    input: &mut syn::DataStruct,
    root_attr: &RootAttr,
) -> syn::Result<TokenStream2> {
    match &mut input.fields {
        syn::Fields::Unnamed(fields) => expand_struct_unnamed(vis, ident, fields, root_attr),
        syn::Fields::Named(fields) => expand_struct_named(vis, ident, fields, root_attr),
        syn::Fields::Unit => {
            syn_error!(ident, "derive_syntax does not support unit structs");
        }
    }
}

fn expand_struct_unnamed(
    vis: &syn::Visibility,
    ident: syn::Ident,
    input: &mut syn::FieldsUnnamed,
    root_attr: &RootAttr,
) -> syn::Result<TokenStream2> {
    let teleparse = crate_ident();
    let mut field_attrs = Vec::with_capacity(input.unnamed.len());
    for field in &mut input.unnamed {
        field_attrs.push(strip_take_attrs(&mut field.attrs));
    }

    let pt_ty = input.unnamed.iter().map(|f| &f.ty).collect::<Vec<_>>();
    let first_ty = match pt_ty.first() {
        Some(x) => x,
        None => syn_error!(&ident, "derive_syntax needs at least 1 field in the struct"),
    };

    let mut apply_semantic_impl = TokenStream2::new();
    for ((i, field), attrs) in
        std::iter::zip(input.unnamed.iter().enumerate(), field_attrs.into_iter())
    {
        let field_attr = parse_field_attributes(field, attrs)?;
        let idx = syn::Index::from(i);
        if let Some(semantic) = field_attr.semantic {
            apply_semantic_impl.extend(quote! {
                parser.apply_semantic(
                    &result.#idx,
                    #teleparse::token_set!(<Self::Prod as #teleparse::syntax::Production>::L{
                        #( #semantic )|*
                    })
                );
            });
        }
    }

    let last = syn::Index::from(pt_ty.len() - 1);
    let root_derive = if root_attr.root {
        Some(root::expand(&ident))
    } else {
        None
    };
    let (name, prod_struct) = derived_prod_name(&ident);
    let output = quote! {
        #[doc(hidden)]
        #[allow(non_camel_case_types)]
        #vis struct #prod_struct;
        #[automatically_derived]
        impl #teleparse::syntax::Production for #prod_struct {
            type L = <<#first_ty as #teleparse::parser::Produce>::Prod as #teleparse::syntax::Production>::L;
            #[inline]
            fn debug() -> ::std::borrow::Cow<'static, str> {
                ::std::borrow::Cow::Borrowed(#name)
            }
            fn register(meta: &mut #teleparse::syntax::MetadataBuilder<Self::L>) {
                #teleparse::register_sequence!(meta, #( <#pt_ty as #teleparse::parser::Produce>::Prod ),*);
            }
        }
        #[automatically_derived]
        impl #teleparse::ToSpan for #ident {
            fn lo(&self) -> #teleparse::Pos { self.0.lo() }
            fn hi(&self) -> #teleparse::Pos { self.#last.hi() }
        }
        #[automatically_derived]
        impl #teleparse::parser::Produce for #ident {
            type Prod = #prod_struct;
            fn produce(
                parser: &mut #teleparse::parser::Parser<'_, <Self::Prod as #teleparse::syntax::Production>::L>,
                meta: &#teleparse::syntax::Metadata<<Self::Prod as #teleparse::syntax::Production>::L>,
            ) -> #teleparse::syntax::Result<Self, <Self::Prod as #teleparse::syntax::Production>::L> {
                use #teleparse::parser::Produce;
                let mut errors = ::std::vec::Vec::new();
                let result = Self(
            #(
                #teleparse::handle_result!(errors, <#pt_ty>::produce(parser, meta))
            ),*
                );
                #apply_semantic_impl
                (result, errors).into()
            }
        }
        #root_derive
    };

    Ok(anon_const_block(output))
}

fn expand_struct_named(
    vis: &syn::Visibility,
    ident: syn::Ident,
    input: &mut syn::FieldsNamed,
    root_attr: &RootAttr,
) -> syn::Result<TokenStream2> {
    let teleparse = crate_ident();
    let mut field_attrs = Vec::with_capacity(input.named.len());
    for field in &mut input.named {
        field_attrs.push(strip_take_attrs(&mut field.attrs));
    }

    let pt_ty = input.named.iter().map(|f| &f.ty).collect::<Vec<_>>();
    let pt_ident = input.named.iter().map(|f| &f.ident).collect::<Vec<_>>();
    let first_ty = match pt_ty.first() {
        Some(x) => x,
        None => syn_error!(&ident, "derive_syntax needs at least 1 field in the struct"),
    };

    let mut apply_semantic_impl = TokenStream2::new();
    for (field, attrs) in std::iter::zip(input.named.iter(), field_attrs.into_iter()) {
        let field_ident = field.ident.as_ref().unwrap();
        let field_attr = parse_field_attributes(field, attrs)?;
        if let Some(semantic) = field_attr.semantic {
            apply_semantic_impl.extend(quote! {
                parser.apply_semantic(
                    &result.#field_ident,
                    #teleparse::token_set!(<Self::Prod as #teleparse::syntax::Production>::L{
                        #( #semantic )|*
                    })
                );
            });
        }
    }

    let first_ident = pt_ident.first().unwrap();
    let last_ident = pt_ident.last().unwrap();
    let root_derive = if root_attr.root {
        Some(root::expand(&ident))
    } else {
        None
    };

    let (name, prod_struct) = derived_prod_name(&ident);

    let output = quote! {
        #[doc(hidden)]
        #[allow(non_camel_case_types)]
        #vis struct #prod_struct;
        #[automatically_derived]
        impl #teleparse::syntax::Production for #prod_struct {
            type L = <<#first_ty as #teleparse::parser::Produce>::Prod as #teleparse::syntax::Production>::L;
            #[inline]
            fn debug() -> ::std::borrow::Cow<'static, str> {
                ::std::borrow::Cow::Borrowed(#name)
            }
            fn register(meta: &mut #teleparse::syntax::MetadataBuilder<Self::L>) {
                #teleparse::register_sequence!(meta, #( <#pt_ty as #teleparse::parser::Produce>::Prod ),*);
            }
        }

        #[automatically_derived]
        impl #teleparse::ToSpan for #ident {
            fn lo(&self) -> #teleparse::Pos { self.#first_ident.lo() }
            fn hi(&self) -> #teleparse::Pos { self.#last_ident.hi() }
        }
        #[automatically_derived]
        impl #teleparse::parser::Produce for #ident {
            type Prod = #prod_struct;
            fn produce(
                parser: &mut #teleparse::parser::Parser<'_, <Self::Prod as #teleparse::syntax::Production>::L>,
                meta: &#teleparse::syntax::Metadata<<Self::Prod as #teleparse::syntax::Production>::L>,
            ) -> #teleparse::syntax::Result<Self, <Self::Prod as #teleparse::syntax::Production>::L> {
                use #teleparse::parser::Produce;
                let mut errors = ::std::vec::Vec::new();
                let result = Self {
            #(
                #pt_ident: #teleparse::handle_result!(errors, <#pt_ty>::produce(parser, meta))
            ),*
                };
                #apply_semantic_impl
                (result, errors).into()
            }
        }
        #root_derive
    };
    Ok(anon_const_block(output))
}

fn expand_enum(
    vis: &syn::Visibility,
    ident: syn::Ident,
    input: &mut syn::DataEnum,
    root_attr: &RootAttr,
) -> syn::Result<TokenStream2> {
    let teleparse = crate_ident();

    let mut variant_attrs = Vec::with_capacity(input.variants.len());
    for variant in &mut input.variants {
        variant_attrs.push(strip_take_attrs(&mut variant.attrs));
    }

    let mut pt_ident = Vec::with_capacity(input.variants.len());
    let mut pt_ty = Vec::with_capacity(input.variants.len());
    for variant in &input.variants {
        if variant.discriminant.is_some() {
            syn_error!(
                variant,
                "derive_syntax does not support enums with discriminants"
            );
        }
        pt_ident.push(&variant.ident);
        match &variant.fields {
            syn::Fields::Unnamed(fields) => {
                let x = match ensure_one(fields.unnamed.iter()) {
                    EnsureOne::One(x) => x,
                    _ => {
                        syn_error!(
                            fields,
                            "derive_syntax only supports variant with exactly one unnamed field"
                        );
                    }
                };
                pt_ty.push(&x.ty);
            }
            _ => {
                syn_error!(
                    variant,
                    "derive_syntax only supports variant with exactly one unnamed field"
                );
            }
        }
    }
    let first_ty = match pt_ty.first() {
        Some(x) => x,
        None => syn_error!(&ident, "derive_syntax needs at least 1 variant in the enum"),
    };

    let mut apply_semantic_impl = Vec::with_capacity(input.variants.len());
    for (variant, attrs) in std::iter::zip(input.variants.iter(), variant_attrs.into_iter()) {
        let variant_attr = parse_field_attributes(variant, attrs)?;
        if let Some(semantic) = variant_attr.semantic {
            apply_semantic_impl.push(quote! {
                parser.apply_semantic(
                    &inner,
                    #teleparse::token_set!(<Self::Prod as #teleparse::syntax::Production>::L{
                        #( #semantic )|*
                    })
                );
            });
        } else {
            apply_semantic_impl.push(quote! {});
        }
    }

    let i = 0..pt_ty.len();

    let root_derive = if root_attr.root {
        Some(root::expand(&ident))
    } else {
        None
    };

    let (name, prod_struct) = derived_prod_name(&ident);
    let output = quote! {
        #[doc(hidden)]
        #[allow(non_camel_case_types)]
        #vis struct #prod_struct;
        #[automatically_derived]
        impl #teleparse::syntax::Production for #prod_struct {
            type L = <<#first_ty as #teleparse::parser::Produce>::Prod as #teleparse::syntax::Production>::L;
            #[inline]
            fn debug() -> ::std::borrow::Cow<'static, str> {
                ::std::borrow::Cow::Borrowed(#name)
            }
            fn register(meta: &mut #teleparse::syntax::MetadataBuilder<Self::L>) {
                #teleparse::register_union!(meta, #( <#pt_ty as #teleparse::parser::Produce>::Prod ),*);
            }
        }
        #[automatically_derived]
        impl #teleparse::parser::Produce for #ident {
            type Prod = #prod_struct;
            fn produce(
                parser: &mut #teleparse::parser::Parser<'_, <Self::Prod as #teleparse::syntax::Production>::L>,
                meta: &#teleparse::syntax::Metadata<<Self::Prod as #teleparse::syntax::Production>::L>,
            ) -> #teleparse::syntax::Result<Self, <Self::Prod as #teleparse::syntax::Production>::L> {
                use #teleparse::syntax::Production;
                let t = Self::prod_id();
                let token_src = parser.peek_token_src();
                match meta.jump.look_up(&t, token_src) {
                #(
                    Some(#i) => {
                        <#pt_ty>::produce(parser, meta).map(|inner| {
                            #apply_semantic_impl
                            Self::#pt_ident(inner)
                        })
                    }
                )*
                    _ => {
                        let first = meta.first.get(&t);
                        let err = parser.expecting(first.clone());
                        let err_vec = ::std::vec![err];
                        #teleparse::syntax::Result::Panic(err_vec)
                    },
                }
            }
        }
        #root_derive
    };

    Ok(anon_const_block(output))
}

fn derived_prod_name(ident: &syn::Ident) -> (String, syn::Ident) {
    let name = ident.to_string();
    let len = name.len();
    (name, format_ident!("DerivedProd_{}_{}", len, ident))
}

struct RootAttr {
    root: bool,
    no_test: bool,
}

fn parse_root_attributes(input: &mut syn::DeriveInput) -> syn::Result<RootAttr> {
    let root_metas = parse_strip_root_meta_optional(input)?;
    let mut root = false;
    let mut no_test = false;
    if let Some(root_metas) = root_metas {
        for meta in root_metas {
            match meta {
                syn::Meta::Path(path) => {
                    if path.is_ident("root") {
                        root = true;
                    } else if path.is_ident("no_test") {
                        no_test = true;
                    } else {
                        syn_error!(path, "Unknown attribute");
                    }
                }
                _ => {
                    syn_error!(meta, "Unknown attribute");
                }
            }
        }
    }
    if no_test && !root {
        syn_error!(input, "no_test can only be used with root");
    }
    Ok(RootAttr { root, no_test })
}

struct FieldAttr {
    semantic: Option<Vec<syn::Ident>>,
    // hook: Option<syn::Ident>,
}

fn parse_field_attributes<T: ToTokens>(
    field: &T,
    attrs: Vec<syn::Attribute>,
) -> syn::Result<FieldAttr> {
    let mut semantic = None;
    let mut hook = None;
    let attr = match ensure_one(attrs) {
        EnsureOne::None => return Ok(FieldAttr { semantic }),
        EnsureOne::More => syn_error!(
            field,
            "Multiple {} attributes found! You might want to merge them.",
            CRATE
        ),
        EnsureOne::One(attr) => attr,
    };
    for meta in parse_crate_attr_meta(&attr)? {
        match meta {
            syn::Meta::List(meta) => {
                if meta.path.is_ident("semantic") {
                    if semantic.is_some() {
                        syn_error!(
                            meta,
                            "Duplicated `semantic` attribute. You might want to merge them."
                        );
                    }
                    semantic = Some(
                        meta.parse_args_with(
                            Punctuated::<syn::Ident, syn::Token![,]>::parse_terminated,
                        )?
                        .into_iter()
                        .collect::<Vec<_>>(),
                    );
                    continue;
                }
                if meta.path.is_ident("hook") {
                    if hook.is_some() {
                        syn_error!(meta, "Duplicated `hook` attribute. There can only be one hook per field. You can wrap the hooks in one function.");
                    }
                    hook = Some(meta.parse_args::<syn::Ident>()?);
                    continue;
                }
            }
            _ => syn_error!(meta, "Invalid attribute format. Expected <attr>(<args>)"),
        }
    }

    Ok(FieldAttr { semantic })
}