-
Notifications
You must be signed in to change notification settings - Fork 153
/
lib.rs
57 lines (48 loc) · 1.73 KB
/
lib.rs
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
#![doc(html_root_url = "https://docs.rs/maud_macros/0.26.0")]
// 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)]
extern crate proc_macro;
mod ast;
mod escape;
mod generate;
use ast::DiagnosticParse;
use proc_macro2::{Ident, Span, TokenStream};
use proc_macro2_diagnostics::Diagnostic;
use quote::quote;
use syn::parse::{ParseStream, Parser};
#[proc_macro]
pub fn html(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
expand(input.into()).into()
}
fn expand(input: TokenStream) -> TokenStream {
// 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();
let mut diagnostics = Vec::new();
let markups = match Parser::parse2(
|input: ParseStream| ast::Markups::diagnostic_parse(input, &mut diagnostics),
input,
) {
Ok(data) => data,
Err(err) => {
let err = err.to_compile_error();
let diag_tokens = diagnostics.into_iter().map(Diagnostic::emit_as_expr_tokens);
return quote! {{
#err
#(#diag_tokens)*
}};
}
};
let diag_tokens = diagnostics.into_iter().map(Diagnostic::emit_as_expr_tokens);
let output_ident = Ident::new("__maud_output", Span::mixed_site());
let stmts = generate::generate(markups, output_ident.clone());
quote! {{
extern crate alloc;
extern crate maud;
let mut #output_ident = alloc::string::String::with_capacity(#size_hint);
#stmts
#(#diag_tokens)*
maud::PreEscaped(#output_ident)
}}
}