aboutsummaryrefslogtreecommitdiff
path: root/antlr-3.4/tool/src/main/antlr3/org/antlr/grammar/v3/ActionTranslator.g
blob: 0aca8b8fc4c65c4c693ad86c7786c3470e0cdd97 (plain)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
/*
 [The "BSD license"]
 Copyright (c) 2010 Terence Parr
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
lexer grammar ActionTranslator;
options {
  filter=true;  // try all non-fragment rules in order specified
  // output=template;  TODO: can we make tokens return templates somehow?
}

@header {
package org.antlr.grammar.v3;
import org.stringtemplate.v4.ST;
import org.antlr.runtime.*;
import org.antlr.tool.*;
import org.antlr.codegen.*;

import org.antlr.runtime.*;
import java.util.List;
import java.util.ArrayList;
import org.antlr.grammar.v3.ANTLRParser;

}

@members {
public List chunks = new ArrayList();
Rule enclosingRule;
int outerAltNum;
Grammar grammar;
CodeGenerator generator;
Token actionToken;

	public ActionTranslator(CodeGenerator generator,
								 String ruleName,
								 GrammarAST actionAST)
	{
		this(new ANTLRStringStream(actionAST.token.getText()));
		this.generator = generator;
		this.grammar = generator.grammar;
	    this.enclosingRule = grammar.getLocallyDefinedRule(ruleName);
	    this.actionToken = actionAST.token;
	    this.outerAltNum = actionAST.outerAltNum;
	}

	public ActionTranslator(CodeGenerator generator,
								 String ruleName,
								 Token actionToken,
								 int outerAltNum)
	{
		this(new ANTLRStringStream(actionToken.getText()));
		this.generator = generator;
		grammar = generator.grammar;
	    this.enclosingRule = grammar.getRule(ruleName);
	    this.actionToken = actionToken;
		this.outerAltNum = outerAltNum;
	}

/** Return a list of strings and ST objects that
 *  represent the translated action.
 */
public List translateToChunks() {
	// System.out.println("###\naction="+action);
	Token t;
	do {
		t = nextToken();
	} while ( t.getType()!= Token.EOF );
	return chunks;
}

public String translate() {
	List theChunks = translateToChunks();
	//System.out.println("chunks="+a.chunks);
	StringBuffer buf = new StringBuffer();
	for (int i = 0; i < theChunks.size(); i++) {
		Object o = (Object) theChunks.get(i);
		if ( o instanceof ST ) buf.append(((ST)o).render());
		else buf.append(o);
	}
	//System.out.println("translated: "+buf.toString());
	return buf.toString();
}

public List translateAction(String action) {
	String rname = null;
	if ( enclosingRule!=null ) {
		rname = enclosingRule.name;
	}
	ActionTranslator translator =
		new ActionTranslator(generator,
								  rname,
								  new CommonToken(ANTLRParser.ACTION,action),outerAltNum);
    return translator.translateToChunks();
}

public boolean isTokenRefInAlt(String id) {
    return enclosingRule.getTokenRefsInAlt(id, outerAltNum)!=null;
}
public boolean isRuleRefInAlt(String id) {
    return enclosingRule.getRuleRefsInAlt(id, outerAltNum)!=null;
}
public Grammar.LabelElementPair getElementLabel(String id) {
    return enclosingRule.getLabel(id);
}

public void checkElementRefUniqueness(String ref, boolean isToken) {
		List refs = null;
		if ( isToken ) {
		    refs = enclosingRule.getTokenRefsInAlt(ref, outerAltNum);
		}
		else {
		    refs = enclosingRule.getRuleRefsInAlt(ref, outerAltNum);
		}
		if ( refs!=null && refs.size()>1 ) {
			ErrorManager.grammarError(ErrorManager.MSG_NONUNIQUE_REF,
									  grammar,
									  actionToken,
									  ref);
		}
}

/** For \$rulelabel.name, return the Attribute found for name.  It
 *  will be a predefined property or a return value.
 */
public Attribute getRuleLabelAttribute(String ruleName, String attrName) {
	Rule r = grammar.getRule(ruleName);
	AttributeScope scope = r.getLocalAttributeScope(attrName);
	if ( scope!=null && !scope.isParameterScope ) {
		return scope.getAttribute(attrName);
	}
	return null;
}

