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
//! Realia provides attribute macros for conditional compilation,
//! analogous to `#[cfg(...)]` and `#[cfg_attr(...)]`.

#![allow(clippy::needless_doctest_main)]

extern crate proc_macro;

mod attr;
mod dep;
mod expr;
mod metadata;

use crate::attr::Then;
use crate::expr::Expr;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use quote::quote;
use syn::{parse_macro_input, ItemFn, Result};

/// Checks whether an environment variable is defined and optionally
/// what value it has.
///
/// If you use this attribute, your project should include a `build.rs` that
/// triggers a rebuild when any environment variables of interest change:
///
/// ```
/// fn main() {
///     // Necessary when using #[realia::env("FOO")]
///     println!("cargo:rerun-if-env-changed=FOO");
/// }
/// ```
///
/// # Example
/// ```
/// #[realia::env("CI")]
/// fn example() {
///     println!("CI is defined");
/// }
/// ```
///
/// ```
/// #[realia::env("CI", "true")]
/// fn example() {
///     println!("CI is set to true");
/// }
/// ```
#[proc_macro_attribute]
pub fn env(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("env", args, input)
}

/// Checks whether an executable exists on the `PATH`.
///
/// If you use this attribute, your project should include a `build.rs` that
/// triggers a rebuild when the `PATH` environment variable changes:
///
/// ```
/// fn main() {
///     println!("cargo:rerun-if-env-changed=PATH");
/// }
/// ```
///
/// # Example
/// ```
/// #[realia::cmd("git")]
/// fn example() {
///     println!("Git is installed and available");
/// }
/// ```
#[proc_macro_attribute]
pub fn cmd(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("cmd", args, input)
}

/// Checks whether a crate has a certain dependency and optionally if that
/// dependency is a certain version.
///
/// The first argument is an "anchor crate", which should generally be your crate.
/// Since this functionality is implemented by checking the output of
/// `cargo metadata --manifest-path $CARGO_MANIFEST_DIR/Cargo.toml`,
/// the anchor is used to ensure consistent results when `$CARGO_MANIFEST_DIR`
/// changes (e.g., when building your crate directly vs when building a downstream crate).
///
/// This accounts for target-specific dependencies, but currently ignores any
/// optional dependencies enabled by features.
///
/// # Example
/// ```
/// #[realia::dep("realia", "syn")]
/// fn example() {
///     println!("Realia depends on Syn");
/// }
/// ```
///
/// ```
/// #[realia::dep("realia", "syn", "1.0.34")]
/// fn example() {
///     println!("Realia uses Syn 1.0.34 exactly");
/// }
/// ```
#[proc_macro_attribute]
pub fn dep(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("dep", args, input)
}

/// Checks whether a crate has a certain dependency at or above a certain version.
///
/// The first argument is an "anchor crate", which should generally be your crate.
/// Since this functionality is implemented by checking the output of
/// `cargo metadata --manifest-path $CARGO_MANIFEST_DIR/Cargo.toml`,
/// the anchor is used to ensure consistent results when `$CARGO_MANIFEST_DIR`
/// changes (e.g., when building your crate directly vs when building a downstream crate).
///
/// This accounts for target-specific dependencies, but currently ignores any
/// optional dependencies enabled by features.
///
/// # Example
/// ```
/// #[realia::dep_since("realia", "syn", "1.0.34")]
/// fn example() {
///     println!("Realia uses Syn 1.0.34 or newer");
/// }
/// ```
#[proc_macro_attribute]
pub fn dep_since(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("dep_since", args, input)
}

/// Checks whether a crate has a certain dependency below a certain version.
///
/// The first argument is an "anchor crate", which should generally be your crate.
/// Since this functionality is implemented by checking the output of
/// `cargo metadata --manifest-path $CARGO_MANIFEST_DIR/Cargo.toml`,
/// the anchor is used to ensure consistent results when `$CARGO_MANIFEST_DIR`
/// changes (e.g., when building your crate directly vs when building a downstream crate).
///
/// This accounts for target-specific dependencies, but currently ignores any
/// optional dependencies enabled by features.
///
/// # Example
/// ```
/// #[realia::dep_before("realia", "syn", "1.0.34")]
/// fn example() {
///     println!("Realia uses Syn 1.0.33 or older");
/// }
/// ```
#[proc_macro_attribute]
pub fn dep_before(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("dep_before", args, input)
}

