From 766f281a5e03dfff7bbbe0891def61f0e4687975 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Mon, 29 Aug 2022 13:15:14 -0700 Subject: [PATCH] 12.3 --- ruby/lib/lox/instance.rb | 11 +++++++++++ ruby/lib/lox/interpreter.rb | 8 ++++++++ ruby/lib/lox/resolver.rb | 6 ++++++ ruby/test/lox/test_interpreter.rb | 30 ++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+) create mode 100644 ruby/lib/lox/instance.rb diff --git a/ruby/lib/lox/instance.rb b/ruby/lib/lox/instance.rb new file mode 100644 index 0000000..0b74998 --- /dev/null +++ b/ruby/lib/lox/instance.rb @@ -0,0 +1,11 @@ +module Lox + class Instance + + def initialize(klass) + @klass = klass + end + + def to_s = "#{@klass.name} instance" + + end +end diff --git a/ruby/lib/lox/interpreter.rb b/ruby/lib/lox/interpreter.rb index 79bea5e..e0ad8aa 100644 --- a/ruby/lib/lox/interpreter.rb +++ b/ruby/lib/lox/interpreter.rb @@ -1,5 +1,6 @@ require_relative "environment" require_relative "function" +require_relative "lox_class" module Lox class Interpreter @@ -43,6 +44,13 @@ module Lox nil end + def visit_class(stmt) + @env.define(stmt.name.lexeme, nil) + klass = LoxClass.new(stmt.name.lexeme) + @env.assign(stmt.name, klass) + nil + end + def execute_block(stmts, env) prev_env = @env @env = env diff --git a/ruby/lib/lox/resolver.rb b/ruby/lib/lox/resolver.rb index ac5aa27..224ceb5 100644 --- a/ruby/lib/lox/resolver.rb +++ b/ruby/lib/lox/resolver.rb @@ -24,6 +24,12 @@ module Lox nil end + def visit_class(stmt) + declare(stmt.name) + define(stmt.name) + nil + end + def visit_expr(stmt) = resolve(stmt.expr) def visit_function(stmt) diff --git a/ruby/test/lox/test_interpreter.rb b/ruby/test/lox/test_interpreter.rb index f2cfcf3..9abf291 100644 --- a/ruby/test/lox/test_interpreter.rb +++ b/ruby/test/lox/test_interpreter.rb @@ -306,6 +306,36 @@ class TestInterpreter < Lox::Test SRC end + def test_class + assert_interpreted "", <<~SRC + class Breakfast { + cook() { + print "Eggs a-fryin'!"; + } + + serve(who) { + print "Enjoy your breakfast, " + who + "."; + } + } + SRC + + assert_interpreted "DevonshireCream", <<~SRC + class DevonshireCream { + serveOn() { + return "Scones"; + } + } + + print DevonshireCream; // Prints "DevonshireCream". + SRC + + assert_interpreted "Bagel instance", <<~SRC + class Bagel {} + var bagel = Bagel(); + print bagel; // Prints "Bagel instance". + SRC + end + private def assert_interpreted(expected, src)