Last active
August 29, 2015 14:02
-
-
Save robertodecurnex/a264320ce3c9a781083d to your computer and use it in GitHub Desktop.
Ruby Parser (Writing a Ruby to JS parser 5' demo)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Pepe | |
def name | |
puts "Pepe" | |
end | |
end | |
message = "Hello " | |
puts(message) | |
Pepe.new.name | |
puts("!") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ruby_parser' | |
def parse s | |
case s[0] | |
when :call then | |
if s[1].nil? && s[2] == :puts | |
"process.stdout.write(#{parse(s[3])})" | |
elsif s[2] == :new | |
"new #{parse(s[1])}()" | |
else | |
"#{parse(s[1])}.#{s[2]}()" | |
end | |
when :lasgn then | |
"#{s[1]} = #{parse(s[2])}" | |
when :str then | |
"\"#{s[1]}\"" | |
when :lvar then | |
"#{s[1]}" | |
when :class then | |
"function #{s[1]} () {#{parse(s[3])}}" | |
when :defn then | |
"this.#{s[1]} = function(#{parse(s[2])}) {#{parse(s[3])}}" | |
when :args then | |
"" | |
when :const | |
"#{s[1]}" | |
else | |
"" | |
end | |
end | |
script = "" | |
pt = RubyParser.for_current_ruby.parse File.read('./hello.rb') | |
puts pt.inspect | |
if pt[0] == :block | |
pt.each do |s| | |
line = parse(s) | |
script += "#{line};\n" unless line.nil? || line.empty? | |
end | |
else | |
script += parse(pt); | |
end | |
File.write('hello.js', script) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment