KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > source > script > ScriptParser


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.java.source.script;
21
22 import com.sun.tools.javac.tree.*;
23 import com.sun.tools.javac.tree.JCTree.*;
24 import com.sun.tools.javac.parser.*;
25 import com.sun.tools.javac.util.*;
26
27 import javax.tools.*;
28
29 import java.io.*;
30 import java.net.URI JavaDoc;
31 import java.net.URISyntaxException JavaDoc;
32 import java.util.logging.*;
33
34 import static com.sun.tools.javac.parser.Token.*;
35
36 public class ScriptParser {
37     protected static final Logger logger = Logger.getLogger("org.netbeans.modules.java.source");
38
39     public void setIn(String JavaDoc name, String JavaDoc s) {
40     log.setSource(name, s);
41     reset();
42         scanner = makeScanner(s);
43         parser = makeParser();
44     }
45     public void setIn(String JavaDoc name, Reader in) {
46     char[] src;
47     try {
48         CharArrayWriter out = new CharArrayWriter();
49         char[] buf = new char[8192];
50         int n;
51         while ((n = in.read(buf)) > 0)
52         out.write(buf, 0, n);
53         out.write(0); // java scanner needs at least one extra end char.
54
src = out.toCharArray();
55     } catch (IOException e) {
56         src = new char[1]; // just the scanner's extra char
57
}
58     log.setSource(name, new String JavaDoc(src, 0, src.length-1));
59     reset();
60     scanner = makeScanner(src, src.length-1);
61         parser = makeParser();
62     }
63     public final JCStatement statement() {
64     return parser.statement();
65     }
66     public final JCExpression expression() {
67     return parser.expression();
68     }
69     public final boolean atEnd() {
70     return scanner.token() == EOF;
71     }
72     public boolean hasErrors() { return log.hasErrors(); }
73     public String JavaDoc getErrors() { return log.getErrors(); }
74     public JCTree statement(String JavaDoc s) {
75         setIn("Script", s);
76     return parser.statement();
77     }
78     public JCTree expression(String JavaDoc s) {
79         setIn("Script", s);
80     return parser.expression();
81     }
82     static public void main(String JavaDoc[] argv) {
83     System.err.println("t="+new ScriptParser().expression("2+2"));
84     }
85
86     public static class ErrorMessage {
87     String JavaDoc msg;
88     int pos;
89     public ErrorMessage(int p, String JavaDoc m) { pos = p; msg = m; }
90     }
91
92     /** allows context to be toyed with before JavaCompiler gets ahold of it */
93     protected Context createContext() {
94         Context ctx = new Context();
95         log = new ScriptLog(ctx);
96         DefaultFileManager.preRegister(ctx);
97         return ctx;
98     }
99     
100     protected ScriptParser() {
101         context = createContext();
102         names = Name.Table.instance(context);
103         make = TreeMaker.instance(context);
104     }
105     
106     protected final Context context;
107     protected ScriptLog log;
108     protected Scanner scanner;
109     protected Parser parser;
110     
111     protected final Name.Table names;
112     protected final TreeMaker make;
113
114     public boolean isToken(Name name) {
115         return scanner.token() == CUSTOM && scanner.name().equals(name);
116     }
117     public Name tokenName(Token token) {
118     return names.fromString(token.name());
119     }
120     public void reset() {
121     log.reset();
122     }
123     protected Scanner makeScanner(String JavaDoc s) {
124         char[] buf = new char[s.length() + 1];
125         System.arraycopy(s.toCharArray(), 0, buf, 0, s.length());
126     return makeScanner(buf, buf.length-1);
127     }
128     private Scanner makeScanner(char[] src, int length) {
129         assert src.length > length; // scanner requires buffer to be larger
130
Scanner.Factory scannerFactory = Scanner.Factory.instance(context);
131     return scannerFactory.newScanner(src, length);
132     }
133     protected Parser makeParser() {
134         Parser.Factory parserFactory = Parser.Factory.instance(context);
135     return parserFactory.newParser(scanner, false, false);
136     }
137
138     static class ScriptLog extends Log {
139     private ErrorMessage[] errors;
140     private int errorListLength;
141     private int maxErrors = 10;
142     private String JavaDoc src = null;
143     private boolean fatalError = false;
144     ScriptLog(Context context) {
145         super(context);
146     }
147     public void reset() { errorListLength = 0; errors=null; }
148     public void prompt() {}
149     public void flush() {}
150     public final void setSource(String JavaDoc name, String JavaDoc src) {
151         this.src = src;
152             try {
153                 useSource(new SimpleJavaFileObject(new URI JavaDoc(name.replace(' ', '_')), JavaFileObject.Kind.SOURCE) {
154                 public CharSequence JavaDoc getCharContent(boolean ignoreEncodingErrors) {
155             return ScriptLog.this.src;
156                 }
157                 });
158             } catch (URISyntaxException JavaDoc ex) {
159                 ex.printStackTrace();
160             }
161     }
162         public final boolean hasErrors() { return fatalError; }
163         public final String JavaDoc getErrors() {
164             if(errorListLength<=0) return null;
165             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
166             if(errorListLength>errors.length) {
167                 sb.append(errorListLength+" errors\n");
168                 errorListLength = errors.length;
169             }
170             for(int i = 0; i<errorListLength; i++) {
171         ErrorMessage e = errors[i];
172         sb.append(source.getFile().getName());
173         sb.append(':');
174         sb.append(source.getLineNumber(e.pos));
175         sb.append(": ");
176                 sb.append(e.msg);
177             }
178             return sb.toString();
179         }
180         public void report(JCDiagnostic diag) {
181         rawError((int)diag.getPosition(), diag.getText());
182         }
183     public void rawError(int pos, String JavaDoc msg) {
184         if(errors==null) errors = new ErrorMessage[maxErrors];
185         if (errorListLength < maxErrors) {
186         StringWriter sw = new StringWriter();
187         PrintWriter writer = new PrintWriter(sw);
188         Log.printLines(writer, msg);
189         writer.flush();
190         errors[errorListLength++] = new ErrorMessage(pos, sw.toString());
191         }
192         fatalError = true;
193     }
194     }
195 }
196
197
Popular Tags