Skip to content
Merged
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
55 changes: 52 additions & 3 deletions mypyc/irbuild/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,10 @@ def __init__(
# keep the names unique within the module
self.generated_class_names: set[str] = set()
self.options = options
# Nodes passed to accept() so far, if strict_accept_checks is enabled (test only)
self.accepted_nodes: set[Statement | Expression] | None = (
set() if options.strict_accept_checks else None
)

# Keep track of the number of lambdas instantiated so we avoid name conflicts.
self.lambda_counter = 0
Expand Down Expand Up @@ -351,18 +355,38 @@ def set_module(self, module_name: str, module_path: str) -> None:
self.builder.set_module(module_name, module_path)

@overload
def accept(self, node: Expression, *, can_borrow: bool = False) -> Value: ...
def accept(
self, node: Expression, *, can_borrow: bool = False, allow_duplicate: bool = False
) -> Value: ...

@overload
def accept(self, node: Statement) -> None: ...
def accept(self, node: Statement, *, allow_duplicate: bool = False) -> None: ...

def accept(self, node: Statement | Expression, *, can_borrow: bool = False) -> Value | None:
def accept(
self,
node: Statement | Expression,
*,
can_borrow: bool = False,
allow_duplicate: bool = False,
) -> Value | None:
"""Transform an expression or a statement.

If can_borrow is true, prefer to generate a borrowed reference.
Borrowed references are faster since they don't require reference count
manipulation, but they are only safe to use in specific contexts.

If allow_duplicate is true, node may have been transformed before, since we
intentionally generate another copy of the code (only matters if
strict_accept_checks is enabled, see allow_duplicate_accepts()).
"""
if self.accepted_nodes is not None:
if allow_duplicate:
with self.allow_duplicate_accepts():
if isinstance(node, Expression):
return self.accept(node, can_borrow=can_borrow)
self.accept(node)
return None
self.check_not_accepted(node)
with self.catch_errors(node.line):
if isinstance(node, Expression):
self.expression_depth += 1
Expand Down Expand Up @@ -396,6 +420,31 @@ def accept(self, node: Statement | Expression, *, can_borrow: bool = False) -> V
pass
return None

@contextmanager
def allow_duplicate_accepts(self) -> Iterator[None]:
"""Allow transforming nodes that were transformed before (strict_accept_checks).

Use this when intentionally generating another copy of some code, such as a
second version of a function. Nodes transformed in the block are still checked
against each other, so that a node evaluated twice within the copy is caught.
"""
old = self.accepted_nodes
if old is not None:
self.accepted_nodes = set()
try:
yield
finally:
self.accepted_nodes = old

def check_not_accepted(self, node: Statement | Expression) -> None:
"""Assert that node hasn't been transformed before (strict_accept_checks only)."""
assert self.accepted_nodes is not None
assert node not in self.accepted_nodes, (
f"{type(node).__name__} accepted twice "
f"({self.module_path}, line {node.line}), so it may be evaluated twice"
)
self.accepted_nodes.add(node)

def flush_keep_alives(self, line: int, *, scope: int = KEEP_ALIVE_SHORT_LIVED) -> None:
self.builder.flush_keep_alives(line, scope=scope)

Expand Down
5 changes: 4 additions & 1 deletion mypyc/irbuild/classdef.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,10 @@ def generate_attr_defaults_init(
origin_module if origin_module != builder.module_name else None
)
try:
val = builder.coerce(builder.accept(stmt.rvalue), attr_type, stmt.line)
# The rvalue was also transformed in the class body.
val = builder.coerce(
builder.accept(stmt.rvalue, allow_duplicate=True), attr_type, stmt.line
)
finally:
builder.globals_lookup_module = None
init = SetAttr(self_var, lvalue.name, val, stmt.rvalue.line)
Expand Down
4 changes: 3 additions & 1 deletion mypyc/irbuild/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,9 @@ def handle_non_ext_method(
class_ir = builder.mapper.type_to_ir[cdef.info]
name = FAST_PREFIX + fdef.name
if name in class_ir.method_decls:
func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef, make_ext_method=True)
# This is a second copy of the method, so it transforms the same nodes again.
with builder.allow_duplicate_accepts():
func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef, make_ext_method=True)
class_ir.methods[name] = func_ir
builder.functions.append(func_ir)

Expand Down
4 changes: 4 additions & 0 deletions mypyc/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ def __init__(
depends_on_librt_internal: bool = False,
experimental_features: bool = False,
strict_traceback_checks: bool = False,
strict_accept_checks: bool = False,
target_python: TargetPython | None = None,
) -> None:
self.strip_asserts = strip_asserts
Expand Down Expand Up @@ -172,3 +173,6 @@ def __init__(
# tests to make sure that no new code which leads to incorrect tracebacks is
# added.
self.strict_traceback_checks = strict_traceback_checks
# If enabled, assert that no AST node is transformed into IR more than once,
# since that usually means it's evaluated twice at runtime. Only for tests.
self.strict_accept_checks = strict_accept_checks
1 change: 1 addition & 0 deletions mypyc/test/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ def run_case_step(self, testcase: DataDrivenTestCase, incremental_step: int) ->
depends_on_librt_internal=librt_internal,
experimental_features=experimental_features,
strict_traceback_checks=True,
strict_accept_checks=True,
)
result = emitmodule.parse_and_typecheck(
sources=sources,
Expand Down
1 change: 1 addition & 0 deletions mypyc/test/testutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ def infer_ir_build_options_from_test_name(name: str) -> CompilerOptions | None:
options = CompilerOptions(
strip_asserts="StripAssert" in name,
strict_traceback_checks=True,
strict_accept_checks=True,
target_python=infer_target_python_from_test_name(name),
)
if has_test_name_tag(name, "experimental"):
Expand Down
Loading