2025-02-04 14:10:16 +02:00
use crate ::compiler ::variable ::Value ;
2025-02-03 18:01:39 +02:00
use std ::collections ::HashMap ;
#[ derive(Default) ]
pub struct SymTab < ' source > {
2025-02-04 00:34:56 +02:00
tables : Vec < HashMap < & ' source str , Value > > ,
2025-02-03 18:01:39 +02:00
}
impl < ' source > SymTab < ' source > {
pub fn get ( & mut self , symbol : & str ) -> & mut Value {
2025-02-04 00:34:56 +02:00
for i in ( 0 .. self . tables . len ( ) ) . rev ( ) {
if self . tables [ i ] . contains_key ( symbol ) {
return self . tables [ i ] . get_mut ( symbol ) . unwrap ( ) ;
}
2025-02-03 18:01:39 +02:00
}
2025-02-04 00:34:56 +02:00
panic! ( " No symbol {} found! " , symbol ) ;
2025-02-03 18:01:39 +02:00
}
2025-02-04 00:34:56 +02:00
pub fn new ( ) -> SymTab < ' source > {
let globals = HashMap ::from ( [
2025-02-03 23:04:36 +02:00
( " + " , Value ::Func ( Value ::add ) ) ,
( " * " , Value ::Func ( Value ::mul ) ) ,
( " - " , Value ::Func ( Value ::sub ) ) ,
( " / " , Value ::Func ( Value ::div ) ) ,
( " % " , Value ::Func ( Value ::rem ) ) ,
( " == " , Value ::Func ( Value ::eq ) ) ,
( " != " , Value ::Func ( Value ::neq ) ) ,
( " < " , Value ::Func ( Value ::lt ) ) ,
( " <= " , Value ::Func ( Value ::le ) ) ,
( " > " , Value ::Func ( Value ::gt ) ) ,
( " >= " , Value ::Func ( Value ::ge ) ) ,
( " not " , Value ::Func ( Value ::not ) ) ,
( " neg " , Value ::Func ( Value ::neg ) ) ,
] ) ;
2025-02-03 18:01:39 +02:00
SymTab {
2025-02-04 00:34:56 +02:00
tables : vec ! [ globals ] ,
}
}
pub fn push_level ( & mut self ) {
self . tables . push ( HashMap ::new ( ) ) ;
}
pub fn remove_level ( & mut self ) {
self . tables . pop ( ) ;
}
pub fn insert ( & mut self , name : & ' source str , val : Value ) {
if self
. tables
. last_mut ( )
. expect ( " Symbols table should never be empty! " )
. insert ( name , val )
. is_some ( )
{
panic! ( " Variable {} already defined in this scope! " , name )
2025-02-03 18:01:39 +02:00
}
}
}