mod keyboard;
mod repl;
mod screen;
use std::process::ExitCode;
const USAGE: &str = "\
Usage:
miru run <file.miru> Run a MiruScriptX program from a file
miru -e <program> Evaluate a program supplied on the command line
miru --eval <program> Evaluate a program supplied on the command line
miru fmt <file.miru> Format a program and print it to standard output
miru fmt -w <file.miru> Format a program and rewrite the file in place
miru migrate <file.miru> Report what version 2.0 changes about a program
miru migrate -w <file> Rename what it can, and report the rest
miru disasm <file.miru> Show the bytecode a program compiles to
miru Start the interactive REPL
miru repl Start the interactive REPL
miru --version Print the version and exit
miru --help Show this help and exit";
const STACK_SIZE: usize = 64 * 1024 * 1024;
fn main() -> ExitCode {
match std::thread::Builder::new()
.name("miru".to_string())
.stack_size(STACK_SIZE)
.spawn(dispatch)
{
Ok(handle) => match handle.join() {
Ok(code) => code,
Err(_) => ExitCode::FAILURE,
},
Err(_) => dispatch(),
}
}
fn dispatch() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
match args.split_first() {
None => repl::run(),
Some((command, rest)) => match command.as_str() {
"run" => run_file(rest),
"-e" | "--eval" => eval_source(rest),
"fmt" => fmt_file(rest),
"migrate" => migrate_file(rest),
"disasm" => disasm_file(rest),
"repl" => {
if rest.is_empty() {
repl::run()
} else {
usage_error("the 'repl' command takes no arguments")
}
}
"--version" | "-v" => {
println!("miru {}", miruscriptx::VERSION);
ExitCode::SUCCESS
}
"--help" | "-h" => {
println!("MiruScriptX {}", miruscriptx::VERSION);
println!();
println!("{USAGE}");
ExitCode::SUCCESS
}
other => usage_error(&format!("unknown command '{other}'")),
},
}
}
struct RealSystem {
arguments: Vec<String>,
}
impl miruscriptx::value::System for RealSystem {
fn read_file(&mut self, path: &str) -> Result<String, String> {
std::fs::read_to_string(path).map_err(|err| format!("cannot read '{path}': {err}"))
}
fn write_file(&mut self, path: &str, contents: &str) -> Result<(), String> {
std::fs::write(path, contents).map_err(|err| format!("cannot write '{path}': {err}"))
}
fn file_exists(&mut self, path: &str) -> bool {
std::path::Path::new(path).is_file()
}
fn arguments(&self) -> Vec<String> {
self.arguments.clone()
}
}
struct RealClock;
impl miruscriptx::value::Clock for RealClock {
fn now_millis(&mut self) -> Result<i64, String> {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| since.as_millis() as i64)
.map_err(|_| "the host's clock is set before 1970".to_string())
}
fn sleep_millis(&mut self, millis: u64) -> Result<(), String> {
std::thread::sleep(std::time::Duration::from_millis(millis));
Ok(())
}
}
fn host(system: Box<RealSystem>) -> miruscriptx::Host {
miruscriptx::Host {
system,
clock: Box::new(RealClock),
keyboard: Box::new(keyboard::RealKeyboard::new()),
screen: Box::new(screen::RealScreen::new()),
}
}
fn eval_source(args: &[String]) -> ExitCode {
let Some((source, rest)) = args.split_first() else {
return usage_error("the '-e' command needs a program");
};
let system = Box::new(RealSystem {
arguments: rest.to_vec(),
});
match miruscriptx::run_source(source, Box::new(std::io::stdout()), host(system)) {
Ok(code) => ExitCode::from(code as u8),
Err(errors) => report(&errors, source),
}
}
fn report(errors: &[miruscriptx::MiruError], source: &str) -> ExitCode {
for error in errors {
eprintln!("miru: {}", error.render(source));
}
if errors.len() > 1 {
eprintln!("miru: {} errors", errors.len());
}
ExitCode::FAILURE
}
fn run_file(args: &[String]) -> ExitCode {
let mut path: Option<&str> = None;
let mut arguments: Vec<String> = Vec::new();
for arg in args {
if path.is_some() {
arguments.push(arg.clone());
continue;
}
match arg.as_str() {
"--vm" => {}
other if other.starts_with("--") => {
return usage_error(&format!("unknown option '{other}' for 'run'"));
}
other => path = Some(other),
}
}
let Some(path) = path else {
return usage_error("the 'run' command needs a file path");
};
let source = match std::fs::read_to_string(path) {
Ok(source) => source,
Err(err) => {
eprintln!("miru: cannot read '{path}': {err}");
return ExitCode::FAILURE;
}
};
let out = Box::new(std::io::stdout());
let system = Box::new(RealSystem { arguments });
match miruscriptx::run_source_from(&source, Some(std::path::Path::new(path)), out, host(system))
{
Ok(code) => ExitCode::from(code as u8),
Err(errors) => report(&errors, &source),
}
}
fn fmt_file(args: &[String]) -> ExitCode {
let mut write = false;
let mut path: Option<&str> = None;
for arg in args {
match arg.as_str() {
"--write" | "-w" => write = true,
other if other.starts_with('-') => {
return usage_error(&format!("unknown option '{other}' for 'fmt'"));
}
other => {
if path.is_some() {
return usage_error("the 'fmt' command takes a single file path");
}
path = Some(other);
}
}
}
let Some(path) = path else {
return usage_error("the 'fmt' command needs a file path");
};
let source = match std::fs::read_to_string(path) {
Ok(source) => source,
Err(err) => {
eprintln!("miru: cannot read '{path}': {err}");
return ExitCode::FAILURE;
}
};
let formatted = match miruscriptx::format_source(&source) {
Ok(formatted) => formatted,
Err(err) => {
eprintln!("miru: {}", err.render(&source));
return ExitCode::FAILURE;
}
};
if write {
match std::fs::write(path, &formatted) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("miru: cannot write '{path}': {err}");
ExitCode::FAILURE
}
}
} else {
print!("{formatted}");
ExitCode::SUCCESS
}
}
fn migrate_file(args: &[String]) -> ExitCode {
let mut write = false;
let mut path: Option<&str> = None;
for arg in args {
match arg.as_str() {
"--write" | "-w" => write = true,
other if other.starts_with('-') => {
return usage_error(&format!("unknown option '{other}' for 'migrate'"));
}
other => {
if path.is_some() {
return usage_error("the 'migrate' command takes a single file path");
}
path = Some(other);
}
}
}
let Some(path) = path else {
return usage_error("the 'migrate' command needs a file path");
};
let source = match std::fs::read_to_string(path) {
Ok(source) => source,
Err(err) => {
eprintln!("miru: cannot read '{path}': {err}");
return ExitCode::FAILURE;
}
};
let migration = match miruscriptx::migrate::migrate(&source) {
Ok(migration) => migration,
Err(err) => {
eprintln!("miru: {}", err.render(&source));
return ExitCode::FAILURE;
}
};
if migration.is_empty() {
println!("{path}: nothing to change for version 2.0");
return ExitCode::SUCCESS;
}
if !migration.renames.is_empty() {
let count = migration.renames.len();
if write {
if let Err(err) = std::fs::write(path, &migration.source) {
eprintln!("miru: cannot write '{path}': {err}");
return ExitCode::FAILURE;
}
println!("{path}: renamed {}", plural(count, "name", "names"));
} else {
println!(
"{path}: {} version 2.0 reserves. Run 'miru migrate -w {path}' to rename them.",
plural(count, "name that", "names that")
);
}
for rename in &migration.renames {
println!(
" {} -> {} {}",
rename.from,
rename.to,
lines_phrase(&rename.lines)
);
}
}
if !migration.notes.is_empty() {
if !migration.renames.is_empty() {
println!();
}
println!(
"{path}: {} version 2.0 gives a different meaning. No tool can decide these.",
plural(migration.notes.len(), "place where", "places where")
);
for note in &migration.notes {
println!(" line {}: {}", note.line, note.message);
}
}
ExitCode::SUCCESS
}
fn plural(count: usize, one: &str, many: &str) -> String {
if count == 1 {
format!("{count} {one}")
} else {
format!("{count} {many}")
}
}
fn lines_phrase(lines: &[usize]) -> String {
let numbers: Vec<String> = lines.iter().map(|line| line.to_string()).collect();
if lines.len() == 1 {
format!("line {}", numbers[0])
} else {
format!("lines {}", numbers.join(", "))
}
}
fn disasm_file(args: &[String]) -> ExitCode {
let path = match args {
[path] if !path.starts_with('-') => path,
[] => return usage_error("the 'disasm' command needs a file path"),
[other] => return usage_error(&format!("unknown option '{other}' for 'disasm'")),
_ => return usage_error("the 'disasm' command takes a single file path"),
};
let source = match std::fs::read_to_string(path) {
Ok(source) => source,
Err(err) => {
eprintln!("miru: cannot read '{path}': {err}");
return ExitCode::FAILURE;
}
};
match miruscriptx::disassemble_source(&source) {
Ok(listing) => {
print!("{listing}");
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("miru: {}", err.render(&source));
ExitCode::FAILURE
}
}
}
fn usage_error(message: &str) -> ExitCode {
eprintln!("miru: {message}");
eprintln!();
eprintln!("{USAGE}");
ExitCode::FAILURE
}