textX / Arpeggio

Parser interpreter based on PEG grammars written in Python http://textx.github.io/Arpeggio/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

indexing children

ImpatientHippo opened this issue · comments

The documentation (http://textx.github.io/Arpeggio/stable/semantics/) says that you can index children by rule name.
baz_created = children['baz']
This does not seem to be true as I get the following error:
TypeError: list indices must be integers or slices, not str

Do you do that in visit_... method? Can you make a minimal test that fails?

Affirmative. Here is a (non)working example.

#!/usr/bin/env python3
from arpeggio import *
from arpeggio import RegExMatch as _

def id(): return _(r"[a-zA-Z.-]+")
def opener(): return "<",id,">"
def closer(): return "</",id,">"
def element(): return opener,pcdata,ZeroOrMore(element,pcdata),closer
def pcdata(): return _(r"[^<>&]*")
def document(): return element,EOF

parser = ParserPython(document)

tree = parser.parse('<text><h>Test</h><p>End</p></text>')

class XmlVisitor(PTNodeVisitor):

  def visit_element(self,node,children):
    print( children['closer'] )

visit_parse_tree(tree,XmlVisitor())

The error is:

Traceback (most recent call last):
  File "./visitor.py", line 22, in <module>
    visit_parse_tree(tree,XmlVisitor())
  File "/usr/local/lib/python3.5/dist-packages/arpeggio/__init__.py", line 1238, in visit_parse_tree
    result = parse_tree.visit(visitor)
  File "/usr/local/lib/python3.5/dist-packages/arpeggio/__init__.py", line 987, in visit
    child = node.visit(visitor)
  File "/usr/local/lib/python3.5/dist-packages/arpeggio/__init__.py", line 987, in visit
    child = node.visit(visitor)
  File "/usr/local/lib/python3.5/dist-packages/arpeggio/__init__.py", line 995, in visit
    result = getattr(visitor, visit_name)(self, children)
  File "./visitor.py", line 20, in visit_element
    print( children['closer'] )
TypeError: list indices must be integers or slices, not str

Thanks. The bug was in the docs. To access the children for a specific rule use attribute access:

  def visit_element(self, node, children):
    print(children.closer)

Note that the html documentation on the gh_pages (and hence on the documentaiton website) still contains the incorrect information.

@ajtribick Thanks for the heads up. Docs is rebuilt as a part of 1.9.1 release.