attr_alias 0.1.5

Reduce attribute repetition with aliases
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
//! This crate allows defining arbitrary aliases for attributes.
//!
//! Aliases are resolved by [`#[attr_alias]`][macro@attr_alias]. Since that
//! attribute requires a nightly compiler, [`#[eval]`][macro@eval] and
//! [`eval_block!`] provide workarounds for use on the stable release channel.
//!
//! # Alias File
//!
//! Due to how procedural macros work and to avoid redundancy, this crate will
//! always read aliases from
#![doc = concat!("\"", alias_file!(), "\".")]
//! Other files may be supported in future versions, but doing so is not
//! currently possible. Open an issue if this is important for your build.
//!
//! ## Syntax
//!
//! - Each alias must begin with `*` and be assigned a valid attribute value.
//! - Aliases can reference others, but referenced aliases must be listed
//!   first.
//!
//! ## Example
//!
//! ```ignore
#![doc = include_str!(concat!("../", alias_file!()))]
//! ```
//!
//! # Features
//!
//! These features are optional and can be enabled or disabled in a
//! "Cargo.toml" file.
//!
//! ### Nightly Features
//!
//! These features are unstable, since they rely on unstable Rust features.
//!
//! - **nightly** -
//!   Provides [`#[attr_alias]`][macro@attr_alias].
//!
//!   Also makes use of the following feature flags:
//!   - [proc\_macro\_tracked\_path]
//!
//! # Dependencies
//!
//! Although this is a proc\_macro crate, it does not depend on [proc\_macro2],
//! [quote], or [syn]. Therefore, its impact on compile time should be minimal.
//!
//! # Comparable Crates
//!
//! The following crates are similar but take different approaches. An overview
//! of benefits and downsides in comparison to this crate is provided for each
//! when expanded.
//!
//! <ul><li><details><summary>
//!
//! **[cfg\_aliases]** -
//! Aliases defined using "build.rs" instructions.
//!
//! </summary>
//!
//! - *Pros:*
//!     - Compile time may be reduced. The declarative macro is only used in
//!       the build file, but the build file must be compiled as well.
//!     - Inner attributes are supported without a nightly feature.
//! - *Cons:*
//!     - Only `#[cfg]` aliases can be defined.
//!     - Some configuration options are not supported (e.g., `test`).
//!     - Alias names are not checked at compile time.
//!     - Aliases are not expanded inline, as would be desirable for
//!       `#[doc(cfg)]`.
//!
//! </details></li><li><details><summary>
//!
//! **[macro\_rules\_attribute]** -
//! Aliases defined as declarative macros.
//!
//! </summary>
//!
//! - *Pros:*
//!     - Aliases are defined within Rust source files.
//!     - Aliases can expand to multiple attributes.
//!     - Declarative macros accepting valid Rust syntax can be used as
//!       attributes.
//! - *Cons:*
//!     - Attributes cannot be attached to statements without a nightly
//!       feature.
//!     - Inner attributes are not supported.
//!     - Aliases cannot be inserted at a specific part of an attribute
//!       (e.g., within `not()`).
//!     - Some dependencies are required, which may impact compile time.
//!
//! </details></li></ul>
//!
//! [cfg\_aliases]: https://crates.io/crates/cfg_aliases
//! [macro\_rules\_attribute]: https://crates.io/crates/macro_rules_attribute
//! [proc\_macro\_tracked\_path]: https://doc.rust-lang.org/unstable-book/library-features/proc-macro-tracked-path.html
//! [proc\_macro2]: https://crates.io/crates/proc_macro2
//! [quote]: https://crates.io/crates/quote
//! [syn]: https://crates.io/crates/syn

// Only require a nightly compiler when building documentation for docs.rs.
// This is a private option that should not be used.
// https://github.com/rust-lang/docs.rs/issues/147#issuecomment-389544407
#![cfg_attr(feature = "nightly", feature(doc_cfg))]
#![cfg_attr(feature = "nightly", feature(proc_macro_tracked_path))]
#![forbid(unsafe_code)]
#![warn(unused_results)]

use std::error;
use std::result;

#[cfg(feature = "nightly")]
use proc_macro::tracked;
use proc_macro::Delimiter;
use proc_macro::Group;
use proc_macro::Literal;
use proc_macro::Punct;
use proc_macro::Spacing;
use proc_macro::Span;
use proc_macro::TokenStream;
use proc_macro::TokenTree;

