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