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

org.antlr.codegen.templates.Cpp.Cpp.stg Maven / Gradle / Ivy

There is a newer version: 3.5.3
Show newest version
/*
 [The "BSD license"]
 Copyright (c) 2005-2009 Gokulakannan Somasundaram,
 
 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.
*/

/*
 * This code generating template and the associated Cpp runtime was produced by:
 * Gokulakannan Somasundaram ( heavy lifting from C Run-time by Jim Idle )
 */
cTypeInitMap ::= [
	"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"    	    : "false",   // Booleans     start out being Antlr C for false
	"byte"		    : "0",              // Bytes        start out being 0
	"short"		    : "0",              // Shorts       start out being 0
	"char"		    : "0"              // Chars        start out being 0
]

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.
 *
 * C++ language generator and runtime by Gokulakannan Somasundaram ( heavy lifting from C Run-time by Jim Idle )
 *
 *
>>

/** 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
            ) ::=
<<

*/
// [The "BSD license"]
// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
//
// 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.



/* =============================================================================
 * 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.
 */
#include    ".hpp"

#include \


// Include delegator definition header files
//
.hpp" }; separator="\n">



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







/** 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
 */



/* End of code
 * =============================================================================
 */

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

beginNamespace(actions) ::= <%
	
	namespace  {
	
%>

endNamespace(actions) ::= <%
	
	}
	
%>


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
        ) ::=
<<


 * The parser  has the callable functions (rules) shown below,


 * The lexer  has the callable functions (rules) shown below,


 * The tree parser  has the callable functions (rules) shown below,

 * which will invoke the code for the associated rule in the source grammar
 * assuming that the input stream is pointing to a token/text stream that could begin
 * this rule.
 *
 * For instance if you call the first (topmost) rule in a parser grammar, you will
 * get the results of a full parse, but calling a rule half way through the grammar will
 * allow you to pass part of a full token stream to the parser, such as for syntax checking
 * in editors and so on.
 *
 */
// [The "BSD license"]
// Copyright (c) 2005-2009 Gokulakannan Somasundaram. 
//
// 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.

#ifndef	__H
#define __H

/* =============================================================================
 * Standard antlr3 C++ runtime definitions
 */
#include \

/* End of standard antlr 3 runtime definitions
 * =============================================================================
 */




// Include delegate definition header files
//
.hpp"}; separator="\n">






#ifdef	WIN32
// Disable: Unreferenced parameter,							- Rules with parameters that are not used
//          constant conditional,							- ANTLR realizes that a prediction is always true (synpred usually)
//          initialized but unused variable					- tree rewrite variables declared but not needed
//          Unreferenced local variable						- lexer rule declares but does not always use _type
//          potentially unitialized variable used			- retval always returned from a rule
//			unreferenced local function has been removed	- susually getTokenNames or freeScope, they can go without warnigns
//
// These are only really displayed at warning level /W4 but that is the code ideal I am aiming at
// and the codegen must generate some of these warnings by necessity, apart from 4100, which is
// usually generated when a parser rule is given a parameter that it does not use. Mostly though
// this is a matter of orthogonality hence I disable that one.
//
#pragma warning( disable : 4100 )
#pragma warning( disable : 4101 )
#pragma warning( disable : 4127 )
#pragma warning( disable : 4189 )
#pragma warning( disable : 4505 )
#pragma warning( disable : 4701 )
#endif


/* ========================
 * BACKTRACKING IS ENABLED
 * ========================
 */





// Include delegator definition classes
//
; }; separator="\n">



typedef Traits ImplTraits;

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

class Tokens
{
public:
	/** Symbolic definitions of all the tokens that the  will work with.
	 *
	 * Antlr will define EOF, but we can't use that as it it is too common in
	 * in C header files and that would be confusing. There is no way to filter this out at the moment
	 * so we just undef it here for now. That isn't the value we get back from C recognizers
	 * anyway. We are looking for ANTLR_TOKEN_EOF.
	 */
	enum Tokens 
	{
		EOF_TOKEN = ImplTraits::CommonTokenType::TOKEN_EOF
		 =  }; separator="\n">
	};

};

/** Context tracking structure for 
 */
