1 // $Id: CQLParser.java,v 1.37 2007-07-03 13:34:30 mike Exp $
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;
13 * Compiles CQL strings into parse trees of CQLNode subtypes.
15 * @version $Id: CQLParser.java,v 1.37 2007-07-03 13:34:30 mike Exp $
16 * @see <A href="http://zing.z3950.org/cql/index.html"
17 * >http://zing.z3950.org/cql/index.html</A>
19 public class CQLParser {
20 private CQLLexer lexer;
21 private int compat; // When false, implement CQL 1.2
22 public static int V1POINT1 = 12368;
23 public static int V1POINT2 = 12369;
24 public static int V1POINT1SORT = 12370;
26 static private boolean DEBUG = false;
27 static private boolean LEXDEBUG = false;
30 * The new parser implements a dialect of CQL specified by the
31 * <tt>compat</tt> argument:
33 * <li>V1POINT1 - CQL version 1.1
35 * <li>V1POINT2 - CQL version 1.2
37 * <li>V1POINT1SORT - CQL version 1.1 but including
38 * <tt>sortby</tt> as specified for CQL 1.2.
42 CQLParser(int compat) {
47 * The new parser implements CQL 1.2
50 this.compat = V1POINT2;
53 private static void debug(String str) {
55 System.err.println("PARSEDEBUG: " + str);
59 * Compiles a CQL query.
61 * The resulting parse tree may be further processed by hand (see
62 * the individual node-types' documentation for details on the
63 * data structure) or, more often, simply rendered out in the
64 * desired form using one of the back-ends. <TT>toCQL()</TT>
65 * returns a decompiled CQL query equivalent to the one that was
66 * compiled in the first place; <TT>toXCQL()</TT> returns an
67 * XML snippet representing the query; and <TT>toPQF()</TT>
68 * returns the query rendered in Index Data's Prefix Query
71 * @param cql The query
72 * @return A CQLNode object which is the root of a parse
73 * tree representing the query. */
74 public CQLNode parse(String cql)
75 throws CQLParseException, IOException {
76 lexer = new CQLLexer(cql, LEXDEBUG);
79 debug("about to parseQuery()");
80 CQLNode root = parseTopLevelPrefixes("cql.serverChoice",
81 new CQLRelation(compat == V1POINT2 ? "=" : "scr"));
82 if (lexer.ttype != lexer.TT_EOF)
83 throw new CQLParseException("junk after end: " + lexer.render());
88 private CQLNode parseTopLevelPrefixes(String index, CQLRelation relation)
89 throws CQLParseException, IOException {
90 debug("top-level prefix mapping");
92 if (lexer.ttype == '>') {
93 return parsePrefix(index, relation, true);
96 CQLNode node = parseQuery(index, relation);
97 if ((compat == V1POINT2 || compat == V1POINT1SORT) &&
98 lexer.ttype == lexer.TT_SORTBY) {
102 CQLSortNode sortnode = new CQLSortNode(node);
103 while (lexer.ttype != lexer.TT_EOF) {
104 String sortindex = matchSymbol("sort index");
105 ModifierSet ms = gatherModifiers(sortindex);
106 sortnode.addSortIndex(ms);
114 private CQLNode parseQuery(String index, CQLRelation relation)
115 throws CQLParseException, IOException {
116 debug("in parseQuery()");
118 CQLNode term = parseTerm(index, relation);
119 while (lexer.ttype != lexer.TT_EOF &&
120 lexer.ttype != ')' &&
121 lexer.ttype != lexer.TT_SORTBY) {
122 if (lexer.ttype == lexer.TT_AND ||
123 lexer.ttype == lexer.TT_OR ||
124 lexer.ttype == lexer.TT_NOT ||
125 lexer.ttype == lexer.TT_PROX) {
126 int type = lexer.ttype;
127 String val = lexer.sval;
129 ModifierSet ms = gatherModifiers(val);
130 CQLNode term2 = parseTerm(index, relation);
131 term = ((type == lexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
132 (type == lexer.TT_OR) ? new CQLOrNode (term, term2, ms) :
133 (type == lexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
134 new CQLProxNode(term, term2, ms));
136 throw new CQLParseException("expected boolean, got " +
141 debug("no more ops");
145 private ModifierSet gatherModifiers(String base)
146 throws CQLParseException, IOException {
147 debug("in gatherModifiers()");
149 ModifierSet ms = new ModifierSet(base);
150 while (lexer.ttype == '/') {
152 if (lexer.ttype != lexer.TT_WORD)
153 throw new CQLParseException("expected modifier, "
154 + "got " + lexer.render());
155 String type = lexer.sval.toLowerCase();
158 // It's a simple modifier consisting of type only
159 ms.addModifier(type);
161 // It's a complex modifier of the form type=value
162 String comparision = lexer.render(lexer.ttype, false);
164 String value = matchSymbol("modifier value");
165 ms.addModifier(type, comparision, value);
172 private CQLNode parseTerm(String index, CQLRelation relation)
173 throws CQLParseException, IOException {
174 debug("in parseTerm()");
178 if (lexer.ttype == '(') {
179 debug("parenthesised term");
181 CQLNode expr = parseQuery(index, relation);
184 } else if (lexer.ttype == '>') {
185 return parsePrefix(index, relation, false);
188 debug("non-parenthesised term");
189 word = matchSymbol("index or term");
190 if (!isRelation() && lexer.ttype != lexer.TT_WORD)
194 String relstr = (lexer.ttype == lexer.TT_WORD ?
195 lexer.sval : lexer.render(lexer.ttype, false));
196 relation = new CQLRelation(relstr);
198 ModifierSet ms = gatherModifiers(relstr);
199 relation.setModifiers(ms);
200 debug("index='" + index + ", " +
201 "relation='" + relation.toCQL() + "'");
204 CQLTermNode node = new CQLTermNode(index, relation, word);
205 debug("made term node " + node.toCQL());
209 private CQLNode parsePrefix(String index, CQLRelation relation,
211 throws CQLParseException, IOException {
212 debug("prefix mapping");
216 String identifier = matchSymbol("prefix-name");
217 if (lexer.ttype == '=') {
220 identifier = matchSymbol("prefix-identifer");
222 CQLNode node = topLevel ?
223 parseTopLevelPrefixes(index, relation) :
224 parseQuery(index, relation);
226 return new CQLPrefixNode(name, identifier, node);
229 // Checks for a relation
230 private boolean isRelation() {
231 debug("isRelation: checking ttype=" + lexer.ttype +
232 " (" + lexer.render() + ")");
233 return (lexer.ttype == '<' ||
234 lexer.ttype == '>' ||
235 lexer.ttype == '=' ||
236 lexer.ttype == lexer.TT_LE ||
237 lexer.ttype == lexer.TT_GE ||
238 lexer.ttype == lexer.TT_NE ||
239 lexer.ttype == lexer.TT_EQEQ);
242 private void match(int token)
243 throws CQLParseException, IOException {
244 debug("in match(" + lexer.render(token, true) + ")");
245 if (lexer.ttype != token)
246 throw new CQLParseException("expected " +
247 lexer.render(token, true) +
248 ", " + "got " + lexer.render());
249 int tmp = lexer.nextToken();
250 debug("match() got token=" + lexer.ttype + ", " +
251 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
252 " (tmp=" + tmp + ")");
255 private String matchSymbol(String expected)
256 throws CQLParseException, IOException {
258 debug("in matchSymbol()");
259 if (lexer.ttype == lexer.TT_WORD ||
260 lexer.ttype == lexer.TT_NUMBER ||
261 lexer.ttype == '"' ||
262 // The following is a complete list of keywords. Because
263 // they're listed here, they can be used unquoted as
264 // indexes, terms, prefix names and prefix identifiers.
265 // ### Instead, we should ask the lexer whether what we
266 // have is a keyword, and let the knowledge reside there.
267 lexer.ttype == lexer.TT_AND ||
268 lexer.ttype == lexer.TT_OR ||
269 lexer.ttype == lexer.TT_NOT ||
270 lexer.ttype == lexer.TT_PROX ||
271 lexer.ttype == lexer.TT_SORTBY) {
272 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
273 lexer.render() : lexer.sval;
278 throw new CQLParseException("expected " + expected + ", " +
279 "got " + lexer.render());
284 * Simple test-harness for the CQLParser class.
286 * Reads a CQL query either from its command-line argument, if
287 * there is one, or standard input otherwise. So these two
288 * invocations are equivalent:
290 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
291 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
293 * The test-harness parses the supplied query and renders is as
294 * XCQL, so that both of the invocations above produce the
299 * <value>and</value>
303 * <value>or</value>
305 * <searchClause>
306 * <index>au</index>
308 * <value>=</value>
310 * <term>Kerninghan</term>
311 * </searchClause>
312 * <searchClause>
313 * <index>au</index>
315 * <value>=</value>
317 * <term>Ritchie</term>
318 * </searchClause>
320 * <searchClause>
321 * <index>ti</index>
323 * <value>=</value>
325 * <term>Unix</term>
326 * </searchClause>
331 * CQL version 1.1 (default version 1.2)
333 * Debug mode: extra output written to stderr.
335 * Causes the output to be written in CQL rather than XCQL - that
336 * is, a query equivalent to that which was input, is output. In
337 * effect, the test harness acts as a query canonicaliser.
339 * The input query, either as XCQL [default] or CQL [if the
340 * <TT>-c</TT> option is supplied].
342 public static void main (String[] args) {
343 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
346 Vector<String> argv = new Vector<String>();
347 for (int i = 0; i < args.length; i++) {
351 int compat = V1POINT2;
352 if (argv.size() > 0 && argv.get(0).equals("-1")) {
357 if (argv.size() > 0 && argv.get(0).equals("-d")) {
362 if (argv.size() > 0 && argv.get(0).equals("-c")) {
365 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
368 pfile = (String) argv.get(0);
372 if (argv.size() > 1) {
373 System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
374 "[-p <pqf-properties> [<CQL-query>]");
375 System.err.println("If unspecified, query is read from stdin");
380 if (argv.size() == 1) {
381 cql = (String) argv.get(0);
383 byte[] bytes = new byte[10000];
385 // Read in the whole of standard input in one go
386 int nbytes = System.in.read(bytes);
387 } catch (IOException ex) {
388 System.err.println("Can't read query: " + ex.getMessage());
391 cql = new String(bytes);
394 CQLParser parser = new CQLParser(compat);
397 root = parser.parse(cql);
398 } catch (CQLParseException ex) {
399 System.err.println("Syntax error: " + ex.getMessage());
401 } catch (IOException ex) {
402 System.err.println("Can't compile query: " + ex.getMessage());
408 System.out.println(root.toCQL());
409 } else if (mode == 'p') {
410 InputStream f = new FileInputStream(pfile);
412 throw new FileNotFoundException(pfile);
414 Properties config = new Properties();
417 System.out.println(root.toPQF(config));
419 System.out.print(root.toXCQL(0));
421 } catch (IOException ex) {
422 System.err.println("Can't render query: " + ex.getMessage());
424 } catch (UnknownIndexException ex) {
425 System.err.println("Unknown index: " + ex.getMessage());
427 } catch (UnknownRelationException ex) {
428 System.err.println("Unknown relation: " + ex.getMessage());
430 } catch (UnknownRelationModifierException ex) {
431 System.err.println("Unknown relation modifier: " +
434 } catch (UnknownPositionException ex) {
435 System.err.println("Unknown position: " + ex.getMessage());
437 } catch (PQFTranslationException ex) {
438 // We catch all of this class's subclasses, so --
439 throw new Error("can't get a PQFTranslationException");