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.
Looks like you have a cycle here, (
Instruction
referencesIfDefinition
,IfDefinition
referencesblock
andblock
referencesInstruction
).I think you probably need to rethink the model your using, or a possible, slightly messy solution