Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
17 changes: 15 additions & 2 deletions mypyc/irbuild/for_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,13 @@ def find_loop_assignments(s: ForStmt) -> set[SymbolNode]:
return collector.symbols


def find_with_assignments(s: WithStmt) -> set[SymbolNode]:
"""Return the variables that a with statement may assign to."""
collector = AssignmentCollector()
s.accept(collector)
return collector.symbols


class AssignmentCollector(TraverserVisitor):
"""Collect the symbols of the variables assigned to (or deleted) in a subtree."""

Expand Down Expand Up @@ -787,13 +794,19 @@ def accept_loop_state(
of a local variable that the loop may assign to, copy it to a new register, since
the assignment must not affect the iteration (as in "for x in a: a = []").
"""
value = builder.accept(expr)
return copy_if_reassigned(builder, builder.accept(expr), reassigned, expr.line)


def copy_if_reassigned(
builder: IRBuilder, value: Value, reassigned: AbstractSet[SymbolNode], line: int
) -> Value:
"""Copy value to a new register if it's the register of a reassigned local variable."""
if isinstance(value, Register):
for symbol in reassigned:
target = builder.symtables[-1].get(symbol)
if isinstance(target, AssignmentTargetRegister) and target.register is value:
copy = Register(value.type)
builder.assign(copy, value, expr.line)
builder.assign(copy, value, line)
return copy
return value

Expand Down
25 changes: 21 additions & 4 deletions mypyc/irbuild/statement.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from __future__ import annotations

import importlib.util
from collections.abc import Callable, Sequence
from collections.abc import Callable, Sequence, Set as AbstractSet
from typing import Final

import mypy.nodes
Expand Down Expand Up @@ -40,6 +40,7 @@
ReturnStmt,
StarExpr,
StrExpr,
SymbolNode,
TempNode,
TryStmt,
TupleExpr,
Expand Down Expand Up @@ -99,7 +100,12 @@
int_borrow_friendly_op,
)
from mypyc.irbuild.constant_fold import check_native_int_final
from mypyc.irbuild.for_helpers import find_loop_assignments, for_loop_helper
from mypyc.irbuild.for_helpers import (
copy_if_reassigned,
find_loop_assignments,
find_with_assignments,
for_loop_helper,
)
from mypyc.irbuild.generator import add_raise_exception_blocks_to_generator_class
from mypyc.irbuild.nonlocalcontrol import (
ExceptNonlocalControl,
Expand Down Expand Up @@ -1133,6 +1139,7 @@ def transform_with(
body: GenFunc,
is_async: bool,
line: int,
reassigned: AbstractSet[SymbolNode],
) -> None:
# This is basically a straight transcription of the Python code in PEP 343.
# I don't actually understand why a bunch of it is the way it is.
Expand All @@ -1141,7 +1148,9 @@ def transform_with(

al = "a" if is_async else ""

mgr_v = builder.accept(expr)
# The context manager is used again after the body, so copy it if it's a local
# variable that may be assigned to (as in "with x: x = y")
mgr_v = copy_if_reassigned(builder, builder.accept(expr), reassigned, line)

if not is_async and mgr_v.type == lock_rprimitive:
transform_with_lock(builder, mgr_v, target, body, line)
Expand Down Expand Up @@ -1250,13 +1259,21 @@ def finally_body() -> None:


def transform_with_stmt(builder: IRBuilder, o: WithStmt) -> None:
reassigned = find_with_assignments(o)

# Generate separate logic for each expr in it, left to right
def generate(i: int) -> None:
if i >= len(o.expr):
builder.accept(o.body)
else:
transform_with(
builder, o.expr[i], o.target[i], lambda: generate(i + 1), o.is_async, o.line
builder,
o.expr[i],
o.target[i],
lambda: generate(i + 1),
o.is_async,
o.line,
reassigned,
)

generate(0)
Expand Down
46 changes: 46 additions & 0 deletions mypyc/test-data/irbuild-threading.test
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,49 @@ L10:
unreachable
L11:
return 1

[case testLockWithReassign]
from librt.threading import Lock

def with_lock(lk: Lock) -> None:
with lk:
lk = Lock()
[out]
def with_lock(lk):
lk, r0 :: librt.threading.Lock
r1 :: bool
r2 :: librt.threading.Lock
r3, r4, r5 :: tuple[object, object, object]
r6 :: None
r7 :: bit
L0:
r0 = lk
r1 = LibRTThreading_Lock_acquire_internal(r0)
L1:
r2 = LibRTThreading_Lock_new_internal()
lk = r2
L2:
L3:
r3 = <error> :: tuple[object, object, object]
r4 = r3
goto L5
L4: (handler for L1)
r5 = CPy_CatchError()
r4 = r5
L5:
r6 = LibRTThreading_Lock_release_internal(r0)
if is_error(r4) goto L7 else goto L6
L6:
CPy_Reraise()
unreachable
L7:
goto L11
L8: (handler for L5, L6)
if is_error(r4) goto L10 else goto L9
L9:
CPy_RestoreExcInfo(r4)
L10:
r7 = CPy_KeepPropagating()
unreachable
L11:
return 1
20 changes: 20 additions & 0 deletions mypyc/test-data/run-async.test
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,26 @@ async def test_x() -> None:
value += f
assert value == 5, value

[case testAsyncWithReassignContextManager]
from testutil import async_val

log: list[str] = []

class ConMan:
def __init__(self, name: str) -> None:
self.name = name
async def __aenter__(self) -> None:
log.append("enter " + self.name)
async def __aexit__(self, *exc: object) -> None:
log.append("exit " + self.name)

async def test_reassign_context_manager() -> None:
x = ConMan("a")
async with x:
x = ConMan("b")
await async_val(None)
assert log == ["enter a", "exit a"], log

[case testRunAsyncSpecialCases]
import asyncio

Expand Down
100 changes: 100 additions & 0 deletions mypyc/test-data/run-misc.test
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,106 @@ enter! crash
exit! a ohno
caught

[case testWithReassignContextManager]
from typing import Any, Iterator
from testutil import assertRaises

log: list[str] = []

class Native:
def __init__(self, name: str) -> None:
self.name = name
def __enter__(self) -> str:
log.append("enter " + self.name)
return self.name + "-value"
def __exit__(self, *exc: object) -> None:
log.append("exit " + self.name)

class NonNative:
def __init__(self, name: str) -> None:
self.name = name
def __enter__(self) -> str:
log.append("enter " + self.name)
return self.name + "-value"
def __exit__(self, *exc: object) -> None:
log.append("exit " + self.name)

NonNativeAny: Any = NonNative

def native_reassign() -> None:
x = Native("a")
with x:
x = Native("b")

def native_reassign_and_raise() -> None:
x = Native("a")
with x:
x = Native("b")
raise ValueError("x")

def non_native_reassign() -> None:
x: Any = NonNativeAny("a")
with x:
x = NonNativeAny("b")

def non_native_reassign_and_raise() -> None:
x: Any = NonNativeAny("a")
with x:
x = NonNativeAny("b")
raise ValueError("x")

def reassign_in_target() -> None:
x: Any = Native("a")
with x as x:
assert x == "a-value"

def reassign_in_second_target() -> None:
x: Any = Native("a")
with x, Native("b") as x:
assert x == "b-value"

def reassign_with_walrus() -> None:
x = Native("a")
with x:
if y := (x := Native("b")):
pass

def delete_in_body() -> None:
x = Native("a")
with x:
del x

def reassign_in_generator() -> Iterator[int]:
x = Native("a")
with x:
x = Native("b")
yield 1
x = Native("c")

def check(f: Any, expected: list[str]) -> None:
log.clear()
f()
assert log == expected, (f.__name__, log)

def test_reassign_context_manager() -> None:
check(native_reassign, ["enter a", "exit a"])
check(non_native_reassign, ["enter a", "exit a"])
check(reassign_in_target, ["enter a", "exit a"])
check(reassign_in_second_target, ["enter a", "enter b", "exit b", "exit a"])
check(reassign_with_walrus, ["enter a", "exit a"])
check(delete_in_body, ["enter a", "exit a"])
check(lambda: list(reassign_in_generator()), ["enter a", "exit a"])

def test_reassign_context_manager_and_raise() -> None:
log.clear()
with assertRaises(ValueError):
native_reassign_and_raise()
assert log == ["enter a", "exit a"], log
log.clear()
with assertRaises(ValueError):
non_native_reassign_and_raise()
assert log == ["enter a", "exit a"], log

[case testDisplays]
from typing import List, Set, Tuple, Sequence, Dict, Any, Mapping

Expand Down
10 changes: 10 additions & 0 deletions mypyc/test-data/run-threading.test
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,16 @@ def test_context_manager_exception() -> None:
pass
assert not lock.locked()

def test_context_manager_reassigned_in_body() -> None:
lock = Lock()
old = lock
with lock:
lock = Lock()
assert old.locked()
assert not lock.locked()
assert not old.locked()
assert not lock.locked()

def test_acquire_blocking_true() -> None:
lock = Lock()
assert lock.acquire(True)
Expand Down
Loading