AttributeScope resolveDynamicScope(String scopeName) {
	if ( grammar.getGlobalScope(scopeName)!=null ) {
		return grammar.getGlobalScope(scopeName);
	}
	Rule scopeRule = grammar.getRule(scopeName);
	if ( scopeRule!=null ) {
		return scopeRule.ruleScope;
	}
	return null; // not a valid dynamic scope
}

protected ST template(String name) {
	ST st = generator.getTemplates().getInstanceOf(name);
	chunks.add(st);
	return st;
}


}

/**	$x.y	x is enclosing rule, y is a return value, parameter, or
 * 			predefined property.
 *
 * 			r[int i] returns [int j]
 * 				:	{$r.i, $r.j, $r.start, $r.stop, $r.st, $r.tree}
 * 				;
 */
SET_ENCLOSING_RULE_SCOPE_ATTR
	:	'$' x=ID '.' y=ID WS? '=' expr=ATTR_VALUE_EXPR ';'
							{enclosingRule!=null &&
	                         $x.text.equals(enclosingRule.name) &&
	                         enclosingRule.getLocalAttributeScope($y.text)!=null}?
		//{System.out.println("found \$rule.attr");}
		{
		ST st = null;
		AttributeScope scope = enclosingRule.getLocalAttributeScope($y.text);
		if ( scope.isPredefinedRuleScope ) {
			if ( $y.text.equals("st") || $y.text.equals("tree") ) {
				st = template("ruleSetPropertyRef_"+$y.text);
				grammar.referenceRuleLabelPredefinedAttribute($x.text);
				st.add("scope", $x.text);
				st.add("attr", $y.text);
				st.add("expr", translateAction($expr.text));
			} else {
				ErrorManager.grammarError(ErrorManager.MSG_WRITE_TO_READONLY_ATTR,
										  grammar,
										  actionToken,
										  $x.text,
										  $y.text);
			}
		}
	    else if ( scope.isPredefinedLexerRuleScope ) {
	    	// this is a better message to emit than the previous one...
			ErrorManager.grammarError(ErrorManager.MSG_WRITE_TO_READONLY_ATTR,
									  grammar,
									  actionToken,
									  $x.text,
									  $y.text);
	    }
		else if ( scope.isParameterScope ) {
			st = template("parameterSetAttributeRef");
			st.add("attr", scope.getAttribute($y.text));
			st.add("expr", translateAction($expr.text));
		}
		else { // must be return value
			st = template("returnSetAttributeRef");
			st.add("ruleDescriptor", enclosingRule);
			st.add("attr", scope.getAttribute($y.text));
			st.add("expr", translateAction($expr.text));
		}
		}
	;
ENCLOSING_RULE_SCOPE_ATTR
	:	'$' x=ID '.' y=ID	{enclosingRule!=null &&
	                         $x.text.equals(enclosingRule.name) &&
	                         enclosingRule.getLocalAttributeScope($y.text)!=null}?
		//{System.out.println("found \$rule.attr");}
		{
		if ( isRuleRefInAlt($x.text)  ) {
			ErrorManager.grammarError(ErrorManager.MSG_RULE_REF_AMBIG_WITH_RULE_IN_ALT,
									  grammar,
									  actionToken,
									  $x.text);
		}
		ST st = null;
		AttributeScope scope = enclosingRule.getLocalAttributeScope($y.text);
		if ( scope.isPredefinedRuleScope ) {
			st = template("rulePropertyRef_"+$y.text);
			grammar.referenceRuleLabelPredefinedAttribute($x.text);
			st.add("scope", $x.text);
			st.add("attr", $y.text);
		}
	    else if ( scope.isPredefinedLexerRuleScope ) {
	    	// perhaps not the most precise error message to use, but...
			ErrorManager.grammarError(ErrorManager.MSG_RULE_HAS_NO_ARGS,
									  grammar,
									  actionToken,
									  $x.text);
	    }
		else if ( scope.isParameterScope ) {
			st = template("parameterAttributeRef");
			st.add("attr", scope.getAttribute($y.text));
		}
		else { // must be return value
			st = template("returnAttributeRef");
			st.add("ruleDescriptor", enclosingRule);
			st.add("attr", scope.getAttribute($y.text));
		}
		}
	;

