Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lists in Malluscript #33

Merged
merged 8 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions examples/array.ms
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
x = [1,4,5,6,"malluscript"];
x = x + "more data";
i = 0;
i um 6 um onnallenkil avarthikuga {
ezhuthuga x[i] + " ";
i = i+1;
}
3 changes: 3 additions & 0 deletions src/executor/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,7 @@ pub enum Expression {
InputNumber((usize, usize)),

FunctionCall((usize, usize), Box<Expression>, Vec<Expression>),

ListExpression((usize, usize), Vec<Expression>),
ListSubScript((usize, usize), Box<Expression>, Box<Expression>),
}
23 changes: 23 additions & 0 deletions src/executor/datatype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ pub enum DataTypes {
Integer(i64),
Bool(bool),
Float(f64),
List(Vec<DataTypes>),
Ref((i64, usize)),
Unknown,
}

Expand All @@ -55,6 +57,23 @@ impl fmt::Display for DataTypes {
DataTypes::String(s) => write!(f, "{}", literal_eval(s)),
DataTypes::Integer(i) => write!(f, "{}", i),
DataTypes::Float(n) => write!(f, "{}", n),
DataTypes::List(list) => {
let mut string = String::from("[");
let mut iter = list.iter().peekable();
while let Some(x) = iter.next() {
if let DataTypes::String(_) = x {
string += &("\"".to_owned() + &x.to_string() + "\"");
} else {
string += &x.to_string();
}

if iter.peek().is_some() {
string += ",";
}
}
string += "]";
write!(f, "{}", string)
}
_ => write!(f, "<Garbage:UnintialisedMemorySpace>"),
}
}
Expand All @@ -75,6 +94,10 @@ impl ops::Add for DataTypes {
(DataTypes::Float(l), DataTypes::String(r)) => DataTypes::String(l.to_string() + &r),
(DataTypes::String(l), DataTypes::Float(r)) => DataTypes::String(l + &r.to_string()),
(DataTypes::String(l), DataTypes::String(r)) => DataTypes::String(l + &r),
(DataTypes::List(mut l), r) => {
l.push(r);
DataTypes::List(l)
}
_ => raise_error(RunTimeErrors::IncompatibleOperation),
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/executor/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::process;
pub enum RunTimeErrors {
UndefinedSymbol(String),
SymbolAlreadyDefined(String),
UnInitialzedData(String),
InvalidAssignment,
DivisionByZero,
IncompatibleOperation,
Expand All @@ -15,6 +14,7 @@ pub enum RunTimeErrors {
InvalidFunctionDeclaration,
ArgumentCountMismatch,
IntegerOverFlow,
IndexOutOfBounds(i64, i64),
}

impl fmt::Display for RunTimeErrors {
Expand All @@ -26,7 +26,6 @@ impl fmt::Display for RunTimeErrors {
RunTimeErrors::SymbolAlreadyDefined(symbol) => {
write!(f, "[Error]: Symbol {} already defined", symbol)
}
RunTimeErrors::UnInitialzedData(data) => write!(f, "Uninitialised variable {}", data),
RunTimeErrors::DivisionByZero => write!(f, "[Error]: Division by Zero"),
RunTimeErrors::IncompatibleOperation => {
write!(f, "[Error]: Incompatible operation between datatypes")
Expand All @@ -49,6 +48,10 @@ impl fmt::Display for RunTimeErrors {
f,
"[Error]: Integer OverFlow, attempt to arithmetic operation that leads to overflow"
),
RunTimeErrors::IndexOutOfBounds(index,limit) => write!(
f,
"[Error]: Index Out Of Bounds, attempted to read/write at index {index} on {limit} sized data"
),
}
}
}
Expand Down
208 changes: 179 additions & 29 deletions src/executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ use crate::lexer::tokens::TokenType;

pub type ScopeLevel = i64;

static GLOBAL_SCOPE: ScopeLevel = 0;

pub struct Executor {
symbol_table: BTreeMap<(ScopeLevel, usize), DataTypes>,
literal_table: HashMap<usize, String>,
symbol_lookup_table: HashMap<String, usize>,
function_table: HashMap<String, (Vec<Expression>, SourceUnit)>,
scope_level: ScopeLevel,
frame_level: ScopeLevel,
return_storage: DataTypes,
subroutine_exit_flag: bool,
}
Expand All @@ -35,7 +37,7 @@ impl Executor {
literal_table,
symbol_lookup_table,
function_table: HashMap::new(),
scope_level: 0,
frame_level: GLOBAL_SCOPE,
subroutine_exit_flag: false,
return_storage: DataTypes::Integer(1),
}
Expand Down Expand Up @@ -94,17 +96,62 @@ impl Executor {
let _ = stdout().flush();
}

Statement::Assignment((p, q), l, r) => {
if let Expression::Symbol((_a, _b), TokenType::Symbol(address)) = l {
self.symbol_table
.entry((self.scope_level, *address))
.or_insert(DataTypes::Unknown);
Statement::Assignment((p, q), l, r) => match l {
Expression::Symbol((_a, _b), TokenType::Symbol(address)) => {
let mut frame_level = self.frame_level;
let mut data_address = *address;

let left_type = self.symbol_table.get(&(self.frame_level, *address));
if let Some(DataTypes::Ref((level, address))) = left_type {
frame_level = *level;
data_address = *address;
}

let data = self.eval_arithmetic_logic_expression(r)?;
self.symbol_table.insert((self.scope_level, *address), data);
} else {
self.symbol_table.insert((frame_level, data_address), data);
}
Expression::ListSubScript((_a, _b), expr, index) => {
let data = self.eval_arithmetic_logic_expression(r)?;
let index = match self.eval_arithmetic_logic_expression(index) {
Ok(DataTypes::Integer(idx)) => idx,
_ => return Err(((*p, *q), RunTimeErrors::IncompatibleOperation)),
};
if let Expression::Symbol((_a, _b), TokenType::Symbol(address)) = **expr {
let mut frame_level = self.frame_level;
let mut data_address = address;
let left_type = self.symbol_table.get(&(self.frame_level, address));
if let Some(DataTypes::Ref((level, address))) = left_type {
frame_level = *level;
data_address = *address;
}

let left = self.symbol_table.get_mut(&(frame_level, data_address));

if let Some(DataTypes::List(list)) = left {
if index < 0 || index > (list.len() - 1) as i64 {
return Err((
(*p, *q),
RunTimeErrors::IndexOutOfBounds(index, list.len() as i64),
));
}

list[index as usize] = data;
} else {
return Err(((*p, *q), RunTimeErrors::InvalidExpression));
}
} else if let Expression::ListSubScript((_a, _b), _, _) = **expr {
let mut indices = Vec::new();
indices.push(index);
let reference = self.evaluate_list_subscript(l, &mut indices)?;
*reference = data;
} else {
return Err(((*p, *q), RunTimeErrors::InvalidExpression));
}
}
_ => {
return Err(((*p, *q), RunTimeErrors::InvalidAssignment));
}
}
},
Statement::EmptyExpression((_p, _q), expr) => {
self.eval_arithmetic_logic_expression(expr)?;
}
Expand Down Expand Up @@ -183,27 +230,23 @@ impl Executor {
_ => Err(((*a, *b), RunTimeErrors::InvalidExpression)),
},
Expression::Symbol((a, b), TokenType::Symbol(address)) => {
let mut level = self.scope_level;
while level > -1 {
if !self.symbol_table.contains_key(&(level, *address)) {
level -= 1;
} else {
break;
}
}
if level == -1 {
return Err((
(*a, *b),
RunTimeErrors::UndefinedSymbol(self.get_symbol_name(*address).unwrap()),
));
let mut level = self.frame_level;

if !self.symbol_table.contains_key(&(level, *address)) {
level = 0;
}

match self.symbol_table.get(&(level, *address)) {
Some(DataTypes::Integer(number)) => Ok(DataTypes::Integer(*number)),
Some(DataTypes::Float(number)) => Ok(DataTypes::Float(*number)),
Some(DataTypes::String(data)) => Ok(DataTypes::String(data.to_string())),
Some(DataTypes::List(data)) => Ok(DataTypes::List(data.to_vec())),
Some(DataTypes::Ref((level, address))) => {
Ok(self.symbol_table.get(&(*level, *address)).unwrap().clone())
}
_ => Err((
(*a, *b),
RunTimeErrors::UnInitialzedData(self.get_symbol_name(*address).unwrap()),
RunTimeErrors::UndefinedSymbol(self.get_symbol_name(*address).unwrap()),
)),
}
}
Expand Down Expand Up @@ -255,20 +298,32 @@ impl Executor {
if let Expression::Symbol(_, TokenType::Symbol(y)) = y {
// allocation
let data = self.eval_arithmetic_logic_expression(x)?.clone();
self.symbol_table.insert((self.scope_level + 1, *y), data);
if let (
DataTypes::List(_),
Expression::Symbol(_, TokenType::Symbol(x)),
) = (&data, x)
{
// lists will be passed by reference by default
self.symbol_table.insert(
(self.frame_level + 1, *y),
DataTypes::Ref((self.frame_level, *x)),
);
} else {
self.symbol_table.insert((self.frame_level + 1, *y), data);
}
} else {
return Err(((*p, *q), RunTimeErrors::InvalidFunctionDeclaration));
}
}

self.scope_level += 1;
self.frame_level += 1;
self.return_storage = DataTypes::Unknown;
self.execute(&function.1)?;

let scope = self.scope_level;
let scope = self.frame_level;
self.symbol_table
.retain(|(scope_level, _), _| *scope_level != scope);
self.scope_level -= 1;
.retain(|(frame_level, _), _| *frame_level != scope);
self.frame_level -= 1;
} else {
return Err(((*p, *q), RunTimeErrors::UndefinedSymbol(name)));
}
Expand All @@ -278,6 +333,101 @@ impl Executor {
Err(((*p, *q), RunTimeErrors::InvalidExpression))
}
}

Expression::ListExpression((_p, _q), items) => {
let mut list = Vec::new();
for item in items {
let data = self.eval_arithmetic_logic_expression(item)?;
list.push(data);
}
Ok(DataTypes::List(list))
}

Expression::ListSubScript((p, q), expr, index) => {
let index = match self.eval_arithmetic_logic_expression(index) {
Ok(DataTypes::Integer(idx)) => idx,
_ => return Err(((*p, *q), RunTimeErrors::IncompatibleOperation)),
};
if let Expression::Symbol((_a, _b), TokenType::Symbol(address)) = **expr {
let mut frame_level = self.frame_level;
let mut data_address = address;
let left_type = self.symbol_table.get(&(self.frame_level, address));
if let Some(DataTypes::Ref((level, address))) = left_type {
frame_level = *level;
data_address = *address;
}
if let Some(data) = self.symbol_table.get_mut(&(frame_level, data_address)) {
if let DataTypes::List(list) = data {
if index < 0 || index > (list.len() - 1) as i64 {
return Err((
(*p, *q),
RunTimeErrors::IndexOutOfBounds(index, list.len() as i64),
));
}
let value = &list[index as usize];
Ok(value.clone())
} else {
Err(((*p, *q), RunTimeErrors::InvalidExpression))
}
} else {
let name = self.get_symbol_name(address).unwrap();
Err(((*p, *q), RunTimeErrors::UndefinedSymbol(name)))
}
} else if let Expression::ListSubScript(_, _, _) = **expr {
let data = self.eval_arithmetic_logic_expression(expr)?;
if let DataTypes::List(list) = data {
if index < 0 || index > (list.len() - 1) as i64 {
return Err((
(*p, *q),
RunTimeErrors::IndexOutOfBounds(index, list.len() as i64),
));
}
let value = &list[index as usize];
Ok(value.clone())
} else {
Err(((*p, *q), RunTimeErrors::InvalidExpression))
}
} else {
Err(((*p, *q), RunTimeErrors::InvalidExpression))
}
}
}
}

