Remove CVS expansions
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / CQLLexer.java
1
2 package org.z3950.zing.cql;
3 import java.io.InputStream;
4 import java.io.Reader;
5 import java.io.StreamTokenizer;
6 import java.io.StringReader;
7
8
9 // This is a semi-trivial subclass for java.io.StreamTokenizer that:
10 //      * Has a halfDecentPushBack() method that actually works
11 //      * Includes a render() method
12 //      * Knows about the multi-character tokens "<=", ">=" and "<>"
13 //      * Recognises a set of keywords as tokens in their own right
14 //      * Includes some primitive debugging-output facilities
15 // It's used only by CQLParser.
16 //
17 class CQLLexer extends StreamTokenizer {
18     // New publicly visible token-types
19     public final static int TT_LE        = 1000;        // The "<=" relation
20     public final static int TT_GE        = 1001;        // The ">=" relation
21     public final static int TT_NE        = 1002;        // The "<>" relation
22     public final static int TT_EQEQ      = 1003;        // The "==" relation
23     public final static int TT_AND       = 1004;        // The "and" boolean
24     public final static int TT_OR        = 1005;        // The "or" boolean
25     public final static int TT_NOT       = 1006;        // The "not" boolean
26     public final static int TT_PROX      = 1007;        // The "prox" boolean
27     public final static int TT_SORTBY     = 1008;       // The "sortby" operator
28
29     // Support for keywords.  It would be nice to compile this linear
30     // list into a Hashtable, but it's hard to store ints as hash
31     // values, and next to impossible to use them as hash keys.  So
32     // we'll just scan the (very short) list every time we need to do
33     // a lookup.
34     private class Keyword {
35         int token;
36         String keyword;
37         Keyword(int token, String keyword) {
38             this.token = token;
39             this.keyword = keyword;
40         }
41     }
42     // This should logically be static, but Java won't allow it  :-P
43     private Keyword[] keywords = {
44         new Keyword(TT_AND, "and"),
45         new Keyword(TT_OR,  "or"),
46         new Keyword(TT_NOT, "not"),
47         new Keyword(TT_PROX, "prox"),
48         new Keyword(TT_SORTBY, "sortby"),
49     };
50
51     // For halfDecentPushBack() and the code at the top of nextToken()
52     private static int TT_UNDEFINED = -1000;
53     private int saved_ttype = TT_UNDEFINED;
54     private double saved_nval;
55     private String saved_sval;
56
57     // Controls debugging output
58     private static boolean DEBUG;
59
60     CQLLexer(String cql, boolean lexdebug) {
61         this(new StringReader(cql), lexdebug);
62     }
63     
64     CQLLexer(Reader cql, boolean lexdebug) {
65         super(cql);
66         wordChars('!', '?');    // ASCII-dependency!
67         wordChars('[', '`');    // ASCII-dependency!
68         quoteChar('"');
69         ordinaryChar('=');
70         ordinaryChar('<');
71         ordinaryChar('>');
72         ordinaryChar('/');
73         ordinaryChar('(');
74         ordinaryChar(')');
75         wordChars('\'', '\''); // prevent this from introducing strings
76         //parseNumbers();
77         ordinaryChar('-');
78         wordChars('-', '-');
79         ordinaryChars('0', '9');
80         wordChars('0', '9');
81         DEBUG = lexdebug;
82     }
83
84     private static void debug(String str) {
85         if (DEBUG)
86             System.err.println("LEXDEBUG: " + str);
87     }
88
89     // I don't honestly understand why we need this, but the
90     // documentation for java.io.StreamTokenizer.pushBack() is pretty
91     // vague about its semantics, and it seems to me that they could
92     // be summed up as "it doesn't work".  This version has the very
93     // clear semantics "pretend I didn't call nextToken() just then".
94     //
95     private void halfDecentPushBack() {
96         saved_ttype = ttype;
97         saved_nval = nval;
98         saved_sval = sval;
99     }
100
101     @Override
102     public int nextToken() throws java.io.IOException {
103         if (saved_ttype != TT_UNDEFINED) {
104             ttype = saved_ttype;
105             nval = saved_nval;
106             sval = saved_sval;
107             saved_ttype = TT_UNDEFINED;
108             debug("using saved ttype=" + ttype + ", " +
109                   "nval=" + nval + ", sval='" + sval + "'");
110             return ttype;
111         }
112
113         underlyingNextToken();
114         if (ttype == '<') {
115             debug("token starts with '<' ...");
116             underlyingNextToken();
117             if (ttype == '=') {
118                 debug("token continues with '=' - it's '<='");
119                 ttype = TT_LE;
120             } else if (ttype == '>') {
121                 debug("token continues with '>' - it's '<>'");
122                 ttype = TT_NE;
123             } else {
124                 debug("next token is " + render() + " (pushed back)");
125                 halfDecentPushBack();
126                 ttype = '<';
127                 debug("AFTER: ttype is now " + ttype + " - " + render());
128             }
129         } else if (ttype == '>') {
130             debug("token starts with '>' ...");
131             underlyingNextToken();
132             if (ttype == '=') {
133                 debug("token continues with '=' - it's '>='");
134                 ttype = TT_GE;
135             } else {
136                 debug("next token is " + render() + " (pushed back)");
137                 halfDecentPushBack();
138                 ttype = '>';
139                 debug("AFTER: ttype is now " + ttype + " - " + render());
140             }
141         } else if (ttype == '=') {
142             debug("token starts with '=' ...");
143             underlyingNextToken();
144             if (ttype == '=') {
145                 debug("token continues with '=' - it's '=='");
146                 ttype = TT_EQEQ;
147             } else {
148                 debug("next token is " + render() + " (pushed back)");
149                 halfDecentPushBack();
150                 ttype = '=';
151                 debug("AFTER: ttype is now " + ttype + " - " + render());
152             }
153         }
154
155         debug("done nextToken(): ttype=" + ttype + ", " +
156               "nval=" + nval + ", " + "sval='" + sval + "'" +
157               " (" + render() + ")");
158
159         return ttype;
160     }
161
162     // It's important to do keyword recognition here at the lowest
163     // level, otherwise when one of these words follows "<" or ">"
164     // (which can be the beginning of multi-character tokens) it gets
165     // pushed back as a string, and its keywordiness is not
166     // recognised.
167     //
168     public int underlyingNextToken() throws java.io.IOException {
169         super.nextToken();
170         if (ttype == TT_WORD)
171             for (int i = 0; i < keywords.length; i++)
172                 if (sval.equalsIgnoreCase(keywords[i].keyword))
173                     ttype = keywords[i].token;
174
175         return ttype;
176     }
177
178     // Simpler interface for the usual case: current token with quoting
179     String render() {
180         return render(ttype, true);
181     }
182
183     String render(int token, boolean quoteChars) {
184         if (token == TT_EOF) {
185             return "EOF";
186         } else if (token == TT_NUMBER) {
187             if ((double) nval == (int) nval) {
188                 return new Integer((int) nval).toString();
189             } else {
190                 return new Double((double) nval).toString();
191             }
192         } else if (token == TT_WORD) {
193             return "word: " + sval;
194         } else if (token == '"') {
195             return "string: \"" + sval + "\"";
196         } else if (token == TT_LE) {
197             return "<=";
198         } else if (token == TT_GE) {
199             return ">=";
200         } else if (token == TT_NE) {
201             return "<>";
202         } else if (token == TT_EQEQ) {
203             return "==";
204         }
205
206         // Check whether its associated with one of the keywords
207         for (int i = 0; i < keywords.length; i++)
208             if (token == keywords[i].token)
209                 return keywords[i].keyword;
210
211         // Otherwise it must be a single character, such as '(' or '/'.
212         String res = String.valueOf((char) token);
213         if (quoteChars) res = "'" + res + "'";
214         return res;
215     }
216
217     public static void main(String[] args) throws Exception {
218         if (args.length > 1) {
219             System.err.println("Usage: CQLLexer [<CQL-query>]");
220             System.err.println("If unspecified, query is read from stdin");
221             System.exit(1);
222         }
223
224         String cql;
225         if (args.length == 1) {
226             cql = args[0];
227         } else {
228             byte[] bytes = new byte[10000];
229             try {
230                 // Read in the whole of standard input in one go
231                 int nbytes = System.in.read(bytes);
232             } catch (java.io.IOException ex) {
233                 System.err.println("Can't read query: " + ex.getMessage());
234                 System.exit(2);
235             }
236             cql = new String(bytes);
237         }
238
239         CQLLexer lexer = new CQLLexer(cql, true);
240         int token;
241         while ((token = lexer.nextToken()) != TT_EOF) {
242             // Nothing to do: debug() statements render tokens for us
243         }
244     }
245 }