Allow a list of quoted terms
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / CQLParser.java
1
2 package org.z3950.zing.cql;
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.util.Properties;
6 import java.io.InputStream;
7 import java.io.FileInputStream;
8 import java.io.FileNotFoundException;
9 import java.io.InputStreamReader;
10 import java.io.Reader;
11 import java.io.StringReader;
12 import java.util.ArrayList;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Set;
16
17
18 /**
19  * Compiles CQL strings into parse trees of CQLNode subtypes.
20  *
21  * @see         <A href="http://zing.z3950.org/cql/index.html"
22  *                      >http://zing.z3950.org/cql/index.html</A>
23  */
24 public class CQLParser {
25     private CQLTokenizer lexer;
26     private final int compat;   // When false, implement CQL 1.2
27     private final Set<String> customRelations = new HashSet<String>();
28     
29     public static final int V1POINT1 = 12368;
30     public static final int V1POINT2 = 12369;
31     public static final int V1POINT1SORT = 12370;
32     public final boolean allowKeywordTerms;
33
34     static private boolean DEBUG = false;
35     static private boolean LEXDEBUG = false;
36
37     /**
38      * The new parser implements a dialect of CQL specified by the
39      * <tt>compat</tt> argument:
40      * <ul>
41      *  <li>V1POINT1 - CQL version 1.1
42      *  </li>
43      *  <li>V1POINT2 - CQL version 1.2
44      *  </li>
45      *  <li>V1POINT1SORT - CQL version 1.1 but including
46      *          <tt>sortby</tt> as specified for CQL 1.2.
47      *  </li>
48      * </ul>
49      */
50     public CQLParser(int compat) {
51         this.compat = compat;
52         this.allowKeywordTerms = true;
53     }
54     
55     /**
56      * Official CQL grammar allows registered keywords like 'and/or/not/sortby/prox' 
57      * to be used unquoted in terms. This constructor allows to create an instance 
58      * of a parser that prohibits this behavior while sacrificing compatibility.
59      * @param compat CQL version compatibility
60      * @param allowKeywordTerms when false registered keywords are disallowed in unquoted terms
61      */
62     public CQLParser(int compat, boolean allowKeywordTerms) {
63         this.compat = compat;
64         this.allowKeywordTerms = allowKeywordTerms;
65     }
66     
67     /**
68      * The new parser implements CQL 1.2
69      */
70     public CQLParser() {
71         this.compat = V1POINT2;
72         this.allowKeywordTerms = true;
73     }
74
75     private static void debug(String str) {
76         if (DEBUG)
77             System.err.println("PARSEDEBUG: " + str);
78     }
79     
80     /**
81      * Registers custom relation in this parser. Note that when a custom relation
82      * is registered the parser is no longer strictly compliant with the chosen spec.
83      * @param relation
84      * @return true if custom relation has not been registered already
85      */
86     public boolean registerCustomRelation(String relation) {
87       return customRelations.add(relation);
88     }
89     
90     /**
91      * Unregisters previously registered custom relation in this instance of the parser.
92      * @param relation
93      * @return true is relation has been previously registered
94      */
95     public boolean unregisterCustomRelation(String relation) {
96       return customRelations.remove(relation);
97     }
98
99     /**
100      * Compiles a CQL query.
101      * <P>
102      * The resulting parse tree may be further processed by hand (see
103      * the individual node-types' documentation for details on the
104      * data structure) or, more often, simply rendered out in the
105      * desired form using one of the back-ends.  <TT>toCQL()</TT>
106      * returns a decompiled CQL query equivalent to the one that was
107      * compiled in the first place; <TT>toXCQL()</TT> returns an
108      * XML snippet representing the query; and <TT>toPQF()</TT>
109      * returns the query rendered in Index Data's Prefix Query
110      * Format.
111      *
112      * @param cql       The query
113      * @return          A CQLNode object which is the root of a parse
114      * tree representing the query.  */
115     public CQLNode parse(String cql)
116         throws CQLParseException, IOException {
117         lexer = new CQLLexer(cql, LEXDEBUG);
118
119         lexer.move();
120         debug("about to parseQuery()");
121         CQLNode root = parseTopLevelPrefixes("cql.serverChoice",
122                 new CQLRelation(compat == V1POINT2 ? "=" : "scr"));
123         if (lexer.what() != CQLTokenizer.TT_EOF)
124             throw new CQLParseException("junk after end: " + lexer.render(), 
125               lexer.pos());
126
127         return root;
128     }
129
130     private CQLNode parseTopLevelPrefixes(String index, CQLRelation relation)
131         throws CQLParseException, IOException {
132         debug("top-level prefix mapping");
133
134         if (lexer.what() == '>') {
135             return parsePrefix(index, relation, true);
136         }
137
138         CQLNode node = parseQuery(index, relation);
139         if ((compat == V1POINT2 || compat == V1POINT1SORT) &&
140             lexer.what() == CQLTokenizer.TT_SORTBY) {
141             match(lexer.what());
142             debug("sortspec");
143
144             CQLSortNode sortnode = new CQLSortNode(node);
145             while (lexer.what() != CQLTokenizer.TT_EOF) {
146                 String sortindex = matchSymbol("sort index");
147                 ModifierSet ms = gatherModifiers(sortindex);
148                 sortnode.addSortIndex(ms);
149             }
150
151             if (sortnode.keys.size() == 0) {
152                 throw new CQLParseException("no sort keys", lexer.pos());
153             }
154
155             node = sortnode;
156         }
157
158         return node;
159     }
160
161     private CQLNode parseQuery(String index, CQLRelation relation)
162         throws CQLParseException, IOException {
163         debug("in parseQuery()");
164
165         CQLNode term = parseTerm(index, relation);
166         while (lexer.what() != CQLTokenizer.TT_EOF &&
167                lexer.what() != ')' &&
168                lexer.what() != CQLTokenizer.TT_SORTBY) {
169             if (lexer.what() == CQLTokenizer.TT_AND ||
170                 lexer.what() == CQLTokenizer.TT_OR ||
171                 lexer.what() == CQLTokenizer.TT_NOT ||
172                 lexer.what() == CQLTokenizer.TT_PROX) {
173                 int type = lexer.what();
174                 String val = lexer.value();
175                 match(type);
176                 ModifierSet ms = gatherModifiers(val);
177                 CQLNode term2 = parseTerm(index, relation);
178                 term = ((type == CQLTokenizer.TT_AND) ? new CQLAndNode(term, term2, ms) :
179                         (type == CQLTokenizer.TT_OR)  ? new CQLOrNode (term, term2, ms) :
180                         (type == CQLTokenizer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
181                                                  new CQLProxNode(term, term2, ms));
182             } else {
183                 throw new CQLParseException("expected boolean, got " +
184                                             lexer.render(), lexer.pos());
185             }
186         }
187
188         debug("no more ops");
189         return term;
190     }
191
192     private ModifierSet gatherModifiers(String base)
193         throws CQLParseException, IOException {
194         debug("in gatherModifiers()");
195
196         ModifierSet ms = new ModifierSet(base);
197         while (lexer.what() == '/') {
198             match('/');
199             if (lexer.what() != CQLTokenizer.TT_WORD)
200                 throw new CQLParseException("expected modifier, "
201                                             + "got " + lexer.render(), 
202                   lexer.pos());
203             String type = lexer.value().toLowerCase();
204             match(lexer.what());
205             if (!isSymbolicRelation()) {
206                 // It's a simple modifier consisting of type only
207                 ms.addModifier(type);
208             } else {
209                 // It's a complex modifier of the form type=value
210                 String comparision = lexer.render(lexer.what(), false);
211                 match(lexer.what());
212                 String value = matchSymbol("modifier value");
213                 ms.addModifier(type, comparision, value);
214             }
215         }
216
217         return ms;
218     }
219
220     private CQLNode parseTerm(String index, CQLRelation relation)
221         throws CQLParseException, IOException {
222         debug("in parseTerm()");
223
224         String word;
225         while (true) {
226             if (lexer.what() == '(') {
227                 debug("parenthesised term");
228                 match('(');
229                 CQLNode expr = parseQuery(index, relation);
230                 match(')');
231                 return expr;
232             } else if (lexer.what() == '>') {
233                 return parsePrefix(index, relation, false);
234             }
235
236             debug("non-parenthesised term");
237             word = matchSymbol("index or term");
238             while (isWordOrString() && !isRelation()) {
239               word = word + " " + lexer.value();
240               match(lexer.what());
241             }
242
243             if (!isRelation())
244               break;
245
246             index = word;
247             String relstr = (lexer.what() == CQLTokenizer.TT_WORD ?
248                              lexer.value() : lexer.render(lexer.what(), false));
249             relation = new CQLRelation(relstr);
250             match(lexer.what());
251             ModifierSet ms = gatherModifiers(relstr);
252             relation.ms = ms;
253             debug("index='" + index + ", " +
254                   "relation='" + relation.toCQL() + "'");
255         }
256
257         CQLTermNode node = new CQLTermNode(index, relation, word);
258         debug("made term node " + node.toCQL());
259         return node;
260     }
261
262     private CQLNode parsePrefix(String index, CQLRelation relation,
263                                 boolean topLevel)
264         throws CQLParseException, IOException {
265         debug("prefix mapping");
266
267         match('>');
268         String name = null;
269         String identifier = matchSymbol("prefix-name");
270         if (lexer.what() == '=') {
271             match('=');
272             name = identifier;
273             identifier = matchSymbol("prefix-identifer");
274         }
275         CQLNode node = topLevel ?
276             parseTopLevelPrefixes(index, relation) :
277             parseQuery(index, relation);
278
279         return new CQLPrefixNode(name, identifier, node);
280     }
281     
282     private boolean isWordOrString() {
283       return CQLTokenizer.TT_WORD == lexer.what() 
284         || CQLTokenizer.TT_STRING == lexer.what();
285     }
286
287     private boolean isRelation() {
288         debug("isRelation: checking what()=" + lexer.what() +
289               " (" + lexer.render() + ")");
290         if (lexer.what() == CQLTokenizer.TT_WORD &&
291             (lexer.value().indexOf('.') >= 0 ||
292              lexer.value().equals("any") ||
293              lexer.value().equals("all") ||
294              lexer.value().equals("within") ||
295              lexer.value().equals("encloses") ||
296              (lexer.value().equals("exact") && compat != V1POINT2) ||
297              (lexer.value().equals("scr") && compat != V1POINT2) ||
298              (lexer.value().equals("adj") && compat == V1POINT2) ||
299              customRelations.contains(lexer.value())))
300           return true;
301
302         return isSymbolicRelation();
303     }
304
305     private boolean isSymbolicRelation() {
306         debug("isSymbolicRelation: checking what()=" + lexer.what() +
307               " (" + lexer.render() + ")");
308         return (lexer.what() == '<' ||
309                 lexer.what() == '>' ||
310                 lexer.what() == '=' ||
311                 lexer.what() == CQLTokenizer.TT_LE ||
312                 lexer.what() == CQLTokenizer.TT_GE ||
313                 lexer.what() == CQLTokenizer.TT_NE ||
314                 lexer.what() == CQLTokenizer.TT_EQEQ);
315     }
316
317     private void match(int token)
318         throws CQLParseException, IOException {
319         debug("in match(" + lexer.render(token, true) + ")");
320         if (lexer.what() != token)
321             throw new CQLParseException("expected " +
322                                         lexer.render(token, true) +
323                                         ", " + "got " + lexer.render(), 
324               lexer.pos());
325         lexer.move();
326         debug("match() got token=" + lexer.what() + ", value()='" + lexer.value() + "'");
327     }
328
329     private String matchSymbol(String expected)
330         throws CQLParseException, IOException {
331
332         debug("in matchSymbol()");
333         if (lexer.what() == CQLTokenizer.TT_WORD ||
334             lexer.what() == CQLTokenizer.TT_STRING ||
335             // The following is a complete list of keywords.  Because
336             // they're listed here, they can be used unquoted as
337             // indexes, terms, prefix names and prefix identifiers.
338             (allowKeywordTerms &&
339             lexer.what() == CQLTokenizer.TT_AND ||
340             lexer.what() == CQLTokenizer.TT_OR ||
341             lexer.what() == CQLTokenizer.TT_NOT ||
342             lexer.what() == CQLTokenizer.TT_PROX ||
343             lexer.what() == CQLTokenizer.TT_SORTBY)) {
344             String symbol = lexer.value();
345             match(lexer.what());
346             return symbol;
347         }
348
349         throw new CQLParseException("expected " + expected + ", " +
350                                     "got " + lexer.render(), lexer.pos());
351     }
352
353
354     /**
355      * Simple test-harness for the CQLParser class.
356      * <P>
357      * Reads a CQL query either from its command-line argument, if
358      * there is one, or standard input otherwise.  So these two
359      * invocations are equivalent:
360      * <PRE>
361      *  CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
362      *  echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
363      * </PRE>
364      * The test-harness parses the supplied query and renders is as
365      * XCQL, so that both of the invocations above produce the
366      * following output:
367      * <PRE>
368      *  &lt;triple&gt;
369      *    &lt;boolean&gt;
370      *      &lt;value&gt;and&lt;/value&gt;
371      *    &lt;/boolean&gt;
372      *    &lt;triple&gt;
373      *      &lt;boolean&gt;
374      *        &lt;value&gt;or&lt;/value&gt;
375      *      &lt;/boolean&gt;
376      *      &lt;searchClause&gt;
377      *        &lt;index&gt;au&lt;/index&gt;
378      *        &lt;relation&gt;
379      *          &lt;value&gt;=&lt;/value&gt;
380      *        &lt;/relation&gt;
381      *        &lt;term&gt;Kerninghan&lt;/term&gt;
382      *      &lt;/searchClause&gt;
383      *      &lt;searchClause&gt;
384      *        &lt;index&gt;au&lt;/index&gt;
385      *        &lt;relation&gt;
386      *          &lt;value&gt;=&lt;/value&gt;
387      *        &lt;/relation&gt;
388      *        &lt;term&gt;Ritchie&lt;/term&gt;
389      *      &lt;/searchClause&gt;
390      *    &lt;/triple&gt;
391      *    &lt;searchClause&gt;
392      *      &lt;index&gt;ti&lt;/index&gt;
393      *      &lt;relation&gt;
394      *        &lt;value&gt;=&lt;/value&gt;
395      *      &lt;/relation&gt;
396      *      &lt;term&gt;Unix&lt;/term&gt;
397      *    &lt;/searchClause&gt;
398      *  &lt;/triple&gt;
399      * </PRE>
400      * <P>
401      * @param -1
402      *  CQL version 1.1 (default version 1.2)
403      * @param -d
404      *  Debug mode: extra output written to stderr.
405      * @param -c
406      *  Causes the output to be written in CQL rather than XCQL - that
407      *  is, a query equivalent to that which was input, is output.  In
408      *  effect, the test harness acts as a query canonicaliser.
409      * @return
410      *  The input query, either as XCQL [default] or CQL [if the
411      *  <TT>-c</TT> option is supplied].
412      */
413     public static void main (String[] args) {
414         char mode = 'x';        // x=XCQL, c=CQL, p=PQF
415         String pfile = null;
416
417         List<String> argv = new ArrayList<String>();
418         for (int i = 0; i < args.length; i++) {
419             argv.add(args[i]);
420         }
421
422         int compat = V1POINT2;
423         if (argv.size() > 0 && argv.get(0).equals("-1")) {
424             compat = V1POINT1;
425             argv.remove(0);
426         }
427
428         if (argv.size() > 0 && argv.get(0).equals("-d")) {
429             DEBUG = true;
430             argv.remove(0);
431         }
432
433         if (argv.size() > 0 && argv.get(0).equals("-c")) {
434             mode = 'c';
435             argv.remove(0);
436         } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
437             mode = 'p';
438             argv.remove(0);
439             pfile = (String) argv.get(0);
440             argv.remove(0);
441         }
442
443         if (argv.size() > 1) {
444             System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
445                                "[-p <pqf-properties> [<CQL-query>]");
446             System.err.println("If unspecified, query is read from stdin");
447             System.exit(1);
448         }
449
450         String cql;
451         if (argv.size() == 1) {
452             cql = (String) argv.get(0);
453         } else {
454             BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
455             try {
456                 // read a single line of input
457               cql = buff.readLine();
458               if (cql == null) {
459                 System.err.println("Can't read query from stdin");
460                 System.exit(2);
461                 return;
462               }
463             } catch (IOException ex) {
464                 System.err.println("Can't read query: " + ex.getMessage());
465                 System.exit(2);
466                 return;
467             }
468         }
469
470         CQLParser parser = new CQLParser(compat);
471         CQLNode root;
472         try {
473             root = parser.parse(cql);
474         } catch (CQLParseException ex) {
475             System.err.println("Syntax error: " + ex.getMessage());
476             System.exit(3);
477             return; //compiler
478         } catch (IOException ex) {
479             System.err.println("Can't compile query: " + ex.getMessage());
480             System.exit(4);
481             return; //compiler
482         }
483
484         try {
485             if (mode == 'c') {
486                 System.out.println(root.toCQL());
487             } else if (mode == 'p') {
488               try {
489                 InputStream f = new FileInputStream(pfile);
490                 Properties config = new Properties();
491                 config.load(f);
492                 f.close();
493                 System.out.println(root.toPQF(config));
494               } catch (IOException ex) {
495                 System.err.println("Can't load PQF properties:" + 
496                   ex.getMessage());
497                 System.exit(5);
498               }
499             } else {
500                 System.out.print(root.toXCQL());
501             }
502         } catch (UnknownIndexException ex) {
503             System.err.println("Unknown index: " + ex.getMessage());
504             System.exit(6);
505         } catch (UnknownRelationException ex) {
506             System.err.println("Unknown relation: " + ex.getMessage());
507             System.exit(7);
508         } catch (UnknownRelationModifierException ex) {
509             System.err.println("Unknown relation modifier: " +
510                                ex.getMessage());
511             System.exit(8);
512         } catch (UnknownPositionException ex) {
513             System.err.println("Unknown position: " + ex.getMessage());
514             System.exit(9);
515         } catch (PQFTranslationException ex) {
516             System.err.println("Cannot translate to PQF: " + ex.getMessage());
517             System.exit(10);
518         }
519     }
520 }