/** Setting $tokenlabel.attr or $tokenref.attr where attr is predefined property of a token is an error. */
SET_TOKEN_SCOPE_ATTR
	:	'$' x=ID '.' y=ID WS? '='
							 {enclosingRule!=null && input.LA(1)!='=' &&
	                         (enclosingRule.getTokenLabel($x.text)!=null||
	                          isTokenRefInAlt($x.text)) &&
	                         AttributeScope.tokenScope.getAttribute($y.text)!=null}?
		//{System.out.println("found \$tokenlabel.attr or \$tokenref.attr");}
		{
		ErrorManager.grammarError(ErrorManager.MSG_WRITE_TO_READONLY_ATTR,
								  grammar,
								  actionToken,
								  $x.text,
								  $y.text);
		}
	;

/** $tokenlabel.attr or $tokenref.attr where attr is predefined property of a token.
 *  If in lexer grammar, only translate for strings and tokens (rule refs)
 */
TOKEN_SCOPE_ATTR
	:	'$' x=ID '.' y=ID	{enclosingRule!=null &&
	                         (enclosingRule.getTokenLabel($x.text)!=null||
	                          isTokenRefInAlt($x.text)) &&
	                         AttributeScope.tokenScope.getAttribute($y.text)!=null &&
	                         (grammar.type!=Grammar.LEXER ||
	                         getElementLabel($x.text).elementRef.token.getType()==ANTLRParser.TOKEN_REF ||
	                         getElementLabel($x.text).elementRef.token.getType()==ANTLRParser.STRING_LITERAL)}?
		// {System.out.println("found \$tokenlabel.attr or \$tokenref.attr");}
		{
		String label = $x.text;
		if ( enclosingRule.getTokenLabel($x.text)==null ) {
			// \$tokenref.attr  gotta get old label or compute new one
			checkElementRefUniqueness($x.text, true);
			label = enclosingRule.getElementLabel($x.text, outerAltNum, generator);
			if ( label==null ) {
				ErrorManager.grammarError(ErrorManager.MSG_FORWARD_ELEMENT_REF,
										  grammar,
										  actionToken,
										  "\$"+$x.text+"."+$y.text);
				label = $x.text;
			}
		}
		ST st = template("tokenLabelPropertyRef_"+$y.text);
		st.add("scope", label);
		st.add("attr", AttributeScope.tokenScope.getAttribute($y.text));
		}
	;

/** Setting $rulelabel.attr or $ruleref.attr where attr is a predefined property is an error
 *  This must also fail, if we try to access a local attribute's field, like $tree.scope = localObject
 *  That must be handled by LOCAL_ATTR below. ANTLR only concerns itself with the top-level scope
 *  attributes declared in scope {} or parameters, return values and the like.
 */
SET_RULE_SCOPE_ATTR
@init {
Grammar.LabelElementPair pair=null;
String refdRuleName=null;
}
	:	'$' x=ID '.' y=ID WS? '=' {enclosingRule!=null && input.LA(1)!='='}?
		{
		pair = enclosingRule.getRuleLabel($x.text);
		refdRuleName = $x.text;
		if ( pair!=null ) {
			refdRuleName = pair.referencedRuleName;
		}
		}
		// supercomplicated because I can't exec the above action.
		// This asserts that if it's a label or a ref to a rule proceed but only if the attribute
		// is valid for that rule's scope
		{(enclosingRule.getRuleLabel($x.text)!=null || isRuleRefInAlt($x.text)) &&
	      getRuleLabelAttribute(enclosingRule.getRuleLabel($x.text)!=null?enclosingRule.getRuleLabel($x.text).referencedRuleName:$x.text,$y.text)!=null}?
		//{System.out.println("found set \$rulelabel.attr or \$ruleref.attr: "+$x.text+"."+$y.text);}
		{
		ErrorManager.grammarError(ErrorManager.MSG_WRITE_TO_READONLY_ATTR,
								  grammar,
								  actionToken,
								  $x.text,
								  $y.text);
		}
	;

