1/*
2 [The "BSD license"]
3 Copyright (c) 2006, 2007 Kay Roepke 2010 Alan Condit
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9 1. Redistributions of source code must retain the above copyright
10    notice, this list of conditions and the following disclaimer.
11 2. Redistributions in binary form must reproduce the above copyright
12    notice, this list of conditions and the following disclaimer in the
13    documentation and/or other materials provided with the distribution.
14 3. The name of the author may not be used to endorse or promote products
15    derived from this software without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29/*
30 *  Template group file for the Objective C code generator.
31 *  Heavily based on Java.stg
32 *
33 *  Written by Kay Roepke <kroepke(at)classdump.org>
34 *  Modified by Alan Condit <acondit(at)ipns.com>
35 *
36 *  This file is part of ANTLR and subject to the same license as ANTLR itself.
37 */
38
39objcTypeInitMap ::= [
40    "int"           : "0",              // Integers     start out being 0
41    "long"          : "0",              // Longs        start out being 0
42    "float"         : "0.0",            // Floats       start out being 0
43    "double"        : "0.0",            // Doubles      start out being 0
44    "BOOL"          : "NO",             // Booleans     start out being Antlr ObjC for false
45    "byte"          : "0",              // Bytes        start out being 0
46    "short"         : "0",              // Shorts       start out being 0
47    "char"          : "0",              // Chars        start out being 0
48    "id"            : "nil",            // ids          start out being nil
49    default         : "nil"             // anything other than an atomic type
50]
51
52className() ::= "<name><!<if(LEXER)>Lexer<else><if(TREE_PARSER)>Tree<endif>Parser<endif>!>"
53leadIn(type) ::=
54<<
55/** \file
56 *  This <type> file was generated by $ANTLR version <ANTLRVersion>
57 *
58 *     -  From the grammar source file : <fileName>
59 *     -                            On : <generatedTimestamp>
60<if(LEXER)>
61 *     -                 for the lexer : <name>Lexer
62<endif>
63<if(PARSER)>
64 *     -                for the parser : <name>Parser
65<endif>
66<if(TREE_PARSER)>
67 *     -           for the tree parser : <name>TreeParser
68<endif>
69 *
70 * Editing it, at least manually, is not wise.
71 *
72 * ObjC language generator and runtime by Alan Condit, acondit|hereisanat|ipns|dotgoeshere|com.
73 *
74 *
75>>
76
77/** The overall file structure of a recognizer; stores methods for rules
78 *  and cyclic DFAs plus support code.
79 */
80outputFile( LEXER,
81            PARSER,
82            TREE_PARSER,
83            actionScope,
84            actions,
85            docComment,
86            recognizer,
87            name,
88            tokens,
89            tokenNames,
90            rules,
91            cyclicDFAs,
92            bitsets,
93            buildTemplate,
94            buildAST,
95            rewriteMode,
96            profile,
97            backtracking,
98            synpreds,
99            memoize,
100            numRules,
101            fileName,
102            ANTLRVersion,
103            generatedTimestamp,
104            trace,
105            scopes,
106            superClass,
107            literals
108            ) ::=
109<<
110<leadIn("OBJC source")>
111*/
112// $ANTLR <ANTLRVersion> <fileName> <generatedTimestamp>
113
114<! <if(actions.(actionScope).header)>
115/* =============================================================================
116 * This is what the grammar programmer asked us to put at the top of every file.
117 */
118<actions.(actionScope).header>
119/* End of Header action.
120 * =============================================================================
121 */
122<endif> !>
123
124/* -----------------------------------------
125 * Include the ANTLR3 generated header file.
126 */
127#import "<name><!<if(LEXER)>Lexer<else><if(TREE_PARSER)>Tree<endif>Parser<endif>!>.h"
128<actions.(actionScope).postinclude>
129/* ----------------------------------------- */
130
131<docComment>
132
133<if(literals)>
134/** String literals used by <name> that we must do things like MATCHS() with.
135 *  C will normally just lay down 8 bit characters, and you can use L"xxx" to
136 *  get wchar_t, but wchar_t is 16 bits on Windows, which is not UTF32 and so
137 *  we perform this little trick of defining the literals as arrays of UINT32
138 *  and passing in the address of these.
139 */
140<literals:{it | static ANTLR3_UCHAR  lit_<i>[]  = <it>;}; separator="\n">
141
142<endif>
143
144/* ============================================================================= */
145/* =============================================================================
146 * Start of recognizer
147 */
148<recognizer>
149>>
150headerFileExtension() ::= ".h"
151
152headerFile( LEXER,
153            PARSER,
154            TREE_PARSER,
155            actionScope,
156            actions,
157            docComment,
158            recognizer,
159            name,
160            tokens,
161            tokenNames,
162            rules,
163            cyclicDFAs,
164            bitsets,
165            buildTemplate,
166            buildAST,
167            rewriteMode,
168            profile,
169            backtracking,
170            synpreds,
171            memoize,
172            numRules,
173            fileName,
174            ANTLRVersion,
175            generatedTimestamp,
176            trace,
177            scopes,
178            superClass,
179            literals
180          ) ::=
181<<
182// $ANTLR <ANTLRVersion> <fileName> <generatedTimestamp>
183
184<@imports>
185<actions.(actionScope).preincludes>
186/* =============================================================================
187 * Standard antlr3 OBJC runtime definitions
188 */
189#import \<Foundation/Foundation.h>
190#import \<ANTLR/ANTLR.h>
191/* End of standard antlr3 runtime definitions
192 * =============================================================================
193 */
194<actions.(actionScope).includes>
195<@end>
196
197<if(LEXER)>
198<lexerHeaderFile(...)>
199<endif>
200<if(PARSER)>
201<parserHeaderFile(...)>
202<endif>
203<if(TREE_PARSER)>
204<treeParserHeaderFile(...)>
205<endif>
206<docComment>
207>>
208
209lexerHeaderFile( LEXER,
210            PARSER,
211            TREE_PARSER,
212            actionScope,
213            actions,
214            docComment,
215            recognizer,
216            name,
217            tokens,
218            tokenNames,
219            rules,
220            cyclicDFAs,
221            bitsets,
222            buildTemplate,
223            profile,
224            backtracking,
225            synpreds,
226            memoize,
227            numRules,
228            fileName,
229            ANTLRVersion,
230            generatedTimestamp,
231            trace,
232            scopes,
233            superClass="ANTLRLexer"
234            ) ::=
235<<
236
237<if(actions.(actionScope).header)>
238/* =============================================================================
239 * This is what the grammar programmer asked us to put at the top of every file.
240 */
241<actions.(actionScope).header>
242/* End of Header action.
243 * =============================================================================
244 */
245<endif>
246
247/* Start cyclicDFAInterface */
248<cyclicDFAs:cyclicDFAInterface()>
249
250#pragma mark Rule return scopes Interface start
251<rules:{rule |
252<rule.ruleDescriptor:{ruleDescriptor | <returnScopeInterface(scope=ruleDescriptor.returnScope)>}>}>
253#pragma mark Rule return scopes Interface end
254#pragma mark Tokens
255#ifdef EOF
256#undef EOF
257#endif
258<tokens:{it | #define <it.name> <it.type>}; separator="\n">
259/* interface lexer class */
260@interface <className()> <@superClassName>: <superClass><@end> { // line 283
261<cyclicDFAs:{dfa | DFA<dfa.decisionNumber> *dfa<dfa.decisionNumber>;}; separator="\n">
262<synpreds:{pred | SEL <pred>Selector;}; separator="\n">
263/* ObjC start of actions.lexer.memVars */
264<actions.lexer.memVars>
265/* ObjC end of actions.lexer.memVars */
266}
267+ (void) initialize;
268+ (<className()> *)new<className()>WithCharStream:(id\<ANTLRCharStream>)anInput;
269/* ObjC start actions.lexer.methodsDecl */
270<actions.lexer.methodsDecl>
271/* ObjC end actions.lexer.methodsDecl */
272<rules:{rule |
273- (<rule.ruleDescriptor:{ruleDescriptor|<returnType()>}>) <if(!rule.ruleDescriptor.isSynPred)>m<rule.ruleName><else><rule.ruleName>_fragment<endif> <if(rule.ruleDescriptor.parameterScope)><rule.ruleDescriptor.parameterScope:parameterScope()><endif>; }; separator="\n"><\n>
274@end /* end of <className()> interface */<\n>
275>>
276
277headerReturnScope(ruleDescriptor) ::= "<returnScopeInterface(...)>"
278headerReturnType(ruleDescriptor) ::= <<
279<if(LEXER)>
280<if(!r.ruleDescriptor.isSynPred)>
281 void
282<else>
283 <ruleDescriptor:returnType()>
284<endif>
285<else>
286 <ruleDescriptor:returnType()>
287<endif>
288>>
289// Produce the lexer output
290lexer(  grammar,
291        name,
292        tokens,
293        scopes,
294        rules,
295        numRules,
296        filterMode,
297        labelType="ANTLRCommonToken",
298        superClass="ANTLRLexer"
299        ) ::= <<
300<cyclicDFAs:cyclicDFA()>
301
302/** As per Terence: No returns for lexer rules! */
303<!
304#pragma mark Rule return scopes start
305<rules:{rule | <rule.ruleDescriptor:{ruleDescriptor |
306<returnScopeImplementation(scope=ruleDescriptor.returnScope)>}>
307}>
308#pragma mark Rule return scopes end
309!>
310@implementation <grammar.recognizerName> // line 330
311
312+ (void) initialize
313{
314    [ANTLRBaseRecognizer setGrammarFileName:@"<fileName>"];
315}
316
317+ (NSString *) tokenNameForType:(NSInteger)aTokenType
318{
319    return [[self getTokenNames] objectAtIndex:aTokenType];
320}
321
322+ (<grammar.recognizerName> *)new<grammar.recognizerName>WithCharStream:(id\<ANTLRCharStream>)anInput
323{
324    return [[<grammar.recognizerName> alloc] initWithCharStream:anInput];
325}
326
327- (id) initWithCharStream:(id\<ANTLRCharStream>)anInput
328{
329    self = [super initWithCharStream:anInput State:[ANTLRRecognizerSharedState newANTLRRecognizerSharedStateWithRuleLen:<numRules>+1]];
330    if ( self != nil ) {
331<if(memoize)>
332        if ( state.ruleMemo == nil ) {
333            state.ruleMemo = [[ANTLRRuleStack newANTLRRuleStackWithSize:<numRules>+1] retain];
334        }
335        if ( [state.ruleMemo count] == 0 ) {
336            // initialize the memoization cache - the indices are 1-based in the runtime code!
337            <! [state.ruleMemo addObject:[NSNull null]];     /* dummy entry to ensure 1-basedness. */ !>
338            for (NSInteger i = 0; i \< <numRules>; i++) {
339                [state.ruleMemo addObject:[ANTLRHashRule newANTLRHashRuleWithLen:17]];
340            }
341        }
342<endif>
343        <synpreds:{pred | <lexerSynpred(name=pred)>};separator="\n">
344        <cyclicDFAs:{dfa | dfa<dfa.decisionNumber> = [DFA<dfa.decisionNumber> newDFA<dfa.decisionNumber>WithRecognizer:self];}; separator="\n">
345        <actions.lexer.init>
346    }
347    return self;
348}
349
350- (void) dealloc
351{
352    <cyclicDFAs:{dfa | [dfa<dfa.decisionNumber> release];}; separator="\n">
353<actions.lexer.dealloc>
354    [super dealloc];
355}
356
357/* ObjC Start of actions.lexer.methods */
358<actions.lexer.methods>
359/* ObjC end of actions.lexer.methods */
360/* ObjC start methods() */
361<@methods()>
362/* ObjC end methods() */
363
364<if(actions.lexer.reset)>
365- (void) reset
366{
367    <actions.lexer.reset>
368    [super reset];
369}
370<endif>
371
372<if(filterMode)>
373<filteringNextToken()>
374<endif>
375/* Start of Rules */
376<rules; separator="\n">
377
378@end /* end of <grammar.recognizerName> implementation line 397 */
379>>
380
381/** A override of Lexer.nextToken() that backtracks over mTokens() looking
382 *  for matches.  No error can be generated upon error; just rewind, consume
383 *  a token and then try again.  backtracking needs to be set as well.
384 *  Make rule memoization happen only at levels above 1 as we start mTokens
385 *  at backtracking==1.
386 */
387filteringNextToken() ::= <<
388- (id\<ANTLRToken>) nextToken
389{
390    while (YES) {
391        if ( [input LA:1] == ANTLRCharStreamEOF ) {
392            return [<labelType> eofToken];
393        }
394        state.token = nil;
395        state.channel = ANTLRTokenChannelDefault;
396        state.tokenStartCharIndex = input.index;
397        state.tokenStartCharPositionInLine = input.charPositionInLine;
398        state.tokenStartLine = input.line;
399        state.text = nil;
400        @try {
401            NSInteger m = [input mark];
402            state.backtracking = 1; /* means we won't throw slow exception */
403            state.failed = NO;
404            [self mTokens];
405            state.backtracking = 0;
406            /* mTokens backtracks with synpred at backtracking==2
407               and we set the synpredgate to allow actions at level 1. */
408            if ( state.failed ) {
409                [input rewind:m];
410                [input consume]; /* advance one char and try again */
411            } else {
412                [self emit];
413                return state.token;
414            }
415        }
416        @catch (ANTLRRecognitionException *re) {
417            // shouldn't happen in backtracking mode, but...
418            [self reportError:re];
419            [self recover:re];
420        }
421    }
422}
423
424- (void)memoize:(id\<ANTLRIntStream\>)anInput
425      RuleIndex:(NSInteger)ruleIndex
426     StartIndex:(NSInteger)ruleStartIndex
427{
428    if ( state.backtracking > 1 ) [super memoize:anInput RuleIndex:ruleIndex StartIndex:ruleStartIndex];
429}
430
431- (BOOL)alreadyParsedRule:(id\<ANTLRIntStream\>)anInput RuleIndex:(NSInteger)ruleIndex
432{
433    if ( state.backtracking > 1 ) return [super alreadyParsedRule:anInput RuleIndex:ruleIndex];
434    return NO;
435}
436>>
437
438actionGate() ::= "state.backtracking == 0"
439
440filteringActionGate() ::= "state.backtracking == 1"
441
442parserHeaderFile( LEXER,
443            PARSER,
444            TREE_PARSER,
445            actionScope,
446            actions,
447            docComment,
448            recognizer,
449            name,
450            tokens,
451            tokenNames,
452            rules,
453            cyclicDFAs,
454            bitsets,
455            buildTemplate,
456            profile,
457            backtracking,
458            synpreds,
459            memoize,
460            numRules,
461            fileName,
462            ANTLRVersion,
463            generatedTimestamp,
464            trace,
465            scopes,
466            literals,
467            superClass="ANTLRParser"
468            ) ::= <<
469/* parserHeaderFile */
470<genericParserHeaderFile(inputStreamType="id\<ANTLRTokenStream>",...)>
471>>
472
473treeParserHeaderFile( LEXER,
474            PARSER,
475            TREE_PARSER,
476            actionScope,
477            actions,
478            docComment,
479            recognizer,
480            name,
481            tokens,
482            tokenNames,
483            rules,
484            cyclicDFAs,
485            bitsets,
486            buildTemplate,
487            profile,
488            backtracking,
489            synpreds,
490            memoize,
491            numRules,
492            fileName,
493            ANTLRVersion,
494            generatedTimestamp,
495            trace,
496            scopes,
497            literals,
498            superClass="ANTLRTreeParser"
499            ) ::= <<
500/* treeParserHeaderFile */
501<genericParserHeaderFile(inputStreamType="id\<ANTLRTreeNodeStream>",...)>
502>>
503
504genericParserHeaderFile( LEXER,
505            PARSER,
506            TREE_PARSER,
507            actionScope,
508            actions,
509            docComment,
510            recognizer,
511            name,
512            tokens,
513            tokenNames,
514            rules,
515            cyclicDFAs,
516            bitsets,
517            buildTemplate,
518            profile,
519            backtracking,
520            synpreds,
521            memoize,
522            numRules,
523            fileName,
524            ANTLRVersion,
525            generatedTimestamp,
526            trace,
527            scopes,
528            superClass,
529            literals,
530            inputStreamType
531            ) ::=
532<<
533<if(actions.(actionScope).header)>
534/* =============================================================================
535 * This is what the grammar programmer asked us to put at the top of every file.
536 */
537<actions.(actionScope).header>
538/* End of Header action.
539 * =============================================================================
540 */
541<endif>
542
543#ifndef ANTLR3TokenTypeAlreadyDefined
544#define ANTLR3TokenTypeAlreadyDefined
545typedef enum {
546    ANTLR_EOF = -1,
547    INVALID,
548    EOR,
549    DOWN,
550    UP,
551    MIN
552} ANTLR3TokenType;
553#endif
554
555<cyclicDFAs:cyclicDFAInterface()>
556#pragma mark Tokens
557#ifdef EOF
558#undef EOF
559#endif
560<tokens:{it | #define <it.name> <it.type>}; separator="\n">
561#pragma mark Dynamic Global Scopes globalAttributeScopeInterface
562<scopes:{it | <if(it.isDynamicGlobalScope)><globalAttributeScopeInterface(scope=it)><endif>}>
563#pragma mark Dynamic Rule Scopes ruleAttributeScopeInterface
564<rules:{rule |
565<rule.ruleDescriptor:{ ruleDescriptor | <ruleAttributeScopeInterface(scope=ruleDescriptor.ruleScope)>}>}>
566#pragma mark Rule Return Scopes returnScopeInterface
567<rules:{rule |<rule.ruleDescriptor:{ ruleDescriptor | <returnScopeInterface(scope=ruleDescriptor.returnScope)>}>}>
568
569/* Interface grammar class */
570@interface <className()> <@superClassName> : <superClass><@end> { /* line 572 */
571#pragma mark Dynamic Rule Scopes ruleAttributeScopeDecl
572<rules:{rule | <rule.ruleDescriptor.ruleScope:ruleAttributeScopeDecl(scope=rule.ruleDescriptor.ruleScope)>}>
573#pragma mark Dynamic Global Rule Scopes globalAttributeScopeMemVar
574<scopes:{it | <if(it.isDynamicGlobalScope)><globalAttributeScopeMemVar(scope=it)><endif>}><\n>
575/* ObjC start of actions.(actionScope).memVars */
576<actions.(actionScope).memVars>
577/* ObjC end of actions.(actionScope).memVars */
578/* ObjC start of memVars */
579<@memVars()>
580/* ObjC end of memVars */
581
582<cyclicDFAs:{dfa | DFA<dfa.decisionNumber> *dfa<dfa.decisionNumber>;}; separator="\n">
583<synpreds:{pred | SEL <pred>Selector;}; separator="\n">
584 }
585
586/* ObjC start of actions.(actionScope).properties */
587<actions.(actionScope).properties>
588/* ObjC end of actions.(actionScope).properties */
589/* ObjC start of properties */
590<@properties()>
591/* ObjC end of properties */
592
593+ (void) initialize;
594+ (id) new<className()>:(<inputStreamType>)aStream;
595/* ObjC start of actions.(actionScope).methodsDecl */
596<actions.(actionScope).methodsDecl>
597/* ObjC end of actions.(actionScope).methodsDecl */
598
599/* ObjC start of methodsDecl */
600<@methodsDecl()>
601/* ObjC end of methodsDecl */
602
603<rules:{rule |
604- (<rule.ruleDescriptor:{ruleDescriptor|<returnType()>}>)<if(!rule.ruleDescriptor.isSynPred)><rule.ruleName><else><rule.ruleName>_fragment<endif><if(rule.ruleDescriptor.parameterScope)><rule.ruleDescriptor.parameterScope:parameterScope()><endif>; }; separator="\n"><\n>
605
606@end /* end of <className()> interface */<\n>
607>>
608
609parser( grammar,
610        name,
611        scopes,
612        tokens,
613        tokenNames,
614        rules,
615        numRules,
616        bitsets,
617        ASTLabelType="ANTLRCommonTree",
618        superClass="ANTLRParser",
619        labelType="ANTLRCommonToken",
620        members={<actions.parser.members>}
621        ) ::= <<
622<genericParser(inputStreamType="id\<ANTLRTokenStream>", rewriteElementType="Token", ...)>
623>>
624
625/** How to generate a tree parser; same as parser except the input
626 *  stream is a different type.
627 */
628treeParser( grammar,
629        name,
630        scopes,
631        tokens,
632        tokenNames,
633        globalAction,
634        rules,
635        numRules,
636        bitsets,
637        filterMode,
638        labelType={<ASTLabelType>},
639        ASTLabelType="ANTLRCommonTree",
640        superClass={<if(filterMode)><if(buildAST)>ANTLRTreeRewriter<else>ANTLRTreeFilter<endif><else>ANTLRTreeParser<endif>},
641        members={<actions.treeparser.members>}
642        ) ::= <<
643<genericParser(inputStreamType="id\<ANTLRTreeNodeStream>", rewriteElementType="Node", ...)>
644>>
645
646/** How to generate a parser */
647genericParser(  grammar,
648        name,
649        scopes,
650        tokens,
651        tokenNames,
652        rules,
653        numRules,
654        cyclicDFAs,          // parser init -- initializes the DFAs
655        bitsets,
656        labelType,
657        ASTLabelType,
658        superClass,
659        members,
660        filterMode,
661        rewriteElementType,
662        inputStreamType
663        ) ::= <<
664<cyclicDFAs:cyclicDFA()>
665
666#pragma mark Bitsets
667<bitsets:{it | <bitset(name={FOLLOW_<it.name>_in_<it.inName><it.tokenIndex>}, words64=it.bits)>}>
668
669#pragma mark Dynamic Global globalAttributeScopeImplementation
670<scopes:{it | <if(it.isDynamicGlobalScope)><globalAttributeScopeImplementation(scope=it)><endif>}>
671
672#pragma mark Dynamic Rule Scopes ruleAttributeScopeImplementation
673<rules:{rule |
674<rule.ruleDescriptor:{ ruleDescriptor | <ruleAttributeScopeImplementation(scope=ruleDescriptor.ruleScope)>}>}>
675
676#pragma mark Rule Return Scopes returnScopeImplementation
677<rules:{rule | <rule.ruleDescriptor:{ ruleDescriptor | <returnScopeImplementation(scope=ruleDescriptor.returnScope)>}>}>
678
679@implementation <grammar.recognizerName>  // line 637
680
681#pragma mark Dynamic Rule Scopes ruleAttributeScope
682<rules:{rule | <rule.ruleDescriptor.ruleScope:ruleAttributeScope()>}>
683#pragma mark global Attribute Scopes globalAttributeScope
684<scopes:{it | <if(it.isDynamicGlobalScope)><globalAttributeScope()><endif>}>
685/* ObjC start actions.(actionScope).synthesize */
686<actions.(actionScope).synthesize>
687/* ObjC start synthesize() */
688<@synthesize()>
689
690+ (void) initialize
691{
692    #pragma mark Bitsets
693    <bitsets:{it | <bitsetInit(name={FOLLOW_<it.name>_in_<it.inName><it.tokenIndex>}, words64=it.bits)>}>
694    [ANTLRBaseRecognizer setTokenNames:[[AMutableArray arrayWithObjects:@"\<invalid>", @"\<EOR>", @"\<DOWN>", @"\<UP>", <tokenNames:{it | @<it>}; separator=", ", wrap="\n ">, nil] retain]];
695    [ANTLRBaseRecognizer setGrammarFileName:@"<fileName>"];
696    <synpreds:{pred | <synpred(pred)>}>
697}
698
699+ (<grammar.recognizerName> *)new<grammar.recognizerName>:(<inputStreamType>)aStream
700{
701<if(PARSER)>
702    return [[<grammar.recognizerName> alloc] initWithTokenStream:aStream];
703<else><! TREE_PARSER !>
704    return [[<grammar.recognizerName> alloc] initWithStream:aStream];
705<endif>
706}
707
708<if(PARSER)>
709- (id) initWithTokenStream:(<inputStreamType>)aStream
710{
711    self = [super initWithTokenStream:aStream State:[ANTLRRecognizerSharedState newANTLRRecognizerSharedStateWithRuleLen:<numRules>+1]];
712    if ( self != nil ) {
713<else><! TREE_PARSER !>
714- (id) initWithStream:(<inputStreamType>)aStream
715{
716    self = [super initWithStream:aStream State:[[ANTLRRecognizerSharedState newANTLRRecognizerSharedStateWithRuleLen:<numRules>+1] retain]];
717    if ( self != nil ) {
718<endif>
719        <! <parserCtorBody()> !>
720        <cyclicDFAs:{dfa | dfa<dfa.decisionNumber> = [DFA<dfa.decisionNumber> newDFA<dfa.decisionNumber>WithRecognizer:self];}; separator="\n">
721        <scopes:{it | <if(it.isDynamicGlobalScope)><globalAttributeScopeInit(scope=it)><endif>}>
722        <rules:{rule | <rule.ruleDescriptor.ruleScope:ruleAttributeScopeInit()>}>
723        /* start of actions-actionScope-init */
724        <actions.(actionScope).init>
725        /* start of init */
726        <@init()>
727    }
728    return self;
729}
730
731- (void) dealloc
732{
733    <cyclicDFAs:{dfa | [dfa<dfa.decisionNumber> release];}; separator="\n">
734    <scopes:{it | <if(it.isDynamicGlobalScope)><globalAttributeScopeDealloc(scope=it)><endif>}>
735    <actions.(actionScope).dealloc>
736    <@dealloc()>
737    [super dealloc];
738}
739
740/* ObjC start actions.(actionScope).methods */
741<actions.(actionScope).methods>
742/* ObjC end actions.(actionScope).methods */
743/* ObjC start methods() */
744<@methods()>
745/* ObjC end methods() */
746/* ObjC start rules */
747<rules; separator="\n">
748/* ObjC end rules */
749
750@end /* end of <grammar.recognizerName> implementation line 692 */<\n>
751>>
752
753parserCtorBody() ::= <<
754<if(memoize)> /* parserCtorBody */
755<if(grammar.grammarIsRoot)>
756state.ruleMemo = [[ANTLRRuleStack newANTLRRuleStack:<numRules>+1] retain];<\n> <! index from 1..n !>
757<endif>
758<endif>
759<grammar.delegators:
760 {g|this.<g:delegateName()> = <g:delegateName()>;}; separator="\n">
761>>
762
763/** A simpler version of a rule template that is specific to the imaginary
764 *  rules created for syntactic predicates.  As they never have return values
765 *  nor parameters etc..., just give simplest possible method.  Don't do
766 *  any of the normal memoization stuff in here either; it's a waste.
767 *  As predicates cannot be inlined into the invoking rule, they need to
768 *  be in a rule by themselves.
769 */
770synpredRule(ruleName, ruleDescriptor, block, description, nakedBlock) ::=
771<<
772// $ANTLR start <ruleName>_fragment
773- (void) <ruleName>_fragment
774{
775    <ruleLabelDefs()>
776    <if(trace)>
777        [self traceIn:\@"<ruleName>_fragment" Index:<ruleDescriptor.index>];
778    @try {
779        <block>
780    }
781    @finally {
782        [self traceOut:\@"<ruleName>_fragment" Index:<ruleDescriptor.index>];
783    }
784<else>
785    <block>
786<endif>
787} // $ANTLR end <ruleName>_fragment
788>>
789
790synpred(name) ::= <<
791SEL <name>Selector = @selector(<name>_fragment);
792<! // $ANTLR start <name>
793- (BOOL) <name>
794{
795    state.backtracking++;
796    <@start()>
797    NSInteger start = [input mark];
798    @try {
799        [self <name>_fragment]; // can never throw exception
800    }
801    @catch (ANTLRRecognitionException *re) {
802        NSLog(@"impossible: %@\n", re.name);
803    }
804    BOOL success = (state.failed == NO);
805    [input rewind:start];
806    <@stop()>
807    state.backtracking--;
808    state.failed=NO;
809    return success;
810} // $ANTLR end <name> <\n> !>
811>>
812
813lexerSynpred(name) ::= <<
814<synpred(name)>
815>>
816
817ruleMemoization(name) ::= <<
818<if(memoize)>
819if ( state.backtracking > 0 && [self alreadyParsedRule:input RuleIndex:<ruleDescriptor.index>] ) { return <ruleReturnValue()>; }
820<endif>
821>>
822
823/** How to test for failure and return from rule */
824checkRuleBacktrackFailure() ::= <<
825<if (backtracking)>if ( state.failed ) return <ruleReturnValue()>;<endif>
826>>
827
828/** This rule has failed, exit indicating failure during backtrack */
829ruleBacktrackFailure() ::= <<
830<if(backtracking)>if ( state.backtracking > 0 ) { state.failed = YES; return <ruleReturnValue()>; }<\n><endif>
831>>
832
833/** How to generate code for a rule.
834 *  The return type aggregates are declared in the header file (headerFile template)
835 */
836rule(ruleName,ruleDescriptor,block,emptyRule,description,exceptions,finally,memoize) ::= <<
837
838/*
839 * $ANTLR start <ruleName>
840 * <fileName>:<description>
841 */
842- (<returnType()>) <ruleName><ruleDescriptor.parameterScope:parameterScope()>
843{
844    <if(trace)>[self traceIn:\@"<ruleName>" Index:<ruleDescriptor.index>];<endif>
845    <if(trace)>NSLog(@"enter <ruleName> %@ failed=%@ backtracking=%d", [input LT:1], (state.failed==YES)?@"YES":@"NO", state.backtracking);<endif>
846    <ruleScopeSetUp()>
847    <ruleDeclarations()>
848    <ruleDescriptor.actions.init>
849    <@preamble()>
850    @try {
851        <ruleMemoization(name=ruleName)>
852        <ruleLabelDefs()>
853        <block>
854        <ruleCleanUp()>
855        <(ruleDescriptor.actions.after):execAction()>
856    }
857<if(exceptions)>
858    <exceptions:{e|<catch(decl=e.decl,action=e.action)><\n>}>
859<else><if(!emptyRule)><if(actions.(actionScope).rulecatch)>
860    <actions.(actionScope).rulecatch>
861<else>
862    @catch (ANTLRRecognitionException *re) {
863        [self reportError:re];
864        [self recover:input Exception:re];
865        <@setErrorReturnValue()>
866    }<\n>
867<endif><endif><endif>
868    @finally {
869        <if(trace)>[self traceOut:@"<ruleName>" Index:<ruleDescriptor.index>];<endif>
870        <memoize()>
871        <ruleScopeCleanUp()>
872        <finally>
873    }
874    <@postamble()>
875    return <ruleReturnValue()>;
876}
877/* $ANTLR end <ruleName> */
878>>
879
880finalCode(finalBlock) ::= <<
881{
882    <finalBlock>
883}
884>>
885
886catch(decl,action) ::= <<
887@catch (<e.decl>) {
888    <e.action>
889}
890>>
891
892ruleDeclarations() ::= <<
893/* ruleDeclarations */
894<if(ruleDescriptor.hasMultipleReturnValues)>
895<returnType()> retval = [<ruleDescriptor:returnStructName()> new<ruleDescriptor:returnStructName()>];
896[retval setStart:[input LT:1]];<\n>
897<else>
898<ruleDescriptor.returnScope.attributes:{ a |
899<a.type> <a.name> = <if(a.initValue)><a.initValue><else><initValue(a.type)><endif>;
900}>
901<endif>
902<if(memoize)>
903NSInteger <ruleDescriptor.name>_StartIndex = input.index;
904<endif>
905>>
906
907ruleScopeSetUp() ::= <<
908/* ruleScopeSetUp */
909<ruleDescriptor.useScopes:{it | [<it>_stack push:[<it>_Scope new<it>_Scope]];}>
910<ruleDescriptor.ruleScope:{it | [<it.name>_stack push:[<it.name>_Scope new<it.name>_Scope]];}>
911>>
912
913ruleScopeCleanUp() ::= <<
914/* ruleScopeCleanUp */
915<ruleDescriptor.useScopes:{it | [<it>_stack pop];}; separator="\n">
916<ruleDescriptor.ruleScope:{it | [<it.name>_stack pop];}; separator="\n">
917>>
918
919ruleLabelDefs() ::= <<
920<[ruleDescriptor.tokenLabels, ruleDescriptor.tokenListLabels,
921  ruleDescriptor.wildcardTreeLabels,ruleDescriptor.wildcardTreeListLabels]
922    :{it | <labelType> *<it.label.text> = nil;}; separator="\n">
923<[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels,ruleDescriptor.wildcardTreeListLabels]
924    :{it | AMutableArray *list_<it.label.text> = nil;}; separator="\n"
925>
926<ruleDescriptor.ruleLabels:ruleLabelDef(); separator="\n">
927<ruleDescriptor.ruleListLabels:{ll|ANTLRParserRuleReturnScope *<ll.label.text> = nil;}; separator="\n">
928>>
929
930lexerRuleLabelDefs() ::= <<
931<[ruleDescriptor.tokenLabels,
932  ruleDescriptor.tokenListLabels,
933  ruleDescriptor.ruleLabels]
934    :{it | <labelType> *<it.label.text>=nil;}; separator="\n"
935>
936<ruleDescriptor.charLabels:{it | NSInteger <it.label.text>;}; separator="\n">
937<[ruleDescriptor.tokenListLabels,
938  ruleDescriptor.ruleListLabels]:{it | AMutableArray *list_<it.label.text>=nil; }; separator="\n">
939>>
940
941ruleReturnValue() ::= <%
942<if(!ruleDescriptor.isSynPred)>
943<if(ruleDescriptor.hasReturnValue)>
944<if(ruleDescriptor.hasSingleReturnValue)>
945<ruleDescriptor.singleValueReturnName>
946<else>
947retval
948<endif>
949<endif>
950<endif>
951%>
952
953ruleCleanUp() ::= <<
954/* token+rule list labels */
955<[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels]:{it | [list_<it.label.text> release];}; separator="\n">
956<if(ruleDescriptor.hasMultipleReturnValues)>
957<if(!TREE_PARSER)>
958[retval setStop:[input LT:-1]];<\n>
959<endif><endif>
960>>
961
962memoize() ::= <<
963<if(memoize)>
964<if(backtracking)>
965if (state.backtracking > 0) [self memoize:input RuleIndex:<ruleDescriptor.index> StartIndex:<ruleDescriptor.name>_StartIndex];
966<endif><endif>
967>>
968
969/** How to generate a rule in the lexer; naked blocks are used for
970 *  fragment rules.
971 */
972lexerRule(ruleName, nakedBlock, ruleDescriptor, block, memoize) ::= <<
973// $ANTLR start "<ruleName>"
974- (void) m<ruleName><if(ruleDescriptor.parameterScope)><ruleDescriptor.parameterScope:parameterScope(scope=it)><endif>
975{
976    //<if(trace)>[self traceIn:\@"<ruleName>" Index:<ruleDescriptor.index>];<endif>
977    <if(trace)>NSLog(@"enter <ruleName> %C line=%d:%d failed=%@ backtracking=%d",
978        [input LA:1],
979        self.line,
980        self.charPositionInLine,
981        (state.failed==YES) ? @"YES" : @"NO",
982        state.backtracking);
983    <endif>
984    <ruleScopeSetUp()>
985    <ruleDeclarations()>
986    @try {
987<if(nakedBlock)>
988        <ruleMemoization(name=ruleName)>
989        <lexerRuleLabelDefs()>
990        <ruleDescriptor.actions.init>
991        <block><\n>
992<else>
993        NSInteger _type = <ruleName>;
994        NSInteger _channel = ANTLRTokenChannelDefault;
995        <ruleMemoization(name=ruleName)>
996        <lexerRuleLabelDefs()>
997        <ruleDescriptor.actions.init>
998        <block>
999        <ruleCleanUp()>
1000        state.type = _type;
1001        state.channel = _channel;
1002        <(ruleDescriptor.actions.after):execAction()>
1003<endif>
1004    }
1005    @finally {
1006        //<if(trace)>[self traceOut:[NSString stringWithFormat:@"<ruleName> %d\n", <ruleDescriptor.index>]];<endif>
1007        <if(trace)>NSLog(@"exit <ruleName> %C line=%d:%d failed=%@ backtracking=%d",
1008                    [input LA:1], self.line, self.charPositionInLine,
1009                    (state.failed==YES) ? @"YES" : @"NO", state.backtracking);<endif>
1010        <ruleScopeCleanUp()>
1011        <memoize()>
1012    }
1013    return;
1014}
1015/* $ANTLR end "<ruleName>" */
1016>>
1017
1018/** How to generate code for the implicitly-defined lexer grammar rule
1019 *  that chooses between lexer rules.
1020 */
1021tokensRule(ruleName,nakedBlock,args,block,ruleDescriptor) ::= <<
1022- (void) mTokens
1023{
1024    <block><\n>
1025}
1026>>
1027
1028// S U B R U L E S
1029
1030/** A (...) subrule with multiple alternatives */
1031block(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
1032// <fileName>:<description> // block
1033NSInteger alt<decisionNumber>=<maxAlt>;
1034<decls>
1035<@predecision()>
1036<decision>
1037<@postdecision()>
1038<@prebranch()>
1039switch (alt<decisionNumber>) {
1040    <alts:{a | <altSwitchCase(i, a)>}>
1041}
1042<@postbranch()>
1043>>
1044
1045/** A rule block with multiple alternatives */
1046ruleBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
1047// <fileName>:<description> //ruleblock
1048NSInteger alt<decisionNumber>=<maxAlt>;
1049<decls>
1050<@predecision()>
1051<decision>
1052<@postdecision()>
1053switch (alt<decisionNumber>) {
1054    <alts:{a | <altSwitchCase(i, a)>}>
1055}
1056>>
1057
1058ruleBlockSingleAlt(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,description) ::= <<
1059// <fileName>:<description> // ruleBlockSingleAlt
1060<decls>
1061<@prealt()>
1062<alts>
1063<@postalt()>
1064>>
1065
1066/** A special case of a (...) subrule with a single alternative */
1067blockSingleAlt(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,description) ::= <<
1068// <fileName>:<description> // blockSingleAlt
1069<decls>
1070<@prealt()>
1071<alts>
1072<@postalt()>
1073>>
1074
1075/** A (..)+ block with 1 or more alternatives */
1076positiveClosureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
1077// <fileName>:<description> // positiveClosureBlock
1078NSInteger cnt<decisionNumber> = 0;
1079<decls>
1080<@preloop()>
1081do {
1082    NSInteger alt<decisionNumber> = <maxAlt>;
1083    <@predecision()>
1084    <decision>
1085    <@postdecision()>
1086    switch (alt<decisionNumber>) {
1087        <alts:{a | <altSwitchCase(i, a)>}>
1088        default :
1089            if ( cnt<decisionNumber> >= 1 )
1090                goto loop<decisionNumber>;
1091            <ruleBacktrackFailure()>
1092            ANTLREarlyExitException *eee =
1093                [ANTLREarlyExitException newException:input decisionNumber:<decisionNumber>];
1094            <@earlyExitException()>
1095            @throw eee;
1096    }
1097    cnt<decisionNumber>++;
1098} while (YES);
1099loop<decisionNumber>: ;
1100<@postloop()>
1101>>
1102
1103positiveClosureBlockSingleAlt ::= positiveClosureBlock
1104
1105/** A (..)* block with 0 or more alternatives */
1106closureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
1107<decls>
1108<@preloop()>
1109do {
1110    NSInteger alt<decisionNumber>=<maxAlt>;
1111    <@predecision()>
1112    <decision>
1113    <@postdecision()>
1114    switch (alt<decisionNumber>) {
1115        <alts:{a | <altSwitchCase(i, a)>}>
1116        default :
1117            goto loop<decisionNumber>;
1118    }
1119} while (YES);
1120loop<decisionNumber>: ;
1121<@postloop()>
1122>>
1123
1124closureBlockSingleAlt ::= closureBlock
1125
1126/** Optional blocks (x)? are translated to (x|) by before code generation
1127 *  so we can just use the normal block template
1128 */
1129optionalBlock ::= block
1130
1131optionalBlockSingleAlt ::= block
1132
1133/** A case in a switch that jumps to an alternative given the alternative
1134 *  number.  A DFA predicts the alternative and then a simple switch
1135 *  does the jump to the code that actually matches that alternative.
1136 */
1137altSwitchCase(altNum, alt) ::= <<
1138case <altNum> : ;
1139    <@prealt()>
1140    <alt>
1141    break;<\n>
1142>>
1143
1144/** An alternative is just a list of elements; at outermost level */
1145alt(elements,altNum,description,autoAST,outerAlt,treeLevel,rew) ::= <<
1146// <fileName>:<description> // alt
1147{
1148<@declarations()>
1149<elements:element()>
1150<rew>
1151<@cleanup()>
1152}
1153>>
1154
1155/** What to emit when there is no rewrite.  For auto build
1156 *  mode, does nothing.
1157 */
1158noRewrite(rewriteBlockLevel, treeLevel) ::= ""
1159
1160// E L E M E N T S
1161
1162/** Dump the elements one per line */
1163element(e) ::= << <@prematch()><\n><e.el><\n> >>
1164
1165/** match a token optionally with a label in front */
1166tokenRef(token,label,elementIndex,terminalOptions) ::= <<
1167<if(label)><label>=(<labelType> *)<endif>[self match:input TokenType:<token> Follow:FOLLOW_<token>_in_<ruleName><elementIndex>]; <checkRuleBacktrackFailure()>
1168>>
1169
1170/** ids+=ID */
1171tokenRefAndListLabel(token,label,elementIndex,terminalOptions) ::= <<
1172<tokenRef(...)>
1173<listLabel(elem=label,...)>
1174>>
1175
1176listLabel(label,elem) ::= <<
1177if (list_<label> == nil) list_<label> = [[AMutableArray arrayWithCapacity:5] retain];
1178[list_<label> addObject:<elem>];<\n>
1179>>
1180
1181/** match a character */
1182charRef(char,label) ::= <<
1183<if(label)>NSInteger <label> = [input LA:1];<\n><endif>
1184[self matchChar:<char>]; <checkRuleBacktrackFailure()><\n>
1185>>
1186
1187/** match a character range */
1188charRangeRef(a,b,label) ::= <<
1189<if(label)><label> = [input LA:1];<\n><endif>
1190[self matchRangeFromChar:<a> to:<b>]; <checkRuleBacktrackFailure()>
1191>>
1192
1193/** For now, sets are interval tests and must be tested inline */
1194matchSet(s,label,elementIndex,terminalOptions,postmatchCode="") ::= <<
1195<if(label)>
1196<if(LEXER)>
1197<label> = [input LA:1];<\n>
1198<else>
1199<label> = (<labelType> *)[input LT:1]; /* matchSet */<\n>
1200<endif><endif>
1201if (<s>) {
1202    [input consume];
1203    <postmatchCode>
1204<if(!LEXER)>
1205    [state setIsErrorRecovery:NO];
1206<endif>
1207    <if(backtracking)>state.failed = NO;<\n><endif>
1208} else {
1209    <ruleBacktrackFailure()>
1210    ANTLRMismatchedSetException *mse = [ANTLRMismatchedSetException newException:nil stream:input];
1211    <@mismatchedSetException()>
1212<if(LEXER)>
1213<if(label)>
1214    mse.c = <label>;
1215<endif>
1216    [self recover:mse];
1217    @throw mse;
1218<else>
1219    @throw mse;
1220    <! use following code to make it recover inline; remove throw mse;
1221    [self recoverFromMismatchedSet:input exception:mse follow:FOLLOW_set_in_<ruleName><elementIndex>]; !>
1222<endif>
1223}<\n>
1224>>
1225
1226matchRuleBlockSet ::= matchSet
1227
1228matchSetAndListLabel(s,label,elementIndex,postmatchCode) ::= <<
1229<matchSet(...)>
1230<listLabel(elem=label,...)>
1231>>
1232
1233/** Match a string literal */
1234lexerStringRef(string,label,elementIndex="0") ::= <<
1235<if(label)>
1236NSInteger <label>Start = input.index;
1237[self matchString:<string>]; <checkRuleBacktrackFailure()>
1238NSInteger StartLine<elementIndex> = self.line;
1239NSInteger <label>StartCharPos<elementIndex> = self.charPositionInLine;
1240<label> = [[<labelType> newToken:input Type:ANTLRTokenTypeInvalid Channel:ANTLRTokenChannelDefault Start:<label>Start Stop:input.index] retain];
1241[self setLine:<label>StartLine<elementIndex>];
1242[self setCharPositionInLine:<label>StartCharPos<elementIndex>];
1243<else>
1244[self matchString:<string>]; <checkRuleBacktrackFailure()><\n>
1245<endif>
1246>>
1247
1248wildcard(token,label,elementIndex,terminalOptions) ::= <<
1249<if(label)>
1250<label> = (<labelType> *)[input LT:1];<\n>
1251<endif>
1252[self matchAny:input]; <checkRuleBacktrackFailure()>
1253>>
1254
1255wildcardAndListLabel(token,label,elementIndex,terminalOptions) ::= <<
1256<wildcard(...)>
1257<listLabel(elem=label,...)>
1258>>
1259
1260/** Match . wildcard in lexer */
1261wildcardChar(label, elementIndex) ::= <<
1262<if(label)>
1263NSInteger <label> = [input LA:1];<\n>
1264<endif>
1265[self matchAny]; <checkRuleBacktrackFailure()><\n>
1266>>
1267
1268wildcardCharListLabel(label, elementIndex) ::= <<
1269<wildcardChar(...)>
1270<listLabel(elem=label,...)>
1271>>
1272
1273/** Match a rule reference by invoking it possibly with arguments
1274 *  and a return value or values.  The 'rule' argument was the
1275 *  target rule name, but now is type Rule, whose toString is
1276 *  same: the rule name.  Now though you can access full rule
1277 *  descriptor stuff.
1278 */
1279ruleRef(rule,label,elementIndex,args,scope) ::= <<
1280/* ruleRef */
1281[self pushFollow:FOLLOW_<rule.name>_in_<ruleName><elementIndex>];
1282<if(label)><label> = <endif>[self <if(scope)><scope:delegateName()>.<endif><rule.name><if(args)>:<first(args)> <rest(args):{ a | arg<i>:<rest(args)>}; separator=" "><endif>];<\n>
1283[self popFollow];
1284<checkRuleBacktrackFailure()><\n>
1285>>
1286
1287/** ids+=r */
1288ruleRefAndListLabel(rule,label,elementIndex,args,scope) ::= <<
1289<ruleRef(...)>
1290<listLabel(elem=label,...)>
1291>>
1292
1293/** A lexer rule reference.
1294 *
1295 *  The 'rule' argument was the target rule name, but now
1296 *  is type Rule, whose toString is same: the rule name.
1297 *  Now though you can access full rule descriptor stuff.
1298 */
1299lexerRuleRef(rule,label,args,elementIndex,scope) ::= <<
1300<if(label)>
1301NSInteger <label>Start<elementIndex> = input.index;
1302[self m<rule.name><if(args)>:<args; separator=" :"><endif>]; <checkRuleBacktrackFailure()><\n>
1303<label> = [[<labelType> newToken:input Type:ANTLRTokenTypeInvalid Channel:ANTLRTokenChannelDefault Start:<label>Start<elementIndex> Stop:input.index-1] retain];
1304<label>.line = self.line;
1305<else>
1306[self <if(scope)><scope:delegateName()>.<endif>m<rule.name><if(args)>:<args; separator=" :"><endif>]; <checkRuleBacktrackFailure()><\n>
1307<endif>
1308>>
1309
1310/** i+=INT in lexer */
1311lexerRuleRefAndListLabel(rule,label,args,elementIndex,scope) ::= <<
1312<lexerRuleRef(...)>
1313<listLabel(elem=label,...)>
1314>>
1315
1316/** EOF in the lexer */
1317lexerMatchEOF(label,elementIndex) ::= <<
1318<if(label)>
1319NSInteger <label>Start<elementIndex> = input.index;
1320[self matchChar:ANTLRCharStreamEOF]; <checkRuleBacktrackFailure()><\n>
1321<labelType> <label> = [[<labelType> newToken:input Type:ANTLRTokenTypeEOF Channel:ANTLRTokenChannelDefault Start:<label>Start<elementIndex> Stop:input.index-1] retain];
1322<label>.line = self.line;
1323<else>
1324[self matchChar:ANTLRCharStreamEOF]; <checkRuleBacktrackFailure()><\n>
1325<endif>
1326>>
1327
1328// used for left-recursive rules
1329recRuleDefArg()                       ::= "int <recRuleArg()>"
1330recRuleArg()                          ::= "_p"
1331recRuleAltPredicate(ruleName,opPrec)  ::= "<recRuleArg()> \<= <opPrec>"
1332recRuleSetResultAction()              ::= "root_0=$<ruleName>_primary.tree;"
1333recRuleSetReturnAction(src,name)      ::= "$<name>=$<src>.<name>;"
1334
1335/** match ^(root children) in tree parser */
1336tree(root, actionsAfterRoot, children, nullableChildList, enclosingTreeLevel, treeLevel) ::= <<
1337<root:element()>
1338<actionsAfterRoot:element()>
1339<if(nullableChildList)>
1340if ( [input LA:1] == DOWN ) {
1341    [self match:input TokenType:DOWN Follow:nil]; <checkRuleBacktrackFailure()>
1342    <children:element()>
1343    [self match:input TokenType:UP Follow:nil]; <checkRuleBacktrackFailure()>
1344}
1345<else>
1346    [self match:input TokenType:DOWN Follow:nil]; <checkRuleBacktrackFailure()>
1347    <children:element()>
1348    [self match:input TokenType:UP Follow:nil]; <checkRuleBacktrackFailure()>
1349<endif>
1350>>
1351
1352/** Every predicate is used as a validating predicate (even when it is
1353 *  also hoisted into a prediction expression).
1354 */
1355validateSemanticPredicate(pred,description) ::= <<
1356if ( !(<evalPredicate(...)>) ) {
1357    <ruleBacktrackFailure()>
1358    @throw [ANTLRFailedPredicateException newException:@"<ruleName>" predicate:@"<description>" stream:input];
1359}
1360>>
1361
1362// F i x e d  D F A  (if-then-else)
1363
1364dfaState(k,edges,eotPredictsAlt,description,stateNumber,semPredState) ::= <<
1365NSInteger LA<decisionNumber>_<stateNumber> = [input LA:<k>];<\n>
1366<edges; separator="\nelse ">
1367else {
1368<if(eotPredictsAlt)>
1369    alt<decisionNumber> = <eotPredictsAlt>;
1370<else>
1371    <ruleBacktrackFailure()>
1372    ANTLRNoViableAltException *nvae = [ANTLRNoViableAltException newException:<decisionNumber> state:<stateNumber> stream:input];
1373    nvae.c = LA<decisionNumber>_<stateNumber>;
1374    <@noViableAltException()>
1375    @throw nvae;<\n>
1376<endif>
1377}
1378>>
1379
1380/** Same as a normal DFA state except that we don't examine lookahead
1381 *  for the bypass alternative.  It delays error detection but this
1382 *  is faster, smaller, and more what people expect.  For (X)? people
1383 *  expect "if ( LA(1)==X ) match(X);" and that's it.
1384 */
1385dfaOptionalBlockState(k,edges,eotPredictsAlt,description,stateNumber,semPredState) ::= <<
1386NSInteger LA<decisionNumber>_<stateNumber> = [input LA:<k>];<\n>
1387<edges; separator="\nelse ">
1388>>
1389
1390/** A DFA state that is actually the loopback decision of a closure
1391 *  loop.  If end-of-token (EOT) predicts any of the targets then it
1392 *  should act like a default clause (i.e., no error can be generated).
1393 *  This is used only in the lexer so that for ('a')* on the end of a rule
1394 *  anything other than 'a' predicts exiting.
1395 */
1396dfaLoopbackState(k,edges,eotPredictsAlt,description,stateNumber,semPredState) ::= <<
1397NSInteger LA<decisionNumber>_<stateNumber> = [input LA:<k>];
1398<edges; separator="\nelse "><\n>
1399<if(eotPredictsAlt)>
1400<if(!edges)>
1401alt<decisionNumber>=<eotPredictsAlt>; <! if no edges, don't gen ELSE !>
1402<else>
1403else {
1404    alt<decisionNumber> = <eotPredictsAlt>;
1405}<\n>
1406<endif><endif>
1407>>
1408
1409/** An accept state indicates a unique alternative has been predicted */
1410dfaAcceptState(alt) ::= "alt<decisionNumber>=<alt>;"
1411
1412/** A simple edge with an expression.  If the expression is satisfied,
1413 *  enter to the target state.  To handle gated productions, we may
1414 *  have to evaluate some predicates for this edge.
1415 */
1416dfaEdge(labelExpr, targetState, predicates) ::= <<
1417if ( (<labelExpr>) <if(predicates)>&& (<predicates>)<endif>) {
1418    <targetState>
1419}
1420>>
1421
1422// F i x e d  D F A  (switch case)
1423
1424/** A DFA state where a SWITCH may be generated.  The code generator
1425 *  decides if this is possible: CodeGenerator.canGenerateSwitch().
1426 */
1427dfaStateSwitch(k,edges,eotPredictsAlt,description,stateNumber,semPredState) ::= <<
1428unichar charLA<decisionNumber> = [input LA:<k>];
1429switch (charLA<decisionNumber>) {
1430    <edges; separator="\n"><\n>
1431default: ;
1432<if(eotPredictsAlt)>
1433    alt<decisionNumber> = <eotPredictsAlt>;
1434<else>
1435    <ruleBacktrackFailure()>
1436    ANTLRNoViableAltException *nvae = [ANTLRNoViableAltException newException:<decisionNumber> state:<stateNumber> stream:input];
1437    nvae.c = charLA<decisionNumber>;
1438    <@noViableAltException()>
1439    @throw nvae;<\n>
1440<endif>
1441}<\n>
1442>>
1443
1444dfaOptionalBlockStateSwitch(k,edges,eotPredictsAlt,description,stateNumber,semPredState) ::= <<
1445switch ([input LA:<k>]) { // dfaOptionalBlockStateSwitch
1446    <edges; separator="\n"><\n>
1447}<\n>
1448>>
1449
1450dfaLoopbackStateSwitch(k, edges,eotPredictsAlt,description,stateNumber,semPredState) ::= <<
1451switch ([input LA:<k>]) { // dfaLoopbackStateSwitch
1452    <edges; separator="\n"><\n>
1453<if(eotPredictsAlt)>
1454default:
1455    alt<decisionNumber> = <eotPredictsAlt>;
1456    break;<\n>
1457<endif>
1458}<\n>
1459>>
1460
1461dfaEdgeSwitch(labels, targetState) ::= <<
1462<labels:{it | case <it>: ;}; separator="\n">
1463    {
1464    <targetState>
1465    }
1466    break;
1467>>
1468
1469// C y c l i c  D F A
1470
1471/** The code to initiate execution of a cyclic DFA; this is used
1472 *  in the rule to predict an alt just like the fixed DFA case.
1473 *  The <name> attribute is inherited via the parser, lexer, ...
1474 */
1475dfaDecision(decisionNumber,description) ::= <<
1476alt<decisionNumber> = [dfa<decisionNumber> predict:input];
1477>>
1478
1479/** Used in headerFile */
1480cyclicDFAInterface(dfa) ::= <<
1481#pragma mark Cyclic DFA interface start DFA<dfa.decisionNumber>
1482@interface DFA<dfa.decisionNumber> : ANTLRDFA {
1483}
1484+ newDFA<dfa.decisionNumber>WithRecognizer:(ANTLRBaseRecognizer *)theRecognizer;
1485- initWithRecognizer:(ANTLRBaseRecognizer *)recognizer;
1486@end /* end of DFA<dfa.decisionNumber> interface  */<\n>
1487#pragma mark Cyclic DFA interface end DFA<dfa.decisionNumber><\n>
1488>>
1489
1490/** Used in lexer/parser implementation files */
1491/* Dump DFA tables as run-length-encoded Strings of octal values.
1492 * Can't use hex as compiler translates them before compilation.
1493 * These strings are split into multiple, concatenated strings.
1494 * Java puts them back together at compile time thankfully.
1495 * Java cannot handle large static arrays, so we're stuck with this
1496 * encode/decode approach.  See analysis and runtime DFA for
1497 * the encoding methods.
1498 */
1499cyclicDFA(dfa) ::= <<
1500#pragma mark Cyclic DFA implementation start DFA<dfa.decisionNumber>
1501@implementation DFA<dfa.decisionNumber>
1502const static NSInteger dfa<dfa.decisionNumber>_eot[<dfa.numberOfStates>] =
1503    {<dfa.eot; wrap="\n     ", separator=",", null="-1">};
1504const static NSInteger dfa<dfa.decisionNumber>_eof[<dfa.numberOfStates>] =
1505    {<dfa.eof; wrap="\n     ", separator=",", null="-1">};
1506const static unichar dfa<dfa.decisionNumber>_min[<dfa.numberOfStates>] =
1507    {<dfa.min; wrap="\n     ", separator=",", null="0">};
1508const static unichar dfa<dfa.decisionNumber>_max[<dfa.numberOfStates>] =
1509    {<dfa.max; wrap="\n     ", separator=",", null="0">};
1510const static NSInteger dfa<dfa.decisionNumber>_accept[<dfa.numberOfStates>] =
1511    {<dfa.accept; wrap="\n     ", separator=",", null="-1">};
1512const static NSInteger dfa<dfa.decisionNumber>_special[<dfa.numberOfStates>] =
1513    {<dfa.special; wrap="\n     ", separator=",", null="-1">};
1514const static NSInteger dfa<dfa.decisionNumber>_transition[] = {};
1515<dfa.edgeTransitionClassMap.keys:{ table |
1516const static NSInteger dfa<dfa.decisionNumber>_transition<i0>[] = {<table; separator=", ", wrap="\n ", null="-1">\};
1517}; null="">
1518
1519+ (id) newDFA<dfa.decisionNumber>WithRecognizer:(ANTLRBaseRecognizer *)aRecognizer
1520{
1521    return [[[DFA<dfa.decisionNumber> alloc] initWithRecognizer:aRecognizer] retain];
1522}
1523
1524- (id) initWithRecognizer:(ANTLRBaseRecognizer *) theRecognizer
1525{
1526    self = [super initWithRecognizer:theRecognizer];
1527    if ( self != nil ) {
1528        decisionNumber = <dfa.decisionNumber>;
1529        eot = dfa<dfa.decisionNumber>_eot;
1530        eof = dfa<dfa.decisionNumber>_eof;
1531        min = dfa<dfa.decisionNumber>_min;
1532        max = dfa<dfa.decisionNumber>_max;
1533        accept = dfa<dfa.decisionNumber>_accept;
1534        special = dfa<dfa.decisionNumber>_special;
1535        if (!(transition = calloc(<dfa.numberOfStates>, sizeof(void*)))) {
1536            [self release];
1537            return nil;
1538        }
1539        len = <dfa.numberOfStates>;
1540        <dfa.transitionEdgeTables:{whichTable|transition[<i0>] = dfa<dfa.decisionNumber>_transition<whichTable>;}; separator="\n", null="">
1541    }
1542    return self;
1543}
1544
1545<if(dfa.specialStateSTs)>
1546/* start dfa.specialStateSTs */
1547- (NSInteger) specialStateTransition:(NSInteger)s Stream:(id\<ANTLRIntStream\>)anInput
1548{
1549<if(LEXER)>
1550    id\<ANTLRIntStream\> input = anInput;<\n>
1551<endif>
1552<if(PARSER)>
1553    id\<ANTLRTokenStream\> input = (id\<ANTLRTokenStream\>)anInput;<\n>
1554<endif>
1555<if(TREE_PARSER)>
1556    id\<ANTLRTreeNodeStream\> input = (id\<ANTLRTreeNodeStream\>)anInput;<\n>
1557<endif>
1558    switch (s) {
1559        <dfa.specialStateSTs:{state |
1560        case <i0> : ;<! compressed special state numbers 0..n-1 !>
1561            <state>}; separator="\n">
1562    }
1563<if(backtracking)>
1564    if ( [recognizer getBacktrackingLevel] > 0 ) { [recognizer setFailed:YES]; return -1; }<\n>
1565<endif>
1566    ANTLRNoViableAltException *nvae = [ANTLRNoViableAltException newException:<dfa.decisionNumber> state:s stream:recognizer.input];
1567    // nvae.c = s;
1568    /* [self error:nvae]; */ <! for debugger - do later !>
1569    @throw nvae;
1570}<\n>
1571/* end dfa.specialStateSTs */
1572<endif>
1573
1574- (void) dealloc
1575{
1576    free(transition);
1577    [super dealloc];
1578}
1579
1580- (NSString *) description
1581{
1582    return @"<dfa.description>";
1583}
1584
1585<@errorMethod()>
1586
1587@end /* end DFA<dfa.decisionNumber> implementation */<\n>
1588#pragma mark Cyclic DFA implementation end DFA<dfa.decisionNumber>
1589<\n>
1590>>
1591/** A state in a cyclic DFA; it's a special state and part of a big switch on
1592 *  state.
1593 */
1594cyclicDFAState(decisionNumber, stateNumber, edges, needErrorClause, semPredState) ::= <<
1595/* cyclicDFAState */
1596NSInteger LA<decisionNumber>_<stateNumber> = [input LA:1];<\n>
1597<if(semPredState)> <! get next lookahead symbol to test edges, then rewind !>
1598NSInteger index<decisionNumber>_<stateNumber> = input.index;
1599[input rewind];<\n>
1600<endif>
1601s = -1;
1602<edges; separator="\nelse ">
1603<if(semPredState)> <! return input cursor to state before we rewound !>
1604[input seek:index<decisionNumber>_<stateNumber>];<\n>
1605<endif>
1606if ( s >= 0 )
1607    return s;
1608 break;
1609>>
1610
1611/** Just like a fixed DFA edge, test the lookahead and indicate what
1612 *  state to jump to next if successful.
1613 */
1614cyclicDFAEdge(labelExpr, targetStateNumber, edgeNumber, predicates) ::= <<
1615/* cyclicDFAEdge */
1616if (<labelExpr><if(predicates)> && (<predicates>)<endif>) { s = <targetStateNumber>;}<\n>
1617>>
1618
1619/** An edge pointing at end-of-token; essentially matches any char;
1620 *  always jump to the target.
1621 */
1622eotDFAEdge(targetStateNumber,edgeNumber, predicates) ::= <<
1623s = <targetStateNumber>;<\n> /* eotDFAEdge */
1624>>
1625
1626// D F A  E X P R E S S I O N S
1627
1628andPredicates(left,right) ::= "(<left>&&<right>)"
1629
1630orPredicates(operands) ::= "(<first(operands)><rest(operands):{o | ||<o>}>)"
1631
1632notPredicate(pred) ::= "!(<evalPredicate(pred, \"\")>)"
1633
1634evalPredicate(pred,description) ::= "(<pred>)"
1635
1636/*
1637 * evalSynPredicate(pred,description) ::= "<pred>()"
1638 *
1639 * synpreds are broken in cyclic DFA special states
1640 *  Damn! For now, work around with using the selectors directly, and by providing a trampoline evalSynPred method in
1641 *  ANTLRDFA
1642 */
1643/* evalSynPredicate(pred,description) ::= "[self evaluateSyntacticPredicate:<pred>Selector stream:input]" */
1644evalSynPredicate(pred,description) ::= "[self evaluateSyntacticPredicate:@selector(<pred>_fragment)]"
1645/* evalSynPredicate(pred,description) ::= "[recognizer <pred>]" */
1646
1647lookaheadTest(atom,k,atomAsInt) ::= "LA<decisionNumber>_<stateNumber>==<atom>"
1648
1649/** Sometimes a lookahead test cannot assume that LA(k) is in a temp variable
1650 *  somewhere.  Must ask for the lookahead directly.
1651 */
1652isolatedLookaheadTest(atom,k,atomAsInt) ::= "[input LA:<k>] == <atom>"
1653
1654lookaheadRangeTest(lower,upper,k,rangeNumber,lowerAsInt,upperAsInt) ::= <%
1655(LA<decisionNumber>_<stateNumber> >= <lower> && LA<decisionNumber>_<stateNumber> \<= <upper>)
1656%>
1657
1658isolatedLookaheadRangeTest(lower,upper,k,rangeNumber,lowerAsInt,upperAsInt) ::= "(([input LA:<k>] >= <lower>) && ([input LA:<k>] \<= <upper>))"
1659
1660setTest(ranges) ::= "<ranges; separator=\"||\">"
1661
1662// A T T R I B U T E S
1663
1664memVars(scope) ::= << <scope.attributes:{a|<a.type> <a.name>;<\n>}; separator="\n"> >>
1665
1666properties(scope) ::= <<
1667<scope.attributes:{a|@property (assign, getter=get<a.name>, setter=set<a.name>:) <a.type> <a.name>;<\n>}; separator="\n">
1668>>
1669
1670methodsDecl(scope) ::= <<
1671<scope.attributes:{a|- (<a.type>)get<a.name>;<\n>- (void)set<a.name>:(<a.type>)aVal;<\n>}; separator="\n">
1672>>
1673
1674synthesize(scope) ::= << <scope.attributes:{a|@synthesize <a.name>;}; separator="\n"> >>
1675
1676methods(scope) ::= <%
1677<scope.attributes:{a|
1678- (<a.type>)get<a.name> { return( <a.name> ); \}<\n>
1679- (void)set<a.name>:(<a.type>)aVal { <a.name> = aVal; \}<\n>}; separator="\n">
1680%>
1681
1682globalAttributeScopeInterface(scope) ::= <%
1683/* globalAttributeScopeInterface */<\n>
1684@interface <scope.name>_Scope : ANTLRSymbolsScope {<\n>
1685<if(scope.attributes)>
1686<memVars(scope)>
1687<endif>
1688}<\n>
1689<if(scope.attributes)>
1690/* start of globalAttributeScopeInterface properties */<\n>
1691<properties(scope)>
1692/* end globalAttributeScopeInterface properties */<\n>
1693<endif>
1694
1695+ (<scope.name>_Scope *)new<scope.name>_Scope;<\n>
1696- (id) init;<\n>
1697<if(scope.attributes)>
1698/* start of globalAttributeScopeInterface methodsDecl */<\n>
1699<methodsDecl(scope)>
1700/* End of globalAttributeScopeInterface methodsDecl */<\n>
1701<endif>
1702@end /* end of <scope.name>_Scope interface */<\n>
1703%>
1704
1705globalAttributeScopeMemVar(scope) ::= <%
1706/* globalAttributeScopeMemVar */<\n>
1707ANTLRSymbolStack *<scope.name>_stack;<\n>
1708<scope.name>_Scope *<scope.name>_scope;<\n>
1709%>
1710
1711globalAttributeScopeImplementation(scope) ::= <%
1712@implementation <scope.name>_Scope  /* globalAttributeScopeImplementation */<\n>
1713<if(scope.attributes)>
1714/* start of synthesize -- OBJC-Line 1750 */<\n>
1715<synthesize(scope)><\n>
1716<endif>
1717<\n>
1718+ (<scope.name>_Scope *)new<scope.name>_Scope<\n>
1719{<\n>
1720    return [[<scope.name>_Scope alloc] init];<\n>
1721}<\n>
1722<\n>
1723- (id) init<\n>
1724{<\n>
1725    self = [super init];<\n>
1726    return self;<\n>
1727}<\n>
1728<\n>
1729<if(scope.attributes)>
1730/* start of iterate get and set functions */<\n>
1731<methods(scope)><\n>
1732/* End of iterate get and set functions */<\n>
1733<endif>
1734@end /* end of <scope.name>_Scope implementation */<\n><\n>
1735%>
1736
1737globalAttributeScopeInit(scope) ::= <<
1738/* globalAttributeScopeInit */<\n>
1739<scope.name>_scope = [<scope.name>_Scope new<scope.name>_Scope];<\n>
1740<scope.name>_stack = [ANTLRSymbolStack newANTLRSymbolStackWithLen:30];<\n>
1741>>
1742
1743globalAttributeScopeDealloc(scope) ::= << [<scope.name>_stack release];<\n> >>
1744
1745globalAttributeScope(scope) ::= << static <scope.name>_stack;<\n> >>
1746
1747ruleAttributeScopeMemVar(scope) ::= <%
1748/* ObjC ruleAttributeScopeMemVar */<\n>
1749<if(scope.attributes)>
1750<scope.name>_Scope *<scope.name>_scope; /* ObjC ruleAttributeScopeMemVar */<\n>
1751<endif>
1752%>
1753
1754ruleAttributeScopeInterface(scope) ::= <%
1755<if(scope.attributes)>
1756/* start of ruleAttributeScopeInterface */<\n>
1757@interface <scope.name>_Scope : ANTLRSymbolsScope {<\n>
1758    <memVars(scope)><\n>
1759}<\n>
1760<\n>
1761/* start property declarations */<\n>
1762<properties(scope)><\n>
1763/* start method declarations */<\n>
1764+ (<scope.name>_Scope *)new<scope.name>_Scope;<\n>
1765- (id) init;<\n>
1766<methodsDecl(scope)><\n>
1767@end /* end of ruleAttributeScopeInterface */<\n><\n>
1768<endif>
1769%>
1770
1771ruleAttributeScopeImplementation(scope) ::= <%
1772<if(scope.attributes)>
1773@implementation <scope.name>_Scope  /* start of ruleAttributeScopeImplementation */<\n>
1774<synthesize(scope)><\n>
1775<\n>
1776+ (<scope.name>_Scope *)new<scope.name>_Scope<\n>
1777{<\n>
1778    return [[<scope.name>_Scope alloc] init];<\n>
1779}<\n>
1780<\n>
1781- (id) init<\n>
1782{<\n>
1783    self = [super init];<\n>
1784    return self;<\n>
1785}<\n>
1786<\n>
1787/* start of <scope.name>_Scope get and set functions */<\n>
1788<methods(scope)><\n>
1789/* End of <scope.name>_Scope get and set functions */<\n>
1790@end /* end of ruleAttributeScopeImplementation */<\n><\n>
1791<endif>
1792%>
1793
1794ruleAttributeScopeInit(scope) ::= <%
1795/* ruleAttributeScopeInit */<\n>
1796<scope.name>_scope = [<scope.name>_Scope new<scope.name>_Scope];<\n>
1797<scope.name>_stack = [ANTLRSymbolStack newANTLRSymbolStackWithLen:30];<\n>
1798%>
1799
1800ruleAttributeScopeDealloc(scope) ::= <% [<scope.name>_Scope release];<\n> %>
1801
1802ruleAttributeScope(scope) ::= <%
1803<if(scope.attributes)>
1804/* ruleAttributeScope */<\n>
1805static ANTLRSymbolStack *<scope.name>_stack;<\n>
1806<endif>
1807%>
1808
1809ruleAttributeScopeDecl(scope) ::= <%
1810/* ruleAttributeScopeDecl */<\n>
1811<if(scope.attributes)>
1812<scope.name>_Scope *<scope.name>_scope;<\n>
1813<endif>
1814%>
1815
1816returnStructName(r) ::= "<className()>_<r.name>_return"
1817
1818returnType() ::= <%
1819<if(!ruleDescriptor.isSynPred)>
1820<if(ruleDescriptor.hasMultipleReturnValues)>
1821<ruleDescriptor:returnStructName()> *
1822<else>
1823<if(ruleDescriptor.hasSingleReturnValue)>
1824<ruleDescriptor.singleValueReturnType>
1825<else>
1826void
1827<endif>
1828<endif>
1829<else>
1830void
1831<endif>
1832%>
1833
1834/** Generate the Objective-C type associated with a single or multiple return
1835 *  values.
1836 */
1837ruleLabelType(referencedRule) ::= <%
1838<if(referencedRule.hasMultipleReturnValues)>
1839<className()>_<referencedRule.name>_return *<else>
1840<if(referencedRule.hasSingleReturnValue)><referencedRule.singleValueReturnType><else>
1841void<endif>
1842<endif>
1843%>
1844
1845delegateName(d) ::= << <if(d.label)><d.label><else>g<d.name><endif> >>
1846
1847/** Using a type to init value map, try to init a type; if not in table
1848 *  must be an object, default value is "null".
1849 */
1850initValue(typeName) ::= <% <objcTypeInitMap.(typeName)> %>
1851
1852/** Define a rule label including default value */
1853ruleLabelDef(label) ::= << <ruleLabelType(referencedRule=label.referencedRule)> <label.label.text> = <initValue(typeName=ruleLabelType(referencedRule=label.referencedRule))>;<\n> >>
1854
1855/** Define a return struct for a rule if the code needs to access its
1856 *  start/stop tokens, tree stuff, attributes, ...  Leave a hole for
1857 *  subgroups to stick in members.
1858 */
1859returnScopeInterface(scope) ::= <<
1860<if(ruleDescriptor.hasMultipleReturnValues)>
1861/* returnScopeInterface <ruleDescriptor:returnStructName()> */
1862@interface <ruleDescriptor:returnStructName()> : ANTLR<if(TREE_PARSER)>Tree<else>Parser<endif>RuleReturnScope { /* returnScopeInterface line 1838 */
1863<@memVars()> /* ObjC start of memVars() */<\n>
1864<if(scope.attributes)>
1865<memVars(scope)><\n>
1866<endif>
1867}
1868/* start property declarations */
1869<@properties()><\n>
1870<if(scope.attributes)>
1871<properties(scope)><\n>
1872<endif>
1873/* start of method declarations */<\n>
1874+ (<ruleDescriptor:returnStructName()> *)new<ruleDescriptor:returnStructName()>;
1875/* this is start of set and get methods */
1876<@methodsDecl()>  /* methodsDecl */<\n>
1877<if(scope.attributes)>
1878/* start of iterated get and set functions */<\n>
1879<methodsDecl(scope)><\n>
1880<endif>
1881@end /* end of returnScopeInterface interface */<\n>
1882<endif>
1883>>
1884
1885returnScopeImplementation(scope) ::= <%
1886<if(ruleDescriptor.hasMultipleReturnValues)>
1887@implementation <ruleDescriptor:returnStructName()> /* returnScopeImplementation */<\n>
1888<@synthesize()> /* start of synthesize -- OBJC-Line 1837 */<\n>
1889<if(scope.attributes)>
1890    <synthesize(scope)><\n>
1891<endif>
1892+ (<ruleDescriptor:returnStructName()> *)new<ruleDescriptor:returnStructName()><\n>
1893{<\n>
1894    return [[[<ruleDescriptor:returnStructName()> alloc] init] retain];<\n>
1895}<\n>
1896<\n>
1897- (id) init<\n>
1898{<\n>
1899    self = [super init];<\n>
1900    return self;<\n>
1901}<\n>
1902<\n>
1903<@methods()><\n>
1904<if(scope.attributes)>
1905/* start of iterate get and set functions */<\n>
1906<methods(scope)><\n>
1907/* End of iterate get and set functions */<\n>
1908<endif>
1909<actions.(actionScope).ruleReturnMethods>
1910<@ruleReturnMembers()><\n>
1911@end /* end of returnScope implementation */<\n><\n>
1912<endif>
1913%>
1914
1915parameterScope(scope) ::= <<
1916<! <scope.attributes:{it | :(<it.type>)<it.name>}; separator=" "> !>
1917<first(scope.attributes):{ a | :(<a.type>)<a.name>}> <rest(scope.attributes):{ a | arg<i>:(<a.type>)<a.name> }; separator=" ">
1918>>
1919
1920parameterAttributeRef(attr) ::= "<attr.name>"
1921parameterSetAttributeRef(attr,expr) ::= "<attr.name> = <expr>;"
1922
1923/** Note that the scopeAttributeRef does not have access to the
1924 * grammar name directly
1925 */
1926scopeAttributeRef(scope,attr,index,negIndex) ::= <%
1927<if(negIndex)>
1928([((<scope>_Scope *)[<scope>_stack objectAtIndex:[<scope>_stack size]-<negIndex>-1)]).<attr.name>
1929<else>
1930<if(index)>
1931((<scope>_Scope *)[<scope>_stack objectAtIndex:<index>]).<attr.name>
1932<else>
1933((<scope>_Scope *)[<scope>_stack peek]).<attr.name>
1934<endif>
1935<endif>
1936%>
1937
1938scopeSetAttributeRef(scope,attr,expr,index,negIndex) ::= <%
1939/* scopeSetAttributeRef */
1940<if(negIndex)>
1941((<scope>_Scope *)[<scope>_stack objectAtIndex:([<scope>_stack size]-<negIndex>-1)]).<attr.name> = <expr>;
1942<else>
1943<if(index)>
1944((<scope>_Scope *)[<scope>_stack objectAtIndex:<index>]).<attr.name> = <expr>;
1945<else>
1946((<scope>_Scope *)[<scope>_stack peek]).<attr.name> = <expr>;
1947<endif>
1948<endif>
1949%>
1950
1951scopeAttributeRefStack() ::= <<
1952/* scopeAttributeRefStack */
1953<if(negIndex)>
1954((<scope>_Scope *)[<scope>_stack objectAtIndex:[<scope>_stack count]-<negIndex>-1]).<attr.name> = <expr>;
1955<else>
1956<if(index)>
1957((<scope>_Scope *)[<scope>_stack objectAtIndex:<index>]).<attr.name> = <expr>;
1958<else>
1959((<scope>_Scope *)[<scope>_stack peek]).<attr.name> = <expr>;
1960<endif>
1961<endif>
1962>>
1963
1964/** $x is either global scope or x is rule with dynamic scope; refers
1965 *  to stack itself not top of stack.  This is useful for predicates
1966 *  like {$function.size()>0 && $function::name.equals("foo")}?
1967 */
1968isolatedDynamicScopeRef(scope) ::= "<scope>_stack"
1969
1970/** reference an attribute of rule; might only have single return value */
1971ruleLabelRef(referencedRule,scope,attr) ::= <<
1972<if(referencedRule.hasMultipleReturnValues)>
1973(<scope>!=nil?<scope>.<attr.name>:<initValue(attr.type)>)
1974<else>
1975<scope>
1976<endif>
1977>>
1978
1979returnAttributeRef(ruleDescriptor,attr) ::= <%
1980<if(ruleDescriptor.hasMultipleReturnValues)>
1981retval.<attr.name>  /* added to returnAttributeRef */<\n>
1982<else>
1983<attr.name><\n>
1984<endif>
1985%>
1986
1987returnSetAttributeRef(ruleDescriptor,attr,expr) ::= <%
1988<if(ruleDescriptor.hasMultipleReturnValues)>
1989 retval.<attr.name> =<expr>; /* added to returnSetAttributeRef */<\n>
1990<else>
1991<attr.name> = <expr>;<\n>
1992<endif>
1993%>
1994
1995/** How to translate $tokenLabel */
1996tokenLabelRef(label) ::= "<label>"
1997
1998/** ids+=ID {$ids} or e+=expr {$e} */
1999listLabelRef(label) ::= "list_<label>"
2000
2001
2002/* not sure the next are the right approach; and they are evaluated early; */
2003/* they cannot see TREE_PARSER or PARSER attributes for example. :( */
2004
2005tokenLabelPropertyRef_text(scope,attr) ::= "(<scope>!=nil?<scope>.text:nil)"
2006tokenLabelPropertyRef_type(scope,attr) ::= "(<scope>!=nil?<scope>.type:0)"
2007tokenLabelPropertyRef_line(scope,attr) ::= "(<scope>!=nil?<scope>.line:0)"
2008tokenLabelPropertyRef_pos(scope,attr) ::= "(<scope>!=nil?<scope>.charPositionInLine:0)"
2009tokenLabelPropertyRef_channel(scope,attr) ::= "(<scope>!=nil?<scope>.channel:0)"
2010tokenLabelPropertyRef_index(scope,attr) ::= "(<scope>!=nil?[<scope> getTokenIndex]:0)"
2011tokenLabelPropertyRef_tree(scope,attr) ::= "<scope>_tree"
2012tokenLabelPropertyRef_int(scope,attr) ::= "(<scope>!=nil?[<scope>.text integerValue]:0)"
2013
2014ruleLabelPropertyRef_start(scope,attr) ::= "(<scope>!=nil?((<labelType> *)<scope>.start):nil)"
2015ruleLabelPropertyRef_stop(scope,attr) ::= "(<scope>!=nil?((<labelType> *)<scope>.stopToken):nil)"
2016ruleLabelPropertyRef_tree(scope,attr) ::= "(<scope>!=nil?((<ASTLabelType> *)<scope>.tree):nil)"
2017ruleLabelPropertyRef_text(scope,attr) ::= <%
2018<if(TREE_PARSER)>
2019(<scope>!=nil?[[input getTokenStream] toStringFromStart:[[input getTreeAdaptor] getTokenStartIndex:[<scope> getStart]]
2020         ToEnd:[[input getTreeAdaptor] getTokenStopIndex:[<scope> getStart]]]:0)
2021<else>
2022(<scope>!=nil?([input toStringFromStart:[<scope> getStart] ToEnd:[<scope> getStop]]:0)
2023<endif>
2024%>
2025ruleLabelPropertyRef_st(scope,attr) ::= "(<scope>!=nil?[<scope> st]:nil)"
2026
2027/** Isolated $RULE ref ok in lexer as it's a Token */
2028lexerRuleLabel(label) ::= "<label>"
2029
2030lexerRuleLabelPropertyRef_type(scope,attr) ::= "(<scope>!=nil?<scope>.type:0)"
2031lexerRuleLabelPropertyRef_line(scope,attr) ::= "(<scope>!=nil?<scope>.line:0)"
2032lexerRuleLabelPropertyRef_pos(scope,attr) ::= "(<scope>!=nil?<scope>.charPositionInLine:-1)"
2033lexerRuleLabelPropertyRef_channel(scope,attr) ::= "(<scope>!=nil?<scope>.channel:0)"
2034lexerRuleLabelPropertyRef_index(scope,attr) ::= "(<scope>!=nil?[<scope> getTokenIndex]:0)"
2035lexerRuleLabelPropertyRef_text(scope,attr) ::= "(<scope>!=nil?<scope>.text:nil)"
2036lexerRuleLabelPropertyRef_int(scope,attr) ::="(<scope>!=nil?[<scope>.text integerValue]:0)"
2037
2038// Somebody may ref $template or $tree or $stop within a rule:
2039rulePropertyRef_start(scope,attr) ::= "((<labelType> *)retval.start)"
2040rulePropertyRef_stop(scope,attr) ::= "((<labelType> *)retval.stopToken)"
2041rulePropertyRef_tree(scope,attr) ::= "((<ASTLabelType> *)retval.tree)"
2042rulePropertyRef_text(scope,attr) ::= <<
2043<if(TREE_PARSER)>
2044[[input getTokenStream] toStringFromStart:[[input getTreeAdaptor] getTokenStartIndex:retval.start.token.startIndex]
2045                                    ToEnd:[[input getTreeAdaptor] getTokenStopIndex:retval.start.token.stopIndex]]
2046<else>
2047[input toStringFromToken:retval.start ToToken:[input LT:-1]]
2048<endif>
2049>>
2050rulePropertyRef_st(scope,attr) ::= "retval.st"
2051
2052/* hideous: find a way to cut down on the number of templates to support read/write access */
2053/* TODO: also, which ones are valid to write to? ask Ter */
2054lexerRuleSetPropertyRef_text(scope,attr,expr) ::= "state.text = <expr>;"
2055lexerRuleSetPropertyRef_type(scope,attr,expr) ::= "_type"
2056lexerRuleSetPropertyRef_line(scope,attr,expr) ::= "state.tokenStartLine"
2057lexerRuleSetPropertyRef_pos(scope,attr,expr) ::= "state.tokenStartCharPositionInLine"
2058lexerRuleSetPropertyRef_index(scope,attr,expr) ::= "-1" /* undefined token index in lexer */
2059lexerRuleSetPropertyRef_channel(scope,attr,expr) ::= "state.channel=<expr>;"
2060lexerRuleSetPropertyRef_start(scope,attr,expr) ::= "state.tokenStartCharIndex"
2061lexerRuleSetPropertyRef_stop(scope,attr,expr) ::= "(input.index-1)"
2062
2063
2064lexerRulePropertyRef_text(scope,attr) ::= "self.text"
2065lexerRulePropertyRef_type(scope,attr) ::= "state.type"
2066lexerRulePropertyRef_line(scope,attr) ::= "state.tokenStartLine"
2067lexerRulePropertyRef_pos(scope,attr) ::= "state.tokenStartCharPositionInLine"
2068lexerRulePropertyRef_index(scope,attr) ::= "-1" // undefined token index in lexer
2069lexerRulePropertyRef_channel(scope,attr) ::= "_channel"
2070lexerRulePropertyRef_start(scope,attr) ::= "state.tokenStartCharIndex"
2071lexerRulePropertyRef_stop(scope,attr) ::= "(input.index-1)"
2072lexerRulePropertyRef_int(scope,attr) ::= "[<scope>.text integerValue]"
2073
2074// setting $st and $tree is allowed in local rule. everything else
2075// is flagged as error
2076ruleSetPropertyRef_tree(scope,attr,expr) ::= "retval.start =<expr>;"
2077ruleSetPropertyRef_st(scope,attr,expr) ::= "retval.st =<expr>;" /* "<\n>#error StringTemplates are unsupported<\n>" */
2078
2079
2080/** How to execute an action */
2081execAction(action) ::= <<
2082<if(backtracking)>
2083if ( <actions.(actionScope).synpredgate> ) {
2084    <action>
2085}
2086<else>
2087<action>
2088<endif>
2089>>
2090
2091/** How to always execute an action even when backtracking */
2092execForcedAction(action) ::= "<action>"
2093
2094// M I S C (properties, etc...)
2095
2096bitset(name, words64) ::= <<
2097static ANTLRBitSet *<name>;
2098static const unsigned long long <name>_data[] = { <words64:{it | <it>LL};separator=", ">};<\n>
2099>>
2100
2101bitsetInit(name, words64) ::= <<
2102<name> = [[ANTLRBitSet newANTLRBitSetWithBits:(const unsigned long long *)<name>_data Count:(NSUInteger)<length(words64)>] retain];<\n>
2103>>
2104
2105codeFileExtension() ::= ".m"
2106
2107true_value() ::= "YES"
2108false_value() ::= "NO"
2109