All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.cassandraunit.shaded.org.antlr.codegen.templates.ObjC.ObjC.stg Maven / Gradle / Ivy

There is a newer version: 4.3.1.0
Show newest version
/*
 [The "BSD license"]
 Copyright (c) 2006, 2007 Kay Roepke 2010 Alan Condit
 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.
*/

/*
 *  Template group file for the Objective C code generator.
 *  Heavily based on Java.stg
 *
 *  Written by Kay Roepke 
 *  Modified by Alan Condit 
 *
 *  This file is part of ANTLR and subject to the same license as ANTLR itself.
 */

objcTypeInitMap ::= [
    "int"           : "0",              // Integers     start out being 0
    "long"          : "0",              // Longs        start out being 0
    "float"         : "0.0",            // Floats       start out being 0
    "double"        : "0.0",            // Doubles      start out being 0
    "BOOL"          : "NO",             // Booleans     start out being Antlr ObjC for false
    "byte"          : "0",              // Bytes        start out being 0
    "short"         : "0",              // Shorts       start out being 0
    "char"          : "0",              // Chars        start out being 0
    "id"            : "nil",            // ids          start out being nil
    default         : "nil"             // anything other than an atomic type
]

// System.Boolean.ToString() returns "True" and "False", but the proper C# literals are "true" and "false"
// The Java version of Boolean returns "true" and "false", so they map to themselves here.
booleanLiteral ::= [
	"True":"true",
	"False":"false",
	"true":"YES",
	"false":"NO",
	default:"NO"
]


className() ::= "LexerTreeParser!>"
leadIn(type) ::=
<<
/** \file
 *  This  file was generated by $ANTLR version 
 *
 *     -  From the grammar source file : 
 *     -                            On : 

 *     -                 for the lexer : Lexer


 *     -                for the parser : Parser


 *     -           for the tree parser : TreeParser

 *
 * Editing it, at least manually, is not wise.
 *
 * ObjC language generator and runtime by Alan Condit, acondit|hereisanat|ipns|dotgoeshere|com.
 *
 *
>>

/** The overall file structure of a recognizer; stores methods for rules
 *  and cyclic DFAs plus support code.
 */
outputFile( LEXER,
            PARSER,
            TREE_PARSER,
            actionScope,
            actions,
            docComment,
            recognizer,
            name,
            tokens,
            tokenNames,
            rules,
            cyclicDFAs,
            bitsets,
            buildTemplate,
            buildAST,
            rewriteMode,
            profile,
            backtracking,
            synpreds,
            memoize,
            numRules,
            fileName,
            ANTLRVersion,
            generatedTimestamp,
            trace,
            scopes,
            superClass,
            literals
            ) ::=
<<

*/
// $ANTLR   


/* =============================================================================
 * This is what the grammar programmer asked us to put at the top of every file.
 */

/* End of Header action.
 * =============================================================================
 */
 !>

/* -----------------------------------------
 * Include the ANTLR3 generated header file.
 */
#import "LexerTreeParser!>.h"

/* ----------------------------------------- */




/** String literals used by  that we must do things like MATCHS() with.
 *  C will normally just lay down 8 bit characters, and you can use L"xxx" to
 *  get wchar_t, but wchar_t is 16 bits on Windows, which is not UTF32 and so
 *  we perform this little trick of defining the literals as arrays of UINT32
 *  and passing in the address of these.
 */
[]  = ;}; separator="\n">



/* ============================================================================= */
/* =============================================================================
 * Start of recognizer
 */

>>
headerFileExtension() ::= ".h"

headerFile( LEXER,
            PARSER,
            TREE_PARSER,
            actionScope,
            actions,
            docComment,
            recognizer,
            name,
            tokens,
            tokenNames,
            rules,
            cyclicDFAs,
            bitsets,
            buildTemplate,
            buildAST,
            rewriteMode,
            profile,
            backtracking,
            synpreds,
            memoize,
            numRules,
            fileName,
            ANTLRVersion,
            generatedTimestamp,
            trace,
            scopes,
            superClass,
            literals
          ) ::=
<<
// $ANTLR   

<@imports>

/* =============================================================================
 * Standard antlr OBJC runtime definitions
 */
#import \
#import \
/* End of standard antlr3 runtime definitions
 * =============================================================================
 */

<@end>











>>

