1 // $Id: CQLParser.java,v 1.35 2007-06-29 15:24:26 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.35 2007-06-29 15:24:26 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);
209 private void match(int token)
210 throws CQLParseException, IOException {
211 debug("in match(" + lexer.render(token, true) + ")");
212 if (lexer.ttype != token)
213 throw new CQLParseException("expected " +
214 lexer.render(token, true) +
215 ", " + "got " + lexer.render());
216 int tmp = lexer.nextToken();
217 debug("match() got token=" + lexer.ttype + ", " +
218 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
219 " (tmp=" + tmp + ")");
222 private String matchSymbol(String expected)
223 throws CQLParseException, IOException {
225 debug("in matchSymbol()");
226 if (lexer.ttype == lexer.TT_WORD ||
227 lexer.ttype == lexer.TT_NUMBER ||
228 lexer.ttype == '"' ||
229 // The following is a complete list of keywords. Because
230 // they're listed here, they can be used unquoted as
231 // indexes, terms, prefix names and prefix identifiers.
232 // ### Instead, we should ask the lexer whether what we
233 // have is a keyword, and let the knowledge reside there.
234 lexer.ttype == lexer.TT_AND ||
235 lexer.ttype == lexer.TT_OR ||
236 lexer.ttype == lexer.TT_NOT ||
237 lexer.ttype == lexer.TT_PROX) {
238 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
239 lexer.render() : lexer.sval;
244 throw new CQLParseException("expected " + expected + ", " +
245 "got " + lexer.render());
250 * Simple test-harness for the CQLParser class.
252 * Reads a CQL query either from its command-line argument, if
253 * there is one, or standard input otherwise. So these two
254 * invocations are equivalent:
256 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
257 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
259 * The test-harness parses the supplied query and renders is as
260 * XCQL, so that both of the invocations above produce the
265 * <value>and</value>
269 * <value>or</value>
271 * <searchClause>
272 * <index>au</index>
274 * <value>=</value>
276 * <term>Kerninghan</term>
277 * </searchClause>
278 * <searchClause>
279 * <index>au</index>
281 * <value>=</value>
283 * <term>Ritchie</term>
284 * </searchClause>
286 * <searchClause>
287 * <index>ti</index>
289 * <value>=</value>
291 * <term>Unix</term>
292 * </searchClause>
297 * CQL version 1.1 (default version 1.2)
299 * Debug mode: extra output written to stderr.
301 * Causes the output to be written in CQL rather than XCQL - that
302 * is, a query equivalent to that which was input, is output. In
303 * effect, the test harness acts as a query canonicaliser.
305 * The input query, either as XCQL [default] or CQL [if the
306 * <TT>-c</TT> option is supplied].
308 public static void main (String[] args) {
309 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
312 Vector<String> argv = new Vector<String>();
313 for (int i = 0; i < args.length; i++) {
317 int compat = V1POINT2;
318 if (argv.size() > 0 && argv.get(0).equals("-1")) {
323 if (argv.size() > 0 && argv.get(0).equals("-d")) {
328 if (argv.size() > 0 && argv.get(0).equals("-c")) {
331 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
334 pfile = (String) argv.get(0);
338 if (argv.size() > 1) {
339 System.err.println("Usage: CQLParser [-1] [-d] [-c] " +
340 "[-p <pqf-properties> [<CQL-query>]");
341 System.err.println("If unspecified, query is read from stdin");
346 if (argv.size() == 1) {
347 cql = (String) argv.get(0);
349 byte[] bytes = new byte[10000];
351 // Read in the whole of standard input in one go
352 int nbytes = System.in.read(bytes);
353 } catch (IOException ex) {
354 System.err.println("Can't read query: " + ex.getMessage());
357 cql = new String(bytes);
360 CQLParser parser = new CQLParser(compat);
363 root = parser.parse(cql);
364 } catch (CQLParseException ex) {
365 System.err.println("Syntax error: " + ex.getMessage());
367 } catch (IOException ex) {
368 System.err.println("Can't compile query: " + ex.getMessage());
374 System.out.println(root.toCQL());
375 } else if (mode == 'p') {
376 InputStream f = new FileInputStream(pfile);
378 throw new FileNotFoundException(pfile);
380 Properties config = new Properties();
383 System.out.println(root.toPQF(config));
385 System.out.print(root.toXCQL(0));
387 } catch (IOException ex) {
388 System.err.println("Can't render query: " + ex.getMessage());
390 } catch (UnknownIndexException ex) {
391 System.err.println("Unknown index: " + ex.getMessage());
393 } catch (UnknownRelationException ex) {
394 System.err.println("Unknown relation: " + ex.getMessage());
396 } catch (UnknownRelationModifierException ex) {
397 System.err.println("Unknown relation modifier: " +
400 } catch (UnknownPositionException ex) {
401 System.err.println("Unknown position: " + ex.getMessage());
403 } catch (PQFTranslationException ex) {
404 // We catch all of this class's subclasses, so --
405 throw new Error("can't get a PQFTranslationException");