79abc31da72e038c1d7efcb3930ac009c8f5a99e
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLParser.java
1 // $Id: CQLParser.java,v 1.14 2002-11-03 16:49:38 mike Exp $
2
3 package org.z3950.zing.cql;
4 import java.io.IOException;
5 import java.util.Vector;
6
7
8 /**
9  * Compiles CQL strings into parse trees of CQLNode subtypes.
10  *
11  * @version     $Id: CQLParser.java,v 1.14 2002-11-03 16:49:38 mike Exp $
12  * @see         <A href="http://zing.z3950.org/cql/index.html"
13  *                      >http://zing.z3950.org/cql/index.html</A>
14  */
15 public class CQLParser {
16     private CQLLexer lexer;
17     static private boolean DEBUG = false;
18     static private boolean LEXDEBUG = false;
19
20     private static void debug(String str) {
21         if (DEBUG)
22             System.err.println("PARSEDEBUG: " + str);
23     }
24
25     /**
26      * Compiles a CQL query.
27      * <P>
28      * The resulting parse tree may be further processed by hand (see
29      * the individual node-types' documentation for details on the
30      * data structure) or, more often, simply rendered out in the
31      * desired form using one of the back-ends.  <TT>toCQL()</TT>
32      * returns a decompiled CQL query equivalent to the one that was
33      * compiled in the first place; and <TT>toXCQL()</TT> returns an
34      * XML snippet representing the query.
35      *
36      * @param cql       The query
37      * @return          A CQLNode object which is the root of a parse
38      * tree representing the query.  */
39     public CQLNode parse(String cql)
40         throws CQLParseException, IOException {
41         lexer = new CQLLexer(cql, LEXDEBUG);
42
43         lexer.nextToken();
44         debug("about to parse_query()");
45         CQLNode root = parse_query("srw.serverChoice", new CQLRelation("="));
46         if (lexer.ttype != lexer.TT_EOF)
47             throw new CQLParseException("junk after end: " + lexer.render());
48
49         return root;
50     }
51
52     private CQLNode parse_query(String qualifier, CQLRelation relation)
53         throws CQLParseException, IOException {
54         debug("in parse_query()");
55
56         CQLNode term = parse_term(qualifier, relation);
57         while (lexer.ttype != lexer.TT_EOF &&
58                lexer.ttype != ')') {
59             if (lexer.ttype == lexer.TT_AND) {
60                 match(lexer.TT_AND);
61                 CQLNode term2 = parse_term(qualifier, relation);
62                 term = new CQLAndNode(term, term2);
63             } else if (lexer.ttype == lexer.TT_OR) {
64                 match(lexer.TT_OR);
65                 CQLNode term2 = parse_term(qualifier, relation);
66                 term = new CQLOrNode(term, term2);
67             } else if (lexer.ttype == lexer.TT_NOT) {
68                 match(lexer.TT_NOT);
69                 CQLNode term2 = parse_term(qualifier, relation);
70                 term = new CQLNotNode(term, term2);
71             } else if (lexer.ttype == lexer.TT_PROX) {
72                 match(lexer.TT_PROX);
73                 CQLProxNode proxnode = new CQLProxNode(term);
74                 gatherProxParameters(proxnode);
75                 CQLNode term2 = parse_term(qualifier, relation);
76                 proxnode.addSecondSubterm(term2);
77                 term = (CQLNode) proxnode;
78             } else {
79                 throw new CQLParseException("expected boolean, got " +
80                                             lexer.render());
81             }
82         }
83
84         debug("no more ops");
85         return term;
86     }
87
88     private CQLNode parse_term(String qualifier, CQLRelation relation)
89         throws CQLParseException, IOException {
90         debug("in parse_term()");
91
92         String word;
93         while (true) {
94             if (lexer.ttype == '(') {
95                 debug("parenthesised term");
96                 match('(');
97                 CQLNode expr = parse_query(qualifier, relation);
98                 match(')');
99                 return expr;
100             } else if (lexer.ttype != lexer.TT_WORD &&
101                        lexer.ttype != lexer.TT_NUMBER &&
102                        lexer.ttype != '"') {
103                 throw new CQLParseException("expected qualifier or term, " +
104                                             "got " + lexer.render());
105             }
106
107             debug("non-parenthesised term");
108             if (lexer.ttype == lexer.TT_NUMBER) {
109                 word = lexer.render();
110             } else {
111                 word = lexer.sval;
112             }
113             match(lexer.ttype);
114             if (!isBaseRelation())
115                 break;
116
117             qualifier = word;
118             relation = new CQLRelation(lexer.render(lexer.ttype, false));
119             match(lexer.ttype);
120
121             while (lexer.ttype == '/') {
122                 match('/');
123                 if (lexer.ttype != lexer.TT_RELEVANT &&
124                     lexer.ttype != lexer.TT_FUZZY &&
125                     lexer.ttype != lexer.TT_STEM)
126                     throw new CQLParseException("expected relation modifier, "
127                                                 + "got " + lexer.render());
128                 relation.addModifier(lexer.sval);
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 void gatherProxParameters(CQLProxNode node)
142         throws CQLParseException, IOException {
143         for (int i = 0; i < 4; i++) {
144             if (lexer.ttype != '/')
145                 return;         // end of proximity parameters
146
147             match('/');
148             if (lexer.ttype != '/') {
149                 // not an omitted default
150                 switch (i) {
151                     // Order should be: relation/distance/unit/ordering
152                     // For now, use MA's: unit/relation/distance/ordering
153                 case 1: gatherProxRelation(node); break;
154                 case 2: gatherProxDistance(node); break;
155                 case 0: gatherProxUnit(node); break;
156                 case 3: gatherProxOrdering(node); break;
157                 }
158             }
159         }
160     }
161
162     private void gatherProxRelation(CQLProxNode node)
163         throws CQLParseException, IOException {
164         if (!isProxRelation())
165             throw new CQLParseException("expected proximity relation, got " +
166                                         lexer.render());
167         node.addModifier("relation", lexer.render(lexer.ttype, false));
168         match(lexer.ttype);
169         debug("gPR matched " + lexer.render(lexer.ttype, false));
170     }
171
172     private void gatherProxDistance(CQLProxNode node)
173         throws CQLParseException, IOException {
174         if (lexer.ttype != lexer.TT_NUMBER)
175             throw new CQLParseException("expected proximity distance, got " +
176                                         lexer.render());
177         node.addModifier("distance", lexer.render(lexer.ttype, false));
178         match(lexer.ttype);
179         debug("gPD matched " + lexer.render(lexer.ttype, false));
180     }
181
182     private void gatherProxUnit(CQLProxNode node)
183         throws CQLParseException, IOException {
184         if (lexer.ttype != lexer.TT_pWORD &&
185             lexer.ttype != lexer.TT_SENTENCE &&
186             lexer.ttype != lexer.TT_PARAGRAPH &&
187             lexer.ttype != lexer.TT_ELEMENT)
188             throw new CQLParseException("expected proximity unit, got " +
189                                         lexer.render());
190         node.addModifier("unit", lexer.render());
191         match(lexer.ttype);
192     }
193
194     private void gatherProxOrdering(CQLProxNode node)
195         throws CQLParseException, IOException {
196         if (lexer.ttype != lexer.TT_ORDERED &&
197             lexer.ttype != lexer.TT_UNORDERED)
198             throw new CQLParseException("expected proximity ordering, got " +
199                                         lexer.render());
200         node.addModifier("ordering", lexer.render());
201         match(lexer.ttype);
202     }
203
204     private boolean isBaseRelation() {
205         debug("isBaseRelation: checking ttype=" + lexer.ttype +
206               " (" + lexer.render() + ")");
207         return (isProxRelation() ||
208                 lexer.ttype == lexer.TT_ANY ||
209                 lexer.ttype == lexer.TT_ALL ||
210                 lexer.ttype == lexer.TT_EXACT);
211     }
212
213     private boolean isProxRelation() {
214         debug("isProxRelation: checking ttype=" + lexer.ttype +
215               " (" + lexer.render() + ")");
216         return (lexer.ttype == '<' ||
217                 lexer.ttype == '>' ||
218                 lexer.ttype == '=' ||
219                 lexer.ttype == lexer.TT_LE ||
220                 lexer.ttype == lexer.TT_GE ||
221                 lexer.ttype == lexer.TT_NE);
222     }
223
224     private void match(int token)
225         throws CQLParseException, IOException {
226         debug("in match(" + lexer.render(token, true) + ")");
227         if (lexer.ttype != token)
228             throw new CQLParseException("expected " +
229                                         lexer.render(token, true) +
230                                         ", " + "got " + lexer.render());
231         int tmp = lexer.nextToken();
232         debug("match() got token=" + lexer.ttype + ", " +
233               "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
234               " (tmp=" + tmp + ")");
235     }
236
237
238     /**
239      * Simple test-harness for the CQLParser class.
240      * <P>
241      * Reads a CQL query either from its command-line argument, if
242      * there is one, or standard input otherwise.  So these two
243      * invocations are equivalent:
244      * <PRE>
245      *  CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
246      *  echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
247      * </PRE>
248      * The test-harness parses the supplied query and renders is as
249      * XCQL, so that both of the invocations above produce the
250      * following output:
251      * <PRE>
252      *  &lt;triple&gt;
253      *    &lt;boolean&gt;
254      *      &lt;value&gt;and&lt;/value&gt;
255      *    &lt;/boolean&gt;
256      *    &lt;triple&gt;
257      *      &lt;boolean&gt;
258      *        &lt;value&gt;or&lt;/value&gt;
259      *      &lt;/boolean&gt;
260      *      &lt;searchClause&gt;
261      *        &lt;index&gt;au&lt;/index&gt;
262      *        &lt;relation&gt;
263      *          &lt;value&gt;=&lt;/value&gt;
264      *        &lt;/relation&gt;
265      *        &lt;term&gt;Kerninghan&lt;/term&gt;
266      *      &lt;/searchClause&gt;
267      *      &lt;searchClause&gt;
268      *        &lt;index&gt;au&lt;/index&gt;
269      *        &lt;relation&gt;
270      *          &lt;value&gt;=&lt;/value&gt;
271      *        &lt;/relation&gt;
272      *        &lt;term&gt;Ritchie&lt;/term&gt;
273      *      &lt;/searchClause&gt;
274      *    &lt;/triple&gt;
275      *    &lt;searchClause&gt;
276      *      &lt;index&gt;ti&lt;/index&gt;
277      *      &lt;relation&gt;
278      *        &lt;value&gt;=&lt;/value&gt;
279      *      &lt;/relation&gt;
280      *      &lt;term&gt;Unix&lt;/term&gt;
281      *    &lt;/searchClause&gt;
282      *  &lt;/triple&gt;
283      * </PRE>
284      * <P>
285      * @param -c
286      *  Causes the output to be written in CQL rather than XCQL - that
287      *  is, a query equivalent to that which was input, is output.  In
288      *  effect, the test harness acts as a query canonicaliser.
289      * @return
290      *  The input query, either as XCQL [default] or CQL [if the
291      *  <TT>-c</TT> option is supplied].
292      */
293     public static void main (String[] args) {
294         boolean canonicalise = false;
295         Vector argv = new Vector();
296         for (int i = 0; i < args.length; i++) {
297             argv.add(args[i]);
298         }
299
300         if (argv.size() > 0 && argv.get(0).equals("-c")) {
301             canonicalise = true;
302             argv.remove(0);
303         }
304
305         if (argv.size() > 1) {
306             System.err.println("Usage: CQLParser [-c] [<CQL-query>]");
307             System.err.println("If unspecified, query is read from stdin");
308             System.exit(1);
309         }
310
311         String cql;
312         if (argv.size() == 1) {
313             cql = (String) argv.get(0);
314         } else {
315             byte[] bytes = new byte[10000];
316             try {
317                 // Read in the whole of standard input in one go
318                 int nbytes = System.in.read(bytes);
319             } catch (java.io.IOException ex) {
320                 System.err.println("Can't read query: " + ex.getMessage());
321                 System.exit(2);
322             }
323             cql = new String(bytes);
324         }
325
326         CQLParser parser = new CQLParser();
327         CQLNode root;
328         try {
329             root = parser.parse(cql);
330             debug("root='" + root + "'");
331             if (canonicalise) {
332                 System.out.println(root.toCQL());
333             } else {
334                 System.out.print(root.toXCQL(0));
335             }
336         } catch (CQLParseException ex) {
337             System.err.println("Syntax error: " + ex.getMessage());
338             System.exit(3);
339         } catch (java.io.IOException ex) {
340             System.err.println("Can't compile query: " + ex.getMessage());
341             System.exit(4);
342         }
343     }
344 }