| 1 |
"""Test cases for annotating source code to highlight inefficiencies.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os.path |
| 6 |
|
| 7 |
from mypy.errors import CompileError |
| 8 |
from mypy.test.config import test_temp_dir |
| 9 |
from mypy.test.data import DataDrivenTestCase |
| 10 |
from mypyc.annotate import generate_annotations, get_max_prio |
| 11 |
from mypyc.ir.pprint import format_func |
| 12 |
from mypyc.test.testutil import ( |
| 13 |
ICODE_GEN_BUILTINS, |
| 14 |
MypycDataSuite, |
| 15 |
assert_test_output, |
| 16 |
build_ir_for_single_file2, |
| 17 |
infer_ir_build_options_from_test_name, |
| 18 |
remove_comment_lines, |
| 19 |
use_custom_builtins, |
| 20 |
) |
| 21 |
|
| 22 |
files = ["annotate-basic.test"] |
| 23 |
|
| 24 |
|
| 25 |
class TestReport(MypycDataSuite): |
| 26 |
files = files |
| 27 |
base_path = test_temp_dir |
| 28 |
optional_out = True |
| 29 |
|
| 30 |
def run_case(self, testcase: DataDrivenTestCase) -> None: |
| 31 |
"""Perform a runtime checking transformation test case.""" |
| 32 |
options = infer_ir_build_options_from_test_name(testcase.name) |
| 33 |
if options is None: |
| 34 |
# Skipped test case |
| 35 |
return |
| 36 |
with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase): |
| 37 |
expected_output = remove_comment_lines(testcase.output) |
| 38 |
|
| 39 |
# Parse "# A: <message>" comments. |
| 40 |
for i, line in enumerate(testcase.input): |
| 41 |
if "# A:" in line: |
| 42 |
msg = line.rpartition("# A:")[2].strip() |
| 43 |
expected_output.append(f"main:{i + 1}: {msg}") |
| 44 |
|
| 45 |
ir = None |
| 46 |
try: |
| 47 |
ir, tree, type_map, mapper = build_ir_for_single_file2(testcase.input, options) |
| 48 |
except CompileError as e: |
| 49 |
actual = e.messages |
| 50 |
else: |
| 51 |
annotations = generate_annotations("native.py", tree, ir, type_map, mapper) |
| 52 |
actual = [] |
| 53 |
for line_num, line_anns in sorted( |
| 54 |
annotations.annotations.items(), key=lambda it: it[0] |
| 55 |
): |
| 56 |
anns = get_max_prio(line_anns) |
| 57 |
str_anns = [a.message for a in anns] |
| 58 |
s = " ".join(str_anns) |
| 59 |
actual.append(f"main:{line_num}: {s}") |
| 60 |
|
| 61 |
try: |
| 62 |
assert_test_output(testcase, actual, "Invalid source code output", expected_output) |
| 63 |
except BaseException: |
| 64 |
if ir: |
| 65 |
print("Generated IR:\n") |
| 66 |
for fn in ir.functions: |
| 67 |
if fn.name == "__top_level__": |
| 68 |
continue |
| 69 |
for s in format_func(fn): |
| 70 |
print(s) |
| 71 |
raise |