class  : public , public Tokens
{
public:
	typedef ImplTraits ImplTraits;
	typedef  ComponentType;
	typedef ComponentType::StreamType StreamType;
	typedef  BaseType;
	typedef ImplTraits::RecognizerSharedStateType\ RecognizerSharedStateType;
	typedef StreamType InputType;

	static const bool IsFiltered = true;

	static const bool IsFiltered = false;

	
	}>
	}>
	
private:	

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


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


    
}; separator="\n\n">

    
}>
    <@members>
    <@end>

public:
    (InputType* instream* }>);
    (InputType* instream, RecognizerSharedStateType* state* }>);
    
    void init(InputType* instream * }> );

    



    void  memoize(ANTLR_MARKER  ruleIndex, ANTLR_MARKER  ruleParseStart);
    bool  alreadyParsedRule(ANTLR_MARKER	ruleIndex);
    
    
      m( );}; separator="\n">
       msynpred( antlr3::ClassForwarder\<  > );
    void m_fragment ();}; separator="\n">


    }>
       (); }; separator="\n">
       msynpred( antlr3::ClassForwarder\<  > );
    void m_fragment ();}; separator="\n">

    // Delegated rules
 ();}; separator="\n">


    const char *    getGrammarFileName();
    void            reset();
    ~();

};

// Function protoypes for the constructor functions that external translation units
// such as delegators and delegates may wish to call.
//

extern ANTLR_UINT8*   TokenNames[];



/* End of token definitions for 
 * =============================================================================
 */



#endif

/* END - Note:Keep extra line feed to satisfy UNIX systems */

>>

grammarType() ::= <%

parser


lexer


tree parser

%>

componentType() ::= <<

ImplTraits::ParserType


ImplTraits::LexerType


ImplTraits::TreeParserType

>>

componentBaseType() ::= <%

ImplTraits::BaseParserType


ImplTraits::BaseLexerType


ImplTraits::BaseTreeParserType

%>

streamType() ::= <<

ImplTraits::ParserType::StreamType


ImplTraits::LexerType::StreamType


ImplTraits::TreeParserType::StreamType

>>


mainName() ::= <%









%>

headerReturnScope(ruleDescriptor) ::= ""

headerReturnType(ruleDescriptor) ::= <%


 void

 


 

%>

// Produce the lexer output
//
lexer(  grammar,
	name,
        tokens,
        scopes,
        rules,
        numRules,
        filterMode,
        superClass,
        labelType="ImplTraits::CommonTokenType*") ::= <<

using namespace antlr3;





/* Override the normal MEMOIZE and HAVEALREADYPARSED macros as this is a filtering
 * lexer. In filter mode, the memoizing and backtracking are gated at BACKTRACKING > 1 rather
 * than just BACKTRACKING. In some cases this might generate code akin to:
 *   if (BACKTRACKING) if (BACKTRACKING > 1) memoize.
 */
void	::memoize(ANTLR_MARKER  ruleIndex, ANTLR_MARKER  ruleParseStart)
{
	BaseType* base = this;
	if ( this->get_backtracking()>1 ) 
		base->memoize( ruleIndex, ruleParseStart );

}

bool	::alreadyParsedRule(ANTLR_MARKER	ruleIndex)
{
	BaseType* base = this;
	if ( this->get_backtracking() > 1 )
		return base->haveParsedRule(ruleIndex);
	return false;
}



/* =========================================================================
 * Lexer matching rules end.
 * =========================================================================
 */

}>



::~()
{

	RuleMemoType* rulememo = this->getRuleMemo();
	if(rulememo != NULL)
	{
		delete rulememo;
		this->setRuleMemo(NULL);
	}


	// Free the lexers that we delegated to
	// functions to. NULL the state so we only free it once.
	//
	->set_lexstate(NULL);
         delete m_; }; separator="\n">

}

void
::reset()
{
    this->get_rec()->reset();
}

/** \brief Name of the grammar file that generated this code
 */
static const char fileName[] = "";

/** \brief Return the name of the grammar file that generated this code.
 */
const char* ::getGrammarFileName()
{
	return fileName;
}

/** \brief Create a new lexer called 
 *
 * \param[in]    instream Pointer to an initialized input stream
 * \return
 *     - Success p initialized for the lex start
 *     - Fail NULL
 */
::(StreamType* instream* }>)
:ImplTraits::BaseLexerType(ANTLR_SIZE_HINT, instream, NULL)
{
	// See if we can create a new lexer with the standard constructor
	//
	this->init(instream }>);
}

