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