1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
8 * A VERY crude, inefficient Java preprocessor
10 * //#define FOO bar baz -- replace all instances of token FOO with "bar baz"
11 * //#replace foo/bar baz/bop -- DUPLICATE everything between here and //#end,
12 * replacing foo with bar and baz with bop in the *second* copy
13 * //#switch(EXPR) -- switch on strings
17 * Replacements are done on a token basis. Tokens are defined as a
18 * sequence of characters which all belong to a single class. The
19 * two character classes are:
22 * - all other non-whitespace characters
24 public class Preprocessor {
26 public static void main(String[] args) throws Exception {
27 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
28 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
30 // process stdin to stdout
31 Preprocessor cc = new Preprocessor(br, bw);
32 Vector err = cc.process();
36 boolean errors = false;
37 for (int i=0; i < err.size(); i++) { if (err.get(i) instanceof Error) errors = true; System.err.println(err.get(i)); }
38 if (errors) throw new Exception();
43 private LineNumberReader in;
44 private PrintWriter out;
46 private Hashtable replace = new Hashtable();
47 private Hashtable repeatreplace = null;
48 private Vector sinceLastRepeat = null;
49 private Vector err = new Vector();
51 private int enumSwitch = 0; // number appended to variable used in switch implementation
53 public Preprocessor(Reader reader, Writer writer) {
58 public void setReader(Reader reader) { r = reader; if (r != null) in = new LineNumberReader(r); }
59 public Reader getReader() { return r; }
61 public void setWriter(Writer writer) { w = writer; if (w != null) out = new PrintWriter(w); }
62 public Writer getWriter() { return w; }
65 /** process data from reader, write to writer, return vector of errors */
66 public Vector process() throws IOException {
71 while((s = in.readLine()) != null) {
72 if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
73 String trimmed = s.trim();
75 if (trimmed.startsWith("//#define ")) {
76 if (trimmed.length() == 9 || trimmed.charAt(9) != ' ') {
77 err.add(new Error("#define badly formed, ignored")); continue PROCESS;
79 int keyStart = indexOfNotWS(trimmed, 9);
81 err.add(new Error("#define requires KEY")); continue PROCESS;
83 int keyEnd = indexOfWS(trimmed, keyStart);
85 int macroStart = trimmed.indexOf('(');
86 int macroEnd = trimmed.indexOf(')');
87 if (macroStart > keyEnd) {
88 // no macro is defined, just make sure something dumb like KEYNA)ME hasn't been done
89 if (macroEnd < keyEnd) { err.add(new Error("#define key contains invalid char: ')'")); continue PROCESS; }
90 macroStart = macroEnd = -1;
93 if (macroStart == 0) {
94 err.add(new Error("#define macro requires name")); continue PROCESS;
95 } else if (macroStart > 0) {
96 if (macroStart > macroEnd) { err.add(new Error("#define macro badly formed")); continue PROCESS; }
97 if (macroStart+1 == macroEnd) { err.add(new Error("#define macro requires property name")); continue PROCESS; }
99 JSFunctionMacro fm = new JSFunctionMacro();
100 String key = trimmed.substring(keyStart, macroStart);
101 String unbound = trimmed.substring(macroStart +1, macroEnd);
102 int unboundDiv = unbound.indexOf(',');
103 if (unboundDiv == -1) {
104 fm.unbound1 = unbound;
106 fm.unbound1 = unbound.substring(0, unboundDiv);
107 fm.unbound2 = unbound.substring(unboundDiv +1);
108 if (fm.unbound1.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
109 if (fm.unbound2.length() == 0) { err.add(new Error("#define macro property 1 requires name")); continue PROCESS; }
111 fm.expression = trimmed.substring(keyEnd).trim();
112 replace.put(key, fm);
114 String key = trimmed.substring(keyStart, keyEnd);
115 String val = trimmed.substring(keyEnd).trim();
116 replace.put(key, val);
118 out.println(); // preserve line numbers
120 } else if (trimmed.startsWith("//#repeat ")) {
121 trimmed = trimmed.substring(9);
122 while(trimmed.charAt(trimmed.length() - 1) == '\\') {
123 String s2 = in.readLine().trim();
124 if (s2.startsWith("//")) s2 = s2.substring(2).trim();
125 trimmed = trimmed.substring(0, trimmed.length() - 1) + " " + s2;
126 out.println(); // preserve line numbers
128 StringTokenizer st = new StringTokenizer(trimmed, " ");
129 repeatreplace = (Hashtable)replace.clone();
130 while (st.hasMoreTokens()) {
131 String tok = st.nextToken().trim();
132 String key = tok.substring(0, tok.indexOf('/'));
133 String val = tok.substring(tok.indexOf('/') + 1);
134 repeatreplace.put(key, val);
136 sinceLastRepeat = new Vector();
137 out.println(); // preserve line numbers
139 } else if (trimmed.startsWith("//#end")) {
140 if (sinceLastRepeat == null) { err.add(new Warning("#end orphaned")); continue PROCESS; }
141 Hashtable save = replace;
142 replace = repeatreplace;
144 for(int i=0; i<sinceLastRepeat.size() - 1; i++) out.print(processLine((String)sinceLastRepeat.elementAt(i), true));
145 sinceLastRepeat = null;
148 } else if (trimmed.startsWith("//#switch")) {
149 int expStart = trimmed.indexOf('(') +1;
150 if (expStart < 1) { err.add(new Error("expected ( in #switch")); continue PROCESS; }
151 int expEnd = trimmed.lastIndexOf(')');
152 if (expEnd == -1) { err.add(new Error("expected ) in #switch")); continue PROCESS; }
153 if (expEnd - expStart <= 1) { err.add(new Error("badly formed #switch statement")); continue PROCESS; }
154 String expr = trimmed.substring(expStart, expEnd);
156 out.println("final String ccSwitch"+enumSwitch+" = (String)("+expr+");");
157 out.println("SUCCESS:do { switch(ccSwitch"+enumSwitch+".length()) {");
159 Hashtable[] byLength = new Hashtable[255];
161 String Default = null;
162 for(trimmed = in.readLine().trim(); !trimmed.startsWith("//#end"); trimmed = in.readLine().trim()) {
163 if (trimmed.startsWith("default:")) {
164 Default = processLine(trimmed.substring(8), false);
167 if (trimmed.startsWith("case ")) {
169 int strStart = trimmed.indexOf('\"') +1;
170 if (strStart < 1) { err.add(new Error("expected opening of String literal")); continue PROCESS; }
171 int strEnd = trimmed.indexOf('\"', strStart);
172 if (strEnd == -1) { err.add(new Error("expected closing of String literal")); continue PROCESS; }
173 key = trimmed.substring(strStart, strEnd);
175 Hashtable thisCase = (Hashtable)byLength[key.length()];
176 if (thisCase == null) byLength[key.length()] = thisCase = new Hashtable();
177 thisCase.put(key, "");
179 // find end of case definition
180 int caseEnd = trimmed.indexOf(':', strEnd) +1;
181 if (caseEnd < 1) { err.add(new Error("expected :")); continue PROCESS; }
182 trimmed = trimmed.substring(caseEnd);
186 Hashtable hash = byLength[key.length()];
187 hash.put(key, (String)hash.get(key) + processLine(trimmed, false) + "\n");
189 out.print(processLine(trimmed, false));
193 for(int i=0; i<255; i++) {
194 if (byLength[i] == null) continue;
195 out.println("case " + i + ": { switch(ccSwitch"+enumSwitch+".charAt(0)) {");
196 buildTrie("", byLength[i]);
197 out.println("}; break; }");
199 out.println("} //switch");
200 if (Default != null) out.println(Default);
201 out.println("} while(false); //OUTER");
205 out.print(processLine(s, false));
212 private void buildTrie(String prefix, Hashtable cases) {
213 Enumeration caseKeys = cases.keys();
214 Vec keys = new Vec();
215 while(caseKeys.hasMoreElements()) keys.addElement(caseKeys.nextElement());
216 keys.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) {
217 return ((String)a).compareTo((String)b);
220 for(int i=0; i<keys.size(); i++) {
221 if (!((String)keys.elementAt(i)).startsWith(prefix)) continue;
222 String prefixPlusOne = ((String)keys.elementAt(i)).substring(0, prefix.length() + 1);
223 if (i<keys.size()-1 && prefixPlusOne.equals((((String)keys.elementAt(i + 1)).substring(0, prefix.length() + 1)))) {
224 out.println("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\': {");
225 out.println("switch(ccSwitch"+enumSwitch+".charAt(" + (prefix.length()+1) + ")) {");
226 buildTrie(prefixPlusOne, cases);
227 out.println("} break; }");
228 while(i<keys.size() && prefixPlusOne.equals(((String)keys.elementAt(i)).substring(0, prefix.length() + 1))) i++;
229 if (i<keys.size()) { i--; continue; }
231 out.println("case \'" + prefixPlusOne.charAt(prefixPlusOne.length() - 1) + "\':");
232 String code = (String)cases.get(keys.elementAt(i));
233 code = code.substring(0, code.length() - 1);
234 String key = (String)keys.elementAt(i);
235 out.println("if (\""+key+"\".equals(ccSwitch"+enumSwitch+")) { if (true) do { " + code + " } while(false); break SUCCESS; } break; ");
240 private String processLine(String s, boolean deleteLineEndings) throws IOException {
241 if (deleteLineEndings && s.indexOf("//") != -1) s = s.substring(0, s.indexOf("//"));
243 for(int i=0; i<s.length(); i++) {
244 char c = s.charAt(i);
245 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
250 for(j = i; j < s.length(); j++) {
252 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
254 String tok = s.substring(i, j);
255 Object val = replace.get(tok);
259 } else if (val instanceof JSFunctionMacro) {
260 if (s.charAt(j) != '(') { err.add(new Error("open paren must follow macro binding for macro " + tok)); continue; }
261 ret += ((JSFunctionMacro)val).process(s.substring(j+1, s.indexOf(')', j)));
262 i = s.indexOf(')', j);
268 if (!deleteLineEndings) ret += "\n";
272 private static int indexOfWS(String s) { return indexOfWS(s, 0); }
273 private static int indexOfWS(String s, int beginIndex) {
274 if (s == null || beginIndex >= s.length()) return -1;
275 for (; beginIndex < s.length(); beginIndex++) {
276 if (s.charAt(beginIndex) == ' ') return beginIndex;
281 private static int indexOfNotWS(String s) { return indexOfWS(s, 0); }
282 private static int indexOfNotWS(String s, int beginIndex) {
283 if (s == null || beginIndex >= s.length()) return -1;
284 for (; beginIndex < s.length(); beginIndex++) {
285 if (s.charAt(beginIndex) != ' ') return beginIndex;
290 public class Warning {
291 protected String msg;
294 public Warning() { msg = ""; }
295 public Warning(String m) { msg = m; if (in != null) line = in.getLineNumber(); }
297 public String toString() { return "WARNING Line "+line+": "+msg; }
300 public class Error extends Warning {
301 public Error() { super(); }
302 public Error(String m) { super(m); }
303 public String toString() { return "ERROR Line "+line+": "+msg; }
306 public static class JSFunctionMacro {
307 public String unbound1 = null;
308 public String unbound2 = null;
309 public String expression = null;
310 public String process(String args) {
311 String bound1 = null;
312 String bound2 = null;
313 if (unbound2 == null) {
315 return expression.replaceAll(unbound1, bound1);
317 bound1 = args.substring(0, args.indexOf(','));
318 bound2 = args.substring(args.indexOf(',') + 1);
319 return (expression.replaceAll(unbound1, bound1).replaceAll(unbound2, bound2));