vidarh / writing-a-compiler-in-ruby

Code from my series on writing a Ruby compiler in Ruby

This URL has Read+Write access

writing-a-compiler-in-ruby / extensions.rb
100644 38 lines (34 sloc) 0.91 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# some useful extension methods to existing classes
 
module Enumerable
  # returns all but the first elements
  def rest
    self[1..-1]
  end
end
 
class Array
  # Visit each node depth first
  # If the given block return :skip,
  # no children of this node gets visited
  # If the given block returns :stop,
  # no further visitation is done.
  #
  # Only Array / Expr nodes get visited.
  #
  # You can pass symbols that will be checked
  # against self[0] to determine whether or
  # not to yield
  #
  # FIXME: This should be moved to AST::Expr
  # when the parser is cleaned up to never
  # create "raw" arrays
  def depth_first(*arg,&block)
    ret = yield(self) if arg.member?(self[0])
    return :stop if ret == :stop
    return true if ret == :skip
    
    self.each do |n|
      ret = n.depth_first(*arg,&block) if n.is_a?(Array)
      return :stop if ret == :stop
    end
    return true
  end
end