/** \brief Create a new lexer called 
 *
 * \param[in]    instream Pointer to an initialized input stream
 * \param[state] state Previously created shared recognizer stat
 * \return
 *     - Success p initialized for the lex start
 *     - Fail NULL
 */
::(StreamType* instream, RecognizerSharedStateType* state* }>)
:ImplTraits::BaseLexerType(ANTLR_SIZE_HINT, instream, state)
{
	this->init(instream } >);
}

void ::init(StreamType* instream* } >)
{
    /* -------------------------------------------------------------------
     * Memory for basic structure is allocated, now to fill in
     * in base ANTLR3 structures. We initialize the function pointers
     * for the standard ANTLR3 lexer function set, but upon return
     * from here, the programmer may set the pointers to provide custom
     * implementations of each function.
     *
     * We don't use the macros defined in .h here so you can get a sense
     * of what goes where.
     */



    // Create a LIST for recording rule memos.
    //
    this->setRuleMemo( new IntTrie(15) );	/* 16 bit depth is enough for 32768 rules! */




	// Initialize the lexers that we are going to delegate some
	// functions to.
	//
	 = new (instream, this->get_lexstate(), this}>);}; separator="\n">


	// Install the pointers back to lexers that will delegate us to perform certain functions
	// for them.
	//
	 = ;}; separator="\n">

}



/* =========================================================================
 * DFA tables for the lexer
 */
 
/* =========================================================================
 * End of DFA tables for the lexer
 */


/* =========================================================================
 * Functions to match the lexer grammar defined tokens from the input stream
 */



/* =========================================================================
 * Lexer matching rules end.
 * =========================================================================
 */


/* =========================================================================
 * Lexer syntactic predicates
 */
}>
/* =========================================================================
 * Lexer syntactic predicates end.
 * =========================================================================
 */


/* End of Lexer code
 * ================================================
 * ================================================
 */
 


>>


filteringNextToken() ::= <<
ImplTraits::CommonTokenType*
ImplTraits::TokenSourceType::nextToken()
{
    LexerType*   lexer;
    typename LexerType::RecognizerSharedStateType* state;

    lexer   = this->get_super();
    state	= lexer->get_lexstate();

    /* Get rid of any previous token (token factory takes care of
     * any deallocation when this token is finally used up.
     */
    state->set_token_present( false );
    state->set_error( false );	    /* Start out without an exception	*/
    state->set_failedflag(false);

    /* Record the start of the token in our input stream.
     */
    state->set_tokenStartCharIndex( lexer->index();
    state->set_tokenStartCharPositionInLine( lexer->getCharPositionInLine() );
    state->set_tokenStartLine( lexer->getLine() );
    state->set_text("");

    /* Now call the matching rules and see if we can generate a new token
     */
    for	(;;)
    {
		if (lexer->LA(1) == ANTLR_CHARSTREAM_EOF)
		{
			/* Reached the end of the stream, nothing more to do.
			 */
			CommonTokenType&    teof = m_eofToken;

			teof.set_startIndex(lexer->getCharIndex());
			teof.set_stopIndex(lexer->getCharIndex());
			teof.setLine(lexer->getLine());
			return  &teof;
		}

		state->set_token_present(false);
		state->set_error(false);	    /* Start out without an exception	*/

		{
			ANTLR_MARKER   m;

			m	= this->get_istream()->mark();
			state->set_backtracking(1);				/* No exceptions */
			state->set_failedflag(false);

			/* Call the generated lexer, see if it can get a new token together.
			 */
			lexer->mTokens();
    			state->set_backtracking(0);

    		

			if(state->get_failed())
			{
				lexer->rewind(m);
				lexer->consume(); 
			}
			else
			{
				lexer->emit();					/* Assemble the token and emit it to the stream */
				TokenType& tok = state->get_token();
				return &tok;
			}
		}
    }
}
>>

actionGate() ::= "this->get_backtracking()==0"

filteringActionGate() ::= "this->get_backtracking()==1"

/** How to generate a parser */
genericParser(  grammar, name, scopes, tokens, tokenNames, rules, numRules,
                bitsets, inputStreamType, superClass,
                labelType, members,	rewriteElementType,
                filterMode, ASTLabelType="ImplTraits::TreeType*") ::= <<

using namespace antlr3;

/** \brief Table of all token names in symbolic order, mainly used for
 *         error reporting.
 */
ANTLR_UINT8* TokenNames[+4]
     = {
        (ANTLR_UINT8*) "\",       /* String to print to indicate an invalid token */
        (ANTLR_UINT8*) "\",
        (ANTLR_UINT8*) "\",
        (ANTLR_UINT8*) "\",
        }; separator=",\n">
       };


    <@members>

    <@end>

