diff --git a/ruby/lib/lox/expr.rb b/ruby/lib/lox/expr.rb index 70da550..2737930 100644 --- a/ruby/lib/lox/expr.rb +++ b/ruby/lib/lox/expr.rb @@ -1,33 +1,21 @@ -require_relative "visitable" - module Lox module Expr - Assign = Struct.new(:name, :value) do - include Visitable - end - - Binary = Struct.new(:left, :op, :right) do - include Visitable - end - - Grouping = Struct.new(:expr) do - include Visitable - end - - Literal = Struct.new(:value) do - include Visitable - end - - Logical = Struct.new(:left, :op, :right) do - include Visitable + def self.expr(name, *children) + klass = Struct.new(name.to_s, *children) do + def accept(visitor) + klass = self.class.to_s.split("::").last.downcase + visitor.send("visit_#{klass}", self) + end + end + const_set(name, klass) end - Unary = Struct.new(:op, :right) do - include Visitable - end - - Variable = Struct.new(:name) do - include Visitable - end + expr :Assign, :name, :value + expr :Binary, :left, :op, :right + expr :Grouping, :expr + expr :Literal, :value + expr :Logical, :left, :op, :right + expr :Unary, :op, :right + expr :Variable, :name end end diff --git a/ruby/lib/lox/stmt.rb b/ruby/lib/lox/stmt.rb index 8f95201..2b46968 100644 --- a/ruby/lib/lox/stmt.rb +++ b/ruby/lib/lox/stmt.rb @@ -1,25 +1,21 @@ -require_relative "visitable" +require_relative "expr" module Lox module Stmt - Block = Struct.new(:stmts) do - include Visitable + def self.stmt(name, *children) + klass = Struct.new(name.to_s, *children) do + def accept(visitor) + klass = self.class.to_s.split("::").last.downcase + visitor.send("visit_#{klass}", self) + end + end + const_set(name, klass) end - Expr = Struct.new(:expr) do - include Visitable - end - - If = Struct.new(:cond, :then, :else) do - include Visitable - end - - Print = Struct.new(:expr) do - include Visitable - end - - Var = Struct.new(:name, :initializer) do - include Visitable - end + stmt :Block, :stmts + stmt :Expr, :expr + stmt :If, :cond, :then, :else + stmt :Print, :expr + stmt :Var, :name, :initializer end end diff --git a/ruby/lib/lox/visitable.rb b/ruby/lib/lox/visitable.rb deleted file mode 100644 index d9866b9..0000000 --- a/ruby/lib/lox/visitable.rb +++ /dev/null @@ -1,8 +0,0 @@ -module Lox - module Visitable - def accept(visitor) - klass = self.class.to_s.split("::").last.downcase - visitor.send("visit_#{klass}", self) - end - end -end