⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 buildnfa.g

📁 antlr最新版本V3源代码
💻 G
📖 第 1 页 / 共 2 页
字号:
header {/* [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.*/package org.antlr.tool;import java.util.*;import org.antlr.analysis.*;import org.antlr.misc.*;}/** Build an NFA from a tree representing an ANTLR grammar. */class TreeToNFAConverter extends TreeParser;options {	importVocab = ANTLR;	ASTLabelType = "GrammarAST";}{/** Factory used to create nodes and submachines */protected NFAFactory factory = null;/** Which NFA object are we filling in? */protected NFA nfa = null;/** Which grammar are we converting an NFA for? */protected Grammar grammar = null;protected String currentRuleName = null;protected int outerAltNum = 0;protected int blockLevel = 0;public TreeToNFAConverter(Grammar g, NFA nfa, NFAFactory factory) {	this();	this.grammar = g;	this.nfa = nfa;	this.factory = factory;}protected void init() {    // define all the rule begin/end NFAStates to solve forward reference issues    Collection rules = grammar.getRules();    for (Iterator itr = rules.iterator(); itr.hasNext();) {		Rule r = (Rule) itr.next();        String ruleName = r.name;        NFAState ruleBeginState = factory.newState();        ruleBeginState.setDescription("rule "+ruleName+" start");		ruleBeginState.setEnclosingRuleName(ruleName);        grammar.setRuleStartState(ruleName, ruleBeginState);        NFAState ruleEndState = factory.newState();        ruleEndState.setDescription("rule "+ruleName+" end");        ruleEndState.setAcceptState(true);		ruleEndState.setEnclosingRuleName(ruleName);        grammar.setRuleStopState(ruleName, ruleEndState);    }}protected void addFollowTransition(String ruleName, NFAState following) {     //System.out.println("adding follow link to rule "+ruleName);     // find last link in FOLLOW chain emanating from rule     NFAState end = grammar.getRuleStopState(ruleName);     while ( end.transition(1)!=null ) {         end = (NFAState)end.transition(1).target;     }     if ( end.transition(0)!=null ) {         // already points to a following node         // gotta add another node to keep edges to a max of 2         NFAState n = factory.newState();         Transition e = new Transition(Label.EPSILON, n);         end.addTransition(e);         end = n;     }     Transition followEdge = new Transition(Label.EPSILON, following);     end.addTransition(followEdge);}protected void finish() {    List rules = new LinkedList();    rules.addAll(grammar.getRules());    int numEntryPoints = factory.build_EOFStates(rules);    if ( numEntryPoints==0 ) {        ErrorManager.grammarWarning(ErrorManager.MSG_NO_GRAMMAR_START_RULE,                                   grammar,                                   null,                                   grammar.name);    }}    public void reportError(RecognitionException ex) {		Token token = null;		if ( ex instanceof MismatchedTokenException ) {			token = ((MismatchedTokenException)ex).token;		}		else if ( ex instanceof NoViableAltException ) {			token = ((NoViableAltException)ex).token;		}        ErrorManager.syntaxError(            ErrorManager.MSG_SYNTAX_ERROR,            grammar,            token,            "buildnfa: "+ex.toString(),            ex);    }}grammar    :   {init();}        ( #( LEXER_GRAMMAR grammarSpec )	    | #( PARSER_GRAMMAR grammarSpec )	    | #( TREE_GRAMMAR grammarSpec )	    | #( COMBINED_GRAMMAR grammarSpec )	    )        {finish();}    ;attrScope	:	#( "scope" ID ACTION )	;grammarSpec	:	ID		(cmt:DOC_COMMENT)?        ( #(OPTIONS .) )?        ( #(TOKENS .) )?        (attrScope)*        (AMPERSAND)* // skip actions        rules	;rules    :   ( rule )+    ;rule{    StateCluster g=null;    StateCluster b = null;    String r=null;}    :   #( RULE id:ID {r=#id.getText();}		{currentRuleName = r; factory.currentRuleName = r;}		(modifier)?        (ARG (ARG_ACTION)?)        (RET (ARG_ACTION)?)		( OPTIONS )?		( ruleScopeSpec )?		   (AMPERSAND)*		   {GrammarAST blk = (GrammarAST)_t;}		   b=block           (exceptionGroup)?           EOR           {                if ( blk.setValue!=null ) {                    // if block comes back as a set not BLOCK, make it                    // a single ALT block                    b = factory.build_AlternativeBlockFromSet(b);                }				if ( Character.isLowerCase(r.charAt(0)) ||					 grammar.type==Grammar.LEXER )				{					// attach start node to block for this rule					NFAState start = grammar.getRuleStartState(r);					start.setAssociatedASTNode(#id);					start.addTransition(new Transition(Label.EPSILON, b.left));					// track decision if > 1 alts					if ( grammar.getNumberOfAltsForDecisionNFA(b.left)>1 ) {						b.left.setDescription(grammar.grammarTreeToString(#rule,false));						b.left.setDecisionASTNode(blk);						int d = grammar.assignDecisionNumber( b.left );						grammar.setDecisionNFA( d, b.left );                    	grammar.setDecisionBlockAST(d, blk);					}					// hook to end of rule node					NFAState end = grammar.getRuleStopState(r);					b.right.addTransition(new Transition(Label.EPSILON,end));				}           }         )    ;modifier	:	"protected"	|	"public"	|	"private"	|	"fragment"	;ruleScopeSpec 	:	#( "scope" (ACTION)? ( ID )* ) 	;block returns [StateCluster g = null]{    StateCluster a = null;    List alts = new LinkedList();    this.blockLevel++;    if ( this.blockLevel==1 ) {this.outerAltNum=1;}}    :   {grammar.isValidSet(this,#block) &&		 !currentRuleName.equals(Grammar.ARTIFICIAL_TOKENS_RULENAME)}?		g=set        {this.blockLevel--;}    |	#( BLOCK ( OPTIONS )?           ( a=alternative rewrite             {             alts.add(a);             if ( this.blockLevel==1 ) {this.outerAltNum++;}             }           )+            EOB        )        {g = factory.build_AlternativeBlock(alts);}        {this.blockLevel--;}    ;alternative returns [StateCluster g=null]{    StateCluster e = null;}    :   #( ALT (e=element {g = factory.build_AB(g,e);} )+ )        {        if (g==null) { // if alt was a list of actions or whatever            g = factory.build_Epsilon();        }        else {        	factory.optimizeAlternative(g);        }        }    ;exceptionGroup	:	( exceptionHandler )+ (finallyClause)?	|	finallyClause    ;exceptionHandler    :    #("catch" ARG_ACTION ACTION)    ;finallyClause    :    #("finally" ACTION)    ;rewrite	:	(			{			if ( grammar.getOption("output")==null ) {				ErrorManager.grammarError(ErrorManager.MSG_REWRITE_OR_OP_WITH_NO_OUTPUT_OPTION,										  grammar, #rewrite.token, currentRuleName);			}			}			#( REWRITE (SEMPRED)? (ALT|TEMPLATE|ACTION) )		)*	;element returns [StateCluster g=null]    :   #(ROOT g=element)    |   #(BANG g=element)    |	#(ASSIGN ID g=element)    |	#(PLUS_ASSIGN ID g=element)    |   #(RANGE a:atom b:atom)        {g = factory.build_Range(grammar.getTokenType(#a.getText()),                                 grammar.getTokenType(#b.getText()));}    |   #(CHAR_RANGE c1:CHAR_LITERAL c2:CHAR_LITERAL)        {        if ( grammar.type==Grammar.LEXER ) {        	g = factory.build_CharRange(#c1.getText(), #c2.getText());        }        }    |   g=atom_or_notatom    |   g=ebnf    |   g=tree    |   #( SYNPRED block )    |   ACTION    |   pred:SEMPRED {g = factory.build_SemanticPredicate(#pred);}    |   spred:SYN_SEMPRED {g = factory.build_SemanticPredicate(#spred);}    |   bpred:BACKTRACK_SEMPRED {g = factory.build_SemanticPredicate(#bpred);}    |   gpred:GATED_SEMPRED {g = factory.build_SemanticPredicate(#gpred);}    |   EPSILON {g = factory.build_Epsilon();}    ;ebnf returns [StateCluster g=null]{    StateCluster b = null;    GrammarAST blk = #ebnf;    if ( blk.getType()!=BLOCK ) {    	blk = (GrammarAST)blk.getFirstChild();    }    GrammarAST eob = blk.getLastChild();}    :   {grammar.isValidSet(this,#ebnf)}? g=set    |	b=block        {        // track decision if > 1 alts        if ( grammar.getNumberOfAltsForDecisionNFA(b.left)>1 ) {            b.left.setDescription(grammar.grammarTreeToString(blk,false));            b.left.setDecisionASTNode(blk);            int d = grammar.assignDecisionNumber( b.left );            grammar.setDecisionNFA( d, b.left );            grammar.setDecisionBlockAST(d, blk);        }        g = b;        }    |   #( OPTIONAL b=block )        {        if ( blk.setValue!=null ) {            // if block comes back SET not BLOCK, make it            // a single ALT block            b = factory.build_AlternativeBlockFromSet(b);        }        g = factory.build_Aoptional(b);    	g.left.setDescription(grammar.grammarTreeToString(#ebnf,false));        // there is always at least one alt even if block has just 1 alt        int d = grammar.assignDecisionNumber( g.left );		grammar.setDecisionNFA(d, g.left);        grammar.setDecisionBlockAST(d, blk);        g.left.setDecisionASTNode(#ebnf);    	}    |   #( CLOSURE b=block )        {        if ( blk.setValue!=null ) {            b = factory.build_AlternativeBlockFromSet(b);        }        g = factory.build_Astar(b);		// track the loop back / exit decision point    	b.right.setDescription("()* loopback of "+grammar.grammarTreeToString(#ebnf,false));        int d = grammar.assignDecisionNumber( b.right );		grammar.setDecisionNFA(d, b.right);        grammar.setDecisionBlockAST(d, blk);        b.right.setDecisionASTNode(eob);        // make block entry state also have same decision for interpreting grammar        NFAState altBlockState = (NFAState)g.left.transition(0).target;        altBlockState.setDecisionASTNode(#ebnf);        altBlockState.setDecisionNumber(d);        g.left.setDecisionNumber(d); // this is the bypass decision (2 alts)        g.left.setDecisionASTNode(#ebnf);    	}    |   #( POSITIVE_CLOSURE b=block )

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -