inline-json5_macro 0.1.2

Supporting crate for inline-json5. (Loess demo project.)
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
//! Loess is grammar agnostic, so anything more specific than [`Punct`] or [`Literal`] is built from scratch here.
//! (I may include some of the utility containers in future versions.)
//!
//! This is a bit more involved since it requires custom conditional parsing.

use std::str::FromStr;

use loess::{Error, ErrorPriority, Errors, Input, IntoTokens, PeekFrom, PopFrom};
use proc_macro2::{Delimiter, Ident, Literal, Punct, TokenStream, TokenTree, extra::DelimSpan};

// This is probably the most interesting, so I'll put it first.
// I'll make the implementation a bit more general so that you can reuse it more easily.
/// Repeating `T` separated by `Delimiter`.
pub struct Delimited<T, Delimiter>(pub Vec<(T, Option<Delimiter>)>);

impl<T: PeekFrom, D> PeekFrom for Delimited<T, D> {
	fn peek_from(input: &Input) -> bool {
		input.is_empty() || T::peek_from(input)
	}
}

impl<T: PopFrom, D: PeekFrom + PopFrom> PopFrom for Delimited<T, D> {
	fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
		let mut items = vec![];
		while !input.is_empty() {
			if let Ok(value) = T::pop_from(input, errors) {
				if let Ok(delimiter) = (!input.is_empty())
					.then(|| D::pop_from(input, errors))
					.transpose()
				{
					items.push((value, delimiter));
				} else {
					// An error has been emitted at this point, so "silently" recover.
					items.push((value, recover(input)))
				}
			} else {
				// An error has been emitted at this point, so "silently" recover.
				recover::<D>(input);
			}
		}

		/// Skips tokens until it finds `Delimiter` or `input` is empty.
		///
		/// Then, parses a `Delimiter` if available.
		///
		/// # Returns
		///
		/// [`Some`], unless the input is reached first.
		fn recover<Delimiter: PeekFrom + PopFrom>(input: &mut Input) -> Option<Delimiter> {
			// Errors that are reported here are very likely to be noise.
			// There should have been an error that was reported before reaching this point, so suppressing them is okay.
			let mut suppressed_errors = Errors::new();
			while !input.is_empty() {
				let len_before = input.len();
				match Delimiter::peek_pop_from(input, &mut suppressed_errors) {
					Ok(Some(delimiter)) => return Some(delimiter),
					Ok(None) => drop(input.tokens.pop_front()), // Not found; skip and continue.
					Err(()) => {
						if input.len() == len_before {
							// Stalled. Skip one.
							drop(input.tokens.pop_front());
						}
						// Continue.
					}
				}
			}
			None
		}

		Ok(Self(items))
	}
}

impl<T: IntoTokens, D: IntoTokens> IntoTokens for Delimited<T, D> {
	fn into_tokens(self, root: &TokenStream, tokens: &mut impl Extend<TokenTree>) {
		// Note that no check to ensure `None` only appears last is performed here.
		// Such a case should be impossible with the current `PopFrom`-implementations.
		// Even if it happened, it would just lead to a compile error further down the line, though.
		for (value, delimiter) in self.0 {
			value.into_tokens(root, tokens);
			delimiter.into_tokens(root, tokens);
		}
	}
}

// I like this format of grammar-like documentation, personally, but it really does nothing here.
/// `[` [`T`](`TokenStream`) `]`
pub struct SquareBrackets<T = TokenStream> {
	pub contents: T,
	pub span: DelimSpan,
}

impl<T> PeekFrom for SquareBrackets<T> {
	fn peek_from(input: &Input) -> bool {
		// If your grammar is more complex, you may need to require `T: PeekFrom` and check inside.
		// Here that's not needed, though.
		matches!(input.front(), Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Bracket)
	}
}

impl<T: PopFrom> PopFrom for SquareBrackets<T> {
	fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
		input
			.pop_or_replace(|tts, _| match tts {
				[TokenTree::Group(group)] if group.delimiter() == Delimiter::Bracket => {
					let mut input = Input {
						tokens: group.stream().into_iter().collect(),
						end: group.span_close(),
					};
					let this = match T::pop_from(&mut input, errors) {
						Ok(contents) => Self {
							contents,
							span: group.delim_span(),
						},
						Err(()) => return Err([group.into()]),
					};
					if !input.is_empty() {
						errors.push(Error::new(
							ErrorPriority::UNCONSUMED_IN_DELIMITER,
							"Unconsumed token inside `[…]`.",
							[input.front_span()],
						));
					}
					Ok(this)
				}
				other => Err(other),
			})
			.map_err(|spans| errors.push(Error::new(ErrorPriority::TOKEN, "Expected `[`.", spans)))
	}
}

