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