All sorts of changes. Generally moving towards first release.
[cql-java-moved-to-github.git] / src / org / z3950 / zing / cql / CQLParser.java
1 // $Id: CQLParser.java,v 1.11 2002-10-31 22:22:01 mike Exp $
2
3 package org.z3950.zing.cql;
4 import java.io.IOException;
5
6
7 /**
8  * Compiles a CQL string into a parse tree.
9  * ##
10  *
11  * @version     $Id: CQLParser.java,v 1.11 2002-10-31 22:22:01 mike Exp $
12  * @see         <A href="http://zing.z3950.org/cql/index.html"
13  *                      >http://zing.z3950.org/cql/index.html</A>
14  */
15 public class CQLParser {
16     private CQLLexer lexer;
17     static private boolean DEBUG = false;
18     static private boolean LEXDEBUG = false;
19
20     private static void debug(String str) {
21         if (DEBUG)
22             System.err.println("PARSEDEBUG: " + str);
23     }
24
25     public CQLNode parse(String cql)
26         throws CQLParseException, IOException {
27         lexer = new CQLLexer(cql, LEXDEBUG);
28
29         lexer.nextToken();
30         debug("about to parse_query()");
31         CQLNode root = parse_query("srw.serverChoice", new CQLRelation("="));
32         if (lexer.ttype != lexer.TT_EOF)
33             throw new CQLParseException("junk after end: " + lexer.render());
34
35         return root;
36     }
37
38     private CQLNode parse_query(String qualifier, CQLRelation relation)
39         throws CQLParseException, IOException {
40         debug("in parse_query()");
41
42         CQLNode term = parse_term(qualifier, relation);
43         while (lexer.ttype != lexer.TT_EOF &&
44                lexer.ttype != ')') {
45             if (lexer.ttype == lexer.TT_AND) {
46                 match(lexer.TT_AND);
47                 CQLNode term2 = parse_term(qualifier, relation);
48                 term = new CQLAndNode(term, term2);
49             } else if (lexer.ttype == lexer.TT_OR) {
50                 match(lexer.TT_OR);
51                 CQLNode term2 = parse_term(qualifier, relation);
52                 term = new CQLOrNode(term, term2);
53             } else if (lexer.ttype == lexer.TT_NOT) {
54                 match(lexer.TT_NOT);
55                 CQLNode term2 = parse_term(qualifier, relation);
56                 term = new CQLNotNode(term, term2);
57             } else if (lexer.ttype == lexer.TT_PROX) {
58                 match(lexer.TT_PROX);
59                 CQLProxNode proxnode = new CQLProxNode(term);
60                 gatherProxParameters(proxnode);
61                 CQLNode term2 = parse_term(qualifier, relation);
62                 proxnode.addSecondSubterm(term2);
63                 term = (CQLNode) proxnode;
64             } else {
65                 throw new CQLParseException("expected boolean, got " +
66                                             lexer.render());
67             }
68         }
69
70         debug("no more ops");
71         return term;
72     }
73
74     private CQLNode parse_term(String qualifier, CQLRelation relation)
75         throws CQLParseException, IOException {
76         debug("in parse_term()");
77
78         String word;
79         while (true) {
80             if (lexer.ttype == '(') {
81                 debug("parenthesised term");
82                 match('(');
83                 CQLNode expr = parse_query(qualifier, relation);
84                 match(')');
85                 return expr;
86             } else if (lexer.ttype != lexer.TT_WORD && lexer.ttype != '"') {
87                 throw new CQLParseException("expected qualifier or term, " +
88                                             "got " + lexer.render());
89             }
90
91             debug("non-parenthesised term");
92             word = lexer.sval;
93             match(lexer.ttype);
94             if (!isBaseRelation())
95                 break;
96
97             qualifier = word;
98             relation = new CQLRelation(lexer.render(lexer.ttype, false));
99             match(lexer.ttype);
100
101             while (lexer.ttype == '/') {
102                 match('/');
103                 // ### could insist on known modifiers only
104                 if (lexer.ttype != lexer.TT_WORD)
105                     throw new CQLParseException("expected relation modifier, "
106                                                 + "got " + lexer.render());
107                 relation.addModifier(lexer.sval);
108                 match(lexer.TT_WORD);
109             }
110
111             debug("qualifier='" + qualifier + ", " +
112                   "relation='" + relation.toCQL() + "'");
113         }
114
115         CQLTermNode node = new CQLTermNode(qualifier, relation, word);
116         debug("made term node " + node.toCQL());
117         return node;
118     }
119
120     private void gatherProxParameters(CQLProxNode node)
121         throws CQLParseException, IOException {
122         for (int i = 0; i < 4; i++) {
123             if (lexer.ttype != '/')
124                 return;         // end of proximity parameters
125
126             match('/');
127             if (lexer.ttype != '/') {
128                 // not an omitted default
129                 switch (i) {
130                     // Assumes order is: relation/distance/unit/ordering
131                 case 0: gatherProxRelation(node); break;
132                 case 1: gatherProxDistance(node); break;
133                 case 2: gatherProxUnit(node); break;
134                 case 3: gatherProxOrdering(node); break;
135                 }
136             }
137         }
138     }
139
140     private void gatherProxRelation(CQLProxNode node)
141         throws CQLParseException, IOException {
142         if (!isProxRelation())
143             throw new CQLParseException("expected proximity relation, got " +
144                                         lexer.render());
145         node.addModifier("relation", lexer.render(lexer.ttype, false));
146         match(lexer.ttype);
147         debug("gPR matched " + lexer.render(lexer.ttype, false));
148     }
149
150     private void gatherProxDistance(CQLProxNode node)
151         throws CQLParseException, IOException {
152         if (lexer.ttype != lexer.TT_NUMBER)
153             throw new CQLParseException("expected proximity distance, got " +
154                                         lexer.render());
155         node.addModifier("distance", lexer.render(lexer.ttype, false));
156         match(lexer.ttype);
157         debug("gPD matched " + lexer.render(lexer.ttype, false));
158     }
159
160     private void gatherProxUnit(CQLProxNode node)
161         throws CQLParseException, IOException {
162         if (lexer.ttype != lexer.TT_pWORD &&
163             lexer.ttype != lexer.TT_SENTENCE &&
164             lexer.ttype != lexer.TT_PARAGRAPH &&
165             lexer.ttype != lexer.TT_ELEMENT)
166             throw new CQLParseException("expected proximity unit, got " +
167                                         lexer.render());
168         node.addModifier("unit", lexer.render());
169         match(lexer.ttype);
170     }
171
172     private void gatherProxOrdering(CQLProxNode node)
173         throws CQLParseException, IOException {
174         if (lexer.ttype != lexer.TT_ORDERED &&
175             lexer.ttype != lexer.TT_UNORDERED)
176             throw new CQLParseException("expected proximity ordering, got " +
177                                         lexer.render());
178         node.addModifier("ordering", lexer.render());
179         match(lexer.ttype);
180     }
181
182     boolean isBaseRelation() {
183         debug("isBaseRelation: checking ttype=" + lexer.ttype +
184               " (" + lexer.render() + ")");
185         return (isProxRelation() ||
186                 lexer.ttype == lexer.TT_ANY ||
187                 lexer.ttype == lexer.TT_ALL ||
188                 lexer.ttype == lexer.TT_EXACT);
189     }
190
191     boolean isProxRelation() {
192         debug("isProxRelation: checking ttype=" + lexer.ttype +
193               " (" + lexer.render() + ")");
194         return (lexer.ttype == '<' ||
195                 lexer.ttype == '>' ||
196                 lexer.ttype == '=' ||
197                 lexer.ttype == lexer.TT_LE ||
198                 lexer.ttype == lexer.TT_GE ||
199                 lexer.ttype == lexer.TT_NE);
200     }
201
202     private void match(int token)
203         throws CQLParseException, IOException {
204         debug("in match(" + lexer.render(token, true) + ")");
205         if (lexer.ttype != token)
206             throw new CQLParseException("expected " +
207                                         lexer.render(token, true) +
208                                         ", " + "got " + lexer.render());
209         int tmp = lexer.nextToken();
210         debug("match() got token=" + lexer.ttype + ", " +
211               "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
212               " (tmp=" + tmp + ")");
213     }
214
215
216     // Test harness.
217     //
218     // e.g. echo '(au=Kerninghan or au=Ritchie) and ti=Unix' |
219     //                          java org.z3950.zing.cql.CQLParser
220     // yields:
221     //  <triple>
222     //    <boolean>and</boolean>
223     //    <triple>
224     //      <boolean>or</boolean>
225     //      <searchClause>
226     //        <index>au<index>
227     //        <relation>=<relation>
228     //        <term>Kerninghan<term>
229     //      </searchClause>
230     //      <searchClause>
231     //        <index>au<index>
232     //        <relation>=<relation>
233     //        <term>Ritchie<term>
234     //      </searchClause>
235     //    </triple>
236     //    <searchClause>
237     //      <index>ti<index>
238     //      <relation>=<relation>
239     //      <term>Unix<term>
240     //    </searchClause>
241     //  </triple>
242     //
243     public static void main (String[] args) {
244         if (args.length > 1) {
245             System.err.println("Usage: CQLParser [<CQL-query>]");
246             System.err.println("If unspecified, query is read from stdin");
247             System.exit(1);
248         }
249
250         String cql;
251         if (args.length == 1) {
252             cql = args[0];
253         } else {
254             byte[] bytes = new byte[10000];
255             try {
256                 // Read in the whole of standard input in one go
257                 int nbytes = System.in.read(bytes);
258             } catch (java.io.IOException ex) {
259                 System.err.println("Can't read query: " + ex.getMessage());
260                 System.exit(2);
261             }
262             cql = new String(bytes);
263         }
264
265         CQLParser parser = new CQLParser();
266         CQLNode root;
267         try {
268             root = parser.parse(cql);
269             debug("root='" + root + "'");
270             System.out.println(root.toCQL());
271         } catch (CQLParseException ex) {
272             System.err.println("Syntax error: " + ex.getMessage());
273             System.exit(3);
274         } catch (java.io.IOException ex) {
275             System.err.println("Can't compile query: " + ex.getMessage());
276             System.exit(4);
277         }
278     }
279 }