Mark syntax errors
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / CQLParser.java
index d577cd9..8a0fc17 100644 (file)
@@ -1,12 +1,12 @@
 
 package org.z3950.zing.cql;
+
+import java.io.BufferedReader;
 import java.io.IOException;
 import java.util.Properties;
 import java.io.InputStream;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.Reader;
-import java.io.StringReader;
+import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -20,8 +20,7 @@ import java.util.Set;
  *                     >http://zing.z3950.org/cql/index.html</A>
  */
 public class CQLParser {
-    private CQLLexer lexer;
-    private PositionAwareReader par; //active reader with position
+    private CQLTokenizer lexer;
     private final int compat;  // When false, implement CQL 1.2
     private final Set<String> customRelations = new HashSet<String>();
     
@@ -59,7 +58,7 @@ public class CQLParser {
      * @param allowKeywordTerms when false registered keywords are disallowed in unquoted terms
      */
     public CQLParser(int compat, boolean allowKeywordTerms) {
-       this.compat = V1POINT2;
+       this.compat = compat;
         this.allowKeywordTerms = allowKeywordTerms;
     }
     
@@ -94,26 +93,6 @@ public class CQLParser {
     public boolean unregisterCustomRelation(String relation) {
       return customRelations.remove(relation);
     }
-    
-    /**
-     * Compiles a CQL query.
-     * <P>
-     * The resulting parse tree may be further processed by hand (see
-     * the individual node-types' documentation for details on the
-     * data structure) or, more often, simply rendered out in the
-     * desired form using one of the back-ends.  <TT>toCQL()</TT>
-     * returns a decompiled CQL query equivalent to the one that was
-     * compiled in the first place; <TT>toXCQL()</TT> returns an
-     * XML snippet representing the query; and <TT>toPQF()</TT>
-     * returns the query rendered in Index Data's Prefix Query
-     * Format.
-     *
-     * @param cql      The query
-     * @return         A CQLNode object which is the root of a parse
-     * tree representing the query.  */
-    public CQLNode parse(String cql) throws CQLParseException, IOException {
-        return parse(new StringReader(cql));
-    }
 
     /**
      * Compiles a CQL query.
@@ -131,18 +110,17 @@ public class CQLParser {
      * @param cql      The query
      * @return         A CQLNode object which is the root of a parse
      * tree representing the query.  */
-    public CQLNode parse(Reader cql)
+    public CQLNode parse(String cql)
        throws CQLParseException, IOException {
-        par = new PositionAwareReader(cql);
-       lexer = new CQLLexer(par, LEXDEBUG);
+       lexer = new CQLLexer(cql, LEXDEBUG);
 
-       lexer.nextToken();
+       lexer.move();
        debug("about to parseQuery()");
        CQLNode root = parseTopLevelPrefixes("cql.serverChoice",
                new CQLRelation(compat == V1POINT2 ? "=" : "scr"));
-       if (lexer.ttype != CQLLexer.TT_EOF)
+       if (lexer.what() != CQLTokenizer.TT_EOF)
            throw new CQLParseException("junk after end: " + lexer.render(), 
-              par.getPosition());
+              lexer.pos());
 
        return root;
     }
@@ -151,25 +129,25 @@ public class CQLParser {
        throws CQLParseException, IOException {
        debug("top-level prefix mapping");
 
-       if (lexer.ttype == '>') {
+       if (lexer.what() == '>') {
            return parsePrefix(index, relation, true);
        }
 
        CQLNode node = parseQuery(index, relation);
        if ((compat == V1POINT2 || compat == V1POINT1SORT) &&
-           lexer.ttype == CQLLexer.TT_SORTBY) {
-           match(lexer.ttype);
+           lexer.what() == CQLTokenizer.TT_SORTBY) {
+           match(lexer.what());
            debug("sortspec");
 
            CQLSortNode sortnode = new CQLSortNode(node);
-           while (lexer.ttype != CQLLexer.TT_EOF) {
+           while (lexer.what() != CQLTokenizer.TT_EOF) {
                String sortindex = matchSymbol("sort index");
                ModifierSet ms = gatherModifiers(sortindex);
                sortnode.addSortIndex(ms);
            }
 
            if (sortnode.keys.size() == 0) {
-               throw new CQLParseException("no sort keys", par.getPosition());
+               throw new CQLParseException("no sort keys", lexer.pos());
            }
 
            node = sortnode;
@@ -183,25 +161,25 @@ public class CQLParser {
        debug("in parseQuery()");
 
        CQLNode term = parseTerm(index, relation);
-       while (lexer.ttype != CQLLexer.TT_EOF &&
-              lexer.ttype != ')' &&
-              lexer.ttype != CQLLexer.TT_SORTBY) {
-           if (lexer.ttype == CQLLexer.TT_AND ||
-               lexer.ttype == CQLLexer.TT_OR ||
-               lexer.ttype == CQLLexer.TT_NOT ||
-               lexer.ttype == CQLLexer.TT_PROX) {
-               int type = lexer.ttype;
-               String val = lexer.sval;
+       while (lexer.what() != CQLTokenizer.TT_EOF &&
+              lexer.what() != ')' &&
+              lexer.what() != CQLTokenizer.TT_SORTBY) {
+           if (lexer.what() == CQLTokenizer.TT_AND ||
+               lexer.what() == CQLTokenizer.TT_OR ||
+               lexer.what() == CQLTokenizer.TT_NOT ||
+               lexer.what() == CQLTokenizer.TT_PROX) {
+               int type = lexer.what();
+               String val = lexer.value();
                match(type);
                ModifierSet ms = gatherModifiers(val);
                CQLNode term2 = parseTerm(index, relation);
-               term = ((type == CQLLexer.TT_AND) ? new CQLAndNode(term, term2, ms) :
-                       (type == CQLLexer.TT_OR)  ? new CQLOrNode (term, term2, ms) :
-                       (type == CQLLexer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
+               term = ((type == CQLTokenizer.TT_AND) ? new CQLAndNode(term, term2, ms) :
+                       (type == CQLTokenizer.TT_OR)  ? new CQLOrNode (term, term2, ms) :
+                       (type == CQLTokenizer.TT_NOT) ? new CQLNotNode(term, term2, ms) :
                                                 new CQLProxNode(term, term2, ms));
            } else {
                throw new CQLParseException("expected boolean, got " +
-                                           lexer.render(), par.getPosition());
+                                           lexer.render(), lexer.pos());
            }
        }
 
@@ -214,21 +192,21 @@ public class CQLParser {
        debug("in gatherModifiers()");
 
        ModifierSet ms = new ModifierSet(base);
-       while (lexer.ttype == '/') {
+       while (lexer.what() == '/') {
            match('/');
-           if (lexer.ttype != CQLLexer.TT_WORD)
+           if (lexer.what() != CQLTokenizer.TT_WORD)
                throw new CQLParseException("expected modifier, "
                                            + "got " + lexer.render(), 
-                  par.getPosition());
-           String type = lexer.sval.toLowerCase();
-           match(lexer.ttype);
+                  lexer.pos());
+           String type = lexer.value().toLowerCase();
+           match(lexer.what());
            if (!isSymbolicRelation()) {
                // It's a simple modifier consisting of type only
                ms.addModifier(type);
            } else {
                // It's a complex modifier of the form type=value
-               String comparision = lexer.render(lexer.ttype, false);
-               match(lexer.ttype);
+               String comparision = lexer.render(lexer.what(), false);
+               match(lexer.what());
                String value = matchSymbol("modifier value");
                ms.addModifier(type, comparision, value);
            }
@@ -241,40 +219,47 @@ public class CQLParser {
        throws CQLParseException, IOException {
        debug("in parseTerm()");
 
-       String word;
+       String first;
+        StringBuilder all;
        while (true) {
-           if (lexer.ttype == '(') {
+           if (lexer.what() == '(') {
                debug("parenthesised term");
                match('(');
                CQLNode expr = parseQuery(index, relation);
                match(')');
                return expr;
-           } else if (lexer.ttype == '>') {
+           } else if (lexer.what() == '>') {
                return parsePrefix(index, relation, false);
            }
 
            debug("non-parenthesised term");
-           word = matchSymbol("index or term");
-            while (lexer.ttype == CQLLexer.TT_WORD && !isRelation()) {
-              word = word + " " + lexer.sval;
-              match(CQLLexer.TT_WORD);
+           first = matchSymbol("index or term");
+            all = new StringBuilder(first);
+            //match relation only on second postion
+            while (isWordOrString() && (all.length() > first.length() || !isRelation())) {
+              all.append(" ").append(lexer.value());
+              match(lexer.what());
             }
 
            if (!isRelation())
-               break;
-
-           index = word;
-           String relstr = (lexer.ttype == CQLLexer.TT_WORD ?
-                            lexer.sval : lexer.render(lexer.ttype, false));
+              break; //we're done if no relation
+           
+            //we have relation, but it only makes sense if preceded by a single term
+            if (all.length() > first.length()) {
+              throw new CQLParseException("unexpected relation '"+lexer.value()+"'"
+                , lexer.pos());
+            }
+            index = first;
+           String relstr = (lexer.what() == CQLTokenizer.TT_WORD ?
+                            lexer.value() : lexer.render(lexer.what(), false));
            relation = new CQLRelation(relstr);
-           match(lexer.ttype);
+           match(lexer.what());
            ModifierSet ms = gatherModifiers(relstr);
            relation.ms = ms;
            debug("index='" + index + ", " +
                  "relation='" + relation.toCQL() + "'");
        }
-
-       CQLTermNode node = new CQLTermNode(index, relation, word);
+       CQLTermNode node = new CQLTermNode(index, relation, all.toString());
        debug("made term node " + node.toCQL());
        return node;
     }
@@ -287,7 +272,7 @@ public class CQLParser {
        match('>');
        String name = null;
        String identifier = matchSymbol("prefix-name");
-       if (lexer.ttype == '=') {
+       if (lexer.what() == '=') {
            match('=');
            name = identifier;
            identifier = matchSymbol("prefix-identifer");
@@ -298,77 +283,76 @@ public class CQLParser {
 
        return new CQLPrefixNode(name, identifier, node);
     }
+    
+    private boolean isWordOrString() {
+      return CQLTokenizer.TT_WORD == lexer.what() 
+        || CQLTokenizer.TT_STRING == lexer.what();
+    }
 
     private boolean isRelation() {
-       debug("isRelation: checking ttype=" + lexer.ttype +
+       debug("isRelation: checking what()=" + lexer.what() +
              " (" + lexer.render() + ")");
-        if (lexer.ttype == CQLLexer.TT_WORD &&
-            (lexer.sval.indexOf('.') >= 0 ||
-             lexer.sval.equals("any") ||
-             lexer.sval.equals("all") ||
-             lexer.sval.equals("within") ||
-             lexer.sval.equals("encloses") ||
-             (lexer.sval.equals("exact") && compat != V1POINT2) ||
-             (lexer.sval.equals("scr") && compat != V1POINT2) ||
-             (lexer.sval.equals("adj") && compat == V1POINT2) ||
-             customRelations.contains(lexer.sval)))
+        if (lexer.what() == CQLTokenizer.TT_WORD &&
+            (lexer.value().indexOf('.') >= 0 ||
+             lexer.value().equals("any") ||
+             lexer.value().equals("all") ||
+             lexer.value().equals("within") ||
+             lexer.value().equals("encloses") ||
+             (lexer.value().equals("exact") && compat != V1POINT2) ||
+             (lexer.value().equals("scr") && compat != V1POINT2) ||
+             (lexer.value().equals("adj") && compat == V1POINT2) ||
+             customRelations.contains(lexer.value())))
           return true;
 
         return isSymbolicRelation();
     }
 
     private boolean isSymbolicRelation() {
-       debug("isSymbolicRelation: checking ttype=" + lexer.ttype +
+       debug("isSymbolicRelation: checking what()=" + lexer.what() +
              " (" + lexer.render() + ")");
-       return (lexer.ttype == '<' ||
-               lexer.ttype == '>' ||
-               lexer.ttype == '=' ||
-               lexer.ttype == CQLLexer.TT_LE ||
-               lexer.ttype == CQLLexer.TT_GE ||
-               lexer.ttype == CQLLexer.TT_NE ||
-               lexer.ttype == CQLLexer.TT_EQEQ);
+       return (lexer.what() == '<' ||
+               lexer.what() == '>' ||
+               lexer.what() == '=' ||
+               lexer.what() == CQLTokenizer.TT_LE ||
+               lexer.what() == CQLTokenizer.TT_GE ||
+               lexer.what() == CQLTokenizer.TT_NE ||
+               lexer.what() == CQLTokenizer.TT_EQEQ);
     }
 
     private void match(int token)
        throws CQLParseException, IOException {
        debug("in match(" + lexer.render(token, true) + ")");
-       if (lexer.ttype != token)
+       if (lexer.what() != token)
            throw new CQLParseException("expected " +
                                        lexer.render(token, true) +
                                        ", " + "got " + lexer.render(), 
-              par.getPosition());
-       int tmp = lexer.nextToken();
-       debug("match() got token=" + lexer.ttype + ", " +
-             "nval=" + lexer.nval + ", sval='" + lexer.sval + "'" +
-             " (tmp=" + tmp + ")");
+              lexer.pos());
+       lexer.move();
+       debug("match() got token=" + lexer.what() + ", value()='" + lexer.value() + "'");
     }
 
     private String matchSymbol(String expected)
        throws CQLParseException, IOException {
 
        debug("in matchSymbol()");
-       if (lexer.ttype == CQLLexer.TT_WORD ||
-           lexer.ttype == CQLLexer.TT_NUMBER ||
-           lexer.ttype == '"' ||
+       if (lexer.what() == CQLTokenizer.TT_WORD ||
+           lexer.what() == CQLTokenizer.TT_STRING ||
            // The following is a complete list of keywords.  Because
            // they're listed here, they can be used unquoted as
            // indexes, terms, prefix names and prefix identifiers.
-           // ### Instead, we should ask the lexer whether what we
-           // have is a keyword, and let the knowledge reside there.
             (allowKeywordTerms &&
-           lexer.ttype == CQLLexer.TT_AND ||
-           lexer.ttype == CQLLexer.TT_OR ||
-           lexer.ttype == CQLLexer.TT_NOT ||
-           lexer.ttype == CQLLexer.TT_PROX ||
-           lexer.ttype == CQLLexer.TT_SORTBY)) {
-           String symbol = (lexer.ttype == CQLLexer.TT_NUMBER) ?
-               lexer.render() : lexer.sval;
-           match(lexer.ttype);
+           lexer.what() == CQLTokenizer.TT_AND ||
+           lexer.what() == CQLTokenizer.TT_OR ||
+           lexer.what() == CQLTokenizer.TT_NOT ||
+           lexer.what() == CQLTokenizer.TT_PROX ||
+           lexer.what() == CQLTokenizer.TT_SORTBY)) {
+           String symbol = lexer.value();
+           match(lexer.what());
            return symbol;
        }
 
        throw new CQLParseException("expected " + expected + ", " +
-                                   "got " + lexer.render(), par.getPosition());
+                                   "got " + lexer.render(), lexer.pos());
     }
 
 
@@ -472,47 +456,59 @@ public class CQLParser {
        if (argv.size() == 1) {
            cql = (String) argv.get(0);
        } else {
-           byte[] bytes = new byte[10000];
+           BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
            try {
-               // Read in the whole of standard input in one go
-               int nbytes = System.in.read(bytes);
+               // read a single line of input
+              cql = buff.readLine();
+              if (cql == null) {
+                System.err.println("Can't read query from stdin");
+               System.exit(2);
+                return;
+              }
            } catch (IOException ex) {
                System.err.println("Can't read query: " + ex.getMessage());
                System.exit(2);
+                return;
            }
-           cql = new String(bytes);
        }
 
        CQLParser parser = new CQLParser(compat);
-       CQLNode root = null;
+       CQLNode root;
        try {
            root = parser.parse(cql);
        } catch (CQLParseException ex) {
            System.err.println("Syntax error: " + ex.getMessage());
+            StringBuilder space = new StringBuilder(cql.length());
+            System.out.println(cql);
+            for (int i=0; i<ex.getPosition(); i++) space.append(" ");
+            space.append("^");
+            System.err.println(space.toString());
            System.exit(3);
+            return; //compiler
        } catch (IOException ex) {
            System.err.println("Can't compile query: " + ex.getMessage());
            System.exit(4);
+            return; //compiler
        }
 
        try {
            if (mode == 'c') {
                System.out.println(root.toCQL());
            } else if (mode == 'p') {
+              try {
                InputStream f = new FileInputStream(pfile);
-               if (f == null)
-                   throw new FileNotFoundException(pfile);
-
                Properties config = new Properties();
                config.load(f);
                f.close();
                System.out.println(root.toPQF(config));
+              } catch (IOException ex) {
+                System.err.println("Can't load PQF properties:" + 
+                  ex.getMessage());
+                System.exit(5);
+              }
            } else {
                System.out.print(root.toXCQL());
            }
-       } catch (IOException ex) {
-           System.err.println("Can't render query: " + ex.getMessage());
-           System.exit(5);
        } catch (UnknownIndexException ex) {
            System.err.println("Unknown index: " + ex.getMessage());
            System.exit(6);
@@ -527,8 +523,8 @@ public class CQLParser {
            System.err.println("Unknown position: " + ex.getMessage());
            System.exit(9);
        } catch (PQFTranslationException ex) {
-           // We catch all of this class's subclasses, so --
-           throw new Error("can't get a PQFTranslationException");
+           System.err.println("Cannot translate to PQF: " + ex.getMessage());
+           System.exit(10);
        }
     }
 }