Skip to content

Commit

Permalink
Fix: Delete Val setting in the symbol table. Symbol only used for Typ…
Browse files Browse the repository at this point in the history
…e Checking.
  • Loading branch information
Jaredanwolfgang committed Dec 5, 2024
1 parent 0794242 commit 92a0ea4
Show file tree
Hide file tree
Showing 10 changed files with 80 additions and 97 deletions.
2 changes: 1 addition & 1 deletion src/analyser/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use thiserror::Error;

pub use SemanticError::*;

#[derive(Error, Debug)]
#[derive(Clone, Error, Debug)]
pub enum SemanticError {
#[error("[Semantic Error] Type Mismatch Error[{id:?}] at line {line:?}: {message:?}")]
TypeError{
Expand Down
18 changes: 16 additions & 2 deletions src/analyser/src/fmt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::fmt::{Display, Result};
use crate::symbol::{Symbol, VarType, BasicType, FuncReturnType};
use crate::table::ScopeTable;
use crate::stack::ScopeStack;

impl<T> Display for Symbol<T>
where
Expand All @@ -14,8 +15,8 @@ where
impl Display for VarType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result {
match self {
VarType::Primitive((basic_type, value)) => {
write!(f, "Primitive: type: {:?}, value: {:?}", basic_type, value)
VarType::Primitive(basic_type) => {
write!(f, "Primitive: type: {:?}", basic_type)
},
VarType::Array(array_type) => {
write!(f, "Array: {:?}", array_type)
Expand Down Expand Up @@ -48,4 +49,17 @@ impl<T: Clone + std::fmt::Debug> Display for ScopeTable<T> {
}
write!(f, "{}", result)
}
}

impl Display for ScopeStack {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut result = String::new();
result.push_str("Function Table");
result.push_str(&format!(" {:?}\n", self.func_scope.borrow()));
result.push_str("Variable Table");
for scope in &self.stack {
result.push_str(&format!(" {:?}\n", scope.borrow()));
}
write!(f, "{}", result)
}
}
29 changes: 8 additions & 21 deletions src/analyser/src/from.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,15 @@ use crate::manager::SymbolManager;
use crate::symbol::*;
use crate::error::SemanticError;

impl From<Value> for Val {
fn from(value: Value) -> Val {
impl From<Value> for BasicType {
fn from(value: Value) -> BasicType {
match value {
Value::Integer(i) => Val::Int(i as i32),
Value::Float(f) => Val::Float(f),
Value::Char(c) => Val::Char(c),
Value::Bool(b) => Val::Bool(b),
Value::String(s) => Val::String(s),
Value::Null => Val::Int(-1)
Value::Integer(_) => BasicType::Int,
Value::Float(_) => BasicType::Float,
Value::Char(_) => BasicType::Char,
Value::Bool(_) => BasicType::Bool,
Value::String(_) => BasicType::String,
Value::Null => BasicType::Null
}
}
}

impl From<Val> for BasicType {
fn from(val: Val) -> BasicType {
match val {
Val::Int(_) => BasicType::Int,
Val::Float(_) => BasicType::Float,
Val::Char(_) => BasicType::Char,
Val::Bool(_) => BasicType::Bool,
Val::String(_) => BasicType::String,
Val::Array(_) => BasicType::Null,
}
}
}
33 changes: 11 additions & 22 deletions src/analyser/src/impls.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::symbol::*;
use crate::manager::SymbolManager;
use crate::error::{SemanticError, SemanticErrorManager};

impl<T> Symbol<T> {
pub fn new(id: i32, is_global: bool, identifier: String, symbol_type: T) -> Symbol<T>{
Expand All @@ -15,51 +16,39 @@ impl<T> Symbol<T> {

// From for VarSymbol
impl VarSymbol {
pub fn primitive(manager: &mut SymbolManager, identifier: String, type_t: BasicType, value: Val, is_global: bool) -> VarSymbol {
manager.new_var_symbol(identifier, VarType::Primitive((type_t, value)), is_global)
pub fn primitive(manager: &mut SymbolManager, identifier: String, type_t: BasicType, is_global: bool) -> VarSymbol {
manager.new_var_symbol(identifier, VarType::Primitive(type_t), is_global)
}

pub fn array(manager: &mut SymbolManager, identifier: String, type_t: BasicType, value: Vec<Val>, dimensions: Vec<usize>, is_global: bool) -> VarSymbol {
manager.new_var_symbol(identifier, VarType::Array((type_t, value, dimensions)), is_global)
pub fn array(manager: &mut SymbolManager, identifier: String, type_t: BasicType, dimensions: Vec<usize>, is_global: bool) -> VarSymbol {
manager.new_var_symbol(identifier, VarType::Array((type_t, dimensions)), is_global)
}

pub fn struct_type(manager: &mut SymbolManager, identifier: String, fields: (Vec<String>, Vec<VarType>), is_global: bool) -> VarSymbol {
manager.new_var_symbol(identifier, VarType::Struct(fields), is_global)
}

pub fn get_primitive(&self) -> Option<(BasicType, Val)> {
pub fn get_primitive(&self) -> Option<BasicType> {
match &self.symbol_type {
VarType::Primitive((t, v)) => Some((*t, v.clone())),
VarType::Primitive(t) => Some(*t),
_ => None,
}
}

pub fn get_array_dimensions(&self) -> Option<Vec<usize>> {
match &self.symbol_type {
VarType::Array((_, _, d)) => Some(d.clone()),
VarType::Array((_, d)) => Some(d.clone()),
_ => None,
}
}

pub fn get_array_value(&self, index: Vec<usize>) -> Option<Val> {
let mut index_value: usize = 0;
let dimensions = self.get_array_dimensions().unwrap();
for i in 0..index.len() {
index_value += index[i] * dimensions[i];
}
match &self.symbol_type {
VarType::Array((_, v, _)) => Some(v[index_value].clone()),
_ => None,
}
}

pub fn get_struct_field(&self, field: String) -> Option<(BasicType, Val)> {
pub fn get_struct_field(&self, field: String) -> Option<BasicType> {
match &self.symbol_type {
VarType::Struct((fields, types)) => {
for i in 0..fields.len() {
if fields[i] == field {
return match &types[i] {
VarType::Primitive((t, v)) => Some((*t, v.clone())),
VarType::Primitive(t) => Some(*t),
_ => None,
}
}
Expand All @@ -68,7 +57,7 @@ impl VarSymbol {
},
_ => None,
}
}
}
}

// From for FuncSymbol
Expand Down
44 changes: 14 additions & 30 deletions src/analyser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,50 +11,34 @@ pub mod manager;

#[cfg(test)]
mod tests {
use crate::symbol::{Symbol, VarType, BasicType, Val, VarSymbol};
use crate::symbol::{Symbol, VarType, BasicType, VarSymbol};
use spl_parser::parse;
use crate::table::ScopeTable;
use crate::stack::ScopeStack;
use crate::manager::SymbolManager;
use crate::walker::Walker;

fn parse_program_symbols(program: &str) -> Vec<VarSymbol> {
fn parse_program(program: &str) -> ScopeStack {
let ast = parse(program).unwrap();
let manager = SymbolManager::default();
let mut walker = Walker::new(ast, manager);
walker.traverse();
walker.get_symbols()
walker.get_tables()
}

#[test]
fn test_symbol_table() {
fn test_scope_stack(){
let program = r#"
int a = 0;
int b = 0;
"#;
let symbols = parse_program_symbols(program);
let mut table = ScopeTable::<VarSymbol>::new();
for symbol in symbols {
table.insert(symbol.identifier.clone(), symbol);
}
assert_eq!(format!("{}", table), "a: Symbol { id: 1, is_global: false, identifier: \"a\", symbol_type: Primitive((Int, Int(0))) }\nb: Symbol { id: 2, is_global: false, identifier: \"b\", symbol_type: Primitive((Int, Int(0))) }\n");
let a = table.lookup(&String::from("a")).unwrap();
assert_eq!(a.get_primitive().unwrap().0, (BasicType::Int));
assert_eq!(a.get_primitive().unwrap().1, (Val::Int(0)));

table.remove(&String::from("a"));
if let Some(a) = table.lookup(&String::from("a")) {
assert!(false);
int main(){
int a = 0;
int b = 1;
{
int a = 1;
int b = 2;
}
}
"#;
let table = parse_program(program);
assert_eq!(format!("{}", table), "")
}

// fn test_scope_stack(){
// let program = r#"
// int a = 0;
// int b = 0;
// "#;
// let symbols = parse_program_symbols(program);
// let mut stack = ScopeStack::new();

// }
}
1 change: 1 addition & 0 deletions src/analyser/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::fmt::Display;
use crate::symbol::{FuncSymbol, Symbol, VarSymbol, FuncType, VarType};
use spl_ast::tree::Variable;
use spl_ast::tree::Function;
use crate::error::SemanticError;


#[derive(Default)]
Expand Down
5 changes: 3 additions & 2 deletions src/analyser/src/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ use std::rc::Rc;
use std::cell::RefCell;
use crate::error::SemanticError;

#[derive(Clone, Debug)]
pub struct ScopeStack {
func_scope: Rc<RefCell<ScopeTable<FuncSymbol>>>,
stack: Vec<Rc<RefCell<ScopeTable<VarSymbol>>>>,
pub func_scope: Rc<RefCell<ScopeTable<FuncSymbol>>>,
pub stack: Vec<Rc<RefCell<ScopeTable<VarSymbol>>>>,
depth: usize,
}

Expand Down
16 changes: 3 additions & 13 deletions src/analyser/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ pub enum VarType {
Struct(StructType)
}

pub type PrimType = (BasicType, Val);
pub type ArrayType = (BasicType, Vec<Val>, Vec<usize>);
pub type PrimType = (BasicType);
pub type ArrayType = (BasicType, Vec<usize>);
pub type StructType = (Vec<String>, Vec<VarType>);
pub type FuncType = (FuncReturnType, Vec<VarType>);

Expand All @@ -55,14 +55,4 @@ pub enum FuncReturnType {
String,
#[default]
Void
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub enum Val {
Int(i32),
Char(char),
Float(f32),
Bool(bool),
String(String),
Array(ArrayType)
}
}
1 change: 1 addition & 0 deletions src/analyser/src/table.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashMap;

// Define the HashMap structure
#[derive(Clone, Debug)]
pub struct ScopeTable<T>
{
pub symbols: HashMap<String, T>
Expand Down
28 changes: 22 additions & 6 deletions src/analyser/src/walker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ pub struct Walker {
pub program: Program,
pub manager: SymbolManager,
pub errors: Vec<SemanticError>,
pub vecs: Vec<VarSymbol>,
pub symbol_tables: ScopeStack,
}

Expand All @@ -20,13 +19,16 @@ impl Walker {
program,
manager,
errors: Vec::new(),
vecs: Vec::new(),
symbol_tables: ScopeStack::new()
}
}

pub fn get_symbols(&self) -> Vec<VarSymbol> {
self.vecs.clone()
pub fn get_tables(&self) -> ScopeStack {
self.symbol_tables.clone()
}

pub fn get_errors(&self) -> Vec<SemanticError> {
self.errors.clone()
}

pub fn traverse(&mut self) {
Expand Down Expand Up @@ -86,7 +88,6 @@ impl Walker {
}
Variable::VarDeclaration(name, values, dimensions) => {
println!("VarDeclaration: {:?}, Values: {:?}, Dimensions: {:?}", name, values, dimensions);
let val = Val::from(*values.clone());
// Validate all dimensions and collect them
let mut dim = Vec::new();
for comp_expr in *dimensions.clone() {
Expand Down Expand Up @@ -114,7 +115,7 @@ impl Walker {
}
let new_symbol = self.manager.new_var_symbol(
*name.clone(),
VarType::Primitive((BasicType::from(val.clone()), val)),
VarType::Primitive(BasicType::from(*values.clone())),
true
);
match self.symbol_tables.define_var_symbol(new_symbol) {
Expand All @@ -128,6 +129,14 @@ impl Walker {
}
Variable::VarAssignment(name, value, dimensions) => {
println!("VarAssignment: {:?}, Value: {:?}, Dimensions: {:?}", name, value, dimensions);
match self.symbol_tables.get_var_symbol(name) {
Ok(symbol) => {

}
Err(err) => {
self.errors.push(err)
}
}
}
Variable::StructReference(name) => println!("StructReference: {:?}", name),
Variable::StructDefinition(name, variables) => {
Expand Down Expand Up @@ -173,9 +182,16 @@ impl Walker {
match body {
Body::Body(exprs) => {
println!("Body");
self.symbol_tables.extend_scope();
for expr in exprs {
self.traverse_expr(expr);
}
// match self.symbol_tables.exit_scope() {
// Ok(()) => {}
// Err(err) => {
// self.errors.push(err)
// }
// }
}
Body::Error => println!("Error in Body"),
}
Expand Down

0 comments on commit 92a0ea4

Please sign in to comment.