Skip to content

[mypyc] Add 'range' primitive type #10307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 8, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions mypyc/codegen/emit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
is_list_rprimitive, is_dict_rprimitive, is_set_rprimitive, is_tuple_rprimitive,
is_none_rprimitive, is_object_rprimitive, object_rprimitive, is_str_rprimitive,
int_rprimitive, is_optional_type, optional_value_type, is_int32_rprimitive,
is_int64_rprimitive, is_bit_rprimitive
is_int64_rprimitive, is_bit_rprimitive, is_range_rprimitive
)
from mypyc.ir.func_ir import FuncDecl
from mypyc.ir.class_ir import ClassIR, all_concrete_classes
Expand Down Expand Up @@ -410,8 +410,8 @@ def emit_cast(self, src: str, dest: str, typ: RType, declare_dest: bool = False,

# TODO: Verify refcount handling.
if (is_list_rprimitive(typ) or is_dict_rprimitive(typ) or is_set_rprimitive(typ)
or is_float_rprimitive(typ) or is_str_rprimitive(typ) or is_int_rprimitive(typ)
or is_bool_rprimitive(typ)):
or is_str_rprimitive(typ) or is_range_rprimitive(typ) or is_float_rprimitive(typ)
or is_int_rprimitive(typ) or is_bool_rprimitive(typ)):
if declare_dest:
self.emit_line('PyObject *{};'.format(dest))
if is_list_rprimitive(typ):
Expand All @@ -420,10 +420,12 @@ def emit_cast(self, src: str, dest: str, typ: RType, declare_dest: bool = False,
prefix = 'PyDict'
elif is_set_rprimitive(typ):
prefix = 'PySet'
elif is_float_rprimitive(typ):
prefix = 'CPyFloat'
elif is_str_rprimitive(typ):
prefix = 'PyUnicode'
elif is_range_rprimitive(typ):
prefix = 'PyRange'
elif is_float_rprimitive(typ):
prefix = 'CPyFloat'
elif is_int_rprimitive(typ):
prefix = 'PyLong'
elif is_bool_rprimitive(typ) or is_bit_rprimitive(typ):
Expand Down
8 changes: 8 additions & 0 deletions mypyc/ir/rtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,10 @@ def __hash__(self) -> int:
tuple_rprimitive = RPrimitive('builtins.tuple', is_unboxed=False,
is_refcounted=True) # type: Final

# Python range object.
range_rprimitive = RPrimitive('builtins.range', is_unboxed=False,
is_refcounted=True) # type: Final


def is_tagged(rtype: RType) -> bool:
return rtype is int_rprimitive or rtype is short_int_rprimitive
Expand Down Expand Up @@ -401,6 +405,10 @@ def is_tuple_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.tuple'


def is_range_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.range'


def is_sequence_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and (
is_list_rprimitive(rtype) or is_tuple_rprimitive(rtype) or is_str_rprimitive(rtype)
Expand Down
4 changes: 3 additions & 1 deletion mypyc/irbuild/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from mypyc.ir.rtypes import (
RType, RUnion, RTuple, RInstance, object_rprimitive, dict_rprimitive, tuple_rprimitive,
none_rprimitive, int_rprimitive, float_rprimitive, str_rprimitive, bool_rprimitive,
list_rprimitive, set_rprimitive
list_rprimitive, set_rprimitive, range_rprimitive
)
from mypyc.ir.func_ir import FuncSignature, FuncDecl, RuntimeArg
from mypyc.ir.class_ir import ClassIR
Expand Down Expand Up @@ -58,6 +58,8 @@ def type_to_rtype(self, typ: Optional[Type]) -> RType:
return set_rprimitive
elif typ.type.fullname == 'builtins.tuple':
return tuple_rprimitive # Varying-length tuple
elif typ.type.fullname == 'builtins.range':
return range_rprimitive
elif typ.type in self.type_to_ir:
inst = RInstance(self.type_to_ir[typ.type])
# Treat protocols as Union[protocol, object], so that we can do fast
Expand Down
6 changes: 6 additions & 0 deletions mypyc/primitives/misc_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@
type=object_rprimitive,
src='PyBool_Type')

# Get the 'range' type object.
load_address_op(
name='builtins.range',
type=object_rprimitive,
src='PyRange_Type')

# Get the boxed Python 'None' object
none_object_op = load_address_op(
name='Py_None',
Expand Down
66 changes: 66 additions & 0 deletions mypyc/test-data/irbuild-basic.test
Original file line number Diff line number Diff line change
Expand Up @@ -3646,3 +3646,69 @@ L0:
r2 = r1 >= 0 :: signed
r3 = truncate r1: int32 to builtins.bool
return r3

[case testRangeObject]
def range_object() -> None:
r = range(4, 12, 2)
sum = 0
for i in r:
sum += i

def range_in_loop() -> None:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There probably is an existing test case for range in a for loop, so this can be removed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I cannot find the irbuild case and I'll keep this.

sum = 0
for i in range(4, 12, 2):
sum += i
[out]
def range_object():
r0, r1, r2, r3, r4, r :: object
sum :: int
r5, r6 :: object
r7, i, r8 :: int
r9 :: bit
L0:
r0 = load_address PyRange_Type
r1 = box(short_int, 8)
r2 = box(short_int, 24)
r3 = box(short_int, 4)
r4 = PyObject_CallFunctionObjArgs(r0, r1, r2, r3, 0)
r = r4
sum = 0
r5 = PyObject_GetIter(r)
L1:
r6 = PyIter_Next(r5)
if is_error(r6) goto L4 else goto L2
L2:
r7 = unbox(int, r6)
i = r7
r8 = CPyTagged_Add(sum, i)
sum = r8
L3:
goto L1
L4:
r9 = CPy_NoErrOccured()
L5:
return 1
def range_in_loop():
sum :: int
r0 :: short_int
i :: int
r1 :: bit
r2 :: int
r3 :: short_int
L0:
sum = 0
r0 = 8
i = r0
L1:
r1 = r0 < 24 :: signed
if r1 goto L2 else goto L4 :: bool
L2:
r2 = CPyTagged_Add(sum, i)
sum = r2
L3:
r3 = r0 + 4
r0 = r3
i = r3
goto L1
L4:
return 1
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two cases seem to work correctly.

2 changes: 1 addition & 1 deletion mypyc/test-data/run-dicts.test
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Dict test cases (compile and run)
# Test cases for dicts (compile and run)

[case testDictStuff]
from typing import Dict, Any, List, Set, Tuple
Expand Down
2 changes: 2 additions & 0 deletions mypyc/test-data/run-floats.test
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Test cases for floats (compile and run)

[case testStrToFloat]
def str_to_float(x: str) -> float:
return float(x)
Expand Down
18 changes: 17 additions & 1 deletion mypyc/test-data/run-loops.test
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Test cases for "for" and "while" loops (compile and run)
# Test cases for "range" objects, "for" and "while" loops (compile and run)

[case testFor]
from typing import List, Tuple
Expand Down Expand Up @@ -452,3 +452,19 @@ def bar(x: Optional[str]) -> None:
[file driver.py]
from native import bar
bar(None)

[case testRangeObject]
r1 = range(4, 12, 2)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you change this to use a test_ function without a custom driver, as that's the "modern" way to write tests.

Test also that coercion to range works, for example something like this:

def f(r: range) -> None:
    pass

r: Any = range(...)
f(r)  # OK

r = 'x'
f(r)  # Should be a TypeError

ff: Any = f
ff(r)  # Again should be a TypeError; this uses the wrapper function since the callee has type Any

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got this error after adding function def f(r: range) -> None:

run-loops.test:460: error: Function "builtins.range" is not valid as a type
run-loops.test:460: note: Perhaps you need "Callable[...]" or a callback protocol?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'll need to change the definition of range into a class in mypyc/test-data/fixtures/ir.py.

for i in r1:
print(i)
try:
r2 = range(4, 12, 0)
except ValueError as e:
assert 'range() arg 3 must not be zero' in str(e)
else:
assert False
[out]
4
6
8
10