lexerHeaderFile( LEXER,
            PARSER,
            TREE_PARSER,
            actionScope,
            actions,
            docComment,
            recognizer,
            name,
            tokens,
            tokenNames,
            rules,
            cyclicDFAs,
            bitsets,
            buildTemplate,
            profile,
            backtracking,
            synpreds,
            memoize,
            numRules,
            fileName,
            ANTLRVersion,
            generatedTimestamp,
            trace,
            scopes,
            superClass="Lexer"
            ) ::=
<<


/* =============================================================================
 * This is what the grammar programmer asked us to put at the top of every file.
 */

/* End of Header action.
 * =============================================================================
 */


/* Start cyclicDFAInterface */


#pragma mark Rule return scopes Interface start
}>}>
#pragma mark Rule return scopes Interface end
#pragma mark Tokens
#ifndef TOKENLISTAlreadyDefined
#define TOKENLISTAlreadyDefined 1
#ifdef EOF
#undef EOF
#endif
 }; separator="\n">
#endif
/* interface lexer class */
@interface  <@superClassName>: <@end> { // line 283
 *dfa;}; separator="\n">
Selector;}; separator="\n">
/* ObjC start of actions.lexer.memVars */

/* ObjC end of actions.lexer.memVars */
}
+ (void) initialize;
+ ( *)newWithCharStream:(id\)anInput;
/* ObjC start actions.lexer.methodsDecl */

/* ObjC end actions.lexer.methodsDecl */
}>) m_fragment ; }; separator="\n"><\n>
@end /* end of  interface */<\n>
>>

headerReturnScope(ruleDescriptor) ::= ""
headerReturnType(ruleDescriptor) ::= <<


 void

 


 

>>
// Produce the lexer output
lexer(  grammar,
        name,
        tokens,
        scopes,
        rules,
        numRules,
        filterMode,
        labelType="CommonToken",
        superClass="Lexer"
        ) ::= <<


/** As per Terence: No returns for lexer rules! */
}>
}>
#pragma mark Rule return scopes end
!>
@implementation  // line 330

+ (void) initialize
{
    [BaseRecognizer setGrammarFileName:@""];
}

+ (NSString *) tokenNameForType:(NSInteger)aTokenType
{
    return [[self getTokenNames] objectAtIndex:aTokenType];
}

+ ( *)newWithCharStream:(id\)anInput
{
    return [[ alloc] initWithCharStream:anInput];
}

- (id) initWithCharStream:(id\)anInput
{
    self = [super initWithCharStream:anInput State:[RecognizerSharedState newRecognizerSharedStateWithRuleLen:+1]];
    if ( self != nil ) {

        if ( state.ruleMemo == nil ) {
            state.ruleMemo = [[RuleStack newRuleStackWithSize:+1] retain];
        }
        if ( [state.ruleMemo count] == 0 ) {
            // initialize the memoization cache - the indices are 1-based in the runtime code!
            
            for (NSInteger i = 0; i \< ; i++) {
                [state.ruleMemo addObject:[HashRule newHashRuleWithLen:17]];
            }
        }

        };separator="\n">
         = [DFA newDFAWithRecognizer:self];}; separator="\n">
        
    }
    return self;
}

- (void) dealloc
{
     release];}; separator="\n">

    [super dealloc];
}

/* ObjC Start of actions.lexer.methods */

/* ObjC end of actions.lexer.methods */
/* ObjC start methods() */
<@methods()>
/* ObjC end methods() */


- (void) reset
{
    
    [super reset];
}





/* Start of Rules */


@end /* end of  implementation line 397 */
>>

/** A override of Lexer.nextToken() that backtracks over mTokens() looking
 *  for matches.  No error can be generated upon error; just rewind, consume
 *  a token and then try again.  backtracking needs to be set as well.
 *  Make rule memoization happen only at levels above 1 as we start mTokens
 *  at backtracking==1.
 */
filteringNextToken() ::= <<
- (id\) nextToken
{
    while (YES) {
        if ( [input LA:1] == CharStreamEOF ) {
            return [ eofToken];
        }
        state.token = nil;
        state.channel = TokenChannelDefault;
        state.tokenStartCharIndex = input.index;
        state.tokenStartCharPositionInLine = input.charPositionInLine;
        state.tokenStartLine = input.line;
        state.text = nil;
        @try {
            NSInteger m = [input mark];
            state.backtracking = 1; /* means we won't throw slow exception */
            state.failed = NO;
            [self mTokens];
            state.backtracking = 0;
            /* mTokens backtracks with synpred at backtracking==2
               and we set the synpredgate to allow actions at level 1. */
            if ( state.failed ) {
                [input rewind:m];
                [input consume]; /* advance one char and try again */
            } else {
                [self emit];
                return state.token;
            }
        }
        @catch (RecognitionException *re) {
            // shouldn't happen in backtracking mode, but...
            [self reportError:re];
            [self recover:re];
        }
    }
}

