From 437a2b9633c595c2823afb064d414c3953d76cb0 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Wed, 17 Aug 2022 20:40:04 -0700 Subject: [PATCH] 11.3.2 --- ruby/lib/lox/resolver.rb | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/ruby/lib/lox/resolver.rb b/ruby/lib/lox/resolver.rb index 1321adf..fdd385a 100644 --- a/ruby/lib/lox/resolver.rb +++ b/ruby/lib/lox/resolver.rb @@ -7,7 +7,7 @@ module Lox @scopes = [] end - def resolve(values) + def resolve(*values) values.each do value.accept(self) end @@ -15,11 +15,18 @@ module Lox def visit_block(stmt) with_scope do - resolve(stmt.stmts) + resolve(*stmt.stmts) end nil end + def visit_var(stmt) + declare(stmt.name) + resolve(stmt.initializer) if stmt.initializer + define(stmt.name) + nil + end + private def with_block @@ -28,6 +35,19 @@ module Lox @scopes.pop end + def declare(name) + scope = @scopes.last + return if scope.nil? + + scope[name.lexeme] = false + end + + def define(name) + scope = @scopes.last + return if scope.nil? + + scopes[name.lexeme] = true + end end end