1 // $Id: CQLParser.java,v 1.22 2002-11-20 01:15:15 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.22 2002-11-20 01:15:15 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 qualifier, CQLRelation relation)
59 throws CQLParseException, IOException {
60 debug("in parseQuery()");
62 CQLNode term = parseTerm(qualifier, relation);
63 while (lexer.ttype != lexer.TT_EOF &&
65 if (lexer.ttype == lexer.TT_AND) {
67 CQLNode term2 = parseTerm(qualifier, relation);
68 term = new CQLAndNode(term, term2);
69 } else if (lexer.ttype == lexer.TT_OR) {
71 CQLNode term2 = parseTerm(qualifier, relation);
72 term = new CQLOrNode(term, term2);
73 } else if (lexer.ttype == lexer.TT_NOT) {
75 CQLNode term2 = parseTerm(qualifier, 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(qualifier, relation);
82 proxnode.addSecondSubterm(term2);
83 term = (CQLNode) proxnode;
85 throw new CQLParseException("expected boolean, got " +
94 private CQLNode parseTerm(String qualifier, CQLRelation relation)
95 throws CQLParseException, IOException {
96 debug("in parseTerm()");
100 if (lexer.ttype == '(') {
101 debug("parenthesised term");
103 CQLNode expr = parseQuery(qualifier, relation);
106 } else if (lexer.ttype == '>') {
108 return parsePrefix(qualifier, relation);
111 debug("non-parenthesised term");
112 word = matchSymbol("qualifier or term");
113 if (!isBaseRelation())
117 relation = new CQLRelation(lexer.render(lexer.ttype, false));
120 while (lexer.ttype == '/') {
122 if (lexer.ttype != lexer.TT_RELEVANT &&
123 lexer.ttype != lexer.TT_FUZZY &&
124 lexer.ttype != lexer.TT_STEM &&
125 lexer.ttype != lexer.TT_PHONETIC)
126 throw new CQLParseException("expected relation modifier, "
127 + "got " + lexer.render());
128 relation.addModifier(lexer.sval.toLowerCase());
132 debug("qualifier='" + qualifier + ", " +
133 "relation='" + relation.toCQL() + "'");
136 CQLTermNode node = new CQLTermNode(qualifier, relation, word);
137 debug("made term node " + node.toCQL());
141 private CQLNode parsePrefix(String qualifier, CQLRelation relation)
142 throws CQLParseException, IOException {
143 debug("prefix mapping");
146 String identifier = matchSymbol("prefix-name");
147 if (lexer.ttype == '=') {
150 identifier = matchSymbol("prefix-identifer");
152 CQLNode term = parseQuery(qualifier, relation);
153 return new CQLPrefixNode(name, identifier, term);
156 private void gatherProxParameters(CQLProxNode node)
157 throws CQLParseException, IOException {
158 for (int i = 0; i < 4; i++) {
159 if (lexer.ttype != '/')
160 return; // end of proximity parameters
163 if (lexer.ttype != '/') {
164 // not an omitted default
166 // Order should be: relation/distance/unit/ordering
167 // For now, use MA's: unit/relation/distance/ordering
168 case 0: gatherProxRelation(node); break;
169 case 1: gatherProxDistance(node); break;
170 case 2: gatherProxUnit(node); break;
171 case 3: gatherProxOrdering(node); break;
177 private void gatherProxRelation(CQLProxNode node)
178 throws CQLParseException, IOException {
179 if (!isProxRelation())
180 throw new CQLParseException("expected proximity relation, got " +
182 node.addModifier("relation", lexer.render(lexer.ttype, false));
184 debug("gPR matched " + lexer.render(lexer.ttype, false));
187 private void gatherProxDistance(CQLProxNode node)
188 throws CQLParseException, IOException {
189 if (lexer.ttype != lexer.TT_NUMBER)
190 throw new CQLParseException("expected proximity distance, got " +
192 node.addModifier("distance", lexer.render(lexer.ttype, false));
194 debug("gPD matched " + lexer.render(lexer.ttype, false));
197 private void gatherProxUnit(CQLProxNode node)
198 throws CQLParseException, IOException {
199 if (lexer.ttype != lexer.TT_pWORD &&
200 lexer.ttype != lexer.TT_SENTENCE &&
201 lexer.ttype != lexer.TT_PARAGRAPH &&
202 lexer.ttype != lexer.TT_ELEMENT)
203 throw new CQLParseException("expected proximity unit, got " +
205 node.addModifier("unit", lexer.render());
209 private void gatherProxOrdering(CQLProxNode node)
210 throws CQLParseException, IOException {
211 if (lexer.ttype != lexer.TT_ORDERED &&
212 lexer.ttype != lexer.TT_UNORDERED)
213 throw new CQLParseException("expected proximity ordering, got " +
215 node.addModifier("ordering", lexer.render());
219 private boolean isBaseRelation() {
220 debug("isBaseRelation: checking ttype=" + lexer.ttype +
221 " (" + lexer.render() + ")");
222 return (isProxRelation() ||
223 lexer.ttype == lexer.TT_ANY ||
224 lexer.ttype == lexer.TT_ALL ||
225 lexer.ttype == lexer.TT_EXACT ||
226 lexer.ttype == lexer.TT_SCR);
229 // Checks for a relation that may be used inside a prox operator
230 private boolean isProxRelation() {
231 debug("isProxRelation: checking ttype=" + lexer.ttype +
232 " (" + lexer.render() + ")");
233 return (lexer.ttype == '<' ||
234 lexer.ttype == '>' ||
235 lexer.ttype == '=' ||
236 lexer.ttype == lexer.TT_LE ||
237 lexer.ttype == lexer.TT_GE ||
238 lexer.ttype == lexer.TT_NE);
241 private void match(int token)
242 throws CQLParseException, IOException {
243 debug("in match(" + lexer.render(token, true) + ")");
244 if (lexer.ttype != token)
245 throw new CQLParseException("expected " +
246 lexer.render(token, true) +
247 ", " + "got " + lexer.render());
248 int tmp = lexer.nextToken();
249 debug("match() got token=" + lexer.ttype + ", " +
250 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
251 " (tmp=" + tmp + ")");
254 private String matchSymbol(String expected)
255 throws CQLParseException, IOException {
257 debug("in matchSymbol()");
258 if (lexer.ttype == lexer.TT_WORD ||
259 lexer.ttype == lexer.TT_NUMBER ||
260 lexer.ttype == '"' ||
261 // The following is a complete list of keywords. Because
262 // they're listed here, they can be used unquoted as
263 // qualifiers, terms, prefix names and prefix identifiers.
264 // ### Instead, we should ask the lexer whether what we
265 // have is a keyword, and let the knowledge reside there.
266 lexer.ttype == lexer.TT_AND ||
267 lexer.ttype == lexer.TT_OR ||
268 lexer.ttype == lexer.TT_NOT ||
269 lexer.ttype == lexer.TT_PROX ||
270 lexer.ttype == lexer.TT_ANY ||
271 lexer.ttype == lexer.TT_ALL ||
272 lexer.ttype == lexer.TT_EXACT ||
273 lexer.ttype == lexer.TT_pWORD ||
274 lexer.ttype == lexer.TT_SENTENCE ||
275 lexer.ttype == lexer.TT_PARAGRAPH ||
276 lexer.ttype == lexer.TT_ELEMENT ||
277 lexer.ttype == lexer.TT_ORDERED ||
278 lexer.ttype == lexer.TT_UNORDERED ||
279 lexer.ttype == lexer.TT_RELEVANT ||
280 lexer.ttype == lexer.TT_FUZZY ||
281 lexer.ttype == lexer.TT_STEM ||
282 lexer.ttype == lexer.TT_SCR ||
283 lexer.ttype == lexer.TT_PHONETIC) {
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 argv = new Vector();
355 for (int i = 0; i < args.length; i++) {
359 if (argv.size() > 0 && argv.get(0).equals("-c")) {
362 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
365 pfile = (String) argv.get(0);
369 if (argv.size() > 1) {
371 "Usage: CQLParser [-c] [-p <pqf-properties> [<CQL-query>]");
372 System.err.println("If unspecified, query is read from stdin");
377 if (argv.size() == 1) {
378 cql = (String) argv.get(0);
380 byte[] bytes = new byte[10000];
382 // Read in the whole of standard input in one go
383 int nbytes = System.in.read(bytes);
384 } catch (IOException ex) {
385 System.err.println("Can't read query: " + ex.getMessage());
388 cql = new String(bytes);
391 CQLParser parser = new CQLParser();
394 root = parser.parse(cql);
395 } catch (CQLParseException ex) {
396 System.err.println("Syntax error: " + ex.getMessage());
398 } catch (IOException ex) {
399 System.err.println("Can't compile query: " + ex.getMessage());
405 System.out.println(root.toCQL());
406 } else if (mode == 'p') {
407 InputStream f = new FileInputStream(pfile);
409 throw new FileNotFoundException(pfile);
411 Properties config = new Properties();
414 System.out.println(root.toPQF(config));
416 System.out.print(root.toXCQL(0));
418 } catch (IOException ex) {
419 System.err.println("Can't render query: " + ex.getMessage());
421 } catch (UnknownQualifierException ex) {
422 System.err.println("Unknown qualifier: " + ex.getMessage());
424 } catch (UnknownRelationException ex) {
425 System.err.println("Unknown relation: " + ex.getMessage());
427 } catch (UnknownRelationModifierException ex) {
428 System.err.println("Unknown relation modifier: " +
431 } catch (UnknownPositionException ex) {
432 System.err.println("Unknown position: " + ex.getMessage());
434 } catch (PQFTranslationException ex) {
435 // We catch all of this class's subclasses, so --
436 throw new Error("can't get a PQFTranslationException");