1 // $Id: CQLParser.java,v 1.30 2007-06-28 00:24: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.30 2007-06-28 00:24: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 static private boolean DEBUG = false;
22 static private boolean LEXDEBUG = false;
24 private static void debug(String str) {
26 System.err.println("PARSEDEBUG: " + str);
30 * Compiles a CQL query.
32 * The resulting parse tree may be further processed by hand (see
33 * the individual node-types' documentation for details on the
34 * data structure) or, more often, simply rendered out in the
35 * desired form using one of the back-ends. <TT>toCQL()</TT>
36 * returns a decompiled CQL query equivalent to the one that was
37 * compiled in the first place; <TT>toXCQL()</TT> returns an
38 * XML snippet representing the query; and <TT>toPQF()</TT>
39 * returns the query rendered in Index Data's Prefix Query
42 * @param cql The query
43 * @return A CQLNode object which is the root of a parse
44 * tree representing the query. */
45 public CQLNode parse(String cql)
46 throws CQLParseException, IOException {
47 lexer = new CQLLexer(cql, LEXDEBUG);
50 debug("about to parseQuery()");
51 CQLNode root = parseQuery("srw.serverChoice", new CQLRelation("scr"));
52 if (lexer.ttype != lexer.TT_EOF)
53 throw new CQLParseException("junk after end: " + lexer.render());
58 private CQLNode parseQuery(String index, CQLRelation relation)
59 throws CQLParseException, IOException {
60 debug("in parseQuery()");
62 CQLNode term = parseTerm(index, relation);
63 while (lexer.ttype != lexer.TT_EOF &&
65 if (lexer.ttype == lexer.TT_AND) {
67 CQLNode term2 = parseTerm(index, relation);
68 term = new CQLAndNode(term, term2);
69 } else if (lexer.ttype == lexer.TT_OR) {
71 CQLNode term2 = parseTerm(index, relation);
72 term = new CQLOrNode(term, term2);
73 } else if (lexer.ttype == lexer.TT_NOT) {
75 CQLNode term2 = parseTerm(index, relation);
76 term = new CQLNotNode(term, term2);
77 } else if (lexer.ttype == lexer.TT_PROX) {
79 CQLProxNode proxnode = new CQLProxNode(term);
80 gatherProxParameters(proxnode);
81 CQLNode term2 = parseTerm(index, relation);
82 proxnode.addSecondSubterm(term2);
83 term = (CQLNode) proxnode;
85 throw new CQLParseException("expected boolean, got " +
94 private CQLNode parseTerm(String index, CQLRelation relation)
95 throws CQLParseException, IOException {
96 debug("in parseTerm()");
100 if (lexer.ttype == '(') {
101 debug("parenthesised term");
103 CQLNode expr = parseQuery(index, relation);
106 } else if (lexer.ttype == '>') {
108 return parsePrefix(index, relation);
111 debug("non-parenthesised term");
112 word = matchSymbol("index or term");
113 if (!isRelation() && lexer.ttype != lexer.TT_WORD)
117 relation = new CQLRelation(lexer.ttype == lexer.TT_WORD ?
119 lexer.render(lexer.ttype, false));
122 while (lexer.ttype == '/') {
124 if (lexer.ttype != lexer.TT_WORD)
125 throw new CQLParseException("expected relation modifier, "
126 + "got " + lexer.render());
127 String type = lexer.sval.toLowerCase();
130 // It's a simple modifier consisting of type only
131 relation.addModifier(type);
133 // It's a complex modifier of the form type=value
134 String comparision = lexer.render(lexer.ttype, false);
138 String value = lexer.ttype == lexer.TT_WORD ? lexer.sval :
139 (double) lexer.nval == (int) lexer.nval ?
140 new Integer((int) lexer.nval).toString() :
141 new Double((double) lexer.nval).toString();
143 matchSymbol("relation-modifier value");
144 relation.addModifier(type, comparision, value);
148 debug("index='" + index + ", " +
149 "relation='" + relation.toCQL() + "'");
152 CQLTermNode node = new CQLTermNode(index, relation, word);
153 debug("made term node " + node.toCQL());
157 private CQLNode parsePrefix(String index, CQLRelation relation)
158 throws CQLParseException, IOException {
159 debug("prefix mapping");
162 String identifier = matchSymbol("prefix-name");
163 if (lexer.ttype == '=') {
166 identifier = matchSymbol("prefix-identifer");
168 CQLNode term = parseQuery(index, relation);
169 return new CQLPrefixNode(name, identifier, term);
172 private void gatherProxParameters(CQLProxNode node)
173 throws CQLParseException, IOException {
174 for (int i = 0; i < 4; i++) {
175 if (lexer.ttype != '/')
176 return; // end of proximity parameters
179 if (lexer.ttype != '/') {
180 // not an omitted default
182 // Order should be: relation/distance/unit/ordering
183 // For now, use MA's: unit/relation/distance/ordering
184 case 0: gatherProxRelation(node); break;
185 case 1: gatherProxDistance(node); break;
186 case 2: gatherProxUnit(node); break;
187 case 3: gatherProxOrdering(node); break;
193 private void gatherProxRelation(CQLProxNode node)
194 throws CQLParseException, IOException {
196 throw new CQLParseException("expected proximity relation, got " +
198 node.addModifier("relation", null, lexer.render(lexer.ttype, false));
200 debug("gPR matched " + lexer.render(lexer.ttype, false));
203 private void gatherProxDistance(CQLProxNode node)
204 throws CQLParseException, IOException {
205 if (lexer.ttype != lexer.TT_NUMBER)
206 throw new CQLParseException("expected proximity distance, got " +
208 node.addModifier("distance", null, lexer.render(lexer.ttype, false));
210 debug("gPD matched " + lexer.render(lexer.ttype, false));
213 private void gatherProxUnit(CQLProxNode node)
214 throws CQLParseException, IOException {
215 if (lexer.ttype != lexer.TT_pWORD &&
216 lexer.ttype != lexer.TT_SENTENCE &&
217 lexer.ttype != lexer.TT_PARAGRAPH &&
218 lexer.ttype != lexer.TT_ELEMENT)
219 throw new CQLParseException("expected proximity unit, got " +
221 node.addModifier("unit", null, lexer.render());
225 private void gatherProxOrdering(CQLProxNode node)
226 throws CQLParseException, IOException {
227 if (lexer.ttype != lexer.TT_ORDERED &&
228 lexer.ttype != lexer.TT_UNORDERED)
229 throw new CQLParseException("expected proximity ordering, got " +
231 node.addModifier("ordering", null, lexer.render());
235 // Checks for a relation that may be used inside a prox operator
236 private boolean isRelation() {
237 debug("isRelation: checking ttype=" + lexer.ttype +
238 " (" + lexer.render() + ")");
239 return (lexer.ttype == '<' ||
240 lexer.ttype == '>' ||
241 lexer.ttype == '=' ||
242 lexer.ttype == lexer.TT_LE ||
243 lexer.ttype == lexer.TT_GE ||
244 lexer.ttype == lexer.TT_NE);
247 private void match(int token)
248 throws CQLParseException, IOException {
249 debug("in match(" + lexer.render(token, true) + ")");
250 if (lexer.ttype != token)
251 throw new CQLParseException("expected " +
252 lexer.render(token, true) +
253 ", " + "got " + lexer.render());
254 int tmp = lexer.nextToken();
255 debug("match() got token=" + lexer.ttype + ", " +
256 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
257 " (tmp=" + tmp + ")");
260 private String matchSymbol(String expected)
261 throws CQLParseException, IOException {
263 debug("in matchSymbol()");
264 if (lexer.ttype == lexer.TT_WORD ||
265 lexer.ttype == lexer.TT_NUMBER ||
266 lexer.ttype == '"' ||
267 // The following is a complete list of keywords. Because
268 // they're listed here, they can be used unquoted as
269 // indexes, terms, prefix names and prefix identifiers.
270 // ### Instead, we should ask the lexer whether what we
271 // have is a keyword, and let the knowledge reside there.
272 lexer.ttype == lexer.TT_AND ||
273 lexer.ttype == lexer.TT_OR ||
274 lexer.ttype == lexer.TT_NOT ||
275 lexer.ttype == lexer.TT_PROX ||
276 lexer.ttype == lexer.TT_pWORD ||
277 lexer.ttype == lexer.TT_SENTENCE ||
278 lexer.ttype == lexer.TT_PARAGRAPH ||
279 lexer.ttype == lexer.TT_ELEMENT ||
280 lexer.ttype == lexer.TT_ORDERED ||
281 lexer.ttype == lexer.TT_UNORDERED) {
282 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
283 lexer.render() : lexer.sval;
288 throw new CQLParseException("expected " + expected + ", " +
289 "got " + lexer.render());
294 * Simple test-harness for the CQLParser class.
296 * Reads a CQL query either from its command-line argument, if
297 * there is one, or standard input otherwise. So these two
298 * invocations are equivalent:
300 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
301 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
303 * The test-harness parses the supplied query and renders is as
304 * XCQL, so that both of the invocations above produce the
309 * <value>and</value>
313 * <value>or</value>
315 * <searchClause>
316 * <index>au</index>
318 * <value>=</value>
320 * <term>Kerninghan</term>
321 * </searchClause>
322 * <searchClause>
323 * <index>au</index>
325 * <value>=</value>
327 * <term>Ritchie</term>
328 * </searchClause>
330 * <searchClause>
331 * <index>ti</index>
333 * <value>=</value>
335 * <term>Unix</term>
336 * </searchClause>
341 * Causes the output to be written in CQL rather than XCQL - that
342 * is, a query equivalent to that which was input, is output. In
343 * effect, the test harness acts as a query canonicaliser.
345 * The input query, either as XCQL [default] or CQL [if the
346 * <TT>-c</TT> option is supplied].
348 public static void main (String[] args) {
349 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
352 Vector<String> argv = new Vector<String>();
353 for (int i = 0; i < args.length; i++) {
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 [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
374 System.err.println("If unspecified, query is read from stdin");
379 if (argv.size() == 1) {
380 cql = (String) argv.get(0);
382 byte[] bytes = new byte[10000];
384 // Read in the whole of standard input in one go
385 int nbytes = System.in.read(bytes);
386 } catch (IOException ex) {
387 System.err.println("Can't read query: " + ex.getMessage());
390 cql = new String(bytes);
393 CQLParser parser = new CQLParser();
396 root = parser.parse(cql);
397 } catch (CQLParseException ex) {
398 System.err.println("Syntax error: " + ex.getMessage());
400 } catch (IOException ex) {
401 System.err.println("Can't compile query: " + ex.getMessage());
407 System.out.println(root.toCQL());
408 } else if (mode == 'p') {
409 InputStream f = new FileInputStream(pfile);
411 throw new FileNotFoundException(pfile);
413 Properties config = new Properties();
416 System.out.println(root.toPQF(config));
418 System.out.print(root.toXCQL(0));
420 } catch (IOException ex) {
421 System.err.println("Can't render query: " + ex.getMessage());
423 } catch (UnknownIndexException ex) {
424 System.err.println("Unknown index: " + ex.getMessage());
426 } catch (UnknownRelationException ex) {
427 System.err.println("Unknown relation: " + ex.getMessage());
429 } catch (UnknownRelationModifierException ex) {
430 System.err.println("Unknown relation modifier: " +
433 } catch (UnknownPositionException ex) {
434 System.err.println("Unknown position: " + ex.getMessage());
436 } catch (PQFTranslationException ex) {
437 // We catch all of this class's subclasses, so --
438 throw new Error("can't get a PQFTranslationException");