maud/maud_macros/src/lib.rs

44 lines
1.3 KiB
Rust
Raw Normal View History

2021-01-09 18:01:17 +13:00
#![doc(html_root_url = "https://docs.rs/maud_macros/0.22.2")]
2018-04-16 20:27:41 +12:00
// TokenStream values are reference counted, and the mental overhead of tracking
// lifetimes outweighs the marginal gains from explicit borrowing
#![allow(clippy::needless_pass_by_value)]
2018-04-16 20:27:41 +12:00
extern crate proc_macro;
mod ast;
mod generate;
2014-12-18 18:57:55 +13:00
mod parse;
2014-12-17 21:11:56 +13:00
use proc_macro2::{Ident, Span, TokenStream, TokenTree};
2020-09-27 21:36:27 +10:00
use proc_macro_error::proc_macro_error;
use quote::quote;
2016-01-01 11:43:59 +13:00
#[proc_macro]
#[proc_macro_error]
pub fn html(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
expand(input.into()).into()
2016-08-15 20:32:39 +12:00
}
#[proc_macro]
#[proc_macro_error]
pub fn html_debug(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let expr = expand(input.into());
2017-08-12 16:21:13 +12:00
println!("expansion:\n{}", expr);
expr.into()
2017-08-12 16:21:13 +12:00
}
fn expand(input: TokenStream) -> TokenStream {
let output_ident = TokenTree::Ident(Ident::new("__maud_output", Span::mixed_site()));
2017-08-12 16:21:13 +12:00
// Heuristic: the size of the resulting markup tends to correlate with the
// code size of the template itself
let size_hint = input.to_string().len();
2020-08-31 09:51:21 +03:00
let markups = parse::parse(input);
let stmts = generate::generate(markups, output_ident.clone());
2017-08-12 16:21:13 +12:00
quote!({
extern crate maud;
let mut #output_ident = ::std::string::String::with_capacity(#size_hint);
#stmts
maud::PreEscaped(#output_ident)
2017-08-12 16:21:13 +12:00
})
}