- (void)memoize:(id\)anInput
      RuleIndex:(NSInteger)ruleIndex
     StartIndex:(NSInteger)ruleStartIndex
{
    if ( state.backtracking > 1 ) [super memoize:anInput RuleIndex:ruleIndex StartIndex:ruleStartIndex];
}

- (BOOL)alreadyParsedRule:(id\)anInput RuleIndex:(NSInteger)ruleIndex
{
    if ( state.backtracking > 1 ) return [super alreadyParsedRule:anInput RuleIndex:ruleIndex];
    return NO;
}
>>

actionGate() ::= "state.backtracking == 0"

filteringActionGate() ::= "state.backtracking == 1"

parserHeaderFile( LEXER,
            PARSER,
            TREE_PARSER,
            actionScope,
            actions,
            docComment,
            recognizer,
            name,
            tokens,
            tokenNames,
            rules,
            cyclicDFAs,
            bitsets,
            buildTemplate,
            profile,
            backtracking,
            synpreds,
            memoize,
            numRules,
            fileName,
            ANTLRVersion,
            generatedTimestamp,
            trace,
            scopes,
            literals,
            superClass="Parser"
            ) ::= <<
/* parserHeaderFile */
",...)>
>>

treeParserHeaderFile( LEXER,
            PARSER,
            TREE_PARSER,
            actionScope,
            actions,
            docComment,
            recognizer,
            name,
            tokens,
            tokenNames,
            rules,
            cyclicDFAs,
            bitsets,
            buildTemplate,
            profile,
            backtracking,
            synpreds,
            memoize,
            numRules,
            fileName,
            ANTLRVersion,
            generatedTimestamp,
            trace,
            scopes,
            literals,
            superClass="TreeParser"
            ) ::= <<
/* treeParserHeaderFile */
",...)>
>>

genericParserHeaderFile( LEXER,
            PARSER,
            TREE_PARSER,
            actionScope,
            actions,
            docComment,
            recognizer,
            name,
            tokens,
            tokenNames,
            rules,
            cyclicDFAs,
            bitsets,
            buildTemplate,
            profile,
            backtracking,
            synpreds,
            memoize,
            numRules,
            fileName,
            ANTLRVersion,
            generatedTimestamp,
            trace,
            scopes,
            superClass,
            literals,
            inputStreamType
            ) ::=
<<

/* =============================================================================
 * This is what the grammar programmer asked us to put at the top of every file.
 */

/* End of Header action.
 * =============================================================================
 */


#ifndef ANTLR3TokenTypeAlreadyDefined
#define ANTLR3TokenTypeAlreadyDefined
typedef enum {
    ANTLR_EOF = -1,
    INVALID,
    EOR,
    DOWN,
    UP,
    MIN
} ANTLR3TokenType;
#endif


#pragma mark Tokens
#ifndef TOKENLISTAlreadyDefined
#define TOKENLISTAlreadyDefined 1
#ifdef EOF
#undef EOF
#endif
 }; separator="\n">
#endif
#pragma mark Dynamic Global Scopes globalAttributeScopeInterface
}>
#pragma mark Dynamic Rule Scopes ruleAttributeScopeInterface
}>}>
#pragma mark Rule Return Scopes returnScopeInterface
}>}>

/* Interface grammar class */
@interface  <@superClassName> : <@end> { /* line 572 */
#pragma mark Dynamic Rule Scopes ruleAttributeScopeDecl
}>
#pragma mark Dynamic Global Rule Scopes globalAttributeScopeMemVar
}><\n>
/* ObjC start of actions.(actionScope).memVars */

/* ObjC end of actions.(actionScope).memVars */
/* ObjC start of memVars */
<@memVars()>
/* ObjC end of memVars */

 *dfa;}; separator="\n">
Selector;}; separator="\n">
 }

/* ObjC start of actions.(actionScope).properties */

/* ObjC end of actions.(actionScope).properties */
/* ObjC start of properties */
<@properties()>
/* ObjC end of properties */

