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

📄 cppcodegenerator.java

📁 SRI international 发布的OAA框架软件
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
		// Generate code for each rule in the lexer
		ids = grammar.rules.elements();
		int ruleNum=0;
		while ( ids.hasMoreElements() ) {
			RuleSymbol sym = (RuleSymbol) ids.nextElement();
			// Don't generate the synthetic rules
			if (!sym.getId().equals("mnextToken")) {
				genRule(sym, false, ruleNum++, grammar.getClassName() + "::");
			}
			exitIfError();
		}

		// Generate the semantic predicate map for debugging
		if (grammar.debuggingOutput)
			genSemPredMap(grammar.getClassName() + "::");

		// Generate the bitsets used throughout the lexer
		genBitsets(bitsetsUsed, ((LexerGrammar)grammar).charVocabulary.size(), grammar.getClassName() + "::", false);

		println("");
		if (nameSpace != null)
			nameSpace.emitClosures(currentOutput);

		// Close the lexer output stream
		currentOutput.close();
		currentOutput = null;
	}
	public void genBody(ParserGrammar g) throws IOException {
		// Open the output stream for the parser and set the currentOutput
		outputFile = grammar.getClassName() + ".cpp";
		outputLine = 1;
		currentOutput = antlr_oaa.Tool.openOutputFile(outputFile);
		//SAS: changed for proper text file io

		genAST = grammar.buildAST;

		tabs = 0;

		// Generate the header common to all output files.
		genHeader(outputFile);

		printHeaderAction(preIncludeCpp);

		// Generate header for the parser
		println("#include \"" + grammar.getClassName() + ".hpp\"");
		println("#include \"antlr/NoViableAltException.hpp\"");
		println("#include \"antlr/SemanticException.hpp\"");

		printHeaderAction(postIncludeCpp);

		if (nameSpace != null)
			nameSpace.emitDeclarations(currentOutput);

		// Output the user-defined parser preamble
		printAction(grammar.preambleAction);

		String sup=null;
		if ( grammar.superClass!=null )
			sup = grammar.superClass;
		else {
			sup = grammar.getSuperClass();
			if (sup.lastIndexOf('.') != -1)
				sup = sup.substring(sup.lastIndexOf('.')+1);
			sup = namespaceAntlr + sup;
		}

		// set up an array of all the rule names so the debugger can
		// keep track of them only by number -- less to store in tree...
		if (grammar.debuggingOutput) {
			println("const char* "+grammar.getClassName()+"::_ruleNames[] = {");
			tabs++;

			Enumeration ids = grammar.rules.elements();
			int ruleNum=0;
			while ( ids.hasMoreElements() ) {
				GrammarSymbol sym = (GrammarSymbol) ids.nextElement();
				if ( sym instanceof RuleSymbol)
					println("\""+((RuleSymbol)sym).getId()+"\",");
			}
			println("0");
			tabs--;
			println("};");
		}

		// Generate parser class constructor from TokenBuffer
		print(grammar.getClassName() + "::" + grammar.getClassName());
		println("("+namespaceAntlr+"TokenBuffer& tokenBuf, int k)");
		println(": " + sup + "(tokenBuf,k)");
		println("{");
		tabs++;
		println("setTokenNames(_tokenNames);");
		// if debugging, set up arrays and call the user-overridable
		//   debugging setup method
		if ( grammar.debuggingOutput ) {
			println("setRuleNames(_ruleNames);");
			println("setSemPredNames(_semPredNames);");
			println("setupDebugging();");
		}
		tabs--;
		println("}");
		println("");

		print(grammar.getClassName() + "::" + grammar.getClassName());
		println("("+namespaceAntlr+"TokenBuffer& tokenBuf)");
		println(": " + sup + "(tokenBuf," + grammar.maxk + ")");
		println("{");
		tabs++;
		println("setTokenNames(_tokenNames);");
		// if debugging, set up arrays and call the user-overridable
		//   debugging setup method
		if ( grammar.debuggingOutput ) {
			println("setRuleNames(_ruleNames);");
			println("setSemPredNames(_semPredNames);");
			println("setupDebugging();");
		}
		tabs--;
		println("}");
		println("");

		// Generate parser class constructor from TokenStream
		print(grammar.getClassName() + "::" + grammar.getClassName());
		println("("+namespaceAntlr+"TokenStream& lexer, int k)");
		println(": " + sup + "(lexer,k)");
		println("{");
		tabs++;
		println("setTokenNames(_tokenNames);");
		// if debugging, set up arrays and call the user-overridable
		//   debugging setup method
		if ( grammar.debuggingOutput ) {
			println("setRuleNames(_ruleNames);");
			println("setSemPredNames(_semPredNames);");
			println("setupDebugging(&lexer);");
		}
		tabs--;
		println("}");
		println("");

		print(grammar.getClassName() + "::" + grammar.getClassName());
		println("("+namespaceAntlr+"TokenStream& lexer)");
		println(": " + sup + "(lexer," + grammar.maxk + ")");
		println("{");
		tabs++;
		println("setTokenNames(_tokenNames);");
		// if debugging, set up arrays and call the user-overridable
		//   debugging setup method
		if ( grammar.debuggingOutput ) {
			println("setRuleNames(_ruleNames);");
			println("setSemPredNames(_semPredNames);");
			println("setupDebugging(&lexer);");
		}
		tabs--;
		println("}");
		println("");

		print(grammar.getClassName() + "::" + grammar.getClassName());
		println("(const "+namespaceAntlr+"ParserSharedInputState& state)");
		println(": " + sup + "(state," + grammar.maxk + ")");
		println("{");
		tabs++;
		println("setTokenNames(_tokenNames);");
		// if debugging, set up arrays and call the user-overridable
		//   debugging setup method
		if ( grammar.debuggingOutput ) {
			println("setRuleNames(_ruleNames);");
			println("setSemPredNames(_semPredNames);");
			println("setupDebugging(&lexer);");
		}
		tabs--;
		println("}");
		println("");

		// Generate code for each rule in the grammar
		Enumeration ids = grammar.rules.elements();
		int ruleNum=0;
		while ( ids.hasMoreElements() ) {
			GrammarSymbol sym = (GrammarSymbol) ids.nextElement();
			if ( sym instanceof RuleSymbol) {
				RuleSymbol rs = (RuleSymbol)sym;
				genRule(rs, rs.references.size()==0, ruleNum++, grammar.getClassName() + "::");
			}
			exitIfError();
		}
		if ( usingCustomAST )
		{
//			println("void "+grammar.getClassName()+"::setASTNodeFactory("+labeledElementASTType+" (*factory)() )");
//			println("{");
//			println("}");
//			println("");

			// when we are using a custom ast override Parser::getAST to return the
			// custom AST type
			println(labeledElementASTType+" "+grammar.getClassName()+"::getAST()");
			println("{");
			println("\treturn returnAST;");
			println("}");
			println("");
		}

		// Generate the token names
		genTokenStrings(grammar.getClassName() + "::");

		// Generate the bitsets used throughout the grammar
		genBitsets(bitsetsUsed, grammar.tokenManager.maxTokenType(), grammar.getClassName() + "::", true);

		// Generate the semantic predicate map for debugging
		if (grammar.debuggingOutput)
			genSemPredMap(grammar.getClassName() + "::");

		// Close class definition
		println("");
		println("");
		if (nameSpace != null)
			nameSpace.emitClosures(currentOutput);

		// Close the parser output stream
		currentOutput.close();
		currentOutput = null;
	}
	public void genBody(TreeWalkerGrammar g) throws IOException {
		// Open the output stream for the parser and set the currentOutput
		outputFile = grammar.getClassName() + ".cpp";
		outputLine = 1;
		currentOutput = antlr_oaa.Tool.openOutputFile(outputFile);
		//SAS: changed for proper text file io

		genAST = grammar.buildAST;
		tabs = 0;

		// Generate the header common to all output files.
		genHeader(outputFile);

		printHeaderAction(preIncludeCpp);

		// Generate header for the parser
		println("#include \"" + grammar.getClassName() + ".hpp\"");
		println("#include \"antlr/Token.hpp\"");
		println("#include \"antlr/AST.hpp\"");
		println("#include \"antlr/NoViableAltException.hpp\"");
		println("#include \"antlr/MismatchedTokenException.hpp\"");
		println("#include \"antlr/SemanticException.hpp\"");
		println("#include \"antlr/BitSet.hpp\"");

		printHeaderAction(postIncludeCpp);

		if (nameSpace != null)
			nameSpace.emitDeclarations(currentOutput);

		// Output the user-defined parser premamble
		printAction(grammar.preambleAction);

		// Generate parser class definition
		String sup=null;
		if ( grammar.superClass!=null ) {
			sup = grammar.superClass;
		}
		else {
			sup = grammar.getSuperClass();
			if (sup.lastIndexOf('.') != -1)
				sup = sup.substring(sup.lastIndexOf('.')+1);
			sup = namespaceAntlr + sup;
		}

		// Generate default parser class constructor
		println(grammar.getClassName() + "::" + grammar.getClassName() + "()");
		println("\t: "+namespaceAntlr+"TreeParser() {");
		tabs++;
		println("setTokenNames(_tokenNames);");
		tabs--;
		println("}");
		println("");

		// Generate code for each rule in the grammar
		Enumeration ids = grammar.rules.elements();
		int ruleNum=0;
		String ruleNameInits = "";
		while ( ids.hasMoreElements() ) {
			GrammarSymbol sym = (GrammarSymbol) ids.nextElement();
			if ( sym instanceof RuleSymbol) {
				RuleSymbol rs = (RuleSymbol)sym;
				genRule(rs, rs.references.size()==0, ruleNum++, grammar.getClassName() + "::");
			}
			exitIfError();
		}

		if ( usingCustomAST )
		{
			// when we are using a custom ast override Parser::getAST to return the
			// custom AST type
			println(labeledElementASTType+" "+grammar.getClassName()+"::getAST()");
			println("{");
			println("\treturn returnAST;");
			println("}");
			println("");
		}

		// Generate the token names
		genTokenStrings(grammar.getClassName() + "::");

		// Generate the bitsets used throughout the grammar
		genBitsets(bitsetsUsed, grammar.tokenManager.maxTokenType(), grammar.getClassName() + "::", true);

		// Close class definition
		println("");
		println("");

		if (nameSpace != null)
			nameSpace.emitClosures(currentOutput);

		// Close the parser output stream
		currentOutput.close();
		currentOutput = null;
	}
	/** Generate a series of case statements that implement a BitSet test.
	 * @param p The Bitset for which cases are to be generated
	 */
	protected void genCases(BitSet p) {
		if ( DEBUG_CODE_GENERATOR ) System.out.println("genCases("+p+")");
		int[] elems;

		elems = p.toArray();
		// Wrap cases four-per-line for lexer, one-per-line for parser
		int wrap = 1; //(grammar instanceof LexerGrammar) ? 4 : 1;
		int j=1;
		boolean startOfLine = true;
		for (int i = 0; i < elems.length; i++) {
			if (j==1) {
				print("");
			} else {
				_print("  ");
			}
			_print("case " + getValueString(elems[i]) + ":");

			if (j==wrap) {
				_println("");
				startOfLine = true;
				j=1;
			}
			else {
				j++;
				startOfLine = false;
			}
		}
		if (!startOfLine) {
			_println("");
		}
	}
	/**Generate common code for a block of alternatives; return a postscript
	 * that needs to be generated at the end of the block.  Other routines
	 * may append else-clauses and such for error checking before the postfix
	 * is generated.
	 * If the grammar is a lexer, then generate alternatives in an order where
	 * alternatives requiring deeper lookahead are generated first, and
	 * EOF in the lookahead set reduces the depth of the lookahead.
	 * @param blk The block to generate
	 * @param noTestForSingle If true, then it does not generate a test for a single alternative.
	 */
	public CppBlockFinishingInfo genCommonBlock(
		AlternativeBlock blk,
		boolean noTestForSingle)
	{
		int nIF=0;
		boolean createdLL1Switch = false;
		int closingBracesOfIFSequence = 0;
		CppBlockFinishingInfo finishingInfo = new CppBlockFinishingInfo();
		if ( DEBUG_CODE_GENERATOR ) System.out.println("genCommonBlk("+blk+")");

		// Save the AST generation state, and set it to that of the block
		boolean savegenAST = genAST;
		genAST = genAST && blk.getAutoGen();

		boolean oldsaveTest = saveText;
		saveText = saveText && blk.getAutoGen();

		// Is this block inverted?  If so, generate special-case code
		if (
			blk.not &&
			analyzer.subruleCanBeInverted(blk, grammar instanceof LexerGrammar)
		) {
			Lookahead p = analyzer.look(1, blk);
			// Variable assignment for labeled elements
			if (blk.getLabel() != null && syntacticPredLevel == 0) {
				println(blk.getLabel() + " = " + lt1Value + ";");
			}

			// AST
			genElementAST(blk);

			String astArgs="";
			if (grammar instanceof TreeWalkerGrammar) {
				if( usingCustomAST )
					astArgs="static_cast<"+namespaceAntlr+"RefAST"+">(_t),";
				else
					astArgs="_t,";
			}

			// match the bitset for the alternative
			println("match(" + astArgs + getBitsetName(markBitsetForGen(p.fset)) + ");");

			// tack on tree cursor motion if doing a tree walker
			if (grammar instanceof TreeWalkerGrammar) {
				println("_t = _t->getNextSibling();");
			}
			return finishingInfo;
		}

		// Special handling for single alt
		if (blk.getAlternatives().size() == 1) {
			Alternative alt = blk.getAlternativeAt(0);

⌨️ 快捷键说明

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