praseedpai / CD_Learn

7 stars 5 forks source link

Violation of the of Parser Grammar #1

Open nithinivi opened 2 years ago

nithinivi commented 2 years ago

https://github.com/praseedpai/CD_Learn/blob/3664a772adc74b3c2a20d32654c67b0bbee20628/Chapter07/SlangStep2/parser.h#L58

Exp* parser::RDParser::Term() {
    Token lToken;
    Exp* retValue = Factor();

    while (currentToken == TOK_MUL || currentToken == TOK_DIV) {
        lToken = currentToken;
        currentToken = GetToken();
        Exp* right = Factor();
        retValue = new BinaryExp(retValue, right, lToken == TOK_MUL ? OP_MUL : OP_DIV);
    }

    return retValue;
}

Shouldn't it be

    Exp* right = Term();

?

sarath-soman commented 2 years ago

It should be, in a different universe with different laws of Math 😄

nithinivi commented 2 years ago

6/2 * 3 = 1 Thanks for the insight :smile:

sarath-soman commented 2 years ago

To make the context more clear - when you write/recreate the expression evaluator in this repository, consider the following test cases (in no way comprehensive) to avoid operator precedence bugs (Will be introduced if you call Term() instead of Factor() in the while loop).

https://github.com/sarath-soman/SlangCompiler/blob/master/src/test/java/com/slang/parser/ParserTest.java - testParseExpression()