/** \brief Name of the grammar file that generated this code
 */
static const char fileName[] = "";

/** \brief Return the name of the grammar file that generated this code.
 */
const char* ::getGrammarFileName()
{
	return fileName;
}
/** \brief Create a new  parser and return a context for it.
 *
 * \param[in] instream Pointer to an input stream interface.
 *
 * \return Pointer to new parser context upon success.
 */
::( StreamType* instream* }>)

{
	// See if we can create a new parser with the standard constructor
	//
	this->init(instream}>);
}

/** \brief Create a new  parser and return a context for it.
 *
 * \param[in] instream Pointer to an input stream interface.
 *
 * \return Pointer to new parser context upon success.
 */
::( StreamType* instream, RecognizerSharedStateType* state* }>)

{
	this->init(instream }>);
}

void ::init(StreamType* instream* }>)
{
    


    /* Create a LIST for recording rule memos.
     */
     typedef RecognizerSharedStateType::RuleMemoType RuleMemoType;
     this->setRuleMemo( new RuleMemoType(15) );	/* 16 bit depth is enough for 32768 rules! */<\n>



	// Initialize the lexers that we are going to delegate some
	// functions to.
	//
	 = new (instream, this->get_psrstate(), this}>);}; separator="\n">
	
        
     	// Install the pointers back to lexers that will delegate us to perform certain functions
     	// for them.
     	//
     		 = ;}; separator="\n">
	
	/* Install the token table
	*/
	this->get_psrstate()->set_tokenNames( TokenNames );

	<@debugStuff()>

}

void
::reset()
{
    this->get_rec()->reset();
}

/** Free the parser resources
 */
::~()
 {
    <@cleanup>
    <@end>

	// Free the parsers that we delegated to
	// functions to.NULL the state so we only free it once.
	//
	->set_psrstate( NULL );
         delete m_;}; separator="\n">



	if(this->getRuleMemo() != NULL)
	{
		delete this->getRuleMemo();
		this->setRuleMemo(NULL);
	}


}

/** Return token names used by this 
 *
 * The returned pointer is used as an index into the token names table (using the token
 * number as the index).
 *
 * \return Pointer to first char * in the table.
 */
static ANTLR_UINT8**	getTokenNames()
{
        return TokenNames;
}

    

/* Declare the bitsets
 */
_in_},
                    words64=it.bits, traits={ImplTraits} )>}>




/* =========================================================================
 * DFA tables for the parser
 */
 
/* =========================================================================
 * End of DFA tables for the parser
 */


/* ==============================================
 * Parsing rules
 */


	// Delegated methods that appear to be a part of this
	// parser
	//
 ::()
    {
        return m_->(}; separator=", ">);
    \}}; separator="\n">


/* End of parsing rules
 * ==============================================
 */

/* ==============================================
 * Syntactic predicates
 */
}>
/* End of syntactic predicates
 * ==============================================
 */

>>

constructorInitializerType(rec_state) ::=<<

    :ImplTraits::BaseParserType(ANTLR_SIZE_HINT, instream, )


    :ImplTraits::BaseTreeParserType(ANTLR_SIZE_HINT, instream, )

>>

parser(	grammar,
		name,
		scopes,
		tokens,
		tokenNames,
		rules,
		numRules,
		bitsets,
		ASTLabelType,
		superClass="Parser",
		labelType="ImplTraits::CommonTokenType*",
		members={}
		) ::= <<



>>

/** 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="ImplTraits::TreeType*",
			superClass="TreeParser",
			members={}
			) ::= <<



>>

/** 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 
void ::m_fragment(  )
{
	
	

    ANTLR_PRINTF("enter  %d failed = %d, backtracking = %d\\n", this->LT(1),failed,this->get_backtracking() );
    
    ANTLR_PRINTF("exit  %d, failed = %d, backtracking = %d\\n", this->LT(1),failed,this->get_backtracking());


    


goto ruleEx; /* Prevent compiler warnings */
ruleEx: ;
}
// $ANTLR end 
>>