+ (void) initialize;
+ ( *) new:()aStream;
/* ObjC start of actions.(actionScope).methodsDecl */

/* ObjC end of actions.(actionScope).methodsDecl */

/* ObjC start of methodsDecl */
<@methodsDecl()>
/* ObjC end of methodsDecl */

}>)_fragment; }; separator="\n"><\n>

@end /* end of  interface */<\n>
>>

parser( grammar,
        name,
        scopes,
        tokens,
        tokenNames,
        rules,
        numRules,
        bitsets,
        ASTLabelType="CommonTree",
        superClass="Parser",
        labelType="CommonToken",
        members={}
        ) ::= <<
", rewriteElementType="Token", ...)>
>>

/** How to generate a tree parser; same as parser except the input
 *  stream is a different type.
 */
treeParser( grammar,
        name,
        scopes,
        tokens,
        tokenNames,
        globalAction,
        rules,
        numRules,
        bitsets,
        filterMode,
        labelType={},
        ASTLabelType="CommonTree",
        superClass={TreeRewriterTreeFilterTreeParser},
        members={}
        ) ::= <<
", rewriteElementType="Node", ...)>
>>

/** How to generate a parser */
genericParser(  grammar,
        name,
        scopes,
        tokens,
        tokenNames,
        rules,
        numRules,
        cyclicDFAs,          // parser init -- initializes the DFAs
        bitsets,
        labelType,
        ASTLabelType,
        superClass,
        members,
        filterMode,
        rewriteElementType,
        inputStreamType
        ) ::= <<


#pragma mark Bitsets
_in_}, words64=it.bits)>}>

#pragma mark Dynamic Global globalAttributeScopeImplementation
}>

#pragma mark Dynamic Rule Scopes ruleAttributeScopeImplementation
}>}>

#pragma mark Rule Return Scopes returnScopeImplementation
}>}>

@implementation   // line 637

/* ObjC start of ruleAttributeScope */
#pragma mark Dynamic Rule Scopes ruleAttributeScope
}>
/* ObjC end of ruleAttributeScope */
#pragma mark global Attribute Scopes globalAttributeScope
/* ObjC start globalAttributeScope */
}>
/* ObjC end globalAttributeScope */
/* ObjC start actions.(actionScope).synthesize */

/* ObjC start synthesize() */
<@synthesize()>

+ (void) initialize
{
    #pragma mark Bitsets
    _in_}, words64=it.bits)>}>
    [BaseRecognizer setTokenNames:[[AMutableArray arrayWithObjects:@"\", @"\", @"\", @"\", }; separator=", ", wrap="\n ">, nil] retain]];
    [BaseRecognizer setGrammarFileName:@""];
    }>
}

+ ( *)new:()aStream
{

    return [[ alloc] initWithTokenStream:aStream];

    return [[ alloc] initWithStream:aStream];

}


- (id) initWithTokenStream:()aStream
{
    self = [super initWithTokenStream:aStream State:[[RecognizerSharedState newRecognizerSharedStateWithRuleLen:+1] retain]];
    if ( self != nil ) {

- (id) initWithStream:()aStream
{
    self = [super initWithStream:aStream State:[[RecognizerSharedState newRecognizerSharedStateWithRuleLen:+1] retain]];
    if ( self != nil ) {

         !>
         = [DFA newDFAWithRecognizer:self];}; separator="\n">
        }>
        }>
        /* start of actions-actionScope-init */
        
        /* start of init */
        <@init()>
    }
    return self;
}

- (void) dealloc
{
     release];}; separator="\n">
    }>
    
    <@dealloc()>
    [super dealloc];
}

/* ObjC start actions.(actionScope).methods */

/* ObjC end actions.(actionScope).methods */
/* ObjC start methods() */
<@methods()>
/* ObjC end methods() */
/* ObjC start rules */

/* ObjC end rules */

@end /* end of  implementation line 692 */<\n>
>>

parserCtorBody() ::= <<
 /* parserCtorBody */

state.ruleMemo = [[RuleStack newRuleStack:+1] retain];<\n> 


 = ;}; separator="\n">
>>

/** A simpler version of a rule template that is specific to the imaginary
 *  rules created for syntactic predicates.  As they never have return values
 *  nor parameters etc..., just give simplest possible method.  Don't do
 *  any of the normal memoization stuff in here either; it's a waste.
 *  As predicates cannot be inlined into the invoking rule, they need to
 *  be in a rule by themselves.
 */