macro_rules! alias_file {
    () => {
        "src/attr-aliases.txt"
    };
}
use alias_file;

macro_rules! tokens {
    ( $($token:expr ,)+ ) => {{
        use proc_macro::TokenTree;

        [$(TokenTree::from($token)),+].into_iter()
    }};
}

macro_rules! path {
    ( $($name:expr),+ ) => {{
        use proc_macro::Ident;
        use proc_macro::Punct;
        use proc_macro::Spacing;
        use proc_macro::Span;

        tokens!(
            $(
                Punct::new(':', Spacing::Joint),
                Punct::new(':', Spacing::Alone),
                Ident::new($name, Span::call_site()),
            )+
        )
    }};
}

mod aliases;
use aliases::Aliases;

fn core_macro(name: &str, arg: &str) -> impl Iterator<Item = TokenTree> {
    path!("core", name).chain(tokens!(
        Punct::new('!', Spacing::Alone),
        Group::new(
            Delimiter::Parenthesis,
            TokenTree::Literal(Literal::string(arg)).into(),
        ),
        Punct::new(';', Spacing::Alone),
    ))
}

struct Error {
    span: Span,
    message: String,
}

impl Error {
    fn new(message: &'static str) -> Self {
        Self {
            span: Span::call_site(),
            message: message.to_owned(),
        }
    }

    fn token(token: &TokenTree) -> Self {
        Self {
            span: token.span(),
            message: "unexpected token".to_owned(),
        }
    }

    fn into_compile_error(self) -> TokenStream {
        core_macro("compile_error", &self.message)
            .map(|mut token| {
                token.set_span(self.span);
                token
            })
            .collect()
    }
}

type Result<T> = result::Result<T, Error>;

trait ResultExt<T> {
    fn wrap_err(self, message: &str) -> Result<T>;
}

impl<T, E> ResultExt<T> for result::Result<T, E>
where
    E: error::Error,
{
    fn wrap_err(self, message: &str) -> Result<T> {
        self.map_err(|error| Error {
            span: Span::call_site(),
            message: format!("{}: {}", message, error),
        })
    }
}

fn parse_empty<I>(tokens: I) -> Result<()>
where
    I: IntoIterator<Item = TokenTree>,
{
    tokens
        .into_iter()
        .next()
        .map(|x| Err(Error::token(&x)))
        .unwrap_or(Ok(()))
}

fn eval_item(item: TokenStream, resolved: &mut bool) -> Result<TokenStream> {
    let mut attr = false;
    item.into_iter()
        .map(|mut token| {
            if let TokenTree::Group(group) = &mut token {
                let delimiter = group.delimiter();
                let mut stream = group.stream();
                if attr && delimiter == Delimiter::Bracket {
                    *resolved |= Aliases::get()?.resolve(&mut stream)?;
                } else {
                    stream = eval_item(stream, resolved)?;
                }
                *group = Group::new(delimiter, stream);
            }
            attr = matches!(
                &token,
                TokenTree::Punct(x)
                    if x.as_char() == '#' || (attr && x.as_char() == '!'),
            );
            Ok(token)
        })
        .collect()
}

/// Resolves an alias using a pattern.
///
/// # Arguments
///
/// The following positional arguments are expected:
/// 1. *alias name* - required and must be a valid [Rust identifier]
/// 2. *expansion pattern* - optional and may include `*` wildcards
///     - The first wildcard in this pattern will be replaced with the expanded
///       alias.
///     - If not specified, this argument defaults to the value of the
///       "default" alias, or `*` if that alias is not defined.
///
/// For example, using the [example alias file], the annotations
/// `#[attr_alias(macos, cfg(*))]` and `#[attr_alias(macos)]` would both expand
/// to `#[cfg(target_os = "macos")]`.
///
/// # Examples
///
/// *Compiled using the [example alias file].*
///
/// ```
/// # #![feature(doc_cfg)]
/// #
/// use std::process::Command;
///
/// use attr_alias::attr_alias;
///
/// struct ProcessBuilder(Command);
///
/// impl ProcessBuilder {
///     #[attr_alias(macos_or_windows)]
///     #[attr_alias(macos_or_windows, doc(cfg(*)))]
///     fn name(&mut self, name: &str) -> &mut Self {
///         unimplemented!();
///     }
/// }
/// ```
///
/// [example alias file]: self#example
/// [Rust identifier]: https://doc.rust-lang.org/reference/identifiers.html
#[cfg(feature = "nightly")]
#[cfg_attr(feature = "nightly", doc(cfg(feature = "nightly")))]
#[proc_macro_attribute]
pub fn attr_alias(args: TokenStream, item: TokenStream) -> TokenStream {
    tracked::path(Aliases::FILE);

    Aliases::get()
        .and_then(|x| x.resolve_args(args))
        .map(|alias| {
            tokens!(
                Punct::new('#', Spacing::Joint),
                Group::new(Delimiter::Bracket, alias),
            )
            .chain(item)
            .collect()
        })
        .unwrap_or_else(Error::into_compile_error)
}

