1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
12 * A VERY crude, inefficient Java preprocessor
14 * //#define FOO bar baz -- replace all instances of token FOO with "bar baz"
15 * //#replace foo/bar baz/bop -- DUPLICATE everything between here and //#end,
16 * replacing foo with bar and baz with bop in the *second* copy
17 * //#switch(EXPR) -- switch on strings
21 * //#ifdef FOO -- includes contents if FOO passed as define to preprocessor
27 * Replacements are done on a token basis. Tokens are defined as a
28 * sequence of characters which all belong to a single class. The
29 * two character classes are:
32 * - all other non-whitespace characters
34 * Preprocessor makes use of several optional system properties:
36 * - ibex.tool.preprocessor.define
37 * - ibex.tool.preprocessor.inputdir
38 * - ibex.tool.preprocessor.outputdir
40 * @author adam@ibex.org, crawshaw@ibex.org
42 public class Preprocessor {
44 public static String replaceAll(String source, String regexp, String replaceWith) {
45 return source.replaceAll(regexp, replaceWith);
48 RE re = new RE(regexp, 0, RESyntax.RE_SYNTAX_PERL5);
49 return (String)re.substituteAll(source, replaceWith);
50 } catch (Exception e) {
57 public static void main(String[] args) throws Exception {
58 List defs = new ArrayList();
60 String define = System.getProperty("ibex.tool.preprocessor.define");
62 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
63 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
66 String inputdir = System.getProperty("ibex.tool.preprocessor.inputdir");
67 if (inputdir == null) inputdir = "src/";
69 String outputdir = System.getProperty("ibex.tool.preprocessor.outputdir");
70 if (outputdir == null) outputdir = "build/java/";
72 if (args.length == 0) {
73 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
74 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
76 // process stdin to stdout
77 Preprocessor cc = new Preprocessor(br, bw, defs);
78 Vector err = cc.process();
82 boolean errors = false;
83 for (int i=0; i < err.size(); i++) {
84 if (err.get(i) instanceof Error) errors = true; System.err.println(err.get(i)); }
85 if (errors) throw new Exception();
87 for(int i=0; i<args.length; i++) {
88 if (!args[i].endsWith(".java")) continue;
89 File source = new File(args[i]);
90 File target = new File(replaceAll(args[i], inputdir, outputdir));
91 if (target.exists() && target.lastModified() > source.lastModified()) continue;
92 System.err.println("preprocessing " + args[i]);
93 new File(target.getParent()).mkdirs();
94 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
95 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target)));
96 Preprocessor cc = new Preprocessor(br, bw, defs);
97 Vector err = cc.process();
99 boolean errors = false;
100 for (int j=0; j < err.size(); j++) {
101 if (err.get(j) instanceof Error) errors = true; System.err.println(err.get(j)); }
102 if (errors) System.exit(-1);
109 private LineNumberReader in;
110 private PrintWriter out;
112 private Hashtable replace = new Hashtable();
113 private Hashtable[] repeatreplaces = null;
114 private Vector sinceLastRepeat = null;
115 private Vector err = new Vector();
118 private int enumSwitch = 0; // number appended to variable used in switch implementation
121 public Preprocessor(Reader reader, Writer writer, List d) {
127 public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
128 public Reader getReader() { return r; }
130 public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
131 public Writer getWriter() { return w; }
134 /** process data from reader, write to writer, return vector of errors */
135 public Vector process() throws IOException {
140 while((s = in.readLine()) != null) {
141 if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
142 String trimmed = s.trim();
144 if (trimmed.startsWith("//#define ")) {
145 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
146 err.add(new Error("#define badly formed, ignored")); continue PROCESS;
148 int keyStart = indexOfNotWS(trimmed, 9);
149 if (keyStart == -1) {
150 err.add(new Error("#define requires KEY")); continue PROCESS;
152 int keyEnd = indexOfWS(trimmed, keyStart);
154 int macroStart = trimmed.indexOf('(');
155 int macroEnd = trimmed.indexOf(')');
156 if (macroStart > keyEnd) {
157 // no macro is defined, just make sure something dumb like KEYNA)ME hasn't been done
158 if (macroEnd < keyEnd) { err.add(new Error("#define key contains invalid char: ')'")); continue PROCESS; }
159 macroStart = macroEnd = -1;
162 if (macroStart == 0) {
163 err.add(new Error("#define macro requires name")); continue PROCESS;
164 } else if (macroStart > 0) {
165 if (macroStart > macroEnd) { err.add(new Error("#define macro badly formed")); continue PROCESS; }
166 if (macroStart+1 == macroEnd) { err.add(new Error("#define macro requires property name")); continue PROCESS; }
168 JSFunctionMacro fm = new JSFunctionMacro();
169 String key = trimmed.substring(keyStart, macroStart);
170 String unbound = trimmed.substring(macroStart +1, macroEnd);
171 int unboundDiv = unbound.indexOf(',');
172 if (unboundDiv == -1) {
173 fm.unbound1 = unbound;
175 fm.unbound1 = unbound.substring(0, unboundDiv);
176 fm.unbound2 = unbound.substring(unboundDiv +1);
177 if (fm.unbound1.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
178 if (fm.unbound2.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
180 fm.expression = trimmed.substring(keyEnd).trim();
181 replace.put(key, fm);
183 String key = trimmed.substring(keyStart, keyEnd);
184 String val = trimmed.substring(keyEnd).trim();
185 replace.put(key, val);
187 out.print("\n"); // preserve line numbers
189 } else if (trimmed.startsWith("//#repeat ")) {
190 trimmed = trimmed.substring(9);
191 while(trimmed.charAt(trimmed.length() - 1) == '\\') {
192 String s2 = in.readLine().trim();
193 if (s2.startsWith("//")) s2 = s2.substring(2).trim();
194 trimmed = trimmed.substring(0, trimmed.length() - 1) + " " + s2;
195 out.print("\n"); // preserve line numbers
197 StringTokenizer st = new StringTokenizer(trimmed, " ");
198 repeatreplaces = null;
199 while (st.hasMoreTokens()) {
200 String tok = st.nextToken().trim();
201 String key = tok.substring(0, tok.indexOf('/'));
202 String vals = tok.substring(tok.indexOf('/') + 1);
203 StringTokenizer st2 = new StringTokenizer(vals,"/");
204 if(repeatreplaces == null) {
205 repeatreplaces = new Hashtable[st2.countTokens()];
206 for(int i=0;i<repeatreplaces.length;i++) repeatreplaces[i] = (Hashtable) replace.clone();
208 for(int i=0;st2.hasMoreTokens() && i<repeatreplaces.length;i++)
209 repeatreplaces[i].put(key, st2.nextToken());
211 sinceLastRepeat = new Vector();
212 out.print("\n"); // preserve line numbers
214 } else if (trimmed.startsWith("//#end")) {
215 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
216 Hashtable save = replace;
218 for(int i=0;i<repeatreplaces.length;i++) {
219 replace = repeatreplaces[i];
220 for(int j=0; j<sinceLastRepeat.size() - 1; j++) out.print(processLine((String)sinceLastRepeat.elementAt(j), true));
222 sinceLastRepeat = null;
224 } else if (trimmed.startsWith("//#ifdef")) {
225 String expr = trimmed.substring(8).trim().toUpperCase();
226 out.println(trimmed);
227 boolean useCode = defs.contains(expr);
228 for (trimmed = in.readLine().trim(); !trimmed.startsWith("//#endif"); trimmed = in.readLine().trim()) {
229 if (trimmed.startsWith("//#else")) useCode = !useCode;
230 else if (!useCode) out.print("// ");
231 out.print(processLine(trimmed, false));
233 out.println("//#endif "+expr);
235 } else if (trimmed.startsWith("//#switch") || trimmed.startsWith("//#jsswitch")) {
236 int expStart = trimmed.indexOf('(') +1;
237 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
238 int expEnd = trimmed.lastIndexOf(')');
239 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
240 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
241 String expr = trimmed.substring(expStart, expEnd);
242 if (trimmed.startsWith("//#jsswitch")) expr = "JSU.toString("+expr+")";
243 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+"); ");
244 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
246 Hashtable[] byLength = new Hashtable[255];
248 String Default = null;
249 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
250 if (trimmed.startsWith("default:")) {
251 Default = processLine(trimmed.substring(8), false);
254 if (trimmed.startsWith("case ")) {
256 int strStart = trimmed.indexOf('\"') +1;
257 if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
258 int strEnd = trimmed.indexOf('\"', strStart);
259 if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
260 key = trimmed.substring(strStart, strEnd);
262 Hashtable thisCase = (Hashtable)byLength[key.length()];
263 if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
264 thisCase.put(key, "");
266 // find end of case definition
267 int caseEnd = trimmed.indexOf(':', strEnd) +1;
268 if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
269 trimmed = trimmed.substring(caseEnd);
273 Hashtable hash = byLength[key.length()];
274 hash.put(key, (String)hash.get(key) + replaceAll(processLine(trimmed, false), "//[^\"]*$", "").trim() + "\n");
276 out.print(processLine(trimmed, false));
280 for(int i=0; i<255; i++) {
281 if (byLength[i] == null) continue;
282 out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) { ");
283 buildTrie("", byLength[i]);
284 out.print("}; break; } ");
286 out.print("} /* switch */ ");
287 if (Default != null) out.print(" " + Default);
288 out.print(" } while(false); /* OUTER */\n");
292 out.print(processLine(s, false));
299 private static class MyVec {
300 private Object[] store;
301 private int size = 0;
303 public MyVec() { this(10); }
304 public MyVec(int i) { store = new Object[i]; }
305 public MyVec(int i, Object[] store) { size = i; this.store = store; }
307 private void grow() { grow(store.length * 2); }
308 private void grow(int newsize) {
309 Object[] newstore = new Object[newsize];
310 System.arraycopy(store, 0, newstore, 0, size);
314 public void removeAllElements() {
315 for(int i=0; i<size; i++) store[i] = null;
319 public void toArray(Object[] o) {
320 for(int i=0; i<size; i++)
324 public int indexOf(Object o) {
325 for(int i=0; i<size; i++)
326 if (o == null ? store[i] == null : store[i].equals(o)) return i;
331 public void addElement(Object o) {
332 if (size >= store.length - 1) grow();
336 public Object peek() {
337 return lastElement();
340 public Object elementAt(int i) {
344 public Object lastElement() {
345 if (size == 0) return null;
346 return store[size - 1];
349 public void push(Object o) { addElement(o); }
350 public Object pop() {
351 Object ret = lastElement();
352 if (size > 0) store[size--] = null;
356 public int size() { return size; }
358 public void setSize(int newSize) {
359 if (newSize < 0) throw new RuntimeException("tried to set size to negative value");
360 if (newSize > store.length) grow(newSize * 2);
362 for(int i=newSize; i<size; i++)
367 public void copyInto(Object[] out) {
368 for(int i=0; i<size; i++)
372 public void fromArray(Object[] in) {
374 for(int i=0; i<size; i++)
378 public void removeElementAt(int i) {
379 if (i >= size || i < 0) throw new RuntimeException("tried to remove an element outside the vector's limits");
380 for(int j=i; j<size - 1; j++)
381 store[j] = store[j + 1];
385 public void setElementAt(Object o, int i) {
386 if (i >= size) setSize(i);
390 public void removeElement(Object o) {
391 int idx = indexOf(o);
392 if (idx != -1) removeElementAt(idx);
395 public void insertElementAt(Object o, int at) {
396 if (size == store.length) grow();
397 for(int i=size; i>at; i--)
398 store[i] = store[i-1];
403 public interface CompareFunc {
404 public int compare(Object a, Object b);
407 public void sort(CompareFunc c) {
408 sort(this, null, c, 0, size-1);
411 public static void sort(MyVec a, MyVec b, CompareFunc c) {
412 if (b != null && a.size != b.size) throw new IllegalArgumentException("MyVec a and b must be of equal size");
413 sort(a, b, c, 0, a.size-1);
416 private static final void sort(MyVec a, MyVec b, CompareFunc c, int start, int end) {
417 Object tmpa, tmpb = null;
418 if(start >= end) return;
420 for(int i=start+1;i<=end;i++) {
422 if (b != null) tmpb = b.store[i];
424 for(j=i-1;j>=start;j--) {
425 if(c.compare(a.store[j],tmpa) <= 0) break;
426 a.store[j+1] = a.store[j];
427 if (b != null) b.store[j+1] = b.store[j];
430 if (b != null) b.store[j+1] = tmpb;
435 Object pivot = a.store[end];
440 while(c.compare(a.store[++lo],pivot) < 0) { }
441 while((hi > lo) && c.compare(a.store[--hi],pivot) > 0) { }
443 if (b != null) swap(b, lo,hi);
447 if (b != null) swap(b, lo,end);
449 sort(a, b, c, start, lo-1);
450 sort(a, b, c, lo+1, end);
453 private static final void swap(MyVec vec, int a, int b) {
455 Object tmp = vec.store[a];
456 vec.store[a] = vec.store[b];
463 private void buildTrie(String prefix, Hashtable cases) {
464 Enumeration caseKeys = cases.keys();
465 MyVec keys = new MyVec();
466 while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
467 keys.sort(new MyVec.CompareFunc() { public int compare(Object a, Object b) {
468 return ((String)a).compareTo((String)b);
471 for(int i=0; i<keys.size(); i++) {
472 if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
473 String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
474 if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
475 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
476 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
477 buildTrie(prefixPlusOne, cases);
478 out.print("} break; } ");
479 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
480 if (i<keys.size()) { i--; continue; }
482 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
483 String code = (String)cases.get(keys.elementAt(i));
484 code = code.substring(0, code.length());
485 String key = (String)keys.elementAt(i);
486 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break; ");
491 private String processLine(String s, boolean deleteLineEndings) throws IOException {
492 if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
494 for(int i=0; i<s.length(); i++) {
495 char c = s.charAt(i);
496 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
501 for(j = i; j < s.length(); j++) {
503 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
505 String tok = s.substring(i, j);
506 Object val = replace.get(tok);
510 } else if (val instanceof JSFunctionMacro) {
511 if (s.charAt(j) != '(') { ret += tok; i = j - 1; continue; }
512 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
513 i = s.indexOf(')', j);
519 if (!deleteLineEndings) ret += "\n";
523 private static int indexOfWS(String s) { return indexOfWS(s, 0); }
524 private static int indexOfWS(String s, int beginIndex) {
525 if (s == null || beginIndex >= s.length()) return -1;
526 for (; beginIndex < s.length(); beginIndex++) {
527 if (s.charAt(beginIndex) == ' ') return beginIndex;
532 private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
533 private static int indexOfNotWS(String s, int beginIndex) {
534 if (s == null || beginIndex >= s.length()) return -1;
535 for (; beginIndex < s.length(); beginIndex++) {
536 if (s.charAt(beginIndex) != ' ') return beginIndex;
541 public class Warning {
542 protected String msg;
545 public Warning() { msg = ""; }
546 public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
548 public int getLine() { return line; }
549 public String getMessage() { return msg; }
550 public String toString() { return "WARNING Line "+line+": "+msg; }
553 public class Error extends Warning {
554 public Error() { super(); }
555 public Error(String m) { super(m); }
556 public String toString() { return "ERROR Line "+line+": "+msg; }
559 public static class JSFunctionMacro {
560 public String unbound1 = null;
561 public String unbound2 = null;
562 public String expression = null;
563 public String process(String args) {
564 String bound1 = null;
565 String bound2 = null;
566 if (unbound2 == null) {
568 return replaceAll(expression, unbound1, bound1);
570 bound1 = args.substring(0, args.indexOf(','));
571 bound2 = args.substring(args.indexOf(',') + 1);
572 return replaceAll(replaceAll(expression, unbound1, bound1), unbound2, bound2);