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