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