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
14 * A VERY crude, inefficient Java preprocessor
16 * //#define FOO bar baz -- replace all instances of token FOO with "bar baz"
17 * //#replace foo/bar baz/bop -- DUPLICATE everything between here and //#end,
18 * replacing foo with bar and baz with bop in the *second* copy
19 * //#switch(EXPR) -- switch on strings
23 * Replacements are done on a token basis. Tokens are defined as a
24 * sequence of characters which all belong to a single class. The
25 * two character classes are:
28 * - all other non-whitespace characters
30 public class Preprocessor {
32 public static void main(String[] args) throws Exception {
33 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
34 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
36 // process stdin to stdout
37 Preprocessor cc = new Preprocessor(br, bw);
38 Vector err = cc.process();
42 boolean errors = false;
43 for (int i=0; i < err.size(); i++) { if (err.get(i) instanceof Error) errors = true; System.err.println(err.get(i)); }
44 if (errors) throw new Exception();
49 private LineNumberReader in;
50 private PrintWriter out;
52 private Hashtable replace = new Hashtable();
53 private Hashtable repeatreplace = null;
54 private Vector sinceLastRepeat = null;
55 private Vector err = new Vector();
57 private int enumSwitch = 0; // number appended to variable used in switch implementation
60 public Preprocessor(Reader reader, Writer writer) {
65 public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
66 public Reader getReader() { return r; }
68 public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
69 public Writer getWriter() { return w; }
72 /** process data from reader, write to writer, return vector of errors */
73 public Vector process() throws IOException {
78 while((s = in.readLine()) != null) {
79 if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
80 String trimmed = s.trim();
82 if (trimmed.startsWith("//#define ")) {
83 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
84 err.add(new Error("#define badly formed, ignored")); continue PROCESS;
86 int keyStart = indexOfNotWS(trimmed, 9);
88 err.add(new Error("#define requires KEY")); continue PROCESS;
90 int keyEnd = indexOfWS(trimmed, keyStart);
92 int macroStart = trimmed.indexOf('(');
93 int macroEnd = trimmed.indexOf(')');
94 if (macroStart > keyEnd) {
95 // no macro is defined, just make sure something dumb like KEYNA)ME hasn't been done
96 if (macroEnd < keyEnd) { err.add(new Error("#define key contains invalid char: ')'")); continue PROCESS; }
97 macroStart = macroEnd = -1;
100 if (macroStart == 0) {
101 err.add(new Error("#define macro requires name")); continue PROCESS;
102 } else if (macroStart > 0) {
103 if (macroStart > macroEnd) { err.add(new Error("#define macro badly formed")); continue PROCESS; }
104 if (macroStart+1 == macroEnd) { err.add(new Error("#define macro requires property name")); continue PROCESS; }
106 JSFunctionMacro fm = new JSFunctionMacro();
107 String key = trimmed.substring(keyStart, macroStart);
108 String unbound = trimmed.substring(macroStart +1, macroEnd);
109 int unboundDiv = unbound.indexOf(',');
110 if (unboundDiv == -1) {
111 fm.unbound1 = unbound;
113 fm.unbound1 = unbound.substring(0, unboundDiv);
114 fm.unbound2 = unbound.substring(unboundDiv +1);
115 if (fm.unbound1.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
116 if (fm.unbound2.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
118 fm.expression = trimmed.substring(keyEnd).trim();
119 replace.put(key, fm);
121 String key = trimmed.substring(keyStart, keyEnd);
122 String val = trimmed.substring(keyEnd).trim();
123 replace.put(key, val);
125 out.print("\n"); // preserve line numbers
127 } else if (trimmed.startsWith("//#repeat ")) {
128 trimmed = trimmed.substring(9);
129 while(trimmed.charAt(trimmed.length() - 1) == '\\') {
130 String s2 = in.readLine().trim();
131 if (s2.startsWith("//")) s2 = s2.substring(2).trim();
132 trimmed = trimmed.substring(0, trimmed.length() - 1) + " " + s2;
133 out.print("\n"); // preserve line numbers
135 StringTokenizer st = new StringTokenizer(trimmed, " ");
136 repeatreplace = (Hashtable)replace.clone();
137 while (st.hasMoreTokens()) {
138 String tok = st.nextToken().trim();
139 String key = tok.substring(0, tok.indexOf('/'));
140 String val = tok.substring(tok.indexOf('/') + 1);
141 repeatreplace.put(key, val);
143 sinceLastRepeat = new Vector();
144 out.print("\n"); // preserve line numbers
146 } else if (trimmed.startsWith("//#end")) {
147 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
148 Hashtable save = replace;
149 replace = repeatreplace;
151 for(int i=0; i<sinceLastRepeat.size() - 1; i++) out.print(processLine((String)sinceLastRepeat.elementAt(i), true));
152 sinceLastRepeat = null;
155 } else if (trimmed.startsWith("//#switch")) {
156 int expStart = trimmed.indexOf('(') +1;
157 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
158 int expEnd = trimmed.lastIndexOf(')');
159 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
160 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
161 String expr = trimmed.substring(expStart, expEnd);
163 out.print("final String ccSwitch"+enumSwitch+" = (String)("+expr+"); ");
164 out.print("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {\n");
166 Hashtable[] byLength = new Hashtable[255];
168 String Default = null;
169 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
170 if (trimmed.startsWith("default:")) {
171 Default = processLine(trimmed.substring(8), false);
174 if (trimmed.startsWith("case ")) {
176 int strStart = trimmed.indexOf('\"') +1;
177 if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
178 int strEnd = trimmed.indexOf('\"', strStart);
179 if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
180 key = trimmed.substring(strStart, strEnd);
182 Hashtable thisCase = (Hashtable)byLength[key.length()];
183 if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
184 thisCase.put(key, "");
186 // find end of case definition
187 int caseEnd = trimmed.indexOf(':', strEnd) +1;
188 if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
189 trimmed = trimmed.substring(caseEnd);
193 Hashtable hash = byLength[key.length()];
194 hash.put(key, (String)hash.get(key) + processLine(trimmed, false).replaceAll("//[^\"]*$", "").trim() + "\n");
196 out.print(processLine(trimmed, false));
200 for(int i=0; i<255; i++) {
201 if (byLength[i] == null) continue;
202 out.print("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) { ");
203 buildTrie("", byLength[i]);
204 out.print("}; break; } ");
206 out.print("} /* switch */ ");
207 if (Default != null) out.print(" " + Default);
208 out.print(" } while(false); /* OUTER */\n");
212 out.print(processLine(s, false));
219 private void buildTrie(String prefix, Hashtable cases) {
220 Enumeration caseKeys = cases.keys();
221 Vec keys = new Vec();
222 while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
223 keys.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) {
224 return ((String)a).compareTo((String)b);
227 for(int i=0; i<keys.size(); i++) {
228 if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
229 String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
230 if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
231 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': { ");
232 out.print("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) { ");
233 buildTrie(prefixPlusOne, cases);
234 out.print("} break; } ");
235 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
236 if (i<keys.size()) { i--; continue; }
238 out.print("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': ");
239 String code = (String)cases.get(keys.elementAt(i));
240 code = code.substring(0, code.length());
241 String key = (String)keys.elementAt(i);
242 out.print("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break; ");
247 private String processLine(String s, boolean deleteLineEndings) throws IOException {
248 if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
250 for(int i=0; i<s.length(); i++) {
251 char c = s.charAt(i);
252 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
257 for(j = i; j < s.length(); j++) {
259 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
261 String tok = s.substring(i, j);
262 Object val = replace.get(tok);
266 } else if (val instanceof JSFunctionMacro) {
267 if (s.charAt(j) != '(') { err.add(new Error("open paren must follow macro binding for macro " + tok)); continue; }
268 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
269 i = s.indexOf(')', j);
275 if (!deleteLineEndings) ret += "\n";
279 private static int indexOfWS(String s) { return indexOfWS(s, 0); }
280 private static int indexOfWS(String s, int beginIndex) {
281 if (s == null || beginIndex >= s.length()) return -1;
282 for (; beginIndex < s.length(); beginIndex++) {
283 if (s.charAt(beginIndex) == ' ') return beginIndex;
288 private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
289 private static int indexOfNotWS(String s, int beginIndex) {
290 if (s == null || beginIndex >= s.length()) return -1;
291 for (; beginIndex < s.length(); beginIndex++) {
292 if (s.charAt(beginIndex) != ' ') return beginIndex;
297 public class Warning {
298 protected String msg;
301 public Warning() { msg = ""; }
302 public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
304 public String toString() { return "WARNING Line "+line+": "+msg; }
307 public class Error extends Warning {
308 public Error() { super(); }
309 public Error(String m) { super(m); }
310 public String toString() { return "ERROR Line "+line+": "+msg; }
313 public static class JSFunctionMacro {
314 public String unbound1 = null;
315 public String unbound2 = null;
316 public String expression = null;
317 public String process(String args) {
318 String bound1 = null;
319 String bound2 = null;
320 if (unbound2 == null) {
322 return expression.replaceAll(unbound1, bound1);
324 bound1 = args.substring(0, args.indexOf(','));
325 bound2 = args.substring(args.indexOf(',') + 1);
326 return (expression.replaceAll(unbound1, bound1).replaceAll(unbound2, bound2));