sailfish/sailfish-compiler/src/compiler.rs

86 lines
2.5 KiB
Rust
Raw Normal View History

2020-06-04 16:39:33 -04:00
use quote::ToTokens;
use std::fs;
2020-06-05 22:58:14 -04:00
use std::path::Path;
2020-06-06 09:49:01 -04:00
use std::sync::Arc;
2020-06-04 16:39:33 -04:00
2020-06-05 22:58:14 -04:00
use crate::config::Config;
2020-06-04 16:39:33 -04:00
use crate::error::*;
use crate::optimizer::Optimizer;
use crate::parser::Parser;
use crate::resolver::Resolver;
2020-06-06 09:49:01 -04:00
use crate::translator::{Translator, TranslatedSource};
2020-06-04 16:39:33 -04:00
use crate::util::rustfmt_block;
2020-06-05 22:58:14 -04:00
#[derive(Default)]
2020-06-04 16:39:33 -04:00
pub struct Compiler {
2020-06-05 22:58:14 -04:00
config: Config
2020-06-04 16:39:33 -04:00
}
impl Compiler {
pub fn new() -> Self {
Self::default()
}
2020-06-05 22:58:14 -04:00
pub fn with_config(config: Config) -> Self {
Self { config }
2020-06-04 16:39:33 -04:00
}
2020-06-06 09:49:01 -04:00
fn translate_file_contents(&self, input: &Path) -> Result<TranslatedSource, Error> {
2020-06-05 22:58:14 -04:00
let parser = Parser::new().delimiter(self.config.delimiter);
let translator = Translator::new().escape(self.config.escape);
2020-06-06 09:49:01 -04:00
let content = fs::read_to_string(input)
.chain_err(|| format!("Failed to open template file: {:?}", input))?;
let stream = parser.parse(&*content);
translator.translate(stream)
}
pub fn compile_file(&self, template_dir: &Path, input: &Path, output: &Path) -> Result<(), Error> {
// TODO: introduce cache system
let input = input.canonicalize()?;
2020-06-06 09:49:01 -04:00
let include_handler = Arc::new(|arg: &str| -> Result<_, Error> {
let input_file = if arg.starts_with("/") {
// absolute imclude
template_dir.join(arg)
} else {
// relative include
input.parent().unwrap().join(arg)
};
2020-06-06 09:49:01 -04:00
Ok(self.translate_file_contents(&*input_file)?.ast)
});
let resolver = Resolver::new().include_handler(include_handler);
2020-06-04 16:39:33 -04:00
let optimizer = Optimizer::new();
let compile_file = |input: &Path, output: &Path| -> Result<(), Error> {
2020-06-06 09:49:01 -04:00
let mut tsource = self.translate_file_contents(input)?;
2020-06-04 16:39:33 -04:00
resolver.resolve(&mut tsource.ast)?;
optimizer.optimize(&mut tsource.ast);
if let Some(parent) = output.parent() {
fs::create_dir_all(parent)?;
}
if output.exists() {
fs::remove_file(output)?;
}
let string = tsource.ast.into_token_stream().to_string();
fs::write(output, rustfmt_block(&*string).unwrap_or(string))?;
Ok(())
};
compile_file(&*input, &*output)
.chain_err(|| "Failed to compile template.")
.map_err(|mut e| {
e.source = fs::read_to_string(&*input).ok();
e.source_file = Some(input.to_owned());
e
})?;
Ok(())
}
}