1 // $Id: CQLParser.java,v 1.29 2007-06-28 00:00:53 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.29 2007-06-28 00:00:53 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 relation.addModifier(lexer.sval.toLowerCase());
131 debug("index='" + index + ", " +
132 "relation='" + relation.toCQL() + "'");
135 CQLTermNode node = new CQLTermNode(index, relation, word);
136 debug("made term node " + node.toCQL());
140 private CQLNode parsePrefix(String index, CQLRelation relation)
141 throws CQLParseException, IOException {
142 debug("prefix mapping");
145 String identifier = matchSymbol("prefix-name");
146 if (lexer.ttype == '=') {
149 identifier = matchSymbol("prefix-identifer");
151 CQLNode term = parseQuery(index, relation);
152 return new CQLPrefixNode(name, identifier, term);
155 private void gatherProxParameters(CQLProxNode node)
156 throws CQLParseException, IOException {
157 for (int i = 0; i < 4; i++) {
158 if (lexer.ttype != '/')
159 return; // end of proximity parameters
162 if (lexer.ttype != '/') {
163 // not an omitted default
165 // Order should be: relation/distance/unit/ordering
166 // For now, use MA's: unit/relation/distance/ordering
167 case 0: gatherProxRelation(node); break;
168 case 1: gatherProxDistance(node); break;
169 case 2: gatherProxUnit(node); break;
170 case 3: gatherProxOrdering(node); break;
176 private void gatherProxRelation(CQLProxNode node)
177 throws CQLParseException, IOException {
179 throw new CQLParseException("expected proximity relation, got " +
181 node.addModifier("relation", null, lexer.render(lexer.ttype, false));
183 debug("gPR matched " + lexer.render(lexer.ttype, false));
186 private void gatherProxDistance(CQLProxNode node)
187 throws CQLParseException, IOException {
188 if (lexer.ttype != lexer.TT_NUMBER)
189 throw new CQLParseException("expected proximity distance, got " +
191 node.addModifier("distance", null, lexer.render(lexer.ttype, false));
193 debug("gPD matched " + lexer.render(lexer.ttype, false));
196 private void gatherProxUnit(CQLProxNode node)
197 throws CQLParseException, IOException {
198 if (lexer.ttype != lexer.TT_pWORD &&
199 lexer.ttype != lexer.TT_SENTENCE &&
200 lexer.ttype != lexer.TT_PARAGRAPH &&
201 lexer.ttype != lexer.TT_ELEMENT)
202 throw new CQLParseException("expected proximity unit, got " +
204 node.addModifier("unit", null, lexer.render());
208 private void gatherProxOrdering(CQLProxNode node)
209 throws CQLParseException, IOException {
210 if (lexer.ttype != lexer.TT_ORDERED &&
211 lexer.ttype != lexer.TT_UNORDERED)
212 throw new CQLParseException("expected proximity ordering, got " +
214 node.addModifier("ordering", null, lexer.render());
218 // Checks for a relation that may be used inside a prox operator
219 private boolean isRelation() {
220 debug("isRelation: checking ttype=" + lexer.ttype +
221 " (" + lexer.render() + ")");
222 return (lexer.ttype == '<' ||
223 lexer.ttype == '>' ||
224 lexer.ttype == '=' ||
225 lexer.ttype == lexer.TT_LE ||
226 lexer.ttype == lexer.TT_GE ||
227 lexer.ttype == lexer.TT_NE);
230 private void match(int token)
231 throws CQLParseException, IOException {
232 debug("in match(" + lexer.render(token, true) + ")");
233 if (lexer.ttype != token)
234 throw new CQLParseException("expected " +
235 lexer.render(token, true) +
236 ", " + "got " + lexer.render());
237 int tmp = lexer.nextToken();
238 debug("match() got token=" + lexer.ttype + ", " +
239 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
240 " (tmp=" + tmp + ")");
243 private String matchSymbol(String expected)
244 throws CQLParseException, IOException {
246 debug("in matchSymbol()");
247 if (lexer.ttype == lexer.TT_WORD ||
248 lexer.ttype == lexer.TT_NUMBER ||
249 lexer.ttype == '"' ||
250 // The following is a complete list of keywords. Because
251 // they're listed here, they can be used unquoted as
252 // indexes, terms, prefix names and prefix identifiers.
253 // ### Instead, we should ask the lexer whether what we
254 // have is a keyword, and let the knowledge reside there.
255 lexer.ttype == lexer.TT_AND ||
256 lexer.ttype == lexer.TT_OR ||
257 lexer.ttype == lexer.TT_NOT ||
258 lexer.ttype == lexer.TT_PROX ||
259 lexer.ttype == lexer.TT_pWORD ||
260 lexer.ttype == lexer.TT_SENTENCE ||
261 lexer.ttype == lexer.TT_PARAGRAPH ||
262 lexer.ttype == lexer.TT_ELEMENT ||
263 lexer.ttype == lexer.TT_ORDERED ||
264 lexer.ttype == lexer.TT_UNORDERED) {
265 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
266 lexer.render() : lexer.sval;
271 throw new CQLParseException("expected " + expected + ", " +
272 "got " + lexer.render());
277 * Simple test-harness for the CQLParser class.
279 * Reads a CQL query either from its command-line argument, if
280 * there is one, or standard input otherwise. So these two
281 * invocations are equivalent:
283 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
284 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
286 * The test-harness parses the supplied query and renders is as
287 * XCQL, so that both of the invocations above produce the
292 * <value>and</value>
296 * <value>or</value>
298 * <searchClause>
299 * <index>au</index>
301 * <value>=</value>
303 * <term>Kerninghan</term>
304 * </searchClause>
305 * <searchClause>
306 * <index>au</index>
308 * <value>=</value>
310 * <term>Ritchie</term>
311 * </searchClause>
313 * <searchClause>
314 * <index>ti</index>
316 * <value>=</value>
318 * <term>Unix</term>
319 * </searchClause>
324 * Causes the output to be written in CQL rather than XCQL - that
325 * is, a query equivalent to that which was input, is output. In
326 * effect, the test harness acts as a query canonicaliser.
328 * The input query, either as XCQL [default] or CQL [if the
329 * <TT>-c</TT> option is supplied].
331 public static void main (String[] args) {
332 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
335 Vector<String> argv = new Vector<String>();
336 for (int i = 0; i < args.length; i++) {
340 if (argv.size() > 0 && argv.get(0).equals("-d")) {
345 if (argv.size() > 0 && argv.get(0).equals("-c")) {
348 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
351 pfile = (String) argv.get(0);
355 if (argv.size() > 1) {
356 System.err.println("Usage: CQLParser [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
357 System.err.println("If unspecified, query is read from stdin");
362 if (argv.size() == 1) {
363 cql = (String) argv.get(0);
365 byte[] bytes = new byte[10000];
367 // Read in the whole of standard input in one go
368 int nbytes = System.in.read(bytes);
369 } catch (IOException ex) {
370 System.err.println("Can't read query: " + ex.getMessage());
373 cql = new String(bytes);
376 CQLParser parser = new CQLParser();
379 root = parser.parse(cql);
380 } catch (CQLParseException ex) {
381 System.err.println("Syntax error: " + ex.getMessage());
383 } catch (IOException ex) {
384 System.err.println("Can't compile query: " + ex.getMessage());
390 System.out.println(root.toCQL());
391 } else if (mode == 'p') {
392 InputStream f = new FileInputStream(pfile);
394 throw new FileNotFoundException(pfile);
396 Properties config = new Properties();
399 System.out.println(root.toPQF(config));
401 System.out.print(root.toXCQL(0));
403 } catch (IOException ex) {
404 System.err.println("Can't render query: " + ex.getMessage());
406 } catch (UnknownIndexException ex) {
407 System.err.println("Unknown index: " + ex.getMessage());
409 } catch (UnknownRelationException ex) {
410 System.err.println("Unknown relation: " + ex.getMessage());
412 } catch (UnknownRelationModifierException ex) {
413 System.err.println("Unknown relation modifier: " +
416 } catch (UnknownPositionException ex) {
417 System.err.println("Unknown position: " + ex.getMessage());
419 } catch (PQFTranslationException ex) {
420 // We catch all of this class's subclasses, so --
421 throw new Error("can't get a PQFTranslationException");