rubyx/lib/parser/transform.rb

58 lines
2.2 KiB
Ruby
Raw Normal View History

2014-04-24 14:43:20 +02:00
require 'parslet'
2014-05-05 08:51:16 +02:00
require 'ast/expression'
2014-04-24 14:43:20 +02:00
module Parser
2014-04-24 14:43:20 +02:00
class Transform < Parslet::Transform
rule(:string => sequence(:chars)) { Ast::StringExpression.new chars.join }
rule(:esc => simple(:esc)) { '\\' + esc }
rule(char: simple(:char)) { char }
2014-05-05 08:51:16 +02:00
rule(:integer => simple(:value)) { Ast::IntegerExpression.new(value.to_i) }
rule(:name => simple(:name)) { Ast::NameExpression.new(name.to_s) }
2014-04-24 14:43:20 +02:00
rule(:argument => simple(:argument)) { argument }
rule(:argument_list => sequence(:argument_list)) { argument_list }
2014-04-24 14:43:20 +02:00
rule( :function_call => simple(:function_call),
:argument_list => sequence(:argument_list)) do
2014-05-05 08:51:16 +02:00
Ast::FuncallExpression.new(function_call.name, argument_list)
end
2014-04-24 14:43:20 +02:00
rule(:conditional => simple(:conditional),
:if_true => {:expressions => sequence(:if_true)},
:if_false => {:expressions => sequence(:if_false)}) do
2014-05-05 08:51:16 +02:00
Ast::ConditionalExpression.new(conditional, if_true, if_false)
end
2014-05-10 18:02:51 +02:00
rule(:while => simple(:while), :while_cond => simple(:while_cond) , :do => simple(:do),
:body => {:expressions => sequence(:body)}) do
Ast::WhileExpression.new(while_cond, body)
end
rule(:parmeter => simple(:parmeter)) { parmeter }
rule(:parmeter_list => sequence(:parmeter_list)) { parmeter_list }
2014-04-24 14:43:20 +02:00
rule(:function_definition => simple(:function_definition),
:parmeter_list => sequence(:parmeter_list),
:expressions => sequence(:expressions)) do
2014-05-05 08:51:16 +02:00
Ast::FunctionExpression.new(function_definition.name, parmeter_list, expressions)
end
2014-04-27 15:30:32 +02:00
rule(:asignee => simple(:left) , :asigned => simple(:right) ) do
Ast::AssignmentExpression.new(left , right )
end
rule(l: simple(:l), o: simple(:o) , r: simple(:r)) do
Ast::OperatorExpression.new( o.to_s.strip , l ,r)
end
2014-04-27 15:30:32 +02:00
#shortcut to get the ast tree for a given string
# optional second arguement specifies a rule that will be parsed (mainly for testing)
def self.ast string , rule = :root
syntax = Parser.new.send(rule).parse(string)
tree = Transform.new.apply(syntax)
tree
end
2014-04-24 14:43:20 +02:00
end
end