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