def __setattr__(self, name, value): """Set attribute and preserve parent pointers.""" if name != "parent": for child in flatten(value): if isinstance(child, CtreeNode): child.parent = self super(CtreeNode, self).__setattr__(name, value)
def generic_visit(self, node): for fieldname, value in ast.iter_fields(node): for child in flatten(value): if isinstance(child, CtreeNode): setattr(child, 'parent', node) self.visit(child) return node
def _genblock(self, forest, insert_curly_brackets=True, increase_indent=True): """generate block of code adding semi colons as necessary""" if increase_indent: self._indent += 1 body = "" for tree in flatten(forest): semicolon_opt = ";" if tree._requires_semicolon() else "" body += self._tab() + tree.codegen(self._indent) + semicolon_opt + "\n" if increase_indent: self._indent -= 1 if insert_curly_brackets: return "{\n%s%s}" % (body, self._tab()) else: return "\n%s" % body
def _resolve(self, value): """ Generated the string for the given child, which might be a list of lists (...of lists...) of nodes. For a single node, don't append a semicolon, otherwise append semicolons and newlines to each statement if they require it. """ children = list(flatten(value)) if len(children) == 1: return children[0].codegen() else: body = "" for child in children: semicolon_opt = ";" if child._requires_semicolon() else "" body += self._tab() + child.codegen() + semicolon_opt + "\n" return body
def _genblock(self, forest, insert_curly_brackets=True, increase_indent=True): """generate block of code adding semi colons as necessary""" if increase_indent: self._indent += 1 body = "" for tree in flatten(forest): semicolon_opt = ";" if tree._requires_semicolon() else "" body += self._tab() + tree.codegen( self._indent) + semicolon_opt + "\n" if increase_indent: self._indent -= 1 if insert_curly_brackets: return "{\n%s%s}" % (body, self._tab()) else: return "\n%s" % body
def __setattr__(self, name, val): from ctree.nodes import CtreeNode if name == "_children": # set parent pointers in child_dict assert isinstance(val, dict) super(TemplateNode, self).__setattr__(name, val) for name, value in val.items(): for child in flatten(value): child.parent = self elif hasattr(self, "_children") and name in self._children: # insert into _children dictionary and set parent pointers self._children[name] = val if isinstance(val, CtreeNode): val.parent = self else: # do standard attribute resolution super(TemplateNode, self).__setattr__(name, val)
def _check(self, nested, flat): actual, expected = list(flatten(nested)), flat self.assertListEqual(actual, expected)
def generic_visit(self, node): for _, value in ast.iter_fields(node): for child in flatten(value): if isinstance(child, ast.AST): self._check(child, node) self.visit(child)
def test_flatten(self): l = [1, 2, 3, [4, 5, [6, 7], [8, 9]]] self.assertEqual(list(flatten(l)), range(1, 10))
def test_flatten(self): l = [1, 2, 3, [4, 5, [6, 7], [8, 9]]] self.assertEqual(list(flatten(l)), list(range(1, 10)))