1# indentedGrammarExample.py
2#
3# Copyright (c) 2006,2016  Paul McGuire
4#
5# A sample of a pyparsing grammar using indentation for
6# grouping (like Python does).
7#
8# Updated to use indentedBlock helper method.
9#
10
11from pyparsing import *
12
13
14data = """\
15def A(z):
16  A1
17  B = 100
18  G = A2
19  A2
20  A3
21B
22def BB(a,b,c):
23  BB1
24  def BBA():
25    bba1
26    bba2
27    bba3
28C
29D
30def spam(x,y):
31     def eggs(z):
32         pass
33"""
34
35
36stmt = Forward()
37suite = IndentedBlock(stmt)
38
39identifier = Word(alphas, alphanums)
40funcDecl = (
41    "def" + identifier + Group("(" + Optional(delimitedList(identifier)) + ")") + ":"
42)
43funcDef = Group(funcDecl + suite)
44
45rvalue = Forward()
46funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
47rvalue << (funcCall | identifier | Word(nums))
48assignment = Group(identifier + "=" + rvalue)
49stmt << (funcDef | assignment | identifier)
50
51module_body = OneOrMore(stmt)
52
53print(data)
54parseTree = module_body.parseString(data)
55parseTree.pprint()
56