upgrades ast to first class

This commit is contained in:
Torsten Ruger
2014-05-05 09:51:16 +03:00
parent 7c0aa8ae7d
commit 7c7e58ea62
10 changed files with 40 additions and 40 deletions

26
lib/ast/conversion.rb Normal file
View File

@ -0,0 +1,26 @@
module Ast
# Convert ast to vm-values via visitor pattern
# We do this (what would otherwise seem like foot-shuffling) to keep the layers seperated
# Ie towards the feature goal of reusing the same parse for several binary outputs
# scope of the funcitons is thus class scope ie self is the expression and all attributes work
# gets included into Value
module Conversion
def to_value
cl_name = self.class.name.to_s.split("::").last.gsub("Expression","").downcase
send "#{cl_name}_value"
end
def funcall_value
FunctionCall.new( name , args.collect{ |a| a.to_value } )
end
def string_value
ObjectReference.new( StringValue.new(string) )
end
end
end
require_relative "expression"
Ast::Expression.class_eval do
include Ast::Conversion
end

87
lib/ast/expression.rb Normal file
View File

@ -0,0 +1,87 @@
# ast classes
module Ast
class Expression
def eval
raise "abstract"
end
def compare other , attributes
return false unless other.class == self.class
attributes.each do |a|
left = send(a)
right = other.send( a)
return false unless left.class == right.class
return false unless left == right
end
return true
end
end
class IntegerExpression < Expression
attr_reader :value
def initialize val
@value = val
end
def == other
compare other , [:value]
end
end
class NameExpression < Expression
attr_reader :name
def initialize name
@name = name
end
def == other
compare other , [:name]
end
end
class StringExpression < Expression
attr_reader :string
def initialize str
@string = str
end
def == other
compare other , [:string]
end
end
class FuncallExpression < Expression
attr_reader :name, :args
def initialize name, args
@name , @args = name , args
end
def == other
compare other , [:name , :args]
end
end
class ConditionalExpression < Expression
attr_reader :cond, :if_true, :if_false
def initialize cond, if_true, if_false
@cond, @if_true, @if_false = cond, if_true, if_false
end
def == other
compare other , [:cond, :if_true, :if_false]
end
end
class AssignmentExpression < Expression
attr_reader :assignee, :assigned
def initialize assignee, assigned
@assignee, @assigned = assignee, assigned
end
def == other
compare other , [:assignee, :assigned]
end
end
class FunctionExpression < Expression
attr_reader :name, :params, :block
def initialize name, params, block
@name, @params, @block = name, params, block
end
def == other
compare other , [:name, :params, :block]
end
end
end