pub fn evaluate_list_subscript(
&mut self,
expr: &Expression,
vec: &mut Vec<i64>,
) -> Result<&mut DataTypes, ((usize, usize), error::RunTimeErrors)> {
if let Expression::ListSubScript((p, q), expr, index) = expr {
let index = match self.eval_arithmetic_logic_expression(index) {
Ok(DataTypes::Integer(idx)) => idx,
_ => return Err(((*p, *q), RunTimeErrors::IncompatibleOperation)),
};
vec.push(index);
return self.evaluate_list_subscript(expr, vec);
} else if let Expression::Symbol((a, b), TokenType::Symbol(address)) = expr {
let mut frame_level = self.frame_level;
let mut data_address = address;
let left_type = self.symbol_table.get(&(self.frame_level, *address));
if let Some(DataTypes::Ref((level, address))) = left_type {
frame_level = *level;
data_address = address;
}
let mut data = self.symbol_table.get_mut(&(frame_level, *data_address));
while let Some(index) = vec.pop() {
if let Some(DataTypes::List(list)) = data {
if index < 0 || index > (list.len() - 1) as i64 {
return Err((
(*a, *b),
RunTimeErrors::IndexOutOfBounds(index, list.len() as i64),
));
}
data = Some(&mut list[index as usize]);
}
}
return Ok(data.unwrap());
}
Err(((0, 0), RunTimeErrors::InvalidExpression))
}
}
6 changes: 3 additions & 3 deletions src/executor/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ fn arithmetic_test() {
";
let exec = get_executor(code).unwrap();
assert_eq!(
exec.symbol_table[&(exec.scope_level, exec.symbol_lookup_table["i"])],
exec.symbol_table[&(exec.frame_level, exec.symbol_lookup_table["i"])],
DataTypes::Integer(162)
);
assert_eq!(
exec.symbol_table[&(exec.scope_level, exec.symbol_lookup_table["j"])],
exec.symbol_table[&(exec.frame_level, exec.symbol_lookup_table["j"])],
DataTypes::Integer(0)
);
}
Expand All @@ -55,7 +55,7 @@ fn malayalam_test() {
";
let exec = get_executor(code).unwrap();
assert_eq!(
exec.symbol_table[&(exec.scope_level, exec.symbol_lookup_table["നമ്പർ"])],
exec.symbol_table[&(exec.frame_level, exec.symbol_lookup_table["നമ്പർ"])],
DataTypes::Integer(10)
);
}
Expand Down
Loading
Loading