/** $rulelabel.attr or $ruleref.attr where attr is a predefined property*/
RULE_SCOPE_ATTR
@init {
Grammar.LabelElementPair pair=null;
String refdRuleName=null;
}
	:	'$' x=ID '.' y=ID {enclosingRule!=null}?
		{
		pair = enclosingRule.getRuleLabel($x.text);
		refdRuleName = $x.text;
		if ( pair!=null ) {
			refdRuleName = pair.referencedRuleName;
		}
		}
		// supercomplicated because I can't exec the above action.
		// This asserts that if it's a label or a ref to a rule proceed but only if the attribute
		// is valid for that rule's scope
		{(enclosingRule.getRuleLabel($x.text)!=null || isRuleRefInAlt($x.text)) &&
	      getRuleLabelAttribute(enclosingRule.getRuleLabel($x.text)!=null?enclosingRule.getRuleLabel($x.text).referencedRuleName:$x.text,$y.text)!=null}?
		//{System.out.println("found \$rulelabel.attr or \$ruleref.attr: "+$x.text+"."+$y.text);}
		{
		String label = $x.text;
		if ( pair==null ) {
			// \$ruleref.attr  gotta get old label or compute new one
			checkElementRefUniqueness($x.text, false);
			label = enclosingRule.getElementLabel($x.text, outerAltNum, generator);
			if ( label==null ) {
				ErrorManager.grammarError(ErrorManager.MSG_FORWARD_ELEMENT_REF,
										  grammar,
										  actionToken,
										  "\$"+$x.text+"."+$y.text);
				label = $x.text;
			}
		}
		ST st;
		Rule refdRule = grammar.getRule(refdRuleName);
		AttributeScope scope = refdRule.getLocalAttributeScope($y.text);
		if ( scope.isPredefinedRuleScope ) {
			st = template("ruleLabelPropertyRef_"+$y.text);
			grammar.referenceRuleLabelPredefinedAttribute(refdRuleName);
			st.add("scope", label);
			st.add("attr", $y.text);
		}
		else if ( scope.isPredefinedLexerRuleScope ) {
			st = template("lexerRuleLabelPropertyRef_"+$y.text);
			grammar.referenceRuleLabelPredefinedAttribute(refdRuleName);
			st.add("scope", label);
			st.add("attr", $y.text);
		}
		else if ( scope.isParameterScope ) {
			// TODO: error!
		}
		else {
			st = template("ruleLabelRef");
			st.add("referencedRule", refdRule);
			st.add("scope", label);
			st.add("attr", scope.getAttribute($y.text));
		}
		}
	;


/** $label	either a token label or token/rule list label like label+=expr */
LABEL_REF
	:	'$' ID {enclosingRule!=null &&
	            getElementLabel($ID.text)!=null &&
		        enclosingRule.getRuleLabel($ID.text)==null}?
		// {System.out.println("found \$label");}
		{
		ST st;
		Grammar.LabelElementPair pair = getElementLabel($ID.text);
		if ( pair.type==Grammar.RULE_LIST_LABEL ||
             pair.type==Grammar.TOKEN_LIST_LABEL ||
             pair.type==Grammar.WILDCARD_TREE_LIST_LABEL )
        {
			st = template("listLabelRef");
		}
		else {
			st = template("tokenLabelRef");
		}
		st.add("label", $ID.text);
		}
	;

/** $tokenref in a non-lexer grammar */
ISOLATED_TOKEN_REF
	:	'$' ID	{grammar.type!=Grammar.LEXER && enclosingRule!=null && isTokenRefInAlt($ID.text)}?
		//{System.out.println("found \$tokenref");}
		{
		String label = enclosingRule.getElementLabel($ID.text, outerAltNum, generator);
		checkElementRefUniqueness($ID.text, true);
		if ( label==null ) {
			ErrorManager.grammarError(ErrorManager.MSG_FORWARD_ELEMENT_REF,
									  grammar,
									  actionToken,
									  $ID.text);
		}
		else {
			ST st = template("tokenLabelRef");
			st.add("label", label);
		}
		}
	;

