2020-06-04 16:39:33 -04:00
|
|
|
use proc_macro2::{Span, TokenStream};
|
2020-12-16 05:55:28 -05:00
|
|
|
use quote::quote;
|
2020-12-16 04:44:24 -05:00
|
|
|
use std::collections::hash_map::DefaultHasher;
|
2020-06-11 02:31:55 -04:00
|
|
|
use std::env;
|
2020-12-16 04:44:24 -05:00
|
|
|
use std::hash::{Hash, Hasher};
|
2020-06-04 16:39:33 -04:00
|
|
|
use std::path::{Path, PathBuf};
|
2020-12-16 05:55:28 -05:00
|
|
|
use syn::parse::{ParseStream, Parser, Result as ParseResult};
|
2020-06-04 16:39:33 -04:00
|
|
|
use syn::punctuated::Punctuated;
|
2020-06-07 10:23:45 -04:00
|
|
|
use syn::{Fields, Ident, ItemStruct, LitBool, LitChar, LitStr, Token};
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-06-13 09:58:57 -04:00
|
|
|
use crate::compiler::{CompilationReport, Compiler};
|
2020-06-07 04:58:52 -04:00
|
|
|
use crate::config::Config;
|
2020-06-04 16:39:33 -04:00
|
|
|
use crate::error::*;
|
|
|
|
|
2020-06-13 09:58:57 -04:00
|
|
|
// options for `template` attributes
|
2020-06-04 16:39:33 -04:00
|
|
|
#[derive(Default)]
|
|
|
|
struct DeriveTemplateOptions {
|
2020-12-16 05:55:28 -05:00
|
|
|
found_keys: Vec<Ident>,
|
2020-06-04 16:39:33 -04:00
|
|
|
path: Option<LitStr>,
|
|
|
|
delimiter: Option<LitChar>,
|
|
|
|
escape: Option<LitBool>,
|
2020-06-06 18:01:15 -04:00
|
|
|
rm_whitespace: Option<LitBool>,
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
|
|
|
|
2020-12-16 05:55:28 -05:00
|
|
|
impl DeriveTemplateOptions {
|
|
|
|
fn parser<'s>(&'s mut self) -> impl Parser + 's {
|
|
|
|
move |outer: ParseStream| -> ParseResult<()> {
|
|
|
|
let s;
|
|
|
|
syn::parenthesized!(s in outer);
|
|
|
|
|
|
|
|
while !s.is_empty() {
|
|
|
|
let key = s.parse::<Ident>()?;
|
|
|
|
s.parse::<Token![=]>()?;
|
|
|
|
|
|
|
|
// check if argument is repeated
|
|
|
|
if self.found_keys.iter().any(|e| *e == key) {
|
|
|
|
return Err(syn::Error::new(
|
|
|
|
key.span(),
|
|
|
|
format!("Argument `{}` was repeated.", key),
|
|
|
|
));
|
|
|
|
}
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-12-16 05:55:28 -05:00
|
|
|
if key == "path" {
|
|
|
|
self.path = Some(s.parse::<LitStr>()?);
|
|
|
|
} else if key == "delimiter" {
|
|
|
|
self.delimiter = Some(s.parse::<LitChar>()?);
|
|
|
|
} else if key == "escape" {
|
|
|
|
self.escape = Some(s.parse::<LitBool>()?);
|
|
|
|
} else if key == "rm_whitespace" {
|
|
|
|
self.rm_whitespace = Some(s.parse::<LitBool>()?);
|
|
|
|
} else {
|
|
|
|
return Err(syn::Error::new(
|
|
|
|
key.span(),
|
|
|
|
format!("Unknown option: `{}`", key),
|
|
|
|
));
|
|
|
|
}
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-12-16 05:55:28 -05:00
|
|
|
self.found_keys.push(key);
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-12-16 05:55:28 -05:00
|
|
|
// consume comma token
|
|
|
|
if s.is_empty() {
|
|
|
|
break;
|
2020-06-04 16:39:33 -04:00
|
|
|
} else {
|
2020-12-16 05:55:28 -05:00
|
|
|
s.parse::<Token![,]>()?;
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-16 05:55:28 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-14 16:36:39 -04:00
|
|
|
fn merge_config_options(config: &mut Config, options: &DeriveTemplateOptions) {
|
2020-06-04 16:39:33 -04:00
|
|
|
if let Some(ref delimiter) = options.delimiter {
|
2020-06-05 22:58:14 -04:00
|
|
|
config.delimiter = delimiter.value();
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
|
|
|
if let Some(ref escape) = options.escape {
|
2020-06-05 22:58:14 -04:00
|
|
|
config.escape = escape.value;
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
2020-06-06 18:01:15 -04:00
|
|
|
if let Some(ref rm_whitespace) = options.rm_whitespace {
|
|
|
|
config.rm_whitespace = rm_whitespace.value;
|
|
|
|
}
|
2020-06-14 16:36:39 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn resolve_template_file(path: &str, template_dirs: &[PathBuf]) -> Option<PathBuf> {
|
|
|
|
for template_dir in template_dirs.iter().rev() {
|
|
|
|
let p = template_dir.join(path);
|
|
|
|
if p.is_file() {
|
|
|
|
return Some(p);
|
|
|
|
}
|
|
|
|
}
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-06-14 16:36:39 -04:00
|
|
|
let mut fallback = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect(
|
|
|
|
"Internal error: environmental variable `CARGO_MANIFEST_DIR` is not set.",
|
|
|
|
));
|
|
|
|
fallback.push("templates");
|
|
|
|
fallback.push(path);
|
|
|
|
|
|
|
|
if fallback.is_file() {
|
|
|
|
return Some(fallback);
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
fn filename_hash(path: &Path) -> String {
|
|
|
|
use std::fmt::Write;
|
|
|
|
|
2020-12-16 04:44:24 -05:00
|
|
|
let mut path_with_hash = String::with_capacity(16);
|
2020-06-14 16:36:39 -04:00
|
|
|
|
|
|
|
if let Some(n) = path.file_name() {
|
|
|
|
let mut filename = &*n.to_string_lossy();
|
|
|
|
if let Some(p) = filename.find('.') {
|
|
|
|
filename = &filename[..p];
|
|
|
|
}
|
2020-12-16 04:44:24 -05:00
|
|
|
path_with_hash.push_str(filename);
|
|
|
|
path_with_hash.push('-');
|
2020-06-14 16:36:39 -04:00
|
|
|
}
|
|
|
|
|
2020-12-16 04:44:24 -05:00
|
|
|
let mut hasher = DefaultHasher::new();
|
|
|
|
path.hash(&mut hasher);
|
|
|
|
let hash = hasher.finish();
|
|
|
|
let _ = write!(path_with_hash, "{:016x}", hash);
|
2020-06-14 16:36:39 -04:00
|
|
|
|
2020-12-16 04:44:24 -05:00
|
|
|
path_with_hash
|
2020-06-14 16:36:39 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn compile(
|
|
|
|
input_file: &Path,
|
|
|
|
output_file: &Path,
|
|
|
|
config: Config,
|
|
|
|
) -> Result<CompilationReport, Error> {
|
2020-06-05 22:58:14 -04:00
|
|
|
let compiler = Compiler::with_config(config);
|
2020-06-14 16:36:39 -04:00
|
|
|
compiler.compile_file(input_file, &*output_file)
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn derive_template_impl(tokens: TokenStream) -> Result<TokenStream, syn::Error> {
|
|
|
|
let strct = syn::parse2::<ItemStruct>(tokens)?;
|
|
|
|
|
|
|
|
let mut all_options = DeriveTemplateOptions::default();
|
|
|
|
for attr in strct.attrs {
|
2020-06-06 14:44:30 -04:00
|
|
|
if attr.path.is_ident("template") {
|
2020-12-16 05:55:28 -05:00
|
|
|
syn::parse::Parser::parse2(all_options.parser(), attr.tokens)?;
|
2020-06-06 14:44:30 -04:00
|
|
|
}
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
|
|
|
|
2020-06-14 17:44:49 -04:00
|
|
|
#[cfg(feature = "config")]
|
2020-07-11 04:02:31 -04:00
|
|
|
let mut config = {
|
|
|
|
let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect(
|
|
|
|
"Internal error: environmental variable `CARGO_MANIFEST_DIR` is not set.",
|
|
|
|
));
|
|
|
|
|
|
|
|
Config::search_file_and_read(&*manifest_dir)
|
|
|
|
.map_err(|e| syn::Error::new(Span::call_site(), e))?
|
|
|
|
};
|
2020-06-14 17:44:49 -04:00
|
|
|
|
|
|
|
#[cfg(not(feature = "config"))]
|
|
|
|
let mut config = Config::default();
|
2020-06-06 09:49:01 -04:00
|
|
|
|
2020-06-11 02:31:55 -04:00
|
|
|
if env::var("SAILFISH_INTEGRATION_TESTS").map_or(false, |s| s == "1") {
|
2020-06-14 16:36:39 -04:00
|
|
|
let template_dir = env::current_dir()
|
|
|
|
.unwrap()
|
2020-06-11 02:31:55 -04:00
|
|
|
.ancestors()
|
|
|
|
.find(|p| p.join("LICENSE").exists())
|
|
|
|
.unwrap()
|
2020-07-14 09:46:58 -04:00
|
|
|
.join("sailfish-tests")
|
2020-06-11 02:31:55 -04:00
|
|
|
.join("integration-tests")
|
|
|
|
.join("tests")
|
|
|
|
.join("fails")
|
|
|
|
.join("templates");
|
2020-06-14 16:36:39 -04:00
|
|
|
config.template_dirs.push(template_dir);
|
2020-06-11 02:31:55 -04:00
|
|
|
}
|
|
|
|
|
2020-06-14 16:36:39 -04:00
|
|
|
let input_file = {
|
|
|
|
let path = all_options.path.as_ref().ok_or_else(|| {
|
|
|
|
syn::Error::new(Span::call_site(), "`path` option must be specified.")
|
|
|
|
})?;
|
|
|
|
resolve_template_file(&*path.value(), &*config.template_dirs).ok_or_else(
|
|
|
|
|| {
|
|
|
|
syn::Error::new(
|
|
|
|
path.span(),
|
|
|
|
format!("Template file {:?} not found", path.value()),
|
|
|
|
)
|
|
|
|
},
|
|
|
|
)?
|
2020-06-04 16:39:33 -04:00
|
|
|
};
|
|
|
|
|
2020-12-28 15:19:12 -05:00
|
|
|
let mut output_file = PathBuf::from(env!("OUT_DIR"));
|
2020-06-04 16:39:33 -04:00
|
|
|
output_file.push("templates");
|
2020-06-14 16:36:39 -04:00
|
|
|
output_file.push(filename_hash(&*input_file));
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-06-14 16:36:39 -04:00
|
|
|
merge_config_options(&mut config, &all_options);
|
|
|
|
let report = compile(&*input_file, &*output_file, config)
|
2020-06-04 16:39:33 -04:00
|
|
|
.map_err(|e| syn::Error::new(Span::call_site(), e))?;
|
|
|
|
|
2020-12-16 05:13:37 -05:00
|
|
|
let input_file_string = input_file
|
|
|
|
.to_str()
|
|
|
|
.unwrap_or_else(|| panic!("Non UTF-8 file name: {:?}", input_file));
|
|
|
|
let output_file_string = output_file
|
|
|
|
.to_str()
|
|
|
|
.unwrap_or_else(|| panic!("Non UTF-8 file name: {:?}", output_file));
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-06-13 09:58:57 -04:00
|
|
|
let mut include_bytes_seq = quote! { include_bytes!(#input_file_string); };
|
|
|
|
for dep in report.deps {
|
2020-12-16 05:13:37 -05:00
|
|
|
if let Some(dep_string) = dep.to_str() {
|
|
|
|
include_bytes_seq.extend(quote! { include_bytes!(#dep_string); });
|
|
|
|
}
|
2020-06-13 09:58:57 -04:00
|
|
|
}
|
|
|
|
|
2020-06-04 16:39:33 -04:00
|
|
|
// Generate tokens
|
|
|
|
|
|
|
|
let name = strct.ident;
|
|
|
|
|
|
|
|
let field_names: Punctuated<Ident, Token![,]> = match strct.fields {
|
|
|
|
Fields::Named(fields) => fields
|
|
|
|
.named
|
|
|
|
.into_iter()
|
|
|
|
.map(|f| {
|
|
|
|
f.ident.expect(
|
|
|
|
"Internal error: Failed to get field name (error code: 73621)",
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.collect(),
|
|
|
|
Fields::Unit => Punctuated::new(),
|
|
|
|
_ => {
|
|
|
|
return Err(syn::Error::new(
|
|
|
|
Span::call_site(),
|
|
|
|
"You cannot derive `Template` or `TemplateOnce` for tuple struct",
|
|
|
|
));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let (impl_generics, ty_generics, where_clause) = strct.generics.split_for_impl();
|
|
|
|
|
2020-12-16 04:34:26 -05:00
|
|
|
// render_once method always results in the same code.
|
|
|
|
// This method can be implemented in `sailfish` crate, but I found that performance
|
|
|
|
// drops when the implementation is written in `sailfish` crate.
|
2020-06-04 16:39:33 -04:00
|
|
|
let tokens = quote! {
|
|
|
|
impl #impl_generics sailfish::TemplateOnce for #name #ty_generics #where_clause {
|
2020-12-16 04:34:26 -05:00
|
|
|
fn render_once(self) -> sailfish::RenderResult {
|
|
|
|
use sailfish::runtime::{Buffer, SizeHint};
|
|
|
|
static SIZE_HINT: SizeHint = SizeHint::new();
|
2020-06-04 16:39:33 -04:00
|
|
|
|
2020-12-24 03:22:11 -05:00
|
|
|
let mut buf = Buffer::with_capacity(SIZE_HINT.get());
|
2020-12-16 04:34:26 -05:00
|
|
|
self.render_once_to(&mut buf)?;
|
|
|
|
SIZE_HINT.update(buf.len());
|
2020-06-18 05:35:39 -04:00
|
|
|
|
2020-12-16 04:34:26 -05:00
|
|
|
Ok(buf.into_string())
|
|
|
|
}
|
2020-06-18 05:35:39 -04:00
|
|
|
|
2020-12-16 04:34:26 -05:00
|
|
|
fn render_once_to(self, __sf_buf: &mut sailfish::runtime::Buffer) -> std::result::Result<(), sailfish::runtime::RenderError> {
|
|
|
|
#include_bytes_seq;
|
2020-07-25 10:56:17 -04:00
|
|
|
|
2020-12-16 04:34:26 -05:00
|
|
|
use sailfish::runtime as __sf_rt;
|
2020-06-04 16:39:33 -04:00
|
|
|
let #name { #field_names } = self;
|
|
|
|
include!(#output_file_string);
|
|
|
|
|
2020-06-18 05:35:39 -04:00
|
|
|
Ok(())
|
2020-06-04 16:39:33 -04:00
|
|
|
}
|
|
|
|
}
|
2020-12-19 03:23:47 -05:00
|
|
|
|
|
|
|
impl #impl_generics sailfish::private::Sealed for #name #ty_generics #where_clause {}
|
2020-06-04 16:39:33 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
Ok(tokens)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn derive_template(tokens: TokenStream) -> TokenStream {
|
|
|
|
derive_template_impl(tokens).unwrap_or_else(|e| e.to_compile_error())
|
|
|
|
}
|