/// `{` [`T`](`TokenStream`) `}`
pub struct Braces<T = TokenStream> {
	pub contents: T,
	pub span: DelimSpan,
}

impl<T> PeekFrom for Braces<T> {
	fn peek_from(input: &Input) -> bool {
		// If your grammar is more complex, you may need to require `T: PeekFrom` and check inside.
		// Here that's not needed, though.
		matches!(input.front(), Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace)
	}
}

impl<T: PopFrom> PopFrom for Braces<T> {
	fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
		input
			.pop_or_replace(|tts, _| match tts {
				[TokenTree::Group(group)] if group.delimiter() == Delimiter::Brace => {
					let mut input = Input {
						tokens: group.stream().into_iter().collect(),
						end: group.span_close(),
					};
					let this = match T::pop_from(&mut input, errors) {
						Ok(contents) => Self {
							contents,
							span: group.delim_span(),
						},
						Err(()) => return Err([group.into()]),
					};
					if !input.is_empty() {
						errors.push(Error::new(
							ErrorPriority::UNCONSUMED_IN_DELIMITER,
							"Unconsumed token inside `{…}`.",
							[input.front_span()],
						));
					}
					Ok(this)
				}
				other => Err(other),
			})
			.map_err(|spans| errors.push(Error::new(ErrorPriority::TOKEN, "Expected `{`.", spans)))
	}
}

/// `(` [`T`](`TokenStream`) `)`
pub struct Parentheses<T = TokenStream> {
	pub contents: T,
	pub span: DelimSpan,
}

impl<T> PeekFrom for Parentheses<T> {
	fn peek_from(input: &Input) -> bool {
		// If your grammar is more complex, you may need to require `T: PeekFrom` and check inside.
		// Here that's not needed, though.
		matches!(input.front(), Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Parenthesis)
	}
}

impl<T: PopFrom> PopFrom for Parentheses<T> {
	fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
		input
			.pop_or_replace(|tts, _| match tts {
				[TokenTree::Group(group)] if group.delimiter() == Delimiter::Parenthesis => {
					let mut input = Input {
						tokens: group.stream().into_iter().collect(),
						end: group.span_close(),
					};
					let this = match T::pop_from(&mut input, errors) {
						Ok(contents) => Self {
							contents,
							span: group.delim_span(),
						},
						Err(()) => return Err([group.into()]),
					};
					if !input.is_empty() {
						errors.push(Error::new(
							ErrorPriority::UNCONSUMED_IN_DELIMITER,
							"Unconsumed token inside `(…)`.",
							[input.front_span()],
						));
					}
					Ok(this)
				}
				other => Err(other),
			})
			.map_err(|spans| errors.push(Error::new(ErrorPriority::TOKEN, "Expected `(`.", spans)))
	}
}

macro_rules! punctuation {
    ($($name:ident $char:literal),*$(,)?) => {$(
        // It's not really necessary to capture the `Punct` here,
        // but it's often nice to reuse input in the output directly.
        #[doc = concat!('`', $char, '`')]
        pub struct $name(pub Punct);

        impl PeekFrom for $name {
            fn peek_from(input: &Input) -> bool {
                // JSON5 doesn't have multi-punct punctuation, so spacing can be safely ignored here.
                matches!(input.front(), Some(TokenTree::Punct(punct)) if punct.as_char() == $char)
            }
        }

        impl PopFrom for $name {
            fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
                input
                    .pop_or_replace(|tts, _| match tts {
                        [TokenTree::Punct(punct)] if punct.as_char() == $char => Ok(Self(punct)),
                        other => Err(other),
                    })
                    .map_err(|spans| errors.push(Error::new(ErrorPriority::TOKEN, concat!("Expected `", $char, "`."), spans)))
            }
        }

        impl IntoTokens for $name {
            fn into_tokens(self, root: &TokenStream, tokens: &mut impl Extend<TokenTree>) {
                self.0.into_tokens(root, tokens)
            }
        }
    )*};
}

punctuation! {
	Colon ':',
	Comma ',',
	Dot '.',
	Minus '-',
	Plus '+',
}

