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