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
14 * Replacements are done on a token basis. Tokens are defined as a
15 * sequence of characters which all belong to a single class. The
16 * two character classes are:
19 * - all other non-whitespace characters
21 public class Preprocessor {
23 static Hashtable replace = new Hashtable();
24 static Hashtable savereplace = replace;
25 static Vector sinceLastRepeat = null;
27 public static void main(String[] args) throws IOException {
28 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
31 while((s = br.readLine()) != null) {
32 if (sinceLastRepeat != null) sinceLastRepeat.addElement(s);
33 String trimmed = s.trim();
34 if (trimmed.startsWith("//#define ")) {
35 trimmed = trimmed.substring(10).trim();
36 String key = trimmed.substring(0, trimmed.indexOf(' '));
37 String val = trimmed.substring(trimmed.indexOf(' ')).trim();
38 replace.put(key, val);
40 } else if (trimmed.startsWith("//#repeat ")) {
41 StringTokenizer st = new StringTokenizer(trimmed.substring(9), " ");
42 savereplace = replace;
43 replace = (Hashtable)replace.clone();
44 while (st.hasMoreTokens()) {
45 String tok = st.nextToken().trim();
46 String key = tok.substring(0, tok.indexOf('/'));
47 String val = tok.substring(tok.indexOf('/') + 1);
48 replace.put(key, val);
50 sinceLastRepeat = new Vector();
52 } else if (trimmed.startsWith("//#end")) {
53 replace = savereplace;
55 for(int i=0; i<sinceLastRepeat.size(); i++) processLine((String)sinceLastRepeat.elementAt(i));
56 sinceLastRepeat = null;
66 static void processLine(String s) throws IOException {
67 for(int i=0; i<s.length(); i++) {
69 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') {
74 for(j = i; j < s.length(); j++) {
76 if (!Character.isLetter(c) && !Character.isDigit(c) && c != '_') break;
78 String tok = s.substring(i, j);
79 String val = (String)replace.get(tok);
80 if (val != null) System.out.print(val);
81 else System.out.print(tok);