Reinstate the "exact" relation even when v1.2 is in effect (the
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / CQLParser.java
1 // $Id: CQLParser.java,v 1.39 2007-08-06 15:54:48 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.39 2007-08-06 15:54:48 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     public CQLParser(int compat) {
43         this.compat = compat;
44     }
45
46     /**
47      * The new parser implements CQL 1.2
48      */
49     public 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 = parseTopLevelPrefixes("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 parseTopLevelPrefixes(String index, CQLRelation relation)
89         throws CQLParseException, IOException {
90         debug("top-level prefix mapping");
91
92         if (lexer.ttype == '>') {
93             return parsePrefix(index, relation, true);
94         }
95
96         CQLNode node = parseQuery(index, relation);
97         if ((compat == V1POINT2 || compat == V1POINT1SORT) &&
98             lexer.ttype == lexer.TT_SORTBY) {
99             match(lexer.ttype);
100             debug("sortspec");
101
102             CQLSortNode sortnode = new CQLSortNode(node);
103             while (lexer.ttype != lexer.TT_EOF) {
104                 String sortindex = matchSymbol("sort index");
105                 ModifierSet ms = gatherModifiers(sortindex);
106                 sortnode.addSortIndex(ms);
107             }
108
109             if (sortnode.keys.size() == 0) {
110                 throw new CQLParseException("no sort keys");
111             }
112
113             node = sortnode;
114         }
115
116         return node;
117     }
118
119     private CQLNode parseQuery(String index, CQLRelation relation)
120         throws CQLParseException, IOException {
121         debug("in parseQuery()");
122
123         CQLNode term = parseTerm(index, relation);
124         while (lexer.ttype != lexer.TT_EOF &&
125                lexer.ttype != ')' &&
126                lexer.ttype != lexer.TT_SORTBY) {
127             if (lexer.ttype == lexer.TT_AND ||
128                 lexer.ttype == lexer.TT_OR ||
129                 lexer.ttype == lexer.TT_NOT ||
130                 lexer.ttype == lexer.TT_PROX) {
131                 int type = lexer.ttype;
132                 String val = lexer.sval;
133                 match(type);
134                 ModifierSet ms = gatherModifiers(val);
135                 CQLNode term2 = parseTerm(index, relation);
136                 term = ((type == lexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
137                         (type == lexer.TT_OR)  ? new CQLOrNode (term, term2, ms) :
138                         (type == lexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
139                                                  new CQLProxNode(term, term2, ms));
140             } else {
141                 throw new CQLParseException("expected boolean, got " +
142                                             lexer.render());
143             }
144         }
145
146         debug("no more ops");
147         return term;
148     }
149
150     private ModifierSet gatherModifiers(String base)
151         throws CQLParseException, IOException {
152         debug("in gatherModifiers()");
153
154         ModifierSet ms = new ModifierSet(base);
155         while (lexer.ttype == '/') {
156             match('/');
157             if (lexer.ttype != lexer.TT_WORD)
158                 throw new CQLParseException("expected modifier, "
159                                             + "got " + lexer.render());
160             String type = lexer.sval.toLowerCase();
161             match(lexer.ttype);
162             if (!isSymbolicRelation()) {
163                 // It's a simple modifier consisting of type only
164                 ms.addModifier(type);
165             } else {
166                 // It's a complex modifier of the form type=value
167                 String comparision = lexer.render(lexer.ttype, false);
168                 match(lexer.ttype);
169                 String value = matchSymbol("modifier value");
170                 ms.addModifier(type, comparision, value);
171             }
172         }
173
174         return ms;
175     }
176
177     private CQLNode parseTerm(String index, CQLRelation relation)
178         throws CQLParseException, IOException {
179         debug("in parseTerm()");
180
181         String word;
182         while (true) {
183             if (lexer.ttype == '(') {
184                 debug("parenthesised term");
185                 match('(');
186                 CQLNode expr = parseQuery(index, relation);
187                 match(')');
188                 return expr;
189             } else if (lexer.ttype == '>') {
190                 return parsePrefix(index, relation, false);
191             }
192
193             debug("non-parenthesised term");
194             word = matchSymbol("index or term");
195             while (lexer.ttype == lexer.TT_WORD && !isRelation()) {
196               word = word + " " + lexer.sval;
197               match(lexer.TT_WORD);
198             }
199
200             if (!isRelation())
201                 break;
202
203             index = word;
204             String relstr = (lexer.ttype == lexer.TT_WORD ?
205                              lexer.sval : lexer.render(lexer.ttype, false));
206             relation = new CQLRelation(relstr);
207             match(lexer.ttype);
208             ModifierSet ms = gatherModifiers(relstr);
209             relation.setModifiers(ms);
210             debug("index='" + index + ", " +
211                   "relation='" + relation.toCQL() + "'");
212         }
213
214         CQLTermNode node = new CQLTermNode(index, relation, word);
215         debug("made term node " + node.toCQL());
216         return node;
217     }
218
219     private CQLNode parsePrefix(String index, CQLRelation relation,
220                                 boolean topLevel)
221         throws CQLParseException, IOException {
222         debug("prefix mapping");
223
224         match('>');
225         String name = null;
226         String identifier = matchSymbol("prefix-name");
227         if (lexer.ttype == '=') {
228             match('=');
229             name = identifier;
230             identifier = matchSymbol("prefix-identifer");
231         }
232         CQLNode node = topLevel ?
233             parseTopLevelPrefixes(index, relation) :
234             parseQuery(index, relation);
235
236         return new CQLPrefixNode(name, identifier, node);
237     }
238
239     private boolean isRelation() {
240         debug("isRelation: checking ttype=" + lexer.ttype +
241               " (" + lexer.render() + ")");
242         if (lexer.ttype == lexer.TT_WORD &&
243             (lexer.sval.indexOf('.') >= 0 ||
244              lexer.sval.equals("any") ||
245              lexer.sval.equals("all") ||
246              lexer.sval.equals("within") ||
247              lexer.sval.equals("encloses") ||
248              lexer.sval.equals("exact") ||
249              (lexer.sval.equals("scr") && compat != V1POINT2) ||
250              (lexer.sval.equals("adj") && compat == V1POINT2)))
251           return true;
252
253         return isSymbolicRelation();
254     }
255
256     private boolean isSymbolicRelation() {
257         debug("isSymbolicRelation: checking ttype=" + lexer.ttype +
258               " (" + lexer.render() + ")");
259         return (lexer.ttype == '<' ||
260                 lexer.ttype == '>' ||
261                 lexer.ttype == '=' ||
262                 lexer.ttype == lexer.TT_LE ||
263                 lexer.ttype == lexer.TT_GE ||
264                 lexer.ttype == lexer.TT_NE ||
265                 lexer.ttype == lexer.TT_EQEQ);
266     }
267
268     private void match(int token)
269         throws CQLParseException, IOException {
270         debug("in match(" + lexer.render(token, true) + ")");
271         if (lexer.ttype != token)
272             throw new CQLParseException("expected " +
273                                         lexer.render(token, true) +
274                                         ", " + "got " + lexer.render());
275         int tmp = lexer.nextToken();
276         debug("match() got token=" + lexer.ttype + ", " +
277               "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
278               " (tmp=" + tmp + ")");
279     }
280
281     private String matchSymbol(String expected)
282         throws CQLParseException, IOException {
283
284         debug("in matchSymbol()");
285         if (lexer.ttype == lexer.TT_WORD ||
286             lexer.ttype == lexer.TT_NUMBER ||
287             lexer.ttype == '"' ||
288             // The following is a complete list of keywords.  Because
289             // they're listed here, they can be used unquoted as
290             // indexes, terms, prefix names and prefix identifiers.
291             // ### Instead, we should ask the lexer whether what we
292             // have is a keyword, and let the knowledge reside there.
293             lexer.ttype == lexer.TT_AND ||
294             lexer.ttype == lexer.TT_OR ||
295             lexer.ttype == lexer.TT_NOT ||
296             lexer.ttype == lexer.TT_PROX ||
297             lexer.ttype == lexer.TT_SORTBY) {
298             String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
299                 lexer.render() : lexer.sval;
300             match(lexer.ttype);
301             return symbol;
302         }
303
304         throw new CQLParseException("expected " + expected + ", " +
305                                     "got " + lexer.render());
306     }
307
308
309     /**
310      * Simple test-harness for the CQLParser class.
311      * <P>
312      * Reads a CQL query either from its command-line argument, if
313      * there is one, or standard input otherwise.  So these two
314      * invocations are equivalent:
315      * <PRE>
316      *  CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
317      *  echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
318      * </PRE>
319      * The test-harness parses the supplied query and renders is as
320      * XCQL, so that both of the invocations above produce the
321      * following output:
322      * <PRE>
323      *  &lt;triple&gt;
324      *    &lt;boolean&gt;
325      *      &lt;value&gt;and&lt;/value&gt;
326      *    &lt;/boolean&gt;
327      *    &lt;triple&gt;
328      *      &lt;boolean&gt;
329      *        &lt;value&gt;or&lt;/value&gt;
330      *      &lt;/boolean&gt;
331      *      &lt;searchClause&gt;
332      *        &lt;index&gt;au&lt;/index&gt;
333      *        &lt;relation&gt;
334      *          &lt;value&gt;=&lt;/value&gt;
335      *        &lt;/relation&gt;
336      *        &lt;term&gt;Kerninghan&lt;/term&gt;
337      *      &lt;/searchClause&gt;
338      *      &lt;searchClause&gt;
339      *        &lt;index&gt;au&lt;/index&gt;
340      *        &lt;relation&gt;
341      *          &lt;value&gt;=&lt;/value&gt;
342      *        &lt;/relation&gt;
343      *        &lt;term&gt;Ritchie&lt;/term&gt;
344      *      &lt;/searchClause&gt;
345      *    &lt;/triple&gt;
346      *    &lt;searchClause&gt;
347      *      &lt;index&gt;ti&lt;/index&gt;
348      *      &lt;relation&gt;
349      *        &lt;value&gt;=&lt;/value&gt;
350      *      &lt;/relation&gt;
351      *      &lt;term&gt;Unix&lt;/term&gt;
352      *    &lt;/searchClause&gt;
353      *  &lt;/triple&gt;
354      * </PRE>
355      * <P>
356      * @param -1
357      *  CQL version 1.1 (default version 1.2)
358      * @param -d
359      *  Debug mode: extra output written to stderr.
360      * @param -c
361      *  Causes the output to be written in CQL rather than XCQL - that
362      *  is, a query equivalent to that which was input, is output.  In
363      *  effect, the test harness acts as a query canonicaliser.
364      * @return
365      *  The input query, either as XCQL [default] or CQL [if the
366      *  <TT>-c</TT> option is supplied].
367      */
368     public static void main (String[] args) {
369         char mode = 'x';        // x=XCQL, c=CQL, p=PQF
370         String pfile = null;
371
372         Vector<String> argv = new Vector<String>();
373         for (int i = 0; i < args.length; i++) {
374             argv.add(args[i]);
375         }
376
377         int compat = V1POINT2;
378         if (argv.size() > 0 && argv.get(0).equals("-1")) {
379             compat = V1POINT1;
380             argv.remove(0);
381         }
382
383         if (argv.size() > 0 && argv.get(0).equals("-d")) {
384             DEBUG = true;
385             argv.remove(0);
386         }
387
388         if (argv.size() > 0 && argv.get(0).equals("-c")) {
389             mode = 'c';
390             argv.remove(0);
391         } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
392             mode = 'p';
393             argv.remove(0);
394             pfile = (String) argv.get(0);
395             argv.remove(0);
396         }
397
398         if (argv.size() > 1) {
399             System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
400                                "[-p <pqf-properties> [<CQL-query>]");
401             System.err.println("If unspecified, query is read from stdin");
402             System.exit(1);
403         }
404
405         String cql;
406         if (argv.size() == 1) {
407             cql = (String) argv.get(0);
408         } else {
409             byte[] bytes = new byte[10000];
410             try {
411                 // Read in the whole of standard input in one go
412                 int nbytes = System.in.read(bytes);
413             } catch (IOException ex) {
414                 System.err.println("Can't read query: " + ex.getMessage());
415                 System.exit(2);
416             }
417             cql = new String(bytes);
418         }
419
420         CQLParser parser = new CQLParser(compat);
421         CQLNode root = null;
422         try {
423             root = parser.parse(cql);
424         } catch (CQLParseException ex) {
425             System.err.println("Syntax error: " + ex.getMessage());
426             System.exit(3);
427         } catch (IOException ex) {
428             System.err.println("Can't compile query: " + ex.getMessage());
429             System.exit(4);
430         }
431
432         try {
433             if (mode == 'c') {
434                 System.out.println(root.toCQL());
435             } else if (mode == 'p') {
436                 InputStream f = new FileInputStream(pfile);
437                 if (f == null)
438                     throw new FileNotFoundException(pfile);
439
440                 Properties config = new Properties();
441                 config.load(f);
442                 f.close();
443                 System.out.println(root.toPQF(config));
444             } else {
445                 System.out.print(root.toXCQL(0));
446             }
447         } catch (IOException ex) {
448             System.err.println("Can't render query: " + ex.getMessage());
449             System.exit(5);
450         } catch (UnknownIndexException ex) {
451             System.err.println("Unknown index: " + ex.getMessage());
452             System.exit(6);
453         } catch (UnknownRelationException ex) {
454             System.err.println("Unknown relation: " + ex.getMessage());
455             System.exit(7);
456         } catch (UnknownRelationModifierException ex) {
457             System.err.println("Unknown relation modifier: " +
458                                ex.getMessage());
459             System.exit(8);
460         } catch (UnknownPositionException ex) {
461             System.err.println("Unknown position: " + ex.getMessage());
462             System.exit(9);
463         } catch (PQFTranslationException ex) {
464             // We catch all of this class's subclasses, so --
465             throw new Error("can't get a PQFTranslationException");
466         }
467     }
468 }