/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This file was taken from ActiveMQ activemq-client/src/main/grammar/SelectorParser.jj.
 *
 * There are some modifications:
 * 1. Convert string expressions default;
 * 2. HEX_LITERAL and OCTAL_LITERAL were removed;
 * 3. LIKE, ESCAPE, XPATH and XQUERY were removed;
 * 4. Computation expressions were removed;
 */

// ----------------------------------------------------------------------------
// OPTIONS
// ----------------------------------------------------------------------------
options {
  STATIC = false;
  UNICODE_INPUT = true;

  //ERROR_REPORTING = false;
}

// ----------------------------------------------------------------------------
// PARSER
// ----------------------------------------------------------------------------

PARSER_BEGIN(SelectorParser)

package org.apache.rocketmq.filter.parser;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.rocketmq.filter.expression.BooleanExpression;
import org.apache.rocketmq.filter.expression.ComparisonExpression;
import org.apache.rocketmq.filter.expression.ConstantExpression;
import org.apache.rocketmq.filter.expression.Expression;
import org.apache.rocketmq.filter.expression.LogicExpression;
import org.apache.rocketmq.filter.expression.MQFilterException;
import org.apache.rocketmq.filter.expression.PropertyExpression;
import org.apache.rocketmq.filter.expression.UnaryExpression;
import org.apache.rocketmq.filter.util.LRUCache;

import java.io.StringReader;
import java.util.ArrayList;

/**
 * JMS Selector Parser generated by JavaCC
 *
 * Do not edit this .java file directly - it is autogenerated from SelectorParser.jj
 */
public class SelectorParser {

    private static final Cache<String, Object> PARSE_CACHE = CacheBuilder.newBuilder().maximumSize(100).build();
//    private static final String CONVERT_STRING_EXPRESSIONS_PREFIX = "convert_string_expressions:";

    public static BooleanExpression parse(String sql) throws MQFilterException {
//        sql = "("+sql+")";
        Object result = PARSE_CACHE.getIfPresent(sql);
        if (result instanceof MQFilterException) {
            throw (MQFilterException) result;
        } else if (result instanceof BooleanExpression) {
            return (BooleanExpression) result;
        } else {

//            boolean convertStringExpressions = false;
//            if( sql.startsWith(CONVERT_STRING_EXPRESSIONS_PREFIX)) {
//                convertStringExpressions = true;
//                sql = sql.substring(CONVERT_STRING_EXPRESSIONS_PREFIX.length());
//            }
//            if( convertStringExpressions ) {
//                ComparisonExpression.CONVERT_STRING_EXPRESSIONS.set(true);
//            }
            ComparisonExpression.CONVERT_STRING_EXPRESSIONS.set(true);
            try {

                BooleanExpression e = new SelectorParser(sql).parse();
                PARSE_CACHE.put(sql, e);
                return e;
            } catch (MQFilterException t) {
                PARSE_CACHE.put(sql, t);
                throw t;
            } finally {
                ComparisonExpression.CONVERT_STRING_EXPRESSIONS.remove();
//                if( convertStringExpressions ) {
//                    ComparisonExpression.CONVERT_STRING_EXPRESSIONS.remove();
//                }
            }
        }
    }

    public static void clearCache() {
        PARSE_CACHE.cleanUp();
    }

    private String sql;

    protected SelectorParser(String sql) {
        this(new StringReader(sql));
        this.sql = sql;
    }

    protected BooleanExpression parse() throws MQFilterException {
        try {
            return this.JmsSelector();
        }
        catch (Throwable e) {
            throw new MQFilterException("Invalid MessageSelector. ", e);
        }
    }

    private BooleanExpression asBooleanExpression(Expression value) throws ParseException  {
        if (value instanceof BooleanExpression) {
            return (BooleanExpression) value;
        }
        if (value instanceof PropertyExpression) {
            return UnaryExpression.createBooleanCast( value );
        }
        throw new ParseException("Expression will not result in a boolean value: " + value);
    }

}

PARSER_END(SelectorParser)

// ----------------------------------------------------------------------------
// Tokens
// ----------------------------------------------------------------------------

/* White Space */
SPECIAL_TOKEN :
{
  " " | "\t" | "\n" | "\r" | "\f"
}

/* Comments */
SKIP:
{
  <LINE_COMMENT: "--" (~["\n","\r"])* ("\n"|"\r"|"\r\n") >
}

SKIP:
{
  <BLOCK_COMMENT: "/*" (~["*"])* "*" ("*" | (~["*","/"] (~["*"])* "*"))* "/">
}

/* Reserved Words */
TOKEN [IGNORE_CASE] :
{
    <  NOT     : "NOT">
  | <  AND     : "AND">
  | <  OR      : "OR">
  | <  BETWEEN : "BETWEEN">
  | <  IN      : "IN">
  | <  TRUE    : "TRUE" >
  | <  FALSE   : "FALSE" >
  | <  NULL    : "NULL" >
  | <  IS      : "IS" >
}

/* Literals */
TOKEN [IGNORE_CASE] :

{

    < DECIMAL_LITERAL: "0" | ["1"-"9"] (["0"-"9"])* (["l","L"])? >
  | < FLOATING_POINT_LITERAL:
          (["0"-"9"])+ "." (["0"-"9"])* (<EXPONENT>)? // matches: 5.5 or 5. or 5.5E10 or 5.E10
        | "." (["0"-"9"])+ (<EXPONENT>)?              // matches: .5 or .5E10
        | (["0"-"9"])+ <EXPONENT>                     // matches: 5E10
    >
  | < #EXPONENT: "E" (["+","-"])? (["0"-"9"])+ >
  | < STRING_LITERAL: "'" ( ("''") | ~["'"] )*  "'" >
}

TOKEN [IGNORE_CASE] :
{
    < ID : ["a"-"z", "_", "$"] (["a"-"z","0"-"9","_", "$"])* >
}

// ----------------------------------------------------------------------------
// Grammer
// ----------------------------------------------------------------------------
BooleanExpression JmsSelector() :
{
    Expression left=null;
}
{
    (
        left = orExpression()
    )
    {
        return asBooleanExpression(left);
    }

}

Expression orExpression() :
{
    Expression left;
    Expression right;
}
{
    (
        left = andExpression()
        (
            <OR> right = andExpression()
            {
                left = LogicExpression.createOR(asBooleanExpression(left), asBooleanExpression(right));
            }
        )*
    )
    {
        return left;
    }

}


Expression andExpression() :
{
    Expression left;
    Expression right;
}
{
    (
        left = equalityExpression()
        (
            <AND> right = equalityExpression()
            {
                left = LogicExpression.createAND(asBooleanExpression(left), asBooleanExpression(right));
            }
        )*
    )
    {
        return left;
    }
}

Expression equalityExpression() :
{
    Expression left;
    Expression right;
}
{
    (
        left = comparisonExpression()
        (

            "=" right = comparisonExpression()
            {
                left = ComparisonExpression.createEqual(left, right);
            }
            |
            "<>" right = comparisonExpression()
            {
                left = ComparisonExpression.createNotEqual(left, right);
            }
            |
            LOOKAHEAD(2)
            <IS> <NULL>
            {
                left = ComparisonExpression.createIsNull(left);
            }
            |
            <IS> <NOT> <NULL>
            {
                left = ComparisonExpression.createIsNotNull(left);
            }
        )*
    )
    {
        return left;
    }
}

Expression comparisonExpression() :
{
    Expression left;
    Expression right;
    Expression low;
    Expression high;
    String t, u;
    boolean not;
    ArrayList list;
}
{
    (
        left = unaryExpr()
        (

                ">" right = unaryExpr()
                {
                    left = ComparisonExpression.createGreaterThan(left, right);
                }
            |
                ">=" right = unaryExpr()
                {
                    left = ComparisonExpression.createGreaterThanEqual(left, right);
                }
            |
                "<" right = unaryExpr()
                {
                    left = ComparisonExpression.createLessThan(left, right);
                }
            |
                "<=" right = unaryExpr()
                {
                    left = ComparisonExpression.createLessThanEqual(left, right);
                }
            |
                <BETWEEN> low = unaryExpr() <AND> high = unaryExpr()
                {
                    left = ComparisonExpression.createBetween(left, low, high);
                }
            |
                LOOKAHEAD(2)
                <NOT> <BETWEEN> low = unaryExpr() <AND> high = unaryExpr()
                {
                    left = ComparisonExpression.createNotBetween(left, low, high);
                }
            |
                <IN>
                "("
                    t = stringLitteral()
                    {
                        list = new ArrayList();
                        list.add( t );
                    }
                    (
                        ","
                        t = stringLitteral()
                        {
                            list.add( t );
                        }

                    )*
                ")"
                {
                   left = ComparisonExpression.createInFilter(left, list);
                }
            |
                LOOKAHEAD(2)
                <NOT> <IN>
                "("
                    t = stringLitteral()
                    {
                        list = new ArrayList();
                        list.add( t );
                    }
                    (
                        ","
                        t = stringLitteral()
                        {
                            list.add( t );
                        }

                    )*
                ")"
                {
                   left = ComparisonExpression.createNotInFilter(left, list);
                }

        )*
    )
    {
        return left;
    }
}

Expression unaryExpr() :
{
    String s=null;
    Expression left=null;
}
{
    (
        LOOKAHEAD( "+" unaryExpr() )
        "+" left=unaryExpr()
        |
        "-" left=unaryExpr()
        {
            left = UnaryExpression.createNegate(left);
        }
        |
        <NOT> left=unaryExpr()
        {
            left = UnaryExpression.createNOT( asBooleanExpression(left) );
        }
        |
        left = primaryExpr()
    )
    {
        return left;
    }

}

Expression primaryExpr() :
{
    Expression left=null;
}
{
    (
        left = literal()
        |
        left = variable()
        |
        "(" left = orExpression() ")"
    )
    {
        return left;
    }
}



ConstantExpression literal() :
{
    Token t;
    String s;
    ConstantExpression left=null;
}
{
    (
        (
            s = stringLitteral()
            {
                left = new ConstantExpression(s);
            }
        )
        |
        (
            t = <DECIMAL_LITERAL>
            {
                left = ConstantExpression.createFromDecimal(t.image);
            }
        )
        |
        (
            t = <FLOATING_POINT_LITERAL>
            {
                left = ConstantExpression.createFloat(t.image);
            }
        )
        |
        (
            <TRUE>
            {
                left = ConstantExpression.TRUE;
            }
        )
        |
        (
            <FALSE>
            {
                left = ConstantExpression.FALSE;
            }
        )
        |
        (
            <NULL>
            {
                left = ConstantExpression.NULL;
            }
        )
    )
    {
        return left;
    }
}

String stringLitteral() :
{
    Token t;
    StringBuffer rc = new StringBuffer();
    boolean first=true;
}
{
    t = <STRING_LITERAL>
    {
        // Decode the sting value.
        String image = t.image;
        for( int i=1; i < image.length()-1; i++ ) {
            char c = image.charAt(i);
            if( c == '\'' )
                i++;
            rc.append(c);
        }
        return rc.toString();
    }
}

PropertyExpression variable() :
{
    Token t;
    PropertyExpression left=null;
}
{
    (
        t = <ID>
        {
            left = new PropertyExpression(t.image);
        }
    )
    {
        return left;
    }
}
