0df4c0f7fd97c0bf06ff5f53f93975b4c63d4cb3
[org.ibex.tool.git] / src / 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[] repeatreplaces = 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                 repeatreplaces = null;
200                 while (st.hasMoreTokens()) {
201                     String tok = st.nextToken().trim();
202                     String key = tok.substring(0, tok.indexOf('/'));
203                     String vals = tok.substring(tok.indexOf('/') + 1);
204                     StringTokenizer st2 = new StringTokenizer(vals,"/");
205                     if(repeatreplaces == null) {
206                         repeatreplaces = new Hashtable[st2.countTokens()];
207                         for(int i=0;i<repeatreplaces.length;i++) repeatreplaces[i] = (Hashtable) replace.clone();
208                     }
209                     for(int i=0;st2.hasMoreTokens() && i<repeatreplaces.length;i++)
210                         repeatreplaces[i].put(key, st2.nextToken());
211                 }
212                 sinceLastRepeat = new Vector();
213                 out.print("\n"); // preserve line numbers
214
215             } else if (trimmed.startsWith("//#end")) {
216                 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
217                 Hashtable save = replace;
218                 out.print("\n");
219                 for(int i=0;i<repeatreplaces.length;i++) {
220                     replace = repeatreplaces[i];
221                     for(int j=0; j<sinceLastRepeat.size() - 1; j++) out.print(processLine((String)sinceLastRepeat.elementAt(j), true));
222                 }
223                 sinceLastRepeat = null;
224                 replace = save;
225             } else if (trimmed.startsWith("//#ifdef")) {
226                 String expr = trimmed.substring(8).trim().toUpperCase();
227                 out.println(trimmed);
228                 boolean useCode = defs.contains(expr);
229                 for (trimmed = in.readLine().trim(); !trimmed.startsWith("//#endif"); trimmed = in.readLine().trim()) {
230                     if (trimmed.startsWith("//#else")) useCode = !useCode;
231                     else if (!useCode) out.print("// ");
232                     out.print(processLine(trimmed, false));
233                 }
234                 out.println("//#endif "+expr);
235
236             } else if (trimmed.startsWith("//#switch")) {
237                 int expStart = trimmed.indexOf('(') +1;
238                 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
239                 int expEnd = trimmed.lastIndexOf(')');
240                 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
241                 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
242                 String expr = trimmed.substring(expStart, expEnd);
243
244                 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+");  ");
245                 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
246
247                 Hashtable[] byLength = new Hashtable[255];
248                 String key = null;
249                 String Default = null;
250                 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
251                     if (trimmed.startsWith("default:")) {
252                         Default = processLine(trimmed.substring(8), false);
253                         continue;
254                     }
255                     if (trimmed.startsWith("case ")) {
256                         // find key
257                         int strStart = trimmed.indexOf('\"') +1;
258                         if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
259                         int strEnd = trimmed.indexOf('\"', strStart);
260                         if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
261                         key = trimmed.substring(strStart, strEnd);
262
263                         Hashtable thisCase = (Hashtable)byLength[key.length()];
264                         if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
265                         thisCase.put(key, "");
266
267                         // find end of case definition
268                         int caseEnd = trimmed.indexOf(':', strEnd) +1;
269                         if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
270                         trimmed = trimmed.substring(caseEnd);
271                     }
272
273                     if (key != null) {
274                         Hashtable hash = byLength[key.length()];
275                         hash.put(key, (String)hash.get(key) + replaceAll(processLine(trimmed, false), "//[^\"]*$", "").trim() + "\n");
276                     } else {
277                         out.print(processLine(trimmed, false));
278                     }
279                 }
280
281                 for(int i=0; i<255; i++) {
282                     if (byLength[i] == null) continue;
283                     out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) { ");
284                     buildTrie("", byLength[i]);
285                     out.print("}; break; }  ");
286                 }
287                 out.print("} /* switch */ ");
288                 if (Default != null) out.print(" " + Default);
289                 out.print(" } while(false); /* OUTER */\n");
290                 enumSwitch++;
291
292             } else {
293                 out.print(processLine(s, false));
294             }
295         }
296
297         return err;
298     }
299
300     private static class MyVec {
301         private Object[] store;
302         private int size = 0;
303     
304         public MyVec() { this(10); }
305         public MyVec(int i) { store = new Object[i]; }
306         public MyVec(int i, Object[] store) { size = i; this.store = store; }
307     
308         private void grow() { grow(store.length * 2); }
309         private void grow(int newsize) {
310             Object[] newstore = new Object[newsize];
311             System.arraycopy(store, 0, newstore, 0, size);
312             store = newstore;
313         }
314
315         public void removeAllElements() {
316             for(int i=0; i<size; i++) store[i] = null;
317             size = 0;
318         }
319
320         public void toArray(Object[] o) {
321             for(int i=0; i<size; i++)
322                 o[i] = store[i];
323         }
324     
325         public int indexOf(Object o) {
326             for(int i=0; i<size; i++)
327                 if (o == null ? store[i] == null : store[i].equals(o)) return i;
328         
329             return -1;
330         }
331     
332         public void addElement(Object o) {
333             if (size >= store.length - 1) grow();
334             store[size++] = o;
335         }
336
337         public Object peek() {
338             return lastElement();
339         }
340
341         public Object elementAt(int i) {
342             return store[i];
343         }
344     
345         public Object lastElement() {
346             if (size == 0) return null;
347             return store[size - 1];
348         }
349
350         public void push(Object o) { addElement(o); }
351         public Object pop() {
352             Object ret = lastElement();
353             if (size > 0) store[size--] = null;
354             return ret;
355         }
356
357         public int size() { return size; }
358
359         public void setSize(int newSize) {
360             if (newSize < 0) throw new RuntimeException("tried to set size to negative value");
361             if (newSize > store.length) grow(newSize * 2);
362             if (newSize < size)
363                 for(int i=newSize; i<size; i++)
364                     store[i] = null;
365             size = newSize;
366         }
367
368         public void copyInto(Object[] out) {
369             for(int i=0; i<size; i++)
370                 out[i] = store[i];
371         }
372
373         public void fromArray(Object[] in) {
374             setSize(in.length);
375             for(int i=0; i<size; i++)
376                 store[i] = in[i];
377         }
378
379         public void removeElementAt(int i) {
380             if (i >= size || i < 0) throw new RuntimeException("tried to remove an element outside the vector's limits");
381             for(int j=i; j<size - 1; j++)
382                 store[j] = store[j + 1];
383             setSize(size - 1);
384         }
385
386         public void setElementAt(Object o, int i) {
387             if (i >= size) setSize(i);
388             store[i] = o;
389         }
390
391         public void removeElement(Object o) {
392             int idx = indexOf(o);
393             if (idx != -1) removeElementAt(idx);
394         }
395
396         public void insertElementAt(Object o, int at) {
397             if (size == store.length) grow();
398             for(int i=size; i>at; i--)
399                 store[i] = store[i-1];
400             store[at] = o;
401             size++;
402         }
403
404         public interface CompareFunc {
405             public int compare(Object a, Object b);
406         }
407
408         public void sort(CompareFunc c) {
409             sort(this, null, c, 0, size-1);
410         }
411
412         public static void sort(MyVec a, MyVec b, CompareFunc c) {
413             if (b != null && a.size != b.size) throw new IllegalArgumentException("MyVec a and b must be of equal size");
414             sort(a, b, c, 0, a.size-1);
415         }
416
417         private static final void sort(MyVec a, MyVec b, CompareFunc c, int start, int end) {
418             Object tmpa, tmpb = null;
419             if(start >= end) return;
420             if(end-start <= 6) {
421                 for(int i=start+1;i<=end;i++) {
422                     tmpa = a.store[i];
423                     if (b != null) tmpb = b.store[i];
424                     int j;
425                     for(j=i-1;j>=start;j--) {
426                         if(c.compare(a.store[j],tmpa) <= 0) break;
427                         a.store[j+1] = a.store[j];
428                         if (b != null) b.store[j+1] = b.store[j];
429                     }
430                     a.store[j+1] = tmpa;
431                     if (b != null) b.store[j+1] = tmpb;
432                 }
433                 return;
434             }
435
436             Object pivot = a.store[end];
437             int lo = start - 1;
438             int hi = end;
439
440             do {
441                 while(c.compare(a.store[++lo],pivot) < 0) { }
442                 while((hi > lo) && c.compare(a.store[--hi],pivot) > 0) { }
443                 swap(a, lo,hi);
444                 if (b != null) swap(b, lo,hi);
445             } while(lo < hi);
446
447             swap(a, lo,end);
448             if (b != null) swap(b, lo,end);
449
450             sort(a, b, c, start, lo-1);
451             sort(a, b, c, lo+1, end);
452         }
453
454         private static final void swap(MyVec vec, int a, int b) {
455             if(a != b) {
456                 Object tmp = vec.store[a];
457                 vec.store[a] = vec.store[b];
458                 vec.store[b] = tmp;
459             }
460         }
461
462     }
463
464     private void buildTrie(String prefix, Hashtable cases) {
465         Enumeration caseKeys = cases.keys();
466         MyVec keys = new MyVec();
467         while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
468         keys.sort(new MyVec.CompareFunc() { public int compare(Object a, Object b) {
469             return ((String)a).compareTo((String)b);
470         } } );
471
472         for(int i=0; i<keys.size(); i++) {
473             if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
474             String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
475             if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
476                 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
477                 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
478                 buildTrie(prefixPlusOne, cases);
479                 out.print("} break; } ");
480                 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
481                 if (i<keys.size()) { i--; continue; }
482             } else {
483                 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
484                 String code = (String)cases.get(keys.elementAt(i));
485                 code = code.substring(0, code.length());
486                 String key = (String)keys.elementAt(i);
487                 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break;  ");
488             }
489         }
490     }
491
492     private String processLine(String s, boolean deleteLineEndings) throws IOException {
493         if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
494         String ret = "";
495         for(int i=0; i<s.length(); i++) {
496             char c = s.charAt(i);
497             if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
498                 ret += c;
499                 continue;
500             }
501             int j;
502             for(j = i; j < s.length(); j++) {
503                 c = s.charAt(j);
504                 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
505             }
506             String tok = s.substring(i, j);
507             Object val = replace.get(tok);
508             if (val == null) {
509                 ret += tok;
510                 i = j - 1;
511             } else if (val instanceof JSFunctionMacro) {
512                 if (s.charAt(j) != '(') { ret += tok; i = j - 1; continue; }
513                 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
514                 i = s.indexOf(')', j);
515             } else {
516                 ret += val;
517                 i = j - 1;
518             }
519         }
520         if (!deleteLineEndings) ret += "\n";
521         return ret;
522     }
523
524     private static int indexOfWS(String s) { return indexOfWS(s, 0); }
525     private static int indexOfWS(String s, int beginIndex) {
526         if (s == null || beginIndex >= s.length()) return -1;
527         for (; beginIndex < s.length(); beginIndex++) {
528             if (s.charAt(beginIndex) == ' ') return beginIndex;
529         }
530         return s.length();
531     }
532
533     private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
534     private static int indexOfNotWS(String s, int beginIndex) {
535         if (s == null || beginIndex >= s.length()) return -1;
536         for (; beginIndex < s.length(); beginIndex++) {
537             if (s.charAt(beginIndex) != ' ') return beginIndex;
538         }
539         return -1;
540     }
541
542     public class Warning {
543         protected String msg;
544         protected int line;
545
546         public Warning() { msg = ""; }
547         public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
548
549         public int getLine() { return line; }
550         public String getMessage() { return msg; }
551         public String toString() { return "WARNING Line "+line+": "+msg; }
552     }
553
554     public class Error extends Warning {
555         public Error() { super(); }
556         public Error(String m) { super(m); }
557         public String toString() { return "ERROR Line "+line+": "+msg; }
558     }
559
560     public static class JSFunctionMacro {
561         public String unbound1 = null;
562         public String unbound2 = null;
563         public String expression = null;
564         public String process(String args) {
565             String bound1 = null;
566             String bound2 = null;
567             if (unbound2 == null) {
568                 bound1 = args;
569                 return replaceAll(expression, unbound1, bound1);
570             } else {
571                 bound1 = args.substring(0, args.indexOf(','));
572                 bound2 = args.substring(args.indexOf(',') + 1);
573                 return replaceAll(replaceAll(expression, unbound1, bound1), unbound2, bound2);
574             }
575         }
576     }
577 }
578