Debian Codegraph @

mypyc/test/test_cheader.py

raw
1 """Test that C functions used in primitives are declared in a header such as CPy.h."""
2
3 from __future__ import annotations
4
5 import glob
6 import os
7 import re
8 import unittest
9
10 from mypyc.ir.deps import HeaderDep, SourceDep
11 from mypyc.ir.ops import PrimitiveDescription
12 from mypyc.primitives import (
13 bytearray_ops,
14 bytes_ops,
15 dict_ops,
16 exc_ops,
17 float_ops,
18 generic_ops,
19 int_ops,
20 librt_strings_ops,
21 librt_vecs_ops,
22 list_ops,
23 misc_ops,
24 registry,
25 set_ops,
26 str_ops,
27 tuple_ops,
28 weakref_ops,
29 )
30
31
32 class TestHeaderInclusion(unittest.TestCase):
33 def test_primitives_included_in_header(self) -> None:
34 base_dir = os.path.join(os.path.dirname(__file__), "..", "lib-rt")
35 with open(os.path.join(base_dir, "CPy.h")) as f:
36 header = f.read()
37 with open(os.path.join(base_dir, "pythonsupport.h")) as f:
38 header += f.read()
39
40 def check_name(name: str) -> None:
41 if name.startswith("CPy"):
42 assert re.search(
43 rf"\b{name}\b", header
44 ), f'"{name}" is used in mypyc.primitives but not declared in CPy.h'
45
46 all_ops = []
47 for values in [
48 registry.method_call_ops.values(),
49 registry.binary_ops.values(),
50 registry.unary_ops.values(),
51 registry.function_ops.values(),
52 ]:
53 for ops in values:
54 all_ops.extend(ops)
55
56 for module in [
57 bytes_ops,
58 str_ops,
59 dict_ops,
60 list_ops,
61 bytearray_ops,
62 generic_ops,
63 int_ops,
64 misc_ops,
65 tuple_ops,
66 exc_ops,
67 float_ops,
68 set_ops,
69 weakref_ops,
70 librt_vecs_ops,
71 librt_strings_ops,
72 ]:
73 for name in dir(module):
74 val = getattr(module, name, None)
75 if isinstance(val, PrimitiveDescription):
76 all_ops.append(val)
77
78 # Find additional headers via extra C source file dependencies.
79 for op in all_ops:
80 if op.dependencies:
81 for dep in op.dependencies:
82 if isinstance(dep, (SourceDep, HeaderDep)):
83 header_fnam = os.path.join(base_dir, dep.get_header())
84 if os.path.isfile(header_fnam):
85 with open(os.path.join(base_dir, header_fnam)) as f:
86 header += f.read()
87
88 for op in all_ops:
89 if op.c_function_name is not None:
90 check_name(op.c_function_name)
91
92 primitives_path = os.path.join(os.path.dirname(__file__), "..", "primitives")
93 for fnam in glob.glob(f"{primitives_path}/*.py"):
94 with open(fnam) as f:
95 content = f.read()
96 for name in re.findall(r'c_function_name=["\'](CPy[A-Z_a-z0-9]+)', content):
97 check_name(name)