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
use num_bigint::BigInt;
use proc_macro2::Span;
use syn::{braced, bracketed, parenthesized, parse, Ident, LitBool, LitChar, LitInt, LitStr, Token};

use std::cmp::Ordering;
use std::hash::{Hash, Hasher};

#[derive(Clone, Debug)]
pub(crate) struct Meta {
	pub(crate) span: Span,
}

impl PartialOrd for Meta {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for Meta {
	fn cmp(&self, _other: &Self) -> Ordering {
		Ordering::Equal
	}
}

impl PartialEq for Meta {
	fn eq(&self, _other: &Self) -> bool {
		true
	}
}

impl Eq for Meta {}

impl Hash for Meta {
	fn hash<H: Hasher>(&self, _state: &mut H) {}
}

impl Default for Meta {
	fn default() -> Self {
		Self {
			span: Span::call_site(),
		}
	}
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub(crate) struct Syntax {
	pub(crate) args: Vec<Expr>,
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub(crate) struct Expr {
	pub(crate) atom: AtomicExpr,
	pub(crate) suffixes: Vec<Suffix>,
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub(crate) enum AtomicExpr {
	BuildInfo(Meta),
	LitBool(bool, Meta),
	LitInt(BigInt, Meta),
	LitChar(char, Meta),
	LitStr(String, Meta),
	Parenthesized(Box<Expr>, Meta),
	FunctionCall(String, Vec<Expr>, Meta),
	MacroCall(String, Vec<Expr>, Meta),
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub(crate) enum Suffix {
	Unwrap,
	Field(String),
	TupleIndex(u32),
	ArrayIndex(Box<Expr>),
	FunctionCall(String, Vec<Expr>),
}

impl parse::Parse for Syntax {
	fn parse(input: parse::ParseStream) -> parse::Result<Self> {
		let args = parse_arguments(&input)?;

		Ok(Self { args })
	}
}

fn parse_arguments(input: parse::ParseStream) -> parse::Result<Vec<Expr>> {
	let mut args = Vec::new();
	if !input.is_empty() {
		args.push(input.parse::<Expr>()?);
		parse_trailing_arguments_impl(&mut args, input)?;
	}
	Ok(args)
}

/*
fn parse_trailing_arguments(input: parse::ParseStream) -> parse::Result<Vec<Expr>> {
	let mut args = Vec::new();
	parse_trailing_arguments_impl(&mut args, input)?;
	Ok(args)
}
*/

fn parse_trailing_arguments_impl(args: &mut Vec<Expr>, input: parse::ParseStream) -> parse::Result<()> {
	while !input.is_empty() {
		input.parse::<Token![,]>()?;
		args.push(input.parse::<Expr>()?);
	}
	Ok(())
}

impl parse::Parse for AtomicExpr {
	fn parse(input: parse::ParseStream) -> parse::Result<Self> {
		let lookahead = input.lookahead1();
		if lookahead.peek(Token![$]) {
			let token = input.parse::<Token![$]>()?;
			Ok(AtomicExpr::BuildInfo(Meta { span: token.spans[0] }))
		} else if lookahead.peek(syn::token::Paren) {
			let expr;
			parenthesized!(expr in input);
			Ok(AtomicExpr::Parenthesized(
				Box::new(expr.parse::<Expr>()?),
				Meta { span: expr.span() },
			))
		} else if lookahead.peek(LitBool) {
			let lit_bool = input.parse::<LitBool>()?;
			Ok(AtomicExpr::LitBool(lit_bool.value, Meta { span: lit_bool.span }))
		} else if lookahead.peek(LitChar) {
			let lit_char = input.parse::<LitChar>()?;
			Ok(AtomicExpr::LitChar(lit_char.value(), Meta { span: lit_char.span() }))
		} else if lookahead.peek(LitInt) {
			let lit_int = input.parse::<LitInt>()?;
			if lit_int.suffix() != "" {
				return Err(syn::Error::new(
					lit_int.span(),
					"Integer suffix is not supported in [build-info] yet",
				));
			}
			Ok(AtomicExpr::LitInt(
				lit_int.base10_parse::<BigInt>()?,
				Meta { span: lit_int.span() },
			))
		} else if lookahead.peek(LitStr) {
			let lit_str = input.parse::<LitStr>()?;
			Ok(AtomicExpr::LitStr(lit_str.value(), Meta { span: lit_str.span() }))
		} else if lookahead.peek(Ident) {
			let id = input.parse::<Ident>()?;

			let lookahead = input.lookahead1();
			if lookahead.peek(syn::token::Paren) {
				let arguments;
				parenthesized!(arguments in input);
				let (arguments, span) = (parse_arguments(&arguments)?, arguments.span());
				Ok(AtomicExpr::FunctionCall(id.to_string(), arguments, Meta { span }))
			} else if lookahead.peek(Token![!]) {
				input.parse::<Token![!]>()?;
				let lookahead = input.lookahead1();
				let (arguments, span) = if lookahead.peek(syn::token::Paren) {
					let arguments;
					parenthesized!(arguments in input);
					(parse_arguments(&arguments)?, arguments.span())
				} else if lookahead.peek(syn::token::Brace) {
					let arguments;
					braced!(arguments in input);
					(parse_arguments(&arguments)?, arguments.span())
				} else if lookahead.peek(syn::token::Bracket) {
					let arguments;
					bracketed!(arguments in input);
					(parse_arguments(&arguments)?, arguments.span())
				} else {
					return Err(lookahead.error());
				};
				Ok(AtomicExpr::MacroCall(id.to_string(), arguments, Meta { span }))
			} else {
				Err(lookahead.error())
			}
		} else {
			Err(lookahead.error())
		}
	}
}

impl parse::Parse for Expr {
	fn parse(input: parse::ParseStream) -> parse::Result<Self> {
		let atom = input.parse::<AtomicExpr>()?;

		let mut suffixes = Vec::new();
		while !input.is_empty() {
			let lookahead = input.lookahead1();
			if lookahead.peek(Token![,]) {
				break;
			} else if lookahead.peek(Token![?]) {
				input.parse::<Token![?]>()?;
				suffixes.push(Suffix::Unwrap);
			} else if lookahead.peek(Token![.]) {
				input.parse::<Token![.]>()?;
				let lookahead = input.lookahead1();
				if lookahead.peek(Ident) {
					let id = input.parse::<Ident>()?;

					let lookahead = input.lookahead1();
					if lookahead.peek(syn::token::Paren) {
						let arguments;
						parenthesized!(arguments in input);
						let arguments = parse_arguments(&arguments)?;
						suffixes.push(Suffix::FunctionCall(id.to_string(), arguments));
					} else {
						suffixes.push(Suffix::Field(id.to_string()));
					}
				} else if lookahead.peek(LitInt) {
					let tuple_index = input.parse::<LitInt>()?;
					suffixes.push(Suffix::TupleIndex(tuple_index.base10_parse()?));
				} else {
					return Err(lookahead.error());
				}
			} else if lookahead.peek(syn::token::Bracket) {
				let expr;
				bracketed!(expr in input);
				let expr = expr.parse::<Expr>()?;
				suffixes.push(Suffix::ArrayIndex(Box::new(expr)));
			} else {
				return Err(lookahead.error());
			}
		}

		Ok(Self { atom, suffixes })
	}
}

#[cfg(test)]
mod test {
	use super::*;

	use pretty_assertions::assert_eq;
	use quote::quote;

	#[test]
	fn no_format() {
		let format = "This is a $test".to_string();
		let ast = quote! {#format};
		let result = syn::parse2::<Syntax>(ast).unwrap();
		assert_eq!(
			result,
			Syntax {
				args: vec![Expr {
					atom: AtomicExpr::LitStr(format, Meta::default()),
					suffixes: vec![],
				}],
			}
		);
	}

	#[test]
	fn format_self() {
		let format = "{}".to_string();
		let ast = quote! {#format, $};
		let result = syn::parse2::<Syntax>(ast).unwrap();
		assert_eq!(
			result,
			Syntax {
				args: vec![
					Expr {
						atom: AtomicExpr::LitStr(format, Meta::default()),
						suffixes: vec![],
					},
					Expr {
						atom: AtomicExpr::BuildInfo(Meta::default()),
						suffixes: vec![]
					}
				]
			}
		);
	}

	#[test]
	fn format_suffixes() {
		let format = "{}".to_string();
		let ast = quote! {#format, $.foo().7[0x0_C].foo};
		let result = syn::parse2::<Syntax>(ast).unwrap();
		assert_eq!(
			result,
			Syntax {
				args: vec![
					Expr {
						atom: AtomicExpr::LitStr(format, Meta::default()),
						suffixes: vec![],
					},
					Expr {
						atom: AtomicExpr::BuildInfo(Meta::default()),
						suffixes: vec![
							Suffix::FunctionCall("foo".to_string(), vec![]),
							Suffix::TupleIndex(7),
							Suffix::ArrayIndex(Box::new(Expr {
								atom: AtomicExpr::LitInt(12.into(), Meta::default()),
								suffixes: vec![],
							})),
							Suffix::Field("foo".to_string())
						]
					}
				],
			}
		);
	}

	#[test]
	fn format_trailing_comma() {
		let format = "{}".to_string();
		let ast = quote! {#format,};
		let result = syn::parse2::<Syntax>(ast);
		assert!(result.is_err());
	}
}