synpredRule(ruleName, ruleDescriptor, block, description, nakedBlock) ::=
<<
// $ANTLR start _fragment
- (void) _fragment
{
    
    
        [self traceIn:\@"_fragment" Index:];
    @try {
        
    }
    @finally {
        [self traceOut:\@"_fragment" Index:];
    }

    

} // $ANTLR end _fragment
>>

synpred(name) ::= <<
SEL Selector = @selector(_fragment);

- (BOOL) 
{
    state.backtracking++;
    <@start()>
    NSInteger start = [input mark];
    @try {
        [self _fragment]; // can never throw exception
    }
    @catch (RecognitionException *re) {
        NSLog(@"impossible: %@\n", re.name);
    }
    BOOL success = (state.failed == NO);
    [input rewind:start];
    <@stop()>
    state.backtracking--;
    state.failed=NO;
    return success;
} // $ANTLR end  <\n> !>
>>

lexerSynpred(name) ::= <<

>>

ruleMemoization(name) ::= <<

if ( state.backtracking > 0 && [self alreadyParsedRule:input RuleIndex:] ) { return ; }

>>

/** How to test for failure and return from rule */
checkRuleBacktrackFailure() ::= <<
if ( state.failed ) return ;
>>

/** This rule has failed, exit indicating failure during backtrack */
ruleBacktrackFailure() ::= <<
if ( state.backtracking > 0 ) { state.failed = YES; return ; }<\n>
>>

/** How to generate code for a rule.
 *  The return type aggregates are declared in the header file (headerFile template)
 */
rule(ruleName,ruleDescriptor,block,emptyRule,description,exceptions,finally,memoize) ::= <<

/*
 * $ANTLR start 
 * :
 */
- () 
{
    [self traceIn:\@"" Index:];
    NSLog(@"enter  %@ failed=%@ backtracking=%d", [input LT:1], (state.failed==YES)?@"YES":@"NO", state.backtracking);
    
    
    
    <@preamble()>
    @try {
        
        
        
        
        <(ruleDescriptor.actions.after):execAction()>
    }

    <\n>}>

    

    @catch (RecognitionException *re) {
        [self reportError:re];
        [self recover:input Exception:re];
        <@setErrorReturnValue()>
    }<\n>

    @finally {
        [self traceOut:@"" Index:];
        
        
        
    }
    <@postamble()>
    return ;
}
/* $ANTLR end  */
>>

finalCode(finalBlock) ::= <<
{
    
}
>>

catch(decl,action) ::= <<
@catch () {
    
}
>>

ruleDeclarations() ::= <<
/* ruleDeclarations */

 retval = [ new];
[retval setStart:[input LT:1]];<\n>

  = ;
}>


NSInteger _StartIndex = input.index;

>>

ruleScopeSetUp() ::= <<
/* ruleScopeSetUp */
_stack push:[_Scope new_Scope]];}>
_stack push:[_Scope new_Scope]];}>
>>

ruleScopeCleanUp() ::= <<
/* ruleScopeCleanUp */
_stack pop];}; separator="\n">
_stack pop];}; separator="\n">
>>

ruleLabelDefs() ::= <%
/* ruleLabelDefs entry */<"\n">
<[ruleDescriptor.tokenLabels, ruleDescriptor.tokenListLabels,
  ruleDescriptor.wildcardTreeLabels,ruleDescriptor.wildcardTreeListLabels]
    :{it | * = nil;}; separator="\n"><"\n">
<[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels,ruleDescriptor.wildcardTreeListLabels]
    :{it | AMutableArray *list_ = nil;}; separator="\n"><"\n">
<"\n">
 = nil;}; separator="\n"><"\n">
%>

lexerRuleLabelDefs() ::= <<
<[ruleDescriptor.tokenLabels,
  ruleDescriptor.tokenListLabels,
  ruleDescriptor.ruleLabels]
    :{it | *=nil;}; separator="\n"
>
;}; separator="\n">
<[ruleDescriptor.tokenListLabels,
  ruleDescriptor.ruleListLabels]:{it |AMutableArray *list_=nil; }; separator="\n">
>>

ruleReturnValue() ::= <%





retval



%>

ruleCleanUp() ::= <<
/* token+rule list labels */
<[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels]:{it |[list_ release];}; separator="\n">


[retval setStop:[input LT:-1]];<\n>

>>

memoize() ::= <<


