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