Implement block scopes (code inside braces)

- Putting code in between braces will create a new scope
This commit is contained in:
Kai-Philipp Nosper 2022-02-04 17:30:23 +01:00
parent cbf31fa513
commit 8b67c4d59c
4 changed files with 14 additions and 0 deletions

View File

@ -113,6 +113,7 @@ pub struct If {
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum Statement { pub enum Statement {
Expr(Expression), Expr(Expression),
Block(BlockScope),
Loop(Loop), Loop(Loop),
If(If), If(If),
Print(Expression), Print(Expression),

View File

@ -18,6 +18,7 @@ impl SimpleAstOptimizer {
for stmt in block { for stmt in block {
match stmt { match stmt {
Statement::Expr(expr) => Self::optimize_expr(expr), Statement::Expr(expr) => Self::optimize_expr(expr),
Statement::Block(block) => Self::optimize_block(block),
Statement::Loop(Loop { Statement::Loop(Loop {
condition, condition,
advancement, advancement,

View File

@ -78,6 +78,10 @@ impl Interpreter {
self.resolve_expr(expr); self.resolve_expr(expr);
} }
Statement::Block(block) => {
self.run_block(block);
}
Statement::Loop(looop) => { Statement::Loop(looop) => {
// loop runs as long condition != 0 // loop runs as long condition != 0
loop { loop {

View File

@ -50,6 +50,14 @@ impl<T: Iterator<Item = Token>> Parser<T> {
} }
Token::EoF | Token::RBraces => break, Token::EoF | Token::RBraces => break,
Token::LBraces => {
self.next();
prog.push(Statement::Block(self.parse_scoped_block()));
if !matches!(self.next(), Token::RBraces) {
panic!("Error parsing block: Expectected closing braces '}}'");
}
}
// By default try to lex a statement // By default try to lex a statement
_ => prog.push(self.parse_stmt()), _ => prog.push(self.parse_stmt()),
} }