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

📄 buildnfa.g

📁 ANTLR(ANother Tool for Language Recognition)它是这样的一种工具
💻 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;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.grammarError(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)*           #(BLOCK b=block EOB)           (exceptionGroup)?           EOR           {           /* 11/28/2005: removed to treat Tokens rule like any other           if ( r.equals(Grammar.ARTIFICIAL_TOKENS_RULENAME) ) {                NFAState ruleState = factory.build_ArtificialMatchTokensRuleNFA();                if ( grammar.getNumberOfAltsForDecisionNFA(ruleState)>1 ) {	                ruleState.setDecisionASTNode(#BLOCK); // always track ast node                    int d = grammar.assignDecisionNumber( ruleState );                    grammar.setDecisionNFA( d, ruleState );                    grammar.setDecisionBlockAST(d, #BLOCK);                }                // hook rule start state for Tokens to its manually-created start                NFAState start = grammar.getRuleStartState(r);		        start.addTransition(new Transition(Label.EPSILON, ruleState));           }           else */           {				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(#BLOCK);						int d = grammar.assignDecisionNumber( b.left );						grammar.setDecisionNFA( d, b.left );                    	grammar.setDecisionBlockAST(d, #BLOCK);					}					// 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();}    :   ( OPTIONS )? // ignore		( a=alternative rewrite {alts.add(a);} )+        {        g = factory.build_AlternativeBlock(alts);        }    ;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	:	( exceptionSpec )+    ;exceptionSpec    :   #("exception" ( ARG_ACTION )? ( exceptionHandler )*)    ;exceptionHandler    :    #("catch" ARG_ACTION 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]    :   g=atom    |   #(  n:NOT            (  #( c:CHAR_LITERAL (ast1:ast_suffix)? )	           {	            int ttype=0;     			if ( grammar.type==Grammar.LEXER ) {        			ttype = Grammar.getCharValueFromGrammarCharLiteral(#c.getText());     			}     			else {        			ttype = grammar.getTokenType(#c.getText());        		}                IntSet notAtom = grammar.complement(ttype);                if ( notAtom.isNil() ) {                    ErrorManager.grammarError(ErrorManager.MSG_EMPTY_COMPLEMENT,					  			              grammar,								              #c.token,									          #c.getText());                }	            g=factory.build_Set(notAtom);	           }            |  #( t:TOKEN_REF (ast3:ast_suffix)? )	           {	           int ttype = grammar.getTokenType(t.getText());               IntSet notAtom = grammar.complement(ttype);               if ( notAtom.isNil() ) {                  ErrorManager.grammarError(ErrorManager.MSG_EMPTY_COMPLEMENT,				  			              grammar,							              #t.token,								          #t.getText());               }	           g=factory.build_Set(notAtom);	           }            |  g=set

⌨️ 快捷键说明

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