N2T/jack_compiler/src/main.rs

54 lines
1.5 KiB
Rust

mod parser;
mod tokenizer;
mod symbol_table;
mod code_writer;
use std::env;
use std::fs;
use std::path::Path;
use std::ffi::OsStr;
use crate::code_writer::get_code_writer;
fn main() {
fn is_jack_file(filename: &Path) -> bool {
let p = Path::new(filename);
if p.is_file() && (p.extension().unwrap() == OsStr::new("jack")) {
return true;
}
return false;
}
fn translate_dir(directory: &Path) {
let paths = fs::read_dir(directory).unwrap();
for path in paths {
let filename = path.unwrap().path();
if is_jack_file(&filename) {
translate_single_file(filename.as_path())
}
}
}
fn translate_single_file(input_file: &Path) {
let mut tokens = tokenizer::tokenize_file(input_file);
let mut writer = get_code_writer();
println!("Compiling {:?}", input_file);
parser::compile_class(&mut tokens, &mut writer);
let output_file = str::replace(input_file.to_str().unwrap(), ".jack", ".vm");
writer.write_to_file(&output_file);
}
let args: Vec<String> = env::args().collect();
for arg in &args[1..] {
let arg_path = Path::new(arg);
println!("{:?}", arg_path);
if is_jack_file(&arg_path) {
translate_single_file(&arg_path);
} else if arg_path.is_dir() {
translate_dir(&arg_path);
} else {
println!("{} is not a *.jack file or directory!", arg);
}
}
}