macro-string 0.2.0

Eager evaluation of macros like `concat!` and `env!`
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
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
//! [![github]](https://github.com/dtolnay/macro-string) [![crates-io]](https://crates.io/crates/macro-string) [![docs-rs]](https://docs.rs/macro-string)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
//! This crate is a helper library for procedural macros to perform eager
//! evaluation of standard library string macros like `concat!` and `env!` in
//! macro input.
//!
//! <table><tr><td>
//! <b>Supported macros:</b>
//! <code>concat!</code>,
//! <code>env!</code>,
//! <code>include!</code>,
//! <code>include_str!</code>,
//! <code>stringify!</code>
//! </td></tr></table>
//!
//! For example, to implement a macro such as the following:
//!
//! ```
//! # macro_rules! include_json {
//! #     ($path:expr) => { $path };
//! # }
//! #
//! // Parses JSON at compile time and expands to a serde_json::Value.
//! let j = include_json!(concat!(env!("CARGO_MANIFEST_DIR"), "/manifest.json"));
//! ```
//!
//! the implementation of `include_json!` will need to parse and eagerly
//! evaluate the two macro calls within its input tokens.
//!
//! ```
//! # extern crate proc_macro;
//! #
//! use macro_string::MacroString;
//! use proc_macro::TokenStream;
//! use std::fs;
//! use syn::parse_macro_input;
//!
//! # const _: &str = stringify! {
//! #[proc_macro]
//! # };
//! pub fn include_json(input: TokenStream) -> TokenStream {
//!     let macro_string = parse_macro_input!(input as MacroString);
//!     let path = match macro_string.eval() {
//!         Ok(path) => path,
//!         Err(err) => return TokenStream::from(err.to_compile_error()),
//!     };
//!
//!     let content = match fs::read(&path) {
//!         Ok(content) => content,
//!         Err(err) => return TokenStream::from(macro_string.error(err).to_compile_error()),
//!     };
//!
//!     let json: serde_json::Value = match serde_json::from_slice(&content) {
//!         Ok(json) => json,
//!         Err(err) => return TokenStream::from(macro_string.error(err).to_compile_error()),
//!     };
//!
//!     /*TODO: print serde_json::Value to TokenStream*/
//!     # unimplemented!()
//! }
//! ```

#![doc(html_root_url = "https://docs.rs/macro-string/0.2.0")]

use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use std::env;
use std::fmt::Display;
use std::fs;
use std::path::{Component, Path, PathBuf};
use syn::parse::{Error, Parse, ParseBuffer, ParseStream, Parser, Result};
use syn::punctuated::Punctuated;
use syn::token::{Brace, Bracket, Paren};
use syn::{
    braced, bracketed, parenthesized, Ident, LitBool, LitChar, LitFloat, LitInt, LitStr, Token,
};

mod kw {
    syn::custom_keyword!(concat);
    syn::custom_keyword!(env);
    syn::custom_keyword!(include);
    syn::custom_keyword!(include_str);
    syn::custom_keyword!(stringify);
}

#[derive(Clone)]
pub struct MacroString {
    expr: Expr,
}

impl Parse for MacroString {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(MacroString {
            expr: input.call(Expr::parse_strict)?,
        })
    }
}

impl MacroString {
    /// Evaluate expression to string.
    ///
    /// # Errors
    ///
    /// Returns an error if the expression was syntactically valid (parsed
    /// successfully) but cannot be evaluated, for example because it refers to
    /// an `env!` for which the environment variable is not set, or an
    /// `include!` for which the file is not found.
    pub fn eval(&self) -> Result<String> {
        self.expr.eval()
    }

