1 // $Id: CQLParser.java,v 1.21 2002-11-17 23:29:02 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.21 2002-11-17 23:29:02 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 lexer.ttype != lexer.TT_PHONETIC)
124 throw new CQLParseException("expected relation modifier, "
125 + "got " + lexer.render());
126 relation.addModifier(lexer.sval.toLowerCase());
130 debug("qualifier='" + qualifier + ", " +
131 "relation='" + relation.toCQL() + "'");
134 CQLTermNode node = new CQLTermNode(qualifier, relation, word);
135 debug("made term node " + node.toCQL());
139 private CQLNode parsePrefix(String qualifier, CQLRelation relation)
140 throws CQLParseException, IOException {
141 debug("prefix mapping");
144 String identifier = matchSymbol("prefix-name");
145 if (lexer.ttype == '=') {
148 identifier = matchSymbol("prefix-identifer");
150 CQLNode term = parseQuery(qualifier, relation);
151 return new CQLPrefixNode(name, identifier, term);
154 private void gatherProxParameters(CQLProxNode node)
155 throws CQLParseException, IOException {
156 for (int i = 0; i < 4; i++) {
157 if (lexer.ttype != '/')
158 return; // end of proximity parameters
161 if (lexer.ttype != '/') {
162 // not an omitted default
164 // Order should be: relation/distance/unit/ordering
165 // For now, use MA's: unit/relation/distance/ordering
166 case 0: gatherProxRelation(node); break;
167 case 1: gatherProxDistance(node); break;
168 case 2: gatherProxUnit(node); break;
169 case 3: gatherProxOrdering(node); break;
175 private void gatherProxRelation(CQLProxNode node)
176 throws CQLParseException, IOException {
177 if (!isProxRelation())
178 throw new CQLParseException("expected proximity relation, got " +
180 node.addModifier("relation", lexer.render(lexer.ttype, false));
182 debug("gPR matched " + lexer.render(lexer.ttype, false));
185 private void gatherProxDistance(CQLProxNode node)
186 throws CQLParseException, IOException {
187 if (lexer.ttype != lexer.TT_NUMBER)
188 throw new CQLParseException("expected proximity distance, got " +
190 node.addModifier("distance", lexer.render(lexer.ttype, false));
192 debug("gPD matched " + lexer.render(lexer.ttype, false));
195 private void gatherProxUnit(CQLProxNode node)
196 throws CQLParseException, IOException {
197 if (lexer.ttype != lexer.TT_pWORD &&
198 lexer.ttype != lexer.TT_SENTENCE &&
199 lexer.ttype != lexer.TT_PARAGRAPH &&
200 lexer.ttype != lexer.TT_ELEMENT)
201 throw new CQLParseException("expected proximity unit, got " +
203 node.addModifier("unit", lexer.render());
207 private void gatherProxOrdering(CQLProxNode node)
208 throws CQLParseException, IOException {
209 if (lexer.ttype != lexer.TT_ORDERED &&
210 lexer.ttype != lexer.TT_UNORDERED)
211 throw new CQLParseException("expected proximity ordering, got " +
213 node.addModifier("ordering", lexer.render());
217 private boolean isBaseRelation() {
218 debug("isBaseRelation: checking ttype=" + lexer.ttype +
219 " (" + lexer.render() + ")");
220 return (isProxRelation() ||
221 lexer.ttype == lexer.TT_ANY ||
222 lexer.ttype == lexer.TT_ALL ||
223 lexer.ttype == lexer.TT_EXACT ||
224 lexer.ttype == lexer.TT_SCR);
227 // Checks for a relation that may be used inside a prox operator
228 private boolean isProxRelation() {
229 debug("isProxRelation: checking ttype=" + lexer.ttype +
230 " (" + lexer.render() + ")");
231 return (lexer.ttype == '<' ||
232 lexer.ttype == '>' ||
233 lexer.ttype == '=' ||
234 lexer.ttype == lexer.TT_LE ||
235 lexer.ttype == lexer.TT_GE ||
236 lexer.ttype == lexer.TT_NE);
239 private void match(int token)
240 throws CQLParseException, IOException {
241 debug("in match(" + lexer.render(token, true) + ")");
242 if (lexer.ttype != token)
243 throw new CQLParseException("expected " +
244 lexer.render(token, true) +
245 ", " + "got " + lexer.render());
246 int tmp = lexer.nextToken();
247 debug("match() got token=" + lexer.ttype + ", " +
248 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
249 " (tmp=" + tmp + ")");
252 private String matchSymbol(String expected)
253 throws CQLParseException, IOException {
255 debug("in matchSymbol()");
256 if (lexer.ttype == lexer.TT_WORD ||
257 lexer.ttype == lexer.TT_NUMBER ||
258 lexer.ttype == '"' ||
259 // The following is a complete list of keywords. Because
260 // they're listed here, they can be used unquoted as
261 // qualifiers, terms, prefix names and prefix identifiers.
262 // ### Instead, we should ask the lexer whether what we
263 // have is a keyword, and let the knowledge reside there.
264 lexer.ttype == lexer.TT_AND ||
265 lexer.ttype == lexer.TT_OR ||
266 lexer.ttype == lexer.TT_NOT ||
267 lexer.ttype == lexer.TT_PROX ||
268 lexer.ttype == lexer.TT_ANY ||
269 lexer.ttype == lexer.TT_ALL ||
270 lexer.ttype == lexer.TT_EXACT ||
271 lexer.ttype == lexer.TT_pWORD ||
272 lexer.ttype == lexer.TT_SENTENCE ||
273 lexer.ttype == lexer.TT_PARAGRAPH ||
274 lexer.ttype == lexer.TT_ELEMENT ||
275 lexer.ttype == lexer.TT_ORDERED ||
276 lexer.ttype == lexer.TT_UNORDERED ||
277 lexer.ttype == lexer.TT_RELEVANT ||
278 lexer.ttype == lexer.TT_FUZZY ||
279 lexer.ttype == lexer.TT_STEM ||
280 lexer.ttype == lexer.TT_SCR ||
281 lexer.ttype == lexer.TT_PHONETIC) {
282 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
283 lexer.render() : lexer.sval;
288 throw new CQLParseException("expected " + expected + ", " +
289 "got " + lexer.render());
294 * Simple test-harness for the CQLParser class.
296 * Reads a CQL query either from its command-line argument, if
297 * there is one, or standard input otherwise. So these two
298 * invocations are equivalent:
300 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
301 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
303 * The test-harness parses the supplied query and renders is as
304 * XCQL, so that both of the invocations above produce the
309 * <value>and</value>
313 * <value>or</value>
315 * <searchClause>
316 * <index>au</index>
318 * <value>=</value>
320 * <term>Kerninghan</term>
321 * </searchClause>
322 * <searchClause>
323 * <index>au</index>
325 * <value>=</value>
327 * <term>Ritchie</term>
328 * </searchClause>
330 * <searchClause>
331 * <index>ti</index>
333 * <value>=</value>
335 * <term>Unix</term>
336 * </searchClause>
341 * Causes the output to be written in CQL rather than XCQL - that
342 * is, a query equivalent to that which was input, is output. In
343 * effect, the test harness acts as a query canonicaliser.
345 * The input query, either as XCQL [default] or CQL [if the
346 * <TT>-c</TT> option is supplied].
348 public static void main (String[] args) {
349 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
352 Vector argv = new Vector();
353 for (int i = 0; i < args.length; i++) {
357 if (argv.size() > 0 && argv.get(0).equals("-c")) {
360 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
363 pfile = (String) argv.get(0);
367 if (argv.size() > 1) {
369 "Usage: CQLParser [-c] [-p <pqf-properties> [<CQL-query>]");
370 System.err.println("If unspecified, query is read from stdin");
375 if (argv.size() == 1) {
376 cql = (String) argv.get(0);
378 byte[] bytes = new byte[10000];
380 // Read in the whole of standard input in one go
381 int nbytes = System.in.read(bytes);
382 } catch (IOException ex) {
383 System.err.println("Can't read query: " + ex.getMessage());
386 cql = new String(bytes);
389 CQLParser parser = new CQLParser();
392 root = parser.parse(cql);
393 } catch (CQLParseException ex) {
394 System.err.println("Syntax error: " + ex.getMessage());
396 } catch (IOException ex) {
397 System.err.println("Can't compile query: " + ex.getMessage());
403 System.out.println(root.toCQL());
404 } else if (mode == 'p') {
405 InputStream f = new FileInputStream(pfile);
407 throw new FileNotFoundException(pfile);
409 Properties config = new Properties();
412 System.out.println(root.toPQF(config));
414 System.out.print(root.toXCQL(0));
416 } catch (IOException ex) {
417 System.err.println("Can't render query: " + ex.getMessage());
419 } catch (UnknownQualifierException ex) {
420 System.err.println("Unknown qualifier: " + ex.getMessage());
422 } catch (UnknownRelationException ex) {
423 System.err.println("Unknown relation: " + ex.getMessage());
425 } catch (UnknownRelationModifierException ex) {
426 System.err.println("Unknown relation modifier: " +
429 } catch (UnknownPositionException ex) {
430 System.err.println("Unknown position: " + ex.getMessage());
432 } catch (PQFTranslationException ex) {
433 // We catch all of this class's subclasses, so --
434 throw new Error("can't get a PQFTranslationException");