1 // $Id: CQLParser.java,v 1.28 2007-06-27 22:44:40 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.28 2007-06-27 22:44:40 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 (!isBaseRelation())
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_RELEVANT &&
125 lexer.ttype != lexer.TT_FUZZY &&
126 lexer.ttype != lexer.TT_STEM &&
127 lexer.ttype != lexer.TT_PHONETIC &&
128 lexer.ttype != lexer.TT_WORD)
129 throw new CQLParseException("expected relation modifier, "
130 + "got " + lexer.render());
131 if (lexer.ttype == lexer.TT_WORD &&
132 lexer.sval.indexOf('.') == -1)
133 throw new CQLParseException("unknown first-class " +
134 "relation modifier: " +
137 relation.addModifier(lexer.sval.toLowerCase());
141 debug("index='" + index + ", " +
142 "relation='" + relation.toCQL() + "'");
145 CQLTermNode node = new CQLTermNode(index, relation, word);
146 debug("made term node " + node.toCQL());
150 private CQLNode parsePrefix(String index, CQLRelation relation)
151 throws CQLParseException, IOException {
152 debug("prefix mapping");
155 String identifier = matchSymbol("prefix-name");
156 if (lexer.ttype == '=') {
159 identifier = matchSymbol("prefix-identifer");
161 CQLNode term = parseQuery(index, relation);
162 return new CQLPrefixNode(name, identifier, term);
165 private void gatherProxParameters(CQLProxNode node)
166 throws CQLParseException, IOException {
167 for (int i = 0; i < 4; i++) {
168 if (lexer.ttype != '/')
169 return; // end of proximity parameters
172 if (lexer.ttype != '/') {
173 // not an omitted default
175 // Order should be: relation/distance/unit/ordering
176 // For now, use MA's: unit/relation/distance/ordering
177 case 0: gatherProxRelation(node); break;
178 case 1: gatherProxDistance(node); break;
179 case 2: gatherProxUnit(node); break;
180 case 3: gatherProxOrdering(node); break;
186 private void gatherProxRelation(CQLProxNode node)
187 throws CQLParseException, IOException {
188 if (!isProxRelation())
189 throw new CQLParseException("expected proximity relation, got " +
191 node.addModifier("relation", null, lexer.render(lexer.ttype, false));
193 debug("gPR matched " + lexer.render(lexer.ttype, false));
196 private void gatherProxDistance(CQLProxNode node)
197 throws CQLParseException, IOException {
198 if (lexer.ttype != lexer.TT_NUMBER)
199 throw new CQLParseException("expected proximity distance, got " +
201 node.addModifier("distance", null, lexer.render(lexer.ttype, false));
203 debug("gPD matched " + lexer.render(lexer.ttype, false));
206 private void gatherProxUnit(CQLProxNode node)
207 throws CQLParseException, IOException {
208 if (lexer.ttype != lexer.TT_pWORD &&
209 lexer.ttype != lexer.TT_SENTENCE &&
210 lexer.ttype != lexer.TT_PARAGRAPH &&
211 lexer.ttype != lexer.TT_ELEMENT)
212 throw new CQLParseException("expected proximity unit, got " +
214 node.addModifier("unit", null, lexer.render());
218 private void gatherProxOrdering(CQLProxNode node)
219 throws CQLParseException, IOException {
220 if (lexer.ttype != lexer.TT_ORDERED &&
221 lexer.ttype != lexer.TT_UNORDERED)
222 throw new CQLParseException("expected proximity ordering, got " +
224 node.addModifier("ordering", null, lexer.render());
228 private boolean isBaseRelation()
229 throws CQLParseException {
230 debug("isBaseRelation: checking ttype=" + lexer.ttype +
231 " (" + lexer.render() + ")");
233 if (lexer.ttype == lexer.TT_WORD &&
234 lexer.sval.indexOf('.') == -1)
235 throw new CQLParseException("unknown first-class relation: " +
238 return (isProxRelation() ||
239 lexer.ttype == lexer.TT_ANY ||
240 lexer.ttype == lexer.TT_ALL ||
241 lexer.ttype == lexer.TT_EXACT ||
242 lexer.ttype == lexer.TT_SCR ||
243 lexer.ttype == lexer.TT_WORD);
246 // Checks for a relation that may be used inside a prox operator
247 private boolean isProxRelation() {
248 debug("isProxRelation: checking ttype=" + lexer.ttype +
249 " (" + lexer.render() + ")");
250 return (lexer.ttype == '<' ||
251 lexer.ttype == '>' ||
252 lexer.ttype == '=' ||
253 lexer.ttype == lexer.TT_LE ||
254 lexer.ttype == lexer.TT_GE ||
255 lexer.ttype == lexer.TT_NE);
258 private void match(int token)
259 throws CQLParseException, IOException {
260 debug("in match(" + lexer.render(token, true) + ")");
261 if (lexer.ttype != token)
262 throw new CQLParseException("expected " +
263 lexer.render(token, true) +
264 ", " + "got " + lexer.render());
265 int tmp = lexer.nextToken();
266 debug("match() got token=" + lexer.ttype + ", " +
267 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
268 " (tmp=" + tmp + ")");
271 private String matchSymbol(String expected)
272 throws CQLParseException, IOException {
274 debug("in matchSymbol()");
275 if (lexer.ttype == lexer.TT_WORD ||
276 lexer.ttype == lexer.TT_NUMBER ||
277 lexer.ttype == '"' ||
278 // The following is a complete list of keywords. Because
279 // they're listed here, they can be used unquoted as
280 // indexes, terms, prefix names and prefix identifiers.
281 // ### Instead, we should ask the lexer whether what we
282 // have is a keyword, and let the knowledge reside there.
283 lexer.ttype == lexer.TT_AND ||
284 lexer.ttype == lexer.TT_OR ||
285 lexer.ttype == lexer.TT_NOT ||
286 lexer.ttype == lexer.TT_PROX ||
287 lexer.ttype == lexer.TT_ANY ||
288 lexer.ttype == lexer.TT_ALL ||
289 lexer.ttype == lexer.TT_EXACT ||
290 lexer.ttype == lexer.TT_pWORD ||
291 lexer.ttype == lexer.TT_SENTENCE ||
292 lexer.ttype == lexer.TT_PARAGRAPH ||
293 lexer.ttype == lexer.TT_ELEMENT ||
294 lexer.ttype == lexer.TT_ORDERED ||
295 lexer.ttype == lexer.TT_UNORDERED ||
296 lexer.ttype == lexer.TT_RELEVANT ||
297 lexer.ttype == lexer.TT_FUZZY ||
298 lexer.ttype == lexer.TT_STEM ||
299 lexer.ttype == lexer.TT_SCR ||
300 lexer.ttype == lexer.TT_PHONETIC) {
301 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
302 lexer.render() : lexer.sval;
307 throw new CQLParseException("expected " + expected + ", " +
308 "got " + lexer.render());
313 * Simple test-harness for the CQLParser class.
315 * Reads a CQL query either from its command-line argument, if
316 * there is one, or standard input otherwise. So these two
317 * invocations are equivalent:
319 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
320 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
322 * The test-harness parses the supplied query and renders is as
323 * XCQL, so that both of the invocations above produce the
328 * <value>and</value>
332 * <value>or</value>
334 * <searchClause>
335 * <index>au</index>
337 * <value>=</value>
339 * <term>Kerninghan</term>
340 * </searchClause>
341 * <searchClause>
342 * <index>au</index>
344 * <value>=</value>
346 * <term>Ritchie</term>
347 * </searchClause>
349 * <searchClause>
350 * <index>ti</index>
352 * <value>=</value>
354 * <term>Unix</term>
355 * </searchClause>
360 * Causes the output to be written in CQL rather than XCQL - that
361 * is, a query equivalent to that which was input, is output. In
362 * effect, the test harness acts as a query canonicaliser.
364 * The input query, either as XCQL [default] or CQL [if the
365 * <TT>-c</TT> option is supplied].
367 public static void main (String[] args) {
368 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
371 Vector<String> argv = new Vector<String>();
372 for (int i = 0; i < args.length; i++) {
376 if (argv.size() > 0 && argv.get(0).equals("-d")) {
381 if (argv.size() > 0 && argv.get(0).equals("-c")) {
384 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
387 pfile = (String) argv.get(0);
391 if (argv.size() > 1) {
392 System.err.println("Usage: CQLParser [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
393 System.err.println("If unspecified, query is read from stdin");
398 if (argv.size() == 1) {
399 cql = (String) argv.get(0);
401 byte[] bytes = new byte[10000];
403 // Read in the whole of standard input in one go
404 int nbytes = System.in.read(bytes);
405 } catch (IOException ex) {
406 System.err.println("Can't read query: " + ex.getMessage());
409 cql = new String(bytes);
412 CQLParser parser = new CQLParser();
415 root = parser.parse(cql);
416 } catch (CQLParseException ex) {
417 System.err.println("Syntax error: " + ex.getMessage());
419 } catch (IOException ex) {
420 System.err.println("Can't compile query: " + ex.getMessage());
426 System.out.println(root.toCQL());
427 } else if (mode == 'p') {
428 InputStream f = new FileInputStream(pfile);
430 throw new FileNotFoundException(pfile);
432 Properties config = new Properties();
435 System.out.println(root.toPQF(config));
437 System.out.print(root.toXCQL(0));
439 } catch (IOException ex) {
440 System.err.println("Can't render query: " + ex.getMessage());
442 } catch (UnknownIndexException ex) {
443 System.err.println("Unknown index: " + ex.getMessage());
445 } catch (UnknownRelationException ex) {
446 System.err.println("Unknown relation: " + ex.getMessage());
448 } catch (UnknownRelationModifierException ex) {
449 System.err.println("Unknown relation modifier: " +
452 } catch (UnknownPositionException ex) {
453 System.err.println("Unknown position: " + ex.getMessage());
455 } catch (PQFTranslationException ex) {
456 // We catch all of this class's subclasses, so --
457 throw new Error("can't get a PQFTranslationException");