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