8d054d999f5c027663d77d39372eec990b45a5b8
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLLexer.java
1 // $Id: CQLLexer.java,v 1.4 2002-11-02 01:21:35 mike Exp $
2
3 package org.z3950.zing.cql;
4 import java.io.StreamTokenizer;
5 import java.io.StringReader;
6 import java.util.Hashtable;
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     static int TT_LE        = 1000;     // The "<=" relation
20     static int TT_GE        = 1001;     // The ">=" relation
21     static int TT_NE        = 1002;     // The "<>" relation
22     static int TT_AND       = 1003;     // The "and" boolean
23     static int TT_OR        = 1004;     // The "or" boolean
24     static int TT_NOT       = 1005;     // The "not" boolean
25     static int TT_PROX      = 1006;     // The "prox" boolean
26     static int TT_ANY       = 1007;     // The "any" relation
27     static int TT_ALL       = 1008;     // The "all" relation
28     static int TT_EXACT     = 1009;     // The "exact" relation
29     static int TT_pWORD     = 1010;     // The "word" proximity unit
30     static int TT_SENTENCE  = 1011;     // The "sentence" proximity unit
31     static int TT_PARAGRAPH = 1012;     // The "paragraph" proximity unit
32     static int TT_ELEMENT   = 1013;     // The "element" proximity unit
33     static int TT_ORDERED   = 1014;     // The "ordered" proximity ordering
34     static int TT_UNORDERED = 1015;     // The "unordered" proximity ordering
35     static int TT_RELEVANT  = 1016;     // The "relevant" relation modifier
36     static int TT_FUZZY     = 1017;     // The "fuzzy" relation modifier
37     static int TT_STEM      = 1018;     // The "stem" relation modifier
38
39     // Support for keywords.  It would be nice to compile this linear
40     // list into a Hashtable, but it's hard to store ints as hash
41     // values, and next to impossible to use them as hash keys.  So
42     // we'll just scan the (very short) list every time we need to do
43     // a lookup.
44     private class Keyword {
45         int token;
46         String keyword;
47         Keyword(int token, String keyword) {
48             this.token = token;
49             this.keyword = keyword;
50         }
51     }
52     // This should logically be static, but Java won't allow it  :-P
53     private Keyword[] keywords = {
54         new Keyword(TT_AND, "and"),
55         new Keyword(TT_OR,  "or"),
56         new Keyword(TT_NOT, "not"),
57         new Keyword(TT_PROX, "prox"),
58         new Keyword(TT_ANY, "any"),
59         new Keyword(TT_ALL, "all"),
60         new Keyword(TT_EXACT, "exact"),
61         new Keyword(TT_pWORD, "word"),
62         new Keyword(TT_SENTENCE, "sentence"),
63         new Keyword(TT_PARAGRAPH, "paragraph"),
64         new Keyword(TT_ELEMENT, "element"),
65         new Keyword(TT_ORDERED, "ordered"),
66         new Keyword(TT_UNORDERED, "unordered"),
67         new Keyword(TT_RELEVANT, "relevant"),
68         new Keyword(TT_FUZZY, "fuzzy"),
69         new Keyword(TT_STEM, "stem"),
70     };
71
72     // For halfDecentPushBack() and the code at the top of nextToken()
73     private static int TT_UNDEFINED = -1000;
74     private int saved_ttype = TT_UNDEFINED;
75     private double saved_nval;
76     private String saved_sval;
77
78     // Controls debugging output
79     private static boolean DEBUG;
80
81     CQLLexer(String cql, boolean lexdebug) {
82         super(new StringReader(cql));
83         wordChars('!', '?');    // ASCII-dependency!
84         wordChars('[', '`');    // ASCII-dependency!
85         quoteChar('"');
86         ordinaryChar('=');
87         ordinaryChar('<');
88         ordinaryChar('>');
89         ordinaryChar('/');
90         ordinaryChar('(');
91         ordinaryChar(')');
92         wordChars('\'', '\''); // prevent this from introducing strings
93         parseNumbers();
94         DEBUG = lexdebug;
95     }
96
97     private static void debug(String str) {
98         if (DEBUG)
99             System.err.println("LEXDEBUG: " + str);
100     }
101
102     // I don't honestly understand why we need this, but the
103     // documentation for java.io.StreamTokenizer.pushBack() is pretty
104     // vague about its semantics, and it seems to me that they could
105     // be summed up as "it doesn't work".  This version has the very
106     // clear semantics "pretend I didn't call nextToken() just then".
107     //
108     private void halfDecentPushBack() {
109         saved_ttype = ttype;
110         saved_nval = nval;
111         saved_sval = sval;
112     }
113
114     public int nextToken() throws java.io.IOException {
115         if (saved_ttype != TT_UNDEFINED) {
116             ttype = saved_ttype;
117             nval = saved_nval;
118             sval = saved_sval;
119             saved_ttype = TT_UNDEFINED;
120             debug("using saved ttype=" + ttype + ", " +
121                   "nval=" + nval + ", sval='" + sval + "'");
122             return ttype;
123         }
124
125         underlyingNextToken();
126         if (ttype == '<') {
127             debug("token starts with '<' ...");
128             underlyingNextToken();
129             if (ttype == '=') {
130                 debug("token continues with '=' - it's '<='");
131                 ttype = TT_LE;
132             } else if (ttype == '>') {
133                 debug("token continues with '>' - it's '<>'");
134                 ttype = TT_NE;
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_GE;
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             return new Integer((int) nval).toString();
188         } else if (token == TT_WORD) {
189             return "word: " + sval;
190         } else if (token == '"') {
191             return "string: \"" + sval + "\"";
192         } else if (token == TT_LE) {
193             return "<=";
194         } else if (token == TT_GE) {
195             return ">=";
196         } else if (token == TT_NE) {
197             return "<>";
198         }
199
200         // Check whether its associated with one of the keywords
201         for (int i = 0; i < keywords.length; i++)
202             if (token == keywords[i].token)
203                 return keywords[i].keyword;
204
205         // Otherwise it must be a single character, such as '(' or '/'.
206         String res = String.valueOf((char) token);
207         if (quoteChars) res = "'" + res + "'";
208         return res;
209     }
210
211     public static void main(String[] args) throws Exception {
212         if (args.length > 1) {
213             System.err.println("Usage: CQLLexer [<CQL-query>]");
214             System.err.println("If unspecified, query is read from stdin");
215             System.exit(1);
216         }
217
218         String cql;
219         if (args.length == 1) {
220             cql = args[0];
221         } else {
222             byte[] bytes = new byte[10000];
223             try {
224                 // Read in the whole of standard input in one go
225                 int nbytes = System.in.read(bytes);
226             } catch (java.io.IOException ex) {
227                 System.err.println("Can't read query: " + ex.getMessage());
228                 System.exit(2);
229             }
230             cql = new String(bytes);
231         }
232
233         CQLLexer lexer = new CQLLexer(cql, true);
234         int token;
235         while ((token = lexer.nextToken()) != TT_EOF) {
236             // Nothing to do: debug() statements render tokens for us
237         }
238     }
239 }