1 // $Id: CQLParser.java,v 1.33 2007-06-29 12:27:08 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.33 2007-06-29 12:27:08 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));
78 throw new CQLParseException("expected boolean, got " +
87 private ModifierSet gatherModifiers(String base)
88 throws CQLParseException, IOException {
89 debug("in gatherModifiers()");
91 ModifierSet ms = new ModifierSet(base);
92 while (lexer.ttype == '/') {
94 if (lexer.ttype != lexer.TT_WORD)
95 throw new CQLParseException("expected modifier, "
96 + "got " + lexer.render());
97 String type = lexer.sval.toLowerCase();
100 // It's a simple modifier consisting of type only
101 ms.addModifier(type);
103 // It's a complex modifier of the form type=value
104 String comparision = lexer.render(lexer.ttype, false);
106 String value = matchSymbol("modifier value");
107 ms.addModifier(type, comparision, value);
114 private CQLNode parseTerm(String index, CQLRelation relation)
115 throws CQLParseException, IOException {
116 debug("in parseTerm()");
120 if (lexer.ttype == '(') {
121 debug("parenthesised term");
123 CQLNode expr = parseQuery(index, relation);
126 } else if (lexer.ttype == '>') {
128 return parsePrefix(index, relation);
131 debug("non-parenthesised term");
132 word = matchSymbol("index or term");
133 if (!isRelation() && lexer.ttype != lexer.TT_WORD)
137 String relstr = (lexer.ttype == lexer.TT_WORD ?
138 lexer.sval : lexer.render(lexer.ttype, false));
139 relation = new CQLRelation(relstr);
141 ModifierSet ms = gatherModifiers(relstr);
142 relation.setModifiers(ms);
143 debug("index='" + index + ", " +
144 "relation='" + relation.toCQL() + "'");
147 CQLTermNode node = new CQLTermNode(index, relation, word);
148 debug("made term node " + node.toCQL());
152 private CQLNode parsePrefix(String index, CQLRelation relation)
153 throws CQLParseException, IOException {
154 debug("prefix mapping");
157 String identifier = matchSymbol("prefix-name");
158 if (lexer.ttype == '=') {
161 identifier = matchSymbol("prefix-identifer");
163 CQLNode term = parseQuery(index, relation);
164 return new CQLPrefixNode(name, identifier, term);
167 // Checks for a relation
168 private boolean isRelation() {
169 debug("isRelation: checking ttype=" + lexer.ttype +
170 " (" + lexer.render() + ")");
171 return (lexer.ttype == '<' ||
172 lexer.ttype == '>' ||
173 lexer.ttype == '=' ||
174 lexer.ttype == lexer.TT_LE ||
175 lexer.ttype == lexer.TT_GE ||
176 lexer.ttype == lexer.TT_NE);
179 private void match(int token)
180 throws CQLParseException, IOException {
181 debug("in match(" + lexer.render(token, true) + ")");
182 if (lexer.ttype != token)
183 throw new CQLParseException("expected " +
184 lexer.render(token, true) +
185 ", " + "got " + lexer.render());
186 int tmp = lexer.nextToken();
187 debug("match() got token=" + lexer.ttype + ", " +
188 "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
189 " (tmp=" + tmp + ")");
192 private String matchSymbol(String expected)
193 throws CQLParseException, IOException {
195 debug("in matchSymbol()");
196 if (lexer.ttype == lexer.TT_WORD ||
197 lexer.ttype == lexer.TT_NUMBER ||
198 lexer.ttype == '"' ||
199 // The following is a complete list of keywords. Because
200 // they're listed here, they can be used unquoted as
201 // indexes, terms, prefix names and prefix identifiers.
202 // ### Instead, we should ask the lexer whether what we
203 // have is a keyword, and let the knowledge reside there.
204 lexer.ttype == lexer.TT_AND ||
205 lexer.ttype == lexer.TT_OR ||
206 lexer.ttype == lexer.TT_NOT ||
207 lexer.ttype == lexer.TT_PROX ||
208 lexer.ttype == lexer.TT_pWORD ||
209 lexer.ttype == lexer.TT_SENTENCE ||
210 lexer.ttype == lexer.TT_PARAGRAPH ||
211 lexer.ttype == lexer.TT_ELEMENT ||
212 lexer.ttype == lexer.TT_ORDERED ||
213 lexer.ttype == lexer.TT_UNORDERED) {
214 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
215 lexer.render() : lexer.sval;
220 throw new CQLParseException("expected " + expected + ", " +
221 "got " + lexer.render());
226 * Simple test-harness for the CQLParser class.
228 * Reads a CQL query either from its command-line argument, if
229 * there is one, or standard input otherwise. So these two
230 * invocations are equivalent:
232 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
233 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
235 * The test-harness parses the supplied query and renders is as
236 * XCQL, so that both of the invocations above produce the
241 * <value>and</value>
245 * <value>or</value>
247 * <searchClause>
248 * <index>au</index>
250 * <value>=</value>
252 * <term>Kerninghan</term>
253 * </searchClause>
254 * <searchClause>
255 * <index>au</index>
257 * <value>=</value>
259 * <term>Ritchie</term>
260 * </searchClause>
262 * <searchClause>
263 * <index>ti</index>
265 * <value>=</value>
267 * <term>Unix</term>
268 * </searchClause>
273 * Causes the output to be written in CQL rather than XCQL - that
274 * is, a query equivalent to that which was input, is output. In
275 * effect, the test harness acts as a query canonicaliser.
277 * The input query, either as XCQL [default] or CQL [if the
278 * <TT>-c</TT> option is supplied].
280 public static void main (String[] args) {
281 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
284 Vector<String> argv = new Vector<String>();
285 for (int i = 0; i < args.length; i++) {
289 if (argv.size() > 0 && argv.get(0).equals("-d")) {
294 if (argv.size() > 0 && argv.get(0).equals("-c")) {
297 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
300 pfile = (String) argv.get(0);
304 if (argv.size() > 1) {
305 System.err.println("Usage: CQLParser [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
306 System.err.println("If unspecified, query is read from stdin");
311 if (argv.size() == 1) {
312 cql = (String) argv.get(0);
314 byte[] bytes = new byte[10000];
316 // Read in the whole of standard input in one go
317 int nbytes = System.in.read(bytes);
318 } catch (IOException ex) {
319 System.err.println("Can't read query: " + ex.getMessage());
322 cql = new String(bytes);
325 CQLParser parser = new CQLParser();
328 root = parser.parse(cql);
329 } catch (CQLParseException ex) {
330 System.err.println("Syntax error: " + ex.getMessage());
332 } catch (IOException ex) {
333 System.err.println("Can't compile query: " + ex.getMessage());
339 System.out.println(root.toCQL());
340 } else if (mode == 'p') {
341 InputStream f = new FileInputStream(pfile);
343 throw new FileNotFoundException(pfile);
345 Properties config = new Properties();
348 System.out.println(root.toPQF(config));
350 System.out.print(root.toXCQL(0));
352 } catch (IOException ex) {
353 System.err.println("Can't render query: " + ex.getMessage());
355 } catch (UnknownIndexException ex) {
356 System.err.println("Unknown index: " + ex.getMessage());
358 } catch (UnknownRelationException ex) {
359 System.err.println("Unknown relation: " + ex.getMessage());
361 } catch (UnknownRelationModifierException ex) {
362 System.err.println("Unknown relation modifier: " +
365 } catch (UnknownPositionException ex) {
366 System.err.println("Unknown position: " + ex.getMessage());
368 } catch (PQFTranslationException ex) {
369 // We catch all of this class's subclasses, so --
370 throw new Error("can't get a PQFTranslationException");