6 import java.lang.reflect.*;
8 import org.eclipse.jdt.core.compiler.IProblem;
9 import org.eclipse.jdt.internal.compiler.ClassFile;
10 import org.eclipse.jdt.internal.compiler.CompilationResult;
11 //import org.eclipse.jdt.internal.compiler.Compiler;
12 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
13 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
14 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
15 import org.eclipse.jdt.internal.compiler.IProblemFactory;
16 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
17 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
18 import org.eclipse.jdt.internal.compiler.env.*;
19 import org.eclipse.jdt.internal.compiler.impl.*;
20 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
22 public class Compiler {
24 private ClassLoader loader = ClassLoader.getSystemClassLoader();
25 private Map loaded = new HashMap();
26 private Writer out = new PrintWriter(System.out);
27 private Preprocessor preprocessor = new Preprocessor(null, null, Collections.EMPTY_LIST);
29 private Source[] sources;
30 private ICompilationUnit[] units;
33 public static void main(String[] args) {
37 public Compiler(String[] files) {
38 sources = new Source[files.length];
39 units = new ICompilationUnit[files.length];
41 for (int i=0; i < files.length; i++) {
42 char[][] n = classname(files[i]);
43 sources[i] = new Source(new File(files[i]), name(n), pack(n));
44 units[i] = sources[i].unit;
47 org.eclipse.jdt.internal.compiler.Compiler jdt =
48 new org.eclipse.jdt.internal.compiler.Compiler(
49 env, policy, settings, results, problems);
54 /** Represents a file to be compiled. */
58 char[] processed = null;
59 byte[] compiled = null;
61 ICompilationUnit unit = new ICompilationUnit() {
62 public char[] getMainTypeName() { return n; }
63 public char[][] getPackageName() { return p; }
64 public char[] getFileName() { return orig.getName().toCharArray(); }
65 public char[] getContents() {
66 if (processed != null) return processed;
69 Reader r = new InputStreamReader(new BufferedInputStream(
70 new FileInputStream(orig)));
71 StringWriter w = new StringWriter();
74 synchronized (preprocessor) {
75 preprocessor.setReader(r);
76 preprocessor.setWriter(w);
77 err = preprocessor.process();
81 System.out.println("Preprocessor Errors, "+err); // FIXME
85 processed = w.toString().toCharArray();
86 } catch (IOException e) {
87 System.out.println("IOException: "+e); // FIXME
95 private Source(File o, char[] n, char[][] p) {
96 orig = o; this.n = n; this.p = p; }
99 // ClassLoader Wrappers ///////////////////////////////////////////////////
101 final static class LoadedNestedType implements IBinaryNestedType {
103 LoadedNestedType(Class c) { this.c = c; }
104 public char[] getName() { return name(c); }
105 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
106 public int getModifiers() { return c.getModifiers(); }
109 final static class LoadedField implements IBinaryField {
113 LoadedField(Field f) {
115 int m = f.getModifiers();
117 c = Constant.NotAConstant;
118 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
120 Class type = f.getType();
121 if (type == Boolean.class) {
122 c = new BooleanConstant(f.getBoolean(null));
123 } else if (type == Byte.class) {
124 c = new ByteConstant(f.getByte(null));
125 } else if (type == Character.class) {
126 c = new CharConstant(f.getChar(null));
127 } else if (type == Double.class) {
128 c = new DoubleConstant(f.getDouble(null));
129 } else if (type == Float.class) {
130 c = new FloatConstant(f.getFloat(null));
131 } else if (type == Integer.class) {
132 c = new IntConstant(f.getInt(null));
133 } else if (type == Long.class) {
134 c = new LongConstant(f.getLong(null));
135 } else if (type == Short.class) {
136 c = new ShortConstant(f.getShort(null));
137 } else if (type == String.class) {
138 c = new StringConstant((String)f.get(null));
140 } catch (IllegalAccessException e) {}
143 public Constant getConstant() { return c; }
144 public char[] getTypeName() { return typeName(f.getType()); }
145 public char[] getName() { return f.getName().toCharArray(); }
146 public int getModifiers() { return f.getModifiers(); }
149 final static class LoadedConstructor implements IBinaryMethod {
150 private Constructor c;
154 LoadedConstructor(Constructor c) {
157 Class[] exs = c.getExceptionTypes();
158 ex = new char[exs.length][];
159 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
161 desc = descriptor(c.getParameterTypes(), null);
163 public int getModifiers() { return c.getModifiers(); }
164 public char[] getSelector() { return c.getName().toCharArray(); }
165 public boolean isConstructor() { return true; }
166 public boolean isClinit() { return false; }
167 public char[][] getArgumentNames() { return null; }
168 public char[][] getExceptionTypeNames() { return ex; }
169 public char[] getMethodDescriptor() { return desc; }
172 final static class LoadedMethod implements IBinaryMethod {
177 LoadedMethod(Method m) {
180 Class[] exs = m.getExceptionTypes();
181 ex = new char[exs.length][];
182 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
184 desc = descriptor(m.getParameterTypes(), m.getReturnType());
186 public int getModifiers() { return m.getModifiers(); }
187 public char[] getSelector() { return m.getName().toCharArray(); }
188 public boolean isConstructor() { return false; }
189 public boolean isClinit() { return false; }
190 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
191 public char[][] getExceptionTypeNames() { return ex; }
192 public char[] getMethodDescriptor() { return desc; }
195 final static class LoadedClass implements IBinaryType {
197 private IBinaryField[] f;
198 private char[][] inf;
199 private IBinaryNestedType[] nested;
200 private IBinaryMethod[] meth = null;
202 LoadedClass(Class c) {
205 Field[] fields = c.getFields();
206 f = new IBinaryField[fields.length];
207 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
209 Class[] interfaces = c.getInterfaces();
210 inf = new char[interfaces.length][];
211 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
213 Class[] classes = c.getClasses();
214 nested = new IBinaryNestedType[classes.length];
215 for (int i=0; i < nested.length; i++)
216 nested[i] = new LoadedNestedType(classes[i]);
218 Constructor[] constructors = c.getConstructors();
219 Method[] methods = c.getDeclaredMethods();
220 if (methods.length + constructors.length > 0) {
221 meth = new IBinaryMethod[methods.length + constructors.length];
223 for (int j=0; j < methods.length; j++)
224 meth[i++] = new LoadedMethod(methods[j]);
225 for (int j=0; j < constructors.length; j++)
226 meth[i++] = new LoadedConstructor(constructors[j]);
231 public char[] getName() { return name(c); }
232 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
233 public char[] getSuperclassName() { return name(c.getSuperclass()); }
234 public IBinaryField[] getFields() { return f; }
235 public char[][] getInterfaceNames() { return inf; }
236 public IBinaryNestedType[] getMemberTypes() { return nested; }
237 public IBinaryMethod[] getMethods() { return meth; }
238 public int getModifiers() { return c.getModifiers(); }
240 public boolean isBinaryType() { return true; }
241 public boolean isClass() { return true; }
242 public boolean isInterface() { return c.isInterface(); }
243 public boolean isAnonymous() { return false; }
244 public boolean isLocal() { return false; } // FIXME
245 public boolean isMember() { return false; } // FIXME
246 public char[] sourceFileName() { return null; }
247 public char[] getFileName() { return null; }
251 // Compiler Parameters ////////////////////////////////////////////////////
253 /** Used by compiler to resolve classes. */
254 final INameEnvironment env = new INameEnvironment() {
255 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
256 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
258 Class c = Class.forName(str(p, '.') + '.' + new String(n));
259 IBinaryType b = (IBinaryType)loaded.get(c);
260 if (b == null) loaded.put(c, b = new LoadedClass(c));
261 return new NameEnvironmentAnswer(b);
262 } catch (ClassNotFoundException e) {}
265 for (int i=0; i < sources.length; i++)
266 if (eq(n, sources[i].n) && eq(p, sources[i].p))
267 return sources[i].compiled == null ?
268 new NameEnvironmentAnswer(sources[i].unit) :
269 new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
270 sources[i].orig.getName().toCharArray(), true));
271 } catch (ClassFormatException e) {
272 System.out.println("Unexpected ClassFormatException"); // FIXME
277 public boolean isPackage(char[][] parent, char[] name) {
278 String parentName = str(parent, '/');
279 for (int i=0; i < sources.length; i++)
280 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
282 loader.getResource(parentName + ".class") == null &&
283 loader.getResource(parentName + '/' + name + ".class") == null;
285 public void cleanup() {}
288 /** Used by compiler to decide what do with problems.. */
289 private final IErrorHandlingPolicy policy =
290 DefaultErrorHandlingPolicies.proceedWithAllProblems();
292 /** Used by compiler for general options. */
293 private final Map settings = new HashMap();
295 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
296 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
297 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
298 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
301 /** Used by compiler for processing compiled classes and their errors. */
302 private final ICompilerRequestor results = new ICompilerRequestor() {
303 public void acceptResult(CompilationResult result) {
304 if (result.hasProblems()) {
305 boolean hasErrors = false;
306 IProblem[] p = result.getProblems();
308 for (int i=0; i < p.length; i++) {
309 if (p[i].isError()) hasErrors = true;
310 out.write(p[i].getOriginatingFileName());
312 out.write(p[i].getSourceLineNumber());
314 out.write(p[i].getMessage());
316 } catch (IOException e) {
317 System.out.println("severe: IOException on out"); // FIXME
320 if (hasErrors) return;
323 ClassFile[] c = result.getClassFiles();
324 for (int i=0; i < c.length; i++) {
326 String name = str(c[i].getCompoundName(), '/') + ".class";
327 OutputStream o = new BufferedOutputStream(
328 new FileOutputStream(new File(name)));
329 o.write(c[i].getBytes());
331 } catch (IOException e) {
332 System.out.println("IOException writing class"); // FIXME
339 /** Problem creater for compiler. */
340 private final IProblemFactory problems = new DefaultProblemFactory();
343 // Helper Functiosn ///////////////////////////////////////////////////////
345 /** Convert source file path into class name block.
346 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
347 private char[][] classname(String name) {
348 String delim = name.indexOf('/') == -1 ? "." : "/";
350 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
351 if (name.startsWith(delim)) name = name.substring(1);
353 StringTokenizer st = new StringTokenizer(name, delim);
354 char[][] n = new char[st.countTokens()][];
355 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
359 /** Convert class name into a String. */
360 private static String str(char[][] name, char delim) {
361 StringBuffer b = new StringBuffer();
362 if (name != null) for (int i=0; i < name.length; i++)
363 if (name[i] != null) { b.append(delim); b.append(name[i]); }
364 if (b.length() > 0) b.deleteCharAt(0);
368 /** Returns the package component of a class name.
369 * Effectively returns char[length - 1][]. */
370 private static char[][] pack(char[][] c) {
371 char[][] p = new char[c.length - 1][];
372 for (int i=0; i < p.length; i++) p[i] = c[i];
376 /** Returns the direct-name component of a class name.
377 * eg. String from java.lang.String */
378 private static char[] name(char[][] c) { return c[c.length - 1]; }
380 /** Returns true of contents of both char arrays are equal. */
381 private static boolean eq(char[][] c1, char[][] c2) {
382 if (c1.length != c2.length) return false;
383 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
387 /** Returns true of contents of both char arrays are equal. */
388 private static boolean eq(char[] c1, char[] c2) {
389 if (c1.length != c2.length) return false;
390 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
394 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
395 private static char[] name(Class c) {
396 return c == null ? null : c.getName().replace('.', '/').toCharArray();
399 /** Returns the type name of a class as per VM Spec 4.3.2. */
400 private static char[] typeName(Class p) {
401 StringBuffer sb = new StringBuffer();
403 return sb.toString().toCharArray();
406 /** Returns the type name of a class as per VM Spec 4.3.2.
407 * eg. int -> I, String -> Ljava/lang/String; */
408 private static void typeName(Class p, StringBuffer sb) {
409 String name = p.getName();
410 switch (name.charAt(0)) {
411 case 'B': case 'C': case 'D': case 'F': case 'I':
412 case 'J': case 'S': case 'Z': case 'V': case '[':
413 sb.append(name); break;
415 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
416 if (name.equals("byte")) { sb.append('B'); break; }
417 case 'c': if (name.equals("char")) { sb.append('C'); break; }
418 case 'd': if (name.equals("double")) { sb.append('D'); break; }
419 case 'f': if (name.equals("float")) { sb.append('F'); break; }
420 case 'i': if (name.equals("int")) { sb.append('I'); break; }
421 case 'l': if (name.equals("long")) { sb.append('J'); break; }
422 case 's': if (name.equals("short")) { sb.append('S'); break; }
423 case 'v': if (name.equals("void")) { sb.append('V'); break; }
425 sb.append('L'); sb.append(name(p)); sb.append(';');
429 /** Returns the descriptor of a method per VM Spec 4.3.3.
430 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
431 private static char[] descriptor(Class[] p, Class r) {
432 StringBuffer sb = new StringBuffer();
434 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
436 if (r != null) typeName(r, sb);
437 return sb.toString().toCharArray();