1
|
|
|
import ast |
2
|
|
|
from py14.context import add_variable_context, add_list_calls |
3
|
|
|
from py14.scope import add_scope_context |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
def parse(*args): |
7
|
|
|
source = ast.parse("\n".join(args)) |
8
|
|
|
add_scope_context(source) |
9
|
|
|
add_variable_context(source) |
10
|
|
|
return source |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
class TestListCallTransformer: |
14
|
|
|
def test_call_added(self): |
15
|
|
|
source = parse( |
16
|
|
|
"results = []", |
17
|
|
|
"results.append(x)", |
18
|
|
|
) |
19
|
|
|
add_list_calls(source) |
20
|
|
|
assert len(source.scopes[-1].vars[0].calls) == 1 |
21
|
|
|
|
22
|
|
|
|
23
|
|
|
class TestVariableTranformer: |
24
|
|
|
def test_vars_of_if(self): |
25
|
|
|
source = parse( |
26
|
|
|
"x = 5", |
27
|
|
|
"if True:", |
28
|
|
|
" y = 10", |
29
|
|
|
" x *= y", |
30
|
|
|
) |
31
|
|
|
assert len(source.vars) == 1 |
32
|
|
|
assert len(source.body[1].body_vars) == 1 |
33
|
|
|
|
34
|
|
|
def test_vars_of_else(self): |
35
|
|
|
source = parse( |
36
|
|
|
"x = 5", |
37
|
|
|
"if True:", |
38
|
|
|
" y = 10", |
39
|
|
|
" x *= y", |
40
|
|
|
"else:", |
41
|
|
|
" z = 3", |
42
|
|
|
" x *= z", |
43
|
|
|
) |
44
|
|
|
assert len(source.vars) == 1 |
45
|
|
|
assert len(source.body[1].body_vars) == 1 |
46
|
|
|
assert len(source.body[1].orelse_vars) == 1 |
47
|
|
|
|
48
|
|
|
def test_local_vars_of_function(self): |
49
|
|
|
source = parse( |
50
|
|
|
"def foo():", |
51
|
|
|
" results = []", |
52
|
|
|
" x = 3", |
53
|
|
|
" z = x", |
54
|
|
|
" results.append(x)", |
55
|
|
|
" return results", |
56
|
|
|
) |
57
|
|
|
assert len(source.vars) == 0 |
58
|
|
|
assert len(source.body[0].vars) == 3 |
59
|
|
|
|
60
|
|
|
def test_local_vars_of_function_with_args(self): |
61
|
|
|
source = parse( |
62
|
|
|
"def foo(x, y):", |
63
|
|
|
" return x + y", |
64
|
|
|
) |
65
|
|
|
assert len(source.vars) == 0 |
66
|
|
|
assert len(source.body[0].vars) == 2 |
67
|
|
|
|
68
|
|
|
def test_subscripts_are_ignored(self): |
69
|
|
|
source = parse("x[0] = 3") |
70
|
|
|
assert len(source.vars) == 0 |
71
|
|
|
|
72
|
|
|
def test_vars_from_loop(self): |
73
|
|
|
source = parse( |
74
|
|
|
"newlist = []", |
75
|
|
|
"for x in list:", |
76
|
|
|
" newlist.append(x)", |
77
|
|
|
) |
78
|
|
|
assert len(source.vars) == 1 |
79
|
|
|
|
80
|
|
|
def test_global_vars_of_module(self): |
81
|
|
|
source = parse( |
82
|
|
|
"x = 3", |
83
|
|
|
"def foo():", |
84
|
|
|
" results = []", |
85
|
|
|
" results.append(x)", |
86
|
|
|
" return results", |
87
|
|
|
) |
88
|
|
|
assert len(source.vars) == 1 |
89
|
|
|
assert len(source.body[1].vars) == 1 |
90
|
|
|
|
91
|
|
|
def test_vars_inside_loop(self): |
92
|
|
|
source = parse( |
93
|
|
|
"def foo():", |
94
|
|
|
" results = []", |
95
|
|
|
" for x in range(0, 10):", |
96
|
|
|
" results.append(x)", |
97
|
|
|
" return results", |
98
|
|
|
) |
99
|
|
|
assert len(source.vars) == 0 |
100
|
|
|
assert len(source.body[0].body[1].vars) == 1 |
101
|
|
|
|