1 // $Id: CQLParser.java,v 1.34 2007-06-29 12:54:05 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.34 2007-06-29 12:54:05 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 String symbol = (lexer.ttype == lexer.TT_NUMBER) ?
209 lexer.render() : lexer.sval;
214 throw new CQLParseException("expected " + expected + ", " +
215 "got " + lexer.render());
220 * Simple test-harness for the CQLParser class.
222 * Reads a CQL query either from its command-line argument, if
223 * there is one, or standard input otherwise. So these two
224 * invocations are equivalent:
226 * CQLParser 'au=(Kerninghan or Ritchie) and ti=Unix'
227 * echo au=(Kerninghan or Ritchie) and ti=Unix | CQLParser
229 * The test-harness parses the supplied query and renders is as
230 * XCQL, so that both of the invocations above produce the
235 * <value>and</value>
239 * <value>or</value>
241 * <searchClause>
242 * <index>au</index>
244 * <value>=</value>
246 * <term>Kerninghan</term>
247 * </searchClause>
248 * <searchClause>
249 * <index>au</index>
251 * <value>=</value>
253 * <term>Ritchie</term>
254 * </searchClause>
256 * <searchClause>
257 * <index>ti</index>
259 * <value>=</value>
261 * <term>Unix</term>
262 * </searchClause>
267 * Causes the output to be written in CQL rather than XCQL - that
268 * is, a query equivalent to that which was input, is output. In
269 * effect, the test harness acts as a query canonicaliser.
271 * The input query, either as XCQL [default] or CQL [if the
272 * <TT>-c</TT> option is supplied].
274 public static void main (String[] args) {
275 char mode = 'x'; // x=XCQL, c=CQL, p=PQF
278 Vector<String> argv = new Vector<String>();
279 for (int i = 0; i < args.length; i++) {
283 if (argv.size() > 0 && argv.get(0).equals("-d")) {
288 if (argv.size() > 0 && argv.get(0).equals("-c")) {
291 } else if (argv.size() > 1 && argv.get(0).equals("-p")) {
294 pfile = (String) argv.get(0);
298 if (argv.size() > 1) {
299 System.err.println("Usage: CQLParser [-d] [-c] [-p <pqf-properties> [<CQL-query>]");
300 System.err.println("If unspecified, query is read from stdin");
305 if (argv.size() == 1) {
306 cql = (String) argv.get(0);
308 byte[] bytes = new byte[10000];
310 // Read in the whole of standard input in one go
311 int nbytes = System.in.read(bytes);
312 } catch (IOException ex) {
313 System.err.println("Can't read query: " + ex.getMessage());
316 cql = new String(bytes);
319 CQLParser parser = new CQLParser();
322 root = parser.parse(cql);
323 } catch (CQLParseException ex) {
324 System.err.println("Syntax error: " + ex.getMessage());
326 } catch (IOException ex) {
327 System.err.println("Can't compile query: " + ex.getMessage());
333 System.out.println(root.toCQL());
334 } else if (mode == 'p') {
335 InputStream f = new FileInputStream(pfile);
337 throw new FileNotFoundException(pfile);
339 Properties config = new Properties();
342 System.out.println(root.toPQF(config));
344 System.out.print(root.toXCQL(0));
346 } catch (IOException ex) {
347 System.err.println("Can't render query: " + ex.getMessage());
349 } catch (UnknownIndexException ex) {
350 System.err.println("Unknown index: " + ex.getMessage());
352 } catch (UnknownRelationException ex) {
353 System.err.println("Unknown relation: " + ex.getMessage());
355 } catch (UnknownRelationModifierException ex) {
356 System.err.println("Unknown relation modifier: " +
359 } catch (UnknownPositionException ex) {
360 System.err.println("Unknown position: " + ex.getMessage());
362 } catch (PQFTranslationException ex) {
363 // We catch all of this class's subclasses, so --
364 throw new Error("can't get a PQFTranslationException");