= LiveAST

== Summary

A pure Ruby library for obtaining live abstract syntax trees of
methods and procs.

== Synopsis

  require 'live_ast'

  class Greet
    def default
      "hello"
    end
  end

  #### ASTs of methods

  m = Greet.instance_method(:default)

  p m.to_ast
  # => s(:defn, :default, s(:args), s(:scope, s(:block,
  #     s(:str, "hello"))))

  #### ASTs of lambdas, procs, blocks

  f = lambda { "foo" }

  p f.to_ast
  # => s(:iter, s(:call, nil, :lambda, s(:arglist)), nil,
  #     s(:str, "foo"))

  def query(&block)
    p block.to_ast
    # => s(:iter, s(:call, nil, :query, s(:arglist)), nil,
    #     s(:str, "bar"))
  end

  query do
    "bar"
  end

  #### ASTs from dynamic code

  f = ast_eval "lambda { 'dynamic' }", binding

  p f.to_ast
  # => s(:iter, s(:call, nil, :lambda, s(:arglist)), nil,
  #     s(:str, "dynamic"))

  ast_eval "def g ; 'dynamic' ; end", binding
  m = method(:g)

  p m.to_ast
  # => s(:defn, :g, s(:args), s(:scope, s(:block, s(:str, "dynamic"))))

== Install

  % gem install live_ast

== Description

LiveAST enables a program to find the ASTs of objects created by
dynamically generated code. It may be used in a strictly noninvasive
manner, where no standard classes or methods are modified, or it may
be transparently integrated into Ruby (experimental). The default
setting is in between.

RubyParser is responsible for parsing and building the ASTs, though
another parser may be easily substituted (in fact the name to_ast is
used instead of to_sexp because LiveAST has no understanding of what
the parser outputs).

LiveAST is thread-safe.

Ruby 1.9.2 or higher is required.

== Links

* Documentation: http://liveast.rubyforge.org
* Rubyforge home: http://rubyforge.org/projects/liveast/
* Repository: http://github.com/quix/live_ast

== to_ruby

Although the ruby2ruby package (gem install ruby2ruby) is
not an official dependency of LiveAST, for convenience

  require 'live_ast/to_ruby'

will require ruby2ruby and define the to_ruby method for Method,
UnboundMethod, and Proc. These methods are one-liners which pass
the extracted ASTs to ruby2ruby.

  require 'live_ast'
  require 'live_ast/to_ruby'

  p lambda { |x, y| x + y }.to_ruby # => "lambda { |x, y| (x + y) }"

  class A
    def f
      "A#f"
    end
  end

  p A.instance_method(:f).to_ruby # => "def f\n  \"A#f\"\nend"

==

Thanks to Ryan Davis for writing RubyParser, Ruby2Ruby, minitest, and
many other great tools.

LiveAST is 249 lines of code (reported by simplecov) which employs a
simple trick to get these ASTs. Unlike ParseTree, which was the real
thing, LiveAST achieves its results by faking them. But like any
sufficiently plausible knockoff, you may never know the difference. Had
I thought of it sooner, I would have called it FarceTree.

==

James M. Lawrence

-- 
Posted via http://www.ruby-forum.com/.