    /// Construct a compile error with a Span encompassing the macro string's
    /// original expression.
    ///
    /// ```compile_fail
    /// my_macro! {
    ///     resources = concat!(env!("CARGO_MANIFEST_DIR"), "/resources.json")
    /// }
    /// ```
    ///
    /// ```text
    /// error: No such file or directory (os error 2) - /path/to/manifest-dir/resources.json
    ///   --> example.rs:85:17
    ///    |
    /// 85 |     resources = concat!(env!("CARGO_MANIFEST_DIR"), "/resources.json")
    ///    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    /// ```
    pub fn error<T: Display>(&self, message: T) -> syn::Error {
        syn::Error::new_spanned(&self.expr, message)
    }
}

#[derive(Clone)]
enum Expr {
    LitStr(LitStr),
    LitChar(LitChar),
    LitInt(LitInt),
    LitFloat(LitFloat),
    LitBool(LitBool),
    Concat(Concat),
    Env(Env),
    Include(Include),
    IncludeStr(IncludeStr),
    Stringify(Stringify),
}

impl Expr {
    fn eval(&self) -> Result<String> {
        match self {
            Expr::LitStr(lit) => Ok(lit.value()),
            Expr::LitChar(lit) => Ok(lit.value().to_string()),
            Expr::LitInt(lit) => Ok(lit.base10_digits().to_owned()),
            Expr::LitFloat(lit) => Ok(lit.base10_digits().to_owned()),
            Expr::LitBool(lit) => Ok(lit.value.to_string()),
            Expr::Concat(expr) => {
                let mut concat = String::new();
                for arg in &expr.args {
                    concat += &arg.eval()?;
                }
                Ok(concat)
            }
            Expr::Env(expr) => {
                let key = expr.arg.eval()?;
                match env::var(&key) {
                    Ok(value) => Ok(value),
                    Err(err) => Err(Error::new_spanned(expr, err)),
                }
            }
            Expr::Include(expr) => {
                let path = expr.arg.eval()?;
                let content = fs_read(&expr, &path)?;
                let inner = Expr::parse_strict.parse_str(&content)?;
                inner.eval()
            }
            Expr::IncludeStr(expr) => {
                let path = expr.arg.eval()?;
                fs_read(&expr, &path)
            }
            Expr::Stringify(expr) => Ok(expr.tokens.to_string()),
        }
    }
}

fn fs_read(span: &dyn ToTokens, path: impl AsRef<Path>) -> Result<String> {
    let mut path = path.as_ref();
    if path.is_relative() {
        let name = span.to_token_stream().into_iter().next().unwrap();
        return Err(Error::new_spanned(
            span,
            format!("a relative path is not supported here; use `{name}!(concat!(env!(\"CARGO_MANIFEST_DIR\"), ...))`"),
        ));
    }

    // Make Windows verbatim paths work even with mixed path separators, which
    // can happen when a path is produced using `concat!`.
    let path_buf: PathBuf;
    if let Some(Component::Prefix(prefix)) = path.components().next() {
        if prefix.kind().is_verbatim() {
            path_buf = path.components().collect();
            path = &path_buf;
        }
    }

    match fs::read_to_string(path) {
        Ok(content) => Ok(content),
        Err(err) => Err(Error::new_spanned(
            span,
            format!("{} {}", err, path.display()),
        )),
    }
}

#[derive(Clone)]
struct Concat {
    name: kw::concat,
    bang_token: Token![!],
    delimiter: MacroDelimiter,
    args: Punctuated<Expr, Token![,]>,
}

#[derive(Clone)]
struct Env {
    name: kw::env,
    bang_token: Token![!],
    delimiter: MacroDelimiter,
    arg: Box<Expr>,
    trailing_comma: Option<Token![,]>,
}

#[derive(Clone)]
struct Include {
    name: kw::include,
    bang_token: Token![!],
    delimiter: MacroDelimiter,
    arg: Box<Expr>,
    trailing_comma: Option<Token![,]>,
}

#[derive(Clone)]
struct IncludeStr {
    name: kw::include_str,
    bang_token: Token![!],
    delimiter: MacroDelimiter,
    arg: Box<Expr>,
    trailing_comma: Option<Token![,]>,
}

