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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! [`Attribute`] parsing for items.

use std::{borrow::Cow, ops::Deref};

use proc_macro2::Span;
use syn::{
	parse::{discouraged::Speculative, Parse, ParseStream},
	punctuated::Punctuated,
	spanned::Spanned,
	Attribute, Data, Ident, Lit, Meta, NestedMeta, Path, PredicateType, Result, Token, TraitBound,
	TraitBoundModifier, Type, TypeParamBound, TypePath, WhereClause, WherePredicate,
};

use crate::{util, Error, Item, Skip, Trait, TraitImpl, DERIVE_WHERE};

/// Attributes on item.
#[derive(Default)]
pub struct ItemAttr {
	/// [`Path`] to this crate.
	pub crate_: Option<Path>,
	/// [`Trait`]s to skip all fields for.
	pub skip_inner: Skip,
	/// [`DeriveWhere`]s on this item.
	pub derive_wheres: Vec<DeriveWhere>,
}

impl ItemAttr {
	/// Create [`ItemAttr`] from [`Attribute`]s.
	pub fn from_attrs(span: Span, data: &Data, attrs: &[Attribute]) -> Result<Self> {
		let mut self_ = ItemAttr::default();
		let mut skip_inners = Vec::new();

		for attr in attrs {
			if attr.path.is_ident(DERIVE_WHERE) {
				if let Ok(meta) = attr.parse_meta() {
					if let Meta::List(list) = meta {
						match list.nested.len() {
							// Don't allow an empty list.
							0 => return Err(Error::empty(list.span())),
							// Check for `skip_inner` if list only has one item.
							1 => match list
								.nested
								.into_iter()
								.next()
								.expect("unexpected empty list")
							{
								NestedMeta::Meta(meta) => {
									if meta.path().is_ident(Skip::SKIP_INNER) {
										// Don't allow `skip_inner` on the item level for enums.
										if let Data::Enum(_) = data {
											return Err(Error::option_enum_skip_inner(meta.span()));
										}

										// Don't parse `Skip` yet, because it needs access to all
										// `DeriveWhere`s.
										skip_inners.push(meta);
									} else if meta.path().is_ident("crate") {
										if let Meta::NameValue(name_value) = meta {
											if let Lit::Str(lit_str) = &name_value.lit {
												match lit_str.parse::<Path>() {
													Ok(path) => {
														if path
															== util::path_from_strs(&[DERIVE_WHERE])
														{
															return Err(Error::path_unnecessary(
																path.span(),
																&format!("::{}", DERIVE_WHERE),
															));
														}

														match self_.crate_ {
															Some(_) => {
																return Err(
																	Error::option_duplicate(
																		name_value.span(),
																		"crate",
																	),
																)
															}
															None => self_.crate_ = Some(path),
														}
													}
													Err(error) => {
														return Err(Error::path(
															lit_str.span(),
															error,
														))
													}
												}
											} else {
												return Err(Error::option_syntax(
													name_value.lit.span(),
												));
											}
										} else {
											return Err(Error::option_syntax(meta.span()));
										}
									}
									// The list can have one item but still not be the `skip_inner`
									// attribute, continue with parsing `DeriveWhere`.
									else {
										self_
											.derive_wheres
											.push(DeriveWhere::from_attr(span, data, attr)?);
									}
								}
								nested_meta => {
									return Err(Error::option_syntax(nested_meta.span()))
								}
							},
							_ => self_
								.derive_wheres
								.push(DeriveWhere::from_attr(span, data, attr)?),
						}
					} else {
						return Err(Error::option_syntax(meta.span()));
					}
				}
				// Anything that can't be parsed by `Meta`, is because `A, B; C` isn't valid syntax.
				else {
					self_
						.derive_wheres
						.push(DeriveWhere::from_attr(span, data, attr)?)
				}
			}
		}

		// Check that we specified at least one `#[derive_where(..)]` with traits.
		if self_.derive_wheres.is_empty() {
			return Err(Error::none(span));
		}

		// Delayed parsing of `skip_inner` to get access to all traits to be
		// implemented.
		for meta in skip_inners {
			self_
				.skip_inner
				.add_attribute(&self_.derive_wheres, None, &meta)?;
		}

		Ok(self_)
	}
}

/// Holds parsed [generics](Generic) and [traits](crate::Trait).
pub struct DeriveWhere {
	/// Save [`Span`] for error messages.
	pub span: Span,
	/// [traits](DeriveTrait) to implement.
	pub traits: Vec<DeriveTraitWrapper>,
	/// [generics](Generic) for where clause.
	pub generics: Vec<Generic>,
}

impl DeriveWhere {
	/// Create [`DeriveWhere`] from [`Attribute`].
	fn from_attr(span: Span, data: &Data, attr: &Attribute) -> Result<Self> {
		attr.parse_args_with(|input: ParseStream| {
			// Parse the attribute input, this should either be:
			// - Comma separated traits.
			// - Comma separated traits `;` Comma separated generics.

			let mut traits = Vec::new();
			let mut generics = Vec::new();

			// Check for an empty list is already done in `ItemAttr::from_attrs`.
			while !input.is_empty() {
				// Start with parsing a trait.
				// Not checking for duplicates here, because these should produce a Rust error
				// anyway.
				traits.push(DeriveTraitWrapper::from_stream(span, data, input)?);

				if !input.is_empty() {
					let mut fork = input.fork();

					// Track `Span` of whatever was found instead of a delimiter. We parse the `,`
					// first because it's allowed to be followed by a `;`.
					let no_delimiter_found = match <Token![,]>::parse(&fork) {
						Ok(_) => {
							input.advance_to(&fork);
							None
						}
						Err(error) => {
							// Reset the fork if we didn't find a `,`.
							fork = input.fork();
							Some(error.span())
						}
					};

					if <Token![;]>::parse(&fork).is_ok() {
						input.advance_to(&fork);

						// If we found a semi-colon, start parsing generics.
						if !input.is_empty() {
							// `parse_teminated` parses everything left, which should end the
							// while-loop.
							// Not checking for duplicates here, as even Rust doesn't give a warning
							// for those: `where T: Clone, T: Clone` produces no error or warning.
							generics = Punctuated::<Generic, Token![,]>::parse_terminated(input)?
								.into_iter()
								.collect();
						}
					}
					// We are here because the input isn't empty, but we also found no delimiter,
					// something unexpected is here instead.
					else if let Some(span) = no_delimiter_found {
						return Err(Error::derive_where_delimiter(span));
					}
				}
			}

			Ok(Self {
				span: attr.span(),
				generics,
				traits,
			})
		})
	}

	/// Returns selected [`DeriveTrait`] if present.
	pub fn trait_(&self, trait_: &Trait) -> Option<&DeriveTrait> {
		self.traits
			.iter()
			.map(|wrapper| &wrapper.trait_)
			.find(|derive_trait| derive_trait == trait_)
	}

	/// Returns `true` if any [`CustomBound`](Generic::CustomBound) is present.
	pub fn any_custom_bound(&self) -> bool {
		self.generics.iter().any(|generic| match generic {
			Generic::CustomBound(_) => true,
			Generic::NoBound(_) => false,
		})
	}

	/// Returns `true` if the given generic type parameter if present.
	pub fn has_type_param(&self, type_param: &Ident) -> bool {
		self.generics.iter().any(|generic| match generic {
			Generic::NoBound(Type::Path(TypePath { qself: None, path })) => {
				if let Some(ident) = path.get_ident() {
					ident == type_param
				} else {
					false
				}
			}
			_ => false,
		})
	}

	/// Returns `true` if any [`Trait`] supports skipping.
	pub fn any_skip(&self) -> bool {
		self.traits.iter().any(|trait_| trait_.supports_skip())
	}

	/// Create [`WhereClause`] for the given parameters.
	pub fn where_clause(
		&self,
		where_clause: &mut Option<Cow<WhereClause>>,
		trait_: &DeriveTrait,
		item: &Item,
	) {
		// Only create a where clause if required
		if !self.generics.is_empty() {
			// We use the existing where clause or create a new one if required.
			let where_clause = where_clause.get_or_insert(Cow::Owned(WhereClause {
				where_token: <Token![where]>::default(),
				predicates: Punctuated::default(),
			}));

			// Insert bounds into the `where` clause.
			for generic in &self.generics {
				where_clause
					.to_mut()
					.predicates
					.push(WherePredicate::Type(match generic {
						Generic::CustomBound(type_bound) => type_bound.clone(),
						Generic::NoBound(path) => PredicateType {
							lifetimes: None,
							bounded_ty: path.clone(),
							colon_token: <Token![:]>::default(),
							bounds: trait_.where_bounds(item),
						},
					}));
			}
		}
	}
}

