1 | #include <iostream> |
---|
2 | #include <fstream> |
---|
3 | |
---|
4 | #include "LexTokenStream.hpp" |
---|
5 | #include "JavaRecognizer.hpp" |
---|
6 | #include "JavaTreeParser.hpp" |
---|
7 | |
---|
8 | ANTLR_USING_NAMESPACE(std) |
---|
9 | ANTLR_USING_NAMESPACE(antlr) |
---|
10 | |
---|
11 | static void parseFile(const string& f); |
---|
12 | static void doTreeAction(const string& f, RefAST t, ASTFactory* factory); |
---|
13 | |
---|
14 | int main(int argc,char* argv[]) |
---|
15 | { |
---|
16 | // Use a try/catch block for parser exceptions |
---|
17 | try { |
---|
18 | // if we have at least one command-line argument |
---|
19 | if ( argc > 1 ) |
---|
20 | { |
---|
21 | cerr << "Parsing..." << endl; |
---|
22 | |
---|
23 | // for each file specified on the command line |
---|
24 | for( int i = 1; i < argc; i++ ) |
---|
25 | { |
---|
26 | cerr << " " << argv[i] << endl; |
---|
27 | parseFile(argv[i]); |
---|
28 | } |
---|
29 | } |
---|
30 | else |
---|
31 | { |
---|
32 | cerr << "Usage: " << argv[0] |
---|
33 | << " <file name(s)>" << endl; |
---|
34 | } |
---|
35 | } |
---|
36 | catch( ANTLRException& e ) |
---|
37 | { |
---|
38 | cerr << "exception: " << e.getMessage() << endl; |
---|
39 | return -1; |
---|
40 | } |
---|
41 | catch( exception& e ) |
---|
42 | { |
---|
43 | cerr << "exception: " << e.what() << endl; |
---|
44 | return -1; |
---|
45 | } |
---|
46 | return 0; |
---|
47 | } |
---|
48 | |
---|
49 | // Here's where we do the real work... |
---|
50 | static void parseFile(const string& f) |
---|
51 | { |
---|
52 | try { |
---|
53 | FILE* fp = fopen(f.c_str(),"r"); |
---|
54 | |
---|
55 | // Create a scanner that reads from the input stream |
---|
56 | LexTokenStream lexer(fp); |
---|
57 | |
---|
58 | // Create a parser that reads from the scanner |
---|
59 | JavaRecognizer parser(lexer); |
---|
60 | |
---|
61 | ASTFactory ast_factory; |
---|
62 | parser.initializeASTFactory(ast_factory); |
---|
63 | parser.setASTFactory(&ast_factory); |
---|
64 | |
---|
65 | // start parsing at the compilationUnit rule |
---|
66 | parser.compilationUnit(); |
---|
67 | |
---|
68 | fclose(fp); |
---|
69 | |
---|
70 | // do something with the tree |
---|
71 | doTreeAction( f, parser.getAST(), &ast_factory ); |
---|
72 | } |
---|
73 | catch (exception& e) { |
---|
74 | cerr << "parser exception: " << e.what() << endl; |
---|
75 | } |
---|
76 | } |
---|
77 | |
---|
78 | static void doTreeAction(const string&, RefAST t, ASTFactory* factory ) |
---|
79 | { |
---|
80 | if ( t==nullAST ) |
---|
81 | return; |
---|
82 | |
---|
83 | JavaTreeParser tparse; |
---|
84 | tparse.initializeASTFactory(*factory); |
---|
85 | tparse.setASTFactory(factory); |
---|
86 | |
---|
87 | try { |
---|
88 | tparse.compilationUnit(t); |
---|
89 | // System.out.println("successful walk of result AST for "+f); |
---|
90 | } |
---|
91 | catch (RecognitionException& e) { |
---|
92 | cerr << e.getMessage() << endl; |
---|
93 | } |
---|
94 | } |
---|
95 | |
---|