/** $lexerruleref from within the lexer */
ISOLATED_LEXER_RULE_REF
	:	'$' ID	{grammar.type==Grammar.LEXER &&
	             enclosingRule!=null &&
	             isRuleRefInAlt($ID.text)}?
		//{System.out.println("found \$lexerruleref");}
		{
		String label = enclosingRule.getElementLabel($ID.text, outerAltNum, generator);
		checkElementRefUniqueness($ID.text, false);
		if ( label==null ) {
			ErrorManager.grammarError(ErrorManager.MSG_FORWARD_ELEMENT_REF,
									  grammar,
									  actionToken,
									  $ID.text);
		}
		else {
			ST st = template("lexerRuleLabel");
			st.add("label", label);
		}
		}
	;

/**  $y 	return value, parameter, predefined rule property, or token/rule
 *          reference within enclosing rule's outermost alt.
 *          y must be a "local" reference; i.e., it must be referring to
 *          something defined within the enclosing rule.
 *
 * 			r[int i] returns [int j]
 * 				:	{$i, $j, $start, $stop, $st, $tree}
 *              ;
 *
 *	TODO: this might get the dynamic scope's elements too.!!!!!!!!!
 */
SET_LOCAL_ATTR
	:	'$' ID WS? '=' expr=ATTR_VALUE_EXPR ';' {enclosingRule!=null
													&& enclosingRule.getLocalAttributeScope($ID.text)!=null
													&& !enclosingRule.getLocalAttributeScope($ID.text).isPredefinedLexerRuleScope}?
		//{System.out.println("found set \$localattr");}
		{
		ST st;
		AttributeScope scope = enclosingRule.getLocalAttributeScope($ID.text);
		if ( scope.isPredefinedRuleScope ) {
			if ($ID.text.equals("tree") || $ID.text.equals("st")) {
				st = template("ruleSetPropertyRef_"+$ID.text);
				grammar.referenceRuleLabelPredefinedAttribute(enclosingRule.name);
				st.add("scope", enclosingRule.name);
				st.add("attr", $ID.text);
				st.add("expr", translateAction($expr.text));
			} else {
				ErrorManager.grammarError(ErrorManager.MSG_WRITE_TO_READONLY_ATTR,
										 grammar,
										 actionToken,
										 $ID.text,
										 "");
			}
		}
		else if ( scope.isParameterScope ) {
			st = template("parameterSetAttributeRef");
			st.add("attr", scope.getAttribute($ID.text));
			st.add("expr", translateAction($expr.text));
		}
		else {
			st = template("returnSetAttributeRef");
			st.add("ruleDescriptor", enclosingRule);
			st.add("attr", scope.getAttribute($ID.text));
			st.add("expr", translateAction($expr.text));
			}
		}
	;
LOCAL_ATTR
	:	'$' ID {enclosingRule!=null && enclosingRule.getLocalAttributeScope($ID.text)!=null}?
		//{System.out.println("found \$localattr");}
		{
		ST st;
		AttributeScope scope = enclosingRule.getLocalAttributeScope($ID.text);
		if ( scope.isPredefinedRuleScope ) {
			st = template("rulePropertyRef_"+$ID.text);
			grammar.referenceRuleLabelPredefinedAttribute(enclosingRule.name);
			st.add("scope", enclosingRule.name);
			st.add("attr", $ID.text);
		}
		else if ( scope.isPredefinedLexerRuleScope ) {
			st = template("lexerRulePropertyRef_"+$ID.text);
			st.add("scope", enclosingRule.name);
			st.add("attr", $ID.text);
		}
		else if ( scope.isParameterScope ) {
			st = template("parameterAttributeRef");
			st.add("attr", scope.getAttribute($ID.text));
		}
		else {
			st = template("returnAttributeRef");
			st.add("ruleDescriptor", enclosingRule);
			st.add("attr", scope.getAttribute($ID.text));
		}
		}
	;

/**	$x::y	the only way to access the attributes within a dynamic scope
 * 			regardless of whether or not you are in the defining rule.
 *
 * 			scope Symbols { List names; }
 * 			r
 * 			scope {int i;}
 * 			scope Symbols;
 * 				:	{$r::i=3;} s {$Symbols::names;}
 * 				;
 * 			s	:	{$r::i; $Symbols::names;}
 * 				;
 */
