MirkoBanchi
MirkoBanchi

Reputation: 2253

How to build a simple AST with pyparsing

I would extract an abstract syntax tree for a very simple recursive grammar, for example for a C function call statement. I have defined the grammar as:

name = Word(srange("[a-z]"), srange("[a-zA-Z0-9_]"))

func_args = Forward()
func_call = (name + "(" + func_args + ZeroOrMore(Word(",") + func_args) + ")").setParseAction(create_node)
func_args <<= (func_call | name)

res = func_call.parseString("func1(func2(v1,func3(v2,v3)))", True)

Parsing is ok but i can't figure out the best way to create the AST.

What i want for this example string is this AST:

func1
  - func2
      - v1
      - func3
          - v2
          - v3

Suppose i have a class tree. When the callback create_node is called for the first func3(v2, v3), i should create nodes for func3 with childs v2 and v3 etc etc until the outer statement is parsed. which is the best way? Thank you

Upvotes: 1

Views: 2100

Answers (1)

Pascal
Pascal

Reputation: 16941

While your example code throws up on me, did you try to name the tokens, similar to shown below, then use dump() on the parsing result?

...
func_call = (name + ...)('call')
func_args <<= (func_call | name)('func')
...
print(res.dump())

You'll have to adapt this code I'm afraid, but somewhere along those lines.

Upvotes: 1

Related Questions