Class: ANTLR3::Scope

Inherits:
Struct
  • Object
show all
Defined in:
lib/antlr3/recognizers.rb

Overview

Scope

Scope is used to represent instances of ANTLR's various attribute scopes. It is identical to Ruby's built-in Struct class, but it takes string attribute declarations from the ANTLR grammar as parameters, and overrides the #initialize method to set the default values if any are present in the scope declaration.

Block = Scope.new( "name", "depth = 0", "variables = {}" )
Block.new                    # => #<struct Block name=nil, depth=0, variables={}>
Block.new( "function" )      # => #<struct Block name="function", depth=0, variables={}>
Block.new( 'a', 1, :x => 3 ) # => #<struct Block name="a", depth=1, variables={ :x => 3 }>

Class Method Summary collapse

Class Method Details

.new(*declarations, &body) ⇒ Object


145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/antlr3/recognizers.rb', line 145

def self.new( *declarations, &body )
  names = []
  defaults = {}
  for decl in declarations
    name, default = decl.to_s.split( /\s*=\s*/, 2 )
    names << ( name = name.to_sym )
    default and defaults[ name ] = default
  end
  super( *names ) do
    
    # If no defaults, leave the initialize method the same as
    # the struct's default initialize for speed. Otherwise,
    # overwrite the initialize to populate with default values.
    unless defaults.empty?
      parameters = names.map do | name |
        "#{ name } = " << defaults.fetch( name, 'nil' )
      end.join( ', ' )
      class_eval( "def initialize( \#{ parameters } )\nsuper( \#{ names.join( ', ' ) } )\nend\n" )
    end
    
    body and class_eval( &body )
  end
end