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