synpred(predname) ::= <<

bool ::msynpred( antlr3::ClassForwarder\<  >  )
{
    ANTLR_MARKER   start;
    bool  success;
    
    this->inc_backtracking();
    <@start()>
    start	= this->mark();
    this->m_fragment();	    // can never throw exception
    success	= !( this->get_failedflag() );
    this->rewind(start);
    <@stop()>
    this->dec_backtracking();
    this->set_failedflag(false);
    return success;
}<\n>
>>

lexerSynpred(predname) ::= <<

>>

ruleMemoization(rname) ::= <<

if ( (this->get_backtracking()>0) && (this->haveParsedRule()) )
{


	retval.start = 0;<\n>


    <(ruleDescriptor.actions.after):execAfter()>
    

    <\n>

    return ;
}

>>

/** How to test for failure and return from rule */
checkRuleBacktrackFailure() ::= <<
if  (this->hasException())
{
    goto ruleEx;
}

if (this->hasFailed())
{
    
    <@debugClean()>
    return ;
}

>>

/** This rule has failed, exit indicating failure during backtrack */
ruleBacktrackFailure() ::= <<

if (this->get_backtracking()>0)
{
    this->set_failedflag( true );
    
    return ;
}

>>

/** How to generate code for a rule.  This includes any return type
 *  data aggregates required for multiple return values.
 */
rule(ruleName,ruleDescriptor,block,emptyRule,description,exceptions,finally,memoize) ::= <<
/**
 * $ANTLR start 
 * :
 */

::()
{
    ANTLR_PRINTF("enter  %s failed=%d, backtracking=%d\n", this->LT(1), this->get_backtracking() );
    
    
    
    
    
    
    
    
    
    	try {
     
    
        try {
    
    
    <@preamble()>
    {
        
    }
    
   

    <(ruleDescriptor.actions.after):execAfter()>
    <\n>}>

    
    	if (this->hasException())
        {
            this->preporterror();
            this->precover();
            <@setErrorReturnValue()>
        }
        
        else
        {
            <(ruleDescriptor.actions.after):execAfter()>
        }<\n>
        
	
	    } 
        
    


    ANTLR_PRINTF("exit  %d failed=%s backtracking=%s\n", this->LT(1), failed, this->get_backtracking() );
    

    

    
    <@postamble()>
    return ;
}
/* $ANTLR end  */
>>

finalCode(finalBlock) ::= <<
{
    
}

>>

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

ruleDeclarations() ::= <<


 retval(this);<\n>


    ImplTraits::RuleReturnValueType _antlr_rule_exit(this);
  

 ;
}>



ANTLR_MARKER _StartIndex;

>>

ruleInitializations() ::= <<
/* Initialize rule variables
 */


retval. = ; }>

 = ; }>



_StartIndex = this->index();<\n>

_stack.push(Scope()); }; separator="\n">
_stack.push(Scope()); }; separator="\n">
>>

ruleLabelDefs() ::= <<
<[ruleDescriptor.tokenLabels,ruleDescriptor.tokenListLabels,
  ruleDescriptor.wildcardTreeLabels,ruleDescriptor.wildcardTreeListLabels]
    :{it |  = NULL;}; separator="\n"
>
<[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels,ruleDescriptor.wildcardTreeListLabels]
    :{it |ImplTraits::TokenPtrsListType list_;}; separator="\n"
>

>>

ruleLabelInitializations() ::= <<


retval.call_start_placeholder();


>>

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

lexerRuleLabelInit() ::= <<
<[ruleDescriptor.tokenListLabels,
  ruleDescriptor.ruleListLabels,
  ruleDescriptor.ruleListLabels]
    :{it |list_ = new ImplTraits::IntTrieType(31);}; separator="\n"
>
>>

lexerRuleLabelFree() ::= <<
<[ruleDescriptor.tokenLabels,
  ruleDescriptor.tokenListLabels,
  ruleDescriptor.ruleLabels]
    :{it | = NULL;}; separator="\n"
