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