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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#![deny(unsafe_code)]
#![cfg_attr(feature = "nightly", feature(allow_internal_unstable))]
#![allow(clippy::tabs_in_doc_comments)]
#![warn(clippy::cargo, clippy::missing_docs_in_private_items)]
#![cfg_attr(doc, warn(rustdoc::all), allow(rustdoc::missing_doc_code_examples))]

//! # Description
//!
//! Derive macro to simplify deriving standard and other traits with custom
//! generic type bounds.
//!
//! # Usage
//!
//! The `derive_where` macro can be used just like std's `#[derive(...)]`
//! statements:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! #[derive_where(Clone, Debug)]
//! struct Example<T>(PhantomData<T>);
//! ```
//!
//! This will generate trait implementations for `Example` for any `T`,
//! as opposed to std's derives, which would only implement these traits with
//! `T: Trait` bound to the corresponding trait.
//!
//! Multiple `derive_where` attributes can be added to an item, but only the
//! first one must use any path qualifications.
//!
//! ```
//! # use std::marker::PhantomData;
//! #[derive_where::derive_where(Clone)]
//! #[derive_where(Debug)]
//! struct Example1<T>(PhantomData<T>);
//! ```
//!
//! In addition, the following convenience options are available:
//!
//! ## Generic type bounds
//!
//! Separated from the list of traits with a semi-colon, types to bind to can be
//! specified. This example will restrict the implementation for `Example` to
//! `T: Clone`:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! #[derive_where(Clone; T)]
//! struct Example<T, U>(T, PhantomData<U>);
//! ```
//!
//! It is also possible to specify the bounds to be applied. This will
//! bind implementation for `Example` to `T: Super`:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! trait Super: Clone {}
//!
//! #[derive_where(Clone; T: Super)]
//! struct Example<T>(PhantomData<T>);
//! ```
//!
//! But more complex trait bounds are possible as well.
//! The example below will restrict the implementation for `Example` to
//! `T::Type: Clone`:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! trait Trait {
//! 	type Type;
//! }
//!
//! struct Impl;
//!
//! impl Trait for Impl {
//! 	type Type = i32;
//! }
//!
//! #[derive_where(Clone; T::Type)]
//! struct Example<T: Trait>(T::Type);
//! ```
//!
//! Any combination of options listed here can be used to satisfy a
//! specific constrain. It is also possible to use multiple separate
//! constrain specifications when required:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! #[derive_where(Clone; T)]
//! #[derive_where(Debug; U)]
//! struct Example<T, U>(PhantomData<T>, PhantomData<U>);
//! ```
//!
//! ## Enum default
//!
//! Deriving [`Default`] on an enum is not possible in Rust at the moment.
//! Derive-where allows this with a `default` attribute:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! #[derive_where(Default)]
//! enum Example<T> {
//! 	#[derive_where(default)]
//! 	A(PhantomData<T>),
//! }
//! ```
//!
//! ## Skipping fields
//!
//! With a `skip` or `skip_inner` attribute fields can be skipped for traits
//! that allow it, which are: [`Debug`], [`Hash`], [`Ord`], [`PartialOrd`],
//! [`PartialEq`], [`Zeroize`] and [`ZeroizeOnDrop`].
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! #[derive_where(Debug, PartialEq; T)]
//! struct Example<T>(#[derive_where(skip)] T);
//!
//! assert_eq!(format!("{:?}", Example(42)), "Example");
//! assert_eq!(Example(42), Example(0));
//! ```
//!
//! It is also possible to skip all fields in an item or variant if desired:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! #[derive_where(Debug)]
//! #[derive_where(skip_inner)]
//! struct StructExample<T>(T);
//!
//! assert_eq!(format!("{:?}", StructExample(42)), "StructExample");
//!
//! #[derive_where(Debug)]
//! enum EnumExample<T> {
//! 	#[derive_where(skip_inner)]
//! 	A(T),
//! }
//!
//! assert_eq!(format!("{:?}", EnumExample::A(42)), "A");
//! ```
//!
//! Selective skipping of fields for certain traits is also an option, both in
//! `skip` and `skip_inner`:
//!
//! ```
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! #[derive_where(Debug, PartialEq)]
//! #[derive_where(skip_inner(Debug))]
//! struct Example<T>(i32, PhantomData<T>);
//!
//! assert_eq!(format!("{:?}", Example(42, PhantomData::<()>)), "Example");
//! assert_ne!(
//! 	Example(42, PhantomData::<()>),
//! 	Example(0, PhantomData::<()>)
//! );
//! ```
//!
//! ## `Zeroize` options
//!
//! [`Zeroize`] has two options:
//! - `crate`: an item-level option which specifies a path to the `zeroize`
//!   crate in case of a re-export or rename.
//! - `fqs`: a field -level option which will use fully-qualified-syntax instead
//!   of calling the [`zeroize`][`method@zeroize`] method on `self` directly.
//!   This is to avoid ambiguity between another method also called `zeroize`.
//!
//! ```
//! # #[cfg(feature = "zeroize")]
//! # {
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! # use zeroize_::Zeroize;
//! # // Fake `Zeroize` implementation because this crate doesn't have access to
//! # // the zeroize crate because of MSRV.
//! # mod zeroize_ {
//! # 	pub trait Zeroize {
//! # 		fn zeroize(&mut self);
//! # 	}
//! # 	impl Zeroize for i32 {
//! # 		fn zeroize(&mut self) {
//! # 			*self = 0;
//! # 		}
//! # 	}
//! # }
//! #[derive_where(Zeroize(crate = "zeroize_"))]
//! struct Example(#[derive_where(Zeroize(fqs))] i32);
//!
//! impl Example {
//! 	// If we didn't specify the `fqs` option, this would lead to a compile
//! 	//error because of method ambiguity.
//! 	fn zeroize(&mut self) {
//! 		self.0 = 1;
//! 	}
//! }
//!
//! let mut test = Example(42);
//!
//! // Will call the struct method.
//! test.zeroize();
//! assert_eq!(test.0, 1);
//!
//! // WIll call the `Zeroize::zeroize` method.
//! Zeroize::zeroize(&mut test);
//! assert_eq!(test.0, 0);
//! # }
//! ```
//!
//! ## `ZeroizeOnDrop` options
//!
//! If the `zeroize-on-drop` feature is enabled, it implements [`ZeroizeOnDrop`]
//! and can be implemented without [`Zeroize`], otherwise it only implements
//! [`Drop`] and requires [`Zeroize`] to be implemented.
//!
//! [`ZeroizeOnDrop`] has one option:
//! - `crate`: an item-level option which specifies a path to the `zeroize`
//!   crate in case of a re-export or rename.
//!
//! ```
//! # #[cfg(feature = "zeroize-on-drop")]
//! # {
//! # use std::marker::PhantomData;
//! # use derive_where::derive_where;
//! # // Fake `ZeroizeOnDrop` implementation because this crate doesn't have access to
//! # // the zeroize crate because of MSRV.
//! # mod zeroize_ {
//! # 	pub trait ZeroizeOnDrop: Drop {}
//! #
//! # 	pub mod __internal {
//! # 		pub trait AssertZeroizeOnDrop {
//! # 			fn zeroize_or_on_drop(&mut self);
//! # 		}
//! #
//! # 		pub trait AssertZeroize {
//! # 			fn zeroize_or_on_drop(&mut self);
//! # 		}
//! #
//! # 		impl AssertZeroize for i32 {
//! # 			fn zeroize_or_on_drop(&mut self) {}
//! # 		}
//! # 	}
//! # }
//! #[derive_where(ZeroizeOnDrop(crate = "zeroize_"))]
//! struct Example(i32);
//!
//! assert!(core::mem::needs_drop::<Example>());
//! # }
//! ```
//!
//! ## Supported traits
//!
//! The following traits can be derived with derive-where:
//! - [`Clone`]
//! - [`Copy`]
//! - [`Debug`]
//! - [`Default`]
//! - [`Eq`]
//! - [`Hash`]
//! - [`Ord`]
//! - [`PartialEq`]
//! - [`PartialOrd`]
//! - [`Zeroize`]: Only available with the `zeroize` crate feature.
//! - [`ZeroizeOnDrop`]: Only available with the `zeroize` crate feature. If the
//!   `zeroize-on-drop` feature is enabled, it implements [`ZeroizeOnDrop`],
//!   otherwise it only implements [`Drop`].
//!
//! ## Supported items
//!
//! Structs, tuple structs, unions and enums are supported. Derive-where tries
//! it's best to discourage usage that could be covered by std's `derive`. For
//! example unit structs and enums only containing unit variants aren't
//! supported.
//!
//! Unions only support [`Clone`] and [`Copy`].
//!
//! ## `no_std` support
//!
//! `no_std` support is provided by default.
//!
//! # Crate features
//!
//! - `nightly`: Implements [`Ord`] and [`PartialOrd`] with the help of
//!   [`core::intrinsics::discriminant_value`], which is what Rust does by
//!   default too. Without this feature [`transmute`](core::mem::transmute) is
//!   used to convert [`Discriminant`](core::mem::Discriminant) to a [`i32`],
//!   which is the underlying type.
//! - `safe`: Implements [`Ord`] and [`PartialOrd`] manually. This is much
//!   slower, but might be preferred if you don't trust derive-where. It also
//!   replaces all cases of [`core::hint::unreachable_unchecked`] in [`Ord`],
//!   [`PartialEq`] and [`PartialOrd`], which is what std uses, with
//!   [`unreachable`].
//! - `zeroize`: Allows deriving [`Zeroize`] and [`method@zeroize`] on [`Drop`].
//! - `zeroize-on-drop`: Allows deriving [`Zeroize`] and [`ZeroizeOnDrop`] and
//!   requires [zeroize] v1.5.0.
//!
//! # MSRV
//!
//! The current MSRV is 1.34 and is being checked by the CI. A change will be
//! accompanied by a minor version bump. If MSRV is important to you, use
//! `derive-where = "~1.x"` to pin a specific minor version to your crate.
//!
//! # Alternatives
//!
//! [derivative](https://crates.io/crates/derivative)
//! ([![Crates.io](https://img.shields.io/crates/v/derivative.svg)](https://crates.io/crates/derivative))
//! is a great alternative with many options. Notably it doesn't support
//! `no_std` and requires an extra `#[derive(Derivative)]` to use.
//!
//! # Changelog
//!
//! See the [CHANGELOG] file for details.
//!
//! # License
//!
//! Licensed under either of
//!
//! - Apache License, Version 2.0 ([LICENSE-APACHE] or <http://www.apache.org/licenses/LICENSE-2.0>)
//! - MIT license ([LICENSE-MIT] or <http://opensource.org/licenses/MIT>)
//!
//! at your option.
//!
//! ## Contribution
//!
//! Unless you explicitly state otherwise, any contribution intentionally
//! submitted for inclusion in the work by you, as defined in the Apache-2.0
//! license, shall be dual licensed as above, without any additional terms or
//! conditions.
//!
//! [CHANGELOG]: https://github.com/ModProg/derive-where/blob/main/CHANGELOG.md
//! [LICENSE-MIT]: https://github.com/ModProg/derive-where/blob/main/LICENSE-MIT
//! [LICENSE-APACHE]: https://github.com/ModProg/derive-where/blob/main/LICENSE-APACHE
//! [zeroize]: https://crates.io/crates/zeroize/1.5.0
//! [`Debug`]: core::fmt::Debug
//! [`Default`]: core::default::Default
//! [`Hash`]: core::hash::Hash
//! [`Zeroize`]: https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html
//! [`ZeroizeOnDrop`]: https://docs.rs/zeroize/1.5.0/zeroize/trait.ZeroizeOnDrop.html
//! [`method@zeroize`]: https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html#tymethod.zeroize
//! [#27]: https://github.com/ModProg/derive-where/issues/27

