initial ibex compiler frontend
[org.ibex.tool.git] / src / java / org / ibex / tool / Compiler.java
1 package org.ibex.tool;
2
3 import java.util.*;
4 import java.io.*;
5
6 import java.lang.reflect.*;
7
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.IBinaryField;
19 import org.eclipse.jdt.internal.compiler.env.IBinaryMethod;
20 import org.eclipse.jdt.internal.compiler.env.IBinaryNestedType;
21 import org.eclipse.jdt.internal.compiler.env.IBinaryType;
22 import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
23 import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
24 import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
25 import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
26 import org.eclipse.jdt.internal.compiler.impl.Constant;
27 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
28
29 public class Compiler {
30
31     private ClassLoader loader = ClassLoader.getSystemClassLoader();
32     private Map loaded = new HashMap();
33     private Writer out = new PrintWriter(System.out);
34     private Preprocessor preprocessor = new Preprocessor(null, null, Collections.EMPTY_LIST);
35
36     private Source[] sources;
37     private ICompilationUnit[] units;
38
39
40     public static void main(String[] args) {
41         new Compiler(args);
42     }
43
44     public Compiler(String[] files) {
45         sources = new Source[files.length];
46         units = new ICompilationUnit[files.length];
47
48         for (int i=0; i < files.length; i++) {
49             char[][] n = classname(files[i]);
50             sources[i] = new Source(new File(files[i]), name(n), pack(n));
51             units[i] = sources[i].unit;
52         }
53
54         org.eclipse.jdt.internal.compiler.Compiler jdt =
55             new org.eclipse.jdt.internal.compiler.Compiler(
56                 env, policy, settings, results, problems);
57         jdt.compile(units);
58     }
59
60
61     // Compiler Parameters ////////////////////////////////////////////////////
62
63     final static class LoadedNestedType implements IBinaryNestedType {
64         private Class c;
65         LoadedNestedType(Class c) { this.c = c; }
66         public char[] getName() { return name(c); }
67         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
68         public int getModifiers() { return c.getModifiers(); }
69     }
70
71     final static class LoadedField implements IBinaryField {
72         private Field f;
73         LoadedField(Field f) { this.f = f; }
74         public Constant getConstant() { return Constant.NotAConstant; }// FIXME
75         public char[] getTypeName() { return typeName(f.getType()); }
76         public char[] getName() { return f.getName().toCharArray(); }
77         public int getModifiers() { return f.getModifiers(); }
78     }
79
80     private static char[] typeName(Class p) {
81         StringBuffer sb = new StringBuffer();
82         typeName(p, sb);
83         return sb.toString().toCharArray();
84     }
85     private static void typeName(Class p, StringBuffer sb) {
86         String name = p.getName();
87         switch (name.charAt(0)) {
88             case 'B': case 'C': case 'D': case 'F': case 'I':
89             case 'J': case 'S': case 'Z': case 'V': case '[':
90                 sb.append(name); break;
91
92             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
93                       if (name.equals("byte"))    { sb.append('B'); break; }
94             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
95             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
96             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
97             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
98             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
99             case 's': if (name.equals("short"))   { sb.append('S'); break; }
100             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
101             default:
102                 sb.append('L'); sb.append(name(p)); sb.append(';');
103         }
104     }
105     private static char[] descriptor(Class[] p, Class r) {
106         StringBuffer sb = new StringBuffer();
107         sb.append('(');
108         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
109         sb.append(')');
110         if (r != null) typeName(r, sb);
111         return sb.toString().toCharArray();
112     }
113
114     final static class LoadedConstructor implements IBinaryMethod {
115         private Constructor c;
116         private char[][] ex;
117         private char[] desc;
118
119         LoadedConstructor(Constructor c) {
120             this.c = c;
121
122             Class[] exs = c.getExceptionTypes();
123             ex = new char[exs.length][];
124             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
125
126             desc = descriptor(c.getParameterTypes(), null);
127         }
128         public int getModifiers() { return c.getModifiers(); }
129         public char[] getSelector() { return c.getName().toCharArray(); }
130         public boolean isConstructor() { return true; }
131         public boolean isClinit() { return false; }
132         public char[][] getArgumentNames() { return null; }
133         public char[][] getExceptionTypeNames() { return ex; }
134         public char[] getMethodDescriptor() { return desc; }
135     }
136
137     final static class LoadedMethod implements IBinaryMethod {
138         private Method m;
139         private char[][] ex;
140         private char[] desc;
141
142         LoadedMethod(Method m) {
143             this.m = m;
144
145             Class[] exs = m.getExceptionTypes();
146             ex = new char[exs.length][];
147             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
148
149             desc = descriptor(m.getParameterTypes(), m.getReturnType());
150         }
151         public int getModifiers() { return m.getModifiers(); }
152         public char[] getSelector() { return m.getName().toCharArray(); }
153         public boolean isConstructor() { return false; }
154         public boolean isClinit() { return false; }
155         public char[][] getArgumentNames() { return null; } // FIXME: does this do anything cool?
156         public char[][] getExceptionTypeNames() { return ex; }
157         public char[] getMethodDescriptor() { return desc; }
158     }
159
160     final static class LoadedClass implements IBinaryType {
161         private Class c;
162         private IBinaryField[] f;
163         private char[][] inf;
164         private IBinaryNestedType[] nested;
165         private IBinaryMethod[] meth = null;
166
167         LoadedClass(Class c) {
168             this.c = c;
169
170             Field[] fields = c.getFields();
171             f = new IBinaryField[fields.length];
172             for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
173
174             Class[] interfaces = c.getInterfaces();
175             inf = new char[interfaces.length][];
176             for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
177
178             Class[] classes = c.getClasses();
179             nested = new IBinaryNestedType[classes.length];
180             for (int i=0; i < nested.length; i++)
181                 nested[i] = new LoadedNestedType(classes[i]);
182
183             Constructor[] constructors = c.getConstructors();
184             Method[] methods = c.getDeclaredMethods();
185             if (methods.length + constructors.length > 0) {
186                 meth = new IBinaryMethod[methods.length + constructors.length];
187                 int i=0;
188                 for (int j=0; j < methods.length; j++)
189                     meth[i++] = new LoadedMethod(methods[j]);
190                 for (int j=0; j < constructors.length; j++)
191                     meth[i++] = new LoadedConstructor(constructors[j]);
192             }
193
194         }
195
196         public char[] getName() { return name(c); }
197         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
198         public char[] getSuperclassName() { return name(c.getSuperclass()); }
199         public IBinaryField[] getFields() { return f; }
200         public char[][] getInterfaceNames() { return inf; }
201         public IBinaryNestedType[] getMemberTypes() { return nested; }
202         public IBinaryMethod[] getMethods() { return meth; }
203         public int getModifiers() { return c.getModifiers(); }
204
205         public boolean isBinaryType() { return true; }
206         public boolean isClass() { return true; }
207         public boolean isInterface() { return c.isInterface(); }
208         public boolean isAnonymous() { return false; }
209         public boolean isLocal() { return false; } // FIXME
210         public boolean isMember() { return false; } // FIXME
211         public char[] sourceFileName() { return null; }
212         public char[] getFileName() { return null; }
213     }
214
215
216     private final INameEnvironment env = new INameEnvironment() {
217         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
218         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
219             try {
220                 Class c = Class.forName(str(p, '.') + '.' + new String(n));
221                 IBinaryType b = (IBinaryType)loaded.get(c);
222                 if (b == null) loaded.put(c, b = new LoadedClass(c));
223                 return new NameEnvironmentAnswer(b);
224             } catch (ClassNotFoundException e) {}
225
226             try {
227                 for (int i=0; i < sources.length; i++)
228                     if (eq(n, sources[i].n) && eq(p, sources[i].p))
229                         return sources[i].compiled == null ?
230                                new NameEnvironmentAnswer(sources[i].unit) :
231                                new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
232                                     sources[i].orig.getName().toCharArray(), true));
233             } catch (ClassFormatException e) {
234                 System.out.println("FIXME unexpected ClassFormatException");
235                 e.printStackTrace();
236             }
237             return null;
238         }
239         public boolean isPackage(char[][] parent, char[] name) {
240             String parentName = str(parent, '/');
241             for (int i=0; i < sources.length; i++)
242                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
243             return
244                 loader.getResource(parentName + ".class") == null &&
245                 loader.getResource(parentName + '/' + name + ".class") == null;
246         }
247         public void cleanup() {}
248     };
249
250     private final IErrorHandlingPolicy policy =
251         DefaultErrorHandlingPolicies.proceedWithAllProblems();
252
253     private final Map settings = new HashMap();
254     {
255         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
256         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
257         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
258         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
259     };
260
261     private final ICompilerRequestor results = new ICompilerRequestor() {
262         public void acceptResult(CompilationResult result) {
263             if (result.hasProblems()) {
264                 boolean hasErrors = false;
265                 IProblem[] p = result.getProblems();
266                 try {
267                     for (int i=0; i < p.length; i++) {
268                         if (p[i].isError()) hasErrors = true;
269                         out.write(p[i].getOriginatingFileName());
270                         out.write(':');
271                         out.write(p[i].getSourceLineNumber());
272                         out.write(':');
273                         out.write(p[i].getMessage());
274                     }
275                 } catch (IOException e) {
276                     System.out.println("FIXME severe: IOException on out");
277                     e.printStackTrace();
278                 }
279                 if (hasErrors) return;
280             }
281
282             ClassFile[] c = result.getClassFiles();
283             for (int i=0; i < c.length; i++) {
284                 try {
285                     String name = str(c[i].getCompoundName(), '/') + ".class";
286                     OutputStream o = new BufferedOutputStream(
287                         new FileOutputStream(new File(name)));
288                     o.write(c[i].getBytes());
289                     o.close();
290                 } catch (IOException e) {
291                     System.out.println("FIXME: IOException writing class");
292                     e.printStackTrace();
293                 }
294             }
295         }
296     };
297
298     private final IProblemFactory problems = new DefaultProblemFactory();
299
300     private final class Source {
301         char[] n; char[][] p;
302         File orig;
303         char[] processed = null;
304         byte[] compiled = null;
305
306         ICompilationUnit unit = new ICompilationUnit() {
307             public char[] getMainTypeName() { return n; }
308             public char[][] getPackageName() { return p; }
309             public char[] getFileName() { return orig.getName().toCharArray(); }
310             public char[] getContents() {
311                 if (processed != null) return processed;
312
313                 try {
314                     Reader r = new InputStreamReader(new BufferedInputStream(
315                                new FileInputStream(orig)));
316                     StringWriter w = new StringWriter();
317                     Vector err;
318
319                     synchronized (preprocessor) {
320                         preprocessor.setReader(r);
321                         preprocessor.setWriter(w);
322                         err = preprocessor.process();
323                     }
324
325                     if (err.size() > 0) {
326                         System.out.println("Preprocessor Errors, "+err); // FIXME
327                         return null;
328                     }
329
330                     processed  = w.toString().toCharArray();
331                 } catch (IOException e) {
332                     System.out.println("FIXME: IOException: "+e); // FIXME
333                     return null;
334                 }
335
336                 return processed;
337             }
338         };
339
340         private Source(File o, char[] n, char[][] p) {
341             orig = o; this.n = n; this.p = p;  }
342     }
343
344     // Helper Functiosn ///////////////////////////////////////////////////////
345
346     /** Convert source file path into class name. */
347     private char[][] classname(String name) {
348         String delim = name.indexOf('/') == -1 ? "." : "/";
349         name = name.trim();
350         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
351         if (name.startsWith(delim)) name = name.substring(1);
352
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();
356         return n;
357     }
358
359     private static String str(char[][] name, char delim) {
360         StringBuffer b = new StringBuffer();
361         if (name != null) for (int i=0; i < name.length; i++)
362             if (name[i] != null) { b.append(delim); b.append(name[i]); }
363         if (b.length() > 0) b.deleteCharAt(0);
364         return b.toString();
365     }
366
367     private static char[][] pack(char[][] c) {
368         char[][] p = new char[c.length - 1][];
369         for (int i=0; i < p.length; i++) p[i] = c[i];
370         return p;
371     }
372
373     private static char[] name(char[][] c) { return c[c.length - 1]; }
374
375     private static boolean eq(char[][] c1, char[][] c2) {
376         if (c1.length != c2.length) return false;
377         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
378         return true;
379     }
380
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 (c1[i] != c2[i]) return false;
384         return true;
385     }
386
387     private static char[] name(Class c) {
388         return c == null ? null : c.getName().replace('.', '/').toCharArray();
389     }
390 }