Skip to content

Commit

Permalink
add blocks to interpreter
Browse files Browse the repository at this point in the history
  • Loading branch information
coletonodonnell committed Feb 18, 2022
1 parent 78ee130 commit df2bfb1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
26 changes: 21 additions & 5 deletions src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ impl Interpreter {
pub fn build_interpreter(instance: crate::Lox) -> Interpreter {
Interpreter {
instance: instance,
environment: Environment::build_envrionment(instance)
environment: Environment::build_environment(instance)
}
}

// Interpret an expression
pub fn interpret(&mut self, statements: Vec<Stmt>) {
for statement in statements {
self.execute(statement)
}
}

Expand Down Expand Up @@ -67,15 +74,19 @@ impl Interpreter {
}
}

// Interpret an expression
pub fn interpret(&mut self, statements: Vec<Stmt>) {
fn execute_block(&mut self, statements: Vec<Stmt>, environment: Environment) {
let previous: Environment = self.environment.clone();
self.environment = environment;

for statement in statements {
self.execute(statement)
self.execute(statement);
}

self.environment = previous;
}
}

impl StmtVisitor<()> for Interpreter {
impl StmtVisitor<> for Interpreter {
fn visit_expression(&mut self, expression: Expr) {
self.visit(expression);
}
Expand Down Expand Up @@ -107,6 +118,11 @@ impl StmtVisitor<()> for Interpreter {
}
}
}

fn visit_block(&mut self, statements: Vec<Stmt>) {
self.execute_block(statements, Environment::build_environment(self.instance));
return
}
}

// See ExprVisitor at Expression for implementation requirements
Expand Down
8 changes: 4 additions & 4 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ impl Parser {
fn block(&mut self) -> Vec<Stmt>{
let mut statements: Vec<Stmt> = Vec::new();

while !(self.check(TokenType::RBrace)) && !self.is_end() {
while !self.check(TokenType::RBrace) && !self.is_end() {
if let Some(a) = self.declaration() {
statements.push(a);
}
Expand Down Expand Up @@ -265,13 +265,13 @@ impl Parser {
let name: Option<Token> = self.consume(TokenType::Id, "Expect variable name.".to_string());
match name {
Some(a) => {
let mut initalizer: Option<Expr> = None;
let mut initializer: Option<Expr> = None;
if self.match_type(vec![TokenType::Equal]) {
initalizer = Some(self.expression());
initializer = Some(self.expression());
}

let _a: Option<Token> = self.consume(TokenType::Semicolon, "Expect ';' after variable decleration.".to_string());
return Some(Stmt::Var{name: a, right: initalizer})
return Some(Stmt::Var{name: a, right: initializer})
},
None => return None
}
Expand Down

0 comments on commit df2bfb1

Please sign in to comment.