From f5a82d852abdb3b6b3bd342572ac5adee6affb7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Wed, 10 Mar 2021 17:59:52 +0100 Subject: remove run_string and rand --- src/lib.rs | 7 ------- 1 file changed, 7 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 5ea0b63..d4787af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,13 +47,6 @@ pub fn run_file(path: &Path, print: bool, functions: Vec<(String, RustFunction)> run(path, print, functions) } -pub fn run_string(source: &str, print: bool, functions: Vec<(String, RustFunction)>) -> Result<(), Vec> { - let mut path = std::env::temp_dir(); - path.push(format!("test_{}.sy", rand::random::())); - std::fs::write(path.clone(), source).expect("Failed to write source to temporary file"); - run(&path, print, functions) -} - fn run(path: &Path, print: bool, functions: Vec<(String, RustFunction)>) -> Result<(), Vec> { let sections = sectionizer::sectionize(path); match compiler::Compiler::new(sections).compile("main", path, &functions) { -- cgit v1.2.1 From 225cd164c8307d39d6e7f4881253ef1de66469b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Wed, 10 Mar 2021 18:01:01 +0100 Subject: change debug print output --- src/compiler.rs | 3 +-- src/lib.rs | 6 +++--- src/vm.rs | 4 ++-- 3 files changed, 6 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/compiler.rs b/src/compiler.rs index 9ab868f..e83c269 100644 --- a/src/compiler.rs +++ b/src/compiler.rs @@ -596,8 +596,7 @@ impl Compiler { /// The line of the current token. fn line(&self) -> usize { if self.section().tokens.len() == 0 { - // unreachable!("An error occured without a section."); - 666666 + 0 } else { self.section().tokens[std::cmp::min(self.current_token, self.section().tokens.len() - 1)].1 } diff --git a/src/lib.rs b/src/lib.rs index d4787af..e1c6ad5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -877,11 +877,11 @@ impl Block { for (i, s) in self.ops.iter().enumerate() { println!("{}{}", if self.line_offsets.contains_key(&i) { - format!("{:5} ", self.line_offsets[&i].red()) + format!("{:5} ", self.line_offsets[&i].blue()) } else { - format!(" {} ", "|".red()) + format!(" {} ", "|".blue()) }, - format!("{:05} {:?}", i.blue(), s) + format!("{:05} {:?}", i.red(), s) ); } println!(); diff --git a/src/vm.rs b/src/vm.rs index 3652321..c5e2d68 100644 --- a/src/vm.rs +++ b/src/vm.rs @@ -498,8 +498,8 @@ impl VM { println!("]"); println!("{:5} {:05} {:?}", - self.frame().block.borrow().line(self.frame().ip).red(), - self.frame().ip.blue(), + self.frame().block.borrow().line(self.frame().ip).blue(), + self.frame().ip.red(), self.frame().block.borrow().ops[self.frame().ip]); } -- cgit v1.2.1 From f671ecc40626e9fbac452981a87636b6f00d7e15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Wed, 10 Mar 2021 18:02:08 +0100 Subject: rename main --- src/compiler.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/compiler.rs b/src/compiler.rs index e83c269..0754a1e 100644 --- a/src/compiler.rs +++ b/src/compiler.rs @@ -1781,7 +1781,7 @@ impl Compiler { } pub(crate) fn compile(&mut self, name: &str, file: &Path, functions: &[(String, RustFunction)]) -> Result> { - let main = Variable::new("/main/", false, Type::Void); + let main = Variable::new("/preamble", false, Type::Void); let slot = self.define(main).unwrap(); self.frame_mut().stack[slot].read = true; -- cgit v1.2.1 From 62147f625e2a51a405c1c7ea5ca2ef4d96b8e7f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Wed, 10 Mar 2021 18:02:16 +0100 Subject: rework run_file --- src/error.rs | 19 +++++++++++---- src/lib.rs | 78 ++++++++++++++++++++++++++++++++++-------------------------- src/main.rs | 24 +++++++------------ src/vm.rs | 18 +++++++------- 4 files changed, 76 insertions(+), 63 deletions(-) (limited to 'src') diff --git a/src/error.rs b/src/error.rs index 9aca985..f967685 100644 --- a/src/error.rs +++ b/src/error.rs @@ -34,6 +34,9 @@ pub enum ErrorKind { SyntaxError(usize, Token), /// (start, end) GitConflictError(usize, usize), + + FileNotFound(PathBuf), + NoFileGiven, } #[derive(Debug, Clone)] @@ -54,10 +57,10 @@ impl fmt::Display for ErrorKind { write!(f, "Cannot apply {:?} to types {}", op, types) } ErrorKind::TypeMismatch(a, b) => { - write!(f, "Expected '{:?}' and got '{:?}'.", a, b) + write!(f, "Expected '{:?}' and got '{:?}'", a, b) } ErrorKind::CannotInfer(a, b) => { - write!(f, "Failed to infer type '{:?}' from '{:?}'.", a, b) + write!(f, "Failed to infer type '{:?}' from '{:?}'", a, b) } ErrorKind::ArgumentType(a, b) => { let expected = a @@ -70,7 +73,7 @@ impl fmt::Display for ErrorKind { expected, given) } ErrorKind::IndexError(value, slot) => { - write!(f, "Cannot index value '{:?}' with type '{:?}'.", value, slot) + write!(f, "Cannot index value '{:?}' with type '{:?}'", value, slot) } ErrorKind::ExternTypeMismatch(name, types) => { write!(f, "Extern function '{}' doesn't accept argument(s) with type(s) {:?}", @@ -86,7 +89,7 @@ impl fmt::Display for ErrorKind { write!(f, "Cannot find field '{}' on {:?}", field, obj) } ErrorKind::ArgumentCount(expected, given) => { - write!(f, "Incorrect argument count, expected {} but got {}.", + write!(f, "Incorrect argument count, expected {} but got {}", expected, given) } ErrorKind::IndexOutOfBounds(value, len, slot) => { @@ -100,7 +103,7 @@ impl fmt::Display for ErrorKind { write!(f, "{}", "[!!] Invalid program [!!]".bold()) } ErrorKind::Unreachable => { - write!(f, "Reached unreachable code.") + write!(f, "Reached unreachable code") } ErrorKind::SyntaxError(line, token) => { write!(f, "Syntax Error on line {} at token {:?}", line, token) @@ -109,6 +112,12 @@ impl fmt::Display for ErrorKind { write!(f, "Git conflict markers found between lines {} and {}", start_line, end_line) } + ErrorKind::FileNotFound(path) => { + write!(f, "File '{}' not found", path.display()) + } + ErrorKind::NoFileGiven => { + write!(f, "No file to run") + } } } } diff --git a/src/lib.rs b/src/lib.rs index e1c6ad5..e88941e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,41 +19,31 @@ mod compiler; mod sectionizer; mod tokenizer; -/// Compiles a file and links the supplied functions as callable external -/// functions. Use this if you want your programs to be able to yield. -pub fn compile_file( - path: &Path, - print: bool, - functions: Vec<(String, RustFunction)> -) -> Result> { - let sections = sectionizer::sectionize(path); - match compiler::Compiler::new(sections).compile("main", path, &functions) { - Ok(prog) => { - let mut vm = vm::VM::new(); - vm.print_blocks = print; - vm.print_ops = print; - vm.typecheck(&prog)?; - vm.init(&prog); - Ok(vm) - } - Err(errors) => Err(errors), - } -} - /// Compiles, links and runs the given file. Supplied functions are callable /// external functions. If you want your program to be able to yield, use /// [compile_file]. -pub fn run_file(path: &Path, print: bool, functions: Vec<(String, RustFunction)>) -> Result<(), Vec> { - run(path, print, functions) +pub fn run_file(args: Args, functions: Vec<(String, RustFunction)>) -> Result<(), Vec> { + run(args, functions) } -fn run(path: &Path, print: bool, functions: Vec<(String, RustFunction)>) -> Result<(), Vec> { - let sections = sectionizer::sectionize(path); - match compiler::Compiler::new(sections).compile("main", path, &functions) { +fn run(args: Args, functions: Vec<(String, RustFunction)>) -> Result<(), Vec> { + let path = match args.file { + Some(file) => file, + None => { + return Err(vec![Error { + kind: ErrorKind::NoFileGiven, + file: PathBuf::from(""), + line: 0, + message: None, + }]); + } + }; + let sections = sectionizer::sectionize(&path); + match compiler::Compiler::new(sections).compile("/preamble", &path, &functions) { Ok(prog) => { let mut vm = vm::VM::new(); - vm.print_blocks = print; - vm.print_ops = print; + vm.print_bytecode = args.print_bytecode; + vm.print_exec = args.print_exec; vm.typecheck(&prog)?; vm.init(&prog); if let Err(e) = vm.run() { @@ -66,6 +56,22 @@ fn run(path: &Path, print: bool, functions: Vec<(String, RustFunction)>) -> Resu } } +pub struct Args { + pub file: Option, + pub print_exec: bool, + pub print_bytecode: bool, +} + +impl Default for Args { + fn default() -> Self { + Self { + file: None, + print_exec: false, + print_bytecode: false, + } + } +} + /// A linkable external function. Created either manually or using /// [sylt_macro::extern_function]. pub type RustFunction = fn(&[Value], bool) -> Result; @@ -994,19 +1000,23 @@ mod tests { ($fn:ident, $path:literal, $print:expr) => { #[test] fn $fn() { - let file = std::path::Path::new($path); - crate::run_file(&file, $print, Vec::new()).unwrap(); + let mut args = $crate::Args::default(); + args.file = Some(std::path::PathBuf::from($path)); + args.print_bytecode = $print; + $crate::run_file(args, Vec::new()).unwrap(); } }; ($fn:ident, $path:literal, $print:expr, $errs:tt) => { #[test] fn $fn() { - use crate::error::ErrorKind; + use $crate::error::ErrorKind; #[allow(unused_imports)] - use crate::Type; + use $crate::Type; - let file = std::path::Path::new($path); - let res = crate::run_file(&file, $print, Vec::new()); + let mut args = $crate::Args::default(); + args.file = Some(std::path::PathBuf::from($path)); + args.print_bytecode = $print; + let res = $crate::run_file(args, Vec::new()); $crate::assert_errs!(res, $errs); } }; diff --git a/src/main.rs b/src/main.rs index 28e4e79..1489fda 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,10 @@ -use std::path::{Path, PathBuf}; +use std::path::Path; -use sylt::run_file; - -struct Args { - file: Option, - print: bool, -} +use sylt::{run_file, Args}; fn main() { let args = parse_args(); - let file = args.file.unwrap_or_else(|| Path::new("progs/tests/simple.sy").to_owned()); - let errs = match run_file(&file, args.print, sylt_macro::link!(extern_test as test)) { + let errs = match run_file(args, sylt_macro::link!(extern_test as test)) { Err(it) => it, _ => return, }; @@ -21,17 +15,17 @@ fn main() { } fn parse_args() -> Args { - let mut args = Args { - file: None, - print: false, - }; + let mut args = Args::default(); for s in std::env::args().skip(1) { let path = Path::new(&s).to_owned(); if path.is_file() { args.file = Some(path); - } else if "-p" == s { - args.print = true; + } else if s == "-v" { + args.print_exec = true; + } else if s == "-vv" { + args.print_exec = true; + args.print_bytecode = true; } else { eprintln!("Invalid argument {}.", s); } diff --git a/src/vm.rs b/src/vm.rs index c5e2d68..792dc36 100644 --- a/src/vm.rs +++ b/src/vm.rs @@ -60,8 +60,8 @@ pub struct VM { constants: Vec, strings: Vec, - pub print_blocks: bool, - pub print_ops: bool, + pub print_bytecode: bool, + pub print_exec: bool, runtime: bool, @@ -89,8 +89,8 @@ impl VM { constants: Vec::new(), strings: Vec::new(), - print_blocks: false, - print_ops: false, + print_bytecode: false, + print_exec: false, runtime: false, extern_functions: Vec::new() @@ -437,7 +437,7 @@ impl VM { error!(self, ErrorKind::ArgumentCount(args.len(), num_args)); } - if self.print_blocks { + if self.print_bytecode { inner.debug_print(); } self.frames.push(Frame { @@ -525,13 +525,13 @@ impl VM { /// Simulates the program. pub fn run(&mut self) -> Result { - if self.print_blocks { + if self.print_bytecode { println!("\n [[{}]]\n", "RUNNING".red()); self.frame().block.borrow().debug_print(); } loop { - if self.print_ops { + if self.print_exec { self.print_stack() } @@ -835,7 +835,7 @@ impl VM { ip: 0 }); - if self.print_blocks { + if self.print_bytecode { println!("\n [[{} - {}]]\n", "TYPECHECKING".purple(), self.frame().block.borrow().name); self.frame().block.borrow().debug_print(); } @@ -847,7 +847,7 @@ impl VM { break; } - if self.print_ops { + if self.print_exec { self.print_stack() } -- cgit v1.2.1 From 21710c73bdf0fc1164422c178c9faaa71bf9cdd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Wed, 10 Mar 2021 18:03:28 +0100 Subject: use correct flag --- src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 1489fda..23ababa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,10 +22,10 @@ fn parse_args() -> Args { if path.is_file() { args.file = Some(path); } else if s == "-v" { - args.print_exec = true; + args.print_bytecode = true; } else if s == "-vv" { - args.print_exec = true; args.print_bytecode = true; + args.print_exec = true; } else { eprintln!("Invalid argument {}.", s); } -- cgit v1.2.1 From 035ac6f1a0fde887ccbdfb9358adddcb89a5bae3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Wed, 10 Mar 2021 18:09:27 +0100 Subject: dont print everything in release ~10% speedup :) --- src/vm.rs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/vm.rs b/src/vm.rs index 792dc36..c7d8d53 100644 --- a/src/vm.rs +++ b/src/vm.rs @@ -437,6 +437,7 @@ impl VM { error!(self, ErrorKind::ArgumentCount(args.len(), num_args)); } + #[cfg(debug_assertions)] if self.print_bytecode { inner.debug_print(); } @@ -531,6 +532,7 @@ impl VM { } loop { + #[cfg(debug_assertions)] if self.print_exec { self.print_stack() } @@ -847,6 +849,7 @@ impl VM { break; } + #[cfg(debug_assertions)] if self.print_exec { self.print_stack() } -- cgit v1.2.1