1#set( $symbol_pound = '#' )
2#set( $symbol_dollar = '$' )
3#set( $symbol_escape = '\' )
4package ${package};
5
6import org.antlr.runtime.*;
7import org.antlr.runtime.tree.*;
8import org.antlr.stringtemplate.*;
9
10import java.io.*;
11import ${package}.TParser.a_return;
12
13
14/**
15 * Test driver program for the ANTLR3 Maven Architype demo
16 *
17 * @author Jim Idle (jimi@temporal-wave.com)
18 */
19class Main {
20
21    private static boolean makeDot = false;
22
23    static  TLexer lexer;
24
25    /** Just a simple test driver for the ASP parser
26     * to show how to call it.
27     */
28
29    	public static void main(String[] args)
30        {
31            try
32            {
33                // Create the lexer, which we can keep reusing if we like
34                //
35                lexer = new TLexer();
36
37                if  (args.length > 0)
38                {
39                    int s = 0;
40
41                    if  (args[0].startsWith("-dot"))
42                    {
43                        makeDot = true;
44                        s = 1;
45                    }
46                    // Recursively parse each directory, and each file on the
47                    // command line
48                    //
49                    for (int i=s; i<args.length; i++)
50                    {
51                        parse(new File(args[i]));
52                    }
53                }
54                else
55                {
56                    System.err.println("Usage: java -jar ${artifactId}-${version}-jar-with-dependencies.jar <directory | filename.dmo>");
57                }
58            }
59            catch (Exception ex)
60            {
61                System.err.println("ANTLR demo parser threw exception:");
62                ex.printStackTrace();
63            }
64        }
65
66        public static void parse(File source) throws Exception
67        {
68
69            // Open the supplied file or directory
70            //
71            try
72            {
73
74                // From here, any exceptions are just thrown back up the chain
75                //
76                if (source.isDirectory())
77                {
78                    System.out.println("Directory: " + source.getAbsolutePath());
79                    String files[] = source.list();
80
81                    for (int i=0; i<files.length; i++)
82                    {
83                        parse(new File(source, files[i]));
84                    }
85                }
86
87                // Else find out if it is an ASP.Net file and parse it if it is
88                //
89                else
90                {
91                    // File without paths etc
92                    //
93                    String sourceFile = source.getName();
94
95                    if  (sourceFile.length() > 3)
96                    {
97                        String suffix = sourceFile.substring(sourceFile.length()-4).toLowerCase();
98
99                        // Ensure that this is a DEMO script (or seemingly)
100                        //
101                        if  (suffix.compareTo(".dmo") == 0)
102                        {
103                            parseSource(source.getAbsolutePath());
104                        }
105                    }
106                }
107            }
108            catch (Exception ex)
109            {
110                System.err.println("ANTLR demo parser caught error on file open:");
111                ex.printStackTrace();
112            }
113
114        }
115
116        public static void parseSource(String source) throws Exception
117        {
118            // Parse an ANTLR demo file
119            //
120            try
121            {
122                // First create a file stream using the povided file/path
123                // and tell the lexer that that is the character source.
124                // You can also use text that you have already read of course
125                // by using the string stream.
126                //
127                lexer.setCharStream(new ANTLRFileStream(source, "UTF8"));
128
129                // Using the lexer as the token source, we create a token
130                // stream to be consumed by the parser
131                //
132                CommonTokenStream tokens = new CommonTokenStream(lexer);
133
134                // Now we need an instance of our parser
135                //
136                TParser parser = new TParser(tokens);
137
138                System.out.println("file: " + source);
139
140                // Provide some user feedback
141                //
142                System.out.println("    Lexer Start");
143                long start = System.currentTimeMillis();
144
145                // Force token load and lex (don't do this normally,
146                // it is just for timing the lexer)
147                //
148                tokens.LT(1);
149                long lexerStop = System.currentTimeMillis();
150                System.out.println("      lexed in " + (lexerStop - start) + "ms.");
151
152                // And now we merely invoke the start rule for the parser
153                //
154                System.out.println("    Parser Start");
155                long pStart = System.currentTimeMillis();
156                a_return psrReturn = parser.a();
157                long stop = System.currentTimeMillis();
158                System.out.println("      Parsed in " + (stop - pStart) + "ms.");
159
160                // If we got a valid a tree (the syntactic validity of the source code
161                // was found to be solid), then let's print the tree to show we
162                // did something; our testing public wants to know!
163                // We do something fairly cool here and generate a graphviz/dot
164                // specification for the tree, which will allow the users to visualize
165                // it :-) we only do that if asked via the -dot option though as not
166                // all users will hsve installed the graphviz toolset from
167                // http://www.graphviz.org
168                //
169
170                // Pick up the generic tree
171                //
172                Tree t = (Tree)psrReturn.getTree();
173
174                // NOw walk it with the generic tree walker, which does nothing but
175                // verify the tree really.
176                //
177                try
178                {
179                    if (parser.getNumberOfSyntaxErrors() == 0) {
180                        TTree walker = new TTree(new CommonTreeNodeStream(t));
181                        System.out.println("    AST Walk Start${symbol_escape}n");
182                        pStart = System.currentTimeMillis();
183                        walker.a();
184                        stop = System.currentTimeMillis();
185                        System.out.println("${symbol_escape}n      AST Walked in " + (stop - pStart) + "ms.");
186                     }
187                }
188                catch(Exception w)
189                {
190                    System.out.println("AST walk caused exception.");
191                    w.printStackTrace();
192                }
193
194                if  (makeDot && tokens.size() < 4096)
195                {
196
197                    // Now stringify it if you want to...
198                    //
199                    // System.out.println(t.toStringTree());
200
201                    // Use the ANLTR built in dot generator
202                    //
203                    DOTTreeGenerator gen = new DOTTreeGenerator();
204
205                    // Which we can cause to generate the DOT specification
206                    // with the input file name suffixed with .dot. You can then use
207                    // the graphviz tools or zgrviewer (Java) to view the graphical
208                    // version of the dot file.
209                    //
210                    source = source.substring(0, source.length()-3);
211                    String outputName = source + "dot";
212
213                    System.out.println("    Producing AST dot (graphviz) file");
214
215                    // It produces a jguru string template.
216                    //
217                    StringTemplate st = gen.toDOT(t, new CommonTreeAdaptor());
218
219                    // Create the output file and write the dot spec to it
220                    //
221                    FileWriter outputStream = new FileWriter(outputName);
222                    outputStream.write(st.toString());
223                    outputStream.close();
224
225                    // Invoke dot to generate a .png file
226                    //
227                    System.out.println("    Producing png graphic for tree");
228                    pStart = System.currentTimeMillis();
229                    Process proc = Runtime.getRuntime().exec("dot -Tpng -o" + source + "png " + outputName);
230                    proc.waitFor();
231                    stop = System.currentTimeMillis();
232                    System.out.println("      PNG graphic produced in " + (stop - pStart) + "ms.");
233                }
234            }
235            catch (FileNotFoundException ex)
236            {
237                // The file we tried to parse does not exist
238                //
239                System.err.println("${symbol_escape}n  !!The file " + source + " does not exist!!${symbol_escape}n");
240            }
241            catch (Exception ex)
242            {
243                // Something went wrong in the parser, report this
244                //
245                System.err.println("Parser threw an exception:${symbol_escape}n${symbol_escape}n");
246                ex.printStackTrace();
247            }
248        }
249
250}
251