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 repeatreplace = 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 repeatreplace = (Hashtable)replace.clone();
200 while (st.hasMoreTokens()) {
201 String tok = st.nextToken().trim();
202 String key = tok.substring(0, tok.indexOf('/'));
203 String val = tok.substring(tok.indexOf('/') + 1);
204 repeatreplace.put(key, val);
206 sinceLastRepeat = new Vector();
207 out.print("\n"); // preserve line numbers
209 } else if (trimmed.startsWith("//#end")) {
210 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
211 Hashtable save = replace;
212 replace = repeatreplace;
214 for(int i=0; i<sinceLastRepeat.size() - 1; i++) out.print(processLine((String)sinceLastRepeat.elementAt(i), true));
215 sinceLastRepeat = null;
217 } else if (trimmed.startsWith("//#ifdef")) {
218 String expr = trimmed.substring(8).trim().toUpperCase();
219 out.println(trimmed);
220 boolean useCode = defs.contains(expr);
221 for (trimmed = in.readLine().trim(); !trimmed.startsWith("//#endif"); trimmed = in.readLine().trim()) {
222 if (trimmed.startsWith("//#else")) useCode = !useCode;
223 else if (!useCode) out.print("// ");
224 out.print(processLine(trimmed, false));
226 out.println("//#endif "+expr);
228 } else if (trimmed.startsWith("//#switch")) {
229 int expStart = trimmed.indexOf('(') +1;
230 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
231 int expEnd = trimmed.lastIndexOf(')');
232 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
233 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
234 String expr = trimmed.substring(expStart, expEnd);
236 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+"); ");
237 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
239 Hashtable[] byLength = new Hashtable[255];
241 String Default = null;
242 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
243 if (trimmed.startsWith("default:")) {
244 Default = processLine(trimmed.substring(8), false);
247 if (trimmed.startsWith("case ")) {
249 int strStart = trimmed.indexOf('\"') +1;
250 if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
251 int strEnd = trimmed.indexOf('\"', strStart);
252 if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
253 key = trimmed.substring(strStart, strEnd);
255 Hashtable thisCase = (Hashtable)byLength[key.length()];
256 if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
257 thisCase.put(key, "");
259 // find end of case definition
260 int caseEnd = trimmed.indexOf(':', strEnd) +1;
261 if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
262 trimmed = trimmed.substring(caseEnd);
266 Hashtable hash = byLength[key.length()];
267 hash.put(key, (String)hash.get(key) + replaceAll(processLine(trimmed, false), "//[^\"]*$", "").trim() + "\n");
269 out.print(processLine(trimmed, false));
273 for(int i=0; i<255; i++) {
274 if (byLength[i] == null) continue;
275 out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) { ");
276 buildTrie("", byLength[i]);
277 out.print("}; break; } ");
279 out.print("} /* switch */ ");
280 if (Default != null) out.print(" " + Default);
281 out.print(" } while(false); /* OUTER */\n");
285 out.print(processLine(s, false));
292 private static class MyVec {
293 private Object[] store;
294 private int size = 0;
296 public MyVec() { this(10); }
297 public MyVec(int i) { store = new Object[i]; }
298 public MyVec(int i, Object[] store) { size = i; this.store = store; }
300 private void grow() { grow(store.length * 2); }
301 private void grow(int newsize) {
302 Object[] newstore = new Object[newsize];
303 System.arraycopy(store, 0, newstore, 0, size);
307 public void removeAllElements() {
308 for(int i=0; i<size; i++) store[i] = null;
312 public void toArray(Object[] o) {
313 for(int i=0; i<size; i++)
317 public int indexOf(Object o) {
318 for(int i=0; i<size; i++)
319 if (o == null ? store[i] == null : store[i].equals(o)) return i;
324 public void addElement(Object o) {
325 if (size >= store.length - 1) grow();
329 public Object peek() {
330 return lastElement();
333 public Object elementAt(int i) {
337 public Object lastElement() {
338 if (size == 0) return null;
339 return store[size - 1];
342 public void push(Object o) { addElement(o); }
343 public Object pop() {
344 Object ret = lastElement();
345 if (size > 0) store[size--] = null;
349 public int size() { return size; }
351 public void setSize(int newSize) {
352 if (newSize < 0) throw new RuntimeException("tried to set size to negative value");
353 if (newSize > store.length) grow(newSize * 2);
355 for(int i=newSize; i<size; i++)
360 public void copyInto(Object[] out) {
361 for(int i=0; i<size; i++)
365 public void fromArray(Object[] in) {
367 for(int i=0; i<size; i++)
371 public void removeElementAt(int i) {
372 if (i >= size || i < 0) throw new RuntimeException("tried to remove an element outside the vector's limits");
373 for(int j=i; j<size - 1; j++)
374 store[j] = store[j + 1];
378 public void setElementAt(Object o, int i) {
379 if (i >= size) setSize(i);
383 public void removeElement(Object o) {
384 int idx = indexOf(o);
385 if (idx != -1) removeElementAt(idx);
388 public void insertElementAt(Object o, int at) {
389 if (size == store.length) grow();
390 for(int i=size; i>at; i--)
391 store[i] = store[i-1];
396 public interface CompareFunc {
397 public int compare(Object a, Object b);
400 public void sort(CompareFunc c) {
401 sort(this, null, c, 0, size-1);
404 public static void sort(MyVec a, MyVec b, CompareFunc c) {
405 if (b != null && a.size != b.size) throw new IllegalArgumentException("MyVec a and b must be of equal size");
406 sort(a, b, c, 0, a.size-1);
409 private static final void sort(MyVec a, MyVec b, CompareFunc c, int start, int end) {
410 Object tmpa, tmpb = null;
411 if(start >= end) return;
413 for(int i=start+1;i<=end;i++) {
415 if (b != null) tmpb = b.store[i];
417 for(j=i-1;j>=start;j--) {
418 if(c.compare(a.store[j],tmpa) <= 0) break;
419 a.store[j+1] = a.store[j];
420 if (b != null) b.store[j+1] = b.store[j];
423 if (b != null) b.store[j+1] = tmpb;
428 Object pivot = a.store[end];
433 while(c.compare(a.store[++lo],pivot) < 0) { }
434 while((hi > lo) && c.compare(a.store[--hi],pivot) > 0) { }
436 if (b != null) swap(b, lo,hi);
440 if (b != null) swap(b, lo,end);
442 sort(a, b, c, start, lo-1);
443 sort(a, b, c, lo+1, end);
446 private static final void swap(MyVec vec, int a, int b) {
448 Object tmp = vec.store[a];
449 vec.store[a] = vec.store[b];
456 private void buildTrie(String prefix, Hashtable cases) {
457 Enumeration caseKeys = cases.keys();
458 MyVec keys = new MyVec();
459 while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
460 keys.sort(new MyVec.CompareFunc() { public int compare(Object a, Object b) {
461 return ((String)a).compareTo((String)b);
464 for(int i=0; i<keys.size(); i++) {
465 if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
466 String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
467 if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
468 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
469 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
470 buildTrie(prefixPlusOne, cases);
471 out.print("} break; } ");
472 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
473 if (i<keys.size()) { i--; continue; }
475 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
476 String code = (String)cases.get(keys.elementAt(i));
477 code = code.substring(0, code.length());
478 String key = (String)keys.elementAt(i);
479 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break; ");
484 private String processLine(String s, boolean deleteLineEndings) throws IOException {
485 if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
487 for(int i=0; i<s.length(); i++) {
488 char c = s.charAt(i);
489 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
494 for(j = i; j < s.length(); j++) {
496 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
498 String tok = s.substring(i, j);
499 Object val = replace.get(tok);
503 } else if (val instanceof JSFunctionMacro) {
504 if (s.charAt(j) != '(') { ret += tok; i = j - 1; continue; }
505 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
506 i = s.indexOf(')', j);
512 if (!deleteLineEndings) ret += "\n";
516 private static int indexOfWS(String s) { return indexOfWS(s, 0); }
517 private static int indexOfWS(String s, int beginIndex) {
518 if (s == null || beginIndex >= s.length()) return -1;
519 for (; beginIndex < s.length(); beginIndex++) {
520 if (s.charAt(beginIndex) == ' ') return beginIndex;
525 private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
526 private static int indexOfNotWS(String s, int beginIndex) {
527 if (s == null || beginIndex >= s.length()) return -1;
528 for (; beginIndex < s.length(); beginIndex++) {
529 if (s.charAt(beginIndex) != ' ') return beginIndex;
534 public class Warning {
535 protected String msg;
538 public Warning() { msg = ""; }
539 public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
541 public int getLine() { return line; }
542 public String getMessage() { return msg; }
543 public String toString() { return "WARNING Line "+line+": "+msg; }
546 public class Error extends Warning {
547 public Error() { super(); }
548 public Error(String m) { super(m); }
549 public String toString() { return "ERROR Line "+line+": "+msg; }
552 public static class JSFunctionMacro {
553 public String unbound1 = null;
554 public String unbound2 = null;
555 public String expression = null;
556 public String process(String args) {
557 String bound1 = null;
558 String bound2 = null;
559 if (unbound2 == null) {
561 return replaceAll(expression, unbound1, bound1);
563 bound1 = args.substring(0, args.indexOf(','));
564 bound2 = args.substring(args.indexOf(',') + 1);
565 return replaceAll(replaceAll(expression, unbound1, bound1), unbound2, bound2);