Skip to content

Eager evaluation of macros like `concat!` and `env!`

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

dtolnay/macro-string

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

85 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

macro-string

github crates.io docs.rs build status

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.

Supported macros: concat!, env!, include!, include_str!, stringify!

For example, to implement a macro such as the following:

// 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.

use macro_string::MacroString;
use proc_macro::TokenStream;
use proc_macro2::Span;
use std::fs;
use syn::parse_macro_input;

#[proc_macro]
pub fn include_json(input: TokenStream) -> TokenStream {
    let MacroString(path) = parse_macro_input!(input);

    let content = match fs::read(&path) {
        Ok(content) => content,
        Err(err) => {
            return TokenStream::from(syn::Error::new(Span::call_site(), err).to_compile_error());
        }
    };

    let json: serde_json::Value = match serde_json::from_slice(&content) {
        Ok(json) => json,
        Err(err) => {
            return TokenStream::from(syn::Error::new(Span::call_site(), err).to_compile_error());
        }
    };

    /*TODO: print serde_json::Value to TokenStream*/
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

About

Eager evaluation of macros like `concat!` and `env!`

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Languages