1 // You may modify, copy, and redistribute this code under the terms of
2 // the GNU Library Public License version 2.1, with the exception of
3 // the portion of clause 6a after the semicolon (aka the "obnoxious
13 * A VERY crude, inefficient Java preprocessor
15 * //#define FOO bar baz -- replace all instances of token FOO with "bar baz"
16 * //#replace foo/bar baz/bop -- DUPLICATE everything between here and //#end,
17 * replacing foo with bar and baz with bop in the *second* copy
18 * //#switch(EXPR) -- switch on strings
22 * //#ifdef FOO -- includes contents if FOO passed as define to preprocessor
28 * Replacements are done on a token basis. Tokens are defined as a
29 * sequence of characters which all belong to a single class. The
30 * two character classes are:
33 * - all other non-whitespace characters
35 * Preprocessor makes use of several optional system properties:
37 * - ibex.tool.preprocessor.define
38 * - ibex.tool.preprocessor.inputdir
39 * - ibex.tool.preprocessor.outputdir
41 * @author adam@ibex.org, crawshaw@ibex.org
43 public class Preprocessor {
45 public static String replaceAll(String source, String regexp, String replaceWith) {
46 return source.replaceAll(regexp, replaceWith);
49 RE re = new RE(regexp, 0, RESyntax.RE_SYNTAX_PERL5);
50 return (String)re.substituteAll(source, replaceWith);
51 } catch (Exception e) {
58 public static void main(String[] args) throws Exception {
59 List defs = new ArrayList();
61 String define = System.getProperty("ibex.tool.preprocessor.define");
63 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
64 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
67 String inputdir = System.getProperty("ibex.tool.preprocessor.inputdir");
68 if (inputdir == null) inputdir = "src/";
70 String outputdir = System.getProperty("ibex.tool.preprocessor.outputdir");
71 if (outputdir == null) outputdir = "build/java/";
73 if (args.length == 0) {
74 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
75 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
77 // process stdin to stdout
78 Preprocessor cc = new Preprocessor(br, bw, defs);
79 Vector err = cc.process();
83 boolean errors = false;
84 for (int i=0; i < err.size(); i++) {
85 if (err.get(i) instanceof Error) errors = true; System.err.println(err.get(i)); }
86 if (errors) throw new Exception();
88 for(int i=0; i<args.length; i++) {
89 if (!args[i].endsWith(".java")) continue;
90 File source = new File(args[i]);
91 File target = new File(replaceAll(args[i], inputdir, outputdir));
92 if (target.exists() && target.lastModified() > source.lastModified()) continue;
93 System.err.println("preprocessing " + args[i]);
94 new File(target.getParent()).mkdirs();
95 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
96 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target)));
97 Preprocessor cc = new Preprocessor(br, bw, defs);
98 Vector err = cc.process();
100 boolean errors = false;
101 for (int j=0; j < err.size(); j++) {
102 if (err.get(j) instanceof Error) errors = true; System.err.println(err.get(j)); }
103 if (errors) System.exit(-1);
110 private LineNumberReader in;
111 private PrintWriter out;
113 private Hashtable replace = new Hashtable();
114 private Hashtable[] repeatreplaces = null;
115 private Vector sinceLastRepeat = null;
116 private Vector err = new Vector();
119 private int enumSwitch = 0; // number appended to variable used in switch implementation
122 public Preprocessor(Reader reader, Writer writer, List d) {
128 public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
129 public Reader getReader() { return r; }
131 public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
132 public Writer getWriter() { return w; }
135 /** process data from reader, write to writer, return vector of errors */
136 public Vector process() throws IOException {
141 while((s = in.readLine()) != null) {
142 if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
143 String trimmed = s.trim();
145 if (trimmed.startsWith("//#define ")) {
146 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
147 err.add(new Error("#define badly formed, ignored")); continue PROCESS;
149 int keyStart = indexOfNotWS(trimmed, 9);
150 if (keyStart == -1) {
151 err.add(new Error("#define requires KEY")); continue PROCESS;
153 int keyEnd = indexOfWS(trimmed, keyStart);
155 int macroStart = trimmed.indexOf('(');
156 int macroEnd = trimmed.indexOf(')');
157 if (macroStart > keyEnd) {
158 // no macro is defined, just make sure something dumb like KEYNA)ME hasn't been done
159 if (macroEnd < keyEnd) { err.add(new Error("#define key contains invalid char: ')'")); continue PROCESS; }
160 macroStart = macroEnd = -1;
163 if (macroStart == 0) {
164 err.add(new Error("#define macro requires name")); continue PROCESS;
165 } else if (macroStart > 0) {
166 if (macroStart > macroEnd) { err.add(new Error("#define macro badly formed")); continue PROCESS; }
167 if (macroStart+1 == macroEnd) { err.add(new Error("#define macro requires property name")); continue PROCESS; }
169 JSFunctionMacro fm = new JSFunctionMacro();
170 String key = trimmed.substring(keyStart, macroStart);
171 String unbound = trimmed.substring(macroStart +1, macroEnd);
172 int unboundDiv = unbound.indexOf(',');
173 if (unboundDiv == -1) {
174 fm.unbound1 = unbound;
176 fm.unbound1 = unbound.substring(0, unboundDiv);
177 fm.unbound2 = unbound.substring(unboundDiv +1);
178 if (fm.unbound1.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
179 if (fm.unbound2.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
181 fm.expression = trimmed.substring(keyEnd).trim();
182 replace.put(key, fm);
184 String key = trimmed.substring(keyStart, keyEnd);
185 String val = trimmed.substring(keyEnd).trim();
186 replace.put(key, val);
188 out.print("\n"); // preserve line numbers
190 } else if (trimmed.startsWith("//#repeat ")) {
191 trimmed = trimmed.substring(9);
192 while(trimmed.charAt(trimmed.length() - 1) == '\\') {
193 String s2 = in.readLine().trim();
194 if (s2.startsWith("//")) s2 = s2.substring(2).trim();
195 trimmed = trimmed.substring(0, trimmed.length() - 1) + " " + s2;
196 out.print("\n"); // preserve line numbers
198 StringTokenizer st = new StringTokenizer(trimmed, " ");
199 repeatreplaces = null;
200 while (st.hasMoreTokens()) {
201 String tok = st.nextToken().trim();
202 String key = tok.substring(0, tok.indexOf('/'));
203 String vals = tok.substring(tok.indexOf('/') + 1);
204 StringTokenizer st2 = new StringTokenizer(vals,"/");
205 if(repeatreplaces == null) {
206 repeatreplaces = new Hashtable[st2.countTokens()];
207 for(int i=0;i<repeatreplaces.length;i++) repeatreplaces[i] = (Hashtable) replace.clone();
209 for(int i=0;st2.hasMoreTokens() && i<repeatreplaces.length;i++)
210 repeatreplaces[i].put(key, st2.nextToken());
212 sinceLastRepeat = new Vector();
213 out.print("\n"); // preserve line numbers
215 } else if (trimmed.startsWith("//#end")) {
216 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
217 Hashtable save = replace;
219 for(int i=0;i<repeatreplaces.length;i++) {
220 replace = repeatreplaces[i];
221 for(int j=0; j<sinceLastRepeat.size() - 1; j++) out.print(processLine((String)sinceLastRepeat.elementAt(j), true));
223 sinceLastRepeat = null;
225 } else if (trimmed.startsWith("//#ifdef")) {
226 String expr = trimmed.substring(8).trim().toUpperCase();
227 out.println(trimmed);
228 boolean useCode = defs.contains(expr);
229 for (trimmed = in.readLine().trim(); !trimmed.startsWith("//#endif"); trimmed = in.readLine().trim()) {
230 if (trimmed.startsWith("//#else")) useCode = !useCode;
231 else if (!useCode) out.print("// ");
232 out.print(processLine(trimmed, false));
234 out.println("//#endif "+expr);
236 } else if (trimmed.startsWith("//#switch")) {
237 int expStart = trimmed.indexOf('(') +1;
238 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
239 int expEnd = trimmed.lastIndexOf(')');
240 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
241 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
242 String expr = trimmed.substring(expStart, expEnd);
244 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+"); ");
245 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
247 Hashtable[] byLength = new Hashtable[255];
249 String Default = null;
250 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
251 if (trimmed.startsWith("default:")) {
252 Default = processLine(trimmed.substring(8), false);
255 if (trimmed.startsWith("case ")) {
257 int strStart = trimmed.indexOf('\"') +1;
258 if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
259 int strEnd = trimmed.indexOf('\"', strStart);
260 if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
261 key = trimmed.substring(strStart, strEnd);
263 Hashtable thisCase = (Hashtable)byLength[key.length()];
264 if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
265 thisCase.put(key, "");
267 // find end of case definition
268 int caseEnd = trimmed.indexOf(':', strEnd) +1;
269 if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
270 trimmed = trimmed.substring(caseEnd);
274 Hashtable hash = byLength[key.length()];
275 hash.put(key, (String)hash.get(key) + replaceAll(processLine(trimmed, false), "//[^\"]*$", "").trim() + "\n");
277 out.print(processLine(trimmed, false));
281 for(int i=0; i<255; i++) {
282 if (byLength[i] == null) continue;
283 out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) { ");
284 buildTrie("", byLength[i]);
285 out.print("}; break; } ");
287 out.print("} /* switch */ ");
288 if (Default != null) out.print(" " + Default);
289 out.print(" } while(false); /* OUTER */\n");
293 out.print(processLine(s, false));
300 private static class MyVec {
301 private Object[] store;
302 private int size = 0;
304 public MyVec() { this(10); }
305 public MyVec(int i) { store = new Object[i]; }
306 public MyVec(int i, Object[] store) { size = i; this.store = store; }
308 private void grow() { grow(store.length * 2); }
309 private void grow(int newsize) {
310 Object[] newstore = new Object[newsize];
311 System.arraycopy(store, 0, newstore, 0, size);
315 public void removeAllElements() {
316 for(int i=0; i<size; i++) store[i] = null;
320 public void toArray(Object[] o) {
321 for(int i=0; i<size; i++)
325 public int indexOf(Object o) {
326 for(int i=0; i<size; i++)
327 if (o == null ? store[i] == null : store[i].equals(o)) return i;
332 public void addElement(Object o) {
333 if (size >= store.length - 1) grow();
337 public Object peek() {
338 return lastElement();
341 public Object elementAt(int i) {
345 public Object lastElement() {
346 if (size == 0) return null;
347 return store[size - 1];
350 public void push(Object o) { addElement(o); }
351 public Object pop() {
352 Object ret = lastElement();
353 if (size > 0) store[size--] = null;
357 public int size() { return size; }
359 public void setSize(int newSize) {
360 if (newSize < 0) throw new RuntimeException("tried to set size to negative value");
361 if (newSize > store.length) grow(newSize * 2);
363 for(int i=newSize; i<size; i++)
368 public void copyInto(Object[] out) {
369 for(int i=0; i<size; i++)
373 public void fromArray(Object[] in) {
375 for(int i=0; i<size; i++)
379 public void removeElementAt(int i) {
380 if (i >= size || i < 0) throw new RuntimeException("tried to remove an element outside the vector's limits");
381 for(int j=i; j<size - 1; j++)
382 store[j] = store[j + 1];
386 public void setElementAt(Object o, int i) {
387 if (i >= size) setSize(i);
391 public void removeElement(Object o) {
392 int idx = indexOf(o);
393 if (idx != -1) removeElementAt(idx);
396 public void insertElementAt(Object o, int at) {
397 if (size == store.length) grow();
398 for(int i=size; i>at; i--)
399 store[i] = store[i-1];
404 public interface CompareFunc {
405 public int compare(Object a, Object b);
408 public void sort(CompareFunc c) {
409 sort(this, null, c, 0, size-1);
412 public static void sort(MyVec a, MyVec b, CompareFunc c) {
413 if (b != null && a.size != b.size) throw new IllegalArgumentException("MyVec a and b must be of equal size");
414 sort(a, b, c, 0, a.size-1);
417 private static final void sort(MyVec a, MyVec b, CompareFunc c, int start, int end) {
418 Object tmpa, tmpb = null;
419 if(start >= end) return;
421 for(int i=start+1;i<=end;i++) {
423 if (b != null) tmpb = b.store[i];
425 for(j=i-1;j>=start;j--) {
426 if(c.compare(a.store[j],tmpa) <= 0) break;
427 a.store[j+1] = a.store[j];
428 if (b != null) b.store[j+1] = b.store[j];
431 if (b != null) b.store[j+1] = tmpb;
436 Object pivot = a.store[end];
441 while(c.compare(a.store[++lo],pivot) < 0) { }
442 while((hi > lo) && c.compare(a.store[--hi],pivot) > 0) { }
444 if (b != null) swap(b, lo,hi);
448 if (b != null) swap(b, lo,end);
450 sort(a, b, c, start, lo-1);
451 sort(a, b, c, lo+1, end);
454 private static final void swap(MyVec vec, int a, int b) {
456 Object tmp = vec.store[a];
457 vec.store[a] = vec.store[b];
464 private void buildTrie(String prefix, Hashtable cases) {
465 Enumeration caseKeys = cases.keys();
466 MyVec keys = new MyVec();
467 while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
468 keys.sort(new MyVec.CompareFunc() { public int compare(Object a, Object b) {
469 return ((String)a).compareTo((String)b);
472 for(int i=0; i<keys.size(); i++) {
473 if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
474 String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
475 if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
476 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
477 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
478 buildTrie(prefixPlusOne, cases);
479 out.print("} break; } ");
480 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
481 if (i<keys.size()) { i--; continue; }
483 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
484 String code = (String)cases.get(keys.elementAt(i));
485 code = code.substring(0, code.length());
486 String key = (String)keys.elementAt(i);
487 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break; ");
492 private String processLine(String s, boolean deleteLineEndings) throws IOException {
493 if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
495 for(int i=0; i<s.length(); i++) {
496 char c = s.charAt(i);
497 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
502 for(j = i; j < s.length(); j++) {
504 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
506 String tok = s.substring(i, j);
507 Object val = replace.get(tok);
511 } else if (val instanceof JSFunctionMacro) {
512 if (s.charAt(j) != '(') { ret += tok; i = j - 1; continue; }
513 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
514 i = s.indexOf(')', j);
520 if (!deleteLineEndings) ret += "\n";
524 private static int indexOfWS(String s) { return indexOfWS(s, 0); }
525 private static int indexOfWS(String s, int beginIndex) {
526 if (s == null || beginIndex >= s.length()) return -1;
527 for (; beginIndex < s.length(); beginIndex++) {
528 if (s.charAt(beginIndex) == ' ') return beginIndex;
533 private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
534 private static int indexOfNotWS(String s, int beginIndex) {
535 if (s == null || beginIndex >= s.length()) return -1;
536 for (; beginIndex < s.length(); beginIndex++) {
537 if (s.charAt(beginIndex) != ' ') return beginIndex;
542 public class Warning {
543 protected String msg;
546 public Warning() { msg = ""; }
547 public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
549 public int getLine() { return line; }
550 public String getMessage() { return msg; }
551 public String toString() { return "WARNING Line "+line+": "+msg; }
554 public class Error extends Warning {
555 public Error() { super(); }
556 public Error(String m) { super(m); }
557 public String toString() { return "ERROR Line "+line+": "+msg; }
560 public static class JSFunctionMacro {
561 public String unbound1 = null;
562 public String unbound2 = null;
563 public String expression = null;
564 public String process(String args) {
565 String bound1 = null;
566 String bound2 = null;
567 if (unbound2 == null) {
569 return replaceAll(expression, unbound1, bound1);
571 bound1 = args.substring(0, args.indexOf(','));
572 bound2 = args.substring(args.indexOf(',') + 1);
573 return replaceAll(replaceAll(expression, unbound1, bound1), unbound2, bound2);