Support for "==" relation (TT_EQEQ)
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLParser.java
1 // $Id: CQLParser.java,v 1.36 2007-06-29 15:39:09 mike Exp $
2
3 package org.z3950.zing.cql;
4 import java.io.IOException;
5 import java.util.Vector;
6 import java.util.Properties;
7 import java.io.InputStream;
8 import java.io.FileInputStream;
9 import java.io.FileNotFoundException;
10
11
12 /**
13  * Compiles CQL strings into parse trees of CQLNode subtypes.
14  *
15  * @version     $Id: CQLParser.java,v 1.36 2007-06-29 15:39:09 mike Exp $
16  * @see         <A href="http://zing.z3950.org/cql/index.html"
17  *                      >http://zing.z3950.org/cql/index.html</A>
18  */
19 public class CQLParser {
20     private CQLLexer lexer;
21     private int compat; // When false, implement CQL 1.2
22     public static int V1POINT1 = 12368;
23     public static int V1POINT2 = 12369;
24     public static int V1POINT1SORT = 12370;
25
26     static private boolean DEBUG = false;
27     static private boolean LEXDEBUG = false;
28
29     /**
30      * The new parser implements a dialect of CQL specified by the
31      * <tt>compat</tt> argument:
32      * <ul>
33      *  <li>V1POINT1 - CQL version 1.1
34      *  </li>
35      *  <li>V1POINT2 - CQL version 1.2
36      *  </li>
37      *  <li>V1POINT1SORT - CQL version 1.1 but including
38      *          <tt>sortby</tt> as specified for CQL 1.2.
39      *  </li>
40      * </ul>
41      */
42     CQLParser(int compat) {
43         this.compat = compat;
44     }
45
46     /**
47      * The new parser implements CQL 1.2
48      */
49     CQLParser() {
50         this.compat = V1POINT2;
51     }
52
53     private static void debug(String str) {
54         if (DEBUG)
55             System.err.println("PARSEDEBUG: " + str);
56     }
57
58     /**
59      * Compiles a CQL query.
60      * <P>
61      * The resulting parse tree may be further processed by hand (see
62      * the individual node-types' documentation for details on the
63      * data structure) or, more often, simply rendered out in the
64      * desired form using one of the back-ends.  <TT>toCQL()</TT>
65      * returns a decompiled CQL query equivalent to the one that was
66      * compiled in the first place; <TT>toXCQL()</TT> returns an
67      * XML snippet representing the query; and <TT>toPQF()</TT>
68      * returns the query rendered in Index Data's Prefix Query
69      * Format.
70      *
71      * @param cql       The query
72      * @return          A CQLNode object which is the root of a parse
73      * tree representing the query.  */
74     public CQLNode parse(String cql)
75         throws CQLParseException, IOException {
76         lexer = new CQLLexer(cql, LEXDEBUG);
77
78         lexer.nextToken();
79         debug("about to parseQuery()");
80         CQLNode root = parseQuery("cql.serverChoice",
81                                   new CQLRelation(compat == V1POINT2 ? "=" : "scr"));
82         if (lexer.ttype != lexer.TT_EOF)
83             throw new CQLParseException("junk after end: " + lexer.render());
84
85         return root;
86     }
87
88     private CQLNode parseQuery(String index, CQLRelation relation)
89         throws CQLParseException, IOException {
90         debug("in parseQuery()");
91
92         CQLNode term = parseTerm(index, relation);
93         while (lexer.ttype != lexer.TT_EOF && lexer.ttype != ')') {
94             if (lexer.ttype == lexer.TT_AND ||
95                 lexer.ttype == lexer.TT_OR ||
96                 lexer.ttype == lexer.TT_NOT ||
97                 lexer.ttype == lexer.TT_PROX) {
98                 int type = lexer.ttype;
99                 String val = lexer.sval;
100                 match(type);
101                 ModifierSet ms = gatherModifiers(val);
102                 CQLNode term2 = parseTerm(index, relation);
103                 term = ((type == lexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
104                         (type == lexer.TT_OR)  ? new CQLOrNode (term, term2, ms) :
105                         (type == lexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
106                                                  new CQLProxNode(term, term2, ms));
107             } else {
108                 throw new CQLParseException("expected boolean, got " +
109                                             lexer.render());
110             }
111         }
112
113         debug("no more ops");
114         return term;
115     }
116
117     private ModifierSet gatherModifiers(String base)
118         throws CQLParseException, IOException {
119         debug("in gatherModifiers()");
120
121         ModifierSet ms = new ModifierSet(base);
122         while (lexer.ttype == '/') {
123             match('/');
124             if (lexer.ttype != lexer.TT_WORD)
125                 throw new CQLParseException("expected modifier, "
126                                             + "got " + lexer.render());
127             String type = lexer.sval.toLowerCase();
128             match(lexer.ttype);
129             if (!isRelation()) {
130                 // It's a simple modifier consisting of type only
131                 ms.addModifier(type);
132             } else {
133                 // It's a complex modifier of the form type=value
134                 String comparision = lexer.render(lexer.ttype, false);
135                 match(lexer.ttype);
136                 String value = matchSymbol("modifier value");
137                 ms.addModifier(type, comparision, value);
138             }
139         }
140
141         return ms;
142     }
143
144     private CQLNode parseTerm(String index, CQLRelation relation)
145         throws CQLParseException, IOException {
146         debug("in parseTerm()");
147
148         String word;
149         while (true) {
150             if (lexer.ttype == '(') {
151                 debug("parenthesised term");
152                 match('(');
153                 CQLNode expr = parseQuery(index, relation);
154                 match(')');
155                 return expr;
156             } else if (lexer.ttype == '>') {
157                 match('>');
158                 return parsePrefix(index, relation);
159             }
160
161             debug("non-parenthesised term");
162             word = matchSymbol("index or term");
163             if (!isRelation() && lexer.ttype != lexer.TT_WORD)
164                 break;
165
166             index = word;
167             String relstr = (lexer.ttype == lexer.TT_WORD ?
168                              lexer.sval : lexer.render(lexer.ttype, false));
169             relation = new CQLRelation(relstr);
170             match(lexer.ttype);
171             ModifierSet ms = gatherModifiers(relstr);
172             relation.setModifiers(ms);
173             debug("index='" + index + ", " +
174                   "relation='" + relation.toCQL() + "'");
175         }
176
177         CQLTermNode node = new CQLTermNode(index, relation, word);
178         debug("made term node " + node.toCQL());
179         return node;
180     }
181
182     private CQLNode parsePrefix(String index, CQLRelation relation)
183         throws CQLParseException, IOException {
184         debug("prefix mapping");
185
186         String name = null;
187         String identifier = matchSymbol("prefix-name");
188         if (lexer.ttype == '=') {
189             match('=');
190             name = identifier;
191             identifier = matchSymbol("prefix-identifer");
192         }
193         CQLNode term = parseQuery(index, relation);
194         return new CQLPrefixNode(name, identifier, term);
195     }
196
197     // Checks for a relation
198     private boolean isRelation() {
199         debug("isRelation: checking ttype=" + lexer.ttype +
200               " (" + lexer.render() + ")");
201         return (lexer.ttype == '<' ||
202                 lexer.ttype == '>' ||
203                 lexer.ttype == '=' ||
204                 lexer.ttype == lexer.TT_LE ||
205                 lexer.ttype == lexer.TT_GE ||
206                 lexer.ttype == lexer.TT_NE ||
207                 lexer.ttype == lexer.TT_EQEQ);
208     }
209
210     private void match(int token)
211         throws CQLParseException, IOException {
212         debug("in match(" + lexer.render(token, true) + ")");
213         if (lexer.ttype != token)
214             throw new CQLParseException("expected " +
215                                         lexer.render(token, true) +
216                                         ", " + "got " + lexer.render());
217         int tmp = lexer.nextToken();
218         debug("match() got token=" + lexer.ttype + ", " +
219               "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
220               " (tmp=" + tmp + ")");
221     }
222
223     private String matchSymbol(String expected)
224         throws CQLParseException, IOException {
225
226         debug("in matchSymbol()");
227         if (lexer.ttype == lexer.TT_WORD ||
228             lexer.ttype == lexer.TT_NUMBER ||
229             lexer.ttype == '"' ||
230             // The following is a complete list of keywords.  Because
231             // they're listed here, they can be used unquoted as
232             // indexes, terms, prefix names and prefix identifiers.
233             // ### Instead, we should ask the lexer whether what we
234             // have is a keyword, and let the knowledge reside there.
235             lexer.ttype == lexer.TT_AND ||
236             lexer.ttype == lexer.TT_OR ||
237             lexer.ttype == lexer.TT_NOT ||
238             lexer.ttype == lexer.TT_PROX) {
239             String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
240                 lexer.render() : lexer.sval;
241             match(lexer.ttype);
242             return symbol;
243         }
244
245         throw new CQLParseException("expected " + expected + ", " +
246                                     "got " + lexer.render());
247     }
248
249
250     /**
251      * Simple test-harness for the CQLParser class.
252      * <P>
253      * Reads a CQL query either from its command-line argument, if
254      * there is one, or standard input otherwise.  So these two
255      * invocations are equivalent:
256      * <PRE>
257      *  CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
258      *  echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
259      * </PRE>
260      * The test-harness parses the supplied query and renders is as
261      * XCQL, so that both of the invocations above produce the
262      * following output:
263      * <PRE>
264      *  &lt;triple&gt;
265      *    &lt;boolean&gt;
266      *      &lt;value&gt;and&lt;/value&gt;
267      *    &lt;/boolean&gt;
268      *    &lt;triple&gt;
269      *      &lt;boolean&gt;
270      *        &lt;value&gt;or&lt;/value&gt;
271      *      &lt;/boolean&gt;
272      *      &lt;searchClause&gt;
273      *        &lt;index&gt;au&lt;/index&gt;
274      *        &lt;relation&gt;
275      *          &lt;value&gt;=&lt;/value&gt;
276      *        &lt;/relation&gt;
277      *        &lt;term&gt;Kerninghan&lt;/term&gt;
278      *      &lt;/searchClause&gt;
279      *      &lt;searchClause&gt;
280      *        &lt;index&gt;au&lt;/index&gt;
281      *        &lt;relation&gt;
282      *          &lt;value&gt;=&lt;/value&gt;
283      *        &lt;/relation&gt;
284      *        &lt;term&gt;Ritchie&lt;/term&gt;
285      *      &lt;/searchClause&gt;
286      *    &lt;/triple&gt;
287      *    &lt;searchClause&gt;
288      *      &lt;index&gt;ti&lt;/index&gt;
289      *      &lt;relation&gt;
290      *        &lt;value&gt;=&lt;/value&gt;
291      *      &lt;/relation&gt;
292      *      &lt;term&gt;Unix&lt;/term&gt;
293      *    &lt;/searchClause&gt;
294      *  &lt;/triple&gt;
295      * </PRE>
296      * <P>
297      * @param -1
298      *  CQL version 1.1 (default version 1.2)
299      * @param -d
300      *  Debug mode: extra output written to stderr.
301      * @param -c
302      *  Causes the output to be written in CQL rather than XCQL - that
303      *  is, a query equivalent to that which was input, is output.  In
304      *  effect, the test harness acts as a query canonicaliser.
305      * @return
306      *  The input query, either as XCQL [default] or CQL [if the
307      *  <TT>-c</TT> option is supplied].
308      */
309     public static void main (String[] args) {
310         char mode = 'x';        // x=XCQL, c=CQL, p=PQF
311         String pfile = null;
312
313         Vector<String> argv = new Vector<String>();
314         for (int i = 0; i < args.length; i++) {
315             argv.add(args[i]);
316         }
317
318         int compat = V1POINT2;
319         if (argv.size() > 0 && argv.get(0).equals("-1")) {
320             compat = V1POINT1;
321             argv.remove(0);
322         }
323
324         if (argv.size() > 0 && argv.get(0).equals("-d")) {
325             DEBUG = true;
326             argv.remove(0);
327         }
328
329         if (argv.size() > 0 && argv.get(0).equals("-c")) {
330             mode = 'c';
331             argv.remove(0);
332         } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
333             mode = 'p';
334             argv.remove(0);
335             pfile = (String) argv.get(0);
336             argv.remove(0);
337         }
338
339         if (argv.size() > 1) {
340             System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
341                                "[-p <pqf-properties> [<CQL-query>]");
342             System.err.println("If unspecified, query is read from stdin");
343             System.exit(1);
344         }
345
346         String cql;
347         if (argv.size() == 1) {
348             cql = (String) argv.get(0);
349         } else {
350             byte[] bytes = new byte[10000];
351             try {
352                 // Read in the whole of standard input in one go
353                 int nbytes = System.in.read(bytes);
354             } catch (IOException ex) {
355                 System.err.println("Can't read query: " + ex.getMessage());
356                 System.exit(2);
357             }
358             cql = new String(bytes);
359         }
360
361         CQLParser parser = new CQLParser(compat);
362         CQLNode root = null;
363         try {
364             root = parser.parse(cql);
365         } catch (CQLParseException ex) {
366             System.err.println("Syntax error: " + ex.getMessage());
367             System.exit(3);
368         } catch (IOException ex) {
369             System.err.println("Can't compile query: " + ex.getMessage());
370             System.exit(4);
371         }
372
373         try {
374             if (mode == 'c') {
375                 System.out.println(root.toCQL());
376             } else if (mode == 'p') {
377                 InputStream f = new FileInputStream(pfile);
378                 if (f == null)
379                     throw new FileNotFoundException(pfile);
380
381                 Properties config = new Properties();
382                 config.load(f);
383                 f.close();
384                 System.out.println(root.toPQF(config));
385             } else {
386                 System.out.print(root.toXCQL(0));
387             }
388         } catch (IOException ex) {
389             System.err.println("Can't render query: " + ex.getMessage());
390             System.exit(5);
391         } catch (UnknownIndexException ex) {
392             System.err.println("Unknown index: " + ex.getMessage());
393             System.exit(6);
394         } catch (UnknownRelationException ex) {
395             System.err.println("Unknown relation: " + ex.getMessage());
396             System.exit(7);
397         } catch (UnknownRelationModifierException ex) {
398             System.err.println("Unknown relation modifier: " +
399                                ex.getMessage());
400             System.exit(8);
401         } catch (UnknownPositionException ex) {
402             System.err.println("Unknown position: " + ex.getMessage());
403             System.exit(9);
404         } catch (PQFTranslationException ex) {
405             // We catch all of this class's subclasses, so --
406             throw new Error("can't get a PQFTranslationException");
407         }
408     }
409 }