94 lines
2.8 KiB
Rust
94 lines
2.8 KiB
Rust
use clap::{Parser, Subcommand};
|
|
use std::fs;
|
|
use std::fs::File;
|
|
use std::io::{BufReader, Read, Write};
|
|
use std::path::Path;
|
|
|
|
use hence::*;
|
|
|
|
#[derive(Debug, Parser)]
|
|
#[clap(author, version, about, long_about = None)]
|
|
struct Cli {
|
|
#[clap(subcommand)]
|
|
commands: Commands,
|
|
}
|
|
|
|
#[derive(Debug, Subcommand)]
|
|
enum Commands {
|
|
#[clap(about = "Lexes source code and outputs tokens")]
|
|
Lex {
|
|
#[clap(value_parser)]
|
|
src: String,
|
|
},
|
|
#[clap(about = "Parses source code and outputs AST")]
|
|
Parse {
|
|
#[clap(value_parser)]
|
|
src: String,
|
|
},
|
|
#[clap(about = "Compiles binary from source code")]
|
|
Assemble {
|
|
#[clap(value_parser)]
|
|
src: String,
|
|
#[clap(value_parser)]
|
|
bin: Option<String>,
|
|
#[clap(long, action)]
|
|
dump: bool,
|
|
},
|
|
#[clap(about = "Emulates binary")]
|
|
Run {
|
|
#[clap(value_parser)]
|
|
bin: String,
|
|
},
|
|
}
|
|
|
|
fn main() {
|
|
let args = Cli::parse();
|
|
match args.commands {
|
|
Commands::Lex { src } => {
|
|
let assembly = fs::read_to_string(src).unwrap();
|
|
let tokens = lexer::lex(assembly).unwrap();
|
|
dbg!(tokens);
|
|
}
|
|
Commands::Parse { src } => {
|
|
let assembly = fs::read_to_string(src).unwrap();
|
|
let tokens = lexer::lex(assembly).unwrap();
|
|
let ast = parser::parse(tokens).unwrap();
|
|
dbg!(ast);
|
|
}
|
|
Commands::Assemble { src, bin, dump } => {
|
|
let assembly = fs::read_to_string(&src).unwrap();
|
|
let tokens = lexer::lex(assembly).unwrap();
|
|
let ast = parser::parse(tokens).unwrap();
|
|
|
|
let mut data = assembler::Data::new(
|
|
match Path::new(&src).parent().unwrap().to_str() {
|
|
Some(x) => x.to_string(),
|
|
_ => panic!("Could not get directory in which source code resides"),
|
|
},
|
|
ast.body,
|
|
);
|
|
assembler::assemble(&mut data).unwrap();
|
|
|
|
if let Some(x) = bin {
|
|
File::create(x).unwrap().write_all(&data.program).unwrap();
|
|
}
|
|
if dump {
|
|
println!("{}", rhexdump::hexdump(&data.program));
|
|
}
|
|
}
|
|
Commands::Run { bin } => {
|
|
let mut program_buf: Vec<u8> = Vec::new();
|
|
let file = File::open(bin).unwrap();
|
|
BufReader::new(file).read_to_end(&mut program_buf).unwrap();
|
|
if program_buf.len() < (32 * 1024) {
|
|
program_buf.append(&mut vec![0; 32 * 1024 - program_buf.len()]);
|
|
}
|
|
|
|
let program: [u8; 32 * 1024] = (&program_buf[0..(32 * 1024)]).try_into().unwrap();
|
|
let mut data = emulator::Data::new(program);
|
|
|
|
emulator::emulate(&mut data).unwrap();
|
|
}
|
|
}
|
|
}
|