Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "ruby_parser"
- class RoelCompiler
- def compile source
- @concat_enabled = true
- @indent = 0
- compile_line *RubyParser.for_current_ruby.parse(source)
- end
- private
- def masgn *_args
- "(" << args(*_args) << ")"
- end
- def args *args
- args.map{ |arg|
- case arg
- when Symbol then arg.to_s
- else send(*arg)
- end
- }.join(", ")
- end
- def iter call_args, args_args, content = nil
- method_invocation = send *call_args
- args_string = args_args.length > 1 ? " |#{send(*args_args)}|" : ""
- @indent += 1
- content_string = content.nil? ? "" : "\n#{indent}#{compile_line(*content)}\n#{indent -1}"
- @indent -= 1
- "#{method_invocation}{#{args_string}#{content_string}}"
- end
- def str value
- value.inspect
- end
- def lit value
- value.inspect
- end
- def lvar value
- value.to_s
- end
- def block *args
- concat_enabled = @concat_enabled
- output = args.map{ |line|
- @concat_enabled = concat_enabled
- compile_line *line
- }.join(" +\n#{indent}")
- output
- end
- def indent offset = 0
- " " * (@indent + offset)
- end
- def hash *args
- "{ " << args.each_slice(2).map{ |key_arg, value_arg| "#{compile_line *key_arg} => #{compile_line *value_arg}" }.join(", ") << " }"
- end
- def ivar value
- value.to_s
- end
- def dstr *args
- prefix = args.shift
- partials = []
- partials << str(prefix) unless prefix.empty?
- args.each{ |arg|
- case arg.first
- when :str
- partials << str(arg.last) unless arg.last.empty?
- else
- partials << "#{compile_line(*arg)}.to_s"
- end
- }
- '('+partials.join("+")+')'
- end
- def evstr content
- compile_line(*content)
- end
- def block_pass *args
- "&" << compile_line(*args.first)
- end
- def const value
- value.to_s
- end
- def call target, method_name, *args
- prefix = target.nil? ? "" : "#{compile_line *target}."
- args_string = args.any? ? "(#{args.map{ |arg| compile_line *arg }.join(", ")})" : ""
- "#{prefix}#{method_name}#{args_string}"
- end
- def compile_line method, *args
- send(method, *args)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement