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)