def x_to_z_gt(ast: AST) -> Optional[LiteralOrAST]: """Convert 'x' identifiers in greater than operations to 'z'.""" if isinstance(ast, PythonComparisonOperator): lhs, *rest = ast.child_slot("CHILDREN") operator, *_ = ast.child_slot("OPERATORS") if isinstance(operator, PythonGreaterThan) and lhs.source_text == "x": return AST.copy(ast, children=["z", *rest])
def delete_print_statements(ast: AST) -> Optional[LiteralOrAST]: """Delete all print statements from the children of AST.""" if isinstance(ast, RootAST) or isinstance(ast, CompoundAST): # Build a list of new children under the AST, eliding print statements. new_children = [ c for c in ast.children if not is_print_statement(c) ] # Special case; if no children remain, add a "pass" statement nop to # avoid syntax errors. new_children = new_children if new_children else ["pass\n"] return AST.copy(ast, children=new_children)
def test_copy_with_kwargs(self): copy = AST.copy( self.root, left=AST.from_string("y", ASTLanguage.Python, deepest=True), ) self.assertEqual(copy.source_text, "y + 1") self.assertNotEqual(copy.oid, self.root.oid) copy = AST.copy(self.root, left=0.5) self.assertEqual(copy.source_text, "0.5 + 1") self.assertNotEqual(copy.oid, self.root.oid) copy = AST.copy(self.root, left=2) self.assertEqual(copy.source_text, "2 + 1") self.assertNotEqual(copy.oid, self.root.oid) copy = AST.copy(self.root, left='"hi"') self.assertEqual(copy.source_text, '"hi" + 1') self.assertNotEqual(copy.oid, self.root.oid) copy = AST.copy(self.root, left="y") self.assertEqual(copy.source_text, "y + 1") self.assertNotEqual(copy.oid, self.root.oid)
def test_copy_no_kwargs(self): copy = AST.copy(self.root) self.assertEqual(1, self.root.refcount()) self.assertEqual(1, copy.refcount()) self.assertEqual(copy.source_text, self.root.source_text) self.assertNotEqual(copy.oid, self.root.oid)