From 5138410be4e89a096b22ee4e68409760f2e115f8 Mon Sep 17 00:00:00 2001 From: Luna Date: Mon, 3 Jun 2019 15:17:07 -0300 Subject: [PATCH] compiler: add scope support --- src/compiler.zig | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/compiler.zig b/src/compiler.zig index cd8eb85..f468ee8 100644 --- a/src/compiler.zig +++ b/src/compiler.zig @@ -244,6 +244,14 @@ pub const Compiler = struct { } } + fn beginScope(self: *Compiler) void { + self.scopeDepth += 1; + } + + fn endScope(self: *Compiler) void { + self.scopeDepth -= 1; + } + fn grouping(self: *Compiler, canAssign: bool) !void { try self.expression(); try self.consume(.RIGHT_PAREN, "Expect ')' after expression."); @@ -456,7 +464,7 @@ pub const Compiler = struct { try self.defineVariable(global); } - fn declaration(self: *Compiler) !void { + fn declaration(self: *Compiler) anyerror!void { if (try self.match(.VAR)) { try self.varDecl(); } else { @@ -465,9 +473,21 @@ pub const Compiler = struct { if (self.parser.panicMode) try self.synchronize(); } + fn block(self: *Compiler) anyerror!void { + while (!self.check(.RIGHT_BRACE) and !self.check(.EOF)) { + try self.declaration(); + } + + try self.consume(.RIGHT_BRACE, "Expect '}' after block."); + } + fn statement(self: *Compiler) !void { if (try self.match(.PRINT)) { try self.printStmt(); + } else if (try self.match(.LEFT_BRACE)) { + self.beginScope(); + try self.block(); + self.endScope(); } else { try self.exprStmt(); }