1 // $Id: CQLParser.java,v 1.36 2007-06-29 15:39:09 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.36 2007-06-29 15:39:09 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 = parseQuery("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 parseQuery(String index, CQLRelation relation)
89 throws CQLParseException, IOException {
90 debug("in parseQuery()");
92 CQLNode term = parseTerm(index, relation);
93 while (lexer.ttype != lexer.TT_EOF && lexer.ttype != ')') {
94 if (lexer.ttype == lexer.TT_AND ||
95 lexer.ttype == lexer.TT_OR ||
96 lexer.ttype == lexer.TT_NOT ||
97 lexer.ttype == lexer.TT_PROX) {
98 int type = lexer.ttype;
99 String val = lexer.sval;
101 ModifierSet ms = gatherModifiers(val);
102 CQLNode term2 = parseTerm(index, relation);
103 term = ((type == lexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
104 (type == lexer.TT_OR) ? new CQLOrNode (term, term2, ms) :
105 (type == lexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
106 new CQLProxNode(term, term2, ms));
108 throw new CQLParseException("expected boolean, got " +
113 debug("no more ops");
117 private ModifierSet gatherModifiers(String base)
118 throws CQLParseException, IOException {
119 debug("in gatherModifiers()");
121 ModifierSet ms = new ModifierSet(base);
122 while (lexer.ttype == '/') {
124 if (lexer.ttype != lexer.TT_WORD)
125 throw new CQLParseException("expected modifier, "
126 + "got " + lexer.render());
127 String type = lexer.sval.toLowerCase();
130 // It's a simple modifier consisting of type only
131 ms.addModifier(type);
133 // It's a complex modifier of the form type=value
134 String comparision = lexer.render(lexer.ttype, false);
136 String value = matchSymbol("modifier value");
137 ms.addModifier(type, comparision, value);
144 private CQLNode parseTerm(String index, CQLRelation relation)
145 throws CQLParseException, IOException {
146 debug("in parseTerm()");
150 if (lexer.ttype == '(') {
151 debug("parenthesised term");
153 CQLNode expr = parseQuery(index, relation);
156 } else if (lexer.ttype == '>') {
158 return parsePrefix(index, relation);
161 debug("non-parenthesised term");
162 word = matchSymbol("index or term");
163 if (!isRelation() && lexer.ttype != lexer.TT_WORD)
167 String relstr = (lexer.ttype == lexer.TT_WORD ?
168 lexer.sval : lexer.render(lexer.ttype, false));
169 relation = new CQLRelation(relstr);
171 ModifierSet ms = gatherModifiers(relstr);
172 relation.setModifiers(ms);
173 debug("index='" + index + ", " +
174 "relation='" + relation.toCQL() + "'");
177 CQLTermNode node = new CQLTermNode(index, relation, word);
178 debug("made term node " + node.toCQL());
182 private CQLNode parsePrefix(String index, CQLRelation relation)
183 throws CQLParseException, IOException {
184 debug("prefix mapping");
187 String identifier = matchSymbol("prefix-name");
188 if (lexer.ttype == '=') {
191 identifier = matchSymbol("prefix-identifer");
193 CQLNode term = parseQuery(index, relation);
194 return new CQLPrefixNode(name, identifier, term);
197 // Checks for a relation
198 private boolean isRelation() {
199 debug("isRelation: checking ttype=" + lexer.ttype +
200 " (" + lexer.render() + ")");
201 return (lexer.ttype == '<' ||
202 lexer.ttype == '>' ||
203 lexer.ttype == '=' ||
204 lexer.ttype == lexer.TT_LE ||
205 lexer.ttype == lexer.TT_GE ||
206 lexer.ttype == lexer.TT_NE ||
207 lexer.ttype == lexer.TT_EQEQ);
210 private void match(int token)
211 throws CQLParseException, IOException {
212 debug("in match(" + lexer.render(token, true) + ")");
213 if (lexer.ttype != token)
214 throw new CQLParseException("expected " +
215 lexer.render(token, true) +
216 ", " + "got " + lexer.render());
217 int tmp = lexer.nextToken();
218 debug("match() got token=" + lexer.ttype + ", " +
219 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
220 " (tmp=" + tmp + ")");
223 private String matchSymbol(String expected)
224 throws CQLParseException, IOException {
226 debug("in matchSymbol()");
227 if (lexer.ttype == lexer.TT_WORD ||
228 lexer.ttype == lexer.TT_NUMBER ||
229 lexer.ttype == '"' ||
230 // The following is a complete list of keywords. Because
231 // they're listed here, they can be used unquoted as
232 // indexes, terms, prefix names and prefix identifiers.
233 // ### Instead, we should ask the lexer whether what we
234 // have is a keyword, and let the knowledge reside there.
235 lexer.ttype == lexer.TT_AND ||
236 lexer.ttype == lexer.TT_OR ||
237 lexer.ttype == lexer.TT_NOT ||
238 lexer.ttype == lexer.TT_PROX) {
239 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
240 lexer.render() : lexer.sval;
245 throw new CQLParseException("expected " + expected + ", " +
246 "got " + lexer.render());
251 * Simple test-harness for the CQLParser class.
253 * Reads a CQL query either from its command-line argument, if
254 * there is one, or standard input otherwise. So these two
255 * invocations are equivalent:
257 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
258 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
260 * The test-harness parses the supplied query and renders is as
261 * XCQL, so that both of the invocations above produce the
266 * <value>and</value>
270 * <value>or</value>
272 * <searchClause>
273 * <index>au</index>
275 * <value>=</value>
277 * <term>Kerninghan</term>
278 * </searchClause>
279 * <searchClause>
280 * <index>au</index>
282 * <value>=</value>
284 * <term>Ritchie</term>
285 * </searchClause>
287 * <searchClause>
288 * <index>ti</index>
290 * <value>=</value>
292 * <term>Unix</term>
293 * </searchClause>
298 * CQL version 1.1 (default version 1.2)
300 * Debug mode: extra output written to stderr.
302 * Causes the output to be written in CQL rather than XCQL - that
303 * is, a query equivalent to that which was input, is output. In
304 * effect, the test harness acts as a query canonicaliser.
306 * The input query, either as XCQL [default] or CQL [if the
307 * <TT>-c</TT> option is supplied].
309 public static void main (String[] args) {
310 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
313 Vector<String> argv = new Vector<String>();
314 for (int i = 0; i < args.length; i++) {
318 int compat = V1POINT2;
319 if (argv.size() > 0 && argv.get(0).equals("-1")) {
324 if (argv.size() > 0 && argv.get(0).equals("-d")) {
329 if (argv.size() > 0 && argv.get(0).equals("-c")) {
332 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
335 pfile = (String) argv.get(0);
339 if (argv.size() > 1) {
340 System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
341 "[-p <pqf-properties> [<CQL-query>]");
342 System.err.println("If unspecified, query is read from stdin");
347 if (argv.size() == 1) {
348 cql = (String) argv.get(0);
350 byte[] bytes = new byte[10000];
352 // Read in the whole of standard input in one go
353 int nbytes = System.in.read(bytes);
354 } catch (IOException ex) {
355 System.err.println("Can't read query: " + ex.getMessage());
358 cql = new String(bytes);
361 CQLParser parser = new CQLParser(compat);
364 root = parser.parse(cql);
365 } catch (CQLParseException ex) {
366 System.err.println("Syntax error: " + ex.getMessage());
368 } catch (IOException ex) {
369 System.err.println("Can't compile query: " + ex.getMessage());
375 System.out.println(root.toCQL());
376 } else if (mode == 'p') {
377 InputStream f = new FileInputStream(pfile);
379 throw new FileNotFoundException(pfile);
381 Properties config = new Properties();
384 System.out.println(root.toPQF(config));
386 System.out.print(root.toXCQL(0));
388 } catch (IOException ex) {
389 System.err.println("Can't render query: " + ex.getMessage());
391 } catch (UnknownIndexException ex) {
392 System.err.println("Unknown index: " + ex.getMessage());
394 } catch (UnknownRelationException ex) {
395 System.err.println("Unknown relation: " + ex.getMessage());
397 } catch (UnknownRelationModifierException ex) {
398 System.err.println("Unknown relation modifier: " +
401 } catch (UnknownPositionException ex) {
402 System.err.println("Unknown position: " + ex.getMessage());
404 } catch (PQFTranslationException ex) {
405 // We catch all of this class's subclasses, so --
406 throw new Error("can't get a PQFTranslationException");