1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
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
10 //import gnu.regexp.*;
15 * A VERY crude, inefficient Java preprocessor
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
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:
29 * - all other non-whitespace characters
31 public class Preprocessor {
33 public static String replaceAll(String source, String regexp, String replaceWith) {
34 return source.replaceAll(regexp, replaceWith);
37 RE re = new RE(regexp, 0, RESyntax.RE_SYNTAX_PERL5);
38 return (String)re.substituteAll(source, replaceWith);
39 } catch (Exception e) {
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));
51 // process stdin to stdout
52 Preprocessor cc = new Preprocessor(br, bw);
53 Vector err = cc.process();
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();
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();
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);
84 private LineNumberReader in;
85 private PrintWriter out;
87 private Hashtable replace = new Hashtable();
88 private Hashtable repeatreplace = null;
89 private Vector sinceLastRepeat = null;
90 private Vector err = new Vector();
92 private int enumSwitch = 0; // number appended to variable used in switch implementation
95 public Preprocessor(Reader reader, Writer writer) {
100 public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
101 public Reader getReader() { return r; }
103 public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
104 public Writer getWriter() { return w; }
107 /** process data from reader, write to writer, return vector of errors */
108 public Vector process() throws IOException {
113 while((s = in.readLine()) != null) {
114 if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
115 String trimmed = s.trim();
117 if (trimmed.startsWith("//#define ")) {
118 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
119 err.add(new Error("#define badly formed, ignored")); continue PROCESS;
121 int keyStart = indexOfNotWS(trimmed, 9);
122 if (keyStart == -1) {
123 err.add(new Error("#define requires KEY")); continue PROCESS;
125 int keyEnd = indexOfWS(trimmed, keyStart);
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;
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; }
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;
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; }
153 fm.expression = trimmed.substring(keyEnd).trim();
154 replace.put(key, fm);
156 String key = trimmed.substring(keyStart, keyEnd);
157 String val = trimmed.substring(keyEnd).trim();
158 replace.put(key, val);
160 out.print("\n"); // preserve line numbers
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
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);
178 sinceLastRepeat = new Vector();
179 out.print("\n"); // preserve line numbers
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;
186 for(int i=0; i<sinceLastRepeat.size() - 1; i++) out.print(processLine((String)sinceLastRepeat.elementAt(i), true));
187 sinceLastRepeat = null;
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);
198 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+"); ");
199 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
201 Hashtable[] byLength = new Hashtable[255];
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);
209 if (trimmed.startsWith("case ")) {
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);
217 Hashtable thisCase = (Hashtable)byLength[key.length()];
218 if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
219 thisCase.put(key, "");
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);
228 Hashtable hash = byLength[key.length()];
229 hash.put(key, (String)hash.get(key) + replaceAll(processLine(trimmed, false), "//[^\"]*$", "").trim() + "\n");
231 out.print(processLine(trimmed, false));
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; } ");
241 out.print("} /* switch */ ");
242 if (Default != null) out.print(" " + Default);
243 out.print(" } while(false); /* OUTER */\n");
247 out.print(processLine(s, false));
254 private static class MyVec {
255 private Object[] store;
256 private int size = 0;
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; }
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);
269 public void removeAllElements() {
270 for(int i=0; i<size; i++) store[i] = null;
274 public void toArray(Object[] o) {
275 for(int i=0; i<size; i++)
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;
286 public void addElement(Object o) {
287 if (size >= store.length - 1) grow();
291 public Object peek() {
292 return lastElement();
295 public Object elementAt(int i) {
299 public Object lastElement() {
300 if (size == 0) return null;
301 return store[size - 1];
304 public void push(Object o) { addElement(o); }
305 public Object pop() {
306 Object ret = lastElement();
307 if (size > 0) store[size--] = null;
311 public int size() { return size; }
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);
317 for(int i=newSize; i<size; i++)
322 public void copyInto(Object[] out) {
323 for(int i=0; i<size; i++)
327 public void fromArray(Object[] in) {
329 for(int i=0; i<size; i++)
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];
340 public void setElementAt(Object o, int i) {
341 if (i >= size) setSize(i);
345 public void removeElement(Object o) {
346 int idx = indexOf(o);
347 if (idx != -1) removeElementAt(idx);
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];
358 public interface CompareFunc {
359 public int compare(Object a, Object b);
362 public void sort(CompareFunc c) {
363 sort(this, null, c, 0, size-1);
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);
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;
375 for(int i=start+1;i<=end;i++) {
377 if (b != null) tmpb = b.store[i];
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];
385 if (b != null) b.store[j+1] = tmpb;
390 Object pivot = a.store[end];
395 while(c.compare(a.store[++lo],pivot) < 0) { }
396 while((hi > lo) && c.compare(a.store[--hi],pivot) > 0) { }
398 if (b != null) swap(b, lo,hi);
402 if (b != null) swap(b, lo,end);
404 sort(a, b, c, start, lo-1);
405 sort(a, b, c, lo+1, end);
408 private static final void swap(MyVec vec, int a, int b) {
410 Object tmp = vec.store[a];
411 vec.store[a] = vec.store[b];
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);
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; }
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; ");
446 private String processLine(String s, boolean deleteLineEndings) throws IOException {
447 if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
449 for(int i=0; i<s.length(); i++) {
450 char c = s.charAt(i);
451 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
456 for(j = i; j < s.length(); j++) {
458 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
460 String tok = s.substring(i, j);
461 Object val = replace.get(tok);
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);
474 if (!deleteLineEndings) ret += "\n";
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;
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;
496 public class Warning {
497 protected String msg;
500 public Warning() { msg = ""; }
501 public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
503 public String toString() { return "WARNING Line "+line+": "+msg; }
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; }
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) {
521 return replaceAll(expression, unbound1, bound1);
523 bound1 = args.substring(0, args.indexOf(','));
524 bound2 = args.substring(args.indexOf(',') + 1);
525 return replaceAll(replaceAll(expression, unbound1, bound1), unbound2, bound2);