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