use crate::build::context::Context;
use crate::build::error;
use crate::build::error::Error::{Glob, NoFileStem, Parse, PathEncoding, IO};
use crate::build::error::ParseError::*;
use crate::build::error::{Error, Errors, ParseError};
use crate::build::iter::First;
use std::path::{Path, PathBuf};
use std::{env, fs};
fn write_format(
line: &str,
line_n: usize,
) -> Result<String, ParseError> {
let mut indices = line.char_indices();
let mut main = String::from("\"");
let mut args = String::new();
let mut literal = String::new();
let mut previous: char = '\0';
while let Some((i, ch)) = indices.next() {
if ch == '$' {
if previous == '\\' {
literal.pop();
literal.push(ch);
previous = ch;
continue;
}
let v = literal
.replace('\\', "\\")
.replace('{', "{{")
.replace('}', "}}")
.replace('\t', "\\t")
.replace('"', "\\\"");
main.push_str(&v);
literal.clear();
previous = '\0';
main.push_str("{}");
let (begin, _) = (&mut indices)
.filter(|&(_, c)| c == '{')
.first()
.ok_or(ExprNotOpened(line_n, i))?;
let (end, _) = (&mut indices)
.filter(|&(_, c)| c == '}')
.first()
.ok_or(ExprNotClosed(line_n, i))?;
args.push_str(", ");
let value = if begin + 1 == end {
"()"
} else {
&line[(begin + 1)..end]
};
args.push_str(value);
} else {
literal.push(ch);
previous = ch;
}
}
let v = literal
.replace('\\', "\\")
.replace('{', "{{")
.replace('}', "}}")
.replace('\t', "\\t")
.replace('"', "\\\"");
main.push_str(&v);
main.push_str("\\n\"");
Ok(main + &args)
}
fn compile_to(name: &str, origin: &str, ctx: &mut Context) -> Result<(), ParseError> {
let mut line_n = 0;
let mut args: Option<Vec<&str>> = Some(vec!["_out: &mut F,"]);
let mut prologue = false;
for line in origin.replace("\r\n", "\n").split('\n') {
line_n += 1;
if line == "---" {
ctx.println(&format!("pub fn {}<F: std::io::Write>(", name));
ctx.indent();
for arg in std::mem::take(&mut args).unwrap() {
ctx.println(arg);
}
ctx.outdent();
ctx.println(") -> std::io::Result<()> {");
ctx.indent();
ctx.push_baseline();
prologue = true;
continue;
}
let trimmed = line.trim();
if let Some(args) = &mut args {
args.push(trimmed);
continue;
}
if trimmed.starts_with('#') {
ctx.println(&trimmed[1..]);
} else if trimmed.starts_with("\\#") {
ctx.print_format(&write_format(&line[1..], line_n)?);
} else {
ctx.print_format(&write_format(line, line_n)?);
}
}
if !prologue {
return Err(PrologueNotFound);
}
ctx.println("Ok(())");
ctx.pop_baseline();
ctx.outdent();
ctx.println("}");
Ok(())
}
pub fn compile(file: PathBuf, ctx: &mut Context) -> Result<(), Error> {
println!("cargo:rerun-if-changed={}", file.display());
let name = match file.file_stem().map(|v| v.to_str()) {
None => return Err(NoFileStem(file)),
Some(None) => return Err(PathEncoding(file)),
Some(Some(v)) => v,
};
let tpl = match fs::read_to_string(&file) {
Ok(tpl) => tpl,
Err(e) => return Err(IO(file, e)),
};
compile_to(name, &tpl, ctx).map_err(|e| Parse(file, e))
}
pub fn compile_all(pattern: &str) -> Result<(), Errors> {
let source_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
let pattern = source_dir.join(pattern);
let pattern = match pattern.to_str() {
None => return Err(PathEncoding(pattern).into()),
Some(pattern) => pattern,
};
let mut ctx = Context::new();
ctx.println("/// Automatically generated by cttm. Do not edit.");
ctx.println("#[allow(dead_code, unused_imports, unused_variables)]");
ctx.println("mod cttm {");
ctx.indent();
ctx.println("use super::*;");
ctx.println("pub mod tpl {");
ctx.indent();
ctx.push_baseline();
ctx.println("use super::*;");
let mut errors: Vec<error::Error> = Vec::new();
for path in glob::glob(pattern)? {
let path = match path {
Ok(path) => path,
Err(e) => {
errors.push(Glob(e));
continue;
}
};
if let Err(e) = compile(path, &mut ctx) {
errors.push(e);
}
}
ctx.pop_baseline();
ctx.outdent();
ctx.println("}");
ctx.outdent();
ctx.println("}");
if !errors.is_empty() {
return Err(Errors::from(errors));
}
let out_dir = Path::new(&env::var("OUT_DIR")?).join("cttm.rs");
fs::write(&out_dir, ctx.as_ref()).map_err(|e| IO(out_dir, e))?;
Ok(())
}