/* [The "BSD licence"] Copyright (c) 2005-2006 Terence Parr Copyright (c) 2007 Ronald Blaschke 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 Perl5 implements ANTLRCore; /** 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 <@imports> <@end> >> lexer(grammar, name, tokens, scopes, rules, numRules, labelType="Token", filterMode) ::= << package ; use base qw( ANTLR::Runtime::Lexer ); use English qw( -no_match_vars ) ; use Readonly; use Switch; use Carp; use ANTLR::Runtime::DFA; use ANTLR::Runtime::NoViableAltException; use strict; use warnings; sub HIDDEN { return ANTLR::Runtime::BaseRecognizer->HIDDEN; } => ;}; separator="\n"> }> sub new { Readonly my $usage => ' new($input)'; croak $usage if @_ != 2; my ($class, $input) = @_; my $self = $class->SUPER::new($input); return $self; } sub get_grammar_file_name { return ""; } }> = ANTLR::Runtime::DFA->new($self);}; separator="\n"> 1; >> perlTypeInitMap ::= [ "$":"undef", "@":"()", "%":"()", default:"undef" ] /** 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() ::= << public Token nextToken() { while (true) { if ( input.LA(1)==CharStream.EOF ) { return Token.EOF_TOKEN; } token = null; channel = Token.DEFAULT_CHANNEL; tokenStartCharIndex = input.index(); tokenStartCharPositionInLine = input.getCharPositionInLine(); tokenStartLine = input.getLine(); text = null; try { int m = input.mark(); backtracking=1; failed=false; mTokens(); backtracking=0; if ( failed ) { input.rewind(m); input.consume(); } else { emit(); 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, bitsets, inputStreamType, superClass, ASTLabelType="Object", labelType, members) ::= << package ; use base qw ( <@superClassName><@end> ); use English qw( -no_match_vars ) ; use Readonly; use Switch; use Carp; use ANTLR::Runtime::BitSet; use strict; use warnings; Readonly my $token_names => [ "\", "\", "\", "\", ]; => ;<\n>sub { return $; }}; separator="\n"> _in_}, words64=it.bits)> }> <@members> sub new { my ($class, $input) = @_; my $self = $class->SUPER::new($input); $self->rule_memo({});<\n> return $self; } <@end> sub get_token_names { return $token_names; } sub get_grammar_file_name { return ""; } }> = new ANTLR::Runtime::DFA->new($self);}; separator="\n"> 1; >> parser(grammar, name, scopes, tokens, tokenNames, rules, numRules, bitsets, ASTLabelType, superClass="ANTLR::Runtime::Parser", labelType="ANTLR::Runtime::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="ANTLR::Runtime::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 sub _fragment { # $self->traceIn("_fragment", ); eval { }; $self->traceOut("_fragment", ); if ($EVAL_ERROR) { croak $EVAL_ERROR; } } # $ANTLR end >> synpred(name) ::= << public final boolean () { backtracking++; <@start()> int start = input.mark(); try { _fragment(); // can never throw exception } catch (RecognitionException re) { System.err.println("impossible: "+re); } boolean success = !failed; input.rewind(start); <@stop()> backtracking--; 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,finally,memoize) ::= << # $ANTLR start # : sub () { # my ($self) = @_; $self->traceIn("", ); <@preamble()> eval { <(ruleDescriptor.actions.after):execAction()> }; <\n>}> my $exception = $EVAL_ERROR; if (ref $exception && $exception->isa('ANTLR::Runtime::RecognitionException')) { $self->report_error($exception); $self->recover($self->input, $exception); }<\n> $self->traceOut("", ); if ($exception) { croak $exception; } <@postamble()> return ; } # $ANTLR end >> catch(decl,action) ::= << catch () { } >> ruleDeclarations() ::= << retval = new (); retval.start = input.LT(1);<\n> = ; }> int _StartIndex = input.index(); >> ruleScopeSetUp() ::= << _stack.push(new _scope());}; separator="\n"> _stack.push(new _scope());}; separator="\n"> >> ruleScopeCleanUp() ::= << _stack.pop();}; separator="\n"> _stack.pop();}; separator="\n"> >> ruleLabelDefs() ::= << <[ruleDescriptor.tokenLabels,ruleDescriptor.tokenListLabels] :{my $ = undef;}; separator="\n" > <[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels] :{List list_=null;}; separator="\n" > = null;}; separator="\n"> >> lexerRuleLabelDefs() ::= << <[ruleDescriptor.tokenLabels, ruleDescriptor.tokenListLabels, ruleDescriptor.ruleLabels] :{ =null;}; separator="\n" > ;}; separator="\n"> <[ruleDescriptor.tokenListLabels, ruleDescriptor.ruleListLabels, ruleDescriptor.ruleListLabels] :{List list_=null;}; separator="\n" > >> ruleReturnValue() ::= << $ $retval >> ruleCleanUp() ::= << retval.stop = input.LT(-1);<\n> >> memoize() ::= << 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) ::= << # $ANTLR start sub m_ { # my ($self) = @_; traceIn("", ); eval { <\n> my $_type = $; $self->set_type($_type); <(ruleDescriptor.actions.after):execAction()> }; traceOut("", ); if ($EVAL_ERROR) { croak $EVAL_ERROR; } } # $ANTLR end >> /** How to generate code for the implicitly-defined lexer grammar rule * that chooses between lexer rules. */ tokensRule(ruleName,nakedBlock,args,block,ruleDescriptor) ::= << sub m_tokens { my ($self) = @_; <\n> } >> // S U B R U L E S /** A (...) subrule with multiple alternatives */ block(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= << # : my $alt = ; <@predecision()> <@postdecision()> <@prebranch()> switch ($alt) { } <@postbranch()> >> /** A rule block with multiple alternatives */ ruleBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= << # : my $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) ::= << # : my $cnt = 0; <@preloop()> LOOP: while (1) { my $alt = ; <@predecision()> <@postdecision()> switch ($alt) { else { if ( $cnt >= 1 ) { last LOOP } my $eee = ANTLR::Runtime::EarlyExitException->new(, $self->input); <@earlyExitException()> croak $eee; } } ++$cnt; } <@postloop()> >> positiveClosureBlockSingleAlt ::= positiveClosureBlock /** A (..)* block with 1 or more alternatives */ closureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= << # : <@preloop()> LOOP: while (1) { my $alt = ; <@predecision()> <@postdecision()> switch ($alt) { else { last 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()> }<\n> >> /** An alternative is just a list of elements; at outermost level */ alt(elements,altNum,description,autoAST,outerAlt,treeLevel,rew) ::= << # : { <@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() ::= << <@prematch()> <\n> >> /** match a token optionally with a label in front */ tokenRef(token,label,elementIndex,hetero) ::= << $