testgnucparser.java
来自「plugin for eclipse」· Java 代码 · 共 108 行
JAVA
108 行
package isis.anp.test;
import isis.anp.common.CToken;
import isis.anp.common.TNode;
import isis.anp.gnuc.GnuCEmitter;
import isis.anp.gnuc.GnuCLexer;
import isis.anp.gnuc.GnuCParser;
import isis.anp.gnuc.GnuCTokenTypes;
import isis.anp.gnuc.GnuCTreeParser;
import java.io.DataInputStream;
import java.io.FileInputStream;
import antlr.ASTFactory;
import antlr.CommonAST;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.debug.misc.ASTFrame;
public class TestGnuCParser
{
public static void main(String[] args)
{
for (int i=0; i<args.length; i++)
{
try
{
String programName = args[i];
DataInputStream dis = null;
if (programName.equals("-")) {
dis = new DataInputStream( System.in );
}
else {
dis = new DataInputStream(new FileInputStream(programName));
}
// create GnuC lexer on the preprocessor output
GnuCLexer lexer = new GnuCLexer ( dis );
lexer.setTokenObjectClass(CToken.class.getName());
lexer.initialize(programName);
// Parse the input expression.
GnuCParser parser = new GnuCParser ( lexer );
// set AST node type to TNode or get nasty cast class errors
parser.setASTNodeClass(TNode.class.getName());
TNode.setTokenVocabulary(GnuCTokenTypes.class.getName());
// invoke parser
try {
parser.translationUnit();
}
catch (RecognitionException e) {
System.err.println("Fatal IO error:\n"+e);
System.exit(1);
}
catch (TokenStreamException e) {
System.err.println("Fatal IO error:\n"+e);
System.exit(1);
}
// Garbage collection hint
System.gc();
System.out.println("AST: -----------------------");
TNode.printTree(parser.getAST());
// run through the treeParser, doesn't do anything
// but verify that the grammar is ok
GnuCTreeParser treeParser = new GnuCTreeParser();
// set AST node type to TNode or get nasty cast class errors
treeParser.setASTNodeClass(TNode.class.getName());
// walk that tree (it doesn't build a new tree --
// it would just be a copy if it did)
treeParser.translationUnit( parser.getAST() );
// Garbage collection hint
System.gc();
System.out.println("Emitter: -----------------------");
GnuCEmitter e = new GnuCEmitter(lexer.getPreprocessorInfoChannel());
// set AST node type to TNode or get nasty cast class errors
e.setASTNodeClass(TNode.class.getName());
// walk that tree
e.translationUnit( parser.getAST() );
// show AST in a swing frame
CommonAST root = (CommonAST)(new ASTFactory().create());
root.setFirstChild(parser.getAST());
ASTFrame frame = new ASTFrame("AST JTree Example", root);
frame.setVisible(true);
// Garbage collection hint
System.gc();
}
catch ( Exception e )
{
System.err.println ( "exception: " + e);
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?