matrix/matrix-bin/src/main.rs

188 lines
4.5 KiB
Rust
Raw Normal View History

2024-02-27 00:00:42 +00:00
use std::{path::PathBuf, io::{self, Read, IsTerminal}, fs, cell::RefCell, rc::Rc};
use clap::{Parser as ArgParser, ColorChoice};
2024-02-29 22:04:28 +00:00
use matrix_lang::prelude::*;
2024-02-19 23:38:15 +00:00
use repl::Repl;
mod repl;
2024-02-27 00:00:42 +00:00
mod helper;
2024-02-19 23:38:15 +00:00
#[derive(Debug, ArgParser)]
#[command(version, long_about = None)]
pub struct Args {
/// A path to a input program. Uses stdin if not specified.
file: Option<PathBuf>,
2024-02-29 22:04:28 +00:00
/// Compiles the given program
2024-02-19 23:38:15 +00:00
#[arg(short, long)]
2024-02-29 22:04:28 +00:00
compile: bool,
/// Optional output for compiled output
#[arg(short, long)]
output: Option<PathBuf>,
2024-02-19 23:38:15 +00:00
/// Print out debug information
#[arg(short, long)]
debug: bool,
2024-02-27 00:00:42 +00:00
/// Choses color
2024-02-29 22:04:28 +00:00
#[arg(long)]
2024-02-27 00:00:42 +00:00
color: Option<ColorChoice>,
2024-02-19 23:38:15 +00:00
/// Disables optimizations
#[arg(long)]
disable_optimizations: bool,
}
2024-02-29 22:04:28 +00:00
pub enum Mode {
Repl,
Execute(String),
Compile(String, PathBuf),
}
2024-02-19 23:38:15 +00:00
pub struct State<'a> {
parser: Parser,
compiler: Compiler<'a>,
2024-02-27 00:00:42 +00:00
vm: Rc<RefCell<Vm>>,
color: bool,
2024-02-19 23:38:15 +00:00
}
impl<'a> State<'a> {
2024-02-29 22:04:28 +00:00
pub fn new (args: Args) -> (Self, Mode) {
2024-02-19 23:38:15 +00:00
let stdin = read_stdin();
let file;
if let Some(path) = &args.file {
file = Some(fs::read_to_string(path).unwrap());
} else if stdin.len() > 0 {
file = Some(stdin);
} else {
file = None;
}
2024-02-29 22:04:28 +00:00
let mode;
let repl;
if args.compile {
let path = match (args.output, args.file) {
(Some(path), _) => path,
(None, Some(path)) => {
let mut path = path.clone();
path.set_extension("matc");
path
},
(None, None) => {
PathBuf::from("matc.out")
}
};
let file = file.unwrap_or(String::new());
mode = Mode::Compile(file, path);
repl = false;
} else if let Some(file) = file {
mode = Mode::Execute(file);
repl = false;
} else {
mode = Mode::Repl;
repl = true;
}
2024-02-19 23:38:15 +00:00
2024-02-29 22:04:28 +00:00
let mut vm = Vm::new();
2024-02-19 23:38:15 +00:00
let parser = ParserBuilder::new()
.optimize(!args.disable_optimizations)
.build();
let compiler = CompilerBuilder::new()
.repl(repl)
.debug(args.debug)
2024-02-23 00:40:09 +00:00
.names(vm.names())
2024-02-29 22:04:28 +00:00
.globals(vm.globals())
2024-02-19 23:38:15 +00:00
.build();
2024-02-29 22:04:28 +00:00
matrix_std::load(&mut vm);
2024-02-23 16:32:47 +00:00
2024-02-27 00:00:42 +00:00
let color = match args.color {
Some(ColorChoice::Auto) | None => {
io::stdout().is_terminal()
},
Some(ColorChoice::Always) => true,
Some(ColorChoice::Never) => false,
};
2024-02-29 22:04:28 +00:00
(Self {
parser,
vm: Rc::new(RefCell::new(vm)),
compiler,
color,
}, mode)
2024-02-19 23:38:15 +00:00
}
2024-02-29 22:04:28 +00:00
pub fn execute(&mut self, fun: Rc<Function>) -> Result<Value> {
2024-02-27 00:00:42 +00:00
let val = self.vm.try_borrow_mut().unwrap().run(fun)?;
2024-02-23 16:32:47 +00:00
Ok(val)
2024-02-19 23:38:15 +00:00
}
2024-02-29 22:04:28 +00:00
pub fn compile(&mut self, code: String) -> Result<Rc<Function>> {
let ast = self.parser.parse(code)?;
let fun = self.compiler.compile(&ast)?;
Ok(fun)
}
pub fn load_program(&mut self, body: String) -> Result<Rc<Function>> {
match Program::load(&body)? {
Some(fun) => {
Ok(fun)
},
None => {
self.compile(body)
},
}
}
2024-02-19 23:38:15 +00:00
}
2024-02-29 22:04:28 +00:00
pub fn error(err: Exception, state: &State) {
2024-02-27 00:00:42 +00:00
if state.color {
2024-02-29 22:04:28 +00:00
println!("\x1b[31mError:\x1b[0m {err}");
2024-02-27 00:00:42 +00:00
} else {
println!("Error: {err}");
}
2024-02-19 23:38:15 +00:00
}
fn read_stdin() -> String {
let mut buffer = String::new();
let mut stdin = io::stdin();
if stdin.is_terminal() {
return String::new();
}
stdin.read_to_string(&mut buffer).unwrap();
buffer
}
2024-02-29 22:04:28 +00:00
fn handle_mode(state: &mut State, mode: Mode) -> Result<()> {
match mode {
Mode::Repl => {
let mut repl = Repl::new(state);
repl.run();
},
Mode::Execute(body) => {
let fun = state.load_program(body)?;
state.execute(fun)?;
},
Mode::Compile(body, path) => {
let fun = state.compile(body)?;
let mut file = File::create(path).map_err(|e|
exception!(IO_EXCEPTION, "{e}")
)?;
Program::save(fun, &mut file)?;
}
};
Ok(())
}
2024-02-19 23:38:15 +00:00
fn main() {
let args = Args::parse();
2024-02-29 22:04:28 +00:00
let (mut state, mode) = State::new(args);
2024-02-19 23:38:15 +00:00
2024-02-29 22:04:28 +00:00
if let Err(e) = handle_mode(&mut state, mode) {
error(e, &state);
2024-02-19 23:38:15 +00:00
}
}