Skip to content

Commit 10c4f27

Browse files
authored
Merge pull request #2098 from Shaikh-Ubaid/fix_cpython_cast
Fix unsigned integer cast for CPython
2 parents c472750 + c446265 commit 10c4f27

File tree

3 files changed

+44
-6
lines changed

3 files changed

+44
-6
lines changed

integration_tests/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,7 @@ RUN(NAME test_str_comparison LABELS cpython llvm c)
634634
RUN(NAME test_bit_length LABELS cpython llvm c)
635635
RUN(NAME str_to_list_cast LABELS cpython llvm c)
636636
RUN(NAME cast_01 LABELS cpython llvm c)
637+
RUN(NAME cast_02 LABELS cpython llvm c)
637638
RUN(NAME test_sys_01 LABELS cpython llvm c NOFAST)
638639
RUN(NAME intent_01 LABELS cpython llvm)
639640

integration_tests/cast_02.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from lpython import u8, u16, u32, u64
2+
3+
def test_01():
4+
x : u32 = u32(10)
5+
print(x)
6+
assert x == u32(10)
7+
8+
y: u16 = u16(x)
9+
print(y)
10+
assert y == u16(10)
11+
12+
z: u64 = u64(y)
13+
print(z)
14+
assert z == u64(10)
15+
16+
w: u8 = u8(z)
17+
print(w)
18+
assert w == u8(10)
19+
20+
def test_02():
21+
x : u64 = u64(11)
22+
print(x)
23+
assert x == u64(11)
24+
25+
y: u8 = u8(x)
26+
print(y)
27+
assert y == u8(11)
28+
29+
z: u16 = u16(y)
30+
print(z)
31+
assert z == u16(11)
32+
33+
w: u32 = u32(z)
34+
print(w)
35+
assert w == u32(11)
36+
37+
38+
def main0():
39+
test_01()
40+
test_02()
41+
42+
main0()

src/runtime/lpython/lpython.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,9 @@
1717
class UnsignedInteger:
1818
def __init__(self, bit_width, value):
1919
if isinstance(value, UnsignedInteger):
20-
if bit_width != value.bit_width:
21-
raise ValueError(f"Bit width mismatch: {bit_width} vs {value.bit_width}")
2220
value = value.value
23-
24-
if not (0 <= value < 2**bit_width):
25-
raise ValueError(f"Value should be in range 0 to {2**bit_width-1} for a {bit_width}-bit unsigned integer.")
2621
self.bit_width = bit_width
27-
self.value = value
22+
self.value = value % (2**bit_width)
2823

2924
def __bool__(self):
3025
return self.value != 0

0 commit comments

Comments
 (0)