1 // $Id: CQLParser.java,v 1.31 2007-06-29 10:25:38 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.31 2007-06-29 10:25:38 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 && lexer.ttype != ')') {
64 if (lexer.ttype == lexer.TT_AND ||
65 lexer.ttype == lexer.TT_OR ||
66 lexer.ttype == lexer.TT_NOT) {
67 int type = lexer.ttype;
68 String val = lexer.sval;
70 ModifierSet ms = gatherModifiers(val);
71 CQLNode term2 = parseTerm(index, relation);
72 term = ((type == lexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
73 (type == lexer.TT_OR) ? new CQLOrNode (term, term2, ms) :
74 new CQLNotNode(term, term2, ms));
75 } else if (lexer.ttype == lexer.TT_PROX) {
77 CQLProxNode proxnode = new CQLProxNode(term);
78 gatherProxParameters(proxnode);
79 CQLNode term2 = parseTerm(index, relation);
80 proxnode.addSecondSubterm(term2);
81 term = (CQLNode) proxnode;
83 throw new CQLParseException("expected boolean, got " +
92 private ModifierSet gatherModifiers(String base)
93 throws CQLParseException, IOException {
94 debug("in gatherModifiers()");
96 ModifierSet ms = new ModifierSet(base);
97 while (lexer.ttype == '/') {
99 if (lexer.ttype != lexer.TT_WORD)
100 throw new CQLParseException("expected modifier, "
101 + "got " + lexer.render());
102 String type = lexer.sval.toLowerCase();
105 // It's a simple modifier consisting of type only
106 ms.addModifier(type);
108 // It's a complex modifier of the form type=value
109 String comparision = lexer.render(lexer.ttype, false);
113 String value = lexer.ttype == lexer.TT_WORD ? lexer.sval :
114 (double) lexer.nval == (int) lexer.nval ?
115 new Integer((int) lexer.nval).toString() :
116 new Double((double) lexer.nval).toString();
118 matchSymbol("modifier value");
119 ms.addModifier(type, comparision, value);
126 private CQLNode parseTerm(String index, CQLRelation relation)
127 throws CQLParseException, IOException {
128 debug("in parseTerm()");
132 if (lexer.ttype == '(') {
133 debug("parenthesised term");
135 CQLNode expr = parseQuery(index, relation);
138 } else if (lexer.ttype == '>') {
140 return parsePrefix(index, relation);
143 debug("non-parenthesised term");
144 word = matchSymbol("index or term");
145 if (!isRelation() && lexer.ttype != lexer.TT_WORD)
149 String relstr = (lexer.ttype == lexer.TT_WORD ?
150 lexer.sval : lexer.render(lexer.ttype, false));
151 relation = new CQLRelation(relstr);
153 ModifierSet ms = gatherModifiers(relstr);
154 relation.setModifiers(ms);
155 debug("index='" + index + ", " +
156 "relation='" + relation.toCQL() + "'");
159 CQLTermNode node = new CQLTermNode(index, relation, word);
160 debug("made term node " + node.toCQL());
164 private CQLNode parsePrefix(String index, CQLRelation relation)
165 throws CQLParseException, IOException {
166 debug("prefix mapping");
169 String identifier = matchSymbol("prefix-name");
170 if (lexer.ttype == '=') {
173 identifier = matchSymbol("prefix-identifer");
175 CQLNode term = parseQuery(index, relation);
176 return new CQLPrefixNode(name, identifier, term);
179 private void gatherProxParameters(CQLProxNode node)
180 throws CQLParseException, IOException {
181 for (int i = 0; i < 4; i++) {
182 if (lexer.ttype != '/')
183 return; // end of proximity parameters
186 if (lexer.ttype != '/') {
187 // not an omitted default
189 // Order should be: relation/distance/unit/ordering
190 // For now, use MA's: unit/relation/distance/ordering
191 case 0: gatherProxRelation(node); break;
192 case 1: gatherProxDistance(node); break;
193 case 2: gatherProxUnit(node); break;
194 case 3: gatherProxOrdering(node); break;
200 private void gatherProxRelation(CQLProxNode node)
201 throws CQLParseException, IOException {
203 throw new CQLParseException("expected proximity relation, got " +
205 node.addModifier("relation", null, lexer.render(lexer.ttype, false));
207 debug("gPR matched " + lexer.render(lexer.ttype, false));
210 private void gatherProxDistance(CQLProxNode node)
211 throws CQLParseException, IOException {
212 if (lexer.ttype != lexer.TT_NUMBER)
213 throw new CQLParseException("expected proximity distance, got " +
215 node.addModifier("distance", null, lexer.render(lexer.ttype, false));
217 debug("gPD matched " + lexer.render(lexer.ttype, false));
220 private void gatherProxUnit(CQLProxNode node)
221 throws CQLParseException, IOException {
222 if (lexer.ttype != lexer.TT_pWORD &&
223 lexer.ttype != lexer.TT_SENTENCE &&
224 lexer.ttype != lexer.TT_PARAGRAPH &&
225 lexer.ttype != lexer.TT_ELEMENT)
226 throw new CQLParseException("expected proximity unit, got " +
228 node.addModifier("unit", null, lexer.render());
232 private void gatherProxOrdering(CQLProxNode node)
233 throws CQLParseException, IOException {
234 if (lexer.ttype != lexer.TT_ORDERED &&
235 lexer.ttype != lexer.TT_UNORDERED)
236 throw new CQLParseException("expected proximity ordering, got " +
238 node.addModifier("ordering", null, lexer.render());
242 // Checks for a relation that may be used inside a prox operator
243 private boolean isRelation() {
244 debug("isRelation: checking ttype=" + lexer.ttype +
245 " (" + lexer.render() + ")");
246 return (lexer.ttype == '<' ||
247 lexer.ttype == '>' ||
248 lexer.ttype == '=' ||
249 lexer.ttype == lexer.TT_LE ||
250 lexer.ttype == lexer.TT_GE ||
251 lexer.ttype == lexer.TT_NE);
254 private void match(int token)
255 throws CQLParseException, IOException {
256 debug("in match(" + lexer.render(token, true) + ")");
257 if (lexer.ttype != token)
258 throw new CQLParseException("expected " +
259 lexer.render(token, true) +
260 ", " + "got " + lexer.render());
261 int tmp = lexer.nextToken();
262 debug("match() got token=" + lexer.ttype + ", " +
263 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
264 " (tmp=" + tmp + ")");
267 private String matchSymbol(String expected)
268 throws CQLParseException, IOException {
270 debug("in matchSymbol()");
271 if (lexer.ttype == lexer.TT_WORD ||
272 lexer.ttype == lexer.TT_NUMBER ||
273 lexer.ttype == '"' ||
274 // The following is a complete list of keywords. Because
275 // they're listed here, they can be used unquoted as
276 // indexes, terms, prefix names and prefix identifiers.
277 // ### Instead, we should ask the lexer whether what we
278 // have is a keyword, and let the knowledge reside there.
279 lexer.ttype == lexer.TT_AND ||
280 lexer.ttype == lexer.TT_OR ||
281 lexer.ttype == lexer.TT_NOT ||
282 lexer.ttype == lexer.TT_PROX ||
283 lexer.ttype == lexer.TT_pWORD ||
284 lexer.ttype == lexer.TT_SENTENCE ||
285 lexer.ttype == lexer.TT_PARAGRAPH ||
286 lexer.ttype == lexer.TT_ELEMENT ||
287 lexer.ttype == lexer.TT_ORDERED ||
288 lexer.ttype == lexer.TT_UNORDERED) {
289 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
290 lexer.render() : lexer.sval;
295 throw new CQLParseException("expected " + expected + ", " +
296 "got " + lexer.render());
301 * Simple test-harness for the CQLParser class.
303 * Reads a CQL query either from its command-line argument, if
304 * there is one, or standard input otherwise. So these two
305 * invocations are equivalent:
307 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
308 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
310 * The test-harness parses the supplied query and renders is as
311 * XCQL, so that both of the invocations above produce the
316 * <value>and</value>
320 * <value>or</value>
322 * <searchClause>
323 * <index>au</index>
325 * <value>=</value>
327 * <term>Kerninghan</term>
328 * </searchClause>
329 * <searchClause>
330 * <index>au</index>
332 * <value>=</value>
334 * <term>Ritchie</term>
335 * </searchClause>
337 * <searchClause>
338 * <index>ti</index>
340 * <value>=</value>
342 * <term>Unix</term>
343 * </searchClause>
348 * Causes the output to be written in CQL rather than XCQL - that
349 * is, a query equivalent to that which was input, is output. In
350 * effect, the test harness acts as a query canonicaliser.
352 * The input query, either as XCQL [default] or CQL [if the
353 * <TT>-c</TT> option is supplied].
355 public static void main (String[] args) {
356 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
359 Vector<String> argv = new Vector<String>();
360 for (int i = 0; i < args.length; i++) {
364 if (argv.size() > 0 && argv.get(0).equals("-d")) {
369 if (argv.size() > 0 && argv.get(0).equals("-c")) {
372 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
375 pfile = (String) argv.get(0);
379 if (argv.size() > 1) {
380 System.err.println("Usage: CQLParser [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
381 System.err.println("If unspecified, query is read from stdin");
386 if (argv.size() == 1) {
387 cql = (String) argv.get(0);
389 byte[] bytes = new byte[10000];
391 // Read in the whole of standard input in one go
392 int nbytes = System.in.read(bytes);
393 } catch (IOException ex) {
394 System.err.println("Can't read query: " + ex.getMessage());
397 cql = new String(bytes);
400 CQLParser parser = new CQLParser();
403 root = parser.parse(cql);
404 } catch (CQLParseException ex) {
405 System.err.println("Syntax error: " + ex.getMessage());
407 } catch (IOException ex) {
408 System.err.println("Can't compile query: " + ex.getMessage());
414 System.out.println(root.toCQL());
415 } else if (mode == 'p') {
416 InputStream f = new FileInputStream(pfile);
418 throw new FileNotFoundException(pfile);
420 Properties config = new Properties();
423 System.out.println(root.toPQF(config));
425 System.out.print(root.toXCQL(0));
427 } catch (IOException ex) {
428 System.err.println("Can't render query: " + ex.getMessage());
430 } catch (UnknownIndexException ex) {
431 System.err.println("Unknown index: " + ex.getMessage());
433 } catch (UnknownRelationException ex) {
434 System.err.println("Unknown relation: " + ex.getMessage());
436 } catch (UnknownRelationModifierException ex) {
437 System.err.println("Unknown relation modifier: " +
440 } catch (UnknownPositionException ex) {
441 System.err.println("Unknown position: " + ex.getMessage());
443 } catch (PQFTranslationException ex) {
444 // We catch all of this class's subclasses, so --
445 throw new Error("can't get a PQFTranslationException");