correctly output preprocessor errors
[org.ibex.tool.git] / src / java / org / ibex / tool / Preprocessor.java
1 // You may modify, copy, and redistribute this code under the terms of
2 // the GNU Library Public License version 2.1, with the exception of
3 // the portion of clause 6a after the semicolon (aka the "obnoxious
4 // relink clause").
5
6 package org.ibex.tool;
7
8 //import gnu.regexp.*;
9 import java.util.*;
10 import java.io.*;
11
12 /**
13  *   A VERY crude, inefficient Java preprocessor
14  *
15  *   //#define FOO bar baz       -- replace all instances of token FOO with "bar baz"
16  *   //#replace foo/bar baz/bop  -- DUPLICATE everything between here and //#end,
17  *                                  replacing foo with bar and baz with bop in the *second* copy
18  *   //#switch(EXPR)             -- switch on strings
19  *       case "case1":
20  *   //#end
21  *
22  *   //#ifdef FOO                -- includes contents if FOO passed as define to preprocessor
23  *       [code]
24  *   //#else
25  *       [code run if !FOO]
26  *   //#endif
27  *
28  *   Replacements are done on a token basis.  Tokens are defined as a
29  *   sequence of characters which all belong to a single class.  The
30  *   two character classes are:
31  *
32  *     - [a-zA-Z0-9_]
33  *     - all other non-whitespace characters
34  *   
35  *   Preprocessor makes use of several optional system properties:
36  *
37  *    - ibex.tool.preprocessor.define
38  *    - ibex.tool.preprocessor.inputdir
39  *    - ibex.tool.preprocessor.outputdir
40  *
41  *   @author adam@ibex.org, crawshaw@ibex.org
42  */
43 public class Preprocessor {
44
45     public static String replaceAll(String source, String regexp, String replaceWith) {
46         return source.replaceAll(regexp, replaceWith);
47         /*
48         try {
49             RE re = new RE(regexp, 0, RESyntax.RE_SYNTAX_PERL5);
50             return (String)re.substituteAll(source, replaceWith);
51         } catch (Exception e) {
52             e.printStackTrace();
53             return null;
54         }
55         */
56     }
57
58     public static void main(String[] args) throws Exception {
59         List defs = new ArrayList();
60
61         String define = System.getProperty("ibex.tool.preprocessor.define");
62         if (define != null) {
63             StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
64             while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
65         }
66
67         String inputdir = System.getProperty("ibex.tool.preprocessor.inputdir");
68         if (inputdir == null) inputdir = "src/";
69
70         String outputdir = System.getProperty("ibex.tool.preprocessor.outputdir");
71         if (outputdir == null) outputdir = "build/java/";
72
73         if (args.length == 0) {
74             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
75             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
76             
77             // process stdin to stdout
78             Preprocessor cc = new Preprocessor(br, bw, defs);
79             Vector err = cc.process();
80             bw.flush();
81             
82             // handle errors
83             boolean errors = false;
84             for (int i=0; i < err.size(); i++) {
85                 if (err.get(i) instanceof Error) errors = true; System.err.println(err.get(i)); }
86             if (errors) throw new Exception();
87         } else {
88             for(int i=0; i<args.length; i++) {
89                 if (!args[i].endsWith(".java")) continue;
90                 File source = new File(args[i]);
91                 File target = new File(replaceAll(args[i], inputdir, outputdir));
92                 if (target.exists() && target.lastModified() > source.lastModified()) continue;
93                 System.err.println("preprocessing " + args[i]);
94                 new File(target.getParent()).mkdirs();
95                 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
96                 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target)));
97                 Preprocessor cc   = new Preprocessor(br, bw, defs);
98                 Vector err = cc.process();
99                 bw.flush();
100                 boolean errors = false;
101                 for (int j=0; j < err.size(); j++) {
102                     if (err.get(j) instanceof Error) errors = true; System.err.println(err.get(j)); }
103                 if (errors) System.exit(-1);
104             }
105         }
106     }
107
108     private Reader r;
109     private Writer w;
110     private LineNumberReader in;
111     private PrintWriter out;
112
113     private Hashtable replace = new Hashtable();
114     private Hashtable repeatreplace = null;
115     private Vector sinceLastRepeat = null;
116     private Vector err = new Vector();
117     private List defs;
118
119     private int enumSwitch = 0; // number appended to variable used in switch implementation
120
121    
122     public Preprocessor(Reader reader, Writer writer, List d) {
123         setReader(reader);
124         setWriter(writer);
125         defs = d;
126     }
127
128     public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
129     public Reader getReader() { return r; }
130
131     public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
132     public Writer getWriter() { return w; }
133
134
135     /** process data from reader, write to writer, return vector of errors */
136     public Vector process() throws IOException {
137         err.clear();
138
139         String s = null;
140 PROCESS:
141         while((s = in.readLine()) != null) {
142             if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
143             String trimmed = s.trim();
144
145             if (trimmed.startsWith("//#define ")) {
146                 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
147                     err.add(new Error("#define badly formed, ignored")); continue PROCESS;
148                 }
149                 int keyStart = indexOfNotWS(trimmed, 9);
150                 if (keyStart == -1) {
151                     err.add(new Error("#define requires KEY")); continue PROCESS;
152                 }
153                 int keyEnd = indexOfWS(trimmed, keyStart);
154
155                 int macroStart = trimmed.indexOf('(');
156                 int macroEnd = trimmed.indexOf(')');
157                 if (macroStart > keyEnd) {
158                     // no macro is defined, just make sure something dumb like KEYNA)ME hasn't been done
159                     if (macroEnd < keyEnd) { err.add(new Error("#define key contains invalid char: ')'")); continue PROCESS; }
160                     macroStart = macroEnd = -1;
161                 }
162
163                 if (macroStart == 0) {
164                     err.add(new Error("#define macro requires name")); continue PROCESS;
165                 } else if (macroStart > 0) {
166                     if (macroStart > macroEnd) { err.add(new Error("#define macro badly formed")); continue PROCESS; }
167                     if (macroStart+1 == macroEnd) { err.add(new Error("#define macro requires property name")); continue PROCESS; }
168
169                     JSFunctionMacro fm = new JSFunctionMacro();
170                     String key = trimmed.substring(keyStart, macroStart);
171                     String unbound = trimmed.substring(macroStart +1, macroEnd);
172                     int unboundDiv = unbound.indexOf(',');
173                     if (unboundDiv == -1) {
174                         fm.unbound1 = unbound;
175                     } else {
176                         fm.unbound1 = unbound.substring(0, unboundDiv);
177                         fm.unbound2 = unbound.substring(unboundDiv +1);
178                         if (fm.unbound1.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
179                         if (fm.unbound2.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
180                     }
181                     fm.expression = trimmed.substring(keyEnd).trim();
182                     replace.put(key, fm);
183                 } else {
184                     String key = trimmed.substring(keyStart, keyEnd);
185                     String val = trimmed.substring(keyEnd).trim();
186                     replace.put(key, val);
187                 }
188                 out.print("\n"); // preserve line numbers
189                 
190             } else if (trimmed.startsWith("//#repeat ")) {
191                 trimmed = trimmed.substring(9);
192                 while(trimmed.charAt(trimmed.length() - 1) == '\\') {
193                     String s2 = in.readLine().trim();
194                     if (s2.startsWith("//")) s2 = s2.substring(2).trim();
195                     trimmed = trimmed.substring(0, trimmed.length() - 1) + " " + s2;
196                     out.print("\n");  // preserve line numbers
197                 }
198                 StringTokenizer st = new StringTokenizer(trimmed, " ");
199                 repeatreplace = (Hashtable)replace.clone();
200                 while (st.hasMoreTokens()) {
201                     String tok = st.nextToken().trim();
202                     String key = tok.substring(0, tok.indexOf('/'));
203                     String val = tok.substring(tok.indexOf('/') + 1);
204                     repeatreplace.put(key, val);
205                 }
206                 sinceLastRepeat = new Vector();
207                 out.print("\n"); // preserve line numbers
208
209             } else if (trimmed.startsWith("//#end")) {
210                 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
211                 Hashtable save = replace;
212                 replace = repeatreplace;
213                 out.print("\n");
214                 for(int i=0; i<sinceLastRepeat.size() - 1; i++) out.print(processLine((String)sinceLastRepeat.elementAt(i), true));
215                 sinceLastRepeat = null;
216                 replace = save;
217             } else if (trimmed.startsWith("//#ifdef")) {
218                 String expr = trimmed.substring(8).trim().toUpperCase();
219                 out.println(trimmed);
220                 boolean useCode = defs.contains(expr);
221                 for (trimmed = in.readLine().trim(); !trimmed.startsWith("//#endif"); trimmed = in.readLine().trim()) {
222                     if (trimmed.startsWith("//#else")) useCode = !useCode;
223                     else if (!useCode) out.print("// ");
224                     out.print(processLine(trimmed, false));
225                 }
226                 out.println("//#endif "+expr);
227
228             } else if (trimmed.startsWith("//#switch")) {
229                 int expStart = trimmed.indexOf('(') +1;
230                 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
231                 int expEnd = trimmed.lastIndexOf(')');
232                 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
233                 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
234                 String expr = trimmed.substring(expStart, expEnd);
235
236                 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+");  ");
237                 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
238
239                 Hashtable[] byLength = new Hashtable[255];
240                 String key = null;
241                 String Default = null;
242                 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
243                     if (trimmed.startsWith("default:")) {
244                         Default = processLine(trimmed.substring(8), false);
245                         continue;
246                     }
247                     if (trimmed.startsWith("case ")) {
248                         // find key
249                         int strStart = trimmed.indexOf('\"') +1;
250                         if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
251                         int strEnd = trimmed.indexOf('\"', strStart);
252                         if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
253                         key = trimmed.substring(strStart, strEnd);
254
255                         Hashtable thisCase = (Hashtable)byLength[key.length()];
256                         if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
257                         thisCase.put(key, "");
258
259                         // find end of case definition
260                         int caseEnd = trimmed.indexOf(':', strEnd) +1;
261                         if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
262                         trimmed = trimmed.substring(caseEnd);
263                     }
264
265                     if (key != null) {
266                         Hashtable hash = byLength[key.length()];
267                         hash.put(key, (String)hash.get(key) + replaceAll(processLine(trimmed, false), "//[^\"]*$", "").trim() + "\n");
268                     } else {
269                         out.print(processLine(trimmed, false));
270                     }
271                 }
272
273                 for(int i=0; i<255; i++) {
274                     if (byLength[i] == null) continue;
275                     out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) { ");
276                     buildTrie("", byLength[i]);
277                     out.print("}; break; }  ");
278                 }
279                 out.print("} /* switch */ ");
280                 if (Default != null) out.print(" " + Default);
281                 out.print(" } while(false); /* OUTER */\n");
282                 enumSwitch++;
283
284             } else {
285                 out.print(processLine(s, false));
286             }
287         }
288
289         return err;
290     }
291
292     private static class MyVec {
293         private Object[] store;
294         private int size = 0;
295     
296         public MyVec() { this(10); }
297         public MyVec(int i) { store = new Object[i]; }
298         public MyVec(int i, Object[] store) { size = i; this.store = store; }
299     
300         private void grow() { grow(store.length * 2); }
301         private void grow(int newsize) {
302             Object[] newstore = new Object[newsize];
303             System.arraycopy(store, 0, newstore, 0, size);
304             store = newstore;
305         }
306
307         public void removeAllElements() {
308             for(int i=0; i<size; i++) store[i] = null;
309             size = 0;
310         }
311
312         public void toArray(Object[] o) {
313             for(int i=0; i<size; i++)
314                 o[i] = store[i];
315         }
316     
317         public int indexOf(Object o) {
318             for(int i=0; i<size; i++)
319                 if (o == null ? store[i] == null : store[i].equals(o)) return i;
320         
321             return -1;
322         }
323     
324         public void addElement(Object o) {
325             if (size >= store.length - 1) grow();
326             store[size++] = o;
327         }
328
329         public Object peek() {
330             return lastElement();
331         }
332
333         public Object elementAt(int i) {
334             return store[i];
335         }
336     
337         public Object lastElement() {
338             if (size == 0) return null;
339             return store[size - 1];
340         }
341
342         public void push(Object o) { addElement(o); }
343         public Object pop() {
344             Object ret = lastElement();
345             if (size > 0) store[size--] = null;
346             return ret;
347         }
348
349         public int size() { return size; }
350
351         public void setSize(int newSize) {
352             if (newSize < 0) throw new RuntimeException("tried to set size to negative value");
353             if (newSize > store.length) grow(newSize * 2);
354             if (newSize < size)
355                 for(int i=newSize; i<size; i++)
356                     store[i] = null;
357             size = newSize;
358         }
359
360         public void copyInto(Object[] out) {
361             for(int i=0; i<size; i++)
362                 out[i] = store[i];
363         }
364
365         public void fromArray(Object[] in) {
366             setSize(in.length);
367             for(int i=0; i<size; i++)
368                 store[i] = in[i];
369         }
370
371         public void removeElementAt(int i) {
372             if (i >= size || i < 0) throw new RuntimeException("tried to remove an element outside the vector's limits");
373             for(int j=i; j<size - 1; j++)
374                 store[j] = store[j + 1];
375             setSize(size - 1);
376         }
377
378         public void setElementAt(Object o, int i) {
379             if (i >= size) setSize(i);
380             store[i] = o;
381         }
382
383         public void removeElement(Object o) {
384             int idx = indexOf(o);
385             if (idx != -1) removeElementAt(idx);
386         }
387
388         public void insertElementAt(Object o, int at) {
389             if (size == store.length) grow();
390             for(int i=size; i>at; i--)
391                 store[i] = store[i-1];
392             store[at] = o;
393             size++;
394         }
395
396         public interface CompareFunc {
397             public int compare(Object a, Object b);
398         }
399
400         public void sort(CompareFunc c) {
401             sort(this, null, c, 0, size-1);
402         }
403
404         public static void sort(MyVec a, MyVec b, CompareFunc c) {
405             if (b != null && a.size != b.size) throw new IllegalArgumentException("MyVec a and b must be of equal size");
406             sort(a, b, c, 0, a.size-1);
407         }
408
409         private static final void sort(MyVec a, MyVec b, CompareFunc c, int start, int end) {
410             Object tmpa, tmpb = null;
411             if(start >= end) return;
412             if(end-start <= 6) {
413                 for(int i=start+1;i<=end;i++) {
414                     tmpa = a.store[i];
415                     if (b != null) tmpb = b.store[i];
416                     int j;
417                     for(j=i-1;j>=start;j--) {
418                         if(c.compare(a.store[j],tmpa) <= 0) break;
419                         a.store[j+1] = a.store[j];
420                         if (b != null) b.store[j+1] = b.store[j];
421                     }
422                     a.store[j+1] = tmpa;
423                     if (b != null) b.store[j+1] = tmpb;
424                 }
425                 return;
426             }
427
428             Object pivot = a.store[end];
429             int lo = start - 1;
430             int hi = end;
431
432             do {
433                 while(c.compare(a.store[++lo],pivot) < 0) { }
434                 while((hi > lo) && c.compare(a.store[--hi],pivot) > 0) { }
435                 swap(a, lo,hi);
436                 if (b != null) swap(b, lo,hi);
437             } while(lo < hi);
438
439             swap(a, lo,end);
440             if (b != null) swap(b, lo,end);
441
442             sort(a, b, c, start, lo-1);
443             sort(a, b, c, lo+1, end);
444         }
445
446         private static final void swap(MyVec vec, int a, int b) {
447             if(a != b) {
448                 Object tmp = vec.store[a];
449                 vec.store[a] = vec.store[b];
450                 vec.store[b] = tmp;
451             }
452         }
453
454     }
455
456     private void buildTrie(String prefix, Hashtable cases) {
457         Enumeration caseKeys = cases.keys();
458         MyVec keys = new MyVec();
459         while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
460         keys.sort(new MyVec.CompareFunc() { public int compare(Object a, Object b) {
461             return ((String)a).compareTo((String)b);
462         } } );
463
464         for(int i=0; i<keys.size(); i++) {
465             if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
466             String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
467             if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
468                 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
469                 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
470                 buildTrie(prefixPlusOne, cases);
471                 out.print("} break; } ");
472                 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
473                 if (i<keys.size()) { i--; continue; }
474             } else {
475                 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
476                 String code = (String)cases.get(keys.elementAt(i));
477                 code = code.substring(0, code.length());
478                 String key = (String)keys.elementAt(i);
479                 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break;  ");
480             }
481         }
482     }
483
484     private String processLine(String s, boolean deleteLineEndings) throws IOException {
485         if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
486         String ret = "";
487         for(int i=0; i<s.length(); i++) {
488             char c = s.charAt(i);
489             if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
490                 ret += c;
491                 continue;
492             }
493             int j;
494             for(j = i; j < s.length(); j++) {
495                 c = s.charAt(j);
496                 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
497             }
498             String tok = s.substring(i, j);
499             Object val = replace.get(tok);
500             if (val == null) {
501                 ret += tok;
502                 i = j - 1;
503             } else if (val instanceof JSFunctionMacro) {
504                 if (s.charAt(j) != '(') { ret += tok; i = j - 1; continue; }
505                 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
506                 i = s.indexOf(')', j);
507             } else {
508                 ret += val;
509                 i = j - 1;
510             }
511         }
512         if (!deleteLineEndings) ret += "\n";
513         return ret;
514     }
515
516     private static int indexOfWS(String s) { return indexOfWS(s, 0); }
517     private static int indexOfWS(String s, int beginIndex) {
518         if (s == null || beginIndex >= s.length()) return -1;
519         for (; beginIndex < s.length(); beginIndex++) {
520             if (s.charAt(beginIndex) == ' ') return beginIndex;
521         }
522         return s.length();
523     }
524
525     private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
526     private static int indexOfNotWS(String s, int beginIndex) {
527         if (s == null || beginIndex >= s.length()) return -1;
528         for (; beginIndex < s.length(); beginIndex++) {
529             if (s.charAt(beginIndex) != ' ') return beginIndex;
530         }
531         return -1;
532     }
533
534     public class Warning {
535         protected String msg;
536         protected int line;
537
538         public Warning() { msg = ""; }
539         public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
540
541         public int getLine() { return line; }
542         public String getMessage() { return msg; }
543         public String toString() { return "WARNING Line "+line+": "+msg; }
544     }
545
546     public class Error extends Warning {
547         public Error() { super(); }
548         public Error(String m) { super(m); }
549         public String toString() { return "ERROR Line "+line+": "+msg; }
550     }
551
552     public static class JSFunctionMacro {
553         public String unbound1 = null;
554         public String unbound2 = null;
555         public String expression = null;
556         public String process(String args) {
557             String bound1 = null;
558             String bound2 = null;
559             if (unbound2 == null) {
560                 bound1 = args;
561                 return replaceAll(expression, unbound1, bound1);
562             } else {
563                 bound1 = args.substring(0, args.indexOf(','));
564                 bound2 = args.substring(args.indexOf(',') + 1);
565                 return replaceAll(replaceAll(expression, unbound1, bound1), unbound2, bound2);
566             }
567         }
568     }
569 }
570