#[derive(Clone)]
struct Stringify {
    name: kw::stringify,
    bang_token: Token![!],
    delimiter: MacroDelimiter,
    tokens: TokenStream,
}

#[derive(Clone)]
enum MacroDelimiter {
    Paren(Paren),
    Brace(Brace),
    Bracket(Bracket),
}

impl Expr {
    fn parse_strict(input: ParseStream) -> Result<Self> {
        Self::parse(input, false)
    }

    fn parse_any(input: ParseStream) -> Result<Self> {
        Self::parse(input, true)
    }

    fn parse(input: ParseStream, allow_nonstring_literals: bool) -> Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(LitStr) {
            let lit: LitStr = input.parse()?;
            if !lit.suffix().is_empty() {
                return Err(Error::new(
                    lit.span(),
                    "unexpected suffix on string literal",
                ));
            }
            Ok(Expr::LitStr(lit))
        } else if allow_nonstring_literals && input.peek(LitChar) {
            let lit: LitChar = input.parse()?;
            if !lit.suffix().is_empty() {
                return Err(Error::new(lit.span(), "unexpected suffix on char literal"));
            }
            Ok(Expr::LitChar(lit))
        } else if allow_nonstring_literals && input.peek(LitInt) {
            let lit: LitInt = input.parse()?;
            match lit.suffix() {
                "" | "i8" | "i16" | "i32" | "i64" | "i128" | "u8" | "u16" | "u32" | "u64"
                | "u128" | "f16" | "f32" | "f64" | "f128" => {}
                _ => {
                    return Err(Error::new(
                        lit.span(),
                        "unexpected suffix on integer literal",
                    ));
                }
            }
            Ok(Expr::LitInt(lit))
        } else if allow_nonstring_literals && input.peek(LitFloat) {
            let lit: LitFloat = input.parse()?;
            match lit.suffix() {
                "" | "f16" | "f32" | "f64" | "f128" => {}
                _ => return Err(Error::new(lit.span(), "unexpected suffix on float literal")),
            }
            Ok(Expr::LitFloat(lit))
        } else if allow_nonstring_literals && input.peek(LitBool) {
            input.parse().map(Expr::LitBool)
        } else if lookahead.peek(kw::concat) {
            input.parse().map(Expr::Concat)
        } else if lookahead.peek(kw::env) {
            input.parse().map(Expr::Env)
        } else if lookahead.peek(kw::include) {
            input.parse().map(Expr::Include)
        } else if lookahead.peek(kw::include_str) {
            input.parse().map(Expr::IncludeStr)
        } else if lookahead.peek(kw::stringify) {
            input.parse().map(Expr::Stringify)
        } else if input.peek(Ident) && input.peek2(Token![!]) && input.peek3(Paren) {
            let ident: Ident = input.parse()?;
            let bang_token: Token![!] = input.parse()?;
            let unsupported = quote!(#ident #bang_token);
            Err(Error::new_spanned(
                unsupported,
                "unsupported macro, expected one of: `concat!`, `env!`, `include!`, `include_str!`, `stringify!`",
            ))
        } else {
            Err(lookahead.error())
        }
    }
}

impl ToTokens for Expr {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            Expr::LitStr(expr) => expr.to_tokens(tokens),
            Expr::LitChar(expr) => expr.to_tokens(tokens),
            Expr::LitInt(expr) => expr.to_tokens(tokens),
            Expr::LitFloat(expr) => expr.to_tokens(tokens),
            Expr::LitBool(expr) => expr.to_tokens(tokens),
            Expr::Concat(expr) => expr.to_tokens(tokens),
            Expr::Env(expr) => expr.to_tokens(tokens),
            Expr::Include(expr) => expr.to_tokens(tokens),
            Expr::IncludeStr(expr) => expr.to_tokens(tokens),
            Expr::Stringify(expr) => expr.to_tokens(tokens),
        }
    }
}

