0

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.

sparrow
  • 41
  • 1
  • 8
  • 1
    You use it on this line `grammar = Enum(word,IfDefinition),";",endl`. Try moving the `IfDefinition` class above the `Instruction` class definition, and define `block` before `IfDefinition` – GP89 Nov 12 '14 at 10:45
  • Hello, GP89! I have tried it, but the error became "NameError: name 'Instruction' is not defined". It seems I didn't use pypeg2 correctly, and I can't figure out how. – sparrow Nov 12 '14 at 10:51

1 Answers1

1

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
GP89
  • 6,600
  • 4
  • 36
  • 64