forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pprinter.py
307 lines (249 loc) · 7.98 KB
/
pprinter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
from output import TypeOutputVisitor
from nodes import (
Node, VarDef, TypeDef, FuncDef, MypyFile, CoerceExpr, TypeExpr
)
from visitor import NodeVisitor
from mtypes import Void, TypeVisitor, Callable, Instance, Type, UnboundType
from maptypevar import num_slots
from transutil import tvar_arg_name
import coerce
class PrettyPrintVisitor(NodeVisitor):
"""Convert transformed parse trees into formatted source code.
Use automatic formatting (i.e. omit original formatting).
"""
void __init__(self):
super().__init__()
self.result = <str> []
self.indent = 0
str output(self):
return ''.join(self.result)
#
# Definitions
#
void visit_mypy_file(self, MypyFile file):
for d in file.defs:
d.accept(self)
void visit_type_def(self, TypeDef tdef):
self.string('class ')
self.string(tdef.name)
if tdef.base_types:
b = <str> []
for bt in tdef.base_types:
if not bt:
continue
elif isinstance(bt, UnboundType):
b.append(((UnboundType)bt).name)
elif ((Instance)bt).type.full_name() != 'builtins.object':
typestr = bt.accept(TypeErasedPrettyPrintVisitor())
b.append(typestr)
if b:
self.string('({})'.format(', '.join(b)))
self.string(':\n')
for d in tdef.defs.body:
d.accept(self)
self.dedent()
void visit_func_def(self, FuncDef fdef):
# FIX varargs, default args, keyword args etc.
ftyp = (Callable)fdef.type
self.type(ftyp.ret_type)
self.string(' ')
self.string(fdef.name())
self.string('(')
for i in range(len(fdef.args)):
a = fdef.args[i]
if i < len(ftyp.arg_types):
self.type(ftyp.arg_types[i])
self.string(' ')
else:
self.string('xxx ')
self.string(a.name())
if i < len(fdef.args) - 1:
self.string(', ')
self.string(')')
fdef.body.accept(self)
void visit_var_def(self, VarDef vdef):
if vdef.items[0][0].name() != '__name__':
self.type(vdef.items[0][1])
self.string(' ')
self.string(vdef.items[0][0].name())
if vdef.init:
self.string(' = ')
self.node(vdef.init)
self.string('\n')
#
# Statements
#
def visit_block(self, b):
self.string(':\n')
for s in b.body:
s.accept(self)
self.dedent()
def visit_pass_stmt(self, o):
self.string('pass\n')
def visit_return_stmt(self, o):
self.string('return ')
if o.expr:
self.node(o.expr)
self.string('\n')
def visit_expression_stmt(self, o):
self.node(o.expr)
self.string('\n')
def visit_assignment_stmt(self, o):
self.node(o.lvalues[0]) # FIX multiple lvalues
self.string(' = ')
self.node(o.rvalue)
self.string('\n')
def visit_if_stmt(self, o):
self.string('if ')
self.node(o.expr[0])
self.node(o.body[0])
for e, b in zip(o.expr[1:], o.body[1:]):
self.string('elif ')
self.node(e)
self.node(b)
if o.else_body:
self.string('else')
self.node(o.else_body)
def visit_while_stmt(self, o):
self.string('while ')
self.node(o.expr)
self.node(o.body)
if o.else_body:
self.string('else')
self.node(o.else_body)
#
# Expressions
#
def visit_call_expr(self, o):
self.node(o.callee)
self.string('(')
self.omit_next_space = True
for i in range(len(o.args)):
self.node(o.args[i])
if i < len(o.args) - 1:
self.string(', ')
self.string(')')
def visit_member_expr(self, o):
self.node(o.expr)
self.string('.' + o.name)
if o.direct:
self.string('!')
def visit_name_expr(self, o):
self.string(o.name)
void visit_coerce_expr(self, CoerceExpr o):
self.string('{')
self.full_type(o.target_type)
if coerce.is_special_primitive(o.source_type):
self.string(' <= ')
self.type(o.source_type)
self.string(' ')
self.node(o.expr)
self.string('}')
void visit_type_expr(self, TypeExpr o):
# Type expressions are only generated during transformation, so we must
# use automatic formatting.
self.string('<')
self.full_type(o.type)
self.string('>')
def visit_index_expr(self, o):
self.node(o.base)
self.string('[')
self.node(o.index)
self.string(']')
def visit_int_expr(self, o):
self.string(str(o.value))
def visit_str_expr(self, o):
self.string(repr(o.value))
def visit_op_expr(self, o):
self.node(o.left)
self.string(' %s ' % o.op)
self.node(o.right)
def visit_unary_expr(self, o):
self.string(o.op)
if o.op == 'not':
self.string(' ')
self.node(o.expr)
def visit_paren_expr(self, o):
self.string('(')
self.node(o.expr)
self.string(')')
def visit_super_expr(self, o):
self.string('super().')
self.string(o.name)
def visit_cast_expr(self, o):
self.string('(')
self.type(o.type)
self.string(')')
self.node(o.expr)
def visit_type_application(self, o):
# Type arguments are erased in transformation.
self.node(o.expr)
#
# Helpers
#
void string(self, str s):
if not s:
return
if self.last_output_char() == '\n':
self.result.append(' ' * self.indent)
self.result.append(s)
if s.endswith(':\n'):
self.indent += 4
void dedent(self):
self.indent -= 4
void node(self, Node n):
n.accept(self)
str last_output_char(self):
if self.result:
return self.result[-1][-1]
return ''
def type(self, t):
"""Pretty-print a type with erased type arguments."""
if t:
v = TypeErasedPrettyPrintVisitor()
self.string(t.accept(v))
def full_type(self, t):
"""Pretty-print a type, includingn type arguments."""
if t:
v = TypePrettyPrintVisitor()
self.string(t.accept(v))
class TypeErasedPrettyPrintVisitor(TypeVisitor<str>):
"""Pretty-print types.
Omit type variables (e.g. C instead of C<int>).
Note that the translation does not preserve all information about the
types, but this is fine since this is only used in test case output.
"""
def visit_any(self, t):
return 'any'
def visit_void(self, t):
return 'void'
def visit_instance(self, t):
return t.type.name()
def visit_type_var(self, t):
return 'any*'
def visit_runtime_type_var(self, t):
v = PrettyPrintVisitor()
t.node.accept(v)
return v.output()
class TypePrettyPrintVisitor(TypeVisitor<str>):
"""Pretty-print types.
Include type variables.
Note that the translation does not preserve all information about the
types, but this is fine since this is only used in test case output.
"""
def visit_any(self, t):
return 'any'
def visit_void(self, t):
return 'void'
def visit_instance(self, t):
s = t.type.name()
if t.args:
argstr = ', '.join([a.accept(self) for a in t.args])
s += '<%s>' % argstr
return s
def visit_type_var(self, t):
return 'any*'
def visit_runtime_type_var(self, t):
v = PrettyPrintVisitor()
t.node.accept(v)
return v.output()