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