Esempio n. 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
Esempio n. 2
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
Esempio n. 3
0
def test_code_generation(file_name, code_orig, interactive=False):
    print(f"{file_name}: ", end='')

    try:
        node_orig = ast.parse(code_orig)
    except SyntaxError:
        print("\033[1;34mSkipping\033[0m")
        return True

    code_gen = ''
    node_gen = None

    try:
        code_gen = visitors.to_source(node_orig)
        node_gen = ast.parse(code_gen)
        assert ast.dump(node_orig) == ast.dump(node_gen)
    except (SyntaxError, AssertionError, KeyError) as e:
        print("\033[1;31m%s\033[0m \033[31m[%s]\033[0m" %
              (type(e).__name__, str(e)))
        if interactive:
            enter_interactive(code_orig, node_orig, code_gen, node_gen)

        return False
    else:
        print("\033[1;32mOK\033[0m")
        return True
Esempio n. 4
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)
Esempio n. 5
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)
Esempio n. 6
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
Esempio n. 7
0
import ast
import optimizer
from astmonkey import visitors

file = open("test.py").read()
tree = ast.parse(file)
optimisation = optimizer.NodeOptimizationTransformer()
tree = optimisation.visit(tree)
print(visitors.to_source(tree))
Esempio n. 8
0
 def assert_code_equal(self, code):
     node = ast.parse(code)
     generated = visitors.to_source(node, indent_with='\t')
     self.assertEqual(code, generated)
Esempio n. 9
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)
import ast
from astmonkey import visitors

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

assert (code == generated_code)
Esempio n. 12
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
Esempio n. 13
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
Esempio n. 14
0
 def test_codegen_roundtrip(self, source):
     node = ast.parse(source)
     generated = visitors.to_source(node)
     assert source == generated
Esempio n. 15
0
 def assert_code_equal(self, code):
     node = ast.parse(code)
     generated = visitors.to_source(node, indent_with='\t')
     self.assertEqual(code, generated)
Esempio n. 16
0
                        print("Zero division error")

        # Power
        if isinstance(node.op, ast.Pow):
            if isinstance(node.left, ast.Constant) and isinstance(
                    node.right, ast.Constant):
                if isinstance(node.right.value, (int, float)) and isinstance(
                        node.left.value, (int, float)):
                    return ast.Constant(
                        value=node.left.value**node.right.value)

        return node


print("enter your line")
code = input()

tree = ast.parse(code)
new_tree = ast.fix_missing_locations(Optimizer().visit(tree))
generated_code = visitors.to_source(new_tree)
print(generated_code)
"""
Написана оптимизация для:
1) случая сложения констант. Рассмотрено сложение с 0.
2) случая вычитания констант и рассмотрен случай ноля
3) умножения констант и 0
4) деления и случаи с 0
5) взятия остатка
6) возведения в степень
"""