/// Holds a single generic [type](Type) or [type with bound](PredicateType).
pub enum Generic {
	/// Generic type with custom [specified bounds](PredicateType).
	CustomBound(PredicateType),
	/// Generic [type](Type) which will be bound to the [`DeriveTrait`].
	NoBound(Type),
}

impl Parse for Generic {
	fn parse(input: ParseStream) -> Result<Self> {
		let fork = input.fork();

		// Try to parse input as a `WherePredicate`. The problem is, both expressions
		// start with a Type, so starting with the `WherePredicate` is the easiest way
		// of differentiating them.
		if let Ok(where_predicate) = WherePredicate::parse(&fork) {
			input.advance_to(&fork);

			// Don't allow lifetimes, as it doesn't make sense in the context.
			if let WherePredicate::Type(path) = where_predicate {
				Ok(Generic::CustomBound(path))
			} else {
				Err(Error::generic(where_predicate.span()))
			}
		} else {
			match Type::parse(input) {
				Ok(type_) => Ok(Generic::NoBound(type_)),
				Err(error) => Err(Error::generic_syntax(error.span(), error)),
			}
		}
	}
}

/// Wrapper around [`DeriveTrait`] to add [`Span`].
pub struct DeriveTraitWrapper {
	/// [`Span`] for error messages.
	pub span: Span,
	/// Trait in this wrapper.
	trait_: DeriveTrait,
}

/// Trait to implement.
pub enum DeriveTrait {
	/// [`Clone`].
	Clone,
	/// [`Copy`].
	Copy,
	/// [`Debug`](std::fmt::Debug).
	Debug,
	/// [`Default`].
	Default,
	/// [`Eq`].
	Eq,
	/// [`Hash`](std::hash::Hash).
	Hash,
	/// [`Ord`].
	Ord,
	/// [`PartialEq`].
	PartialEq,
	/// [`PartialOrd`].
	PartialOrd,
	/// [`Zeroize`](https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html).
	#[cfg(feature = "zeroize")]
	Zeroize {
		/// [`Zeroize`](https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html) path.
		crate_: Option<Path>,
	},
	/// [`ZeroizeOnDrop`](https://docs.rs/zeroize/latest/zeroize/trait.ZeroizeOnDrop.html).
	#[cfg(feature = "zeroize")]
	ZeroizeOnDrop {
		/// [`ZeroizeOnDrop`](https://docs.rs/zeroize/latest/zeroize/trait.ZeroizeOnDrop.html) path.
		crate_: Option<Path>,
	},
}

impl Deref for DeriveTraitWrapper {
	type Target = DeriveTrait;

	fn deref(&self) -> &Self::Target {
		&self.trait_
	}
}

impl Deref for DeriveTrait {
	type Target = Trait;

	fn deref(&self) -> &Self::Target {
		use DeriveTrait::*;

		match self {
			Clone => &Trait::Clone,
			Copy => &Trait::Copy,
			Debug => &Trait::Debug,
			Default => &Trait::Default,
			Eq => &Trait::Eq,
			Hash => &Trait::Hash,
			Ord => &Trait::Ord,
			PartialEq => &Trait::PartialEq,
			PartialOrd => &Trait::PartialOrd,
			#[cfg(feature = "zeroize")]
			Zeroize { .. } => &Trait::Zeroize,
			#[cfg(feature = "zeroize")]
			ZeroizeOnDrop { .. } => &Trait::ZeroizeOnDrop,
		}
	}
}

impl PartialEq<Trait> for &DeriveTraitWrapper {
	fn eq(&self, other: &Trait) -> bool {
		let trait_: &DeriveTrait = self;
		trait_ == *other
	}
}

impl PartialEq<Trait> for &DeriveTrait {
	fn eq(&self, other: &Trait) -> bool {
		let trait_: &Trait = self;
		trait_ == other
	}
}

