Search code examples
pythonparsinglexerply

Ply example calculator multiple expressions


I've been trying out the Ply example calculator from Github.

When I run the calculator, it runs inside of a REPL. How would I use Ply to enable multiple expressions to be evaluated, one after the other.

For example, if I enter 3+4 the REPL does this:

calc > 3+4
7
calc >

If I enter 4+3 6+2 the REPL does this:

calc > 4+3 6+2
Syntax error at '6'
2
calc >  

How would I modify the example calculator to enable the REPL to do this:

calc > 4+3 6+2
7
8
calc > 

Do I need to modify the grammar, the parser or both? I've tried modifying the grammar to make it left recursive but it doesn't seem to work.


Solution

  • The sample calculator's grammar allows expressions like - 42 (or -(4*8)+7). If such an expression were the second expression on a line, it would create an ambiguity. Is:

    calc > 4 * 3 -(4*8)+7
    

    one expression or two?

    One way to make the grammar unambiguous would be to allow multiple expressions on a line separated with a comma. You could do that by just adding '.' to the list of literal tokens, and placing the function

    def p_line(p):
        '''line : statement
                | line ',' statement'''
        pass
    

    as the first parser function (i.e., just before p_statement_assign.

    With that change:

    $ python calc.py
    Generating LALR tables
    calc > 2+3
    5
    calc > 2+3,4+6
    5
    10
    calc > 2,3
    2
    3
    calc > a=2,a+7
    9