funcj icon indicating copy to clipboard operation
funcj copied to clipboard

Need help with grammar definiton.

Open kiransunkari opened this issue 8 months ago • 0 comments

Hi Jon, I've been working on defining a grammar for parsing expressions from strings. Currently, my grammar is set up to handle expressions like a == 2, where a is an identifier, == is an operator, and 2 is a value. I've defined literals for identifiers and values, including strings, numbers, true, and false, along with comparison and logical operators. My grammar properly handles expressions involving multiple sub-expressions: a == 2 && b == false as well. Now, I'm looking to extend my grammar to support expressions with array fields, like a[value == 2]. which means under array field a, value == 2. To handle array expression I extended the grammar like this.

      final Parser<Chr, Either<Value, Expr>> valueOrExpression =  Parser.choice(
         numberValue.map(Either::left),
         stringValue.map(Either::left),
         trueValue.map(Either::left),
         falseValue.map(Either::left),
         expr.map(Either::right)
      );
      // Define a parser for handling both comparison and array match expressions
   final Parser<Chr, Expr> cmpOrArrayExpr =
         identifier.andL(whitespace.optional())
            .and(Parser.choice(arrayOpenOp, comparableOp.map(CmpOp::getCode)))
            .andL(whitespace.optional())
            .and(valueOrExpression)
            .andL(whitespace.optional())
            .and(arrayCloseOp.optional())
            .map((ident, symbolAfterIdentifier, expression, closeOp) -> {
               // If the expression is an array match expression, return an ArrayMatchExpr instance
               // eg: a["type" == 2]
               if (symbolAfterIdentifier.equals("["))
               {
                  return new Array(ident, CmpOp.EQ, expression);
               }
               else
               {
                  return new Cmp(ident, CmpOp.fromCode(symbolAfterIdentifier), expression.left());
               }
            });

For expressions like "a[value > 2 && b == 5]", my grammar rules can convert the string to the expression tree. However, for filter expressions such as "a[type == 2]", it's attempting to convert "type" to a boolean value. I understand that in the valueOrExpression, I defined trueValue before the expression, causing it to try and convert to a boolean and fail.

I'm currently stuck on this issue and would greatly appreciate your help on this.

kiransunkari avatar Jun 20 '24 10:06 kiransunkari