duplicate 0.3.0

The attribute macro `duplicate` can duplicate an item with variable substitution.
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use crate::{
	parse_utils::*,
	substitute::{duplicate_and_substitute, Substitution},
	DuplicationDefinition, Result, SubstitutionGroup,
};
use proc_macro::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
use std::{collections::HashSet, iter::Peekable};

/// Parses the invocation of duplicate, returning all the substitutions that
/// should be made to the item.
///
/// If parsing succeeds returns first a substitution group that indicates global
/// substitutions that should be applied to all duplicates but don't on their
/// own indicate a duplicate. Then comes a list of substitution groups, each of
/// which indicates on duplicate.
pub(crate) fn parse_invocation(attr: TokenStream) -> Result<DuplicationDefinition>
{
	let mut iter = attr.into_iter().peekable();

	let (global_substitutions, extra) = validate_global_substitutions(&mut iter)?;
	match extra
	{
		None =>
		{
			validate_verbose_invocation(iter, global_substitutions.substitutions.is_empty()).map(
				|dups| {
					DuplicationDefinition {
						global_substitutions,
						duplications: dups,
					}
				},
			)
		},
		Some((ident, group)) =>
		{
			let substitutions = validate_short_attr(
				Some(TokenTree::Ident(ident))
					.into_iter()
					.chain(group.map(|g| TokenTree::Group(g)).into_iter())
					.chain(iter),
			)?;
			let mut reorder = Vec::new();

			for _ in 0..substitutions[0].2.len()
			{
				reorder.push(SubstitutionGroup::new());
			}

			for (ident, args, subs) in substitutions
			{
				for (idx, sub) in subs.into_iter().enumerate()
				{
					let substitution = Substitution::new(&args, sub.into_iter());
					if let Ok(substitution) = substitution
					{
						reorder[idx].add_substitution(
							Ident::new(&ident.clone(), Span::call_site()),
							substitution,
						)?;
					}
					else
					{
						return Err((Span::call_site(), "Failed creating substitution".into()));
					}
				}
			}
			Ok(DuplicationDefinition {
				global_substitutions,
				duplications: reorder,
			})
		},
	}
}

