#!/usr/bin/ruby

# dumps the parse tree of a ruby script (first argument)
# to a file (second argument, or stdout if none given)
# as a series of lisp s-expressions

require 'rubygems'
require_gem 'ParseTree'

def parse( text )
  m = Module::new
  m.module_eval "def stub ; class << self ; #{ text } end end"
  ParseTree.new.parse_tree_for_method( m, :stub )[2][1][2][2][1][1..-1]
end

def format_lisp_sexp( sexp, indent=0 )
  first = true

  sexp.map do |value|
    pad = " "

    output = case value
             when Array
               pad = "\n#{ " " * indent }"
               "(#{ format_lisp_sexp( value, indent + 2 ) })"
             when Symbol
               value.to_s
             when String
               value.inspect
             else
               "#<#{ value.inspect }>"
             end

    if first
      first = false
      output
    else
      pad + output
    end
  end.to_s
end

tree = File.open( $*[0], "r" ) { |stream| parse( stream.read ) }
if $*[1]
  File.open( $*[1], "w" ) { |stream| stream.puts format_lisp_sexp( tree ) }
else
  $stdout.puts format_lisp_sexp( tree )
end

