syn_derive/
lib.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
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
/*!
A simple crate for reducing the boilerplate when writing parsers with [`syn`].

## Structs

```rust
# use syn::{*, token::Paren, punctuated::*};
# use quote::TokenStreamExt;
#[derive(syn_derive::Parse, syn_derive::ToTokens)]
struct ExampleStruct {
    #[parse(Attribute::parse_outer)]
    #[to_tokens(|tokens, val| tokens.append_all(val))]
    attrs: Vec<Attribute>,

    path: Path,

    #[syn(parenthesized)]
    paren_token: Paren,

    #[syn(in = paren_token)]
    #[parse(Punctuated::parse_terminated)]
    args: Punctuated<Box<Expr>, Token![,]>,

    semi_token: Token![;],

    #[parse(Pat::parse_multi, boxed)]
    pub pat: Box<Pat>,
}
```

<code>#[syn(parenthesized)]</code>,
<code>#[syn(braced)]</code>,
<code>#[syn(bracketed)]</code>:
  Corresponds to the isonymous macros in `syn`.
  Must be attached to [`struct@Paren`], [`struct@Brace`], and [`struct@Bracket`] fields, respectively.

<code>#[syn(in = Ident)]</code>:
  The field is read from inside the named delimiter pair.

<code>#[parse(fn(ParseStream) -> syn::Result\<T>)]</code>:
  A function used to parse the field,
  often used with [`Punctuated::parse_terminated`]
  or [`Attribute::parse_outer`].

<code>#[parse(_, boxed)]</code>:
  Wraps the specified parse function to box the value.
  Useful with functions like `Pat::parse_multi` above.

<code>#[to_tokens(fn(&mut TokenStream, &T)]</code>:
  A function used to tokenize the field.
  Often used with [`TokenStreamExt::append_all`],
  though for type resolution reasons this needs to be indirected through a closure expression.

## Enums

```rust
# use syn::{*, token::Paren, punctuated::*};
#[derive(syn_derive::Parse, syn_derive::ToTokens)]
enum ExampleEnum {
    #[parse(peek = Token![struct])]
    Struct(ItemStruct),
    #[parse(peek = Token![enum])]
    Enum(ItemEnum),

    Other {
        path: Path,
        semi_token: Token![;],
    }
}
```

<code>#[parse(prefix = fn([`ParseStream`]) -> [`syn::Result`]<_>)]</code>>:
  A prefix used for all branches, before doing the peeking.
  Useful when all branches support attributes, for example.
  The return value is ignored, which gives somewhat suboptimal performance, since the prefix is parsed twice.

<code>#[parse(peek = [`Token`])]</code>:
  Checks whether the variant should be parsed.
  Even if multiple peeks succeed, only the first successful variant is attempted.

<code>#[parse(peek_func = fn([`ParseStream`]) -> [`bool`])]</code>:
  More powerful than `peek` (such as allowing [`peek2`](syn::parse::ParseBuffer::peek2)), but gives worse error messages on failure.
  `peek` should be preferred when possible.

# Feature flags
- `full` (enabled by default): enables `syn/full`, which is needed to parse complex expressions — such as closures — in attribute values.
  Without this, you can still use for example paths to functions, but this is much less convenient.

# Alternatives
- [`derive-syn-parse`](https://docs.rs/derive-syn-parse/latest/)
  does not handle [`ToTokens`].
  It also seems to encourage throwing tokens away with its `prefix` and `postfix` attributes.
- [`parsel`](https://docs.rs/parsel/latest/)
  uses its own types for parentheses, meaning the AST types have different API from [`syn`]'s own.

*/

use proc_macro2::{Span, TokenStream};
use syn::parse::{ParseStream, Parser};
use syn::{parse_macro_input, Data, DeriveInput, Ident};
use syn::spanned::Spanned;
use proc_macro_error::{proc_macro_error, Diagnostic, Level};

#[cfg(doc)]
use {
	syn::{
		Token,
		Attribute,
		punctuated::Punctuated,
		token::{Paren, Bracket, Brace},
	},
	quote::TokenStreamExt,
};

#[proc_macro_error]
#[proc_macro_derive(Parse, attributes(syn, parse))]
pub fn derive_parse(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
	let input = parse_macro_input!(item as DeriveInput);
	derive_parse_inner(input).into()
}

#[proc_macro_error]
#[proc_macro_derive(ToTokens, attributes(syn, to_tokens))]
pub fn derive_tokens(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
	let input = parse_macro_input!(item as DeriveInput);
	derive_tokens_inner(input).into()
}

macro_rules! q {
	(_      => $($b:tt)*) => { ::quote::quote!         {                $($b)* } };
	($a:expr=> $($b:tt)*) => { ::quote::quote_spanned! { ($a).span() => $($b)* } };
}

macro_rules! pq {
	(_      => $($b:tt)*) => { ::syn::parse_quote!         {                $($b)* } };
	($a:expr=> $($b:tt)*) => { ::syn::parse_quote_spanned! { ($a).span() => $($b)* } };
}

trait Emit {
	type T;
	fn emit(self) -> Self::T;
}
impl Emit for syn::Error {
	type T = ();
	fn emit(self) {
		self.span().error(&self.to_string()).emit();
	}
}
impl<T> Emit for Result<T, syn::Error> {
	type T = Option<T>;
	fn emit(self) -> Option<T> {
		match self {
			Ok(v) => Some(v),
			Err(e) => { e.emit(); None }
		}
	}
}

trait SpanError: Spanned {
	fn warning(&self, text: &str) -> Diagnostic {
		Diagnostic:: spanned(self.span(), Level::Warning, text.to_owned())
	}

	fn error(&self, text: &str) -> Diagnostic {
		Diagnostic:: spanned(self.span(), Level::Error, text.to_owned())
	}
}
impl <T: Spanned> SpanError for T {}

fn derive_parse_inner(input: DeriveInput) -> TokenStream {
	let body = match &input.data {
		Data::Struct(data) => {
			derive_parse_fields(pq!{_=> Self }, input.span(), &data.fields)
		}
		Data::Enum(data) => {
			let mut prefix_expr = None::<syn::Expr>;
			for attr in &input.attrs {
				if attr.path().is_ident("parse") {
					attr.parse_nested_meta(|meta| {
						if meta.path.is_ident("prefix") {
							prefix_expr = Some(meta.value()?.parse()?);
							return Ok(());
						}
						Err(meta.error("unrecognized key"))
					}).emit();
				}
			}

			let mut main_body = TokenStream::new();
			for variant in &data.variants {
				let ident = &variant.ident;
				let body = derive_parse_fields(pq!{ident=> Self::#ident }, variant.span(), &variant.fields);
				let mut body = q!{variant=> return #body; };
				for attr in &variant.attrs {
					if attr.path().is_ident("parse") {
						attr.parse_nested_meta(|meta| {
							if meta.path.is_ident("peek") {
								let token = meta.value()?.parse::<syn::Expr>()?;
								body = q!{variant=>
									if __lookahead.peek(#token) { #body }
								};
								return Ok(());
							}
							if meta.path.is_ident("peek_func") {
								let func = meta.value()?.parse::<syn::Expr>()?;
								body = q!{variant=>
									let peek: fn(::syn::parse::ParseStream) -> bool = #func;
									if peek(&head.fork()) { #body }
								};
								return Ok(());
							}
							Err(meta.error("unrecognized key"))
						}).emit();
					}
				}
				main_body.extend(body)
			}
			let prefix_expr = prefix_expr.iter();
			q!{_=> {
				let head = __input.fork();
				#( head.call(#prefix_expr)?; )*
				let __lookahead = head.lookahead1();
				#main_body
				#[allow(unreachable_code)]
				return Err(__lookahead.error())
			} }
		},
		Data::Union(_) => {
			Span::call_site().error("unions not supported").emit();
			q!{_=> { } }
		}
	};

	let name = &input.ident;
	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
	q!{_=>
		#[automatically_derived]
		#[allow(clippy::init_numbered_fields)]
		impl #impl_generics ::syn::parse::Parse for #name #ty_generics #where_clause {
			fn parse(__input: ::syn::parse::ParseStream) -> ::syn::Result<Self> #body
		}
	}
}

fn derive_tokens_inner(input: DeriveInput) -> TokenStream {
	let body = match &input.data {
		Data::Struct(data) => {
			let (pat, body) = derive_tokens_fields(pq!{_=> Self }, input.span(), &data.fields);
			q!{_=> let #pat = self; #body }
		}
		Data::Enum(data) => {
			let mut match_body = TokenStream::new();
			for variant in &data.variants {
				let ident = &variant.ident;
				let (pat, body) = derive_tokens_fields(pq!{ident=> Self::#ident }, variant.span(), &variant.fields);
				match_body.extend(q!{variant=> #pat => #body, })
			}
			q!{_=> match self { #match_body } }
		},
		Data::Union(_) => {
			Span::call_site().error("unions not supported").emit();
			TokenStream::new()
		}
	};

	let name = &input.ident;
	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
	q!{_=>
		#[automatically_derived]
		impl #impl_generics ::quote::ToTokens for #name #ty_generics #where_clause {
			fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
				#body
			}
		}
	}
}

fn derive_parse_fields(path: syn::Path, span: Span, fields: &syn::Fields) -> TokenStream {
	let mut defs = TokenStream::new();
	let mut body = TokenStream::new();
	for (member, fa, field) in named(fields) {
		let stream = fa.stream.unwrap_or_else(|| pq!{field.span()=> __input });

		let mut expr = match &fa.delimiter {
			Some(delimiter) => {
				defs.extend(q!{member=> let #member; });
				q!{member=> ::syn::#delimiter!(#member in #stream) }
			}
			None => {
				q!{member=> #stream.parse()? }
			}
		};

		for attr in &field.attrs {
			if attr.path().is_ident("parse") {
				if fa.delimiter.is_some() {
					fa.delimiter.span().error("cannot do custom parsing on delimiters").emit();
				}
				attr.parse_args_with(|input: ParseStream| {
					let e = input.parse::<syn::Expr>()?;
					expr = q!{e=> #stream.call(#e)?};

					if input.is_empty() {
						return Ok(());
					}
					input.parse::<syn::Token![,]>()?;
					if input.is_empty() {
						return Ok(());
					}

					syn::meta::parser(|meta| {
						if meta.path.is_ident("boxed") {
							expr = q!{meta.path.span()=> ::std::boxed::Box::new(#expr)};
							return Ok(())
						}
						Err(meta.error("unrecognized key"))
					}).parse2(input.parse::<TokenStream>()?)
				}).emit();
			}
		}

		body.extend(q!{member=> #member: #expr, });
	}
	q!{span=> { #defs ::syn::Result::Ok(#path { #body }) } }
}

fn derive_tokens_fields(path: syn::Path, span: Span, fields: &syn::Fields) -> (TokenStream, TokenStream) {
	let mut pat = TokenStream::new();
	let mut body = TokenStream::new();
	let mut iter = named(fields).peekable();
	derive_tokens_fields_inner(&mut iter, None, &mut pat, &mut body);
	if let Some(a) = iter.next() {
		a.2.span().error("invalid `in`").emit();
	}
	(q!{span=> #path { #pat } }, q!{span=> { #body } })
}

fn derive_tokens_fields_inner(
	iter: &mut std::iter::Peekable<impl Iterator<Item = (syn::Member, FieldAttr, syn::Field)>>,
	stream: Option<Ident>,
	pat: &mut TokenStream,
	body: &mut TokenStream,
) {
	while let Some((member, fa, field)) = iter.next_if(|a| a.1.stream == stream) {
		let ident = match &member {
			syn::Member::Named(ident) => {
				pat.extend(q!{member=> #member, });
				ident.clone()
			}
			syn::Member::Unnamed(index) => {
				let i = index.index;
				let ident = quote::format_ident!("__{i}", span = index.span());
				pat.extend(q!{member=> #member: #ident, });
				ident
			}
		};

		let mut expr = match &fa.delimiter {
			Some(delimiter) => {
				let mut body = TokenStream::new();
				derive_tokens_fields_inner(iter, Some(ident.clone()), pat, &mut body);
				q!{delimiter=> #ident.surround(tokens, |tokens| { #body }) }
			}
			None => {
				q!{member=> #ident.to_tokens(tokens) }
			}
		};

		for attr in &field.attrs {
			if attr.path().is_ident("to_tokens") {
				if fa.delimiter.is_some() {
					fa.delimiter.span().error("cannot do custom parsing on delimiters").emit();
				}
				if let Some(e) = attr.parse_args::<syn::Expr>().emit() {
					expr = q!{e=> {
						let __expr: fn(&mut ::proc_macro2::TokenStream, _) = #e;
						__expr(tokens, #ident)
					} };
				}
			}
		}

		body.extend(q!{field=> #expr; });
	}
}

#[derive(Clone, Debug, Default)]
struct FieldAttr {
	delimiter: Option<Ident>,
	stream: Option<Ident>,
}

fn parse_field_attr(field: &syn::Field) -> FieldAttr {
	let mut out = FieldAttr::default();
	for attr in &field.attrs {
		if attr.path().is_ident("syn") {
			attr.parse_nested_meta(|meta| {
				if meta.path.is_ident("in") {
					out.stream = Some(meta.value()?.parse()?);
					return Ok(());
				}
				if meta.path.is_ident("parenthesized") || meta.path.is_ident("braced") || meta.path.is_ident("bracketed") {
					out.delimiter = meta.path.get_ident().cloned();
					return Ok(());
				}
				Err(meta.error("unrecognized key"))
			}).emit();
		}
	}
	out
}

fn named(
	fields: &syn::Fields
) -> impl Iterator<Item=(syn::Member, FieldAttr, syn::Field)> + '_ {
	fields.iter().cloned()
		.enumerate()
		.map(|(i, f)| (
			f.ident.clone().map_or_else(
				|| syn::Member::Unnamed(syn::Index { index: i as u32, span: f.span() }),
				syn::Member::Named,
			),
			parse_field_attr(&f),
			f,
		))
}