2 package org.z3950.zing.cql;
3 import java.io.IOException;
4 import java.util.Properties;
5 import java.io.InputStream;
6 import java.io.FileInputStream;
7 import java.io.FileNotFoundException;
9 import java.io.StringReader;
10 import java.util.ArrayList;
11 import java.util.List;
15 * Compiles CQL strings into parse trees of CQLNode subtypes.
17 * @see <A href="http://zing.z3950.org/cql/index.html"
18 * >http://zing.z3950.org/cql/index.html</A>
20 public class CQLParser {
21 private CQLLexer lexer;
22 private PositionAwareReader par; //active reader with position
23 private int compat; // When false, implement CQL 1.2
24 public static final int V1POINT1 = 12368;
25 public static final int V1POINT2 = 12369;
26 public static final int V1POINT1SORT = 12370;
28 static private boolean DEBUG = false;
29 static private boolean LEXDEBUG = false;
32 * The new parser implements a dialect of CQL specified by the
33 * <tt>compat</tt> argument:
35 * <li>V1POINT1 - CQL version 1.1
37 * <li>V1POINT2 - CQL version 1.2
39 * <li>V1POINT1SORT - CQL version 1.1 but including
40 * <tt>sortby</tt> as specified for CQL 1.2.
44 public CQLParser(int compat) {
49 * The new parser implements CQL 1.2
52 this.compat = V1POINT2;
55 private static void debug(String str) {
57 System.err.println("PARSEDEBUG: " + str);
61 * Compiles a CQL query.
63 * The resulting parse tree may be further processed by hand (see
64 * the individual node-types' documentation for details on the
65 * data structure) or, more often, simply rendered out in the
66 * desired form using one of the back-ends. <TT>toCQL()</TT>
67 * returns a decompiled CQL query equivalent to the one that was
68 * compiled in the first place; <TT>toXCQL()</TT> returns an
69 * XML snippet representing the query; and <TT>toPQF()</TT>
70 * returns the query rendered in Index Data's Prefix Query
73 * @param cql The query
74 * @return A CQLNode object which is the root of a parse
75 * tree representing the query. */
76 public CQLNode parse(String cql) throws CQLParseException, IOException {
77 return parse(new StringReader(cql));
81 * Compiles a CQL query.
83 * The resulting parse tree may be further processed by hand (see
84 * the individual node-types' documentation for details on the
85 * data structure) or, more often, simply rendered out in the
86 * desired form using one of the back-ends. <TT>toCQL()</TT>
87 * returns a decompiled CQL query equivalent to the one that was
88 * compiled in the first place; <TT>toXCQL()</TT> returns an
89 * XML snippet representing the query; and <TT>toPQF()</TT>
90 * returns the query rendered in Index Data's Prefix Query
93 * @param cql The query
94 * @return A CQLNode object which is the root of a parse
95 * tree representing the query. */
96 public CQLNode parse(Reader cql)
97 throws CQLParseException, IOException {
98 par = new PositionAwareReader(cql);
99 lexer = new CQLLexer(par, LEXDEBUG);
102 debug("about to parseQuery()");
103 CQLNode root = parseTopLevelPrefixes("cql.serverChoice",
104 new CQLRelation(compat == V1POINT2 ? "=" : "scr"));
105 if (lexer.ttype != CQLLexer.TT_EOF)
106 throw new CQLParseException("junk after end: " + lexer.render(),
112 private CQLNode parseTopLevelPrefixes(String index, CQLRelation relation)
113 throws CQLParseException, IOException {
114 debug("top-level prefix mapping");
116 if (lexer.ttype == '>') {
117 return parsePrefix(index, relation, true);
120 CQLNode node = parseQuery(index, relation);
121 if ((compat == V1POINT2 || compat == V1POINT1SORT) &&
122 lexer.ttype == CQLLexer.TT_SORTBY) {
126 CQLSortNode sortnode = new CQLSortNode(node);
127 while (lexer.ttype != CQLLexer.TT_EOF) {
128 String sortindex = matchSymbol("sort index");
129 ModifierSet ms = gatherModifiers(sortindex);
130 sortnode.addSortIndex(ms);
133 if (sortnode.keys.size() == 0) {
134 throw new CQLParseException("no sort keys", par.getPosition());
143 private CQLNode parseQuery(String index, CQLRelation relation)
144 throws CQLParseException, IOException {
145 debug("in parseQuery()");
147 CQLNode term = parseTerm(index, relation);
148 while (lexer.ttype != CQLLexer.TT_EOF &&
149 lexer.ttype != ')' &&
150 lexer.ttype != CQLLexer.TT_SORTBY) {
151 if (lexer.ttype == CQLLexer.TT_AND ||
152 lexer.ttype == CQLLexer.TT_OR ||
153 lexer.ttype == CQLLexer.TT_NOT ||
154 lexer.ttype == CQLLexer.TT_PROX) {
155 int type = lexer.ttype;
156 String val = lexer.sval;
158 ModifierSet ms = gatherModifiers(val);
159 CQLNode term2 = parseTerm(index, relation);
160 term = ((type == CQLLexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
161 (type == CQLLexer.TT_OR) ? new CQLOrNode (term, term2, ms) :
162 (type == CQLLexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
163 new CQLProxNode(term, term2, ms));
165 throw new CQLParseException("expected boolean, got " +
166 lexer.render(), par.getPosition());
170 debug("no more ops");
174 private ModifierSet gatherModifiers(String base)
175 throws CQLParseException, IOException {
176 debug("in gatherModifiers()");
178 ModifierSet ms = new ModifierSet(base);
179 while (lexer.ttype == '/') {
181 if (lexer.ttype != CQLLexer.TT_WORD)
182 throw new CQLParseException("expected modifier, "
183 + "got " + lexer.render(),
185 String type = lexer.sval.toLowerCase();
187 if (!isSymbolicRelation()) {
188 // It's a simple modifier consisting of type only
189 ms.addModifier(type);
191 // It's a complex modifier of the form type=value
192 String comparision = lexer.render(lexer.ttype, false);
194 String value = matchSymbol("modifier value");
195 ms.addModifier(type, comparision, value);
202 private CQLNode parseTerm(String index, CQLRelation relation)
203 throws CQLParseException, IOException {
204 debug("in parseTerm()");
208 if (lexer.ttype == '(') {
209 debug("parenthesised term");
211 CQLNode expr = parseQuery(index, relation);
214 } else if (lexer.ttype == '>') {
215 return parsePrefix(index, relation, false);
218 debug("non-parenthesised term");
219 word = matchSymbol("index or term");
220 while (lexer.ttype == CQLLexer.TT_WORD && !isRelation()) {
221 word = word + " " + lexer.sval;
222 match(CQLLexer.TT_WORD);
229 String relstr = (lexer.ttype == CQLLexer.TT_WORD ?
230 lexer.sval : lexer.render(lexer.ttype, false));
231 relation = new CQLRelation(relstr);
233 ModifierSet ms = gatherModifiers(relstr);
235 debug("index='" + index + ", " +
236 "relation='" + relation.toCQL() + "'");
239 CQLTermNode node = new CQLTermNode(index, relation, word);
240 debug("made term node " + node.toCQL());
244 private CQLNode parsePrefix(String index, CQLRelation relation,
246 throws CQLParseException, IOException {
247 debug("prefix mapping");
251 String identifier = matchSymbol("prefix-name");
252 if (lexer.ttype == '=') {
255 identifier = matchSymbol("prefix-identifer");
257 CQLNode node = topLevel ?
258 parseTopLevelPrefixes(index, relation) :
259 parseQuery(index, relation);
261 return new CQLPrefixNode(name, identifier, node);
264 private boolean isRelation() {
265 debug("isRelation: checking ttype=" + lexer.ttype +
266 " (" + lexer.render() + ")");
267 if (lexer.ttype == CQLLexer.TT_WORD &&
268 (lexer.sval.indexOf('.') >= 0 ||
269 lexer.sval.equals("any") ||
270 lexer.sval.equals("all") ||
271 lexer.sval.equals("within") ||
272 lexer.sval.equals("encloses") ||
273 (lexer.sval.equals("exact") && compat != V1POINT2) ||
274 (lexer.sval.equals("scr") && compat != V1POINT2) ||
275 (lexer.sval.equals("adj") && compat == V1POINT2)))
278 return isSymbolicRelation();
281 private boolean isSymbolicRelation() {
282 debug("isSymbolicRelation: checking ttype=" + lexer.ttype +
283 " (" + lexer.render() + ")");
284 return (lexer.ttype == '<' ||
285 lexer.ttype == '>' ||
286 lexer.ttype == '=' ||
287 lexer.ttype == CQLLexer.TT_LE ||
288 lexer.ttype == CQLLexer.TT_GE ||
289 lexer.ttype == CQLLexer.TT_NE ||
290 lexer.ttype == CQLLexer.TT_EQEQ);
293 private void match(int token)
294 throws CQLParseException, IOException {
295 debug("in match(" + lexer.render(token, true) + ")");
296 if (lexer.ttype != token)
297 throw new CQLParseException("expected " +
298 lexer.render(token, true) +
299 ", " + "got " + lexer.render(),
301 int tmp = lexer.nextToken();
302 debug("match() got token=" + lexer.ttype + ", " +
303 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
304 " (tmp=" + tmp + ")");
307 private String matchSymbol(String expected)
308 throws CQLParseException, IOException {
310 debug("in matchSymbol()");
311 if (lexer.ttype == CQLLexer.TT_WORD ||
312 lexer.ttype == CQLLexer.TT_NUMBER ||
313 lexer.ttype == '"' ||
314 // The following is a complete list of keywords. Because
315 // they're listed here, they can be used unquoted as
316 // indexes, terms, prefix names and prefix identifiers.
317 // ### Instead, we should ask the lexer whether what we
318 // have is a keyword, and let the knowledge reside there.
319 lexer.ttype == CQLLexer.TT_AND ||
320 lexer.ttype == CQLLexer.TT_OR ||
321 lexer.ttype == CQLLexer.TT_NOT ||
322 lexer.ttype == CQLLexer.TT_PROX ||
323 lexer.ttype == CQLLexer.TT_SORTBY) {
324 String symbol = (lexer.ttype == CQLLexer.TT_NUMBER) ?
325 lexer.render() : lexer.sval;
330 throw new CQLParseException("expected " + expected + ", " +
331 "got " + lexer.render(), par.getPosition());
336 * Simple test-harness for the CQLParser class.
338 * Reads a CQL query either from its command-line argument, if
339 * there is one, or standard input otherwise. So these two
340 * invocations are equivalent:
342 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
343 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
345 * The test-harness parses the supplied query and renders is as
346 * XCQL, so that both of the invocations above produce the
351 * <value>and</value>
355 * <value>or</value>
357 * <searchClause>
358 * <index>au</index>
360 * <value>=</value>
362 * <term>Kerninghan</term>
363 * </searchClause>
364 * <searchClause>
365 * <index>au</index>
367 * <value>=</value>
369 * <term>Ritchie</term>
370 * </searchClause>
372 * <searchClause>
373 * <index>ti</index>
375 * <value>=</value>
377 * <term>Unix</term>
378 * </searchClause>
383 * CQL version 1.1 (default version 1.2)
385 * Debug mode: extra output written to stderr.
387 * Causes the output to be written in CQL rather than XCQL - that
388 * is, a query equivalent to that which was input, is output. In
389 * effect, the test harness acts as a query canonicaliser.
391 * The input query, either as XCQL [default] or CQL [if the
392 * <TT>-c</TT> option is supplied].
394 public static void main (String[] args) {
395 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
398 List<String> argv = new ArrayList<String>();
399 for (int i = 0; i < args.length; i++) {
403 int compat = V1POINT2;
404 if (argv.size() > 0 && argv.get(0).equals("-1")) {
409 if (argv.size() > 0 && argv.get(0).equals("-d")) {
414 if (argv.size() > 0 && argv.get(0).equals("-c")) {
417 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
420 pfile = (String) argv.get(0);
424 if (argv.size() > 1) {
425 System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
426 "[-p <pqf-properties> [<CQL-query>]");
427 System.err.println("If unspecified, query is read from stdin");
432 if (argv.size() == 1) {
433 cql = (String) argv.get(0);
435 byte[] bytes = new byte[10000];
437 // Read in the whole of standard input in one go
438 int nbytes = System.in.read(bytes);
439 } catch (IOException ex) {
440 System.err.println("Can't read query: " + ex.getMessage());
443 cql = new String(bytes);
446 CQLParser parser = new CQLParser(compat);
449 root = parser.parse(cql);
450 } catch (CQLParseException ex) {
451 System.err.println("Syntax error: " + ex.getMessage());
453 } catch (IOException ex) {
454 System.err.println("Can't compile query: " + ex.getMessage());
460 System.out.println(root.toCQL());
461 } else if (mode == 'p') {
462 InputStream f = new FileInputStream(pfile);
464 throw new FileNotFoundException(pfile);
466 Properties config = new Properties();
469 System.out.println(root.toPQF(config));
471 System.out.print(root.toXCQL());
473 } catch (IOException ex) {
474 System.err.println("Can't render query: " + ex.getMessage());
476 } catch (UnknownIndexException ex) {
477 System.err.println("Unknown index: " + ex.getMessage());
479 } catch (UnknownRelationException ex) {
480 System.err.println("Unknown relation: " + ex.getMessage());
482 } catch (UnknownRelationModifierException ex) {
483 System.err.println("Unknown relation modifier: " +
486 } catch (UnknownPositionException ex) {
487 System.err.println("Unknown position: " + ex.getMessage());
489 } catch (PQFTranslationException ex) {
490 // We catch all of this class's subclasses, so --
491 throw new Error("can't get a PQFTranslationException");