Parse complex relation modifiers.
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLParser.java
1 // $Id: CQLParser.java,v 1.30 2007-06-28 00:24:48 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.30 2007-06-28 00:24:48 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 &&
64                lexer.ttype != ')') {
65             if (lexer.ttype == lexer.TT_AND) {
66                 match(lexer.TT_AND);
67                 CQLNode term2 = parseTerm(index, relation);
68                 term = new CQLAndNode(term, term2);
69             } else if (lexer.ttype == lexer.TT_OR) {
70                 match(lexer.TT_OR);
71                 CQLNode term2 = parseTerm(index, relation);
72                 term = new CQLOrNode(term, term2);
73             } else if (lexer.ttype == lexer.TT_NOT) {
74                 match(lexer.TT_NOT);
75                 CQLNode term2 = parseTerm(index, relation);
76                 term = new CQLNotNode(term, term2);
77             } else if (lexer.ttype == lexer.TT_PROX) {
78                 match(lexer.TT_PROX);
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 CQLNode parseTerm(String index, CQLRelation relation)
95         throws CQLParseException, IOException {
96         debug("in parseTerm()");
97
98         String word;
99         while (true) {
100             if (lexer.ttype == '(') {
101                 debug("parenthesised term");
102                 match('(');
103                 CQLNode expr = parseQuery(index, relation);
104                 match(')');
105                 return expr;
106             } else if (lexer.ttype == '>') {
107                 match('>');
108                 return parsePrefix(index, relation);
109             }
110
111             debug("non-parenthesised term");
112             word = matchSymbol("index or term");
113             if (!isRelation() && lexer.ttype != lexer.TT_WORD)
114                 break;
115
116             index = word;
117             relation = new CQLRelation(lexer.ttype == lexer.TT_WORD ?
118                                        lexer.sval :
119                                        lexer.render(lexer.ttype, false));
120             match(lexer.ttype);
121
122             while (lexer.ttype == '/') {
123                 match('/');
124                 if (lexer.ttype != lexer.TT_WORD)
125                     throw new CQLParseException("expected relation 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                     relation.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
137                     // Yuck
138                     String value = lexer.ttype == lexer.TT_WORD ? lexer.sval :
139                         (double) lexer.nval == (int) lexer.nval ?
140                         new Integer((int) lexer.nval).toString() :
141                         new Double((double) lexer.nval).toString();
142
143                     matchSymbol("relation-modifier value");
144                     relation.addModifier(type, comparision, value);
145                 }
146             }
147
148             debug("index='" + index + ", " +
149                   "relation='" + relation.toCQL() + "'");
150         }
151
152         CQLTermNode node = new CQLTermNode(index, relation, word);
153         debug("made term node " + node.toCQL());
154         return node;
155     }
156
157     private CQLNode parsePrefix(String index, CQLRelation relation)
158         throws CQLParseException, IOException {
159         debug("prefix mapping");
160
161         String name = null;
162         String identifier = matchSymbol("prefix-name");
163         if (lexer.ttype == '=') {
164             match('=');
165             name = identifier;
166             identifier = matchSymbol("prefix-identifer");
167         }
168         CQLNode term = parseQuery(index, relation);
169         return new CQLPrefixNode(name, identifier, term);
170     }
171
172     private void gatherProxParameters(CQLProxNode node)
173         throws CQLParseException, IOException {
174         for (int i = 0; i < 4; i++) {
175             if (lexer.ttype != '/')
176                 return;         // end of proximity parameters
177
178             match('/');
179             if (lexer.ttype != '/') {
180                 // not an omitted default
181                 switch (i) {
182                     // Order should be: relation/distance/unit/ordering
183                     // For now, use MA's: unit/relation/distance/ordering
184                 case 0: gatherProxRelation(node); break;
185                 case 1: gatherProxDistance(node); break;
186                 case 2: gatherProxUnit(node); break;
187                 case 3: gatherProxOrdering(node); break;
188                 }
189             }
190         }
191     }
192
193     private void gatherProxRelation(CQLProxNode node)
194         throws CQLParseException, IOException {
195         if (!isRelation())
196             throw new CQLParseException("expected proximity relation, got " +
197                                         lexer.render());
198         node.addModifier("relation", null, lexer.render(lexer.ttype, false));
199         match(lexer.ttype);
200         debug("gPR matched " + lexer.render(lexer.ttype, false));
201     }
202
203     private void gatherProxDistance(CQLProxNode node)
204         throws CQLParseException, IOException {
205         if (lexer.ttype != lexer.TT_NUMBER)
206             throw new CQLParseException("expected proximity distance, got " +
207                                         lexer.render());
208         node.addModifier("distance", null, lexer.render(lexer.ttype, false));
209         match(lexer.ttype);
210         debug("gPD matched " + lexer.render(lexer.ttype, false));
211     }
212
213     private void gatherProxUnit(CQLProxNode node)
214         throws CQLParseException, IOException {
215         if (lexer.ttype != lexer.TT_pWORD &&
216             lexer.ttype != lexer.TT_SENTENCE &&
217             lexer.ttype != lexer.TT_PARAGRAPH &&
218             lexer.ttype != lexer.TT_ELEMENT)
219             throw new CQLParseException("expected proximity unit, got " +
220                                         lexer.render());
221         node.addModifier("unit", null, lexer.render());
222         match(lexer.ttype);
223     }
224
225     private void gatherProxOrdering(CQLProxNode node)
226         throws CQLParseException, IOException {
227         if (lexer.ttype != lexer.TT_ORDERED &&
228             lexer.ttype != lexer.TT_UNORDERED)
229             throw new CQLParseException("expected proximity ordering, got " +
230                                         lexer.render());
231         node.addModifier("ordering", null, lexer.render());
232         match(lexer.ttype);
233     }
234
235     // Checks for a relation that may be used inside a prox operator
236     private boolean isRelation() {
237         debug("isRelation: checking ttype=" + lexer.ttype +
238               " (" + lexer.render() + ")");
239         return (lexer.ttype == '<' ||
240                 lexer.ttype == '>' ||
241                 lexer.ttype == '=' ||
242                 lexer.ttype == lexer.TT_LE ||
243                 lexer.ttype == lexer.TT_GE ||
244                 lexer.ttype == lexer.TT_NE);
245     }
246
247     private void match(int token)
248         throws CQLParseException, IOException {
249         debug("in match(" + lexer.render(token, true) + ")");
250         if (lexer.ttype != token)
251             throw new CQLParseException("expected " +
252                                         lexer.render(token, true) +
253                                         ", " + "got " + lexer.render());
254         int tmp = lexer.nextToken();
255         debug("match() got token=" + lexer.ttype + ", " +
256               "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
257               " (tmp=" + tmp + ")");
258     }
259
260     private String matchSymbol(String expected)
261         throws CQLParseException, IOException {
262
263         debug("in matchSymbol()");
264         if (lexer.ttype == lexer.TT_WORD ||
265             lexer.ttype == lexer.TT_NUMBER ||
266             lexer.ttype == '"' ||
267             // The following is a complete list of keywords.  Because
268             // they're listed here, they can be used unquoted as
269             // indexes, terms, prefix names and prefix identifiers.
270             // ### Instead, we should ask the lexer whether what we
271             // have is a keyword, and let the knowledge reside there.
272             lexer.ttype == lexer.TT_AND ||
273             lexer.ttype == lexer.TT_OR ||
274             lexer.ttype == lexer.TT_NOT ||
275             lexer.ttype == lexer.TT_PROX ||
276             lexer.ttype == lexer.TT_pWORD ||
277             lexer.ttype == lexer.TT_SENTENCE ||
278             lexer.ttype == lexer.TT_PARAGRAPH ||
279             lexer.ttype == lexer.TT_ELEMENT ||
280             lexer.ttype == lexer.TT_ORDERED ||
281             lexer.ttype == lexer.TT_UNORDERED) {
282             String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
283                 lexer.render() : lexer.sval;
284             match(lexer.ttype);
285             return symbol;
286         }
287
288         throw new CQLParseException("expected " + expected + ", " +
289                                     "got " + lexer.render());
290     }
291
292
293     /**
294      * Simple test-harness for the CQLParser class.
295      * <P>
296      * Reads a CQL query either from its command-line argument, if
297      * there is one, or standard input otherwise.  So these two
298      * invocations are equivalent:
299      * <PRE>
300      *  CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
301      *  echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
302      * </PRE>
303      * The test-harness parses the supplied query and renders is as
304      * XCQL, so that both of the invocations above produce the
305      * following output:
306      * <PRE>
307      *  &lt;triple&gt;
308      *    &lt;boolean&gt;
309      *      &lt;value&gt;and&lt;/value&gt;
310      *    &lt;/boolean&gt;
311      *    &lt;triple&gt;
312      *      &lt;boolean&gt;
313      *        &lt;value&gt;or&lt;/value&gt;
314      *      &lt;/boolean&gt;
315      *      &lt;searchClause&gt;
316      *        &lt;index&gt;au&lt;/index&gt;
317      *        &lt;relation&gt;
318      *          &lt;value&gt;=&lt;/value&gt;
319      *        &lt;/relation&gt;
320      *        &lt;term&gt;Kerninghan&lt;/term&gt;
321      *      &lt;/searchClause&gt;
322      *      &lt;searchClause&gt;
323      *        &lt;index&gt;au&lt;/index&gt;
324      *        &lt;relation&gt;
325      *          &lt;value&gt;=&lt;/value&gt;
326      *        &lt;/relation&gt;
327      *        &lt;term&gt;Ritchie&lt;/term&gt;
328      *      &lt;/searchClause&gt;
329      *    &lt;/triple&gt;
330      *    &lt;searchClause&gt;
331      *      &lt;index&gt;ti&lt;/index&gt;
332      *      &lt;relation&gt;
333      *        &lt;value&gt;=&lt;/value&gt;
334      *      &lt;/relation&gt;
335      *      &lt;term&gt;Unix&lt;/term&gt;
336      *    &lt;/searchClause&gt;
337      *  &lt;/triple&gt;
338      * </PRE>
339      * <P>
340      * @param -c
341      *  Causes the output to be written in CQL rather than XCQL - that
342      *  is, a query equivalent to that which was input, is output.  In
343      *  effect, the test harness acts as a query canonicaliser.
344      * @return
345      *  The input query, either as XCQL [default] or CQL [if the
346      *  <TT>-c</TT> option is supplied].
347      */
348     public static void main (String[] args) {
349         char mode = 'x';        // x=XCQL, c=CQL, p=PQF
350         String pfile = null;
351
352         Vector<String> argv = new Vector<String>();
353         for (int i = 0; i < args.length; i++) {
354             argv.add(args[i]);
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 [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
374             System.err.println("If unspecified, query is read from stdin");
375             System.exit(1);
376         }
377
378         String cql;
379         if (argv.size() == 1) {
380             cql = (String) argv.get(0);
381         } else {
382             byte[] bytes = new byte[10000];
383             try {
384                 // Read in the whole of standard input in one go
385                 int nbytes = System.in.read(bytes);
386             } catch (IOException ex) {
387                 System.err.println("Can't read query: " + ex.getMessage());
388                 System.exit(2);
389             }
390             cql = new String(bytes);
391         }
392
393         CQLParser parser = new CQLParser();
394         CQLNode root = null;
395         try {
396             root = parser.parse(cql);
397         } catch (CQLParseException ex) {
398             System.err.println("Syntax error: " + ex.getMessage());
399             System.exit(3);
400         } catch (IOException ex) {
401             System.err.println("Can't compile query: " + ex.getMessage());
402             System.exit(4);
403         }
404
405         try {
406             if (mode == 'c') {
407                 System.out.println(root.toCQL());
408             } else if (mode == 'p') {
409                 InputStream f = new FileInputStream(pfile);
410                 if (f == null)
411                     throw new FileNotFoundException(pfile);
412
413                 Properties config = new Properties();
414                 config.load(f);
415                 f.close();
416                 System.out.println(root.toPQF(config));
417             } else {
418                 System.out.print(root.toXCQL(0));
419             }
420         } catch (IOException ex) {
421             System.err.println("Can't render query: " + ex.getMessage());
422             System.exit(5);
423         } catch (UnknownIndexException ex) {
424             System.err.println("Unknown index: " + ex.getMessage());
425             System.exit(6);
426         } catch (UnknownRelationException ex) {
427             System.err.println("Unknown relation: " + ex.getMessage());
428             System.exit(7);
429         } catch (UnknownRelationModifierException ex) {
430             System.err.println("Unknown relation modifier: " +
431                                ex.getMessage());
432             System.exit(8);
433         } catch (UnknownPositionException ex) {
434             System.err.println("Unknown position: " + ex.getMessage());
435             System.exit(9);
436         } catch (PQFTranslationException ex) {
437             // We catch all of this class's subclasses, so --
438             throw new Error("can't get a PQFTranslationException");
439         }
440     }
441 }