2022-01-26 08:07:53 +00:00
|
|
|
use std::{fs::{read_to_string, File}, path::Path, io::{Write, Seek}, time::Instant};
|
2022-01-24 20:08:41 +00:00
|
|
|
|
|
|
|
use structopt::StructOpt;
|
|
|
|
|
|
|
|
mod args;
|
|
|
|
use args::Args;
|
2022-01-21 23:43:50 +00:00
|
|
|
|
|
|
|
mod util;
|
2022-01-23 21:42:08 +00:00
|
|
|
use util::cover_paren;
|
|
|
|
|
2022-01-21 23:43:50 +00:00
|
|
|
mod parser;
|
2022-01-26 08:07:53 +00:00
|
|
|
use parser::{tokenize, Parser, Sexpr};
|
2022-01-21 23:43:50 +00:00
|
|
|
|
2022-01-26 01:45:59 +00:00
|
|
|
mod compiler;
|
2022-01-26 08:07:53 +00:00
|
|
|
use compiler::{compile::Compiler, instr::Instr};
|
|
|
|
|
|
|
|
mod vm;
|
2022-01-25 22:06:57 +00:00
|
|
|
|
2022-01-21 23:43:50 +00:00
|
|
|
fn main() {
|
2022-01-26 04:05:42 +00:00
|
|
|
let start = Instant::now();
|
2022-01-24 20:08:41 +00:00
|
|
|
let args = Args::from_args();
|
2022-01-23 21:42:08 +00:00
|
|
|
|
2022-01-24 20:08:41 +00:00
|
|
|
let src = cover_paren(read_to_string(&args.file).unwrap());
|
2022-01-26 08:07:53 +00:00
|
|
|
let file_name = match args.output {
|
|
|
|
Some(path) => path,
|
|
|
|
None => Path::new(&args.file).to_path_buf(),
|
|
|
|
}.file_stem().unwrap().to_str().unwrap().to_string();
|
2022-01-23 21:42:08 +00:00
|
|
|
|
2022-01-24 20:08:41 +00:00
|
|
|
let tokens = tokenize(&src);
|
|
|
|
let mut parser = Parser::new(tokens.clone());
|
2022-01-23 21:42:08 +00:00
|
|
|
let result = parser.parse();
|
2022-01-24 20:08:41 +00:00
|
|
|
|
2022-01-26 08:07:53 +00:00
|
|
|
match result {
|
|
|
|
Ok(ast) => {
|
|
|
|
compile(ast, file_name, start);
|
2022-01-26 04:05:42 +00:00
|
|
|
},
|
2022-01-26 08:07:53 +00:00
|
|
|
Err(e) => {
|
|
|
|
eprintln!("{}", e);
|
|
|
|
}
|
|
|
|
}
|
2022-01-26 04:05:42 +00:00
|
|
|
|
2022-01-26 08:07:53 +00:00
|
|
|
}
|
2022-01-26 04:05:42 +00:00
|
|
|
|
2022-01-26 08:07:53 +00:00
|
|
|
fn compile(ast: Sexpr, file_name: String, start: Instant) {
|
|
|
|
let mut compiler = Compiler::new();
|
|
|
|
let code = compiler.compile(ast, 0);
|
|
|
|
match code {
|
|
|
|
Ok(code) => {
|
|
|
|
let mut file = File::create(format!("{}.bsm", file_name)).unwrap();
|
|
|
|
for line in code {
|
|
|
|
write!(file, "{}\n", line).unwrap();
|
2022-01-26 04:05:42 +00:00
|
|
|
}
|
2022-01-26 08:07:53 +00:00
|
|
|
file.seek(std::io::SeekFrom::End(-1)).unwrap(); // Trim last newline
|
2022-01-26 04:05:42 +00:00
|
|
|
|
2022-01-26 08:07:53 +00:00
|
|
|
let elapsed = start.elapsed();
|
|
|
|
println!("Compiled in {}.{}s", elapsed.as_secs(), elapsed.subsec_millis());
|
2022-01-25 22:06:57 +00:00
|
|
|
},
|
2022-01-26 08:07:53 +00:00
|
|
|
Err(err) => {
|
|
|
|
eprintln!("{}", err);
|
2022-01-24 20:08:41 +00:00
|
|
|
}
|
|
|
|
}
|
2022-01-21 23:43:50 +00:00
|
|
|
}
|