schala/src/main.rs

286 lines
8.9 KiB
Rust
Raw Normal View History

2016-01-17 00:16:01 -08:00
#![feature(advanced_slice_patterns, slice_patterns, box_patterns)]
2016-12-28 15:56:02 -08:00
extern crate getopts;
extern crate linefeed;
2015-08-14 17:07:02 -07:00
use std::path::Path;
use std::fs::File;
use std::io::Read;
use std::process;
2017-01-23 19:11:50 -08:00
use std::io::Write;
use std::default::Default;
2015-07-22 03:02:55 -07:00
mod schala_lang;
use schala_lang::SchalaEvaluator;
use schala_lang::Schala;
2016-01-18 02:24:14 -08:00
mod maaru_lang;
2017-01-21 01:49:45 -08:00
mod language;
use language::{ProgrammingLanguage, LanguageInterface, LLVMCodeString, EvaluationMachine};
2017-01-21 01:49:45 -08:00
2016-12-26 23:29:24 -08:00
mod llvm_wrap;
2016-02-11 10:49:45 -08:00
2015-07-16 01:40:37 -07:00
fn main() {
2017-02-02 01:04:15 -08:00
2017-02-02 01:21:40 -08:00
let languages: Vec<Box<LanguageInterface>> =
vec![
Box::new((Schala::new(), SchalaEvaluator::new(None))),
Box::new((maaru_lang::Maaru::new(), maaru_lang::MaaruEvaluator::new())),
];
2017-02-02 01:04:15 -08:00
2016-12-29 02:04:03 -08:00
let option_matches =
2017-01-09 22:56:29 -08:00
match program_options().parse(std::env::args()) {
Ok(o) => o,
Err(e) => {
println!("{:?}", e);
std::process::exit(1);
}
};
2017-02-02 01:04:15 -08:00
if option_matches.opt_present("list-languages") {
for lang in languages {
println!("{}", lang.get_language_name());
}
std::process::exit(1);
}
2017-01-09 04:26:42 -08:00
let trace = option_matches.opt_present("t");
2017-01-16 02:47:05 -08:00
let show_llvm = option_matches.opt_present("l");
2016-12-28 15:56:02 -08:00
match option_matches.free[..] {
[] | [_] => {
2017-02-02 01:04:15 -08:00
let mut repl = Repl::new(languages);
repl.run();
2016-12-29 02:04:03 -08:00
}
[_, ref filename, _..] => {
let language = Schala::new();
2017-01-23 01:32:57 -08:00
run_noninteractive(filename, !option_matches.opt_present("i"), trace, &language);
2016-12-28 15:56:02 -08:00
}
};
}
fn program_options() -> getopts::Options {
let mut options = getopts::Options::new();
2016-12-29 02:04:03 -08:00
options.optflag("i",
"interpret",
"Interpret source file instead of compiling");
2017-01-09 04:26:42 -08:00
options.optflag("t",
"trace-evaluation",
"Print out trace of evaluation");
2017-01-16 02:47:05 -08:00
options.optflag("l",
"llvm-in-repl",
"Show LLVM IR in REPL");
2017-02-02 01:04:15 -08:00
options.optflag("",
"list-languages",
"Show a list of all supported languages");
2016-12-28 15:56:02 -08:00
options
2016-03-03 22:18:16 -08:00
}
2016-01-24 22:25:12 -08:00
fn run_noninteractive<'a, T: ProgrammingLanguage>(filename: &str, compile: bool, trace_evaluation: bool, language: &T) {
2016-03-03 22:18:16 -08:00
let mut source_file = File::open(&Path::new(filename)).unwrap();
let mut buffer = String::new();
source_file.read_to_string(&mut buffer).unwrap();
2016-01-24 22:25:12 -08:00
2017-01-23 01:32:57 -08:00
let tokens = match T::tokenize(&buffer) {
2016-12-28 22:52:23 -08:00
Ok(t) => t,
Err(e) => {
2016-12-28 23:55:13 -08:00
println!("Tokenization error: {}", e.msg);
std::process::exit(1)
2016-12-28 22:52:23 -08:00
}
2016-03-03 22:18:16 -08:00
};
2016-01-24 22:25:12 -08:00
2017-01-23 01:32:57 -08:00
let ast = match T::parse(tokens) {
2016-03-03 22:18:16 -08:00
Ok(ast) => ast,
2016-12-28 23:55:13 -08:00
Err(err) => {
println!("Parse error: {:?}", err.msg);
2017-01-23 01:32:57 -08:00
/*println!("Remaining tokens: {:?}", err.remaining_tokens);*/
2016-12-28 23:55:13 -08:00
std::process::exit(1)
}
2016-03-03 22:18:16 -08:00
};
2016-01-24 22:25:12 -08:00
2016-03-04 14:32:22 -08:00
if compile {
2017-01-23 01:32:57 -08:00
compilation_sequence(T::compile(ast), filename);
2016-03-04 14:32:22 -08:00
} else {
let mut evaluator = <T as ProgrammingLanguage>::Evaluator::new();
if trace_evaluation {
evaluator.set_option("trace_evaluation", true);
}
2017-01-23 01:32:57 -08:00
let results = T::evaluate(ast, &mut evaluator);
2016-03-04 14:32:22 -08:00
for result in results.iter() {
println!("{}", result);
}
2015-08-14 17:07:02 -07:00
}
2015-07-16 02:55:03 -07:00
}
2017-01-12 22:43:26 -08:00
type LineReader = linefeed::Reader<linefeed::terminal::DefaultTerminal>;
2017-02-02 00:23:48 -08:00
struct Repl {
2015-12-20 13:20:24 -08:00
show_tokens: bool,
show_parse: bool,
2017-01-16 02:38:58 -08:00
show_llvm_ir: bool,
languages: Vec<Box<LanguageInterface>>,
current_language_index: usize,
interpreter_directive_sigil: char,
2017-01-12 22:43:26 -08:00
reader: LineReader,
2015-12-20 13:20:24 -08:00
}
2017-02-02 00:23:48 -08:00
impl Repl {
2017-02-02 01:04:15 -08:00
fn new(languages: Vec<Box<LanguageInterface>>) -> Repl {
2017-01-13 12:10:02 -08:00
let mut reader: linefeed::Reader<_> = linefeed::Reader::new("Schala").unwrap();
2017-01-12 22:43:26 -08:00
reader.set_prompt(">> ");
Repl {
show_tokens: false,
show_parse: false,
2017-02-02 01:04:15 -08:00
show_llvm_ir: false,
languages: languages,
current_language_index: 0,
interpreter_directive_sigil: '.',
2017-01-12 22:43:26 -08:00
reader: reader,
}
}
fn run(&mut self) {
use linefeed::ReadResult::*;
println!("Schala v 0.02");
loop {
2017-01-12 22:43:26 -08:00
match self.reader.read_line() {
Err(e) => {
2017-01-13 12:10:02 -08:00
println!("Terminal read error: {}", e);
},
Ok(Eof) => {
break;
}
Ok(Input(ref input)) => {
2017-01-13 12:10:02 -08:00
self.reader.add_history(input.clone());
2017-01-12 21:51:00 -08:00
if self.handle_interpreter_directive(input) {
continue;
}
let output = self.input_handler(input);
2017-01-13 12:10:02 -08:00
println!("=> {}", output);
}
2017-01-13 12:10:02 -08:00
_ => (),
}
}
2017-01-13 12:10:02 -08:00
println!("Exiting...");
}
fn input_handler(&mut self, input: &str) -> String {
let ref mut language = self.languages[self.current_language_index];
language.evaluate_in_repl(input, language::LanguageInterfaceOptions::default())
}
fn handle_interpreter_directive(&mut self, input: &str) -> bool {
match input.chars().nth(0) {
Some(ch) if ch == self.interpreter_directive_sigil => (),
_ => return false
}
let mut iter = input.chars();
iter.next();
let trimmed_sigil: &str = iter.as_str();
let commands: Vec<&str> = trimmed_sigil
.split_whitespace()
.collect();
let cmd: &str = match commands.get(0).clone() {
None => return true,
Some(s) => s
};
match cmd {
"exit" | "quit" => process::exit(0),
"history" => {
for item in self.reader.history() {
println!("{}", item);
}
},
"lang" => {
match commands[1] {
"show" => {
for (i, lang) in self.languages.iter().enumerate() {
if i == self.current_language_index {
println!("* {}", lang.get_language_name());
} else {
println!("{}", lang.get_language_name());
}
}
},
"next" => {
self.current_language_index = (self.current_language_index + 1) % self.languages.len();
}
"prev" | "previous" => {
self.current_language_index = if self.current_language_index == 0 { self.languages.len() - 1 } else { self.current_language_index - 1 }
},
e => println!("Bad `lang` argument: {}", e),
}
},
"set" => {
let show = match commands[1] {
"show" => true,
"hide" => false,
e => {
println!("Bad `set` argument: {}", e);
return true;
}
};
match commands[2] {
"tokens" => self.show_tokens = show,
"parse" => self.show_parse = show,
2017-02-02 00:23:48 -08:00
"eval" => { /*self.evaluator.set_option("trace_evaluation", show);*/ },
2017-01-16 02:38:58 -08:00
"llvm" => self.show_llvm_ir = show,
e => {
println!("Bad `show`/`hide` argument: {}", e);
return true;
}
}
},
2017-01-13 18:59:34 -08:00
e => println!("Unknown command: {}", e)
2015-12-20 13:20:24 -08:00
}
return true;
2015-12-20 13:20:24 -08:00
}
}
2017-01-21 01:49:45 -08:00
2017-01-23 19:11:50 -08:00
pub fn compilation_sequence(llvm_code: LLVMCodeString, sourcefile: &str) {
use std::process::Command;
let ll_filename = "out.ll";
let obj_filename = "out.o";
let q: Vec<&str> = sourcefile.split('.').collect();
let bin_filename = match &q[..] {
&[name, "schala"] => name,
_ => panic!("Bad filename {}", sourcefile),
};
let LLVMCodeString(llvm_str) = llvm_code;
println!("Compilation process finished for {}", ll_filename);
File::create(ll_filename)
.and_then(|mut f| f.write_all(llvm_str.as_bytes()))
.expect("Error writing file");
let llc_output = Command::new("llc")
.args(&["-filetype=obj", ll_filename, "-o", obj_filename])
.output()
.expect("Failed to run llc");
if !llc_output.status.success() {
println!("{}", String::from_utf8_lossy(&llc_output.stderr));
}
let gcc_output = Command::new("gcc")
.args(&["-o", bin_filename, &obj_filename])
.output()
.expect("failed to run gcc");
if !gcc_output.status.success() {
println!("{}", String::from_utf8_lossy(&gcc_output.stdout));
println!("{}", String::from_utf8_lossy(&gcc_output.stderr));
}
for filename in [obj_filename].iter() {
Command::new("rm")
.arg(filename)
.output()
.expect(&format!("failed to run rm {}", filename));
}
}