2018-01-19 05:48:08 -05:00
|
|
|
# Simple DSL implementation for Ripper code generation
|
|
|
|
#
|
|
|
|
# input: /*% ripper: stmts_add(stmts_new, void_stmt) %*/
|
2018-01-20 12:45:24 -05:00
|
|
|
# output:
|
|
|
|
# VALUE v1, v2;
|
|
|
|
# v1 = dispatch0(stmts_new);
|
|
|
|
# v2 = dispatch0(void_stmt);
|
|
|
|
# $$ = dispatch2(stmts_add, v1, v2);
|
2018-01-19 05:48:08 -05:00
|
|
|
|
|
|
|
class DSL
|
|
|
|
def initialize(code, options)
|
|
|
|
@events = {}
|
|
|
|
@error = options.include?("error")
|
|
|
|
@brace = options.include?("brace")
|
2018-01-19 10:43:42 -05:00
|
|
|
@final = options.include?("final")
|
2018-01-20 12:45:24 -05:00
|
|
|
@vars = 0
|
2018-01-19 05:48:08 -05:00
|
|
|
|
|
|
|
# create $1 == "$1", $2 == "$2", ...
|
|
|
|
re, s = "", ""
|
|
|
|
1.upto(9) do |n|
|
|
|
|
re << "(..)"
|
|
|
|
s << "$#{ n }"
|
|
|
|
end
|
|
|
|
/#{ re }/ =~ s
|
|
|
|
|
2018-01-20 00:39:03 -05:00
|
|
|
# struct parser_params *p
|
|
|
|
p = "p"
|
|
|
|
|
2018-01-20 12:45:24 -05:00
|
|
|
@code = ""
|
|
|
|
@last_value = eval(code)
|
2018-01-19 05:48:08 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
attr_reader :events
|
|
|
|
|
|
|
|
undef lambda
|
|
|
|
undef hash
|
|
|
|
undef class
|
|
|
|
|
|
|
|
def generate
|
|
|
|
s = "$$"
|
2018-01-19 10:43:42 -05:00
|
|
|
s = "p->result" if @final
|
2018-01-20 12:45:24 -05:00
|
|
|
s = "#@code#{ s }=#@last_value;"
|
|
|
|
s = "{VALUE #{ (1..@vars).map {|v| "v#{ v }" }.join(",") };#{ s }}" if @vars > 0
|
2018-01-19 05:48:08 -05:00
|
|
|
s << "ripper_error(p);" if @error
|
|
|
|
s = "{#{ s }}" if @brace
|
2018-01-20 00:39:00 -05:00
|
|
|
"\t\t\t#{s}"
|
2018-01-19 05:48:08 -05:00
|
|
|
end
|
|
|
|
|
2018-01-20 12:45:24 -05:00
|
|
|
def new_var
|
|
|
|
"v#{ @vars += 1 }"
|
|
|
|
end
|
|
|
|
|
2018-01-20 12:45:25 -05:00
|
|
|
def opt_event(event, default, addend)
|
|
|
|
add_event(event, [default, addend], true)
|
|
|
|
end
|
|
|
|
|
|
|
|
def add_event(event, args, qundef_check = false)
|
2018-01-20 12:52:51 -05:00
|
|
|
event = event.to_s.sub(/!\z/, "")
|
2018-01-20 12:45:25 -05:00
|
|
|
@events[event] = args.size
|
|
|
|
vars = []
|
|
|
|
args.each do |arg|
|
|
|
|
vars << v = new_var
|
|
|
|
@code << "#{ v }=#{ arg };"
|
|
|
|
end
|
|
|
|
v = new_var
|
|
|
|
d = "dispatch#{ args.size }(#{ [event, *vars].join(",") })"
|
|
|
|
d = "#{ vars.last }==Qundef ? #{ vars.first } : #{ d }" if qundef_check
|
|
|
|
@code << "#{ v }=#{ d };"
|
|
|
|
v
|
|
|
|
end
|
|
|
|
|
2018-01-19 10:22:36 -05:00
|
|
|
def method_missing(event, *args)
|
|
|
|
if event.to_s =~ /!\z/
|
2018-01-20 12:45:25 -05:00
|
|
|
add_event(event, args)
|
2018-01-20 00:39:02 -05:00
|
|
|
elsif args.empty? and /\Aid[A-Z]/ =~ event.to_s
|
|
|
|
event
|
2018-01-19 05:48:08 -05:00
|
|
|
else
|
2018-01-19 10:22:36 -05:00
|
|
|
"#{ event }(#{ args.join(", ") })"
|
2018-01-19 05:48:08 -05:00
|
|
|
end
|
|
|
|
end
|
2018-01-20 00:39:01 -05:00
|
|
|
|
|
|
|
def self.const_missing(name)
|
|
|
|
name
|
|
|
|
end
|
2018-01-19 05:48:08 -05:00
|
|
|
end
|
|
|
|
|