1use std::fs;
3use std::path::Path;
5use std::path::PathBuf;
7use std::process;
9use std::time;
11use std::env;
13use mist_parser::error;
15use crate::modules;
17pub fn build(force: bool) -> PathBuf {
19 let start = time::Instant::now();
21 let root = env::current_dir().expect("Unable to find project root");
23 let src: PathBuf = root.join("src");
25 let out: PathBuf = root.join(".mist/src");
27 let master = modules::master_package(src.join("main.mist"), out.join("main.rs"));
29 master.transpile(&out);
31 let elapsed = start.elapsed();
33 println!(
35 "\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m",
36 elapsed
37 );
38 root
40} impl modules::Module {
42 fn transpile(self: &Self, parent_dir: &PathBuf) -> String {
44 let dir: PathBuf = self.output_dir(&parent_dir);
46 let output_file: PathBuf = self.output_path(&parent_dir);
48 let _ = fs::create_dir_all(&dir);
50 let mut output: String = String::new();
52 for child in &self.children {
54 output.push_str(&child.transpile(&dir));
56 }
57 if self.path.is_dir() {
59 let res = fs::write(&output_file, output);
61 if res.is_err() {
63 eprintln!(
65 "error: failed to write output {}\n {}",
66 output_file.display(),
67 res.unwrap_err(),
68 );
69 process::exit(1);
71 }
72 } else {
73 transpile_file(&self.path, &output_file, &output);
75 }
76 format!("pub mod {};\n", self.name)
78 }
79}
80fn transpile_file(path: &PathBuf, output_file: &PathBuf, mod_decl: &str) -> () {
82 let source: String = match fs::read_to_string(path) {
84 Ok(s) => s, Err(e) => {
88 eprintln!("error: failed to read file {}\n {}", path.display(), e);
90 process::exit(1);
92 }
93 };
94 let mut gc = mist_codegen::RustCodegen::new();
96 let output: String = gc.generate(match mist_parser::parse(&source) {
98 Ok(ast) => ast, Err(e) => {
102 match e {
104 error::ParseError::Ast(e) => {
106 let start_pos = e.span.start_pos().line_col();
108 let span = e.span.as_str();
110 eprintln!(
112 "\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
113 path.as_os_str().display(),
114 start_pos.0,
115 start_pos.1,
116 e.error_message,
117 span,
118 if span.ends_with("\n") { "" } else { "\n" },
119 "^".repeat(span.trim().len()),
120 );
121 process::exit(1);
123 } error::ParseError::PreAst(e) => {
126 eprintln!("error: parse failed in {}\n{}", path.display(), e);
128 process::exit(1);
130 }
131 }
132 }
133 });
134 let res = fs::write(&output_file, format!("{mod_decl}{output}"));
136 if res.is_err() {
138 eprintln!(
140 "error: failed to write output {}\n {}",
141 output_file.display(),
142 res.unwrap_err(),
143 );
144 process::exit(1);
146 }
147}