Skip to content

Commit bcc6a2c

Browse files
authored
Merge pull request #1917 from Smit-create/i-1915
CPython: Fix Union bugs
2 parents f7fa24f + 2d0b43b commit bcc6a2c

File tree

3 files changed

+21
-8
lines changed

3 files changed

+21
-8
lines changed

integration_tests/CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ RUN(NAME enum_06 LABELS cpython llvm c)
559559
RUN(NAME enum_07 IMPORT_PATH ..
560560
LABELS cpython llvm c)
561561
RUN(NAME union_01 LABELS cpython llvm c)
562-
RUN(NAME union_02 LABELS llvm c)
562+
RUN(NAME union_02 LABELS cpython llvm c)
563563
RUN(NAME union_03 LABELS cpython llvm c)
564564
RUN(NAME union_04 IMPORT_PATH ..
565565
LABELS cpython llvm c)

integration_tests/union_02.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ class C:
1919
@ccall
2020
@union
2121
class D(Union):
22-
a: A = A()
23-
b: B = B()
24-
c: C = C()
22+
a: A = A(0, 3.0)
23+
b: B = B(i64(0), 2.0)
24+
c: C = C(i64(0), 0.0, 1.0)
2525

2626
def test_struct_union():
2727
d: D = D()

src/runtime/lpython/lpython.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import platform
55
from dataclasses import dataclass as py_dataclass, is_dataclass as py_is_dataclass
66

7+
78
# TODO: this does not seem to restrict other imports
89
__slots__ = ["i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", "c32", "c64", "CPtr",
910
"overload", "ccall", "TypeVar", "pointer", "c_p_pointer", "Pointer",
@@ -89,10 +90,19 @@ def __init__(self, type, dims):
8990
Const = ConstType("Const")
9091
Callable = Type("Callable")
9192
Allocatable = Type("Allocatable")
92-
Union = ctypes.Union
9393
Pointer = PointerType("Pointer")
9494

9595

96+
class Union:
97+
def __init__(self):
98+
pass
99+
100+
def __setattr__(self, name: str, value):
101+
self.__dict__[name] = value
102+
103+
def __getattr__(self, name: str):
104+
return self.__dict__[name]
105+
96106
class Intent:
97107
def __init__(self, type):
98108
self._type = type
@@ -381,7 +391,6 @@ def convert_to_ctypes_Union(f):
381391
for name in f.__annotations__:
382392
ltype_ = f.__annotations__[name]
383393
fields.append((name, convert_type_to_ctype(ltype_)))
384-
385394
f._fields_ = fields
386395
f.__annotations__ = {}
387396

@@ -467,12 +476,16 @@ def inner(fn):
467476

468477
def union(f):
469478
fields = []
479+
fa = {}
470480
for name in f.__annotations__:
471481
ltype_ = f.__annotations__[name]
472-
fields.append((name, convert_type_to_ctype(ltype_)))
482+
ltype_ = convert_type_to_ctype(ltype_)
483+
fa[name] = ltype_
484+
485+
fields.append((name, ltype_))
473486

474487
f._fields_ = fields
475-
f.__annotations__ = {}
488+
f.__annotations__ = fa
476489
return f
477490

478491
def pointer(x, type_=None):

0 commit comments

Comments
 (0)