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