2
require 'ruby2ruby'
require 'parsetree'

code = "puts(var)"
sexp = SexpProcessor.new.process(ParseTree.translate(code))
 # => s(:fcall, :puts, s(:array, s(:vcall, :var)))
code = Ruby2Ruby.new.process(sexp)
 # => UnknownNodeError: Bug! Unknown node-type :fcall to Ruby2Ruby

Is there some way to translate Sexps from ParseTree back to ruby code?

I started writing some code that would do this translation but I want to know if that already exists. Another problem is the Ruby2Ruby puts a lot of unneeded parentheses in arithmetic operations (like 4+3-2+-2**4 to (((4 + 3) - 2) + -(2 ** 4)), both working equivalently). Is there some way to remove them?

Bob Aman
  • 32,839
  • 9
  • 71
  • 95
Guilherme Bernal
  • 8,183
  • 25
  • 43
  • Working out the minimal set of parens necessary for unambiguous representation of the code is hard. –  Jan 26 '11 at 19:40
  • Maybe you don't need to use Sexps at all. Are you just trying to get at the source of the running code? – Seamus Abshere Jan 26 '11 at 23:25

2 Answers2

2

I'm not sure if this works for you, because you seem to want to parse ruby code out of strings, but if you actually want the source of running code, you can do:

$ irb
?> require 'rubygems'
=> true 
?> require 'parse_tree'
=> true 
?> require 'parse_tree_extensions'
=> true 
?> require 'ruby2ruby'
=> true 
?> def calc; 4+3-2+-2**4; end
=> nil 
?> puts method(:calc).to_ruby
def calc
  (((4 + 3) - 2) + -(2 ** 4))
end

Although that does add the spacing that you didn't want.

Seamus Abshere
  • 8,326
  • 4
  • 44
  • 61
  • Exploring the file "parse_tree_extensions.rb" I found class called `Unifier`, that converts the sexp to be readable to the Ruby2Ruby. My code now works if I add `require 'unified_ruby'; sexp = Unifier.new.process(sexp)` after calling the Ruby2Ruby. Thank you by the tip. – Guilherme Bernal Jan 27 '11 at 19:06
1

I think they ought to be compatible, as they're written by the same person, but sometimes bugs creep in (as can be seen in this question which featured incompatibilities between two gems by the same author).

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338