Rename error variants
This commit is contained in:
@@ -11,10 +11,12 @@ use std::cmp::Ordering;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
pub use v2::{Compiler, Error};
|
||||
|
||||
quick_error! {
|
||||
#[derive(Debug)]
|
||||
pub enum CompileError {
|
||||
ParseError(err: parser::ParseError) {
|
||||
ParseError(err: parser::Error) {
|
||||
from()
|
||||
display("Parse error: {}", err)
|
||||
}
|
||||
@@ -43,7 +45,7 @@ quick_error! {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Compiler<'a, W: std::io::Write> {
|
||||
pub struct CompilerV1<'a, W: std::io::Write> {
|
||||
parser: ASTParser,
|
||||
/// Max stack size for the program is by default 512.
|
||||
variable_scope: Vec<HashMap<String, i32>>,
|
||||
@@ -54,7 +56,7 @@ pub struct Compiler<'a, W: std::io::Write> {
|
||||
declared_main: bool,
|
||||
}
|
||||
|
||||
impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
impl<'a, W: std::io::Write> CompilerV1<'a, W> {
|
||||
pub fn new(parser: ASTParser, writer: &'a mut BufWriter<W>) -> Self {
|
||||
Self {
|
||||
parser,
|
||||
@@ -212,7 +214,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
self.variable_scope.push(HashMap::new());
|
||||
|
||||
fn perform_operation<W: std::io::Write>(
|
||||
compiler: &mut Compiler<W>,
|
||||
compiler: &mut CompilerV1<W>,
|
||||
op: &str,
|
||||
left: Expression,
|
||||
right: Expression,
|
||||
|
||||
@@ -38,6 +38,36 @@ macro_rules! compile {
|
||||
}};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_function_declaration_with_spillover_params() -> anyhow::Result<()> {
|
||||
let compiled = compile!(debug r#"
|
||||
// we need more than 4 params to 'spill' into a stack var
|
||||
fn doSomething(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {};
|
||||
"#);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {"
|
||||
j main
|
||||
doSomething:
|
||||
pop r8 #arg9
|
||||
pop r9 #arg8
|
||||
pop r10 #arg7
|
||||
pop r11 #arg6
|
||||
pop r12 #arg5
|
||||
pop r13 #arg4
|
||||
pop r14 #arg3
|
||||
pop r15 #arg2
|
||||
push ra
|
||||
pop ra
|
||||
sub sp 1
|
||||
j ra
|
||||
"}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_function_declaration_with_register_params() -> anyhow::Result<()> {
|
||||
let compiled = compile!(debug r#"
|
||||
@@ -51,13 +81,9 @@ fn test_function_declaration_with_register_params() -> anyhow::Result<()> {
|
||||
indoc! {"
|
||||
j main
|
||||
doSomething:
|
||||
pop r8 #arg2
|
||||
pop r9 #arg1
|
||||
push ra
|
||||
push r4
|
||||
move r4 r0 #arg1
|
||||
push r5
|
||||
move r5 r1 #arg2
|
||||
pop r5
|
||||
pop r4
|
||||
pop ra
|
||||
j ra
|
||||
"}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::variable_manager::{self, LocationRequest, VariableLocation, VariableScope};
|
||||
use parser::{
|
||||
Parser as ASTParser,
|
||||
tree_node::{BlockExpression, Expression, FunctionExpression},
|
||||
@@ -8,17 +9,18 @@ use std::{
|
||||
io::{BufWriter, Write},
|
||||
};
|
||||
|
||||
use crate::variable_manager::VariableScope;
|
||||
|
||||
quick_error! {
|
||||
#[derive(Debug)]
|
||||
pub enum CompilerError {
|
||||
ParseError(error: parser::ParseError) {
|
||||
pub enum Error {
|
||||
ParseError(error: parser::Error) {
|
||||
from()
|
||||
}
|
||||
IoError(error: std::io::Error) {
|
||||
from()
|
||||
}
|
||||
ScopeError(error: variable_manager::Error) {
|
||||
from()
|
||||
}
|
||||
DuplicateFunction(func_name: String) {
|
||||
display("{func_name} has already been defined")
|
||||
}
|
||||
@@ -60,7 +62,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compile(mut self) -> Result<(), CompilerError> {
|
||||
pub fn compile(mut self) -> Result<(), Error> {
|
||||
let expr = self.parser.parse_all()?;
|
||||
|
||||
let Some(expr) = expr else { return Ok(()) };
|
||||
@@ -69,7 +71,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
self.expression(expr, &mut VariableScope::default())
|
||||
}
|
||||
|
||||
fn write_output(&mut self, output: impl Into<String>) -> Result<(), CompilerError> {
|
||||
fn write_output(&mut self, output: impl Into<String>) -> Result<(), Error> {
|
||||
self.output.write_all(output.into().as_bytes())?;
|
||||
self.output.write_all(b"\n")?;
|
||||
self.current_line += 1;
|
||||
@@ -80,7 +82,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
&mut self,
|
||||
expr: Expression,
|
||||
scope: &mut VariableScope<'v>,
|
||||
) -> Result<(), CompilerError> {
|
||||
) -> Result<(), Error> {
|
||||
match expr {
|
||||
Expression::Function(expr_func) => self.expression_function(expr_func, scope)?,
|
||||
Expression::Block(expr_block) => {
|
||||
@@ -96,7 +98,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
&mut self,
|
||||
mut expr: BlockExpression,
|
||||
scope: &mut VariableScope<'v>,
|
||||
) -> Result<(), CompilerError> {
|
||||
) -> Result<(), Error> {
|
||||
// First, sort the expressions to ensure functions are hoisted
|
||||
expr.0.sort_by(|a, b| {
|
||||
if matches!(b, Expression::Function(_)) && matches!(a, Expression::Function(_)) {
|
||||
@@ -120,11 +122,13 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compile a function declaration.
|
||||
/// Calees are responsible for backing up any registers they wish to use.
|
||||
fn expression_function<'v>(
|
||||
&mut self,
|
||||
expr: FunctionExpression,
|
||||
scope: &mut VariableScope<'v>,
|
||||
) -> Result<(), CompilerError> {
|
||||
) -> Result<(), Error> {
|
||||
let FunctionExpression {
|
||||
name,
|
||||
arguments,
|
||||
@@ -132,38 +136,69 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
||||
} = expr;
|
||||
|
||||
if self.function_locations.contains_key(&name) {
|
||||
return Err(CompilerError::DuplicateFunction(name));
|
||||
return Err(Error::DuplicateFunction(name));
|
||||
}
|
||||
|
||||
self.function_locations
|
||||
.insert(name.clone(), self.current_line);
|
||||
|
||||
// Declare the function as a line identifier
|
||||
self.write_output(format!("{}:", name))?;
|
||||
self.write_output("push ra")?;
|
||||
|
||||
// Create a new block scope for the function body
|
||||
let mut block_scope = VariableScope::scoped(&scope);
|
||||
|
||||
for (index, var_name) in arguments.iter().enumerate() {
|
||||
self.write_output(format!("push r{}", index + 4))?;
|
||||
self.write_output(format!(
|
||||
"move r{} r{} {}",
|
||||
index + 4,
|
||||
index,
|
||||
if self.config.debug {
|
||||
format!("#{}", var_name)
|
||||
} else {
|
||||
"".into()
|
||||
let mut saved_variables = 0;
|
||||
|
||||
// do a reverse pass to pop variables from the stack and put them into registers
|
||||
for var_name in arguments
|
||||
.iter()
|
||||
.rev()
|
||||
.take(VariableScope::PERSIST_REGISTER_COUNT as usize)
|
||||
{
|
||||
let loc = block_scope.add_variable(var_name, LocationRequest::Persist)?;
|
||||
// we don't need to imcrement the stack offset as it's already on the stack from the
|
||||
// previous scope
|
||||
|
||||
match loc {
|
||||
VariableLocation::Persistant(loc) => {
|
||||
self.write_output(format!(
|
||||
"pop r{loc} {}",
|
||||
if self.config.debug {
|
||||
format!("#{}", var_name)
|
||||
} else {
|
||||
"".into()
|
||||
}
|
||||
))?;
|
||||
}
|
||||
))?;
|
||||
VariableLocation::Stack(_) => {
|
||||
unimplemented!("Attempted to save to stack without tracking in scope")
|
||||
}
|
||||
|
||||
_ => {
|
||||
unimplemented!(
|
||||
"Attempted to return a Temporary scoped variable from a Persistant request"
|
||||
)
|
||||
}
|
||||
}
|
||||
saved_variables += 1;
|
||||
}
|
||||
|
||||
// now do a forward pass in case we have spilled into the stack. We don't need to push
|
||||
// anything as they already exist on the stack, but we DO need to let our block_scope be
|
||||
// aware that the variables exist on the stack (left to right)
|
||||
for var_name in arguments.iter().take(arguments.len() - saved_variables) {
|
||||
block_scope.add_variable(var_name, LocationRequest::Stack)?;
|
||||
}
|
||||
|
||||
self.write_output("push ra")?;
|
||||
self.expression_block(body, &mut block_scope)?;
|
||||
self.write_output("pop ra")?;
|
||||
|
||||
for (indx, _) in arguments.iter().enumerate().rev() {
|
||||
self.write_output(format!("pop r{}", indx + 4))?;
|
||||
if block_scope.stack_offset() > 0 {
|
||||
self.write_output(format!("sub sp {}", block_scope.stack_offset()))?;
|
||||
}
|
||||
|
||||
self.write_output("pop ra")?;
|
||||
self.write_output("j ra")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,12 +1,28 @@
|
||||
// r0 - r3 : function arguments
|
||||
// r4 - r9 : temporary variables
|
||||
// r10 - r15 : persistant variables
|
||||
// r0 - r7 : temporary variables
|
||||
// r8 - r15 : persistant variables
|
||||
|
||||
use std::collections::HashMap;
|
||||
use quick_error::quick_error;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
enum VarType {
|
||||
/// Represents a parameter register (r0 - r3)
|
||||
Func(u8),
|
||||
const TEMP: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
|
||||
const PERSIST: [u8; 8] = [8, 9, 10, 11, 12, 13, 14, 15];
|
||||
|
||||
quick_error! {
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
DuplicateVariable(var: String) {
|
||||
display("{var} already exists.")
|
||||
}
|
||||
UnknownVariable(var: String) {
|
||||
display("{var} does not exist.")
|
||||
}
|
||||
Unknown(reason: String) {
|
||||
display("{reason}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum VarType {
|
||||
/// Represents a temporary register (r4 - r8)
|
||||
Temp(u8),
|
||||
/// Represents a variable register (r9 - r15)
|
||||
@@ -15,19 +31,136 @@ enum VarType {
|
||||
Stack(u16),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
/// A request to store a variable at a specific register type
|
||||
pub enum LocationRequest {
|
||||
/// Request to store a variable in a temprary register.
|
||||
Temp,
|
||||
/// Request to store a variable in a persistant register.
|
||||
Persist,
|
||||
/// Request to store a variable in the stack.
|
||||
Stack,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum VariableLocation {
|
||||
Temporary(u8),
|
||||
Persistant(u8),
|
||||
Stack(u16),
|
||||
}
|
||||
|
||||
pub struct VariableScope<'a> {
|
||||
stack: Vec<HashMap<&'a str, usize>>,
|
||||
temp: HashMap<&'a str, u8>,
|
||||
persist: HashMap<&'a str, u8>,
|
||||
temporary_vars: VecDeque<u8>,
|
||||
persistant_vars: VecDeque<u8>,
|
||||
var_lookup_table: HashMap<String, VariableLocation>,
|
||||
var_stack: HashMap<String, u16>,
|
||||
stack_offset: u16,
|
||||
parent: Option<&'a VariableScope<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Default for VariableScope<'a> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
parent: None,
|
||||
stack_offset: 0,
|
||||
persistant_vars: PERSIST.to_vec().into(),
|
||||
temporary_vars: TEMP.to_vec().into(),
|
||||
var_stack: HashMap::new(),
|
||||
var_lookup_table: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> VariableScope<'a> {
|
||||
pub const TEMP_REGISTER_COUNT: u8 = 8;
|
||||
pub const PERSIST_REGISTER_COUNT: u8 = 8;
|
||||
|
||||
pub fn scoped(parent: &'a VariableScope<'a>) -> Self {
|
||||
Self {
|
||||
parent: Option::Some(parent),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stack_offset(&self) -> u16 {
|
||||
self.stack_offset
|
||||
}
|
||||
|
||||
pub fn stack_incr(&mut self) {
|
||||
self.stack_offset += 1;
|
||||
}
|
||||
|
||||
/// Adds and tracks a new scoped variable. If the location you request is full, will fall back
|
||||
/// to the stack.
|
||||
pub fn add_variable(
|
||||
&mut self,
|
||||
var_name: impl Into<String>,
|
||||
location: LocationRequest,
|
||||
) -> Result<VariableLocation, Error> {
|
||||
let var_name = var_name.into();
|
||||
if self.var_lookup_table.contains_key(var_name.as_str()) {
|
||||
return Err(Error::DuplicateVariable(var_name));
|
||||
}
|
||||
let var_location = match location {
|
||||
LocationRequest::Temp => {
|
||||
if let Some(next_var) = self.temporary_vars.pop_front() {
|
||||
let loc = VariableLocation::Temporary(next_var);
|
||||
loc
|
||||
} else {
|
||||
let loc = VariableLocation::Stack(self.stack_offset);
|
||||
self.stack_offset += 1;
|
||||
loc
|
||||
}
|
||||
}
|
||||
LocationRequest::Persist => {
|
||||
if let Some(next_var) = self.persistant_vars.pop_front() {
|
||||
let loc = VariableLocation::Persistant(next_var);
|
||||
loc
|
||||
} else {
|
||||
let loc = VariableLocation::Stack(self.stack_offset);
|
||||
self.stack_offset += 1;
|
||||
loc
|
||||
}
|
||||
}
|
||||
LocationRequest::Stack => {
|
||||
let loc = VariableLocation::Stack(self.stack_offset);
|
||||
self.stack_offset += 1;
|
||||
loc
|
||||
}
|
||||
};
|
||||
self.var_lookup_table.insert(var_name, var_location.clone());
|
||||
|
||||
Ok(var_location)
|
||||
}
|
||||
|
||||
pub fn get_location_of(
|
||||
&mut self,
|
||||
var_name: impl Into<String>,
|
||||
) -> Result<VariableLocation, Error> {
|
||||
let var_name = var_name.into();
|
||||
self.var_lookup_table
|
||||
.get(var_name.as_str())
|
||||
.map(|v| v.clone())
|
||||
.ok_or(Error::UnknownVariable(var_name))
|
||||
}
|
||||
|
||||
pub fn free_temp(&mut self, var_name: impl Into<String>) -> Result<(), Error> {
|
||||
let var_name = var_name.into();
|
||||
let Some(location) = self.var_lookup_table.remove(var_name.as_str()) else {
|
||||
return Err(Error::UnknownVariable(var_name));
|
||||
};
|
||||
|
||||
match location {
|
||||
VariableLocation::Temporary(t) => {
|
||||
self.temporary_vars.push_back(t);
|
||||
}
|
||||
VariableLocation::Persistant(_) => {
|
||||
return Err(Error::UnknownVariable(String::from(
|
||||
"Attempted to free a `let` variable.",
|
||||
)));
|
||||
}
|
||||
VariableLocation::Stack(_) => {}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user