Using the Parser gem

Given a Ruby source file we want to parse ...

file: simple_number.rb

#!/usr/bin/env ruby

# This file is called simpleNumber.rb
# It contains the class SimpleNumber

class SimpleNumber

  def initialize( num )
    raise if !num.is_a?(Numeric)
    @x = num
  end
  
#Invokes the block once for add element of self, replacing the element with the value returned by #block. See also multiply.
#
#   a = [ "a", "b", "c", "d" ]
#   a.collect! {|x| x + "!" }
#   a             #=>  [ "a!", "b!", "c!", "d!" ]

  def add( y )
    @x + y
  end

  def multiply( y )
    @x * y
  end

end

we can parse it with ...

require 'parser/current'
p Parser::CurrentRuby.parse File.read('simple_number.rb')

to output the following:

(class
  (const nil :SimpleNumber) nil
  (begin
    (def :initialize
      (args
        (arg :num))
      (begin
        (if
          (send
            (send
              (lvar :num) :is_a?
              (const nil :Numeric)) :!)
          (send nil :raise) nil)
        (ivasgn :@x
          (lvar :num))))
    (def :add
      (args
        (arg :y))
      (send
        (ivar :@x) :+
        (lvar :y)))
    (def :multiply
      (args
        (arg :y))
      (send
        (ivar :@x) :*
        (lvar :y)))))
 => (class
  (const nil :SimpleNumber) nil
  (begin
    (def :initialize
      (args
        (arg :num))
      (begin
        (if
          (send
            (send
              (lvar :num) :is_a?
              (const nil :Numeric)) :!)
          (send nil :raise) nil)
        (ivasgn :@x
          (lvar :num))))
    (def :add
      (args
        (arg :y))
      (send
        (ivar :@x) :+
        (lvar :y)))
    (def :multiply
      (args
        (arg :y))
      (send
        (ivar :@x) :*
        (lvar :y))))) 

Resources

Tags:
Source:
0915hrs.txt
Published:
24-06-2014 09:15