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