>
<[ruleDescriptor.tokenListLabels,
  ruleDescriptor.ruleListLabels,
  ruleDescriptor.ruleListLabels]
    :{it | delete list_;}; separator="\n"
>
>>

ruleReturnValue() ::= <%





retval



%>

memoize() ::= <<


if ( this->get_backtracking() > 0 ) { this->memoize(, _StartIndex); }


>>

ruleCleanUp() ::= <<

// This is where rules clean up and exit
//
goto ruleEx; /* Prevent compiler warnings */
ruleEx: ;



retval.call_stop_placeholder();<\n>



>>

scopeClean() ::= <<
_stack.pop(); }; separator="\n">
_stack.pop(); }; separator="\n">

>>
/** How to generate a rule in the lexer; naked blocks are used for
 *  fragment rules, which do not produce tokens.
 */
lexerRule(ruleName,nakedBlock,ruleDescriptor,block,memoize) ::= <<
//   Comes from: 
/** \brief Lexer rule generated by ANTLR3
 *
 * $ANTLR start 
 *
 * Looks to match the characters the constitute the token 
 * from the attached input stream.
 *
 *
 * \remark
 *  - lexer->error == true if an exception was thrown.
 */
void ::m()
{
    ANTLR_UINT32	_type;
    
    
    
    
    std::cout \<\< "enter  '" \<\< (char)this->LA(1)
              \<\< "' line=" \<\< this->getLine() \<\< ":" \<\< this->getCharPositionInLine()
              \<\< " failed=" \<\< this->get_failedflag() \<\< " backtracking=" \<\< this->get_backtracking() \<\< std::endl;
    


    
    
    

    <\n>

    
    
    _type	    = ;

    

    
	this->get_lexstate()->set_type(_type);

    
    std::cout \<\< "exit  '" \<\< (char)this->LA(1)
              \<\< "' line=" \<\< this->getLine() \<\< ":" \<\< this->getCharPositionInLine()
              \<\< " failed=" \<\< this->get_failedflag() \<\< " backtracking=" \<\< this->get_backtracking() \<\< std::endl;
    
    
    
    <(ruleDescriptor.actions.after):execAfter()>
    
}
// $ANTLR end 
>>

/** How to generate code for the implicitly-defined lexer grammar rule
 *  that chooses between lexer rules.
 */
tokensRule(ruleName,nakedBlock,args,block,ruleDescriptor) ::= <<
/** This is the entry point in to the lexer from an object that
 *  wants to generate the next token, such as a pCOMMON_TOKEN_STREAM
 */
void
::mTokens()
{
    <\n>

    goto ruleTokensEx; /* Prevent compiler warnings */
ruleTokensEx: ;
}
>>

// S U B R U L E S

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

// :
{
    int alt=;
    
    <@predecision()>
    
    <@postdecision()>
    <@prebranch()>
    switch (alt)
    {
	}>
    }
    <@postbranch()>
}
>>

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

    ANTLR_UINT32 alt;

    alt=;

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

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

<@prealt()>

<@postalt()>
>>

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

<@prealt()>

<@postalt()>
>>

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

    for (;;)
    {
        int alt=;
	<@predecision()>
	
	<@postdecision()>
	switch (alt)
	{
	    }>
	    default:

		if ( cnt >= 1 )
		{
		    goto loop;
		}
		
		
		<@earlyExitException()>
		goto ruleEx;
	}
	cnt++;
    }
    loop: ;	/* Jump to here if this rule does not match */
    <@postloop()>
}
>>

earlyExitEx() ::= <<
/* mismatchedSetEx()
 */
new ANTLR_Exception\< ImplTraits, EARLY_EXIT_EXCEPTION, StreamType>( this->get_rec(), "" );
<\n>
>>
positiveClosureBlockSingleAlt ::= positiveClosureBlock

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

// :


<@preloop()>
for (;;)
{
    int alt=;
    <@predecision()>
    
    <@postdecision()>
    switch (alt)
    {
	}>
	default:
	    goto loop;	/* break out of the loop */
	    break;
    }
}
loop: ; /* Jump out to here if this rule does not match */
<@postloop()>
>>

closureBlockSingleAlt ::= closureBlock

/** Optional blocks (x)? are translated to (x|) by antlr 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) ::= <<
// :
{
    <@declarations()>
    <@initializations()>
    
    
    <@cleanup()>
}
>>

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

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

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