Parsing python with PLY

796 Views Asked by At

I'm trying to write a python parser, and in my opiniion it could parse an "if statement" but it doesn't. It shows me a "syntax error" message.

Can someone tell me what I'm doing wrong?

Thanks in advance.

The code is here: https://github.com/narke/py2neko


I modified the input string like this:

s = '''if 5:
    print 10
else:
    print 20 \n'''
check_syntax(s)

and the output is:

Syntax error at '5'
atom: 10
factor None
None
cmp: None None
atom: 20
factor None
None
cmp: None None 
simple_stmt: None
1

There are 1 best solutions below

0
On

From your code:

s = "if 5:\n"
check_syntax(s)

if 5:\n is not valid syntax because it is not a complete if statement. You need to provide a suite (code to execute) if the expression is True. For example:

>>> if 5:
... 
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block

>>> compile('if 5:\n', '<string>', 'exec')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    if 5:
        ^
SyntaxError: unexpected EOF while parsing

>>> compile('if 5:\n  print 5', '<string>', 'exec')
<code object <module> at 0xb7f60530, file "<string>", line 2>