Debian Codegraph @

mypyc/annotate.py

raw
1 """Generate source code formatted as HTML, with bottlenecks annotated and highlighted.
2
3 Various heuristics are used to detect common issues that cause slower than
4 expected performance.
5 """
6
7 from __future__ import annotations
8
9 import os.path
10 import sys
11 from html import escape
12 from typing import Final
13
14 from mypy.build import BuildResult
15 from mypy.nodes import (
16 AssignmentStmt,
17 CallExpr,
18 ClassDef,
19 Decorator,
20 DictionaryComprehension,
21 Expression,
22 ForStmt,
23 FuncDef,
24 GeneratorExpr,
25 IndexExpr,
26 LambdaExpr,
27 MemberExpr,
28 MypyFile,
29 NamedTupleExpr,
30 NameExpr,
31 NewTypeExpr,
32 Node,
33 OpExpr,
34 RefExpr,
35 TupleExpr,
36 TypedDictExpr,
37 TypeInfo,
38 TypeVarExpr,
39 Var,
40 WithStmt,
41 )
42 from mypy.traverser import TraverserVisitor
43 from mypy.types import AnyType, Instance, ProperType, Type, TypeOfAny, get_proper_type
44 from mypy.util import FancyFormatter
45 from mypyc.ir.func_ir import FuncIR
46 from mypyc.ir.module_ir import ModuleIR
47 from mypyc.ir.ops import CallC, LoadLiteral, LoadStatic, Value
48 from mypyc.irbuild.mapper import Mapper
49
50
51 class Annotation:
52 """HTML annotation for compiled source code"""
53
54 def __init__(self, message: str, priority: int = 1) -> None:
55 # Message as HTML that describes an issue and/or how to fix it.
56 # Multiple messages on a line may be concatenated.
57 self.message = message
58 # If multiple annotations are generated for a single line, only report
59 # the highest-priority ones. Some use cases generate multiple annotations,
60 # and this can be used to reduce verbosity by hiding the lower-priority
61 # ones.
62 self.priority = priority
63
64
65 op_hints: Final = {
66 "PyNumber_Add": Annotation('Generic "+" operation.'),
67 "PyNumber_Subtract": Annotation('Generic "-" operation.'),
68 "PyNumber_Multiply": Annotation('Generic "*" operation.'),
69 "PyNumber_TrueDivide": Annotation('Generic "/" operation.'),
70 "PyNumber_FloorDivide": Annotation('Generic "//" operation.'),
71 "PyNumber_Positive": Annotation('Generic unary "+" operation.'),
72 "PyNumber_Negative": Annotation('Generic unary "-" operation.'),
73 "PyNumber_And": Annotation('Generic "&" operation.'),
74 "PyNumber_Or": Annotation('Generic "|" operation.'),
75 "PyNumber_Xor": Annotation('Generic "^" operation.'),
76 "PyNumber_Lshift": Annotation('Generic "<<" operation.'),
77 "PyNumber_Rshift": Annotation('Generic ">>" operation.'),
78 "PyNumber_Invert": Annotation('Generic "~" operation.'),
79 "PyObject_Call": Annotation("Generic call operation."),
80 "PyObject_CallObject": Annotation("Generic call operation."),
81 "PyObject_RichCompare": Annotation("Generic comparison operation."),
82 "PyObject_GetItem": Annotation("Generic indexing operation."),
83 "PyObject_SetItem": Annotation("Generic indexed assignment."),
84 }
85
86 stdlib_hints: Final = {
87 "functools.partial": Annotation(
88 '"functools.partial" is inefficient in compiled code.', priority=3
89 ),
90 "itertools.chain": Annotation(
91 '"itertools.chain" is inefficient in compiled code (hint: replace with for loops).',
92 priority=3,
93 ),
94 "itertools.groupby": Annotation(
95 '"itertools.groupby" is inefficient in compiled code.', priority=3
96 ),
97 "itertools.islice": Annotation(
98 '"itertools.islice" is inefficient in compiled code (hint: replace with for loop over index range).',
99 priority=3,
100 ),
101 "copy.deepcopy": Annotation(
102 '"copy.deepcopy" tends to be slow. Make a shallow copy if possible.', priority=2
103 ),
104 }
105
106 CSS = """\
107 .collapsible {
108 cursor: pointer;
109 }
110
111 .content {
112 display: block;
113 margin-top: 10px;
114 margin-bottom: 10px;
115 }
116
117 .hint {
118 display: inline;
119 border: 1px solid #ccc;
120 padding: 5px;
121 }
122 """
123
124 JS = """\
125 document.querySelectorAll('.collapsible').forEach(function(collapsible) {
126 collapsible.addEventListener('click', function() {
127 const content = this.nextElementSibling;
128 if (content.style.display === 'none') {
129 content.style.display = 'block';
130 } else {
131 content.style.display = 'none';
132 }
133 });
134 });
135 """
136
137
138 class AnnotatedSource:
139 """Annotations for a single compiled source file."""
140
141 def __init__(self, path: str, annotations: dict[int, list[Annotation]]) -> None:
142 self.path = path
143 self.annotations = annotations
144
145
146 def generate_annotated_html(
147 html_fnam: str, result: BuildResult, modules: dict[str, ModuleIR], mapper: Mapper
148 ) -> None:
149 annotations = []
150 for mod, mod_ir in modules.items():
151 path = result.graph[mod].path
152 tree = result.graph[mod].tree
153 assert tree is not None
154 annotations.append(
155 generate_annotations(path or "<source>", tree, mod_ir, result.types, mapper)
156 )
157 html = generate_html_report(annotations)
158 with open(html_fnam, "w") as f:
159 f.write(html)
160
161 formatter = FancyFormatter(sys.stdout, sys.stderr, False)
162 formatted = formatter.style(os.path.abspath(html_fnam), "none", underline=True, bold=True)
163 print(f"\nWrote {formatted} -- open in browser to view\n")
164
165
166 def generate_annotations(
167 path: str, tree: MypyFile, ir: ModuleIR, type_map: dict[Expression, Type], mapper: Mapper
168 ) -> AnnotatedSource:
169 anns = {}
170 for func_ir in ir.functions:
171 anns.update(function_annotations(func_ir, tree))
172 visitor = ASTAnnotateVisitor(type_map, mapper)
173 for defn in tree.defs:
174 defn.accept(visitor)
175 anns.update(visitor.anns)
176 for line in visitor.ignored_lines:
177 if line in anns:
178 del anns[line]
179 return AnnotatedSource(path, anns)
180
181
182 def function_annotations(func_ir: FuncIR, tree: MypyFile) -> dict[int, list[Annotation]]:
183 """Generate annotations based on mypyc IR."""
184 # TODO: check if func_ir.line is -1
185 anns: dict[int, list[Annotation]] = {}
186 for block in func_ir.blocks:
187 for op in block.ops:
188 if isinstance(op, CallC):
189 name = op.function_name
190 ann: str | Annotation | None = None
191 if name == "CPyObject_GetAttr":
192 attr_name = get_str_literal(op.args[1])
193 if attr_name in ("__prepare__", "GeneratorExit", "StopIteration"):
194 # These attributes are internal to mypyc/CPython, and/or accessed
195 # implicitly in generated code. The user has little control over
196 # them.
197 ann = None
198 elif attr_name:
199 ann = f'Get non-native attribute "{attr_name}".'
200 else:
201 ann = "Dynamic attribute lookup."
202 elif name == "PyObject_SetAttr":
203 attr_name = get_str_literal(op.args[1])
204 if attr_name == "__mypyc_attrs__":
205 # This is set implicitly and can't be avoided.
206 ann = None
207 elif attr_name:
208 ann = f'Set non-native attribute "{attr_name}".'
209 else:
210 ann = "Dynamic attribute set."
211 elif name == "PyObject_VectorcallMethod":
212 method_name = get_str_literal(op.args[0])
213 if method_name:
214 ann = f'Call non-native method "{method_name}" (it may be defined in a non-native class, or decorated).'
215 else:
216 ann = "Dynamic method call."
217 elif name in op_hints:
218 ann = op_hints[name]
219 elif name in ("CPyDict_GetItem", "CPyDict_SetItem"):
220 if (
221 isinstance(op.args[0], LoadStatic)
222 and isinstance(op.args[1], LoadLiteral)
223 and func_ir.name != "__top_level__"
224 ):
225 load = op.args[0]
226 name = str(op.args[1].value)
227 sym = tree.names.get(name)
228 if (
229 sym
230 and sym.node
231 and load.namespace == "static"
232 and load.identifier == "globals"
233 ):
234 if sym.node.fullname in stdlib_hints:
235 ann = stdlib_hints[sym.node.fullname]
236 elif isinstance(sym.node, Var):
237 ann = (
238 f'Access global "{name}" through namespace '
239 + "dictionary (hint: access is faster if you can make it Final)."
240 )
241 else:
242 ann = f'Access "{name}" through global namespace dictionary.'
243 if ann:
244 if isinstance(ann, str):
245 ann = Annotation(ann)
246 anns.setdefault(op.line, []).append(ann)
247 return anns
248
249
250 class ASTAnnotateVisitor(TraverserVisitor):
251 """Generate annotations from mypy AST and inferred types."""
252
253 def __init__(self, type_map: dict[Expression, Type], mapper: Mapper) -> None:
254 self.anns: dict[int, list[Annotation]] = {}
255 self.ignored_lines: set[int] = set()
256 self.func_depth = 0
257 self.type_map = type_map
258 self.mapper = mapper
259
260 def visit_func_def(self, o: FuncDef, /) -> None:
261 if self.func_depth > 0:
262 self.annotate(
263 o,
264 "A nested function object is allocated each time statement is executed. "
265 + "A module-level function would be faster.",
266 )
267 self.func_depth += 1
268 super().visit_func_def(o)
269 self.func_depth -= 1
270
271 def visit_for_stmt(self, o: ForStmt, /) -> None:
272 self.check_iteration([o.expr], "For loop")
273 super().visit_for_stmt(o)
274
275 def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None:
276 self.check_iteration(o.sequences, "Comprehension")
277 super().visit_dictionary_comprehension(o)
278
279 def visit_generator_expr(self, o: GeneratorExpr, /) -> None:
280 self.check_iteration(o.sequences, "Comprehension or generator")
281 super().visit_generator_expr(o)
282
283 def check_iteration(self, expressions: list[Expression], kind: str) -> None:
284 for expr in expressions:
285 typ = self.get_type(expr)
286 if isinstance(typ, AnyType):
287 self.annotate(expr, f'{kind} uses generic operations (iterable has type "Any").')
288 elif isinstance(typ, Instance) and typ.type.fullname in (
289 "typing.Iterable",
290 "typing.Iterator",
291 "typing.Sequence",
292 "typing.MutableSequence",
293 ):
294 self.annotate(
295 expr,
296 f'{kind} uses generic operations (iterable has the abstract type "{typ.type.fullname}").',
297 )
298
299 def visit_class_def(self, o: ClassDef, /) -> None:
300 super().visit_class_def(o)
301 if self.func_depth == 0:
302 # Don't complain about base classes at top level
303 for base in o.base_type_exprs:
304 self.ignored_lines.add(base.line)
305
306 for s in o.defs.body:
307 if isinstance(s, AssignmentStmt):
308 # Don't complain about attribute initializers
309 self.ignored_lines.add(s.line)
310 elif isinstance(s, Decorator):
311 # Don't complain about decorator definitions that generate some
312 # dynamic operations. This is a bit heavy-handed.
313 self.ignored_lines.add(s.func.line)
314
315 def visit_with_stmt(self, o: WithStmt, /) -> None:
316 for expr in o.expr:
317 if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr):
318 node = expr.callee.node
319 if isinstance(node, Decorator):
320 if any(
321 isinstance(d, RefExpr)
322 and d.node
323 and d.node.fullname == "contextlib.contextmanager"
324 for d in node.decorators
325 ):
326 self.annotate(
327 expr,
328 f'"{node.name}" uses @contextmanager, which is slow '
329 + "in compiled code. Use a native class with "
330 + '"__enter__" and "__exit__" methods instead.',
331 priority=3,
332 )
333 super().visit_with_stmt(o)
334
335 def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None:
336 special_form = False
337 if self.func_depth == 0:
338 analyzed: Expression | None = o.rvalue
339 if isinstance(o.rvalue, (CallExpr, IndexExpr, OpExpr)):
340 analyzed = o.rvalue.analyzed
341 if o.is_alias_def or isinstance(
342 analyzed, (TypeVarExpr, NamedTupleExpr, TypedDictExpr, NewTypeExpr)
343 ):
344 special_form = True
345 if special_form:
346 # TODO: Ignore all lines if multi-line
347 self.ignored_lines.add(o.line)
348 super().visit_assignment_stmt(o)
349
350 def visit_name_expr(self, o: NameExpr, /) -> None:
351 if ann := stdlib_hints.get(o.fullname):
352 self.annotate(o, ann)
353
354 def visit_member_expr(self, o: MemberExpr, /) -> None:
355 super().visit_member_expr(o)
356 if ann := stdlib_hints.get(o.fullname):
357 self.annotate(o, ann)
358
359 def visit_call_expr(self, o: CallExpr, /) -> None:
360 super().visit_call_expr(o)
361 if (
362 isinstance(o.callee, RefExpr)
363 and o.callee.fullname == "builtins.isinstance"
364 and len(o.args) == 2
365 ):
366 arg = o.args[1]
367 self.check_isinstance_arg(arg)
368 elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, TypeInfo):
369 info = o.callee.node
370 class_ir = self.mapper.type_to_ir.get(info)
371 if (class_ir and not class_ir.is_ext_class) or (
372 class_ir is None and not info.fullname.startswith("builtins.")
373 ):
374 self.annotate(
375 o, f'Creating an instance of non-native class "{info.name}" ' + "is slow.", 2
376 )
377 elif class_ir and class_ir.is_augmented:
378 self.annotate(
379 o,
380 f'Class "{info.name}" is only partially native, and '
381 + "constructing an instance is slow.",
382 2,
383 )
384 elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, Decorator):
385 decorator = o.callee.node
386 if self.mapper.is_native_ref_expr(o.callee):
387 self.annotate(
388 o,
389 f'Calling a decorated function ("{decorator.name}") is inefficient, even if it\'s native.',
390 2,
391 )
392
393 def check_isinstance_arg(self, arg: Expression) -> None:
394 if isinstance(arg, RefExpr):
395 if isinstance(arg.node, TypeInfo) and arg.node.is_protocol:
396 self.annotate(
397 arg, f'Expensive isinstance() check against protocol "{arg.node.name}".'
398 )
399 elif isinstance(arg, TupleExpr):
400 for item in arg.items:
401 self.check_isinstance_arg(item)
402
403 def visit_lambda_expr(self, o: LambdaExpr, /) -> None:
404 self.annotate(
405 o,
406 "A new object is allocated for lambda each time it is evaluated. "
407 + "A module-level function would be faster.",
408 )
409 super().visit_lambda_expr(o)
410
411 def annotate(self, o: Node, ann: str | Annotation, priority: int = 1) -> None:
412 if isinstance(ann, str):
413 ann = Annotation(ann, priority=priority)
414 self.anns.setdefault(o.line, []).append(ann)
415
416 def get_type(self, e: Expression) -> ProperType:
417 t = self.type_map.get(e)
418 if t:
419 return get_proper_type(t)
420 return AnyType(TypeOfAny.unannotated)
421
422
423 def get_str_literal(v: Value) -> str | None:
424 if isinstance(v, LoadLiteral) and isinstance(v.value, str):
425 return v.value
426 return None
427
428
429 def get_max_prio(anns: list[Annotation]) -> list[Annotation]:
430 max_prio = max(a.priority for a in anns)
431 return [a for a in anns if a.priority == max_prio]
432
433
434 def generate_html_report(sources: list[AnnotatedSource]) -> str:
435 html = []
436 html.append("<html>\n<head>\n")
437 html.append(f"<style>\n{CSS}\n</style>")
438 html.append("</head>\n")
439 html.append("<body>\n")
440 for src in sources:
441 html.append(f"<h2><tt>{src.path}</tt></h2>\n")
442 html.append("<pre>")
443 src_anns = src.annotations
444 with open(src.path) as f:
445 lines = f.readlines()
446 for i, s in enumerate(lines):
447 s = escape(s)
448 line = i + 1
449 linenum = "%5d" % line
450 if line in src_anns:
451 anns = get_max_prio(src_anns[line])
452 ann_strs = [a.message for a in anns]
453 hint = " ".join(ann_strs)
454 s = colorize_line(linenum, s, hint_html=hint)
455 else:
456 s = linenum + " " + s
457 html.append(s)
458 html.append("</pre>")
459
460 html.append("<script>")
461 html.append(JS)
462 html.append("</script>")
463
464 html.append("</body></html>\n")
465 return "".join(html)
466
467
468 def colorize_line(linenum: str, s: str, hint_html: str) -> str:
469 hint_prefix = " " * len(linenum) + " "
470 line_span = f'<div class="collapsible" style="background-color: #fcc">{linenum} {s}</div>'
471 hint_div = f'<div class="content">{hint_prefix}<div class="hint">{hint_html}</div></div>'
472 return f"<span>{line_span}{hint_div}</span>"