Programming is Fun
Programming is Fun

Reputation: 99

PLY Parsing error for function declaration

I trying to parse the following source language in python

print("hello")

What i am doing in PLY is the following

import ply
import yacc

tokens =('LPAREN','RPAREN','STRING','PRINT')
reserved ={
('print': 'PRINT')
}

t_LPAREN ='\('
t_RPREN = '\)'
t_STRING = r'\".*?\"'

t_ignore = " \t"

def p_print(p):
  'statement : print LPAREN STRING RPAREN'
  print(p[3])
def p_error(p):
  print("Syntax error at %s"%p.value)
lex.lex()
yacc.yacc()
s ='print("Hello")'
yacc.parse(s)

I was expecting that it will print Hello. But i am getting the error

Syntax err at 'print'

Anyone can help me what mistake i am doing? Thanks

Upvotes: 0

Views: 1633

Answers (1)

cs95
cs95

Reputation: 402503

Here's a list of everything that was off with your code:

  1. Import statements. You've missed importing the modules properly. I'm not sure how you got as far as you did, but the right way to import these modules is with

    import ply.lex as lex
    import ply.yacc as yacc
    
  2. the PRINT token is specified, but no rule defined for it. Define the rule like this:

    t_PRINT = r'print'
    
  3. Your grammar rule for the print statement should specify the token name, not what the token matches too.

    def p_print(p):
      r'statement : PRINT LPAREN STRING RPAREN'
      ...
    
  4. Removed the reserved structure, it seemed to serve no purpose.

After fixing these errors, we have:

import ply.lex as lex
import ply.yacc as yacc

tokens =('LPAREN','RPAREN','STRING','PRINT')

t_LPAREN ='\('
t_RPAREN = '\)'
t_STRING = r'\".*?\"'
t_PRINT = r'print'
t_ignore = " \t"

def p_print(p):
  'statement : PRINT LPAREN STRING RPAREN'
  print(p[3])

def p_error(p):
  print("Syntax error at %s"%p.value)

lex.lex()
yacc.yacc()
s ='print("Hello")'
yacc.parse(s)

Output:

WARNING: No t_error rule is defined
"Hello"

It's okay for now, but do define a t_error rule for larger programs.

Upvotes: 1

Related Questions