/// Equivalent to [`#[eval]`][macro@eval] but does not have restrictions on
/// where it can be attached.
///
/// # Examples
///
/// *Compiled using the [example alias file].*
///
/// Non-inline modules can be annotated:
///
/// ```
/// attr_alias::eval_block! {
///     #[attr_alias(macos, cfg_attr(*, path = "sys/macos.rs"))]
///     #[attr_alias(macos, cfg_attr(not(*), path = "sys/common.rs"))]
///     mod sys;
/// }
/// ```
#[cfg_attr(
    feature = "nightly",
    doc = "
Using [`#[eval]`][macro@eval] would require a nightly feature:

```
#![feature(proc_macro_hygiene)]

#[attr_alias::eval]
#[attr_alias(macos, cfg_attr(*, path = \"sys/macos.rs\"))]
#[attr_alias(macos, cfg_attr(not(*), path = \"sys/common.rs\"))]
mod sys;
```"
)]
///
/// [example alias file]: self#example
#[proc_macro]
pub fn eval_block(item: TokenStream) -> TokenStream {
    let mut resolved = false;
    let mut result = eval_item(item, &mut resolved)
        .unwrap_or_else(Error::into_compile_error);

    let trigger = if resolved {
        Aliases::create_trigger()
    } else {
        Err(Error::new("unnecessary attribute"))
    };
    match trigger {
        Ok(trigger) => result.extend(trigger),
        Err(error) => result.extend(error.into_compile_error()),
    }

    result
}

/// Resolves [`#[attr_alias]`][macro@attr_alias] attributes.
///
/// This attribute must be attached to a file-level item. It allows
/// [`#[attr_alias]`][macro@attr_alias] attributes within that item to be
/// resolved without nightly features.
///
/// # Errors
///
/// Errors will typically be clear, but for those that are not, they can be
/// interpreted as follows:
/// - *"cannot find attribute `attr_alias` in this scope"* -
///   The [`#[attr_alias]`][macro@attr_alias] attribute was used without this
///   attribute or importing it.
/// - *"`const` items in this context need a name"* -
///   This attribute was attached to an item that is not at the top level of a
///   file.
/// - *"non-inline modules in proc macro input are unstable"* ([E0658]) -
///   Due to the [proc\_macro\_hygiene] feature being unstable, [`eval_block!`]
///   should be used instead.
///
/// # Examples
///
/// *Compiled using the [example alias file].*
///
/// **Conditionally Defining a Method:**
///
/// ```
/// # #![cfg_attr(feature = "nightly", feature(doc_cfg))]
/// #
/// use std::process::Command;
///
/// struct ProcessBuilder(Command);
///
/// #[attr_alias::eval]
/// impl ProcessBuilder {
///     #[attr_alias(macos_or_windows)]
#[cfg_attr(
    feature = "nightly",
    doc = "    #[attr_alias(macos_or_windows, doc(cfg(*)))]"
)]
///     fn name(&mut self, name: &str) -> &mut Self {
///         unimplemented!();
///     }
/// }
/// ```
#[cfg_attr(
    feature = "nightly",
    doc = "
**Setting Lint Configuration:**

```
#![feature(custom_inner_attributes)]
# #![feature(prelude_import)]

#![attr_alias::eval]
#![attr_alias(warnings, *)]
```"
)]
///
/// [E0658]: https://doc.rust-lang.org/error_codes/E0658.html
/// [example alias file]: self#example
/// [proc\_macro\_hygiene]: https://doc.rust-lang.org/unstable-book/language-features/proc-macro-hygiene.html
#[proc_macro_attribute]
pub fn eval(args: TokenStream, item: TokenStream) -> TokenStream {
    if let Err(error) = parse_empty(args) {
        return error.into_compile_error();
    }

    eval_block(item)
}