1 // $Id: CQLParser.java,v 1.32 2007-06-29 11:56:47 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.32 2007-06-29 11:56:47 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 lexer.ttype == lexer.TT_PROX) {
68 int type = lexer.ttype;
69 String val = lexer.sval;
71 ModifierSet ms = gatherModifiers(val);
72 CQLNode term2 = parseTerm(index, relation);
73 term = ((type == lexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
74 (type == lexer.TT_OR) ? new CQLOrNode (term, term2, ms) :
75 (type == lexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
76 new CQLProxNode(term, term2, ms));
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 ModifierSet gatherModifiers(String base)
95 throws CQLParseException, IOException {
96 debug("in gatherModifiers()");
98 ModifierSet ms = new ModifierSet(base);
99 while (lexer.ttype == '/') {
101 if (lexer.ttype != lexer.TT_WORD)
102 throw new CQLParseException("expected modifier, "
103 + "got " + lexer.render());
104 String type = lexer.sval.toLowerCase();
107 // It's a simple modifier consisting of type only
108 ms.addModifier(type);
110 // It's a complex modifier of the form type=value
111 String comparision = lexer.render(lexer.ttype, false);
113 String value = matchSymbol("modifier value");
114 ms.addModifier(type, comparision, value);
121 private CQLNode parseTerm(String index, CQLRelation relation)
122 throws CQLParseException, IOException {
123 debug("in parseTerm()");
127 if (lexer.ttype == '(') {
128 debug("parenthesised term");
130 CQLNode expr = parseQuery(index, relation);
133 } else if (lexer.ttype == '>') {
135 return parsePrefix(index, relation);
138 debug("non-parenthesised term");
139 word = matchSymbol("index or term");
140 if (!isRelation() && lexer.ttype != lexer.TT_WORD)
144 String relstr = (lexer.ttype == lexer.TT_WORD ?
145 lexer.sval : lexer.render(lexer.ttype, false));
146 relation = new CQLRelation(relstr);
148 ModifierSet ms = gatherModifiers(relstr);
149 relation.setModifiers(ms);
150 debug("index='" + index + ", " +
151 "relation='" + relation.toCQL() + "'");
154 CQLTermNode node = new CQLTermNode(index, relation, word);
155 debug("made term node " + node.toCQL());
159 private CQLNode parsePrefix(String index, CQLRelation relation)
160 throws CQLParseException, IOException {
161 debug("prefix mapping");
164 String identifier = matchSymbol("prefix-name");
165 if (lexer.ttype == '=') {
168 identifier = matchSymbol("prefix-identifer");
170 CQLNode term = parseQuery(index, relation);
171 return new CQLPrefixNode(name, identifier, term);
174 private void gatherProxParameters(CQLProxNode node)
175 throws CQLParseException, IOException {
176 for (int i = 0; i < 4; i++) {
177 if (lexer.ttype != '/')
178 return; // end of proximity parameters
181 if (lexer.ttype != '/') {
182 // not an omitted default
184 // Order should be: relation/distance/unit/ordering
185 // For now, use MA's: unit/relation/distance/ordering
186 case 0: gatherProxRelation(node); break;
187 case 1: gatherProxDistance(node); break;
188 case 2: gatherProxUnit(node); break;
189 case 3: gatherProxOrdering(node); break;
195 private void gatherProxRelation(CQLProxNode node)
196 throws CQLParseException, IOException {
198 throw new CQLParseException("expected proximity relation, got " +
200 node.addModifier("relation", null, lexer.render(lexer.ttype, false));
202 debug("gPR matched " + lexer.render(lexer.ttype, false));
205 private void gatherProxDistance(CQLProxNode node)
206 throws CQLParseException, IOException {
207 if (lexer.ttype != lexer.TT_NUMBER)
208 throw new CQLParseException("expected proximity distance, got " +
210 node.addModifier("distance", null, lexer.render(lexer.ttype, false));
212 debug("gPD matched " + lexer.render(lexer.ttype, false));
215 private void gatherProxUnit(CQLProxNode node)
216 throws CQLParseException, IOException {
217 if (lexer.ttype != lexer.TT_pWORD &&
218 lexer.ttype != lexer.TT_SENTENCE &&
219 lexer.ttype != lexer.TT_PARAGRAPH &&
220 lexer.ttype != lexer.TT_ELEMENT)
221 throw new CQLParseException("expected proximity unit, got " +
223 node.addModifier("unit", null, lexer.render());
227 private void gatherProxOrdering(CQLProxNode node)
228 throws CQLParseException, IOException {
229 if (lexer.ttype != lexer.TT_ORDERED &&
230 lexer.ttype != lexer.TT_UNORDERED)
231 throw new CQLParseException("expected proximity ordering, got " +
233 node.addModifier("ordering", null, lexer.render());
237 // Checks for a relation that may be used inside a prox operator
238 private boolean isRelation() {
239 debug("isRelation: checking ttype=" + lexer.ttype +
240 " (" + lexer.render() + ")");
241 return (lexer.ttype == '<' ||
242 lexer.ttype == '>' ||
243 lexer.ttype == '=' ||
244 lexer.ttype == lexer.TT_LE ||
245 lexer.ttype == lexer.TT_GE ||
246 lexer.ttype == lexer.TT_NE);
249 private void match(int token)
250 throws CQLParseException, IOException {
251 debug("in match(" + lexer.render(token, true) + ")");
252 if (lexer.ttype != token)
253 throw new CQLParseException("expected " +
254 lexer.render(token, true) +
255 ", " + "got " + lexer.render());
256 int tmp = lexer.nextToken();
257 debug("match() got token=" + lexer.ttype + ", " +
258 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
259 " (tmp=" + tmp + ")");
262 private String matchSymbol(String expected)
263 throws CQLParseException, IOException {
265 debug("in matchSymbol()");
266 if (lexer.ttype == lexer.TT_WORD ||
267 lexer.ttype == lexer.TT_NUMBER ||
268 lexer.ttype == '"' ||
269 // The following is a complete list of keywords. Because
270 // they're listed here, they can be used unquoted as
271 // indexes, terms, prefix names and prefix identifiers.
272 // ### Instead, we should ask the lexer whether what we
273 // have is a keyword, and let the knowledge reside there.
274 lexer.ttype == lexer.TT_AND ||
275 lexer.ttype == lexer.TT_OR ||
276 lexer.ttype == lexer.TT_NOT ||
277 lexer.ttype == lexer.TT_PROX ||
278 lexer.ttype == lexer.TT_pWORD ||
279 lexer.ttype == lexer.TT_SENTENCE ||
280 lexer.ttype == lexer.TT_PARAGRAPH ||
281 lexer.ttype == lexer.TT_ELEMENT ||
282 lexer.ttype == lexer.TT_ORDERED ||
283 lexer.ttype == lexer.TT_UNORDERED) {
284 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
285 lexer.render() : lexer.sval;
290 throw new CQLParseException("expected " + expected + ", " +
291 "got " + lexer.render());
296 * Simple test-harness for the CQLParser class.
298 * Reads a CQL query either from its command-line argument, if
299 * there is one, or standard input otherwise. So these two
300 * invocations are equivalent:
302 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
303 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
305 * The test-harness parses the supplied query and renders is as
306 * XCQL, so that both of the invocations above produce the
311 * <value>and</value>
315 * <value>or</value>
317 * <searchClause>
318 * <index>au</index>
320 * <value>=</value>
322 * <term>Kerninghan</term>
323 * </searchClause>
324 * <searchClause>
325 * <index>au</index>
327 * <value>=</value>
329 * <term>Ritchie</term>
330 * </searchClause>
332 * <searchClause>
333 * <index>ti</index>
335 * <value>=</value>
337 * <term>Unix</term>
338 * </searchClause>
343 * Causes the output to be written in CQL rather than XCQL - that
344 * is, a query equivalent to that which was input, is output. In
345 * effect, the test harness acts as a query canonicaliser.
347 * The input query, either as XCQL [default] or CQL [if the
348 * <TT>-c</TT> option is supplied].
350 public static void main (String[] args) {
351 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
354 Vector<String> argv = new Vector<String>();
355 for (int i = 0; i < args.length; i++) {
359 if (argv.size() > 0 && argv.get(0).equals("-d")) {
364 if (argv.size() > 0 && argv.get(0).equals("-c")) {
367 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
370 pfile = (String) argv.get(0);
374 if (argv.size() > 1) {
375 System.err.println("Usage: CQLParser [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
376 System.err.println("If unspecified, query is read from stdin");
381 if (argv.size() == 1) {
382 cql = (String) argv.get(0);
384 byte[] bytes = new byte[10000];
386 // Read in the whole of standard input in one go
387 int nbytes = System.in.read(bytes);
388 } catch (IOException ex) {
389 System.err.println("Can't read query: " + ex.getMessage());
392 cql = new String(bytes);
395 CQLParser parser = new CQLParser();
398 root = parser.parse(cql);
399 } catch (CQLParseException ex) {
400 System.err.println("Syntax error: " + ex.getMessage());
402 } catch (IOException ex) {
403 System.err.println("Can't compile query: " + ex.getMessage());
409 System.out.println(root.toCQL());
410 } else if (mode == 'p') {
411 InputStream f = new FileInputStream(pfile);
413 throw new FileNotFoundException(pfile);
415 Properties config = new Properties();
418 System.out.println(root.toPQF(config));
420 System.out.print(root.toXCQL(0));
422 } catch (IOException ex) {
423 System.err.println("Can't render query: " + ex.getMessage());
425 } catch (UnknownIndexException ex) {
426 System.err.println("Unknown index: " + ex.getMessage());
428 } catch (UnknownRelationException ex) {
429 System.err.println("Unknown relation: " + ex.getMessage());
431 } catch (UnknownRelationModifierException ex) {
432 System.err.println("Unknown relation modifier: " +
435 } catch (UnknownPositionException ex) {
436 System.err.println("Unknown position: " + ex.getMessage());
438 } catch (PQFTranslationException ex) {
439 // We catch all of this class's subclasses, so --
440 throw new Error("can't get a PQFTranslationException");