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