Improve test-harnesses and their associated scripts.
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLLexer.java
1 // $Id: CQLLexer.java,v 1.3 2002-11-01 23:45:28 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         ordinaryChar('=');
84         ordinaryChar('<');
85         ordinaryChar('>');
86         ordinaryChar('/');
87         ordinaryChar('(');
88         ordinaryChar(')');
89         wordChars('\'', '\''); // prevent this from introducing strings
90         parseNumbers();
91         DEBUG = lexdebug;
92     }
93
94     private static void debug(String str) {
95         if (DEBUG)
96             System.err.println("LEXDEBUG: " + str);
97     }
98
99     // I don't honestly understand why we need this, but the
100     // documentation for java.io.StreamTokenizer.pushBack() is pretty
101     // vague about its semantics, and it seems to me that they could
102     // be summed up as "it doesn't work".  This version has the very
103     // clear semantics "pretend I didn't call nextToken() just then".
104     //
105     private void halfDecentPushBack() {
106         saved_ttype = ttype;
107         saved_nval = nval;
108         saved_sval = sval;
109     }
110
111     public int nextToken() throws java.io.IOException {
112         if (saved_ttype != TT_UNDEFINED) {
113             ttype = saved_ttype;
114             nval = saved_nval;
115             sval = saved_sval;
116             saved_ttype = TT_UNDEFINED;
117             debug("using saved ttype=" + ttype + ", " +
118                   "nval=" + nval + ", sval='" + sval + "'");
119             return ttype;
120         }
121
122         underlyingNextToken();
123         if (ttype == '<') {
124             debug("token starts with '<' ...");
125             underlyingNextToken();
126             if (ttype == '=') {
127                 debug("token continues with '=' - it's '<='");
128                 ttype = TT_LE;
129             } else if (ttype == '>') {
130                 debug("token continues with '>' - it's '<>'");
131                 ttype = TT_NE;
132             } else {
133                 debug("next token is " + render() + " (pushed back)");
134                 halfDecentPushBack();
135                 ttype = '<';
136                 debug("AFTER: ttype is now " + ttype + " - " + render());
137             }
138         } else if (ttype == '>') {
139             debug("token starts with '>' ...");
140             underlyingNextToken();
141             if (ttype == '=') {
142                 debug("token continues with '=' - it's '>='");
143                 ttype = TT_GE;
144             } else {
145                 debug("next token is " + render() + " (pushed back)");
146                 halfDecentPushBack();
147                 ttype = '>';
148                 debug("AFTER: ttype is now " + ttype + " - " + render());
149             }
150         }
151
152         debug("done nextToken(): ttype=" + ttype + ", " +
153               "nval=" + nval + ", " + "sval='" + sval + "'" +
154               " (" + render() + ")");
155
156         return ttype;
157     }
158
159     // It's important to do keyword recognition here at the lowest
160     // level, otherwise when one of these words follows "<" or ">"
161     // (which can be the beginning of multi-character tokens) it gets
162     // pushed back as a string, and its keywordiness is not
163     // recognised.
164     //
165     public int underlyingNextToken() throws java.io.IOException {
166         super.nextToken();
167         if (ttype == TT_WORD)
168             for (int i = 0; i < keywords.length; i++)
169                 if (sval.equalsIgnoreCase(keywords[i].keyword))
170                     ttype = keywords[i].token;
171
172         return ttype;
173     }
174
175     // Simpler interface for the usual case: current token with quoting
176     String render() {
177         return render(ttype, true);
178     }
179
180     String render(int token, boolean quoteChars) {
181         if (token == TT_EOF) {
182             return "EOF";
183         } else if (token == TT_NUMBER) {
184             return new Integer((int) nval).toString();
185         } else if (token == TT_WORD) {
186             return "word: " + sval;
187         } else if (token == '"') {
188             return "string: \"" + sval + "\"";
189         } else if (token == TT_LE) {
190             return "<=";
191         } else if (token == TT_GE) {
192             return ">=";
193         } else if (token == TT_NE) {
194             return "<>";
195         }
196
197         // Check whether its associated with one of the keywords
198         for (int i = 0; i < keywords.length; i++)
199             if (token == keywords[i].token)
200                 return keywords[i].keyword;
201
202         // Otherwise it must be a single character, such as '(' or '/'.
203         String res = String.valueOf((char) token);
204         if (quoteChars) res = "'" + res + "'";
205         return res;
206     }
207
208     public static void main(String[] args) throws Exception {
209         if (args.length > 1) {
210             System.err.println("Usage: CQLLexer [<CQL-query>]");
211             System.err.println("If unspecified, query is read from stdin");
212             System.exit(1);
213         }
214
215         String cql;
216         if (args.length == 1) {
217             cql = args[0];
218         } else {
219             byte[] bytes = new byte[10000];
220             try {
221                 // Read in the whole of standard input in one go
222                 int nbytes = System.in.read(bytes);
223             } catch (java.io.IOException ex) {
224                 System.err.println("Can't read query: " + ex.getMessage());
225                 System.exit(2);
226             }
227             cql = new String(bytes);
228         }
229
230         CQLLexer lexer = new CQLLexer(cql, true);
231         int token;
232         while ((token = lexer.nextToken()) != TT_EOF) {
233             // Nothing to do: debug() statements render tokens for us
234         }
235     }
236 }