macro_rules! macro_delimiter {
    ($var:ident in $input:ident) => {{
        let (delim, content) = $input.call(macro_delimiter)?;
        $var = content;
        delim
    }};
}

fn macro_delimiter(input: ParseStream) -> Result<(MacroDelimiter, ParseBuffer)> {
    let content;
    let lookahead = input.lookahead1();
    let delim = if input.peek(Paren) {
        MacroDelimiter::Paren(parenthesized!(content in input))
    } else if input.peek(Brace) {
        MacroDelimiter::Brace(braced!(content in input))
    } else if input.peek(Bracket) {
        MacroDelimiter::Bracket(bracketed!(content in input))
    } else {
        return Err(lookahead.error());
    };
    Ok((delim, content))
}

impl MacroDelimiter {
    fn surround<F>(&self, tokens: &mut TokenStream, f: F)
    where
        F: FnOnce(&mut TokenStream),
    {
        match self {
            MacroDelimiter::Paren(delimiter) => delimiter.surround(tokens, f),
            MacroDelimiter::Brace(delimiter) => delimiter.surround(tokens, f),
            MacroDelimiter::Bracket(delimiter) => delimiter.surround(tokens, f),
        }
    }
}

impl Parse for Concat {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(Concat {
            name: input.parse()?,
            bang_token: input.parse()?,
            delimiter: macro_delimiter!(content in input),
            args: Punctuated::parse_terminated_with(&content, Expr::parse_any)?,
        })
    }
}

impl ToTokens for Concat {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.name.to_tokens(tokens);
        self.bang_token.to_tokens(tokens);
        self.delimiter
            .surround(tokens, |tokens| self.args.to_tokens(tokens));
    }
}

impl Parse for Env {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(Env {
            name: input.parse()?,
            bang_token: input.parse()?,
            delimiter: macro_delimiter!(content in input),
            arg: Expr::parse_strict(&content).map(Box::new)?,
            trailing_comma: content.parse()?,
        })
    }
}

impl ToTokens for Env {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.name.to_tokens(tokens);
        self.bang_token.to_tokens(tokens);
        self.delimiter.surround(tokens, |tokens| {
            self.arg.to_tokens(tokens);
            self.trailing_comma.to_tokens(tokens);
        });
    }
}

impl Parse for Include {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(Include {
            name: input.parse()?,
            bang_token: input.parse()?,
            delimiter: macro_delimiter!(content in input),
            arg: Expr::parse_strict(&content).map(Box::new)?,
            trailing_comma: content.parse()?,
        })
    }
}

impl ToTokens for Include {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.name.to_tokens(tokens);
        self.bang_token.to_tokens(tokens);
        self.delimiter.surround(tokens, |tokens| {
            self.arg.to_tokens(tokens);
            self.trailing_comma.to_tokens(tokens);
        });
    }
}

impl Parse for IncludeStr {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(IncludeStr {
            name: input.parse()?,
            bang_token: input.parse()?,
            delimiter: macro_delimiter!(content in input),
            arg: Expr::parse_strict(&content).map(Box::new)?,
            trailing_comma: content.parse()?,
        })
    }
}

impl ToTokens for IncludeStr {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.name.to_tokens(tokens);
        self.bang_token.to_tokens(tokens);
        self.delimiter.surround(tokens, |tokens| {
            self.arg.to_tokens(tokens);
            self.trailing_comma.to_tokens(tokens);
        });
    }
}

impl Parse for Stringify {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(Stringify {
            name: input.parse()?,
            bang_token: input.parse()?,
            delimiter: macro_delimiter!(content in input),
            tokens: content.parse()?,
        })
    }
}

impl ToTokens for Stringify {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.name.to_tokens(tokens);
        self.bang_token.to_tokens(tokens);
        self.delimiter
            .surround(tokens, |tokens| self.tokens.to_tokens(tokens));
    }
}