• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1grammar t022scopes;
2
3options {
4    language=Cpp;
5}
6
7/* global scopes */
8scope aScope {
9names
10}
11
12@lexer::includes{
13#include "UserTestTraits.hpp"
14}
15@lexer::namespace
16{ Antlr3Test }
17
18@parser::includes {
19#include "UserTestTraits.hpp"
20}
21@parser::namespace
22{ Antlr3Test }
23
24a
25scope aScope;
26    :   {$aScope::names = [];} ID*
27    ;
28
29
30/* rule scopes, from the book, final beta, p.147 */
31
32b[v]
33scope {x}
34    : {$b::x = v;} b2
35    ;
36
37b2
38    : b3
39    ;
40
41b3
42    : {$b::x}?=> ID // only visible, if b was called with True
43    | NUM
44    ;
45
46
47/* rule scopes, from the book, final beta, p.148 */
48
49c returns [res]
50scope {
51    symbols
52}
53@init {
54    $c::symbols = set();
55}
56    : '{' c1* c2+ '}'
57        { $res = $c::symbols; }
58    ;
59
60c1
61    : 'int' ID {$c::symbols.add($ID.text)} ';'
62    ;
63
64c2
65    : ID '=' NUM ';'
66        {
67            if $ID.text not in $c::symbols:
68                raise RuntimeError($ID.text)
69        }
70    ;
71
72/* recursive rule scopes, from the book, final beta, p.150 */
73
74d returns [res]
75scope {
76    symbols
77}
78@init {
79    $d::symbols = set();
80}
81    : '{' d1* d2* '}'
82        { $res = $d::symbols; }
83    ;
84
85d1
86    : 'int' ID {$d::symbols.add($ID.text)} ';'
87    ;
88
89d2
90    : ID '=' NUM ';'
91        {
92            for s in reversed(range(len($d))):
93                if $ID.text in $d[s]::symbols:
94                    break
95            else:
96                raise RuntimeError($ID.text)
97        }
98    | d
99    ;
100
101/* recursive rule scopes, access bottom-most scope */
102
103e returns [res]
104scope {
105    a
106}
107@after {
108    $res = $e::a;
109}
110    : NUM { $e[0]::a = int($NUM.text); }
111    | '{' e '}'
112    ;
113
114
115/* recursive rule scopes, access with negative index */
116
117f returns [res]
118scope {
119    a
120}
121@after {
122    $res = $f::a;
123}
124    : NUM { $f[-2]::a = int($NUM.text); }
125    | '{' f '}'
126    ;
127
128
129/* tokens */
130
131ID  :   ('a'..'z')+
132    ;
133
134NUM :   ('0'..'9')+
135    ;
136
137WS  :   (' '|'\n'|'\r')+ {$channel=HIDDEN}
138    ;
139