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