SET_DYNAMIC_SCOPE_ATTR
	:	'$' x=ID '::' y=ID WS? '=' expr=ATTR_VALUE_EXPR ';'
						   {resolveDynamicScope($x.text)!=null &&
						     resolveDynamicScope($x.text).getAttribute($y.text)!=null}?
		//{System.out.println("found set \$scope::attr "+ $x.text + "::" + $y.text + " to " + $expr.text);}
		{
		AttributeScope scope = resolveDynamicScope($x.text);
		if ( scope!=null ) {
			ST st = template("scopeSetAttributeRef");
			st.add("scope", $x.text);
			st.add("attr",  scope.getAttribute($y.text));
			st.add("expr",  translateAction($expr.text));
		}
		else {
			// error: invalid dynamic attribute
		}
		}
	;

DYNAMIC_SCOPE_ATTR
	:	'$' x=ID '::' y=ID
						   {resolveDynamicScope($x.text)!=null &&
						     resolveDynamicScope($x.text).getAttribute($y.text)!=null}?
		//{System.out.println("found \$scope::attr "+ $x.text + "::" + $y.text);}
		{
		AttributeScope scope = resolveDynamicScope($x.text);
		if ( scope!=null ) {
			ST st = template("scopeAttributeRef");
			st.add("scope", $x.text);
			st.add("attr",  scope.getAttribute($y.text));
		}
		else {
			// error: invalid dynamic attribute
		}
		}
	;


ERROR_SCOPED_XY
	:	'$' x=ID '::' y=ID
		{
		chunks.add(getText());
		generator.issueInvalidScopeError($x.text,$y.text,
		                                 enclosingRule,actionToken,
		                                 outerAltNum);		
		}
	;
	
/**		To access deeper (than top of stack) scopes, use the notation:
 *
 * 		$x[-1]::y previous (just under top of stack)
 * 		$x[-i]::y top of stack - i where the '-' MUST BE PRESENT;
 * 				  i.e., i cannot simply be negative without the '-' sign!
 * 		$x[i]::y  absolute index i (0..size-1)
 * 		$x[0]::y  is the absolute 0 indexed element (bottom of the stack)
 */
DYNAMIC_NEGATIVE_INDEXED_SCOPE_ATTR
	:	'$' x=ID '[' '-' expr=SCOPE_INDEX_EXPR ']' '::' y=ID
		// {System.out.println("found \$scope[-...]::attr");}
		{
		ST st = template("scopeAttributeRef");
		st.add("scope",    $x.text);
		st.add("attr",     resolveDynamicScope($x.text).getAttribute($y.text));
		st.add("negIndex", $expr.text);
		}		
	;

DYNAMIC_ABSOLUTE_INDEXED_SCOPE_ATTR
	:	'$' x=ID '[' expr=SCOPE_INDEX_EXPR ']' '::' y=ID 
		// {System.out.println("found \$scope[...]::attr");}
		{
		ST st = template("scopeAttributeRef");
		st.add("scope", $x.text);
		st.add("attr",  resolveDynamicScope($x.text).getAttribute($y.text));
		st.add("index", $expr.text);
		}		
	;

fragment
SCOPE_INDEX_EXPR
	:	(~']')+
	;
	
/** $r		y is a rule's dynamic scope or a global shared scope.
 * 			Isolated $rulename is not allowed unless it has a dynamic scope *and*
 * 			there is no reference to rulename in the enclosing alternative,
 * 			which would be ambiguous.  See TestAttributes.testAmbiguousRuleRef()
 */
ISOLATED_DYNAMIC_SCOPE
	:	'$' ID {resolveDynamicScope($ID.text)!=null}?
		// {System.out.println("found isolated \$scope where scope is a dynamic scope");}
		{
		ST st = template("isolatedDynamicScopeRef");
		st.add("scope", $ID.text);
		}		
	;
	
// antlr.g then codegen.g does these first two currently.
// don't want to duplicate that code.