macro_rules! keywords {
    ($($name:ident $str:literal),*$(,)?) => {$(
        #[doc = concat!('`', $str, '`')]
        pub struct $name(pub Ident);

        impl PeekFrom for $name {
            fn peek_from(input: &Input) -> bool {
                matches!(input.front(), Some(TokenTree::Ident(ident)) if ident == $str)
            }
        }

        impl PopFrom for $name {
            fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
                input
                    .pop_or_replace(|tts, _| match tts {
                        [TokenTree::Ident(ident)] if ident == $str => Ok(Self(ident)),
                        other => Err(other),
                    })
                    .map_err(|spans| {
                        errors.push(Error::new(
                            ErrorPriority::TOKEN,
                            concat!("Expected `", $str, "`."),
                            spans,
                        ))
                    })
            }
        }
    )*};
}

keywords! {
	False "false",
	Infinity "infinity",
	NaN "NaN",
	Null "null",
	True "true",
}

pub struct NumberLiteral(pub Option<Dot>, pub Literal);

impl PeekFrom for NumberLiteral {
	fn peek_from(input: &Input) -> bool {
		Dot::peek_from(input)
			|| if let Some(TokenTree::Literal(literal)) = input.front() {
				let s = literal.to_string();
				if s.starts_with("0x") {
					return true;
				}
				for c in s.chars() {
					if !(c.is_ascii_digit() || c == '.' || c == 'e') {
						return false;
					}
				}
				true
			} else {
				false
			}
	}
}

impl PopFrom for NumberLiteral {
	fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
		if let Some(dot) = Dot::peek_pop_from(input, errors).expect("infallible") {
			input
				.pop_or_replace(|tts, _| {
					if let [TokenTree::Literal(literal)] = tts {
						let s = literal.to_string();
						for c in s.chars() {
							if !(c.is_ascii_digit() || c == 'e') {
								return Err([literal.into()]);
							}
						}
						Ok(Self(Some(dot), literal))
					} else {
						Err(tts)
					}
				})
				.map_err(|spans| spans.into_iter().collect::<Vec<_>>())
		} else {
			input
				.pop_or_replace(|tts, _| {
					if let [TokenTree::Literal(literal)] = tts {
						let s = literal.to_string();
						if s.starts_with("0x") {
							return Ok(Self(None, literal));
						}
						for c in s.chars() {
							if !(c.is_ascii_digit() || c == '.' || c == 'e') {
								return Err([literal.into()]);
							}
						}
						Ok(Self(None, literal))
					} else {
						Err(tts)
					}
				})
				.map_err(|spans| spans.into_iter().collect())
		}
		.map_err(|spans| {
			errors.push(Error::new(
				ErrorPriority::TOKEN,
				concat!("Expected number literal."),
				spans,
			))
		})
	}
}

impl IntoTokens for NumberLiteral {
	fn into_tokens(self, _root: &TokenStream, tokens: &mut impl Extend<TokenTree>) {
		match self.0 {
			Some(Dot(_)) => tokens.extend([Literal::from_str(&format!("0.{}", self.1))
				.expect("This should be reasonably constrained by the parsing step.")
				.into()]),
			None => tokens.extend([self.1.into()]),
		}
	}
}

pub struct String(pub Literal);

impl PeekFrom for String {
	fn peek_from(input: &Input) -> bool {
		matches!(input.front(), Some(TokenTree::Literal(literal)) if literal.to_string().starts_with('"'))
	}
}

impl PopFrom for String {
	fn pop_from(input: &mut Input, _errors: &mut Errors) -> Result<Self, ()> {
		// This should always be guarded behind `::peek_from`, so I'll use assertions here.

		let Some(TokenTree::Literal(literal)) = input.tokens.pop_front() else {
			unreachable!("Expected String.")
		};

		assert!(literal.to_string().starts_with('"'), "Expected String.");

		Ok(Self(literal))
	}
}

pub struct Identifier(pub Ident);

impl PeekFrom for Identifier {
	fn peek_from(input: &Input) -> bool {
		matches!(input.front(), Some(TokenTree::Ident(ident)) if !ident.to_string().starts_with("r#"))
	}
}

impl PopFrom for Identifier {
	fn pop_from(input: &mut Input, errors: &mut Errors) -> Result<Self, ()> {
		input
			.pop_or_replace(|tts, _| match tts {
				[TokenTree::Ident(ident)] if !ident.to_string().starts_with("r#") => {
					Ok(Self(ident))
				}
				other => Err(other),
			})
			.map_err(|spans| {
				errors.push(Error::new(
					ErrorPriority::TOKEN,
					"Expected plain identifier.",
					spans,
				))
			})
	}
}