ANTLR for Ruby

Scopes

updated Sunday, August 04, 2013 at 09:59PM EDT

The term scope can be a little confusing, as it used to describe a number of different constructs within ANTLR, each with its own purpose. Furthermore, when the discussion begins to inject the word scope as it is generally understood in theoretical computing, as in “dynamically-scoped language,” the term’s meaning becomes increasingly vague.

For the purposes of this article, the term scope refers to an abstract data object used to store information during the recognition process. In the ruby source code, scopes are mostly implmented as simple Struct classes. Therefore, references to scope objects in action blocks are Struct objects, which respond to the standard Struct methods.

There are several different types of scopes in ANTLR grammars. Rule and global scopes are general structures that are maintained on a stack to hold arbitrary values; they provide a convenient way to exchange information with other rules. Return scopes are used to specify an arbitrary number of return values for a rule. Additionally, they are used provide useful information about the recognition work performed by the rule to an outer rule that referenced it, such as the range of tokens advanced during the rule. Finally, parameter scopes refer to the named arguments of a rule.

Rule Scopes

01
parser grammar IUseARuleScope;
02
03
@header { require 'set' }
04
05
boring_block
06
scope {
07
  symbols;
08
}
09
@init {
10
    $boring_block::symbols = Set.new;
11
}
12
@after {
13
    puts( "Found declarations for these variables: " )
14
    $boring_block::symbols.sort.each { | n | puts( "  - #{ n }" ) }
15
}
16
    : '{' number_declarations* assignments+ '}'
17
    ;
18
19
number_declarations
20
    : 'int' ID $boring_block::symbols.add( $ID.text ) } ';'
21
    ;
22
23
assignments
24
  : ID '=' NUM ';'
25
    {
26
        $boring_block::symbols.include?( $ID.text ) or 
27
          raise( "%p has not been declared" % $ID.text )
28
    }
29
  ;

Global / Grammar Scopes

Return Scopes

Parameter Scopes