1 // You may modify, copy, and redistribute this code under
2 // the terms of the GNU General Public License version 2.
11 * A VERY crude, inefficient Java preprocessor
13 * //#define FOO bar baz -- replace all instances of token FOO with "bar baz"
14 * //#replace foo/bar baz/bop -- DUPLICATE everything between here and //#end,
15 * replacing foo with bar and baz with bop in the *second* copy
16 * //#switch(EXPR) -- switch on strings
20 * //#ifdef FOO -- includes contents if FOO passed as define to preprocessor
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 * Preprocessor makes use of several optional system properties:
33 * - ibex.tool.preprocessor.define
34 * - ibex.tool.preprocessor.inputdir
35 * - ibex.tool.preprocessor.outputdir
37 * @author adam@ibex.org, crawshaw@ibex.org
39 public class Preprocessor {
41 public static String replaceAll(String source, String regexp, String replaceWith) {
42 return source.replaceAll(regexp, replaceWith);
45 RE re = new RE(regexp, 0, RESyntax.RE_SYNTAX_PERL5);
46 return (String)re.substituteAll(source, replaceWith);
47 } catch (Exception e) {
54 public static void main(String[] args) throws Exception {
55 List defs = new ArrayList();
57 String define = System.getProperty("ibex.tool.preprocessor.define");
59 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
60 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
63 String inputdir = System.getProperty("ibex.tool.preprocessor.inputdir");
64 if (inputdir == null) inputdir = "src/";
66 String outputdir = System.getProperty("ibex.tool.preprocessor.outputdir");
67 if (outputdir == null) outputdir = "build/java/";
69 if (args.length == 0) {
70 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
71 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
73 // process stdin to stdout
74 Preprocessor cc = new Preprocessor(br, bw, defs);
75 Vector err = cc.process();
79 boolean errors = false;
80 for (int i=0; i < err.size(); i++) {
81 if (err.get(i) instanceof Error) errors = true; System.err.println(err.get(i)); }
82 if (errors) throw new Exception();
84 for(int i=0; i<args.length; i++) {
85 if (!args[i].endsWith(".java")) continue;
86 File source = new File(args[i]);
87 File target = new File(replaceAll(args[i], inputdir, outputdir));
88 if (target.exists() && target.lastModified() > source.lastModified()) continue;
89 System.err.println("preprocessing " + args[i]);
90 new File(target.getParent()).mkdirs();
91 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
92 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target)));
93 Preprocessor cc = new Preprocessor(br, bw, defs);
94 Vector err = cc.process();
96 boolean errors = false;
97 for (int j=0; j < err.size(); j++) {
98 if (err.get(j) instanceof Error) errors = true; System.err.println(err.get(j)); }
99 if (errors) System.exit(-1);
106 private LineNumberReader in;
107 private PrintWriter out;
109 private Hashtable replace = new Hashtable();
110 private Hashtable repeatreplace = null;
111 private Vector sinceLastRepeat = null;
112 private Vector err = new Vector();
115 private int enumSwitch = 0; // number appended to variable used in switch implementation
118 public Preprocessor(Reader reader, Writer writer, List d) {
124 public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
125 public Reader getReader() { return r; }
127 public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
128 public Writer getWriter() { return w; }
131 /** process data from reader, write to writer, return vector of errors */
132 public Vector process() throws IOException {
137 while((s = in.readLine()) != null) {
138 if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
139 String trimmed = s.trim();
141 if (trimmed.startsWith("//#define ")) {
142 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
143 err.add(new Error("#define badly formed, ignored")); continue PROCESS;
145 int keyStart = indexOfNotWS(trimmed, 9);
146 if (keyStart == -1) {
147 err.add(new Error("#define requires KEY")); continue PROCESS;
149 int keyEnd = indexOfWS(trimmed, keyStart);
151 int macroStart = trimmed.indexOf('(');
152 int macroEnd = trimmed.indexOf(')');
153 if (macroStart > keyEnd) {
154 // no macro is defined, just make sure something dumb like KEYNA)ME hasn't been done
155 if (macroEnd < keyEnd) { err.add(new Error("#define key contains invalid char: ')'")); continue PROCESS; }
156 macroStart = macroEnd = -1;
159 if (macroStart == 0) {
160 err.add(new Error("#define macro requires name")); continue PROCESS;
161 } else if (macroStart > 0) {
162 if (macroStart > macroEnd) { err.add(new Error("#define macro badly formed")); continue PROCESS; }
163 if (macroStart+1 == macroEnd) { err.add(new Error("#define macro requires property name")); continue PROCESS; }
165 JSFunctionMacro fm = new JSFunctionMacro();
166 String key = trimmed.substring(keyStart, macroStart);
167 String unbound = trimmed.substring(macroStart +1, macroEnd);
168 int unboundDiv = unbound.indexOf(',');
169 if (unboundDiv == -1) {
170 fm.unbound1 = unbound;
172 fm.unbound1 = unbound.substring(0, unboundDiv);
173 fm.unbound2 = unbound.substring(unboundDiv +1);
174 if (fm.unbound1.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
175 if (fm.unbound2.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
177 fm.expression = trimmed.substring(keyEnd).trim();
178 replace.put(key, fm);
180 String key = trimmed.substring(keyStart, keyEnd);
181 String val = trimmed.substring(keyEnd).trim();
182 replace.put(key, val);
184 out.print("\n"); // preserve line numbers
186 } else if (trimmed.startsWith("//#repeat ")) {
187 trimmed = trimmed.substring(9);
188 while(trimmed.charAt(trimmed.length() - 1) == '\\') {
189 String s2 = in.readLine().trim();
190 if (s2.startsWith("//")) s2 = s2.substring(2).trim();
191 trimmed = trimmed.substring(0, trimmed.length() - 1) + " " + s2;
192 out.print("\n"); // preserve line numbers
194 StringTokenizer st = new StringTokenizer(trimmed, " ");
195 repeatreplace = (Hashtable)replace.clone();
196 while (st.hasMoreTokens()) {
197 String tok = st.nextToken().trim();
198 String key = tok.substring(0, tok.indexOf('/'));
199 String val = tok.substring(tok.indexOf('/') + 1);
200 repeatreplace.put(key, val);
202 sinceLastRepeat = new Vector();
203 out.print("\n"); // preserve line numbers
205 } else if (trimmed.startsWith("//#end")) {
206 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
207 Hashtable save = replace;
208 replace = repeatreplace;
210 for(int i=0; i<sinceLastRepeat.size() - 1; i++) out.print(processLine((String)sinceLastRepeat.elementAt(i), true));
211 sinceLastRepeat = null;
213 } else if (trimmed.startsWith("//#ifdef")) {
214 String expr = trimmed.substring(8).trim().toUpperCase();
215 out.println(trimmed);
216 boolean useCode = defs.contains(expr);
217 for (trimmed = in.readLine().trim(); !trimmed.startsWith("//#endif"); trimmed = in.readLine().trim()) {
218 if (!useCode) out.print("// ");
219 out.print(processLine(trimmed, false));
221 out.println("//#endif "+expr);
223 } else if (trimmed.startsWith("//#switch")) {
224 int expStart = trimmed.indexOf('(') +1;
225 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
226 int expEnd = trimmed.lastIndexOf(')');
227 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
228 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
229 String expr = trimmed.substring(expStart, expEnd);
231 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+"); ");
232 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
234 Hashtable[] byLength = new Hashtable[255];
236 String Default = null;
237 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
238 if (trimmed.startsWith("default:")) {
239 Default = processLine(trimmed.substring(8), false);
242 if (trimmed.startsWith("case ")) {
244 int strStart = trimmed.indexOf('\"') +1;
245 if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
246 int strEnd = trimmed.indexOf('\"', strStart);
247 if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
248 key = trimmed.substring(strStart, strEnd);
250 Hashtable thisCase = (Hashtable)byLength[key.length()];
251 if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
252 thisCase.put(key, "");
254 // find end of case definition
255 int caseEnd = trimmed.indexOf(':', strEnd) +1;
256 if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
257 trimmed = trimmed.substring(caseEnd);
261 Hashtable hash = byLength[key.length()];
262 hash.put(key, (String)hash.get(key) + replaceAll(processLine(trimmed, false), "//[^\"]*$", "").trim() + "\n");
264 out.print(processLine(trimmed, false));
268 for(int i=0; i<255; i++) {
269 if (byLength[i] == null) continue;
270 out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) { ");
271 buildTrie("", byLength[i]);
272 out.print("}; break; } ");
274 out.print("} /* switch */ ");
275 if (Default != null) out.print(" " + Default);
276 out.print(" } while(false); /* OUTER */\n");
280 out.print(processLine(s, false));
287 private static class MyVec {
288 private Object[] store;
289 private int size = 0;
291 public MyVec() { this(10); }
292 public MyVec(int i) { store = new Object[i]; }
293 public MyVec(int i, Object[] store) { size = i; this.store = store; }
295 private void grow() { grow(store.length * 2); }
296 private void grow(int newsize) {
297 Object[] newstore = new Object[newsize];
298 System.arraycopy(store, 0, newstore, 0, size);
302 public void removeAllElements() {
303 for(int i=0; i<size; i++) store[i] = null;
307 public void toArray(Object[] o) {
308 for(int i=0; i<size; i++)
312 public int indexOf(Object o) {
313 for(int i=0; i<size; i++)
314 if (o == null ? store[i] == null : store[i].equals(o)) return i;
319 public void addElement(Object o) {
320 if (size >= store.length - 1) grow();
324 public Object peek() {
325 return lastElement();
328 public Object elementAt(int i) {
332 public Object lastElement() {
333 if (size == 0) return null;
334 return store[size - 1];
337 public void push(Object o) { addElement(o); }
338 public Object pop() {
339 Object ret = lastElement();
340 if (size > 0) store[size--] = null;
344 public int size() { return size; }
346 public void setSize(int newSize) {
347 if (newSize < 0) throw new RuntimeException("tried to set size to negative value");
348 if (newSize > store.length) grow(newSize * 2);
350 for(int i=newSize; i<size; i++)
355 public void copyInto(Object[] out) {
356 for(int i=0; i<size; i++)
360 public void fromArray(Object[] in) {
362 for(int i=0; i<size; i++)
366 public void removeElementAt(int i) {
367 if (i >= size || i < 0) throw new RuntimeException("tried to remove an element outside the vector's limits");
368 for(int j=i; j<size - 1; j++)
369 store[j] = store[j + 1];
373 public void setElementAt(Object o, int i) {
374 if (i >= size) setSize(i);
378 public void removeElement(Object o) {
379 int idx = indexOf(o);
380 if (idx != -1) removeElementAt(idx);
383 public void insertElementAt(Object o, int at) {
384 if (size == store.length) grow();
385 for(int i=size; i>at; i--)
386 store[i] = store[i-1];
391 public interface CompareFunc {
392 public int compare(Object a, Object b);
395 public void sort(CompareFunc c) {
396 sort(this, null, c, 0, size-1);
399 public static void sort(MyVec a, MyVec b, CompareFunc c) {
400 if (b != null && a.size != b.size) throw new IllegalArgumentException("MyVec a and b must be of equal size");
401 sort(a, b, c, 0, a.size-1);
404 private static final void sort(MyVec a, MyVec b, CompareFunc c, int start, int end) {
405 Object tmpa, tmpb = null;
406 if(start >= end) return;
408 for(int i=start+1;i<=end;i++) {
410 if (b != null) tmpb = b.store[i];
412 for(j=i-1;j>=start;j--) {
413 if(c.compare(a.store[j],tmpa) <= 0) break;
414 a.store[j+1] = a.store[j];
415 if (b != null) b.store[j+1] = b.store[j];
418 if (b != null) b.store[j+1] = tmpb;
423 Object pivot = a.store[end];
428 while(c.compare(a.store[++lo],pivot) < 0) { }
429 while((hi > lo) && c.compare(a.store[--hi],pivot) > 0) { }
431 if (b != null) swap(b, lo,hi);
435 if (b != null) swap(b, lo,end);
437 sort(a, b, c, start, lo-1);
438 sort(a, b, c, lo+1, end);
441 private static final void swap(MyVec vec, int a, int b) {
443 Object tmp = vec.store[a];
444 vec.store[a] = vec.store[b];
451 private void buildTrie(String prefix, Hashtable cases) {
452 Enumeration caseKeys = cases.keys();
453 MyVec keys = new MyVec();
454 while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
455 keys.sort(new MyVec.CompareFunc() { public int compare(Object a, Object b) {
456 return ((String)a).compareTo((String)b);
459 for(int i=0; i<keys.size(); i++) {
460 if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
461 String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
462 if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
463 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
464 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
465 buildTrie(prefixPlusOne, cases);
466 out.print("} break; } ");
467 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
468 if (i<keys.size()) { i--; continue; }
470 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
471 String code = (String)cases.get(keys.elementAt(i));
472 code = code.substring(0, code.length());
473 String key = (String)keys.elementAt(i);
474 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break; ");
479 private String processLine(String s, boolean deleteLineEndings) throws IOException {
480 if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
482 for(int i=0; i<s.length(); i++) {
483 char c = s.charAt(i);
484 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
489 for(j = i; j < s.length(); j++) {
491 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
493 String tok = s.substring(i, j);
494 Object val = replace.get(tok);
498 } else if (val instanceof JSFunctionMacro) {
499 if (s.charAt(j) != '(') { ret += tok; i = j - 1; continue; }
500 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
501 i = s.indexOf(')', j);
507 if (!deleteLineEndings) ret += "\n";
511 private static int indexOfWS(String s) { return indexOfWS(s, 0); }
512 private static int indexOfWS(String s, int beginIndex) {
513 if (s == null || beginIndex >= s.length()) return -1;
514 for (; beginIndex < s.length(); beginIndex++) {
515 if (s.charAt(beginIndex) == ' ') return beginIndex;
520 private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
521 private static int indexOfNotWS(String s, int beginIndex) {
522 if (s == null || beginIndex >= s.length()) return -1;
523 for (; beginIndex < s.length(); beginIndex++) {
524 if (s.charAt(beginIndex) != ' ') return beginIndex;
529 public class Warning {
530 protected String msg;
533 public Warning() { msg = ""; }
534 public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
536 public String toString() { return "WARNING Line "+line+": "+msg; }
539 public class Error extends Warning {
540 public Error() { super(); }
541 public Error(String m) { super(m); }
542 public String toString() { return "ERROR Line "+line+": "+msg; }
545 public static class JSFunctionMacro {
546 public String unbound1 = null;
547 public String unbound2 = null;
548 public String expression = null;
549 public String process(String args) {
550 String bound1 = null;
551 String bound2 = null;
552 if (unbound2 == null) {
554 return replaceAll(expression, unbound1, bound1);
556 bound1 = args.substring(0, args.indexOf(','));
557 bound2 = args.substring(args.indexOf(',') + 1);
558 return replaceAll(replaceAll(expression, unbound1, bound1), unbound2, bound2);