impl DeriveTraitWrapper {
	/// Create [`DeriveTrait`] from [`ParseStream`].
	fn from_stream(span: Span, data: &Data, input: ParseStream) -> Result<Self> {
		match Meta::parse(input) {
			Ok(meta) => {
				let trait_ = Trait::from_path(meta.path())?;

				if let Data::Union(_) = data {
					// Make sure this `Trait` supports unions.
					if !trait_.supports_union() {
						return Err(Error::union(span));
					}
				}

				match meta {
					Meta::Path(path) => Ok(Self {
						span: path.span(),
						trait_: trait_.default_derive_trait(),
					}),
					Meta::List(list) => {
						if list.nested.is_empty() {
							return Err(Error::option_empty(list.span()));
						}

						Ok(Self {
							span: list.span(),
							// This will return an error if no options are supported.
							trait_: trait_.parse_derive_trait(list)?,
						})
					}
					Meta::NameValue(name_value) => Err(Error::option_syntax(name_value.span())),
				}
			}
			Err(error) => Err(Error::trait_syntax(error.span())),
		}
	}
}

impl DeriveTrait {
	/// Returns fully qualified [`Path`] for this trait.
	pub fn path(&self) -> Path {
		use DeriveTrait::*;

		match self {
			Clone => util::path_from_root_and_strs(self.crate_(), &["clone", "Clone"]),
			Copy => util::path_from_root_and_strs(self.crate_(), &["marker", "Copy"]),
			Debug => util::path_from_root_and_strs(self.crate_(), &["fmt", "Debug"]),
			Default => util::path_from_root_and_strs(self.crate_(), &["default", "Default"]),
			Eq => util::path_from_root_and_strs(self.crate_(), &["cmp", "Eq"]),
			Hash => util::path_from_root_and_strs(self.crate_(), &["hash", "Hash"]),
			Ord => util::path_from_root_and_strs(self.crate_(), &["cmp", "Ord"]),
			PartialEq => util::path_from_root_and_strs(self.crate_(), &["cmp", "PartialEq"]),
			PartialOrd => util::path_from_root_and_strs(self.crate_(), &["cmp", "PartialOrd"]),
			#[cfg(feature = "zeroize")]
			Zeroize { .. } => util::path_from_root_and_strs(self.crate_(), &["Zeroize"]),
			#[cfg(feature = "zeroize")]
			ZeroizeOnDrop { .. } => util::path_from_root_and_strs(self.crate_(), &["ZeroizeOnDrop"]),
		}
	}

	/// Returns the path to the root crate for this trait.
	pub fn crate_(&self) -> Path {
		use DeriveTrait::*;

		match self {
			Clone => util::path_from_strs(&["core"]),
			Copy => util::path_from_strs(&["core"]),
			Debug => util::path_from_strs(&["core"]),
			Default => util::path_from_strs(&["core"]),
			Eq => util::path_from_strs(&["core"]),
			Hash => util::path_from_strs(&["core"]),
			Ord => util::path_from_strs(&["core"]),
			PartialEq => util::path_from_strs(&["core"]),
			PartialOrd => util::path_from_strs(&["core"]),
			#[cfg(feature = "zeroize")]
			Zeroize { crate_, .. } => {
				if let Some(crate_) = crate_ {
					crate_.clone()
				} else {
					util::path_from_strs(&["zeroize"])
				}
			}
			#[cfg(feature = "zeroize")]
			ZeroizeOnDrop { crate_, .. } => {
				if let Some(crate_) = crate_ {
					crate_.clone()
				} else {
					util::path_from_strs(&["zeroize"])
				}
			}
		}
	}

	/// Returns where-clause bounds for the trait in respect of the item type.
	fn where_bounds(&self, data: &Item) -> Punctuated<TypeParamBound, Token![+]> {
		let mut list = Punctuated::new();

		list.push(TypeParamBound::Trait(TraitBound {
			paren_token: None,
			modifier: TraitBoundModifier::None,
			lifetimes: None,
			path: self.path(),
		}));

		// Add bounds specific to the trait.
		if let Some(bound) = self.additional_where_bounds(data) {
			list.push(bound)
		}

		list
	}
}