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

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

There is a newer version: 3.5.3
Show newest version
/*
 [The "BSD license"]
 Copyright (c) 2005-2006 Terence Parr
 Copyright (c) 2007-2008 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;

/** 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, superClass="ANTLR::Runtime::Lexer")  ::= <<
package ;

use Carp;
use English qw( -no_match_vars ) ;
use Readonly;
use Switch;

use ANTLR::Runtime::BaseRecognizer;
use ANTLR::Runtime::DFA;
use ANTLR::Runtime::NoViableAltException;

use Moose;

extends 'ANTLR::Runtime::Lexer';

Readonly my $HIDDEN => ANTLR::Runtime::BaseRecognizer->HIDDEN;
sub HIDDEN { $HIDDEN }

use constant {
     => , }; separator="\n">
};
}>


sub BUILD {
    my ($self, $arg_ref) = @_;

    $self->init_dfas();
}

sub get_grammar_file_name {
    return "";
}






}>

';}; separator="\n">

sub init_dfas {
    my ($self) = @_;

    dfa(::DFA->new({ recognizer => $self }));
    }; separator="\n">

    return;
}

 

no Moose;
__PACKAGE__->meta->make_immutable();
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;
}
>>

actionGate() ::= "$self->state->backtracking==0"

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

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

use English qw( -no_match_vars ) ;
use Readonly;
use Switch;
use Carp;
use ANTLR::Runtime::BitSet;

use Moose;

extends '<@superClassName><@end>';

Readonly my $token_names => [
    "\", "\", "\", "\", 
];

use constant {
 => , }; separator="\n">
};

_in_},
                    words64=it.bits)>

}>
<@members>


sub BUILD {
    my ($self, $arg_ref) = @_;


    $self->state->rule_memo({});<\n>

}
<@end>

sub get_token_names {
    return $token_names;
}

sub get_grammar_file_name {
    return "";
}





}>

 = __PACKAGE__::DFA->new($self);}; separator="\n">
 

no Moose;
__PACKAGE__->meta->make_immutable();
1;
__END__
>>

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={}, filterMode) ::= <<

>>

/** 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 ($self->state->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);
        $exception = undef;
    }<\n>



    $self->traceOut("", );
    
    
    
    if ($exception) {
        croak $exception;
        #$exception->rethrow();
    }
    <@postamble()>
    return ;
}
# $ANTLR end 
>>

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

ruleDeclarations() ::= <<

my $retval = ->new();
$retval->set_start($self->input->LT(1));<\n>

 = ;
}>


my $_start_index = $self->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->set_stop($self->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 = ;
        my $_channel = $self->DEFAULT_TOKEN_CHANNEL;
        
        
        
        
        
        $self->state->type($_type);
        $self->state->channel($_channel);
        <(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,terminalOptions) ::= <<
$