dabeaz / sly

Sly Lex Yacc
Other
816 stars 107 forks source link

How do I determine the nestedness level #63

Closed mzelyony closed 3 years ago

mzelyony commented 3 years ago

I have a working lexer and semi-working parser. My data contains name=value pairs , and value can be an object in itself. I am trying to determine how deep in the tree I am when my method for the nested object is being called. I tried to add indentLevel as the member of Parser, but that fails. I understand why - it is because the nested elements are reduced before the object itself, but I do not see a proper way to do it. Please advice. See code snippet below.

   tokens = {ELEM_NAME, ELEM_VALUE, 
              LBRACKET, RBRACKET}

.......

    @_('LBRACKET elements RBRACKET')
    def aggregate(self, p):
        return p.elements

    @_('element elements')
    def elements(self, p):
        return p.element + "\n" + p.elements

    @_('element')
    def elements(self, p):
        return p.element

    @_('ELEM_NAME LBRACKET elements RBRACKET')
    def element(self, p):
        self.d_identLevel += 1
        retStr = p.ELEM_NAME + "\n" + p.elements
        self.d_identLevel -= 1
        return retStr

    @_('ELEM_NAME ELEM_VALUE')
    def element(self, p):
        return self.ident() + p.ELEM_NAME + "=" +p.ELEM_VALUE
mzelyony commented 3 years ago

Solved this after RTFM properly. Adding an embedded action after LBRACKET worked