Debian Codegraph @

mypyc/test/test_emitfunc.py

raw
1 from __future__ import annotations
2
3 import unittest
4
5 from mypy.test.helpers import assert_string_arrays_equal
6 from mypyc.codegen.emit import Emitter, EmitterContext
7 from mypyc.codegen.emitfunc import FunctionEmitterVisitor, generate_native_function
8 from mypyc.common import HAVE_IMMORTAL, PLATFORM_SIZE
9 from mypyc.ir.class_ir import ClassIR
10 from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg
11 from mypyc.ir.ops import (
12 ERR_NEVER,
13 Assign,
14 AssignMulti,
15 BasicBlock,
16 Box,
17 Branch,
18 Call,
19 CallC,
20 Cast,
21 ComparisonOp,
22 CString,
23 DecRef,
24 Extend,
25 GetAttr,
26 GetElementPtr,
27 Goto,
28 IncRef,
29 Integer,
30 IntOp,
31 LoadAddress,
32 LoadLiteral,
33 LoadMem,
34 Op,
35 Register,
36 Return,
37 SetAttr,
38 SetElement,
39 SetMem,
40 TupleGet,
41 Unbox,
42 Undef,
43 Unreachable,
44 Value,
45 )
46 from mypyc.ir.pprint import generate_names_for_ir
47 from mypyc.ir.rtypes import (
48 RArray,
49 RInstance,
50 RStruct,
51 RTuple,
52 RType,
53 RUnion,
54 RVec,
55 bool_rprimitive,
56 c_int_rprimitive,
57 cstring_rprimitive,
58 dict_rprimitive,
59 int32_rprimitive,
60 int64_rprimitive,
61 int_rprimitive,
62 list_rprimitive,
63 none_rprimitive,
64 object_rprimitive,
65 pointer_rprimitive,
66 short_int_rprimitive,
67 str_rprimitive,
68 )
69 from mypyc.irbuild.vtable import compute_vtable
70 from mypyc.namegen import NameGenerator
71 from mypyc.primitives.dict_ops import (
72 dict_get_item_op,
73 dict_new_op,
74 dict_set_item_op,
75 dict_update_op,
76 )
77 from mypyc.primitives.int_ops import int_neg_op
78 from mypyc.primitives.list_ops import list_append_op, list_get_item_op, list_set_item_op
79 from mypyc.primitives.misc_ops import none_object_op
80 from mypyc.primitives.registry import binary_ops
81 from mypyc.subtype import is_subtype
82
83
84 class TestFunctionEmitterVisitor(unittest.TestCase):
85 """Test generation of fragments of C from individual IR ops."""
86
87 def setUp(self) -> None:
88 self.registers: list[Register] = []
89
90 def add_local(name: str, rtype: RType) -> Register:
91 reg = Register(rtype, name)
92 self.registers.append(reg)
93 return reg
94
95 self.n = add_local("n", int_rprimitive)
96 self.m = add_local("m", int_rprimitive)
97 self.k = add_local("k", int_rprimitive)
98 self.l = add_local("l", list_rprimitive)
99 self.ll = add_local("ll", list_rprimitive)
100 self.o = add_local("o", object_rprimitive)
101 self.o2 = add_local("o2", object_rprimitive)
102 self.d = add_local("d", dict_rprimitive)
103 self.b = add_local("b", bool_rprimitive)
104 self.s1 = add_local("s1", short_int_rprimitive)
105 self.s2 = add_local("s2", short_int_rprimitive)
106 self.i32 = add_local("i32", int32_rprimitive)
107 self.i32_1 = add_local("i32_1", int32_rprimitive)
108 self.i64 = add_local("i64", int64_rprimitive)
109 self.i64_1 = add_local("i64_1", int64_rprimitive)
110 self.ptr = add_local("ptr", pointer_rprimitive)
111 self.t = add_local("t", RTuple([int_rprimitive, bool_rprimitive]))
112 self.tt = add_local(
113 "tt", RTuple([RTuple([int_rprimitive, bool_rprimitive]), bool_rprimitive])
114 )
115 self.vi64 = add_local("vi64", RVec(int64_rprimitive))
116 self.vi32 = add_local("vi32", RVec(int32_rprimitive))
117 self.vs = add_local("vs", RVec(str_rprimitive))
118 self.vs_opt = add_local("vs", RVec(RUnion([str_rprimitive, none_rprimitive])))
119 self.vvs = add_local("vvs", RVec(RVec(str_rprimitive)))
120 ir = ClassIR("A", "mod")
121 ir.attributes = {
122 "x": bool_rprimitive,
123 "y": int_rprimitive,
124 "i1": int64_rprimitive,
125 "i2": int32_rprimitive,
126 "t": RTuple([object_rprimitive, object_rprimitive]),
127 }
128 ir.bitmap_attrs = ["i1", "i2"]
129 compute_vtable(ir)
130 ir.mro = [ir]
131 self.r = add_local("r", RInstance(ir))
132 self.none = add_local("none", none_rprimitive)
133
134 self.struct_type = RStruct(
135 "Foo", ["b", "x", "y"], [bool_rprimitive, int32_rprimitive, int64_rprimitive]
136 )
137 self.st = add_local("st", self.struct_type)
138
139 self.context = EmitterContext(NameGenerator([["mod"]]), True)
140
141 def test_goto(self) -> None:
142 self.assert_emit(Goto(BasicBlock(2)), "goto CPyL2;")
143
144 def test_goto_next_block(self) -> None:
145 next_block = BasicBlock(2)
146 self.assert_emit(Goto(next_block), "", next_block=next_block)
147
148 def test_return(self) -> None:
149 self.assert_emit(Return(self.m), "return cpy_r_m;")
150
151 def test_integer(self) -> None:
152 self.assert_emit(Assign(self.n, Integer(5)), "cpy_r_n = 10;")
153 self.assert_emit(Assign(self.i32, Integer(5, c_int_rprimitive)), "cpy_r_i32 = 5;")
154
155 def test_tuple_get(self) -> None:
156 self.assert_emit(TupleGet(self.t, 1, 0), "cpy_r_r0 = cpy_r_t.f1;")
157
158 def test_load_None(self) -> None: # noqa: N802
159 self.assert_emit(
160 LoadAddress(none_object_op.type, none_object_op.src, 0),
161 "cpy_r_r0 = (PyObject *)&_Py_NoneStruct;",
162 )
163
164 def test_assign_int(self) -> None:
165 self.assert_emit(Assign(self.m, self.n), "cpy_r_m = cpy_r_n;")
166
167 def test_int_add(self) -> None:
168 self.assert_emit_binary_op(
169 "+", self.n, self.m, self.k, "cpy_r_r0 = CPyTagged_Add(cpy_r_m, cpy_r_k);"
170 )
171
172 def test_int_sub(self) -> None:
173 self.assert_emit_binary_op(
174 "-", self.n, self.m, self.k, "cpy_r_r0 = CPyTagged_Subtract(cpy_r_m, cpy_r_k);"
175 )
176
177 def test_int_neg(self) -> None:
178 assert int_neg_op.c_function_name is not None
179 self.assert_emit(
180 CallC(
181 int_neg_op.c_function_name,
182 [self.m],
183 int_neg_op.return_type,
184 int_neg_op.steals,
185 int_neg_op.is_borrowed,
186 int_neg_op.is_borrowed,
187 int_neg_op.error_kind,
188 55,
189 ),
190 "cpy_r_r0 = CPyTagged_Negate(cpy_r_m);",
191 )
192
193 def test_branch(self) -> None:
194 self.assert_emit(
195 Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.BOOL),
196 """if (cpy_r_b) {
197 goto CPyL8;
198 } else
199 goto CPyL9;
200 """,
201 )
202 b = Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.BOOL)
203 b.negated = True
204 self.assert_emit(
205 b,
206 """if (!cpy_r_b) {
207 goto CPyL8;
208 } else
209 goto CPyL9;
210 """,
211 )
212
213 def test_branch_no_else(self) -> None:
214 next_block = BasicBlock(9)
215 b = Branch(self.b, BasicBlock(8), next_block, Branch.BOOL)
216 self.assert_emit(b, """if (cpy_r_b) goto CPyL8;""", next_block=next_block)
217 next_block = BasicBlock(9)
218 b = Branch(self.b, BasicBlock(8), next_block, Branch.BOOL)
219 b.negated = True
220 self.assert_emit(b, """if (!cpy_r_b) goto CPyL8;""", next_block=next_block)
221
222 def test_branch_no_else_negated(self) -> None:
223 next_block = BasicBlock(1)
224 b = Branch(self.b, next_block, BasicBlock(2), Branch.BOOL)
225 self.assert_emit(b, """if (!cpy_r_b) goto CPyL2;""", next_block=next_block)
226 next_block = BasicBlock(1)
227 b = Branch(self.b, next_block, BasicBlock(2), Branch.BOOL)
228 b.negated = True
229 self.assert_emit(b, """if (cpy_r_b) goto CPyL2;""", next_block=next_block)
230
231 def test_branch_is_error(self) -> None:
232 b = Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)
233 self.assert_emit(
234 b,
235 """if (cpy_r_b == 2) {
236 goto CPyL8;
237 } else
238 goto CPyL9;
239 """,
240 )
241 b = Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)
242 b.negated = True
243 self.assert_emit(
244 b,
245 """if (cpy_r_b != 2) {
246 goto CPyL8;
247 } else
248 goto CPyL9;
249 """,
250 )
251
252 def test_branch_is_error_next_block(self) -> None:
253 next_block = BasicBlock(8)
254 b = Branch(self.b, next_block, BasicBlock(9), Branch.IS_ERROR)
255 self.assert_emit(b, """if (cpy_r_b != 2) goto CPyL9;""", next_block=next_block)
256 b = Branch(self.b, next_block, BasicBlock(9), Branch.IS_ERROR)
257 b.negated = True
258 self.assert_emit(b, """if (cpy_r_b == 2) goto CPyL9;""", next_block=next_block)
259
260 def test_branch_rare(self) -> None:
261 self.assert_emit(
262 Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.BOOL, rare=True),
263 """if (unlikely(cpy_r_b)) {
264 goto CPyL8;
265 } else
266 goto CPyL9;
267 """,
268 )
269 next_block = BasicBlock(9)
270 self.assert_emit(
271 Branch(self.b, BasicBlock(8), next_block, Branch.BOOL, rare=True),
272 """if (unlikely(cpy_r_b)) goto CPyL8;""",
273 next_block=next_block,
274 )
275 next_block = BasicBlock(8)
276 b = Branch(self.b, next_block, BasicBlock(9), Branch.BOOL, rare=True)
277 self.assert_emit(b, """if (likely(!cpy_r_b)) goto CPyL9;""", next_block=next_block)
278 next_block = BasicBlock(8)
279 b = Branch(self.b, next_block, BasicBlock(9), Branch.BOOL, rare=True)
280 b.negated = True
281 self.assert_emit(b, """if (likely(cpy_r_b)) goto CPyL9;""", next_block=next_block)
282
283 def test_call(self) -> None:
284 decl = FuncDecl(
285 "myfn", None, "mod", FuncSignature([RuntimeArg("m", int_rprimitive)], int_rprimitive)
286 )
287 self.assert_emit(Call(decl, [self.m], 55), "cpy_r_r0 = CPyDef_myfn(cpy_r_m);")
288
289 def test_call_two_args(self) -> None:
290 decl = FuncDecl(
291 "myfn",
292 None,
293 "mod",
294 FuncSignature(
295 [RuntimeArg("m", int_rprimitive), RuntimeArg("n", int_rprimitive)], int_rprimitive
296 ),
297 )
298 self.assert_emit(
299 Call(decl, [self.m, self.k], 55), "cpy_r_r0 = CPyDef_myfn(cpy_r_m, cpy_r_k);"
300 )
301
302 def test_inc_ref(self) -> None:
303 self.assert_emit(IncRef(self.o), "CPy_INCREF(cpy_r_o);")
304 self.assert_emit(IncRef(self.o), "CPy_INCREF(cpy_r_o);", rare=True)
305
306 def test_dec_ref(self) -> None:
307 self.assert_emit(DecRef(self.o), "CPy_DECREF(cpy_r_o);")
308 self.assert_emit(DecRef(self.o), "CPy_DecRef(cpy_r_o);", rare=True)
309
310 def test_inc_ref_int(self) -> None:
311 self.assert_emit(IncRef(self.m), "CPyTagged_INCREF(cpy_r_m);")
312 self.assert_emit(IncRef(self.m), "CPyTagged_IncRef(cpy_r_m);", rare=True)
313
314 def test_dec_ref_int(self) -> None:
315 self.assert_emit(DecRef(self.m), "CPyTagged_DECREF(cpy_r_m);")
316 self.assert_emit(DecRef(self.m), "CPyTagged_DecRef(cpy_r_m);", rare=True)
317
318 def test_dec_ref_tuple(self) -> None:
319 self.assert_emit(DecRef(self.t), "CPyTagged_DECREF(cpy_r_t.f0);")
320
321 def test_dec_ref_tuple_nested(self) -> None:
322 self.assert_emit(DecRef(self.tt), "CPyTagged_DECREF(cpy_r_tt.f0.f0);")
323
324 def test_list_get_item(self) -> None:
325 self.assert_emit(
326 CallC(
327 str(list_get_item_op.c_function_name),
328 [self.m, self.k],
329 list_get_item_op.return_type,
330 list_get_item_op.steals,
331 list_get_item_op.is_borrowed,
332 list_get_item_op.error_kind,
333 55,
334 ),
335 """cpy_r_r0 = CPyList_GetItem(cpy_r_m, cpy_r_k);""",
336 )
337
338 def test_list_set_item(self) -> None:
339 self.assert_emit(
340 CallC(
341 str(list_set_item_op.c_function_name),
342 [self.l, self.n, self.o],
343 list_set_item_op.return_type,
344 list_set_item_op.steals,
345 list_set_item_op.is_borrowed,
346 list_set_item_op.error_kind,
347 55,
348 ),
349 """cpy_r_r0 = CPyList_SetItem(cpy_r_l, cpy_r_n, cpy_r_o);""",
350 )
351
352 def test_box_int(self) -> None:
353 self.assert_emit(Box(self.n), """cpy_r_r0 = CPyTagged_StealAsObject(cpy_r_n);""")
354
355 def test_unbox_int(self) -> None:
356 self.assert_emit(
357 Unbox(self.m, int_rprimitive, 55),
358 """if (likely(PyLong_Check(cpy_r_m)))
359 cpy_r_r0 = CPyTagged_FromObject(cpy_r_m);
360 else {
361 CPy_TypeError("int", cpy_r_m); cpy_r_r0 = CPY_INT_TAG;
362 }
363 """,
364 )
365
366 def test_box_i64(self) -> None:
367 self.assert_emit(Box(self.i64), """cpy_r_r0 = PyLong_FromLongLong(cpy_r_i64);""")
368
369 def test_unbox_i64(self) -> None:
370 self.assert_emit(
371 Unbox(self.o, int64_rprimitive, 55), """cpy_r_r0 = CPyLong_AsInt64(cpy_r_o);"""
372 )
373
374 def test_box_vec(self) -> None:
375 self.assert_emit(Box(self.vi64), """cpy_r_r0 = VecI64Api.box(cpy_r_vi64);""")
376 self.assert_emit(Box(self.vi32), """cpy_r_r0 = VecI32Api.box(cpy_r_vi32);""")
377 self.assert_emit(
378 Box(self.vs), """cpy_r_r0 = VecTApi.box(cpy_r_vs, (size_t)&PyUnicode_Type);"""
379 )
380 self.assert_emit(
381 Box(self.vs_opt),
382 """cpy_r_r0 = VecTApi.box(cpy_r_vs, ((size_t)&PyUnicode_Type | 1));""",
383 )
384 self.assert_emit(Box(self.vvs), """cpy_r_r0 = VecNestedApi.box(cpy_r_vvs);""")
385
386 def test_unbox_vec(self) -> None:
387 self.assert_emit(
388 Unbox(self.o, RVec(int64_rprimitive), 55),
389 """cpy_r_r0 = VecI64Api.unbox(cpy_r_o);
390 if (VEC_IS_ERROR(cpy_r_r0)) {
391 CPy_TypeError("vec[i64]", cpy_r_o); cpy_r_r0 = (VecI64) { -1, NULL };
392 }
393 """,
394 )
395 self.assert_emit(
396 Unbox(self.o, RVec(int32_rprimitive), 55),
397 """cpy_r_r0 = VecI32Api.unbox(cpy_r_o);
398 if (VEC_IS_ERROR(cpy_r_r0)) {
399 CPy_TypeError("vec[i32]", cpy_r_o); cpy_r_r0 = (VecI32) { -1, NULL };
400 }
401 """,
402 )
403 self.assert_emit(
404 Unbox(self.o, RVec(str_rprimitive), 55),
405 """cpy_r_r0 = VecTApi.unbox(cpy_r_o, (size_t)&PyUnicode_Type);
406 if (VEC_IS_ERROR(cpy_r_r0)) {
407 CPy_TypeError("vec[str]", cpy_r_o); cpy_r_r0 = (VecT) { -1, NULL };
408 }
409 """,
410 )
411 self.assert_emit(
412 Unbox(self.o, RVec(RUnion([str_rprimitive, none_rprimitive])), 55),
413 """cpy_r_r0 = VecTApi.unbox(cpy_r_o, ((size_t)&PyUnicode_Type | 1));
414 if (VEC_IS_ERROR(cpy_r_r0)) {
415 CPy_TypeError("vec[str | None]", cpy_r_o); cpy_r_r0 = (VecT) { -1, NULL };
416 }
417 """,
418 )
419 self.assert_emit(
420 Unbox(self.o, RVec(self.r.type), 55),
421 """cpy_r_r0 = VecTApi.unbox(cpy_r_o, (size_t)CPyType_A);
422 if (VEC_IS_ERROR(cpy_r_r0)) {
423 CPy_TypeError("vec[mod.A]", cpy_r_o); cpy_r_r0 = (VecT) { -1, NULL };
424 }
425 """,
426 )
427
428 def test_unbox_vec_nested(self) -> None:
429 self.assert_emit(
430 Unbox(self.o, RVec(RVec(str_rprimitive)), 55),
431 """cpy_r_r0 = VecNestedApi.unbox(cpy_r_o, (size_t)&PyUnicode_Type, 1);
432 if (VEC_IS_ERROR(cpy_r_r0)) {
433 CPy_TypeError("vec[vec[str]]", cpy_r_o); cpy_r_r0 = (VecNested) { -1, NULL };
434 }
435 """,
436 )
437 self.assert_emit(
438 Unbox(self.o, RVec(RVec(RUnion([str_rprimitive, none_rprimitive]))), 55),
439 """cpy_r_r0 = VecNestedApi.unbox(cpy_r_o, ((size_t)&PyUnicode_Type | 1), 1);
440 if (VEC_IS_ERROR(cpy_r_r0)) {
441 CPy_TypeError("vec[vec[str | None]]", cpy_r_o); cpy_r_r0 = (VecNested) { -1, NULL };
442 }
443 """,
444 )
445 self.assert_emit(
446 Unbox(self.o, RVec(RVec(int64_rprimitive)), 55),
447 """cpy_r_r0 = VecNestedApi.unbox(cpy_r_o, 2, 1);
448 if (VEC_IS_ERROR(cpy_r_r0)) {
449 CPy_TypeError("vec[vec[i64]]", cpy_r_o); cpy_r_r0 = (VecNested) { -1, NULL };
450 }
451 """,
452 )
453
454 def test_list_append(self) -> None:
455 self.assert_emit(
456 CallC(
457 str(list_append_op.c_function_name),
458 [self.l, self.o],
459 list_append_op.return_type,
460 list_append_op.steals,
461 list_append_op.is_borrowed,
462 list_append_op.error_kind,
463 1,
464 ),
465 """cpy_r_r0 = PyList_Append(cpy_r_l, cpy_r_o);""",
466 )
467
468 def test_get_attr(self) -> None:
469 self.assert_emit(
470 GetAttr(self.r, "y", 1),
471 """cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_y;
472 if (unlikely(cpy_r_r0 == CPY_INT_TAG)) {
473 PyErr_SetString(PyExc_AttributeError, "attribute 'y' of 'A' undefined");
474 } else {
475 CPyTagged_INCREF(cpy_r_r0);
476 }
477 """,
478 )
479
480 def test_get_attr_non_refcounted(self) -> None:
481 self.assert_emit(
482 GetAttr(self.r, "x", 1),
483 """cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_x;
484 if (unlikely(cpy_r_r0 == 2)) {
485 PyErr_SetString(PyExc_AttributeError, "attribute 'x' of 'A' undefined");
486 }
487 """,
488 )
489
490 def test_get_attr_merged(self) -> None:
491 op = GetAttr(self.r, "y", 1)
492 branch = Branch(op, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)
493 branch.traceback_entry = ("foobar", 123)
494 self.assert_emit(
495 op,
496 """\
497 cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_y;
498 if (unlikely(cpy_r_r0 == CPY_INT_TAG)) {
499 CPy_AttributeError("prog.py", "foobar", "A", "y", 123, CPyStatic_prog___globals);
500 goto CPyL8;
501 }
502 CPyTagged_INCREF(cpy_r_r0);
503 goto CPyL9;
504 """,
505 next_branch=branch,
506 skip_next=True,
507 )
508
509 def test_get_attr_with_bitmap(self) -> None:
510 self.assert_emit(
511 GetAttr(self.r, "i1", 1),
512 """cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_i1;
513 if (unlikely(cpy_r_r0 == -113) && !(((mod___AObject *)cpy_r_r)->bitmap & 1)) {
514 PyErr_SetString(PyExc_AttributeError, "attribute 'i1' of 'A' undefined");
515 }
516 """,
517 )
518
519 def test_get_attr_nullable_with_tuple(self) -> None:
520 self.assert_emit(
521 GetAttr(self.r, "t", 1, allow_error_value=True),
522 """cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_t;
523 if (cpy_r_r0.f0 != NULL) {
524 CPy_INCREF(cpy_r_r0.f0);
525 CPy_INCREF(cpy_r_r0.f1);
526 }
527 """,
528 )
529
530 def test_set_attr(self) -> None:
531 self.assert_emit(
532 SetAttr(self.r, "y", self.m, 1),
533 """if (((mod___AObject *)cpy_r_r)->_y != CPY_INT_TAG) {
534 CPyTagged_DECREF(((mod___AObject *)cpy_r_r)->_y);
535 }
536 ((mod___AObject *)cpy_r_r)->_y = cpy_r_m;
537 cpy_r_r0 = 1;
538 """,
539 )
540
541 def test_set_attr_non_refcounted(self) -> None:
542 self.assert_emit(
543 SetAttr(self.r, "x", self.b, 1),
544 """((mod___AObject *)cpy_r_r)->_x = cpy_r_b;
545 cpy_r_r0 = 1;
546 """,
547 )
548
549 def test_set_attr_no_error(self) -> None:
550 op = SetAttr(self.r, "y", self.m, 1)
551 op.error_kind = ERR_NEVER
552 self.assert_emit(
553 op,
554 """if (((mod___AObject *)cpy_r_r)->_y != CPY_INT_TAG) {
555 CPyTagged_DECREF(((mod___AObject *)cpy_r_r)->_y);
556 }
557 ((mod___AObject *)cpy_r_r)->_y = cpy_r_m;
558 """,
559 )
560
561 def test_set_attr_non_refcounted_no_error(self) -> None:
562 op = SetAttr(self.r, "x", self.b, 1)
563 op.error_kind = ERR_NEVER
564 self.assert_emit(
565 op,
566 """((mod___AObject *)cpy_r_r)->_x = cpy_r_b;
567 """,
568 )
569
570 def test_set_attr_with_bitmap(self) -> None:
571 # For some rtypes the error value overlaps a valid value, so we need
572 # to use a separate bitmap to track defined attributes.
573 self.assert_emit(
574 SetAttr(self.r, "i1", self.i64, 1),
575 """if (unlikely(cpy_r_i64 == -113)) {
576 ((mod___AObject *)cpy_r_r)->bitmap |= 1;
577 }
578 ((mod___AObject *)cpy_r_r)->_i1 = cpy_r_i64;
579 cpy_r_r0 = 1;
580 """,
581 )
582 self.assert_emit(
583 SetAttr(self.r, "i2", self.i32, 1),
584 """if (unlikely(cpy_r_i32 == -113)) {
585 ((mod___AObject *)cpy_r_r)->bitmap |= 2;
586 }
587 ((mod___AObject *)cpy_r_r)->_i2 = cpy_r_i32;
588 cpy_r_r0 = 1;
589 """,
590 )
591
592 def test_set_attr_init_with_bitmap(self) -> None:
593 op = SetAttr(self.r, "i1", self.i64, 1)
594 op.is_init = True
595 self.assert_emit(
596 op,
597 """if (unlikely(cpy_r_i64 == -113)) {
598 ((mod___AObject *)cpy_r_r)->bitmap |= 1;
599 }
600 ((mod___AObject *)cpy_r_r)->_i1 = cpy_r_i64;
601 cpy_r_r0 = 1;
602 """,
603 )
604
605 def test_dict_get_item(self) -> None:
606 self.assert_emit(
607 CallC(
608 str(dict_get_item_op.c_function_name),
609 [self.d, self.o2],
610 dict_get_item_op.return_type,
611 dict_get_item_op.steals,
612 dict_get_item_op.is_borrowed,
613 dict_get_item_op.error_kind,
614 1,
615 ),
616 """cpy_r_r0 = CPyDict_GetItem(cpy_r_d, cpy_r_o2);""",
617 )
618
619 def test_dict_set_item(self) -> None:
620 self.assert_emit(
621 CallC(
622 str(dict_set_item_op.c_function_name),
623 [self.d, self.o, self.o2],
624 dict_set_item_op.return_type,
625 dict_set_item_op.steals,
626 dict_set_item_op.is_borrowed,
627 dict_set_item_op.error_kind,
628 1,
629 ),
630 """cpy_r_r0 = CPyDict_SetItem(cpy_r_d, cpy_r_o, cpy_r_o2);""",
631 )
632
633 def test_dict_update(self) -> None:
634 self.assert_emit(
635 CallC(
636 str(dict_update_op.c_function_name),
637 [self.d, self.o],
638 dict_update_op.return_type,
639 dict_update_op.steals,
640 dict_update_op.is_borrowed,
641 dict_update_op.error_kind,
642 1,
643 ),
644 """cpy_r_r0 = CPyDict_Update(cpy_r_d, cpy_r_o);""",
645 )
646
647 def test_new_dict(self) -> None:
648 self.assert_emit(
649 CallC(
650 dict_new_op.c_function_name,
651 [],
652 dict_new_op.return_type,
653 dict_new_op.steals,
654 dict_new_op.is_borrowed,
655 dict_new_op.error_kind,
656 1,
657 ),
658 """cpy_r_r0 = PyDict_New();""",
659 )
660
661 def test_dict_contains(self) -> None:
662 self.assert_emit_binary_op(
663 "in", self.b, self.o, self.d, """cpy_r_r0 = PyDict_Contains(cpy_r_d, cpy_r_o);"""
664 )
665
666 def test_int_op(self) -> None:
667 self.assert_emit(
668 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.ADD, 1),
669 """cpy_r_r0 = cpy_r_s1 + cpy_r_s2;""",
670 )
671 self.assert_emit(
672 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.SUB, 1),
673 """cpy_r_r0 = cpy_r_s1 - cpy_r_s2;""",
674 )
675 self.assert_emit(
676 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.MUL, 1),
677 """cpy_r_r0 = cpy_r_s1 * cpy_r_s2;""",
678 )
679 self.assert_emit(
680 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.DIV, 1),
681 """cpy_r_r0 = cpy_r_s1 / cpy_r_s2;""",
682 )
683 self.assert_emit(
684 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.MOD, 1),
685 """cpy_r_r0 = cpy_r_s1 % cpy_r_s2;""",
686 )
687 self.assert_emit(
688 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.AND, 1),
689 """cpy_r_r0 = cpy_r_s1 & cpy_r_s2;""",
690 )
691 self.assert_emit(
692 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.OR, 1),
693 """cpy_r_r0 = cpy_r_s1 | cpy_r_s2;""",
694 )
695 self.assert_emit(
696 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.XOR, 1),
697 """cpy_r_r0 = cpy_r_s1 ^ cpy_r_s2;""",
698 )
699 self.assert_emit(
700 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.LEFT_SHIFT, 1),
701 """cpy_r_r0 = cpy_r_s1 << cpy_r_s2;""",
702 )
703 self.assert_emit(
704 IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.RIGHT_SHIFT, 1),
705 """cpy_r_r0 = (Py_ssize_t)cpy_r_s1 >> (Py_ssize_t)cpy_r_s2;""",
706 )
707 self.assert_emit(
708 IntOp(short_int_rprimitive, self.i64, self.i64_1, IntOp.RIGHT_SHIFT, 1),
709 """cpy_r_r0 = cpy_r_i64 >> cpy_r_i64_1;""",
710 )
711
712 def test_comparison_op(self) -> None:
713 # signed
714 self.assert_emit(
715 ComparisonOp(self.s1, self.s2, ComparisonOp.SLT, 1),
716 """cpy_r_r0 = (Py_ssize_t)cpy_r_s1 < (Py_ssize_t)cpy_r_s2;""",
717 )
718 self.assert_emit(
719 ComparisonOp(self.i32, self.i32_1, ComparisonOp.SLT, 1),
720 """cpy_r_r0 = cpy_r_i32 < cpy_r_i32_1;""",
721 )
722 self.assert_emit(
723 ComparisonOp(self.i64, self.i64_1, ComparisonOp.SLT, 1),
724 """cpy_r_r0 = cpy_r_i64 < cpy_r_i64_1;""",
725 )
726 # unsigned
727 self.assert_emit(
728 ComparisonOp(self.s1, self.s2, ComparisonOp.ULT, 1),
729 """cpy_r_r0 = cpy_r_s1 < cpy_r_s2;""",
730 )
731 self.assert_emit(
732 ComparisonOp(self.i32, self.i32_1, ComparisonOp.ULT, 1),
733 """cpy_r_r0 = (uint32_t)cpy_r_i32 < (uint32_t)cpy_r_i32_1;""",
734 )
735 self.assert_emit(
736 ComparisonOp(self.i64, self.i64_1, ComparisonOp.ULT, 1),
737 """cpy_r_r0 = (uint64_t)cpy_r_i64 < (uint64_t)cpy_r_i64_1;""",
738 )
739
740 # object type
741 self.assert_emit(
742 ComparisonOp(self.o, self.o2, ComparisonOp.EQ, 1),
743 """cpy_r_r0 = cpy_r_o == cpy_r_o2;""",
744 )
745 self.assert_emit(
746 ComparisonOp(self.o, self.o2, ComparisonOp.NEQ, 1),
747 """cpy_r_r0 = cpy_r_o != cpy_r_o2;""",
748 )
749
750 def test_load_mem(self) -> None:
751 self.assert_emit(LoadMem(bool_rprimitive, self.ptr), """cpy_r_r0 = *(char *)cpy_r_ptr;""")
752
753 def test_set_mem(self) -> None:
754 self.assert_emit(
755 SetMem(bool_rprimitive, self.ptr, self.b), """*(char *)cpy_r_ptr = cpy_r_b;"""
756 )
757
758 def test_get_element_ptr(self) -> None:
759 r = RStruct(
760 "Foo", ["b", "i32", "i64"], [bool_rprimitive, int32_rprimitive, int64_rprimitive]
761 )
762 self.assert_emit(
763 GetElementPtr(self.o, r, "b"),
764 """cpy_r_r0 = (CPyPtr)((CPyPtr)cpy_r_o + offsetof(Foo, b));""",
765 )
766 self.assert_emit(
767 GetElementPtr(self.o, r, "i32"),
768 """cpy_r_r0 = (CPyPtr)((CPyPtr)cpy_r_o + offsetof(Foo, i32));""",
769 )
770 self.assert_emit(
771 GetElementPtr(self.o, r, "i64"),
772 """cpy_r_r0 = (CPyPtr)((CPyPtr)cpy_r_o + offsetof(Foo, i64));""",
773 )
774
775 def test_set_element(self) -> None:
776 # Use compact syntax when setting the initial element of an undefined value
777 self.assert_emit(
778 SetElement(Undef(self.struct_type), "b", self.b), """cpy_r_r0.b = cpy_r_b;"""
779 )
780 # We propagate the unchanged values in subsequent assignments
781 self.assert_emit(
782 SetElement(self.st, "x", self.i32),
783 """cpy_r_r0 = (Foo) { cpy_r_st.b, cpy_r_i32, cpy_r_st.y };""",
784 )
785
786 def test_load_address(self) -> None:
787 self.assert_emit(
788 LoadAddress(object_rprimitive, "PyDict_Type"),
789 """cpy_r_r0 = (PyObject *)&PyDict_Type;""",
790 )
791
792 def test_assign_multi(self) -> None:
793 t = RArray(object_rprimitive, 2)
794 a = Register(t, "a")
795 self.registers.append(a)
796 self.assert_emit(
797 AssignMulti(a, [self.o, self.o2]), """PyObject *cpy_r_a[2] = {cpy_r_o, cpy_r_o2};"""
798 )
799
800 def test_long_unsigned(self) -> None:
801 a = Register(int64_rprimitive, "a")
802 self.assert_emit(
803 Assign(a, Integer(1 << 31, int64_rprimitive)), """cpy_r_a = 2147483648LL;"""
804 )
805 self.assert_emit(
806 Assign(a, Integer((1 << 31) - 1, int64_rprimitive)), """cpy_r_a = 2147483647;"""
807 )
808
809 def test_long_signed(self) -> None:
810 a = Register(int64_rprimitive, "a")
811 self.assert_emit(
812 Assign(a, Integer(-(1 << 31) + 1, int64_rprimitive)), """cpy_r_a = -2147483647;"""
813 )
814 self.assert_emit(
815 Assign(a, Integer(-(1 << 31), int64_rprimitive)), """cpy_r_a = -2147483648LL;"""
816 )
817
818 def test_cast_and_branch_merge(self) -> None:
819 op = Cast(self.r, dict_rprimitive, 1)
820 next_block = BasicBlock(9)
821 branch = Branch(op, BasicBlock(8), next_block, Branch.IS_ERROR)
822 branch.traceback_entry = ("foobar", 123)
823 self.assert_emit(
824 op,
825 """\
826 if (likely(PyDict_Check(cpy_r_r)))
827 cpy_r_r0 = cpy_r_r;
828 else {
829 CPy_TypeErrorTraceback("prog.py", "foobar", 123, CPyStatic_prog___globals, "dict", cpy_r_r);
830 goto CPyL8;
831 }
832 """,
833 next_block=next_block,
834 next_branch=branch,
835 skip_next=True,
836 )
837
838 def test_cast_and_branch_no_merge_1(self) -> None:
839 op = Cast(self.r, dict_rprimitive, 1)
840 branch = Branch(op, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)
841 branch.traceback_entry = ("foobar", 123)
842 self.assert_emit(
843 op,
844 """\
845 if (likely(PyDict_Check(cpy_r_r)))
846 cpy_r_r0 = cpy_r_r;
847 else {
848 CPy_TypeError("dict", cpy_r_r);
849 cpy_r_r0 = NULL;
850 }
851 """,
852 next_block=BasicBlock(10),
853 next_branch=branch,
854 skip_next=False,
855 )
856
857 def test_cast_and_branch_no_merge_2(self) -> None:
858 op = Cast(self.r, dict_rprimitive, 1)
859 next_block = BasicBlock(9)
860 branch = Branch(op, BasicBlock(8), next_block, Branch.IS_ERROR)
861 branch.negated = True
862 branch.traceback_entry = ("foobar", 123)
863 self.assert_emit(
864 op,
865 """\
866 if (likely(PyDict_Check(cpy_r_r)))
867 cpy_r_r0 = cpy_r_r;
868 else {
869 CPy_TypeError("dict", cpy_r_r);
870 cpy_r_r0 = NULL;
871 }
872 """,
873 next_block=next_block,
874 next_branch=branch,
875 )
876
877 def test_cast_and_branch_no_merge_3(self) -> None:
878 op = Cast(self.r, dict_rprimitive, 1)
879 next_block = BasicBlock(9)
880 branch = Branch(op, BasicBlock(8), next_block, Branch.BOOL)
881 branch.traceback_entry = ("foobar", 123)
882 self.assert_emit(
883 op,
884 """\
885 if (likely(PyDict_Check(cpy_r_r)))
886 cpy_r_r0 = cpy_r_r;
887 else {
888 CPy_TypeError("dict", cpy_r_r);
889 cpy_r_r0 = NULL;
890 }
891 """,
892 next_block=next_block,
893 next_branch=branch,
894 )
895
896 def test_cast_and_branch_no_merge_4(self) -> None:
897 op = Cast(self.r, dict_rprimitive, 1)
898 next_block = BasicBlock(9)
899 branch = Branch(op, BasicBlock(8), next_block, Branch.IS_ERROR)
900 self.assert_emit(
901 op,
902 """\
903 if (likely(PyDict_Check(cpy_r_r)))
904 cpy_r_r0 = cpy_r_r;
905 else {
906 CPy_TypeError("dict", cpy_r_r);
907 cpy_r_r0 = NULL;
908 }
909 """,
910 next_block=next_block,
911 next_branch=branch,
912 )
913
914 def test_extend(self) -> None:
915 a = Register(int32_rprimitive, "a")
916 self.assert_emit(Extend(a, int64_rprimitive, signed=True), """cpy_r_r0 = cpy_r_a;""")
917 self.assert_emit(
918 Extend(a, int64_rprimitive, signed=False), """cpy_r_r0 = (uint32_t)cpy_r_a;"""
919 )
920 if PLATFORM_SIZE == 4:
921 self.assert_emit(
922 Extend(self.n, int64_rprimitive, signed=True),
923 """cpy_r_r0 = (Py_ssize_t)cpy_r_n;""",
924 )
925 self.assert_emit(
926 Extend(self.n, int64_rprimitive, signed=False), """cpy_r_r0 = cpy_r_n;"""
927 )
928 if PLATFORM_SIZE == 8:
929 self.assert_emit(Extend(a, int_rprimitive, signed=True), """cpy_r_r0 = cpy_r_a;""")
930 self.assert_emit(
931 Extend(a, int_rprimitive, signed=False), """cpy_r_r0 = (uint32_t)cpy_r_a;"""
932 )
933
934 def test_inc_ref_none(self) -> None:
935 b = Box(self.none)
936 self.assert_emit([b, IncRef(b)], "" if HAVE_IMMORTAL else "CPy_INCREF(cpy_r_r0);")
937
938 def test_inc_ref_bool(self) -> None:
939 b = Box(self.b)
940 self.assert_emit([b, IncRef(b)], "" if HAVE_IMMORTAL else "CPy_INCREF(cpy_r_r0);")
941
942 def test_inc_ref_int_literal(self) -> None:
943 for x in -5, 0, 1, 5, 255, 256:
944 b = LoadLiteral(x, object_rprimitive)
945 self.assert_emit([b, IncRef(b)], "" if HAVE_IMMORTAL else "CPy_INCREF(cpy_r_r0);")
946 for x in -1123355, -6, 257, 123235345:
947 b = LoadLiteral(x, object_rprimitive)
948 self.assert_emit([b, IncRef(b)], "CPy_INCREF(cpy_r_r0);")
949
950 def test_c_string(self) -> None:
951 s = Register(cstring_rprimitive, "s")
952 self.assert_emit(Assign(s, CString(b"foo")), """cpy_r_s = "foo";""")
953 self.assert_emit(Assign(s, CString(b'foo "o')), r"""cpy_r_s = "foo \"o";""")
954 self.assert_emit(Assign(s, CString(b"\x00")), r"""cpy_r_s = "\x00";""")
955 self.assert_emit(Assign(s, CString(b"\\")), r"""cpy_r_s = "\\";""")
956 for i in range(256):
957 b = bytes([i])
958 if b == b"\n":
959 target = "\\n"
960 elif b == b"\r":
961 target = "\\r"
962 elif b == b"\t":
963 target = "\\t"
964 elif b == b'"':
965 target = '\\"'
966 elif b == b"\\":
967 target = "\\\\"
968 elif i < 32 or i >= 127:
969 target = "\\x%.2x" % i
970 else:
971 target = b.decode("ascii")
972 self.assert_emit(Assign(s, CString(b)), f'cpy_r_s = "{target}";')
973
974 def assert_emit(
975 self,
976 op: Op | list[Op],
977 expected: str,
978 next_block: BasicBlock | None = None,
979 *,
980 rare: bool = False,
981 next_branch: Branch | None = None,
982 skip_next: bool = False,
983 ) -> None:
984 block = BasicBlock(0)
985 if isinstance(op, Op):
986 block.ops.append(op)
987 else:
988 block.ops.extend(op)
989 op = op[-1]
990 value_names = generate_names_for_ir(self.registers, [block])
991 emitter = Emitter(self.context, value_names)
992 declarations = Emitter(self.context, value_names)
993 emitter.fragments = []
994 declarations.fragments = []
995
996 visitor = FunctionEmitterVisitor(emitter, declarations, "prog.py", "prog")
997 visitor.next_block = next_block
998 visitor.rare = rare
999 if next_branch:
1000 visitor.ops = [op, next_branch]
1001 else:
1002 visitor.ops = [op]
1003 visitor.op_index = 0
1004
1005 op.accept(visitor)
1006 frags = declarations.fragments + emitter.fragments
1007 actual_lines = [line.strip(" ") for line in frags]
1008 assert all(line.endswith("\n") for line in actual_lines)
1009 actual_lines = [line.rstrip("\n") for line in actual_lines]
1010 if not expected.strip():
1011 expected_lines = []
1012 else:
1013 expected_lines = expected.rstrip().split("\n")
1014 expected_lines = [line.strip(" ") for line in expected_lines]
1015 assert_string_arrays_equal(
1016 expected_lines, actual_lines, msg="Generated code unexpected", traceback=True
1017 )
1018 if skip_next:
1019 assert visitor.op_index == 1
1020 else:
1021 assert visitor.op_index == 0
1022
1023 def assert_emit_binary_op(
1024 self, op: str, dest: Value, left: Value, right: Value, expected: str
1025 ) -> None:
1026 if op in binary_ops:
1027 ops = binary_ops[op]
1028 for desc in ops:
1029 if is_subtype(left.type, desc.arg_types[0]) and is_subtype(
1030 right.type, desc.arg_types[1]
1031 ):
1032 args = [left, right]
1033 if desc.ordering is not None:
1034 args = [args[i] for i in desc.ordering]
1035 # This only supports primitives that map to C calls
1036 assert desc.c_function_name is not None
1037 self.assert_emit(
1038 CallC(
1039 desc.c_function_name,
1040 args,
1041 desc.return_type,
1042 desc.steals,
1043 desc.is_borrowed,
1044 desc.error_kind,
1045 55,
1046 ),
1047 expected,
1048 )
1049 return
1050 else:
1051 assert False, "Could not find matching op"
1052
1053
1054 class TestGenerateFunction(unittest.TestCase):
1055 def setUp(self) -> None:
1056 self.arg = RuntimeArg("arg", int_rprimitive)
1057 self.reg = Register(int_rprimitive, "arg")
1058 self.block = BasicBlock(0)
1059
1060 def test_simple(self) -> None:
1061 self.block.ops.append(Return(self.reg))
1062 fn = FuncIR(
1063 FuncDecl("myfunc", None, "mod", FuncSignature([self.arg], int_rprimitive)),
1064 [self.reg],
1065 [self.block],
1066 )
1067 value_names = generate_names_for_ir(fn.arg_regs, fn.blocks)
1068 emitter = Emitter(EmitterContext(NameGenerator([["mod"]]), True), value_names)
1069 generate_native_function(fn, emitter, "prog.py", "prog")
1070 result = emitter.fragments
1071 assert_string_arrays_equal(
1072 ["CPyTagged CPyDef_myfunc(CPyTagged cpy_r_arg) {\n", " return cpy_r_arg;\n", "}\n"],
1073 result,
1074 msg="Generated code invalid",
1075 )
1076
1077 def test_register(self) -> None:
1078 reg = Register(int_rprimitive)
1079 op = Assign(reg, Integer(5))
1080 self.block.ops.append(op)
1081 self.block.ops.append(Unreachable())
1082 fn = FuncIR(
1083 FuncDecl("myfunc", None, "mod", FuncSignature([self.arg], list_rprimitive)),
1084 [self.reg],
1085 [self.block],
1086 )
1087 value_names = generate_names_for_ir(fn.arg_regs, fn.blocks)
1088 emitter = Emitter(EmitterContext(NameGenerator([["mod"]]), True), value_names)
1089 generate_native_function(fn, emitter, "prog.py", "prog")
1090 result = emitter.fragments
1091 assert_string_arrays_equal(
1092 [
1093 "PyObject *CPyDef_myfunc(CPyTagged cpy_r_arg) {\n",
1094 " CPyTagged cpy_r_r0;\n",
1095 " cpy_r_r0 = 10;\n",
1096 " CPy_Unreachable();\n",
1097 "}\n",
1098 ],
1099 result,
1100 msg="Generated code invalid",
1101 )