/** %foo(a={},b={},...) ctor */
TEMPLATE_INSTANCE
	:	'%' ID '(' ( WS? ARG (',' WS? ARG)* WS? )? ')'
		// {System.out.println("found \%foo(args)");}
		{
		String action = getText().substring(1,getText().length());
		String ruleName = "<outside-of-rule>";
		if ( enclosingRule!=null ) {
			ruleName = enclosingRule.name;
		}
		ST st =
			generator.translateTemplateConstructor(ruleName,
												   outerAltNum,
												   actionToken,
												   action);
		if ( st!=null ) {
			chunks.add(st);
		}
		}
	;

/** %({name-expr})(a={},...) indirect template ctor reference */
INDIRECT_TEMPLATE_INSTANCE
	:	'%' '(' ACTION ')' '(' ( WS? ARG (',' WS? ARG)* WS? )? ')'
		// {System.out.println("found \%({...})(args)");}
		{
		String action = getText().substring(1,getText().length());
		ST st =
			generator.translateTemplateConstructor(enclosingRule.name,
												   outerAltNum,
												   actionToken,
												   action);
		chunks.add(st);
		}
	;

fragment
ARG	:	ID '=' ACTION
	;

/**	%{expr}.y = z; template attribute y of ST-typed expr to z */
SET_EXPR_ATTRIBUTE
	:	'%' a=ACTION '.' ID WS? '=' expr=ATTR_VALUE_EXPR ';'
		// {System.out.println("found \%{expr}.y = z;");}
		{
		ST st = template("actionSetAttribute");
		String action = $a.text;
		action = action.substring(1,action.length()-1); // stuff inside {...}
		st.add("st", translateAction(action));
		st.add("attrName", $ID.text);
		st.add("expr", translateAction($expr.text));
		}
	;
	
/*    %x.y = z; set template attribute y of x (always set never get attr)
 *              to z [languages like python without ';' must still use the
 *              ';' which the code generator is free to remove during code gen]
 */
SET_ATTRIBUTE
	:	'%' x=ID '.' y=ID WS? '=' expr=ATTR_VALUE_EXPR ';'
		// {System.out.println("found \%x.y = z;");}
		{
		ST st = template("actionSetAttribute");
		st.add("st", $x.text);
		st.add("attrName", $y.text);
		st.add("expr", translateAction($expr.text));
		}
	;

/** Don't allow an = as first char to prevent $x == 3; kind of stuff. */
fragment
ATTR_VALUE_EXPR
	:	~'=' (~';')*
	;
	
/** %{string-expr} anonymous template from string expr */
TEMPLATE_EXPR
	:	'%' a=ACTION
		// {System.out.println("found \%{expr}");}
		{
		ST st = template("actionStringConstructor");
		String action = $a.text;
		action = action.substring(1,action.length()-1); // stuff inside {...}
		st.add("stringExpr", translateAction(action));
		}
	;
	
fragment
ACTION
	:	'{' (options {greedy=false;}:.)* '}'
	;
	
ESC :   '\\' '$' {chunks.add("\$");}
	|	'\\' '%' {chunks.add("\%");}
	|	'\\' ~('$'|'%') {chunks.add(getText());}
    ;       

ERROR_XY
	:	'$' x=ID '.' y=ID
		{
		chunks.add(getText());
		generator.issueInvalidAttributeError($x.text,$y.text,
		                                     enclosingRule,actionToken,
		                                     outerAltNum);
		}
	;
	
ERROR_X
	:	'$' x=ID
		{
		chunks.add(getText());
		generator.issueInvalidAttributeError($x.text,
		                                     enclosingRule,actionToken,
		                                     outerAltNum);
		}
	;
	
UNKNOWN_SYNTAX
	:	'$'
		{
		chunks.add(getText());
		// shouldn't need an error here.  Just accept \$ if it doesn't look like anything
		}
	|	'%' (ID|'.'|'('|')'|','|'{'|'}'|'"')*
		{
		chunks.add(getText());
		ErrorManager.grammarError(ErrorManager.MSG_INVALID_TEMPLATE_ACTION,
								  grammar,
								  actionToken,
								  getText());
		}
	;

TEXT:	~('$'|'%'|'\\')+ {chunks.add(getText());}
	;
	
fragment
ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
    ;

fragment
INT :	'0'..'9'+
	;

fragment
WS	:	(' '|'\t'|'\n'|'\r')+
	;