1 // $Id: CQLParser.java,v 1.20 2002-11-14 22:04:16 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.20 2002-11-14 22:04:16 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; and <TT>toXCQL()</TT> returns an
38 * XML snippet representing the query.
40 * @param cql The query
41 * @return A CQLNode object which is the root of a parse
42 * tree representing the query. */
43 public CQLNode parse(String cql)
44 throws CQLParseException, IOException {
45 lexer = new CQLLexer(cql, LEXDEBUG);
48 debug("about to parseQuery()");
49 CQLNode root = parseQuery("srw.serverChoice", new CQLRelation("scr"));
50 if (lexer.ttype != lexer.TT_EOF)
51 throw new CQLParseException("junk after end: " + lexer.render());
56 private CQLNode parseQuery(String qualifier, CQLRelation relation)
57 throws CQLParseException, IOException {
58 debug("in parseQuery()");
60 CQLNode term = parseTerm(qualifier, relation);
61 while (lexer.ttype != lexer.TT_EOF &&
63 if (lexer.ttype == lexer.TT_AND) {
65 CQLNode term2 = parseTerm(qualifier, relation);
66 term = new CQLAndNode(term, term2);
67 } else if (lexer.ttype == lexer.TT_OR) {
69 CQLNode term2 = parseTerm(qualifier, relation);
70 term = new CQLOrNode(term, term2);
71 } else if (lexer.ttype == lexer.TT_NOT) {
73 CQLNode term2 = parseTerm(qualifier, relation);
74 term = new CQLNotNode(term, term2);
75 } else if (lexer.ttype == lexer.TT_PROX) {
77 CQLProxNode proxnode = new CQLProxNode(term);
78 gatherProxParameters(proxnode);
79 CQLNode term2 = parseTerm(qualifier, relation);
80 proxnode.addSecondSubterm(term2);
81 term = (CQLNode) proxnode;
83 throw new CQLParseException("expected boolean, got " +
92 private CQLNode parseTerm(String qualifier, CQLRelation relation)
93 throws CQLParseException, IOException {
94 debug("in parseTerm()");
98 if (lexer.ttype == '(') {
99 debug("parenthesised term");
101 CQLNode expr = parseQuery(qualifier, relation);
104 } else if (lexer.ttype == '>') {
106 return parsePrefix(qualifier, relation);
109 debug("non-parenthesised term");
110 word = matchSymbol("qualifier or term");
111 if (!isBaseRelation())
115 relation = new CQLRelation(lexer.render(lexer.ttype, false));
118 while (lexer.ttype == '/') {
120 if (lexer.ttype != lexer.TT_RELEVANT &&
121 lexer.ttype != lexer.TT_FUZZY &&
122 lexer.ttype != lexer.TT_STEM)
123 throw new CQLParseException("expected relation modifier, "
124 + "got " + lexer.render());
125 relation.addModifier(lexer.sval.toLowerCase());
129 debug("qualifier='" + qualifier + ", " +
130 "relation='" + relation.toCQL() + "'");
133 CQLTermNode node = new CQLTermNode(qualifier, relation, word);
134 debug("made term node " + node.toCQL());
138 private CQLNode parsePrefix(String qualifier, CQLRelation relation)
139 throws CQLParseException, IOException {
140 debug("prefix mapping");
143 String identifier = matchSymbol("prefix-name");
144 if (lexer.ttype == '=') {
147 identifier = matchSymbol("prefix-identifer");
149 CQLNode term = parseTerm(qualifier, relation);
150 return new CQLPrefixNode(name, identifier, term);
153 private void gatherProxParameters(CQLProxNode node)
154 throws CQLParseException, IOException {
155 for (int i = 0; i < 4; i++) {
156 if (lexer.ttype != '/')
157 return; // end of proximity parameters
160 if (lexer.ttype != '/') {
161 // not an omitted default
163 // Order should be: relation/distance/unit/ordering
164 // For now, use MA's: unit/relation/distance/ordering
165 case 0: gatherProxRelation(node); break;
166 case 1: gatherProxDistance(node); break;
167 case 2: gatherProxUnit(node); break;
168 case 3: gatherProxOrdering(node); break;
174 private void gatherProxRelation(CQLProxNode node)
175 throws CQLParseException, IOException {
176 if (!isProxRelation())
177 throw new CQLParseException("expected proximity relation, got " +
179 node.addModifier("relation", lexer.render(lexer.ttype, false));
181 debug("gPR matched " + lexer.render(lexer.ttype, false));
184 private void gatherProxDistance(CQLProxNode node)
185 throws CQLParseException, IOException {
186 if (lexer.ttype != lexer.TT_NUMBER)
187 throw new CQLParseException("expected proximity distance, got " +
189 node.addModifier("distance", lexer.render(lexer.ttype, false));
191 debug("gPD matched " + lexer.render(lexer.ttype, false));
194 private void gatherProxUnit(CQLProxNode node)
195 throws CQLParseException, IOException {
196 if (lexer.ttype != lexer.TT_pWORD &&
197 lexer.ttype != lexer.TT_SENTENCE &&
198 lexer.ttype != lexer.TT_PARAGRAPH &&
199 lexer.ttype != lexer.TT_ELEMENT)
200 throw new CQLParseException("expected proximity unit, got " +
202 node.addModifier("unit", lexer.render());
206 private void gatherProxOrdering(CQLProxNode node)
207 throws CQLParseException, IOException {
208 if (lexer.ttype != lexer.TT_ORDERED &&
209 lexer.ttype != lexer.TT_UNORDERED)
210 throw new CQLParseException("expected proximity ordering, got " +
212 node.addModifier("ordering", lexer.render());
216 private boolean isBaseRelation() {
217 debug("isBaseRelation: checking ttype=" + lexer.ttype +
218 " (" + lexer.render() + ")");
219 return (isProxRelation() ||
220 lexer.ttype == lexer.TT_ANY ||
221 lexer.ttype == lexer.TT_ALL ||
222 lexer.ttype == lexer.TT_EXACT ||
223 lexer.ttype == lexer.TT_SCR);
226 private boolean isProxRelation() {
227 debug("isProxRelation: checking ttype=" + lexer.ttype +
228 " (" + lexer.render() + ")");
229 return (lexer.ttype == '<' ||
230 lexer.ttype == '>' ||
231 lexer.ttype == '=' ||
232 lexer.ttype == lexer.TT_LE ||
233 lexer.ttype == lexer.TT_GE ||
234 lexer.ttype == lexer.TT_NE);
237 private void match(int token)
238 throws CQLParseException, IOException {
239 debug("in match(" + lexer.render(token, true) + ")");
240 if (lexer.ttype != token)
241 throw new CQLParseException("expected " +
242 lexer.render(token, true) +
243 ", " + "got " + lexer.render());
244 int tmp = lexer.nextToken();
245 debug("match() got token=" + lexer.ttype + ", " +
246 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
247 " (tmp=" + tmp + ")");
250 private String matchSymbol(String expected)
251 throws CQLParseException, IOException {
253 debug("in matchSymbol()");
254 if (lexer.ttype == lexer.TT_WORD ||
255 lexer.ttype == lexer.TT_NUMBER ||
256 lexer.ttype == '"' ||
257 // The following is a complete list of keywords. Because
258 // they're listed here, they can be used unquoted as
259 // qualifiers, terms, prefix names and prefix identifiers.
260 lexer.ttype == lexer.TT_AND ||
261 lexer.ttype == lexer.TT_OR ||
262 lexer.ttype == lexer.TT_NOT ||
263 lexer.ttype == lexer.TT_PROX ||
264 lexer.ttype == lexer.TT_ANY ||
265 lexer.ttype == lexer.TT_ALL ||
266 lexer.ttype == lexer.TT_EXACT ||
267 lexer.ttype == lexer.TT_pWORD ||
268 lexer.ttype == lexer.TT_SENTENCE ||
269 lexer.ttype == lexer.TT_PARAGRAPH ||
270 lexer.ttype == lexer.TT_ELEMENT ||
271 lexer.ttype == lexer.TT_ORDERED ||
272 lexer.ttype == lexer.TT_UNORDERED ||
273 lexer.ttype == lexer.TT_RELEVANT ||
274 lexer.ttype == lexer.TT_FUZZY ||
275 lexer.ttype == lexer.TT_STEM ||
276 lexer.ttype == lexer.TT_SCR) {
277 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
278 lexer.render() : lexer.sval;
283 throw new CQLParseException("expected " + expected + ", " +
284 "got " + lexer.render());
289 * Simple test-harness for the CQLParser class.
291 * Reads a CQL query either from its command-line argument, if
292 * there is one, or standard input otherwise. So these two
293 * invocations are equivalent:
295 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
296 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
298 * The test-harness parses the supplied query and renders is as
299 * XCQL, so that both of the invocations above produce the
304 * <value>and</value>
308 * <value>or</value>
310 * <searchClause>
311 * <index>au</index>
313 * <value>=</value>
315 * <term>Kerninghan</term>
316 * </searchClause>
317 * <searchClause>
318 * <index>au</index>
320 * <value>=</value>
322 * <term>Ritchie</term>
323 * </searchClause>
325 * <searchClause>
326 * <index>ti</index>
328 * <value>=</value>
330 * <term>Unix</term>
331 * </searchClause>
336 * Causes the output to be written in CQL rather than XCQL - that
337 * is, a query equivalent to that which was input, is output. In
338 * effect, the test harness acts as a query canonicaliser.
340 * The input query, either as XCQL [default] or CQL [if the
341 * <TT>-c</TT> option is supplied].
343 public static void main (String[] args) {
344 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
347 Vector argv = new Vector();
348 for (int i = 0; i < args.length; i++) {
352 if (argv.size() > 0 && argv.get(0).equals("-c")) {
355 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
358 pfile = (String) argv.get(0);
362 if (argv.size() > 1) {
364 "Usage: CQLParser [-c] [-p <pqf-properties> [<CQL-query>]");
365 System.err.println("If unspecified, query is read from stdin");
370 if (argv.size() == 1) {
371 cql = (String) argv.get(0);
373 byte[] bytes = new byte[10000];
375 // Read in the whole of standard input in one go
376 int nbytes = System.in.read(bytes);
377 } catch (IOException ex) {
378 System.err.println("Can't read query: " + ex.getMessage());
381 cql = new String(bytes);
384 CQLParser parser = new CQLParser();
387 root = parser.parse(cql);
388 } catch (CQLParseException ex) {
389 System.err.println("Syntax error: " + ex.getMessage());
391 } catch (IOException ex) {
392 System.err.println("Can't compile query: " + ex.getMessage());
398 System.out.println(root.toCQL());
399 } else if (mode == 'p') {
400 InputStream f = new FileInputStream(pfile);
402 throw new FileNotFoundException(pfile);
404 Properties config = new Properties();
407 System.out.println(root.toPQF(config));
409 System.out.print(root.toXCQL(0));
411 } catch (IOException ex) {
412 System.err.println("Can't render query: " + ex.getMessage());
414 } catch (UnknownQualifierException ex) {
415 System.err.println("Unknown qualifier: " + ex.getMessage());
417 } catch (UnknownRelationException ex) {
418 System.err.println("Unknown relation: " + ex.getMessage());
420 } catch (UnknownRelationModifierException ex) {
421 System.err.println("Unknown relation modifier: " +
424 } catch (UnknownPositionException ex) {
425 System.err.println("Unknown position: " + ex.getMessage());
427 } catch (PQFTranslationException ex) {
428 // We catch all of this class's subclasses, so --
429 throw new Error("can't get a PQFTranslationException");