Meet "name undefined " error while using pypeg2

155 views Asked by At

I want to use pypeg2 to parse c# code. So I have to define C# grammar first. I know little about parsing expression grammar(PEG), and assume that it has a lot in common with Backus-Naur form(BNF). Recursion is allowed in BNF, so I define my grammar like this:

from __future__ import unicode_literals,print_function
from pypeg2 import *


class Instruction(list):
    grammar = Enum(word,IfDefinition),";",endl

class IfDefinition(list):
    grammar = "if",block,"else",block

block = "{",maybe_some(Instruction),"}"

When I tried to execute the code, I met the error “NameError: name 'IfDefinition' is not defined”. If I don't use "IfDefinition" before defining it, I can't construct multiple levels of nested "IfDefinition". I want to know how to define the if expression's grammar using pypeg2.

1

There are 1 answers

0
GP89 On

Looks like you have a cycle here, (Instruction references IfDefinition, IfDefinition references block and block references Instruction).

I think you probably need to rethink the model your using, or a possible, slightly messy solution

class Instruction(list):
    pass

block = "{",maybe_some(Instruction),"}" 

class IfDefinition(list):
    grammar = "if",block,"else",block

Instruction.grammar = Enum(word,IfDefinition),";",endl