if (state.backtracking > 0) [self memoize:input RuleIndex: StartIndex:_StartIndex];

>>

/** How to generate a rule in the lexer; naked blocks are used for
 *  fragment rules.
 */
lexerRule(ruleName, nakedBlock, ruleDescriptor, block, memoize) ::= <<
// $ANTLR start ""
- (void) m
{
    //[self traceIn:\@"" Index:];
    NSLog(@"enter  %C line=%d:%d failed=%@ backtracking=%d",
        [input LA:1],
        self.line,
        self.charPositionInLine,
        (state.failed==YES) ? @"YES" : @"NO",
        state.backtracking);
    
    
    
    @try {

        
        
        
        <\n>

        NSInteger _type = ;
        NSInteger _channel = TokenChannelDefault;
        
        
        
        
        
        state.type = _type;
        state.channel = _channel;
        <(ruleDescriptor.actions.after):execAction()>

    }
    @finally {
        //[self traceOut:[NSString stringWithFormat:@" %d\n", ]];
        NSLog(@"exit  %C line=%d:%d failed=%@ backtracking=%d",
                    [input LA:1], self.line, self.charPositionInLine,
                    (state.failed==YES) ? @"YES" : @"NO", state.backtracking);
        
        
    }
    return;
}
/* $ANTLR end "" */
>>

/** How to generate code for the implicitly-defined lexer grammar rule
 *  that chooses between lexer rules.
 */
tokensRule(ruleName,nakedBlock,args,block,ruleDescriptor) ::= <<
- (void) mTokens
{
    <\n>
}
>>

// S U B R U L E S

/** A (...) subrule with multiple alternatives */
block(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
// : // block
NSInteger alt=;

<@predecision()>

<@postdecision()>
<@prebranch()>
switch (alt) {
    }>
}
<@postbranch()>
>>

/** A rule block with multiple alternatives */
ruleBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
// : //ruleblock
NSInteger alt=;

<@predecision()>

<@postdecision()>
switch (alt) {
    }>
}
>>

ruleBlockSingleAlt(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,description) ::= <<
// : // ruleBlockSingleAlt

<@prealt()>

<@postalt()>
>>

/** A special case of a (...) subrule with a single alternative */
blockSingleAlt(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,description) ::= <<
// : // blockSingleAlt

<@prealt()>

<@postalt()>
>>

/** A (..)+ block with 1 or more alternatives */
positiveClosureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
// : // positiveClosureBlock
NSInteger cnt = 0;

<@preloop()>
do {
    NSInteger alt = ;
    <@predecision()>
    
    <@postdecision()>
    switch (alt) {
        }>
        default :
            if ( cnt >= 1 )
                goto loop;
            
            EarlyExitException *eee =
                [EarlyExitException newException:input decisionNumber:];
            <@earlyExitException()>
            @throw eee;
    }
    cnt++;
} while (YES);
loop: ;
<@postloop()>
>>

positiveClosureBlockSingleAlt ::= positiveClosureBlock

/** A (..)* block with 0 or more alternatives */
closureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<

<@preloop()>
do {
    NSInteger alt=;
    <@predecision()>
    
    <@postdecision()>
    switch (alt) {
        }>
        default :
            goto loop;
    }
} while (YES);
loop: ;
<@postloop()>
>>

closureBlockSingleAlt ::= closureBlock

/** Optional blocks (x)? are translated to (x|) by before code generation
 *  so we can just use the normal block template
 */
optionalBlock ::= block

optionalBlockSingleAlt ::= block

/** A case in a switch that jumps to an alternative given the alternative
 *  number.  A DFA predicts the alternative and then a simple switch
 *  does the jump to the code that actually matches that alternative.
 */
altSwitchCase(altNum, alt) ::= <<
case  : ;
    <@prealt()>
    
    break;<\n>
>>

/** An alternative is just a list of elements; at outermost level */
alt(elements,altNum,description,autoAST,outerAlt,treeLevel,rew) ::= <<
// : // alt
{
<@declarations()>


<@cleanup()>
}
>>

/** What to emit when there is no rewrite.  For auto build
 *  mode, does nothing.
 */
noRewrite(rewriteBlockLevel, treeLevel) ::= ""

// E L E M E N T S

/** Dump the elements one per line */
element(e) ::= << <@prematch()><\n><\n> >>

/** match a token optionally with a label in front */
tokenRef(token,label,elementIndex,terminalOptions) ::= <<