Python PLY parsing : definition scope -


i'm using ply parse files containing nested blocks. typically :

a {     b {      }     c {         d {          }     }     } 

i using simple grammar :

def p_nodes(p):     '''     nodes : node nodes           | node     '''     # ??  def p_node(p):     '''     node : identifier open_curly_brace node_çontent close_curly_brace     '''     p[0] = node(p[3])#fixme?  def p_node_content(p):     '''     node_content : nodes                  |     '''     if len(p) > 1:         p[0] = p[1]     else         p[0] = none 

i know able access 'parent' node in parser. in other terms how can build ast can retrieve in example d child of c child of a since have visibility parent rule in parser.

what should put in p_nodes , p_node valid ast can built ? thanks.

we have need node class, presume like:

class node:     def __init__(self, children):         self.children = children         self.type = none 

then parser that:

def p_nodes(p):     '''     nodes : node nodes           | node     '''     if len(p) > 2:         p[0] = [p[1]] + p[2]     else         p[0] = [p[1]]   def p_node(p):     '''     node : identifier open_curly_brace node_content close_curly_brace     '''     p[0] = node(p[3])  def p_node_content(p):     '''     node_content : nodes                  |     '''     if len(p) > 1:         p[0] = p[1]     else         p[0] = none 

then have real ast, each node containing reference childs.

eventually, if want node have reference parent, have iterate on ast root , set attribute on children, same on it's children...

to that, change node class this:

class node:     def __init__(self, children):         self.children = children         self.parent = none      def set_parent(self, parent):         self.parent = parent 

and run similar function this:

def set_parent_to_ast(root_node):     node in root_node.children:         node.set_parent(root_node)         set_parent_to_ast(node) 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -