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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
// Lint advocates use of bool::then_some, stablizied in rustc 1.62.0
//! # Impl-tools
//!
//! [`#[autoimpl]`](macro@autoimpl) is an alternative to
//! [`#[derive]`](macro@derive) with more features (also usable on traits).
//!
//! [`#[impl_default]`](macro@impl_default) is an alternative to
//! `#[derive(Default)]` supporting field initializers.
//!
//! [`#[impl_self]`](macro@impl_self) provides `impl Self` syntax, avoiding the
//! need to repeat generics when writing impls on a local type definition.
//! This supercedes [`impl_scope!`] (except regarding [`macro@impl_default`]).
//!
//! [`impl_anon!`] is a function-like macro used to define and instantiate a
//! unique (single-use) type. It supports everything supported by [`impl_scope!`]
//! plus field initializers and (limited) automatic typing of fields.
//!
//! User-extensions to both [`#[autoimpl]`](macro@autoimpl) and [`macro@impl_self`]
//! are possible with a custom proc-macro crate depending on
//! [impl-tools-lib](https://crates.io/crates/impl-tools-lib).
doctest!;
extern crate proc_macro;
use ;
use TokenStream;
use ;
use parse_macro_input;
use ;
/// Impl [`Default`] with given field or type initializers
///
/// This macro may be used in one of two ways.
///
/// NOTE: this macro is already partially obsolete since Rust 1.62 added support
/// for [default enum variants](https://blog.rust-lang.org/2022/06/30/Rust-1.62.0/#default-enum-variants).
/// Once [RFC 3681](https://github.com/rust-lang/rfcs/pull/3681) (default field values)
/// is stable in this crate's MSRV, this macro will be deprecated.
///
/// ### Type-level initializer
///
/// ```
/// # use impl_tools::impl_default;
/// /// A simple enum; default value is Blue
/// #[impl_default(Colour::Blue)]
/// enum Colour {
/// Red,
/// Green,
/// Blue,
/// }
///
/// fn main() {
/// assert!(matches!(Colour::default(), Colour::Blue));
/// }
/// ```
///
/// A where clause is optional: `#[impl_default(EXPR where BOUNDS)]`.
///
/// ### Field-level initializer
///
/// This variant only supports structs. Fields specified as `name: type = expr`
/// will be initialized with `expr`, while other fields will be initialized with
/// `Default::default()`.
///
/// ```
/// # use impl_tools::{impl_default, impl_scope};
/// impl_scope! {
/// #[impl_default]
/// struct Person {
/// name: String = "Jane Doe".to_string(),
/// age: u32 = 72,
/// occupation: String,
/// }
/// }
///
/// fn main() {
/// let person = Person::default();
/// assert_eq!(person.name, "Jane Doe");
/// assert_eq!(person.age, 72);
/// assert_eq!(person.occupation, "");
/// }
/// ```
///
/// A where clause is optional: `#[impl_default(where BOUNDS)]`.
/// An alternative to the standard [`macro@derive`] macro
///
/// This macro may be used:
///
/// - [On a type definition](#on-type-definitions), to implement a specified trait
/// - [On a trait definition](#on-trait-definitions), to implement the trait for specified types
/// supporting [`Deref`]
///
/// # On type definitions
///
/// `#[autoimpl]` on type definitions functions similarly to [`#[derive]`](macro@derive). The differences are as follows.
///
/// There is no implied bound on generic parameters. Instead, bounds must be specified explicitly, using syntax like `where T: Clone`. The special syntax `where T: trait` may be used where `trait` desugars to the target trait for each implementation. An example:
/// ```
/// # use impl_tools::autoimpl;
/// #[autoimpl(Clone, Debug where T: trait)]
/// struct Wrapper<T>(pub T);
/// ```
///
/// ### `ignore`
///
/// Traits like [`Debug`] may be implemented while `ignore`-ing some fields, for example:
/// ```
/// # use impl_tools::autoimpl;
/// #[autoimpl(Debug ignore self.f)]
/// struct PairWithFn<T> {
/// x: f32,
/// y: f32,
/// f: fn(&T),
/// }
/// ```
///
/// ### `using`
///
/// Traits like [`Deref`] may be implemented by `using` a named field, for example:
/// ```
/// # use impl_tools::autoimpl;
/// #[autoimpl(Deref, DerefMut using self.1)]
/// struct AnnotatedWrapper<T>(String, T);
/// ```
/// In the above example, [`Deref::Target`] will be implemented as `T` (the type
/// of the field `self.1`). The `Target` type may instead be specified explicitly:
/// ```
/// # use impl_tools::autoimpl;
/// #[autoimpl(Deref<Target = T> using self.0)]
/// struct MyBoxingWrapper<T: ?Sized>(Box<T>);
/// ```
///
/// ## Supported traits
///
/// | Path | *ignore* | *using* | *notes* |
/// |----- |--- |--- |--- |
/// | [`::core::borrow::Borrow<T>`] | - | borrow target | `T` is type of target field |
/// | [`::core::borrow::BorrowMut<T>`] | - | borrow target | `T` is type of target field |
/// | [`::core::clone::Clone`] | yes | - | ignored fields use `Default::default()` |
/// | [`::core::cmp::Eq`] | * | - | *allowed with `PartialEq` |
/// | [`::core::cmp::Ord`] | yes | - | |
/// | [`::core::cmp::PartialEq`] | yes | - | |
/// | [`::core::cmp::PartialOrd`] | yes | - | |
/// | [`::core::convert::AsRef<T>`] | - | ref target | `T` is type of target field |
/// | [`::core::convert::AsMut<T>`] | - | ref target | `T` is type of target field |
/// | [`::core::default::Default`] | - | - | [`macro@impl_default`] is a more flexible alternative |
/// | [`::core::fmt::Debug`] | yes | - | |
/// | [`::core::hash::Hash`] | yes | - | |
/// | [`::core::marker::Copy`] | * | - | *allowed with `Clone` |
/// | [`::core::ops::Deref`] | - | deref target | See [`Deref::Target` type](#dereftarget-type) below |
/// | [`::core::ops::DerefMut`] | - | deref target | |
///
/// Traits are matched using the path, as follows:
///
/// - Only the last component, e.g. `#[autoimpl(Clone)]`
/// - The full path with leading `::`, e.g. `#[autoimpl(::core::clone::Clone)]`
/// - The full path without leading `::`, e.g. `#[autoimpl(core::clone::Clone)]`
/// - The full path with/without leading `::`, using `std` instead of `core` or `alloc`,
/// e.g. `#[autoimpl(std::clone::Clone)]`
///
/// ## Parameter syntax
///
/// > _ParamsMulti_ :\
/// > ( _Trait_ ),+ _Using_? _Ignores_? _WhereClause_?
/// >
/// > _Using_ :\
/// > `using` `self` `.` _Member_
/// >
/// > _Ignores_ :\
/// > `ignore` ( `self` `.` _Member_ ),+
/// >
/// > _WhereClause_ :\
/// > `where` ( _WherePredicate_ ),*
///
/// **Targets:** each *Trait* listed is implemented for the annotated type.
///
///
/// # On trait definitions
///
/// `#[autoimpl]` on trait definitions generates an implementation of that trait
/// for the given targets. This functions using an implementation of [`Deref`]
/// (and, where required, [`DerefMut`]) to lower the target type to some other
/// type supporting the trait. We call this latter type the **definitive type**.
///
/// It is required that the target type(s) implemented are generic over some
/// type parameter(s). These generic parameters are introduced using `for<..>`.
/// It is further required that at least one generic parameter has a bound on
/// `trait`; the first such parameter is inferred to be the *definitive type*.
///
/// For example, the following usage implements `MyTrait` for targets `&T`,
/// `&mut T` and `Box<dyn MyTrait>` using definitive type `T`:
/// ```
/// # use impl_tools::autoimpl;
/// #[autoimpl(for<T: trait + ?Sized> &T, &mut T, Box<T>)]
/// trait MyTrait {
/// fn f(&self) -> String;
/// }
/// ```
/// The expansion for target `Box<T>` looks like:
/// ```
/// # trait MyTrait {
/// # fn f(&self) -> String;
/// # }
/// #[automatically_derived]
/// impl<T: MyTrait + ?Sized> MyTrait for Box<T> {
/// fn f(&self) -> String {
/// <T as MyTrait>::f(self)
/// }
/// }
/// ```
///
/// ## Generics
///
/// Traits using generics and trait items using generics are, for the most part,
/// supported.
///
/// Items with a where clause with a type bound on `Self` cannot be implemented
/// via [`Deref`] since the item is not guaranteed to exist on the definitive
/// type. Such items with a default implementation may be implemented using this
/// that default implementation, though this results in a warning by default
/// (requires feature "nightly-diagnostics").
/// In other cases an error is reported.
///
/// An example:
/// ```
/// # use impl_tools::autoimpl;
/// # use std::fmt::Debug;
/// #[autoimpl(for<'a, T> &'a T, &'a mut T, Box<T> where T: trait + ?Sized)]
/// trait G<V>
/// where
/// V: Debug,
/// {
/// fn g(&self) -> V;
///
/// fn s<X>(&self, f: impl Fn(V) -> X) -> X
/// where
/// Self: Sized,
/// {
/// f(self.g())
/// }
/// }
/// ```
///
/// ## Parameter syntax
///
/// > _ParamsTrait_ :\
/// > `for` _Generics_ ( _Type_ ),+ _WhereClause_?
///
/// [`Deref`]: std::ops::Deref
/// [`Deref::Target`]: std::ops::Deref::Target
/// [`DerefMut`]: std::ops::DerefMut
/// Implement a type with `impl Self` syntax
///
/// This macro facilitates definition of a type (struct, enum or union) plus
/// implementations via `impl Self { .. }` syntax: `Self` is expanded to the
/// type's name, including generics and bounds (as defined on the type).
///
/// Caveat: `rustfmt` can not yet format contents (see
/// [rustfmt#5254](https://github.com/rust-lang/rustfmt/issues/5254),
/// [rustfmt#5538](https://github.com/rust-lang/rustfmt/pull/5538)).
///
/// Note: this macro is largely redundant with the [`macro@impl_self`] macro,
/// the one exception being [`macro@impl_default`] support. This macro will be
/// deprecated simultaneously with [`macro@impl_default`].
///
/// ## Special attribute macros
///
/// Additionally, `impl_scope!` supports special attribute macros evaluated
/// within its scope:
///
/// - [`#[impl_default]`](macro@impl_default): implement [`Default`] using
/// field initializers (which are not legal syntax outside of `impl_scope!`)
///
/// Note: matching these macros within `impl_scope!` does not use path
/// resolution. Using `#[impl_tools::impl_default]` would resolve the variant
/// of this macro which *doesn't support* field initializers.
///
/// ## Syntax
///
/// > _ImplScope_ :\
/// > `impl_scope!` `{` _ScopeItem_ _ItemImpl_ * `}`
/// >
/// > _ScopeItem_ :\
/// > _ItemEnum_ | _ItemStruct_ | _ItemType_ | _ItemUnion_
///
/// That is, one type definition followed by a set of implementations.
/// Impls must take one of two forms:
///
/// - `impl Self { ... }` — generic parameters and bounds of the type are used
/// - `impl MyType { ... }` where `MyType` matches the name of the defined type
///
/// Generic parameters from the type are included implicitly with the first form.
/// Additional generic parameters and where clauses are supported (parameters
/// and bounds are merged).
///
/// ## Example
///
/// ```
/// impl_tools::impl_scope! {
/// struct Pair<T>(T, T);
///
/// impl Self {
/// pub fn new(a: T, b: T) -> Self {
/// Pair(a, b)
/// }
/// }
///
/// impl Self where T: Clone {
/// pub fn splat(a: T) -> Self {
/// let b = a.clone();
/// Pair(a, b)
/// }
/// }
/// }
/// ```
/// Construct an anonymous struct
///
/// Rust doesn't currently support [`impl Trait { ... }` expressions](https://github.com/canndrew/rfcs/blob/impl-trait-expressions/text/0000-impl-trait-expressions.md)
/// or implicit typing of struct fields. This macro is a **hack** allowing that.
///
/// Example:
/// ```
/// use std::fmt;
/// fn main() {
/// let world = "world";
/// let says_hello_world = impl_tools::impl_anon! {
/// struct(&'static str = world);
/// impl fmt::Display for Self {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "hello {}", self.0)
/// }
/// }
/// };
/// assert_eq!(format!("{}", says_hello_world), "hello world");
/// }
/// ```
///
/// That is, this macro creates an anonymous struct type (must be a struct),
/// which may have trait implementations, then creates an instance of that
/// struct.
///
/// Struct fields may have a fixed type or may be generic. Syntax is as follows:
///
/// - **regular struct:** `ident: ty = value`
/// - **regular struct:** `ident: ty` (uses `Default` to construct value)
/// - **regular struct:** `ident = value` (type is generic without bounds)
/// - **tuple struct:** `ty = value`
/// - **tuple struct:** `ty` (uses `Default` to construct value)
///
/// The field name, `ident`, may be `_` (anonymous field).
///
/// The field type, `ty`, may be or may contain inferred types (`_`) and/or
/// `impl Trait` type expressions. These are substituted with generics on the
/// type.
///
/// Refer to [examples](https://github.com/search?q=impl_anon+repo%3Akas-gui%2Fkas+path%3Aexamples&type=Code) for usage.
/// Implement a type with `impl Self` syntax
///
/// This attribute macro supports a type (struct, enum, type alias or union)
/// definition plus associated `impl` items within a `mod`.
///
/// Macro expansion discards the `mod` entirely, placing all contents into the
/// outer scope. This simplifies privacy rules in many use-cases, and highlights
/// that the usage of `mod` is purely a hack to make the macro input valid Rust
/// syntax (and thus compatible with `rustfmt`).
///
/// ## Syntax
///
/// > _ImplSelf_ :\
/// > `#[impl_self]` `mod` _Name_ `{` _ScopeItem_ _ItemImpl_ * `}`
/// >
/// > _ScopeItem_ :\
/// > _ItemEnum_ | _ItemStruct_ | _ItemType_ | _ItemUnion_
///
/// Here, _ItemEnum_, _ItemStruct_, _ItemType_ and _ItemUnion_ are `enum`,
/// `struct`, `type` alias and `union` definitions respectively. Whichever of
/// these is used, it must match the module name _Name_.
///
/// _ItemImpl_ is an `impl` item. It may use the standard implementation syntax
/// (e.g. `impl Debug for MyType { .. }`) or `impl Self` syntax (see below).
///
/// The `mod` may not contain any other items, except `doc` items (documentation
/// on the module itself is ignored in favour of documentation on the defined
/// type) and attributes (which apply as usual).
///
/// ### `impl Self` syntax
///
/// `impl Self` "syntax" is syntactically-valid (but not semantically-valid)
/// Rust syntax for writing inherent and trait `impl` blocks:
///
/// - `impl Self { ... }` — an inherent `impl` item on the defined type
/// - `impl Debug for Self { ... }` — a trait `impl` item on the defined type
///
/// Generic parameters and bounds are copied from the type definition.
/// Additional generic parameters may be specified; these extend the list of
/// generic parameters on the type itself, and thus must have distinct names.
/// Additional bounds (where clauses) may be specified; these extend the list of
/// bounds on the type itself.
///
/// ## Example
///
/// ```
/// #[impl_tools::impl_self]
/// mod Pair {
/// /// A pair of values of type `T`
/// pub struct Pair<T>(T, T);
///
/// impl Self {
/// pub fn new(a: T, b: T) -> Self {
/// Pair(a, b)
/// }
/// }
///
/// impl Self where T: Clone {
/// pub fn splat(a: T) -> Self {
/// let b = a.clone();
/// Pair(a, b)
/// }
/// }
/// }
/// ```