Example #1
0
 def test_fix_linen_umbers(self):
     """Check if an AST with wrong lineno attribute is corrected in the process."""
     node = ast.parse('x = 1' + self.EOL + 'y = 2')
     # set both line numbers to 1
     node.body[1].lineno = 1
     visitors.to_source(node)
     assert node.body[1].lineno == 2
Example #2
0
 def test_codegen_semantic_preservation(self, source):
     """Check if converting code into AST, converting it back to code
     and converting it into an AST again yields the same AST.
     """
     node = ast.parse(source)
     generated = visitors.to_source(node)
     node_from_generated = ast.parse(generated)
     assert ast.dump(node) == ast.dump(node_from_generated)
Example #3
0
def get_template(filename):
    cached = cache.get(filename)

    if not cached:

        with open(filename) as fp:
            source = fp.read()

        if sys.version_info[0] < 3:
            source = source.decode("utf-8")

        tree = parse(source)
        compiled = compile_tree(tree)
        module = ast.Module(compiled)
        optimized = optimize(module)

        template_source = ""
        try:
            from astmonkey import visitors
            template_source = visitors.to_source(optimized)
        except ImportError:
            try:
                import codegen
                template_source = codegen.to_source(optimized)
            except ImportError:
                template_source = ""

        code = compile(ast.fix_missing_locations(optimized), filename, "exec")

        globs = {
            ESCAPE: escape,
            QUOTEATTR: quoteattr,
            TO_STRING: soft_unicode,
            WRITE_ATTRS: write_attrs
        }        

        scope = {}
        exec_(code, globs, scope)
        main_fun = scope[MAIN]
        concat = "".join

        def render(**kwargs):
            output = []
            context = {WRITE: output.append, WRITE_MULTI: output.extend}
            context.update(kwargs)
            main_fun(**context)
            return concat(output)

        setattr(render, "template_source", template_source)

        cached = render
        cache[filename] = cached

    return cached
Example #4
0
def ast_to_source_file(ast_node, file_path):
    with open(file_path, 'w') as source_file:
        source_code = visitors.to_source(ast_node)
        source_file.write(source_code)
import ast
from astmonkey import visitors

code = 'x = y + 1'
node = ast.parse(code)
generated_code = visitors.to_source(node)

assert(code == generated_code)
Example #6
0
 def test_codegen_roundtrip(self, source):
     """Check if converting code into AST and converting it back to code yields the same code."""
     node = ast.parse(source)
     generated = visitors.to_source(node)
     assert source == generated
Example #7
0
 def assert_code_equal(self, code):
     node = ast.parse(code)
     generated = visitors.to_source(node, indent_with='\t')
     self.assertEqual(code, generated)