From dade99a51f7681ea9ad82aa208aa738ec09d732c Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Tue, 30 Aug 2022 19:23:14 -0700 Subject: [PATCH] 13.3.1 --- ruby/lib/lox/expr.rb | 1 + ruby/lib/lox/parser.rb | 8 ++++++++ ruby/test/lox/test_interpreter.rb | 22 ++++++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/ruby/lib/lox/expr.rb b/ruby/lib/lox/expr.rb index 1c1e7a8..b7ecc66 100644 --- a/ruby/lib/lox/expr.rb +++ b/ruby/lib/lox/expr.rb @@ -18,6 +18,7 @@ module Lox expr :Literal, :value expr :Logical, :left, :op, :right expr :Set, :object, :name, :value + expr :Super, :keyword, :method expr :This, :keyword expr :Unary, :op, :right expr :Variable, :name diff --git a/ruby/lib/lox/parser.rb b/ruby/lib/lox/parser.rb index a68b6d5..8a9dbc6 100644 --- a/ruby/lib/lox/parser.rb +++ b/ruby/lib/lox/parser.rb @@ -316,6 +316,14 @@ module Lox return Expr::Literal.new(true) if match?(:TRUE) return Expr::Literal.new(nil) if match?(:NIL) return Expr::Literal.new(prev.literal) if match?(:NUMBER, :STRING) + + if match?(:SUPER) + keyword = prev + consume!(:DOT, "Expect '.' after 'super'.") + method = consume!(:IDENTIFIER, "Expect superclass method name.") + return Expr::Super.new(keyword, method) + end + return Expr::This.new(prev) if match?(:THIS) return Expr::Variable.new(prev) if match?(:IDENTIFIER) diff --git a/ruby/test/lox/test_interpreter.rb b/ruby/test/lox/test_interpreter.rb index 5410fbc..4c5d21d 100644 --- a/ruby/test/lox/test_interpreter.rb +++ b/ruby/test/lox/test_interpreter.rb @@ -484,6 +484,28 @@ class TestInterpreter < Lox::Test SRC end + def test_calling_superclass_methods + assert_interpreted <<~OUT, <<~SRC + Fry until golden brown. + Pipe full of custard and coat with chocolate. + OUT + class Doughnut { + cook() { + print "Fry until golden brown."; + } + } + + class BostonCream < Doughnut { + cook() { + super.cook(); + print "Pipe full of custard and coat with chocolate."; + } + } + + BostonCream().cook(); + SRC + end + private def assert_interpreted(expected, src)