/* [The "BSD licence"] Copyright (c) 2005-2006 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ group Cpp implements ANTLRCore; cppTypeInitMap ::= [ "int":"0", "long":"0", "float":"0.0", "double":"0.0", "bool":"false", "byte":"0", "short":"0", "char":"0", default:"0" // anything other than an atomic type ] // What we generate lexer/parser/treeparser, used a suffix in a few places generatedType() ::= << LexerParserTreeParser >> leadIn(type) ::= << /** \file * * This file was generated by ANTLR version * * - From the grammar source file : * - On : * - for the lexer : <\n> * - for the parser : <\n> * - for the tree parser : <\n> * * Edit at your own peril. */ >> standardHeaders() ::= << #include \.h> #warning "No profiling support.." #warning "No tree parsing yet..." >> /** 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, profile, backtracking, synpreds, memoize, numRules, fileName, ANTLRVersion, generatedTimestamp, trace, scopes, superClass) ::= << <@includes> #include "" <@end> // Header action start ======================================================== // Header action end ======================================================== >> parserHeaderFile() ::= << >> treeParserHeaderFile() ::= << >> lexerHeaderFile() ::= << template\ class : public antlr3::Lexer\ { // carry over general types typedef typename StreamType::position_type position_type; typedef typename StreamType::char_type char_type; typedef antlr3::tokenid_type tokenid_type; typedef antlr3::channel_type channel_type; typedef antlr3::decision_type decision_type; // exception shorthands typedef antlr3::MismatchException\ MismatchException; typedef antlr3::MismatchedRangeException\ MismatchedRangeException; typedef antlr3::MismatchedSetException\ MismatchedSetException; typedef antlr3::EarlyExitException\ EarlyExitException; typedef antlr3::NoViableAltException\ NoViableAltException; // @TODO backtracking ruleMemo = new HashMap[+1];<\n> public: = ;}; separator="\n"> }> (StreamType* input) : antlr3::Lexer\(input) { } // syn preds }> // cyclic dfa's dfa = new DFA(this);}; separator="\n"> // dfa tables.. }; // class <\n> >> headerFile( 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 ) ::= << #ifndef __H #define __H <@includes> <@end> #endif // __H<\n> >> lexer(grammar, name, tokens, scopes, rules, numRules, labelType="Token", filterMode) ::= << >> filteringNextToken() ::= << /** 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. */ public Token nextToken() { while (true) { if ( input.LA(1)==CharStream.EOF ) { return Token.EOF_TOKEN; } this->token = 0; tokenStartCharIndex = getCharIndex(); try { int m = input.mark(); backtracking=1; failed=false; mTokens(); backtracking=0; if ( failed ) { input.rewind(m); input.consume(); } else { return token; } } catch (RecognitionException re) { // shouldn't happen in backtracking mode, but... reportError(re); recover(re); } } } public void memoize(IntStream input, int ruleIndex, int ruleStartIndex) { if ( backtracking > 1 ) super.memoize(input, ruleIndex, ruleStartIndex); } public boolean alreadyParsedRule(IntStream input, int ruleIndex) { if ( backtracking > 1 ) return super.alreadyParsedRule(input, ruleIndex); return false; } >> filteringActionGate() ::= "backtracking == 1" /** How to generate a parser */ genericParser( grammar, name, scopes, tokens, tokenNames, rules, numRules, cyclicDFAs, bitsets, inputStreamType, superClass, ASTLabelType="Object", labelType, members ) ::= << // genericParser class : public <@superClassName><@end> { public: static const char* tokenNames[] = { "\", "\", "\", "\", }; =;}; separator="\n"> }> <@members> (StreamType* input) : \(input) { ruleMemo = new HashMap[+1];<\n> } <@end> //@TODO public String[] getTokenNames() { return tokenNames; } //@TODO public String getGrammarFileName() { return ""; } }> dfa = new DFA(this);}; separator="\n"> _in_}, words64=it.bits)> }; >> parser( grammar, name, scopes, tokens, tokenNames, rules, numRules, bitsets, ASTLabelType, superClass="Parser", labelType="Token", 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, labelType={}, ASTLabelType="Object", 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 public void _fragment() throws RecognitionException { System.out.println("enter "+input.LT(1)+" failed="+failed+" backtracking="+backtracking); try { } finally { System.out.println("exit "+input.LT(1)+" failed="+failed+" backtracking="+backtracking); } } // $ANTLR end >> synpred(name) ::= << public boolean () { this->backtracking++; <@start()> int start = input.mark(); try { _fragment(); // can never throw exception } catch (RecognitionException re) { System.err.println("impossible: "+re); } boolean success = ! this->failed; input.rewind(start); <@stop()> this->backtracking--; this->failed = false; return success; }<\n> >> lexerSynpred(name) ::= << >> ruleMemoization(name) ::= << if ( backtracking > 0 && alreadyParsedRule(input, ) ) return ; >> /** How to test for failure and return from rule */ checkRuleBacktrackFailure() ::= << if (failed) return ; >> /** This rule has failed, exit indicating failure during backtrack */ ruleBacktrackFailure() ::= << if (backtracking > 0) { failed = 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,memoize) ::= << // $ANTLR start // : public () throw(antlr3::BaseRecognitionException) { antlr3::Tracer trace(this,""); System.out.println("enter "+input.LT(1)+" failed="+failed+" backtracking="+backtracking); <@preamble()> try { } <\n>}> catch (RecognitionException re) { reportError(re); recover(input,re); }<\n> finally { System.out.println("exit "+input.LT(1)+" failed="+failed+" backtracking="+backtracking); <(ruleDescriptor.actions.finally):execAction()> } <@postamble()> return ; } // $ANTLR end >> catch(decl,action) ::= << catch () { } >> ruleDeclarations() ::= << _stack.push(new _scope());}; separator="\n"> _stack.push(new _scope());}; separator="\n"> retval = new (); retval.start = input.LT(1);<\n> = ; }> int _StartIndex = input.index(); >> ruleLabelDefs() ::= << <[ruleDescriptor.tokenLabels,ruleDescriptor.tokenListLabels] :{ =null;}; separator="\n" > <[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels] :{List list_=null;}; separator="\n" > <[ruleDescriptor.ruleLabels,ruleDescriptor.ruleListLabels] :ruleLabelDef(label=it); separator="\n" > <[ruleDescriptor.allRuleRefsInAltsWithRewrites,ruleDescriptor.allTokenRefsInAltsWithRewrites] :{List list_=new ArrayList();}; separator="\n" > >> ruleReturnValue() ::= << retval >> ruleCleanUp() ::= << _stack.pop();}; separator="\n"> _stack.pop();}; separator="\n"> retval.stop = input.LT(-1);<\n> if ( backtracking > 0 ) { memoize(input, , _StartIndex); } >> /** How to generate a rule in the lexer; naked blocks are used for * fragment rules. */ lexerRule(ruleName,nakedBlock,ruleDescriptor,block,memoize) ::= << void m() throw(antlr3::BaseRecognitionException) { antlr3::Tracer trace(this,""); antlr3::CountScope nestingTracker(this->ruleNestingLevel); StreamType& input(this->getInput()); <\n> tokenid_type type = ; channel_type channel = antlr3::Token::DEFAULT_CHANNEL; position_type start(input.getPosition()); token == 0 && this->ruleNestingLevel == 1 ) { TokenType *tt = TokenBuilder::build(type,start,input,channel); std::cout \<\< (*tt) \<\< std::endl; this->emit(tt); }<\n> })> } >> /** How to generate code for the implicitly-defined lexer grammar rule * that chooses between lexer rules. */ tokensRule(ruleName,nakedBlock,args,block,ruleDescriptor) ::= << void mTokens() throw(antlr3::BaseRecognitionException) { StreamType& input(this->getInput()); <\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 : decision_type alt=; <@predecision()> <@postdecision()> <@prebranch()> switch (alt) { } <@postbranch()> >> /** A rule block with multiple alternatives */ ruleBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= << // ruleBlock : decision_type 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) ::= << // : <@prealt()> <@postalt()> >> /** A (..)+ block with 0 or more alternatives */ positiveClosureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= << // positiveClosureBlock : decision_type cnt=0; <@preloop()> do { decision_type alt=; <@predecision()> <@postdecision()> switch (alt) { default : if ( cnt >= 1 ) goto loop; EarlyExitException eee( input.getPosition(), ); <@earlyExitException()> throw eee; } cnt++; } while (true); loop: ; <@postloop()> >> positiveClosureBlockSingleAlt ::= positiveClosureBlock /** A (..)* block with 1 or more alternatives */ closureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= << // closureBlock : <@preloop()> do { decision_type alt=; <@predecision()> <@postdecision()> switch (alt) { default : goto loop; } } while (true); 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() ::= << case : <@prealt()> break;<\n> >> /** An alternative is just a list of elements; at outermost level */ alt(elements,altNum,description,autoAST,outerAlt) ::= << // alt : { <@declarations()> <@cleanup()> } >> // E L E M E N T S /** Dump the elements one per line */ element() ::= << // element : <@prematch()> <\n> >> /** match a token optionally with a label in front */ tokenRef(token,label,elementIndex) ::= << // tokenRef