fixed bug 440
[org.ibex.core.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 java.util.*;
11 import java.io.*;
12
13 /**
14  *   A VERY crude, inefficient Java preprocessor
15  *
16  *   //#define FOO bar baz       -- replace all instances of token FOO with "bar baz"
17  *   //#replace foo/bar baz/bop  -- DUPLICATE everything between here and //#end,
18  *                                  replacing foo with bar and baz with bop in the *second* copy
19  *   //#switch(EXPR)             -- switch on strings
20  *       case "case1":
21  *   //#end
22  *
23  *   Replacements are done on a token basis.  Tokens are defined as a
24  *   sequence of characters which all belong to a single class.  The
25  *   two character classes are:
26  *
27  *     - [a-zA-Z0-9_]
28  *     - all other non-whitespace characters
29  */
30 public class Preprocessor {
31
32     public static void main(String[] args) throws Exception {
33         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
34         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
35
36         // process stdin to stdout
37         Preprocessor cc = new Preprocessor(br, bw);
38         Vector err = cc.process();
39         bw.flush();
40
41         // handle errors
42         boolean errors = false;
43         for (int i=0; i < err.size(); i++) { if (err.get(i) instanceof Error) errors = true; System.err.println(err.get(i)); }
44         if (errors) throw new Exception();
45     }
46
47     private Reader r;
48     private Writer w;
49     private LineNumberReader in;
50     private PrintWriter out;
51
52     private Hashtable replace = new Hashtable();
53     private Hashtable repeatreplace = null;
54     private Vector sinceLastRepeat = null;
55     private Vector err = new Vector();
56
57     private int enumSwitch = 0; // number appended to variable used in switch implementation
58
59    
60     public Preprocessor(Reader reader, Writer writer) {
61         setReader(reader);
62         setWriter(writer);
63     }
64
65     public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
66     public Reader getReader() { return r; }
67
68     public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
69     public Writer getWriter() { return w; }
70
71
72     /** process data from reader, write to writer, return vector of errors */
73     public Vector process() throws IOException {
74         err.clear();
75
76         String s = null;
77 PROCESS:
78         while((s = in.readLine()) != null) {
79             if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
80             String trimmed = s.trim();
81
82             if (trimmed.startsWith("//#define ")) {
83                 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
84                     err.add(new Error("#define badly formed, ignored")); continue PROCESS;
85                 }
86                 int keyStart = indexOfNotWS(trimmed, 9);
87                 if (keyStart == -1) {
88                     err.add(new Error("#define requires KEY")); continue PROCESS;
89                 }
90                 int keyEnd = indexOfWS(trimmed, keyStart);
91
92                 int macroStart = trimmed.indexOf('(');
93                 int macroEnd = trimmed.indexOf(')');
94                 if (macroStart > keyEnd) {
95                     // no macro is defined, just make sure something dumb like KEYNA)ME hasn't been done
96                     if (macroEnd < keyEnd) { err.add(new Error("#define key contains invalid char: ')'")); continue PROCESS; }
97                     macroStart = macroEnd = -1;
98                 }
99
100                 if (macroStart == 0) {
101                     err.add(new Error("#define macro requires name")); continue PROCESS;
102                 } else if (macroStart > 0) {
103                     if (macroStart > macroEnd) { err.add(new Error("#define macro badly formed")); continue PROCESS; }
104                     if (macroStart+1 == macroEnd) { err.add(new Error("#define macro requires property name")); continue PROCESS; }
105
106                     JSFunctionMacro fm = new JSFunctionMacro();
107                     String key = trimmed.substring(keyStart, macroStart);
108                     String unbound = trimmed.substring(macroStart +1, macroEnd);
109                     int unboundDiv = unbound.indexOf(',');
110                     if (unboundDiv == -1) {
111                         fm.unbound1 = unbound;
112                     } else {
113                         fm.unbound1 = unbound.substring(0, unboundDiv);
114                         fm.unbound2 = unbound.substring(unboundDiv +1);
115                         if (fm.unbound1.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
116                         if (fm.unbound2.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
117                     }
118                     fm.expression = trimmed.substring(keyEnd).trim();
119                     replace.put(key, fm);
120                 } else {
121                     String key = trimmed.substring(keyStart, keyEnd);
122                     String val = trimmed.substring(keyEnd).trim();
123                     replace.put(key, val);
124                 }
125                 out.print("\n"); // preserve line numbers
126                 
127             } else if (trimmed.startsWith("//#repeat ")) {
128                 trimmed = trimmed.substring(9);
129                 while(trimmed.charAt(trimmed.length() - 1) == '\\') {
130                     String s2 = in.readLine().trim();
131                     if (s2.startsWith("//")) s2 = s2.substring(2).trim();
132                     trimmed = trimmed.substring(0, trimmed.length() - 1) + " " + s2;
133                     out.print("\n");  // preserve line numbers
134                 }
135                 StringTokenizer st = new StringTokenizer(trimmed, " ");
136                 repeatreplace = (Hashtable)replace.clone();
137                 while (st.hasMoreTokens()) {
138                     String tok = st.nextToken().trim();
139                     String key = tok.substring(0, tok.indexOf('/'));
140                     String val = tok.substring(tok.indexOf('/') + 1);
141                     repeatreplace.put(key, val);
142                 }
143                 sinceLastRepeat = new Vector();
144                 out.print("\n"); // preserve line numbers
145
146             } else if (trimmed.startsWith("//#end")) {
147                 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
148                 Hashtable save = replace;
149                 replace = repeatreplace;
150                 out.print("\n");
151                 for(int i=0; i<sinceLastRepeat.size() - 1; i++) out.print(processLine((String)sinceLastRepeat.elementAt(i), true));
152                 sinceLastRepeat = null;
153                 replace = save;
154
155             } else if (trimmed.startsWith("//#switch")) {
156                 int expStart = trimmed.indexOf('(') +1;
157                 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
158                 int expEnd = trimmed.lastIndexOf(')');
159                 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
160                 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
161                 String expr = trimmed.substring(expStart, expEnd);
162
163                 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+");  ");
164                 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
165
166                 Hashtable[] byLength = new Hashtable[255];
167                 String key = null;
168                 String Default = null;
169                 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
170                     if (trimmed.startsWith("default:")) {
171                         Default = processLine(trimmed.substring(8), false);
172                         continue;
173                     }
174                     if (trimmed.startsWith("case ")) {
175                         // find key
176                         int strStart = trimmed.indexOf('\"') +1;
177                         if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
178                         int strEnd = trimmed.indexOf('\"', strStart);
179                         if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
180                         key = trimmed.substring(strStart, strEnd);
181
182                         Hashtable thisCase = (Hashtable)byLength[key.length()];
183                         if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
184                         thisCase.put(key, "");
185
186                         // find end of case definition
187                         int caseEnd = trimmed.indexOf(':', strEnd) +1;
188                         if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
189                         trimmed = trimmed.substring(caseEnd);
190                     }
191
192                     if (key != null) {
193                         Hashtable hash = byLength[key.length()];
194                         hash.put(key, (String)hash.get(key) + processLine(trimmed, false).replaceAll("//[^\"]*$", ""));
195                     } else {
196                         out.print(processLine(trimmed, false));
197                     }
198                 }
199
200                 for(int i=0; i<255; i++) {
201                     if (byLength[i] == null) continue;
202                     out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) {\n");
203                     buildTrie("", byLength[i]);
204                     out.print("}; break; }\n");
205                 }
206                 out.print("} /* switch */ ");
207                 if (Default != null) out.print("\n" + Default);
208                 out.print(" } while(false); //OUTER\n");
209                 enumSwitch++;
210
211             } else {
212                 out.print(processLine(s, false));
213             }
214         }
215
216         return err;
217     }
218
219     private void buildTrie(String prefix, Hashtable cases) {
220         Enumeration caseKeys = cases.keys();
221         Vec keys = new Vec();
222         while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
223         keys.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) {
224             return ((String)a).compareTo((String)b);
225         } } );
226
227         for(int i=0; i<keys.size(); i++) {
228             if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
229             String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
230             if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
231                 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
232                 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
233                 buildTrie(prefixPlusOne, cases);
234                 out.print("} break; } ");
235                 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
236                 if (i<keys.size()) { i--; continue; }
237             } else {
238                 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
239                 String code = (String)cases.get(keys.elementAt(i));
240                 code = code.substring(0, code.length() - 1);
241                 String key = (String)keys.elementAt(i);
242                 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break;  ");
243             }
244         }
245     }
246
247     private String processLine(String s, boolean deleteLineEndings) throws IOException {
248         if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
249         String ret = "";
250         for(int i=0; i<s.length(); i++) {
251             char c = s.charAt(i);
252             if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
253                 ret += c;
254                 continue;
255             }
256             int j;
257             for(j = i; j < s.length(); j++) {
258                 c = s.charAt(j);
259                 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
260             }
261             String tok = s.substring(i, j);
262             Object val = replace.get(tok);
263             if (val == null) {
264                 ret += tok;
265                 i = j - 1;
266             } else if (val instanceof JSFunctionMacro) {
267                 if (s.charAt(j) != '(') { err.add(new Error("open paren must follow macro binding for macro " + tok)); continue; }
268                 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
269                 i = s.indexOf(')', j);
270             } else {
271                 ret += val;
272                 i = j - 1;
273             }
274         }
275         if (!deleteLineEndings) ret += "\n";
276         return ret;
277     }
278
279     private static int indexOfWS(String s) { return indexOfWS(s, 0); }
280     private static int indexOfWS(String s, int beginIndex) {
281         if (s == null || beginIndex >= s.length()) return -1;
282         for (; beginIndex < s.length(); beginIndex++) {
283             if (s.charAt(beginIndex) == ' ') return beginIndex;
284         }
285         return s.length();
286     }
287
288     private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
289     private static int indexOfNotWS(String s, int beginIndex) {
290         if (s == null || beginIndex >= s.length()) return -1;
291         for (; beginIndex < s.length(); beginIndex++) {
292             if (s.charAt(beginIndex) != ' ') return beginIndex;
293         }
294         return -1;
295     }
296
297     public class Warning {
298         protected String msg;
299         protected int line;
300
301         public Warning() { msg = ""; }
302         public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
303
304         public String toString() { return "WARNING Line "+line+": "+msg; }
305     }
306
307     public class Error extends Warning {
308         public Error() { super(); }
309         public Error(String m) { super(m); }
310         public String toString() { return "ERROR Line "+line+": "+msg; }
311     }
312
313     public static class JSFunctionMacro {
314         public String unbound1 = null;
315         public String unbound2 = null;
316         public String expression = null;
317         public String process(String args) {
318             String bound1 = null;
319             String bound2 = null;
320             if (unbound2 == null) {
321                 bound1 = args;
322                 return expression.replaceAll(unbound1, bound1);
323             } else {
324                 bound1 = args.substring(0, args.indexOf(','));
325                 bound2 = args.substring(args.indexOf(',') + 1);
326                 return (expression.replaceAll(unbound1, bound1).replaceAll(unbound2, bound2));
327             }
328         }
329     }
330 }
331