1 // $Id: CQLParser.java,v 1.39 2007-08-06 15:54:48 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.39 2007-08-06 15:54:48 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 public 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);
109 if (sortnode.keys.size() == 0) {
110 throw new CQLParseException("no sort keys");
119 private CQLNode parseQuery(String index, CQLRelation relation)
120 throws CQLParseException, IOException {
121 debug("in parseQuery()");
123 CQLNode term = parseTerm(index, relation);
124 while (lexer.ttype != lexer.TT_EOF &&
125 lexer.ttype != ')' &&
126 lexer.ttype != lexer.TT_SORTBY) {
127 if (lexer.ttype == lexer.TT_AND ||
128 lexer.ttype == lexer.TT_OR ||
129 lexer.ttype == lexer.TT_NOT ||
130 lexer.ttype == lexer.TT_PROX) {
131 int type = lexer.ttype;
132 String val = lexer.sval;
134 ModifierSet ms = gatherModifiers(val);
135 CQLNode term2 = parseTerm(index, relation);
136 term = ((type == lexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
137 (type == lexer.TT_OR) ? new CQLOrNode (term, term2, ms) :
138 (type == lexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
139 new CQLProxNode(term, term2, ms));
141 throw new CQLParseException("expected boolean, got " +
146 debug("no more ops");
150 private ModifierSet gatherModifiers(String base)
151 throws CQLParseException, IOException {
152 debug("in gatherModifiers()");
154 ModifierSet ms = new ModifierSet(base);
155 while (lexer.ttype == '/') {
157 if (lexer.ttype != lexer.TT_WORD)
158 throw new CQLParseException("expected modifier, "
159 + "got " + lexer.render());
160 String type = lexer.sval.toLowerCase();
162 if (!isSymbolicRelation()) {
163 // It's a simple modifier consisting of type only
164 ms.addModifier(type);
166 // It's a complex modifier of the form type=value
167 String comparision = lexer.render(lexer.ttype, false);
169 String value = matchSymbol("modifier value");
170 ms.addModifier(type, comparision, value);
177 private CQLNode parseTerm(String index, CQLRelation relation)
178 throws CQLParseException, IOException {
179 debug("in parseTerm()");
183 if (lexer.ttype == '(') {
184 debug("parenthesised term");
186 CQLNode expr = parseQuery(index, relation);
189 } else if (lexer.ttype == '>') {
190 return parsePrefix(index, relation, false);
193 debug("non-parenthesised term");
194 word = matchSymbol("index or term");
195 while (lexer.ttype == lexer.TT_WORD && !isRelation()) {
196 word = word + " " + lexer.sval;
197 match(lexer.TT_WORD);
204 String relstr = (lexer.ttype == lexer.TT_WORD ?
205 lexer.sval : lexer.render(lexer.ttype, false));
206 relation = new CQLRelation(relstr);
208 ModifierSet ms = gatherModifiers(relstr);
209 relation.setModifiers(ms);
210 debug("index='" + index + ", " +
211 "relation='" + relation.toCQL() + "'");
214 CQLTermNode node = new CQLTermNode(index, relation, word);
215 debug("made term node " + node.toCQL());
219 private CQLNode parsePrefix(String index, CQLRelation relation,
221 throws CQLParseException, IOException {
222 debug("prefix mapping");
226 String identifier = matchSymbol("prefix-name");
227 if (lexer.ttype == '=') {
230 identifier = matchSymbol("prefix-identifer");
232 CQLNode node = topLevel ?
233 parseTopLevelPrefixes(index, relation) :
234 parseQuery(index, relation);
236 return new CQLPrefixNode(name, identifier, node);
239 private boolean isRelation() {
240 debug("isRelation: checking ttype=" + lexer.ttype +
241 " (" + lexer.render() + ")");
242 if (lexer.ttype == lexer.TT_WORD &&
243 (lexer.sval.indexOf('.') >= 0 ||
244 lexer.sval.equals("exact") ||
245 lexer.sval.equals("any") ||
246 lexer.sval.equals("all") ||
247 (lexer.sval.equals("scr") && compat == V1POINT2)))
250 return isSymbolicRelation();
253 private boolean isSymbolicRelation() {
254 debug("isSymbolicRelation: checking ttype=" + lexer.ttype +
255 " (" + lexer.render() + ")");
256 return (lexer.ttype == '<' ||
257 lexer.ttype == '>' ||
258 lexer.ttype == '=' ||
259 lexer.ttype == lexer.TT_LE ||
260 lexer.ttype == lexer.TT_GE ||
261 lexer.ttype == lexer.TT_NE ||
262 lexer.ttype == lexer.TT_EQEQ);
265 private void match(int token)
266 throws CQLParseException, IOException {
267 debug("in match(" + lexer.render(token, true) + ")");
268 if (lexer.ttype != token)
269 throw new CQLParseException("expected " +
270 lexer.render(token, true) +
271 ", " + "got " + lexer.render());
272 int tmp = lexer.nextToken();
273 debug("match() got token=" + lexer.ttype + ", " +
274 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
275 " (tmp=" + tmp + ")");
278 private String matchSymbol(String expected)
279 throws CQLParseException, IOException {
281 debug("in matchSymbol()");
282 if (lexer.ttype == lexer.TT_WORD ||
283 lexer.ttype == lexer.TT_NUMBER ||
284 lexer.ttype == '"' ||
285 // The following is a complete list of keywords. Because
286 // they're listed here, they can be used unquoted as
287 // indexes, terms, prefix names and prefix identifiers.
288 // ### Instead, we should ask the lexer whether what we
289 // have is a keyword, and let the knowledge reside there.
290 lexer.ttype == lexer.TT_AND ||
291 lexer.ttype == lexer.TT_OR ||
292 lexer.ttype == lexer.TT_NOT ||
293 lexer.ttype == lexer.TT_PROX ||
294 lexer.ttype == lexer.TT_SORTBY) {
295 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
296 lexer.render() : lexer.sval;
301 throw new CQLParseException("expected " + expected + ", " +
302 "got " + lexer.render());
307 * Simple test-harness for the CQLParser class.
309 * Reads a CQL query either from its command-line argument, if
310 * there is one, or standard input otherwise. So these two
311 * invocations are equivalent:
313 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
314 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
316 * The test-harness parses the supplied query and renders is as
317 * XCQL, so that both of the invocations above produce the
322 * <value>and</value>
326 * <value>or</value>
328 * <searchClause>
329 * <index>au</index>
331 * <value>=</value>
333 * <term>Kerninghan</term>
334 * </searchClause>
335 * <searchClause>
336 * <index>au</index>
338 * <value>=</value>
340 * <term>Ritchie</term>
341 * </searchClause>
343 * <searchClause>
344 * <index>ti</index>
346 * <value>=</value>
348 * <term>Unix</term>
349 * </searchClause>
354 * CQL version 1.1 (default version 1.2)
356 * Debug mode: extra output written to stderr.
358 * Causes the output to be written in CQL rather than XCQL - that
359 * is, a query equivalent to that which was input, is output. In
360 * effect, the test harness acts as a query canonicaliser.
362 * The input query, either as XCQL [default] or CQL [if the
363 * <TT>-c</TT> option is supplied].
365 public static void main (String[] args) {
366 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
369 Vector<String> argv = new Vector<String>();
370 for (int i = 0; i < args.length; i++) {
374 int compat = V1POINT2;
375 if (argv.size() > 0 && argv.get(0).equals("-1")) {
380 if (argv.size() > 0 && argv.get(0).equals("-d")) {
385 if (argv.size() > 0 && argv.get(0).equals("-c")) {
388 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
391 pfile = (String) argv.get(0);
395 if (argv.size() > 1) {
396 System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
397 "[-p <pqf-properties> [<CQL-query>]");
398 System.err.println("If unspecified, query is read from stdin");
403 if (argv.size() == 1) {
404 cql = (String) argv.get(0);
406 byte[] bytes = new byte[10000];
408 // Read in the whole of standard input in one go
409 int nbytes = System.in.read(bytes);
410 } catch (IOException ex) {
411 System.err.println("Can't read query: " + ex.getMessage());
414 cql = new String(bytes);
417 CQLParser parser = new CQLParser(compat);
420 root = parser.parse(cql);
421 } catch (CQLParseException ex) {
422 System.err.println("Syntax error: " + ex.getMessage());
424 } catch (IOException ex) {
425 System.err.println("Can't compile query: " + ex.getMessage());
431 System.out.println(root.toCQL());
432 } else if (mode == 'p') {
433 InputStream f = new FileInputStream(pfile);
435 throw new FileNotFoundException(pfile);
437 Properties config = new Properties();
440 System.out.println(root.toPQF(config));
442 System.out.print(root.toXCQL(0));
444 } catch (IOException ex) {
445 System.err.println("Can't render query: " + ex.getMessage());
447 } catch (UnknownIndexException ex) {
448 System.err.println("Unknown index: " + ex.getMessage());
450 } catch (UnknownRelationException ex) {
451 System.err.println("Unknown relation: " + ex.getMessage());
453 } catch (UnknownRelationModifierException ex) {
454 System.err.println("Unknown relation modifier: " +
457 } catch (UnknownPositionException ex) {
458 System.err.println("Unknown position: " + ex.getMessage());
460 } catch (PQFTranslationException ex) {
461 // We catch all of this class's subclasses, so --
462 throw new Error("can't get a PQFTranslationException");