/// Validates global substitutions and returns a substitution group with them.
///
/// When it fails to validate a global substitution, it might return the next
/// identifier that the iterator produced optionally followed by the next group
/// too. The two must therefore be assumed to precede any tokentrees returned by
/// the iterator and calling this function.
/// This may happen if the global substitutions are followed by short-syntax,
/// which starts the same way as a global substitution.
fn validate_global_substitutions(
	iter: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<(SubstitutionGroup, Option<(Ident, Option<Group>)>)>
{
	let mut sub_group = SubstitutionGroup::new();
	loop
	{
		match extract_inline_substitution(iter)
		{
			Ok((ident, Ok(sub))) => sub_group.add_substitution(ident, sub)?,
			Ok((ident, Err(group))) => return Ok((sub_group, Some((ident, group)))),
			_ => break,
		}

		match iter.peek()
		{
			Some(TokenTree::Punct(p)) if is_semicolon(p) =>
			{
				let _ = iter.next();
			},
			Some(t) => return Err((t.span(), "Expected ';'.".into())),
			_ => break,
		}
	}
	Ok((sub_group, None))
}

/// Validates that a duplicate invocation uses the verbose syntax, and returns
/// all the substitutions that should be made.
fn validate_verbose_invocation(
	iter: impl Iterator<Item = TokenTree>,
	err_on_no_subs: bool,
) -> Result<Vec<SubstitutionGroup>>
{
	let mut iter = iter.peekable();
	if err_on_no_subs && iter.peek().is_none()
	{
		return Err((Span::call_site(), "No substitutions found.".into()));
	}

	let mut sub_groups = Vec::new();

	let mut substitution_ids = None;
	let mut err_span = Span::call_site();
	loop
	{
		if let Ok(tree) = next_token(&mut iter, err_span, "Substitution group")
		{
			err_span = tree.span();
			match &tree
			{
				TokenTree::Punct(p) if is_nested_invocation(p) =>
				{
					let nested_duplicated = invoke_nested(&mut iter, p.span())?;
					let subs = validate_verbose_invocation(nested_duplicated.into_iter(), true)?;
					sub_groups.extend(subs.into_iter());
				},
				_ =>
				{
					sub_groups.push(extract_verbose_substitutions(tree, &substitution_ids)?);
					if None == substitution_ids
					{
						substitution_ids = Some(
							sub_groups[0]
								.identifiers_with_args()
								.map(|(ident, count)| (ident.clone(), count))
								.collect(),
						)
					}
				},
			}
		}
		else
		{
			break;
		}
	}

	Ok(sub_groups)
}

/// Extracts an inline substitution, i.e. a substitution identifier followed by
/// an optional parameter list, followed by a substitution.
///
/// If a substitution identifier is encountered but not the rest of the
/// substitution, the identifier is returned on its own.
fn extract_inline_substitution(
	stream: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<(Ident, std::result::Result<Substitution, Option<Group>>)>
{
	let token = peek_next_token(stream, Span::call_site(), "Substitution identifier")?;

	if let TokenTree::Ident(ident) = token
	{
		let _ = stream.next();
		let group_1 = peek_parse_group(stream, Delimiter::Parenthesis, ident.span(), "");

		if let Ok(params) = group_1
		{
			let _ = stream.next();
			parse_group(
				stream,
				Delimiter::Bracket,
				ident.span(),
				"Hint: A substitution identifier should be followed by a group containing the \
				 code to be inserted instead of any occurrence of the identifier.",
			)
			.and_then(|sub| {
				extract_argument_list(&params)
					.map(|args| Ok(Substitution::new(&args, sub.stream().into_iter()).unwrap()))
					.or_else(|err| Err(err))
			})
			.or_else(|_| Ok(Err(Some(params))))
		}
		else
		{
			parse_group(
				stream,
				Delimiter::Bracket,
				ident.span(),
				"Hint: A substitution identifier should be followed by a group containing the \
				 code to be inserted instead of any occurrence of the identifier.",
			)
			.map(|sub| Ok(Substitution::new_simple(sub.stream())))
			.or_else(|_| Ok(Err(None)))
		}
		.map(|result| (ident, result))
	}
	else
	{
		Err((token.span(), "Expected substitution identifier.".into()))
	}
}

/// Extracts a substitution group in the verbose syntax.
fn extract_verbose_substitutions(
	tree: TokenTree,
	existing: &Option<HashSet<(String, usize)>>,
) -> Result<SubstitutionGroup>
{
	// Must get span now, before it's corrupted.
	let tree_span = tree.span();
	let group = check_group(
		tree,
		Delimiter::Bracket,
		"Hint: When using verbose syntax, a substitutions must be enclosed in a \
		 group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \
		 ]\n]",
	)?;

	if group.stream().into_iter().count() == 0
	{
		return Err((group.span(), "No substitution groups found.".into()));
	}

	let mut substitutions = SubstitutionGroup::new();
	let mut stream = group.stream().into_iter().peekable();

	loop
	{
		if let Ok((ident, Ok(substitution))) = extract_inline_substitution(&mut stream)
		{
			substitutions.add_substitution(ident, substitution)?;
		}
		else
		{
			// Check no substitution idents are missing or with wrong argument counts.
			if let Some(idents) = existing
			{
				let sub_idents: HashSet<_> = substitutions.identifiers_with_args().collect();
				// Map idents to string reference so we can use HashSet::difference
				let idents = idents
					.iter()
					.map(|(ident, count)| (ident, count.clone()))
					.collect();
				let diff: Vec<_> = sub_idents.difference(&idents).collect();

				if diff.len() > 0
				{
					let mut msg: String = "Invalid substitutions.\nThe following identifiers were \
					                       not found in previous substitution groups or had \
					                       different arguments:\n"
						.into();
					for ident in diff
					{
						msg.push_str(&ident.0.to_string());
						msg.push_str("(");
						if ident.1 > 0
						{
							msg.push_str("_");
						}
						for _ in 1..(ident.1)
						{
							msg.push_str(",_")
						}
						msg.push_str(")");
					}

					return Err((tree_span, msg));
				}
			}
			break;
		}
	}
	Ok(substitutions)
}

/// Validates a duplicate invocation using the short syntax and returns the
/// substitution that should be made.
fn validate_short_attr(
	iter: impl Iterator<Item = TokenTree>,
) -> Result<Vec<(String, Vec<String>, Vec<TokenStream>)>>
{
	let mut iter = iter.peekable();

	let (idents, span) = validate_short_get_identifiers(&mut iter, Span::call_site())?;
	let mut result: Vec<_> = idents
		.into_iter()
		.map(|(ident, args)| (ident, args, Vec::new()))
		.collect();
	validate_short_get_all_substitution_goups(iter, span, &mut result)?;

	Ok(result)
}

/// Assuming use of the short syntax, gets the initial list of substitution
/// identifiers.
fn validate_short_get_identifiers(
	iter: &mut impl Iterator<Item = TokenTree>,
	mut span: Span,
) -> Result<(Vec<(String, Vec<String>)>, Span)>
{
	let mut iter = iter.peekable();
	let mut result = Vec::new();
	loop
	{
		let next_token = next_token(&mut iter, span, "Substitution identifier or ';'")?;
		span = next_token.span();
		match &next_token
		{
			TokenTree::Ident(ident) =>
			{
				result.push((
					ident.to_string(),
					validate_short_get_identifier_arguments(&mut iter)?, // Vec::new()
				))
			},
			TokenTree::Punct(p) if is_semicolon(&p) => break,
			_ => return Err((span, "Expected substitution identifier or ';'.".into())),
		}
	}
	Ok((result, span))
}

/// Assuming use of the short syntax, gets the list of identifier arguments.
fn validate_short_get_identifier_arguments(
	iter: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<Vec<String>>
{
	if let Some(token) = iter.peek()
	{
		if let TokenTree::Group(group) = token
		{
			if check_delimiter(group, Delimiter::Parenthesis).is_ok()
			{
				let result = extract_argument_list(group)?;
				// Make sure to consume the group
				let _ = iter.next();
				return Ok(result);
			}
		}
	}
	Ok(Vec::new())
}

/// Gets all substitution groups in the short syntax and inserts
/// them into the given vec.
fn validate_short_get_all_substitution_goups<'a>(
	iter: impl Iterator<Item = TokenTree>,
	mut span: Span,
	result: &mut Vec<(String, Vec<String>, Vec<TokenStream>)>,
) -> Result<()>
{
	let mut iter = iter.peekable();
	loop
	{
		if let Some(TokenTree::Punct(p)) = iter.peek()
		{
			if is_nested_invocation(&p)
			{
				let p_span = p.span();
				// consume '#'
				iter.next();

				let nested_duplicated = invoke_nested(&mut iter, p_span)?;
				validate_short_get_all_substitution_goups(
					&mut nested_duplicated.into_iter(),
					span.clone(),
					result,
				)?;
			}
		}
		else
		{
			validate_short_get_substitutions(
				&mut iter,
				span,
				result.iter_mut().map(|(_, _, vec)| {
					vec.push(TokenStream::new());
					vec.last_mut().unwrap()
				}),
			)?;

			if let Some(token) = iter.next()
			{
				span = token.span();
				if let TokenTree::Punct(p) = token
				{
					if is_semicolon(&p)
					{
						continue;
					}
				}
				return Err((span, "Expected ';'.".into()));
			}
			else
			{
				break;
			}
		}
	}
	Ok(())
}

/// Extracts a substitution group in the short syntax and inserts it into
/// the elements returned by the given group's iterator.
fn validate_short_get_substitutions<'a>(
	iter: &mut Peekable<impl Iterator<Item = TokenTree>>,
	mut span: Span,
	mut groups: impl Iterator<Item = &'a mut TokenStream>,
) -> Result<Span>
{
	if let Some(token) = iter.next()
	{
		let group = check_group(token, Delimiter::Bracket, "")?;
		span = group.span();
		*groups.next().unwrap() = group.stream();

		for stream in groups
		{
			let group = parse_group(iter, Delimiter::Bracket, span, "")?;
			span = group.span();
			*stream = group.stream();
		}
	}
	Ok(span)
}

/// Invokes a nested invocation of duplicate, assuming the
/// next group is the attribute part of the invocation and the
/// group after that is the element.
fn invoke_nested(
	iter: &mut Peekable<impl Iterator<Item = TokenTree>>,
	span: Span,
) -> Result<TokenStream>
{
	let hints = "Hint: '#' is a nested invocation of the macro and must therefore be followed by \
	             a group containing the invocation.\nExample:\n#[\n\tidentifier [ substitute1 ] [ \
	             substitute2 ]\n][\n\tCode to be substituted whenever 'identifier' occurs \n]";
	let nested_attr = parse_group(iter, Delimiter::Bracket, span, hints)?;
	let nested_dup_def = parse_invocation(nested_attr.stream())?;

	let nested_item = parse_group(iter, Delimiter::Bracket, nested_attr.span(), hints)?;
	duplicate_and_substitute(
		nested_item.stream(),
		&nested_dup_def.global_substitutions,
		nested_dup_def.duplications.iter(),
	)
}