/// Checks whether a crate has a certain dependency installed from the registry
/// (as opposed to being a Git dependency or a path dependency). This is useful
/// if you have non-registry dependencies with a
/// [registry fallback for publishing](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#multiple-locations).
///
/// The first argument is an "anchor crate", which should generally be your crate.
/// Since this functionality is implemented by checking the output of
/// `cargo metadata --manifest-path $CARGO_MANIFEST_DIR/Cargo.toml`,
/// the anchor is used to ensure consistent results when `$CARGO_MANIFEST_DIR`
/// changes (e.g., when building your crate directly vs when building a downstream crate).
///
/// This accounts for target-specific dependencies, but currently ignores any
/// optional dependencies enabled by features.
///
/// # Example
/// ```
/// #[realia::dep_from_registry("realia", "syn")]
/// fn example() {
///     println!("Realia uses Syn from the registry");
/// }
/// ```
#[proc_macro_attribute]
pub fn dep_from_registry(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("dep_from_registry", args, input)
}

/// Inverts another condition.
///
/// # Example
/// ```
/// #[realia::not(cmd("git"))]
/// fn example() {
///     println!("Git is not installed");
/// }
/// ```
#[proc_macro_attribute]
pub fn not(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("not", args, input)
}

/// Checks if at least one of multiple conditions is met.
///
/// # Example
/// ```
/// #[realia::any(cmd("git"), cmd("hg"))]
/// fn example() {
///     println!("Some version control is available");
/// }
/// ```
#[proc_macro_attribute]
pub fn any(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("any", args, input)
}

/// Checks if multiple conditions are met.
///
/// # Example
/// ```
/// #[realia::all(cmd("git"), env("GIT_AUTHOR_NAME"))]
/// fn example() {
///     println!("Git is available and GIT_AUTHOR_NAME is defined");
/// }
/// ```
#[proc_macro_attribute]
pub fn all(args: TokenStream, input: TokenStream) -> TokenStream {
    cfg("all", args, input)
}

fn cfg(top: &str, args: TokenStream, input: TokenStream) -> TokenStream {
    match try_cfg(top, args, input) {
        Ok(tokens) => tokens,
        Err(err) => TokenStream::from(err.to_compile_error()),
    }
}

fn try_cfg(top: &str, args: TokenStream, input: TokenStream) -> Result<TokenStream> {
    let args = TokenStream2::from(args);
    let top = Ident::new(top, Span::call_site());

    let mut full_args = quote!(#top);
    if !args.is_empty() {
        full_args.extend(quote!((#args)));
    }

    let expr: Expr = syn::parse2(full_args)?;

    if expr.eval() {
        Ok(input)
    } else {
        Ok(TokenStream::new())
    }
}

/// Applies an attribute when the condition is met.
/// You can also specify `const` this way.
///
/// # Example
/// ```
/// #[test]
/// #[realia::attr(not(cmd("git")), ignore)]
/// fn some_test_that_requires_git() {}
/// ```
///
/// ```
/// #[realia::attr(env("USE_CONST_FN"), const)]
/// fn this_becomes_const() {}
/// ```
#[proc_macro_attribute]
pub fn attr(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as attr::Args);

    match try_attr(args, input) {
        Ok(tokens) => tokens,
        Err(err) => TokenStream::from(err.to_compile_error()),
    }
}

fn try_attr(args: attr::Args, input: TokenStream) -> Result<TokenStream> {
    if !args.condition.eval() {
        return Ok(input);
    }

    match args.then {
        Then::Const(const_token) => {
            let mut input: ItemFn = syn::parse(input)?;
            input.sig.constness = Some(const_token);
            Ok(TokenStream::from(quote!(#input)))
        }
        Then::Attribute(then) => {
            let input = TokenStream2::from(input);
            Ok(TokenStream::from(quote! {
                #[cfg_attr(all(), #then)]
                #input
            }))
        }
    }
}