// MSRV: needed to support a lower MSRV.
extern crate proc_macro;

mod attr;
mod data;
mod error;
mod input;
mod item;
#[cfg(test)]
mod test;
mod trait_;
mod util;

use std::{borrow::Cow, iter};

use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
	spanned::Spanned, Attribute, DataEnum, DataStruct, DataUnion, DeriveInput, Fields, FieldsNamed,
	FieldsUnnamed, Generics, Variant,
};

#[cfg(feature = "zeroize")]
use self::attr::ZeroizeFqs;
use self::{
	attr::{Default, DeriveTrait, DeriveWhere, FieldAttr, ItemAttr, Skip, VariantAttr},
	data::{Data, DataType, Field, SimpleType},
	error::Error,
	input::Input,
	item::Item,
	trait_::{Trait, TraitImpl},
	util::Either,
};

/// Name of the `derive_where` proc-macro.
const DERIVE_WHERE: &str = "derive_where";
/// Name of the `derive_where_visited` proc-macro.
const DERIVE_WHERE_VISITED: &str = "derive_where_visited";

/// Item-level options:
/// - `#[derive_where(Clone, ..; T, ..)]`: Specify traits to implement and
///   optionally bounds.
///   - `#[derive_where(Zeroize(crate = "path"))]`: Specify path to [`Zeroize`]
///     trait.
///   - `#[derive_where(ZeroizeOnDrop(crate = "path"))]`: Specify path to
///     [`ZeroizeOnDrop`] trait.
/// - `#[derive_where(skip_inner(Clone, ..))]`: Skip all fields in the item.
///   Optionally specify traits to constrain skipping fields. Only works for
///   structs, for enums use this on the variant-level.
///
/// Variant-level options:
/// - `#[derive_where(default)]`: Uses this variant as the default for the
///   [`Default`](core::default::Default) implementation.
/// - `#[derive_where(skip_inner(Clone, ..))]`: Skip all fields in this variant.
///   Optionally specify traits to constrain skipping fields.
///
/// Field-level options:
/// - `#[derive_where(skip(Clone, ...))]`: Skip field. Optionally specify traits
///   to constrain skipping field.
/// - `#[derive_where(Zeroize(fqs))]`: Use fully-qualified-syntax when
///   implementing [`Zeroize`].
///
/// See the [crate](crate) level description for more details.
///
/// [`Zeroize`]: https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html
/// [`ZeroizeOnDrop`]: https://docs.rs/zeroize/latest/zeroize/trait.ZeroizeOnDrop.html
#[proc_macro_attribute]
#[cfg_attr(feature = "nightly", allow_internal_unstable(core_intrinsics))]
pub fn derive_where(
	attr: proc_macro::TokenStream,
	original_input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
	let attr: TokenStream = attr.into();
	let input: TokenStream = original_input.clone().into();
	let input = quote! {
		#[derive_where(#attr)]
		#input
	};

	let item = match syn::parse2::<DeriveInput>(input) {
		Ok(item) => item,
		Err(error) => {
			return iter::once(original_input)
				.chain(iter::once(proc_macro::TokenStream::from(
					error.into_compile_error(),
				)))
				.collect();
		}
	};

	let mut cleaned_item = input_without_derive_where_attributes(item.clone());
	let span = cleaned_item.span();

	match { Input::from_input(span, &item) } {
		Ok(Input {
			derive_where_visited,
			derive_wheres,
			generics,
			item,
		}) => {
			cleaned_item
				.attrs
				.push(syn::parse_quote! { #[#derive_where_visited] });

			iter::once(cleaned_item.into_token_stream())
				.chain(
					derive_wheres
						.iter()
						.flat_map(|derive_where| {
							iter::repeat(derive_where).zip(&derive_where.traits)
						})
						.map(|(derive_where, trait_)| {
							generate_impl(derive_where, trait_, &item, generics)
						}),
				)
				.collect::<TokenStream>()
				.into()
		}
		Err(error) => iter::once(cleaned_item.into_token_stream())
			.chain(iter::once(error.into_compile_error()))
			.collect::<TokenStream>()
			.into(),
	}
}

/// Marker attribute signifying that this item was already processed by a
/// `derive_where` attribute before. This should prevent users to wrongly use a
/// qualified path for a `derive_where` attribute except the first one.
#[doc(hidden)]
#[proc_macro_attribute]
pub fn derive_where_visited(
	_attr: proc_macro::TokenStream,
	input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
	// No-op, just here to mark the item as visited.
	input
}

/// Generate implementation for a [`Trait`].
fn generate_impl(
	derive_where: &DeriveWhere,
	trait_: &DeriveTrait,
	item: &Item,
	generics: &Generics,
) -> TokenStream {
	let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
	let mut where_clause = where_clause.map(Cow::Borrowed);
	derive_where.where_clause(&mut where_clause, trait_, item);

	let body = generate_body(trait_, item);

	let ident = item.ident();
	let path = trait_.impl_path(trait_);
	let mut output = quote! {
		impl #impl_generics #path for #ident #type_generics
		#where_clause
		{
			#body
		}
	};

	if let Some((path, body)) = trait_.additional_impl(trait_) {
		output.extend(quote! {
			impl #impl_generics #path for #ident #type_generics
			#where_clause
			{
				#body
			}
		})
	}

	output
}

/// Generate implementation method body for a [`Trait`].
fn generate_body(trait_: &DeriveTrait, item: &Item) -> TokenStream {
	match &item {
		Item::Item(data) => {
			let body = trait_.build_body(trait_, data);
			trait_.build_signature(item, trait_, &body)
		}
		Item::Enum { variants, .. } => {
			let body: TokenStream = variants
				.iter()
				.map(|data| trait_.build_body(trait_, data))
				.collect();

			trait_.build_signature(item, trait_, &body)
		}
	}
}

/// Removes `derive_where` attributes from the item and all fields and variants.
///
/// This is necessary because Rust currently does not support helper attributes
/// for attribute proc-macros and therefore doesn't automatically remove them.
fn input_without_derive_where_attributes(mut input: DeriveInput) -> DeriveInput {
	use syn::Data;
	let DeriveInput { data, attrs, .. } = &mut input;

	/// Remove all `derive_where` attributes.
	fn remove_derive_where(attrs: &mut Vec<Attribute>) {
		let ident = Ident::new("derive_where", Span::call_site());
		attrs.retain(|attr| !attr.path.is_ident(&ident))
	}

	/// Remove all `derive_where` attributes from [`FieldsNamed`].
	fn remove_derive_where_from_fields_named(fields: &mut FieldsNamed) {
		let FieldsNamed { named, .. } = fields;
		named
			.iter_mut()
			.for_each(|field| remove_derive_where(&mut field.attrs))
	}

	/// Remove all `derive_where` attributes from [`Fields`].
	fn remove_derive_where_from_fields(fields: &mut Fields) {
		match fields {
			Fields::Named(fields) => remove_derive_where_from_fields_named(fields),
			Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => unnamed
				.iter_mut()
				.for_each(|field| remove_derive_where(&mut field.attrs)),
			Fields::Unit => (),
		}
	}

	// Remove `derive_where` attributes from the item.
	remove_derive_where(attrs);

	// Remove `derive_where` attributes from variants or fields.
	match data {
		Data::Struct(DataStruct { fields, .. }) => remove_derive_where_from_fields(fields),
		Data::Enum(DataEnum { variants, .. }) => {
			variants
				.iter_mut()
				.for_each(|Variant { attrs, fields, .. }| {
					remove_derive_where(attrs);
					remove_derive_where_from_fields(fields)
				})
		}
		Data::Union(DataUnion { fields, .. }) => remove_derive_where_from_fields_named(fields),
	}

	input
}