Skip to content

Commit

Permalink
fix: fix shadowing with same variable
Browse files Browse the repository at this point in the history
We now make sure to see if a name has already been defined in the
correct scope and if it is the case when do not define it again.
  • Loading branch information
Yag000 committed Aug 11, 2023
1 parent 03ea58c commit d99ec20
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
26 changes: 25 additions & 1 deletion crates/compiler/src/compiler.rs
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,31 @@ impl Compiler {
self.emit(Opcode::Pop, vec![]);
}
Statement::Let(s) => {
let symbol = self.symbol_table.define(s.name.value);
// This step is extremely important. If it is not done then when shadowing variables
// and using the previous value we get an error. Because we would have assigned
// a new index to the symbol and the GetGlobal instruction would get a NULL
// value instead of the previous value. (corresponds to issue #11)
let symbol = match self.symbol_table.resolve(&s.name.value) {
Some(symbol) => match symbol.scope {
SymbolScope::Global => {
// A Local variable should never replace a global one
if self.symbol_table.has_outer() {
// This means that the symbol will
// be local and not global
self.symbol_table.define(s.name.value)
} else {
symbol
}
}
SymbolScope::Local => symbol,

// We only want to do in in the case of "normal" variable assignation.
// The special cases should not be touched, since the program should not
// have access to them, only the compiler/vm
_ => self.symbol_table.define(s.name.value),
},
None => self.symbol_table.define(s.name.value),
};

self.compile_expression(s.value)?;

Expand Down
4 changes: 4 additions & 0 deletions crates/compiler/src/symbol_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ impl SymbolTable {
self.store.insert(symbol.name.clone(), symbol.clone());
symbol
}

pub fn has_outer(&self) -> bool{
self.outer.is_some()
}
}

#[cfg(test)]
Expand Down

0 comments on commit d99ec20

Please sign in to comment.