85ee63ba22abc249985f7dab27f939e5f79b8ed2
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLParser.java
1 // $Id: CQLParser.java,v 1.22 2002-11-20 01:15:15 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.22 2002-11-20 01:15:15 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.render(lexer.ttype, false));
118             match(lexer.ttype);
119
120             while (lexer.ttype == '/') {
121                 match('/');
122                 if (lexer.ttype != lexer.TT_RELEVANT &&
123                     lexer.ttype != lexer.TT_FUZZY &&
124                     lexer.ttype != lexer.TT_STEM &&
125                     lexer.ttype != lexer.TT_PHONETIC)
126                     throw new CQLParseException("expected relation modifier, "
127                                                 + "got " + lexer.render());
128                 relation.addModifier(lexer.sval.toLowerCase());
129                 match(lexer.ttype);
130             }
131
132             debug("qualifier='" + qualifier + ", " +
133                   "relation='" + relation.toCQL() + "'");
134         }
135
136         CQLTermNode node = new CQLTermNode(qualifier, relation, word);
137         debug("made term node " + node.toCQL());
138         return node;
139     }
140
141     private CQLNode parsePrefix(String qualifier, CQLRelation relation)
142         throws CQLParseException, IOException {
143         debug("prefix mapping");
144
145         String name = null;
146         String identifier = matchSymbol("prefix-name");
147         if (lexer.ttype == '=') {
148             match('=');
149             name = identifier;
150             identifier = matchSymbol("prefix-identifer");
151         }
152         CQLNode term = parseQuery(qualifier, relation);
153         return new CQLPrefixNode(name, identifier, term);
154     }
155
156     private void gatherProxParameters(CQLProxNode node)
157         throws CQLParseException, IOException {
158         for (int i = 0; i < 4; i++) {
159             if (lexer.ttype != '/')
160                 return;         // end of proximity parameters
161
162             match('/');
163             if (lexer.ttype != '/') {
164                 // not an omitted default
165                 switch (i) {
166                     // Order should be: relation/distance/unit/ordering
167                     // For now, use MA's: unit/relation/distance/ordering
168                 case 0: gatherProxRelation(node); break;
169                 case 1: gatherProxDistance(node); break;
170                 case 2: gatherProxUnit(node); break;
171                 case 3: gatherProxOrdering(node); break;
172                 }
173             }
174         }
175     }
176
177     private void gatherProxRelation(CQLProxNode node)
178         throws CQLParseException, IOException {
179         if (!isProxRelation())
180             throw new CQLParseException("expected proximity relation, got " +
181                                         lexer.render());
182         node.addModifier("relation", lexer.render(lexer.ttype, false));
183         match(lexer.ttype);
184         debug("gPR matched " + lexer.render(lexer.ttype, false));
185     }
186
187     private void gatherProxDistance(CQLProxNode node)
188         throws CQLParseException, IOException {
189         if (lexer.ttype != lexer.TT_NUMBER)
190             throw new CQLParseException("expected proximity distance, got " +
191                                         lexer.render());
192         node.addModifier("distance", lexer.render(lexer.ttype, false));
193         match(lexer.ttype);
194         debug("gPD matched " + lexer.render(lexer.ttype, false));
195     }
196
197     private void gatherProxUnit(CQLProxNode node)
198         throws CQLParseException, IOException {
199         if (lexer.ttype != lexer.TT_pWORD &&
200             lexer.ttype != lexer.TT_SENTENCE &&
201             lexer.ttype != lexer.TT_PARAGRAPH &&
202             lexer.ttype != lexer.TT_ELEMENT)
203             throw new CQLParseException("expected proximity unit, got " +
204                                         lexer.render());
205         node.addModifier("unit", lexer.render());
206         match(lexer.ttype);
207     }
208
209     private void gatherProxOrdering(CQLProxNode node)
210         throws CQLParseException, IOException {
211         if (lexer.ttype != lexer.TT_ORDERED &&
212             lexer.ttype != lexer.TT_UNORDERED)
213             throw new CQLParseException("expected proximity ordering, got " +
214                                         lexer.render());
215         node.addModifier("ordering", lexer.render());
216         match(lexer.ttype);
217     }
218
219     private boolean isBaseRelation() {
220         debug("isBaseRelation: checking ttype=" + lexer.ttype +
221               " (" + lexer.render() + ")");
222         return (isProxRelation() ||
223                 lexer.ttype == lexer.TT_ANY ||
224                 lexer.ttype == lexer.TT_ALL ||
225                 lexer.ttype == lexer.TT_EXACT ||
226                 lexer.ttype == lexer.TT_SCR);
227     }
228
229     // Checks for a relation that may be used inside a prox operator
230     private boolean isProxRelation() {
231         debug("isProxRelation: checking ttype=" + lexer.ttype +
232               " (" + lexer.render() + ")");
233         return (lexer.ttype == '<' ||
234                 lexer.ttype == '>' ||
235                 lexer.ttype == '=' ||
236                 lexer.ttype == lexer.TT_LE ||
237                 lexer.ttype == lexer.TT_GE ||
238                 lexer.ttype == lexer.TT_NE);
239     }
240
241     private void match(int token)
242         throws CQLParseException, IOException {
243         debug("in match(" + lexer.render(token, true) + ")");
244         if (lexer.ttype != token)
245             throw new CQLParseException("expected " +
246                                         lexer.render(token, true) +
247                                         ", " + "got " + lexer.render());
248         int tmp = lexer.nextToken();
249         debug("match() got token=" + lexer.ttype + ", " +
250               "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
251               " (tmp=" + tmp + ")");
252     }
253
254     private String matchSymbol(String expected)
255         throws CQLParseException, IOException {
256
257         debug("in matchSymbol()");
258         if (lexer.ttype == lexer.TT_WORD ||
259             lexer.ttype == lexer.TT_NUMBER ||
260             lexer.ttype == '"' ||
261             // The following is a complete list of keywords.  Because
262             // they're listed here, they can be used unquoted as
263             // qualifiers, terms, prefix names and prefix identifiers.
264             // ### Instead, we should ask the lexer whether what we
265             // have is a keyword, and let the knowledge reside there.
266             lexer.ttype == lexer.TT_AND ||
267             lexer.ttype == lexer.TT_OR ||
268             lexer.ttype == lexer.TT_NOT ||
269             lexer.ttype == lexer.TT_PROX ||
270             lexer.ttype == lexer.TT_ANY ||
271             lexer.ttype == lexer.TT_ALL ||
272             lexer.ttype == lexer.TT_EXACT ||
273             lexer.ttype == lexer.TT_pWORD ||
274             lexer.ttype == lexer.TT_SENTENCE ||
275             lexer.ttype == lexer.TT_PARAGRAPH ||
276             lexer.ttype == lexer.TT_ELEMENT ||
277             lexer.ttype == lexer.TT_ORDERED ||
278             lexer.ttype == lexer.TT_UNORDERED ||
279             lexer.ttype == lexer.TT_RELEVANT ||
280             lexer.ttype == lexer.TT_FUZZY ||
281             lexer.ttype == lexer.TT_STEM ||
282             lexer.ttype == lexer.TT_SCR ||
283             lexer.ttype == lexer.TT_PHONETIC) {
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 argv = new Vector();
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("-c")) {
360             mode = 'c';
361             argv.remove(0);
362         } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
363             mode = 'p';
364             argv.remove(0);
365             pfile = (String) argv.get(0);
366             argv.remove(0);
367         }
368
369         if (argv.size() > 1) {
370             System.err.println(
371                 "Usage: CQLParser [-c] [-p <pqf-properties> [<CQL-query>]");
372             System.err.println("If unspecified, query is read from stdin");
373             System.exit(1);
374         }
375
376         String cql;
377         if (argv.size() == 1) {
378             cql = (String) argv.get(0);
379         } else {
380             byte[] bytes = new byte[10000];
381             try {
382                 // Read in the whole of standard input in one go
383                 int nbytes = System.in.read(bytes);
384             } catch (IOException ex) {
385                 System.err.println("Can't read query: " + ex.getMessage());
386                 System.exit(2);
387             }
388             cql = new String(bytes);
389         }
390
391         CQLParser parser = new CQLParser();
392         CQLNode root = null;
393         try {
394             root = parser.parse(cql);
395         } catch (CQLParseException ex) {
396             System.err.println("Syntax error: " + ex.getMessage());
397             System.exit(3);
398         } catch (IOException ex) {
399             System.err.println("Can't compile query: " + ex.getMessage());
400             System.exit(4);
401         }
402
403         try {
404             if (mode == 'c') {
405                 System.out.println(root.toCQL());
406             } else if (mode == 'p') {
407                 InputStream f = new FileInputStream(pfile);
408                 if (f == null)
409                     throw new FileNotFoundException(pfile);
410
411                 Properties config = new Properties();
412                 config.load(f);
413                 f.close();
414                 System.out.println(root.toPQF(config));
415             } else {
416                 System.out.print(root.toXCQL(0));
417             }
418         } catch (IOException ex) {
419             System.err.println("Can't render query: " + ex.getMessage());
420             System.exit(5);
421         } catch (UnknownQualifierException ex) {
422             System.err.println("Unknown qualifier: " + ex.getMessage());
423             System.exit(6);
424         } catch (UnknownRelationException ex) {
425             System.err.println("Unknown relation: " + ex.getMessage());
426             System.exit(7);
427         } catch (UnknownRelationModifierException ex) {
428             System.err.println("Unknown relation modifier: " +
429                                ex.getMessage());
430             System.exit(8);
431         } catch (UnknownPositionException ex) {
432             System.err.println("Unknown position: " + ex.getMessage());
433             System.exit(9);
434         } catch (PQFTranslationException ex) {
435             // We catch all of this class's subclasses, so --
436             throw new Error("can't get a PQFTranslationException");
437         }
438     }
439 }