From e54dbb3eefb2542a7e8e12bfc5addd2d093bab68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A0=95=EC=A4=80=EC=9A=B0?= Date: Wed, 11 Nov 2026 04:09:32 +0900 Subject: [PATCH 1/2] fix: preserve measurement-dependent subroutine return values --- .../default_simulator/openqasm/interpreter.py | 298 ++++++++++++- .../openqasm/program_context.py | 69 ++- .../openqasm/simulation_path.py | 16 +- .../openqasm/test_simulation_path.py | 24 ++ .../openqasm/test_subroutine_returns.py | 407 ++++++++++++++++++ 5 files changed, 781 insertions(+), 33 deletions(-) create mode 100644 test/unit_tests/braket/default_simulator/openqasm/test_subroutine_returns.py diff --git a/src/braket/default_simulator/openqasm/interpreter.py b/src/braket/default_simulator/openqasm/interpreter.py index 76b3c722..4d024683 100644 --- a/src/braket/default_simulator/openqasm/interpreter.py +++ b/src/braket/default_simulator/openqasm/interpreter.py @@ -12,7 +12,8 @@ # language governing permissions and limitations under the License. from collections.abc import Iterable -from copy import deepcopy +from contextlib import contextmanager +from copy import copy, deepcopy from dataclasses import fields from enum import StrEnum from functools import singledispatchmethod @@ -78,6 +79,7 @@ ContinueStatement, DiscreteSet, Expression, + ExpressionStatement, FloatLiteral, FloatType, ForInLoop, @@ -164,6 +166,8 @@ def __init__( self._warn_advanced_features = warn_advanced_features self._input_names: set[str] = set() self._output_names: set[str] = set() + self._expression_temporaries: list[str] = [] + self._next_expression_temporary = 0 def build_circuit( self, source: str, inputs: dict[str, io_type] | None = None, is_file: bool = False @@ -221,8 +225,24 @@ def _(self, node: Program) -> None: raise ValueError("braket verbatim pragma must be followed by a box statement") self.visit(node.statements) + @visit.register + def _(self, node: ExpressionStatement) -> None: + with self._expression_scope(): + expression = self._prepare_expression(node.expression) + if expression is not None: + self._expression_values(expression) + @visit.register def _(self, node: ClassicalDeclaration) -> None: + with self._expression_scope(): + node = copy(node) + if node.init_expression is not None and not isinstance( + node.init_expression, QuantumMeasurement + ): + node.init_expression = self._prepare_expression(node.init_expression) + self._declare_classical(node) + + def _declare_classical(self, node: ClassicalDeclaration) -> None: if isinstance(node.init_expression, QuantumMeasurement): # `bit b = measure q;` runs as `bit b; b = measure q;` self.visit(ClassicalDeclaration(node.type, node.identifier, None)) @@ -491,6 +511,24 @@ def inline_gate_def_body(self, body: list[QuantumStatement]) -> list[QuantumStat @visit.register def _(self, node: QuantumGate) -> None: + with self._expression_scope(): + node = copy(node) + node.arguments = self._prepare_values( + node.arguments, later=[node.modifiers, node.qubits] + ) + node.modifiers = self._prepare_modifiers(node.modifiers, later=node.qubits) + node.qubits = [ + self._prepare_reference(qubit, later=node.qubits[index + 1 :]) + for index, qubit in enumerate(node.qubits) + ] + operands = [node.arguments, node.qubits, node.modifiers] + if self.context.is_mcm_dependent(operands): + for _ in self.context.iter_classical_scopes(operands): + self._visit_quantum_gate(deepcopy(node)) + else: + self._visit_quantum_gate(node) + + def _visit_quantum_gate(self, node: QuantumGate) -> None: gate_name = node.name.name arguments = self.visit(node.arguments) modifiers = self.visit(node.modifiers) @@ -576,6 +614,15 @@ def _(self, node: QuantumGate) -> None: @visit.register def _(self, node: QuantumPhase) -> None: + with self._expression_scope(): + node = copy(node) + node.argument = self._prepare_values([node.argument], later=node.modifiers)[0] + node.modifiers = self._prepare_modifiers(node.modifiers) + operands = [node.argument, node.modifiers] + for _ in self.context.iter_classical_scopes(operands): + self._visit_quantum_phase(deepcopy(node)) + + def _visit_quantum_phase(self, node: QuantumPhase) -> None: node.argument = self.visit(node.argument) node.modifiers = self.visit(node.modifiers) if is_inverted(node): @@ -667,6 +714,12 @@ def _resolve_measurement_index(self, name: str, index: Expression) -> int | Symb @visit.register def _(self, node: ClassicalAssignment) -> None: + with self._expression_scope(): + node = copy(node) + node.rvalue = self._prepare_expression(node.rvalue) + self._assign_classical(node) + + def _assign_classical(self, node: ClassicalAssignment) -> None: if self.context.supports_midcircuit_measurement and self.context.is_mcm_dependent( node.rvalue ): @@ -709,6 +762,17 @@ def _(self, node: BitstringLiteral) -> ArrayLiteral: @visit.register def _(self, node: BranchingStatement) -> None: + with self._expression_scope(): + node = copy(node) + try: + node.condition = self._prepare_expression(node.condition) + except NameError: + if self.context.is_mcm_dependent(node.condition): + raise TypeError("Branching condition not supported.") from None + raise + self._visit_branch(node) + + def _visit_branch(self, node: BranchingStatement) -> None: self._uses_advanced_language_features = True if self.context.supports_midcircuit_measurement and self.context.is_mcm_dependent( node.condition @@ -733,6 +797,12 @@ def _(self, node: BranchingStatement) -> None: @visit.register def _(self, node: ForInLoop) -> None: + with self._expression_scope(): + node = copy(node) + node.set_declaration = self._prepare_expression(node.set_declaration) + self._visit_for_loop(node) + + def _visit_for_loop(self, node: ForInLoop) -> None: self._uses_advanced_language_features = True if self.context.supports_midcircuit_measurement and self.context.is_mcm_dependent( node.set_declaration @@ -773,6 +843,41 @@ def _(self, node: ForInLoop) -> None: @visit.register def _(self, node: WhileLoop) -> None: + if not self._has_function_call(node.while_condition): + self._visit_while_loop(node) + return + with self._expression_scope(): + original_condition = node.while_condition + iterations = 0 + while True: + prepared = self._prepare_expression(original_condition) + condition = self._expression_result(self._expression_values(prepared)) + if self.context.is_mcm_dependent(condition): + break + if not cast_to(BooleanLiteral, self.visit(condition)).value: + return + iterations += 1 + if _MAX_LOOP_ITERATIONS > 0 and iterations > _MAX_LOOP_ITERATIONS: + raise RuntimeError( + f"While loop exceeded {_MAX_LOOP_ITERATIONS} iterations " + f"during static unrolling. The loop condition may never become false." + ) + try: + self.visit(deepcopy(node.block)) + except _BreakSignal: + self.context.handle_loop_break() + return + except _ContinueSignal: + self.context.handle_loop_continue() + + def refresh_condition(): + with self._expression_scope(): + prepared = self._prepare_expression(original_condition) + self._set_temporary_values(condition.name, self._expression_values(prepared)) + + self._visit_while_loop(WhileLoop(condition, node.block), refresh_condition) + + def _visit_while_loop(self, node: WhileLoop, refresh_condition=None) -> None: self._uses_advanced_language_features = True if self.context.supports_midcircuit_measurement and self.context.is_mcm_dependent( node.while_condition @@ -781,12 +886,16 @@ def _(self, node: WhileLoop) -> None: for _ in gen: try: self.visit(deepcopy(node.block)) + if refresh_condition is not None: + refresh_condition() except _BreakSignal: self.context.handle_loop_break() gen.close() break except _ContinueSignal: self.context.handle_loop_continue() + if refresh_condition is not None: + refresh_condition() continue else: iterations = 0 @@ -873,10 +982,18 @@ def _(self, node: SubroutineDefinition) -> None: def _(self, node: FunctionCall) -> QASMNode | None: self._uses_advanced_language_features = True function_name = node.name.name - arguments = self.visit(node.arguments) if function_name in builtin_functions: - return builtin_functions[function_name](*arguments) + return builtin_functions[function_name](*self.visit(node.arguments)) function_def = self.context.get_subroutine_definition(function_name) + values = [] + for _ in self.context.iter_classical_scopes(node.arguments): + arguments = self.visit(deepcopy(node.arguments)) + values.extend(self._call_subroutine(function_def, node.arguments, arguments)) + return self._expression_result(values) if values else None + + def _call_subroutine(self, function_def, argument_nodes, arguments): + returned_values = [] + array_values = [] with self.context.enter_scope(): for arg_passed, arg_defined in zip(arguments, function_def.arguments): if isinstance(arg_defined, ClassicalArgument): @@ -891,14 +1008,16 @@ def _(self, node: FunctionCall) -> QASMNode | None: qubit_name = get_identifier_name(arg_defined.name) self.context.declare_qubit_alias(qubit_name, arg_passed) - return_value = None for statement in deepcopy(function_def.body): - visited = self.visit(statement) if isinstance(statement, ReturnStatement): - return_value = visited + if statement.expression is not None: + with self._expression_scope(): + expression = self._prepare_expression(statement.expression) + returned_values = self._expression_values(expression) break + self.visit(statement) - for arg_passed, arg_defined in zip(node.arguments, function_def.arguments): + for arg_passed, arg_defined in zip(argument_nodes, function_def.arguments): if isinstance(arg_defined, ClassicalArgument) and isinstance( arg_defined.type, ArrayReferenceType ): @@ -907,13 +1026,166 @@ def _(self, node: FunctionCall) -> QASMNode | None: identifier.indices = self.visit(identifier.indices) else: identifier = arg_passed - reference_value = self.context.get_value(arg_defined.name.name) - self.context.update_value(identifier, reference_value) - self.context.track_mcm_dependency( - get_identifier_name(identifier), reference_value - ) + array_values.append((identifier, self._expression_values(arg_defined.name))) + + # Restore caller bindings before copying reference arguments back. The + # caller and parameter may legally have identical names. + for identifier, values in array_values: + by_path = dict(values) + for _ in self.context.iter_classical_scopes(identifier): + path = self.context.active_paths[0] if self.context.active_paths else None + self.context.update_value(identifier, by_path[path]) + self.context.track_mcm_dependency(get_identifier_name(identifier), identifier) + return returned_values + + @contextmanager + def _expression_scope(self): + start = len(self._expression_temporaries) + try: + yield + finally: + for name in self._expression_temporaries[start:]: + self.context.discard_temporary(name) + del self._expression_temporaries[start:] + + def _expression_values(self, expression): + values = [] + for _ in self.context.iter_classical_scopes(expression): + value = self.visit(deepcopy(expression)) + paths = self.context.active_paths + values.extend((path, deepcopy(value)) for path in paths) + if not paths: + values.append((None, value)) + return values + + def _expression_result(self, values): + first = values[0][1] + if all(value == first for _, value in values): + return first + # These names cannot occur in source. Ordinary per-path bindings keep + # results alive only until the enclosing expression has consumed them. + name = f"@call_result_{self._next_expression_temporary}" + self._next_expression_temporary += 1 + self._expression_temporaries.append(name) + self.context.declare_temporary(name, first) + self._set_temporary_values(name, values) + return Identifier(name) + + def _set_temporary_values(self, name, values): + for path, value in values: + variable = path.get_variable(name) if path is not None else None + if variable is not None: + variable.value = value + else: + self.context.update_value(Identifier(name), value) + self.context.mark_mcm_dependent(name) + + def _prepare_values(self, expressions, later=()): + """Preserve each value before a following operand can change its inputs.""" + prepared = [] + for index, expression in enumerate(expressions): + value = self._prepare_expression(expression) + following = expressions[index + 1 :] + list(later) + if self._has_function_call(following): + value = self._expression_result(self._expression_values(value)) + prepared.append(value) + return prepared + + def _prepare_modifiers(self, modifiers, later=()): + arguments = self._prepare_values([modifier.argument for modifier in modifiers], later) + prepared = [] + for modifier, argument in zip(modifiers, arguments, strict=True): + modifier = copy(modifier) + modifier.argument = argument + prepared.append(modifier) + return prepared + + def _prepare_reference(self, expression, later=()): + """Freeze reference indices, not the referenced array or qubit value.""" + expression = copy(expression) + if isinstance(expression, IndexExpression): + if isinstance(expression.index, list): + expression.index = self._prepare_values(expression.index, later) + else: + expression.index = self._prepare_values([expression.index], later)[0] + expression.collection = self._prepare_reference(expression.collection, later) + elif isinstance(expression, IndexedIdentifier): + prepared = [] + for index, indices in enumerate(expression.indices): + following = expression.indices[index + 1 :] + list(later) + if isinstance(indices, list): + indices = self._prepare_values(indices, following) + else: + indices = self._prepare_values([indices], following)[0] + prepared.append(indices) + expression.indices = prepared + return expression + + def _prepare_expression(self, expression): + """Execute calls once, retaining per-path results in temporary bindings.""" + if not self._has_function_call(expression): + return expression + if isinstance(expression, list): + return [self._prepare_expression(item) for item in expression] + if not isinstance(expression, QASMNode): + return expression + expression = deepcopy(expression) + if isinstance(expression, FunctionCall): + prepared = [] + definition = None + if expression.name.name not in builtin_functions: + definition = self.context.get_subroutine_definition(expression.name.name) + for index, argument in enumerate(expression.arguments): + parameter = definition.arguments[index] if definition else None + by_reference = parameter is not None and ( + not isinstance(parameter, ClassicalArgument) + or isinstance(parameter.type, ArrayReferenceType) + ) + later = expression.arguments[index + 1 :] + value = ( + self._prepare_reference(argument, later) + if by_reference + else self._prepare_values([argument], later)[0] + ) + prepared.append(value) + expression.arguments = prepared + if expression.name.name in builtin_functions: + return self._expression_result(self._expression_values(expression)) + return self.visit(expression) + if isinstance(expression, BinaryExpression): + expression.lhs, expression.rhs = self._prepare_values([expression.lhs, expression.rhs]) + return expression + if isinstance(expression, RangeDefinition): + expression.start, expression.end, expression.step = self._prepare_values( + [expression.start, expression.end, expression.step] + ) + return expression + if isinstance(expression, (ArrayLiteral, DiscreteSet)): + expression.values = self._prepare_values(expression.values) + return expression + if isinstance(expression, (IndexExpression, IndexedIdentifier)): + return self._prepare_reference(expression) + for field in fields(expression): + if field.name == "span": + continue + value = getattr(expression, field.name) + if isinstance(value, QASMNode): + setattr(expression, field.name, self._prepare_expression(value)) + elif isinstance(value, list): + setattr(expression, field.name, [self._prepare_expression(item) for item in value]) + return expression - return return_value + @staticmethod + def _has_function_call(expression): + if isinstance(expression, FunctionCall): + return True + if isinstance(expression, list): + return any(Interpreter._has_function_call(item) for item in expression) + return isinstance(expression, QASMNode) and any( + Interpreter._has_function_call(getattr(expression, field.name)) + for field in fields(expression) + if field.name != "span" + ) @visit.register def _(self, node: ReturnStatement) -> QASMNode | None: diff --git a/src/braket/default_simulator/openqasm/program_context.py b/src/braket/default_simulator/openqasm/program_context.py index dd16d71c..298a62a1 100644 --- a/src/braket/default_simulator/openqasm/program_context.py +++ b/src/braket/default_simulator/openqasm/program_context.py @@ -609,6 +609,18 @@ def pop_scope(self) -> None: self.gate_table.pop_scope() self._mcm_dependent_scopes.pop() + def declare_temporary(self, name: str, value: LiteralType) -> None: + """Store an expression temporary without declaring a measurement register.""" + self.declare_variable(name, type(value), value) + + def discard_temporary(self, name: str) -> None: + """Remove a consumed expression temporary from its declaration scope.""" + for table in (self.symbol_table, self.variable_table): + for scope in table._scopes: + scope.pop(name, None) + for scope in self._mcm_dependent_scopes: + scope.discard(name) + @property def in_global_scope(self): return self.symbol_table.in_global_scope @@ -1314,6 +1326,22 @@ def __init__(self, circuit: Circuit | None = None, simulator: BaseLocalSimulator self._batch_size: int = 1 self._pending_mcm_targets: list[_PendingMeasurement] = [] + def push_scope(self) -> None: + super().push_scope() + self._enter_frame_for_active_paths() + + def pop_scope(self) -> None: + self._exit_frame_for_active_paths() + super().pop_scope() + + def declare_temporary(self, name: str, value: LiteralType) -> None: + self._store_variable(name, type(value), value, False) + + def discard_temporary(self, name: str) -> None: + super().discard_temporary(name) + for path in self._paths: + path.variables.pop(name, None) + @property def circuit(self): self._flush_pending_mcm_targets() @@ -1435,6 +1463,7 @@ def _store_variable( # Symbol table is shared across paths (type info only) self.symbol_table.add_symbol(name, symbol_type, const) + self.variable_table.add_variable(name, None) # Store value per-path as a FramedVariable for path_idx in self._active_path_indices: path = self._paths[path_idx] @@ -1545,11 +1574,13 @@ def is_initialized(self, name: str) -> bool: return super().is_initialized(name) def _bound_in_inner_scope(self, name: str) -> bool: - """Whether ``name`` is bound to a value in a non-global variable-table scope.""" - return any( - not is_none_like(scope[name]) - for scope in self.variable_table._scopes[1:] - if name in scope + """Whether a scoped qubit alias shadows the per-path classical binding.""" + return ( + any( + name in scope and not is_none_like(scope[name]) + for scope in self.variable_table._scopes[1:] + ) + and self.get_type(name) is Identifier ) def _flush_pending_mcm_for_variable(self, name: str) -> None: @@ -1902,10 +1933,12 @@ def iter_classical_scopes(self, expression): return saved_active = list(self._active_path_indices) + surviving_paths = [] for path_idx in saved_active: self._focus_on_path(path_idx) yield - self._active_path_indices = saved_active + surviving_paths.extend(self._active_path_indices) + self._active_path_indices = surviving_paths def evaluate_condition(self, condition): """Evaluate a branching condition, yielding per-path branch decisions. @@ -2184,17 +2217,19 @@ def _initialize_paths_from_circuit(self) -> None: initial_path._instructions = [copy(ins) for ins in self._circuit.instructions] initial_path.shots = self._shots - for name, value in self.variable_table.items(): - var_type = self.get_type(name) - is_const = self.get_const(name) - fv = FramedVariable( - name=name, - var_type=var_type, - value=value, - is_const=bool(is_const), - frame_number=initial_path.frame_number, - ) - initial_path.set_variable(name, fv) + for frame_number, (variables, symbols) in enumerate( + zip(self.variable_table._scopes, self.symbol_table._scopes, strict=True) + ): + for name, value in variables.items(): + symbol = symbols[name] + fv = FramedVariable( + name=name, + var_type=symbol.type, + value=value, + is_const=bool(symbol.const), + frame_number=frame_number, + ) + initial_path.set_variable(name, fv) def _branch_measurement( self, diff --git a/src/braket/default_simulator/openqasm/simulation_path.py b/src/braket/default_simulator/openqasm/simulation_path.py index 01449f3f..29ef748a 100644 --- a/src/braket/default_simulator/openqasm/simulation_path.py +++ b/src/braket/default_simulator/openqasm/simulation_path.py @@ -35,6 +35,7 @@ def __init__(self, name: str, var_type: Any, value: Any, is_const: bool, frame_n self._value = value self._is_const = is_const self._frame_number = frame_number + self.previous: FramedVariable | None = None @property def name(self) -> str: @@ -149,9 +150,13 @@ def exit_frame(self, previous_frame: int) -> None: Removes all variables declared in frames newer than `previous_frame` and restores the frame number. """ - self._variables = { - name: var for name, var in self._variables.items() if var.frame_number <= previous_frame - } + restored = {} + for name, var in self._variables.items(): + while var is not None and var.frame_number > previous_frame: + var = var.previous + if var is not None: + restored[name] = var + self._variables = restored self._frame_number = previous_frame def add_instruction(self, instruction: GateOperation) -> None: @@ -160,6 +165,11 @@ def add_instruction(self, instruction: GateOperation) -> None: def set_variable(self, name: str, var: FramedVariable) -> None: """Set a classical variable in this path's variable state.""" + previous = self._variables.get(name) + if previous is not None and previous.frame_number < var.frame_number: + var.previous = previous + elif previous is not None and previous.frame_number == var.frame_number: + var.previous = previous.previous self._variables[name] = var def get_variable(self, name: str) -> FramedVariable | None: diff --git a/test/unit_tests/braket/default_simulator/openqasm/test_simulation_path.py b/test/unit_tests/braket/default_simulator/openqasm/test_simulation_path.py index 6e1f05b9..8c1d2a7e 100644 --- a/test/unit_tests/braket/default_simulator/openqasm/test_simulation_path.py +++ b/test/unit_tests/braket/default_simulator/openqasm/test_simulation_path.py @@ -168,3 +168,27 @@ def test_nested_frames(self): path.exit_frame(frame0) assert set(path.variables.keys()) == {"a"} + + def test_shadowed_variables_are_restored_after_branching(self): + path = SimulationPath() + path.set_variable("x", FramedVariable("x", int, 99, False, 0)) + path.enter_frame() + path.set_variable("x", FramedVariable("x", int, 7, False, 1)) + child = path.branch() + child.get_variable("x").value = 9 + + path.exit_frame(0) + child.exit_frame(0) + assert path.get_variable("x").value == 99 + assert child.get_variable("x").value == 99 + child.get_variable("x").value = 100 + assert path.get_variable("x").value == 99 + + def test_replacing_same_frame_variable_retains_outer_binding(self): + path = SimulationPath() + path.set_variable("x", FramedVariable("x", int, 99, False, 0)) + path.enter_frame() + path.set_variable("x", FramedVariable("x", int, 7, False, 1)) + path.set_variable("x", FramedVariable("x", int, 9, False, 1)) + path.exit_frame(0) + assert path.get_variable("x").value == 99 diff --git a/test/unit_tests/braket/default_simulator/openqasm/test_subroutine_returns.py b/test/unit_tests/braket/default_simulator/openqasm/test_subroutine_returns.py new file mode 100644 index 00000000..4aeb1d01 --- /dev/null +++ b/test/unit_tests/braket/default_simulator/openqasm/test_subroutine_returns.py @@ -0,0 +1,407 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. + +import pytest + +from braket.default_simulator.density_matrix_simulator import DensityMatrixSimulator +from braket.default_simulator.openqasm.interpreter import Interpreter +from braket.default_simulator.state_vector_simulator import StateVectorSimulator +from braket.ir.openqasm import Program + +CHOOSE = """ +def choose(qubit p) -> int { + bit z; + int r = 123; + z = measure p; + if (z == 0) { r = 7; } else { r = 9; } + return r; +} +""" + + +@pytest.mark.parametrize("simulator_type", [StateVectorSimulator, DensityMatrixSimulator]) +def test_initialized_local_return_after_measurement(simulator_type): + source = "OPENQASM 3;" + CHOOSE + "qubit q; output int out; out = choose(q);" + outputs = simulator_type().run_openqasm(Program(source=source), shots=16).outputs + assert outputs == [{"out": 7}] * 16 + + +@pytest.mark.parametrize("shots,batch_size", [(1, 1), (32, 1), (32, 16)]) +@pytest.mark.parametrize( + "declarations,statement,expected", + [ + ("", "out = choose(q);", lambda m: 7 + 2 * m), + ("", "int local = choose(q); out = local;", lambda m: 7 + 2 * m), + ( + "def wrapper(qubit p) -> int { return choose(p) + 1; }", + "out = wrapper(q);", + lambda m: 8 + 2 * m, + ), + ( + "", + "if (choose(q) == 7) { out = 11; } else { out = 13; }", + lambda m: 11 + 2 * m, + ), + ( + "def read(qubit p) -> bit { bit b; b = measure p; return b; }", + "out = int(read(q));", + lambda m: m, + ), + ( + "def plus(int a) -> int { int r = a + 2; return r; }", + "out = plus(choose(q));", + lambda m: 9 + 2 * m, + ), + ( + "", + "out = 0; for int i in [0:choose(q)] { out += 1; }", + lambda m: 8 + 2 * m, + ), + ], + ids=["assignment", "initializer", "nested", "condition", "bit", "argument", "range"], +) +def test_measurement_dependent_subroutine_returns( + declarations, statement, expected, shots, batch_size +): + source = f""" + OPENQASM 3; + {CHOOSE} + {declarations} + qubit q; + U(pi/2, 0, pi) q; + output int out; + output bit m; + output int r; + r = 99; + {statement} + m = measure q; + """ + result = StateVectorSimulator().run_openqasm( + Program(source=source), shots=shots, batch_size=batch_size + ) + assert len(result.outputs) == shots + for output in result.outputs: + assert output["out"] == expected(output["m"]) + assert output["r"] == 99 + + +@pytest.mark.parametrize("shots", [1, 32]) +def test_repeated_calls_and_operand_order(shots): + source = """ + OPENQASM 3; + def flip(qubit p) -> int { + bit b; + b = measure p; + int r = int(b); + U(pi, 0, pi) p; + return r; + } + qubit q; + U(pi/2, 0, pi) q; + output bit initial; + initial = measure q; + output int out; + out = flip(q) * 10 + flip(q); + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=shots).outputs + assert len(outputs) == shots + for output in outputs: + assert output["out"] == 1 + 9 * output["initial"] + + +@pytest.mark.parametrize("lhs", ["", "a[0] + "]) +def test_return_and_mutable_array_copy_back_have_same_path_value(lhs): + source = ( + """ + OPENQASM 3; + def write(mutable array[int[32], #dim=1] a, qubit p) -> int { + bit b; + b = measure p; + if (b) { a[0] = 9; } else { a[0] = 7; } + return a[0]; + } + array[int[32], 1] a = {5}; + qubit q; + U(pi/2, 0, pi) q; + output int out; + output int stored; + out = """ + + lhs + + """write(a, q); + stored = a[0]; + """ + ) + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=32).outputs + assert len(outputs) == 32 + for output in outputs: + assert output["out"] == output["stored"] + (5 if lhs else 0) + assert output["stored"] in (7, 9) + + +def test_call_results_do_not_leak_into_registers_or_scopes(): + context = StateVectorSimulator().create_program_context() + context._shots = 32 + interpreter = Interpreter(context) + interpreter.run( + "OPENQASM 3;" + + CHOOSE + + """ + qubit q; + U(pi/2, 0, pi) q; + output int out; + choose(q); + out = choose(q); + """ + ) + assert interpreter._expression_temporaries == [] + assert not any( + name.startswith("@call_result_") + for scope in context.variable_table._scopes + for name in scope + ) + for path in context.active_paths: + assert not any(name.startswith("@call_result_") for name in path.variables) + assert not any( + register.name.startswith("@call_result_") + for register in context.circuit.classical_registers + ) + assert list(context._output_variables) == ["out"] + + +@pytest.mark.parametrize( + "gate", ["U(choose_angle(q[0]), 0, pi) q[1];", "ctrl @ gphase(choose_angle(q[0])) q[1];"] +) +def test_return_value_in_gate_angle(gate): + # The controlled phase is observed by surrounding it with Hadamards. + prepare = "U(pi/2, 0, pi) q[1];" if "gphase" in gate else "" + source = ( + """ + OPENQASM 3; + def choose_angle(qubit p) -> float { + bit b; + float a = 0; + b = measure p; + if (b) { a = pi; } + return a; + } + qubit[2] q; + U(pi/2, 0, pi) q[0]; + """ + + prepare + + gate + + prepare + + """ + output bit[2] out; + out = measure q; + """ + ) + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=32).outputs + assert len(outputs) == 32 + assert all(output["out"][0] == output["out"][1] for output in outputs) + + +def test_call_in_while_condition_is_evaluated_once_per_iteration(): + source = """ + OPENQASM 3; + def flip(qubit p) -> int { + bit b; + b = measure p; + int r = int(b); + U(pi, 0, pi) p; + return r; + } + qubit q; + U(pi/2, 0, pi) q; + output bit initial; + initial = measure q; + output int count; + count = 0; + while (flip(q) == 0) { count += 1; } + output bit final; + final = measure q; + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=32).outputs + assert len(outputs) == 32 + for output in outputs: + assert output["count"] == 1 - output["initial"] + assert output["final"] == 0 + + +@pytest.mark.parametrize("body", ["count += 1;", "count += 1; continue;"]) +def test_pure_call_in_while_condition_is_refreshed(body): + context = Interpreter().run( + """ + OPENQASM 3; + def below(int a) -> bool { return a < 3; } + int count = 0; + while (below(count)) { + """ + + body + + "}" + ) + assert context.get_value("count").value == 3 + + +def test_pure_call_in_while_condition_keeps_iteration_limit(monkeypatch): + monkeypatch.setattr("braket.default_simulator.openqasm.interpreter._MAX_LOOP_ITERATIONS", 3) + with pytest.raises(RuntimeError, match="exceeded 3 iterations"): + Interpreter().run("OPENQASM 3; def always() -> bool { return true; } while (always()) {}") + + +def test_call_in_reused_branch_body_runs_for_every_active_path(): + source = """ + OPENQASM 3; + def read(qubit p) -> bit { bit b; b = measure p; return b; } + qubit[2] q; + U(pi/2, 0, pi) q[0]; + U(pi/2, 0, pi) q[1]; + output bit first; + output bit second; + output bit out; + first = measure q[0]; + second = measure q[1]; + if (first == 0 || first == 1) { out = read(q[1]); } + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=128).outputs + assert len(outputs) == 128 + assert all(output["out"] == output["second"] for output in outputs) + + +def test_while_call_condition_can_become_path_dependent_after_first_iteration(): + source = """ + OPENQASM 3; + def positive(int value) -> bool { return value > 0; } + qubit q; + U(pi/2, 0, pi) q; + output bit m; + output int count; + count = 0; + int remaining = 2; + while (positive(remaining)) { + count += 1; + if (remaining == 2) { + m = measure q; + remaining = int(m); + } else { + remaining = 0; + } + } + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=64).outputs + assert len(outputs) == 64 + assert all(output["count"] == 1 + output["m"] for output in outputs) + + +def test_gate_arguments_preserve_values_before_later_call_side_effects(): + source = """ + OPENQASM 3; + def write(mutable array[float[64], #dim=1] a) -> float { + a[0] = pi; + return 0; + } + array[float[64], 1] a = {0}; + qubit q; + U(a[0], write(a), 0) q; + output bit out; + out = measure q; + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=32).outputs + assert outputs == [{"out": 0}] * 32 + + +@pytest.mark.parametrize( + "statement,expected", + [ + ("for int i in [a[0]:write(a)] { out += 1; }", 2), + ("array[int[32], 2] v = {a[0], write(a)}; out = v[0] * 10 + v[1];", 1), + ], +) +def test_ordered_value_operands_preserve_values_before_later_call(statement, expected): + source = ( + """ + OPENQASM 3; + def write(mutable array[int[32], #dim=1] a) -> int { a[0] = 3; return 1; } + array[int[32], 1] a = {0}; + output int out; + out = 0; + """ + + statement + ) + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=16).outputs + assert outputs == [{"out": expected}] * 16 + + +def test_qubit_reference_index_is_evaluated_before_later_argument_call(): + source = """ + OPENQASM 3; + def write(mutable array[int[32], #dim=1] a) -> int { a[0] = 1; return 0; } + def use(qubit p, int ignored) { x p; } + array[int[32], 1] a = {0}; + qubit[2] q; + use(q[a[0]], write(a)); + output bit[2] out; + out = measure q; + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=16).outputs + assert outputs == [{"out": [1, 0]}] * 16 + + +def test_gate_arguments_are_evaluated_before_qubit_indices(): + source = """ + OPENQASM 3; + def write(mutable array[float[64], #dim=1] a) -> int { a[0] = pi; return 0; } + array[float[64], 1] a = {0}; + qubit[1] q; + U(a[0], 0, 0) q[write(a)]; + output bit out; + out = measure q[0]; + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=16).outputs + assert outputs == [{"out": 0}] * 16 + + +@pytest.mark.parametrize( + "gate", + ["pow(write(a)) @ U(a[0], 0, 0) q[0];", "pow(a[0]) @ x q[write(a) - 1];"], +) +def test_gate_modifiers_preserve_operand_order(gate): + source = ( + """ + OPENQASM 3; + def write(mutable array[float[64], #dim=1] a) -> int { a[0] = pi; return 1; } + array[float[64], 1] a = {0}; + qubit[1] q; + """ + + gate + + """ + output bit out; + out = measure q[0]; + """ + ) + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=16).outputs + assert outputs == [{"out": 0}] * 16 + + +def test_gate_qubit_indices_are_evaluated_in_order(): + source = """ + OPENQASM 3; + def write(mutable array[int[32], #dim=1] a) -> int { a[0] = 1; return 1; } + array[int[32], 1] a = {0}; + qubit[2] q; + x q[0]; + cnot q[a[0]], q[write(a)]; + output bit[2] out; + out = measure q; + """ + outputs = StateVectorSimulator().run_openqasm(Program(source=source), shots=16).outputs + assert outputs == [{"out": [1, 1]}] * 16 From 92ceb7b66ac0a3ec260a33b7aa3f67528b4b1ff2 Mon Sep 17 00:00:00 2001 From: AJ-comp <69152847+AJ-comp@users.noreply.github.com> Date: Thu, 3 Dec 2026 06:17:32 +0000 Subject: [PATCH 2/2] fix: resolve subroutine qubit array arguments through the scope Inside a subroutine, a qubit argument is a scoped alias of the caller's qubits, but qubit operands were resolved by looking their name up in qubit_mapping, which only holds the global registers. Indexing a qubit array argument therefore failed or acted on the wrong qubits: - measure, reset and barrier on an element, slice or set of the argument raised AttributeError ('Identifier' object has no attribute 'values'), or acted on a global register with the argument's name; - passing an element or a slice of the argument to another subroutine, or aliasing it with let, raised KeyError. Resolve such operands through the scope to the qubits they refer to, and compose their indices with the alias target, so that an argument bound to part of a register, such as q[1:2] or q[{3, 1}], can be indexed like a register, and index errors name the alias. Gate operands are now resolved once. A broadcast gate call was visited again, and the operands of a builtin gate were visited again before dispatch, so an operand that was already resolved was looked up again where a gate or subroutine parameter with the name of its register shadowed it. Control qubits inserted into a gate body were captured the same way; they now get names that no program can use. A let alias declared in a subroutine was added to qubit_mapping under its own name. qubit_mapping is not scoped, so the alias replaced a register or alias of the same name from the caller: after the subroutine returned, that name still referred to the alias's qubits, and an argument that referred to the caller's alias of the same name changed inside the subroutine. An alias declared in a subroutine or a for-loop body now refers to the qubits directly, or, for a concatenation, to a register under a name that no program can use, one for each scope depth. Indexing qubits with a range or a set returned numpy integers, so the measured qubits of a result could not be serialized (GateModelTaskResult.json() raised TypeError). Index the tuple of qubits directly so that they stay ints. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ard2P3eLBmoqeX6wiw3SYi --- .../default_simulator/openqasm/interpreter.py | 142 ++++++-- .../openqasm/program_context.py | 27 +- .../openqasm/test_interpreter.py | 326 ++++++++++++++++++ .../braket/default_simulator/test_mcm.py | 182 ++++++++++ 4 files changed, 644 insertions(+), 33 deletions(-) diff --git a/src/braket/default_simulator/openqasm/interpreter.py b/src/braket/default_simulator/openqasm/interpreter.py index 4d024683..7f4509cd 100644 --- a/src/braket/default_simulator/openqasm/interpreter.py +++ b/src/braket/default_simulator/openqasm/interpreter.py @@ -119,6 +119,7 @@ from .program_context import ( AbstractProgramContext, ProgramContext, + QubitTable, _BreakSignal, _ContinueSignal, ) @@ -388,7 +389,7 @@ def _(self, node: QubitDeclaration) -> None: @visit.register def _(self, node: QuantumReset) -> None: - self.context.add_reset(list(self.context.get_qubits(self.visit(node.qubits)))) + self.context.add_reset(list(self.context.get_qubits(self._resolve_qubits(node.qubits)))) @visit.register def _(self, node: QuantumBarrier) -> None: @@ -397,28 +398,85 @@ def _(self, node: QuantumBarrier) -> None: # Convert qubit expressions to qubit indices qubits = [] for qubit_expr in node.qubits: - qubit_indices = self.context.get_qubits(self.visit(qubit_expr)) + qubit_indices = self.context.get_qubits(self._resolve_qubits(qubit_expr)) qubits.extend(qubit_indices) self.context.add_barrier(qubits) else: # Barrier with no qubits applies to all qubits self.context.add_barrier(None) - @visit.register - def _(self, node: IndexedIdentifier) -> IndexedIdentifier | LiteralType: - """Returns an identifier for qubits, value for classical identifier""" - name = node.name - indices = [] - for index in node.indices: + def _qubit_alias_target(self, name: Identifier) -> Identifier | IndexedIdentifier | None: + """Returns the qubits that ``name`` refers to if it is a qubit alias, such as a + subroutine qubit argument or a ``let`` alias, and None otherwise. A qubit register is + an alias of itself, so None is returned for it too. + + The lookup is scoped, so a subroutine argument shadows a register with the same name. + """ + try: + symbol_type = self.context.get_type(name.name) + except KeyError: + return None + if symbol_type is not Identifier: + return None + target = self.visit(name) + if isinstance(target, Identifier) and target.name == name.name: + return None + return target + + def _index_qubits( + self, name: str, target: Identifier | IndexedIdentifier, indices: list + ) -> IndexedIdentifier: + """Returns the qubits that ``name[indices]`` refers to, where ``name`` refers to the + qubits ``target``. + """ + if isinstance(target, Identifier) and target.name == name: + return IndexedIdentifier(target, indices) + # ``name`` is an alias, such as a subroutine argument bound to q[1:2]. Apply the + # indices to the positions of the register that the alias covers, and select those + # positions of the register, so that indices of every kind work and errors name the + # alias. + register = target if isinstance(target, Identifier) else target.name + positions = QubitTable() + positions[register.name] = tuple(range(self.context.qubit_mapping.get_qubit_size(register))) + part = QubitTable() + part[name] = positions.get_by_identifier(target) + selected = part.get_by_identifier(IndexedIdentifier(Identifier(name), indices)) + return IndexedIdentifier( + register, [DiscreteSet([IntegerLiteral(position) for position in selected])] + ) + + def _resolve_qubits( + self, qubits: Identifier | IndexedIdentifier + ) -> Identifier | IndexedIdentifier: + """Resolves a qubit operand as written in the program, such as ``s[1]`` where ``s`` is + a subroutine qubit argument, to the qubits it refers to. + """ + if isinstance(qubits, IndexedIdentifier): + target = self._qubit_alias_target(qubits.name) + if target is not None: + return self._index_qubits( + qubits.name.name, target, self._visit_indices(qubits.indices) + ) + return self.visit(qubits) + + def _visit_indices(self, indices: list) -> list: + visited = [] + for index in indices: if isinstance(index, DiscreteSet): self._uses_advanced_language_features = True - indices.append(index) + visited.append(index) else: for element in index: if isinstance(element, RangeDefinition): self._uses_advanced_language_features = True - indices.append([self.visit(element)]) - updated = IndexedIdentifier(name, indices) + visited.append([self.visit(element)]) + return visited + + @visit.register + def _(self, node: IndexedIdentifier) -> IndexedIdentifier | LiteralType: + """Returns an identifier for qubits, value for classical identifier""" + name = node.name + updated = IndexedIdentifier(name, self._visit_indices(node.indices)) if name.name not in self.context.qubit_mapping: return self.context.get_value_by_identifier(updated) return updated @@ -439,7 +497,8 @@ def _(self, node: IndexExpression) -> IndexedIdentifier | ArrayLiteral: if isinstance(node.collection, Identifier): # indexed QuantumArgument if isinstance(self.context.get_type(node.collection.name), type(Identifier)): - return IndexedIdentifier(node.collection, [index]) + target = self._qubit_alias_target(node.collection) + return self._index_qubits(node.collection.name, target or node.collection, [index]) var_type = self.context.get_type(get_identifier_name(node.collection)) type_width = get_type_width(var_type) collection = self.visit(node.collection) @@ -529,7 +588,6 @@ def _(self, node: QuantumGate) -> None: self._visit_quantum_gate(node) def _visit_quantum_gate(self, node: QuantumGate) -> None: - gate_name = node.name.name arguments = self.visit(node.arguments) modifiers = self.visit(node.modifiers) if self.context.in_global_scope and modifiers: @@ -542,8 +600,24 @@ def _visit_quantum_gate(self, node: QuantumGate) -> None: else: # IndexedIdentifier dereffed_name = self.visit(qubit.name) simplified_indices = self.visit(qubit.indices) - qubits.append(IndexedIdentifier(dereffed_name, simplified_indices)) + if any(isinstance(index, DiscreteSet) for index in simplified_indices): + self._uses_advanced_language_features = True + qubits.append( + self._index_qubits(qubit.name.name, dereffed_name, simplified_indices) + ) + self._apply_gate(node, arguments, modifiers, qubits) + def _apply_gate( + self, + node: QuantumGate, + arguments: list, + modifiers: list[QuantumGateModifier], + qubits: list[Identifier | IndexedIdentifier], + ) -> None: + """Applies the gate of ``node`` to qubits that are already resolved. Their names are not + looked up again, since a gate or subroutine parameter may shadow their registers. + """ + gate_name = node.name.name qubit_lengths = np.array( [self.context.qubit_mapping.get_qubit_size(qubit) for qubit in qubits] ) @@ -563,18 +637,10 @@ def _visit_quantum_gate(self, node: QuantumGate) -> None: ) else: indexed_qubits[j].indices.append([IntegerLiteral(i)]) - gate_call = QuantumGate( - modifiers, - node.name, - arguments, - indexed_qubits, - ) - self.visit(gate_call) + self._apply_gate(node, arguments, modifiers, indexed_qubits) return if self.context.is_builtin_gate(gate_name): - # to simplify indices - qubits = self.visit(qubits) self.handle_builtin_gate( gate_name, arguments, @@ -591,11 +657,18 @@ def _visit_quantum_gate(self, node: QuantumGate) -> None: ctrl_qubits = qubits[:num_ctrl] gate_qubits = qubits[num_ctrl:] + # The control qubits are added to the statements of the body, so give them + # names that no program can use. Otherwise a gate parameter with the name of + # their register would capture them when the statements are visited. + ctrl_names = [Identifier(f"{i}ctrl") for i in range(num_ctrl)] + for ctrl_name, ctrl_qubit in zip(ctrl_names, ctrl_qubits): + self.context.declare_qubit_alias(ctrl_name.name, ctrl_qubit) + modified_gate_body = modify_body( deepcopy(gate_def.body), is_inverted(node), ctrl_modifiers, - ctrl_qubits, + ctrl_names, pow_modifiers, ) @@ -645,7 +718,7 @@ def _(self, node: QuantumGateModifier) -> QuantumGateModifier: @visit.register def _(self, node: QuantumMeasurement) -> None: - return self.context.get_qubits(self.visit(node.qubit)) + return self.context.get_qubits(self._resolve_qubits(node.qubit)) @visit.register def _(self, node: Box) -> None: @@ -929,16 +1002,23 @@ def _(self, node: AliasStatement) -> None: alias_name = node.target.name if isinstance(node.value, Identifier): # Simple alias: let q1 = q - self.context.qubit_mapping[alias_name] = self.context.get_qubits(node.value) - self.context.declare_qubit_alias(alias_name, node.value) + target = self._qubit_alias_target(node.value) or node.value + qubits = self.context.get_qubits(target) elif isinstance(node.value, Concatenation): # Concatenation alias: let combined = q1 ++ q2 - lhs_qubits = tuple(self.context.get_qubits(node.value.lhs)) - rhs_qubits = tuple(self.context.get_qubits(node.value.rhs)) - self.context.qubit_mapping[alias_name] = lhs_qubits + rhs_qubits - self.context.declare_qubit_alias(alias_name, Identifier(alias_name)) + lhs = self._qubit_alias_target(node.value.lhs) or node.value.lhs + rhs = self._qubit_alias_target(node.value.rhs) or node.value.rhs + qubits = tuple(self.context.get_qubits(lhs)) + tuple(self.context.get_qubits(rhs)) + # The qubits may come from several registers, so they get a register of their own. + target = None else: raise NotImplementedError(f"Alias with {type(node.value).__name__} is not supported") + if self.context.in_global_scope: + self.context.qubit_mapping[alias_name] = qubits + target = target or Identifier(alias_name) + elif target is None: + target = self.context.add_local_qubits(alias_name, qubits) + self.context.declare_qubit_alias(alias_name, target) @visit.register def _(self, node: Include) -> None: diff --git a/src/braket/default_simulator/openqasm/program_context.py b/src/braket/default_simulator/openqasm/program_context.py index 08e6cc55..bd83849f 100644 --- a/src/braket/default_simulator/openqasm/program_context.py +++ b/src/braket/default_simulator/openqasm/program_context.py @@ -168,17 +168,19 @@ def validate_qubit_in_range(qubit: int): if len(primary_index) != 1: raise IndexError("Cannot index multiple dimensions for qubits.") primary_index = primary_index[0] + # Index the tuple of qubits directly rather than a numpy array of it, so that the + # qubits stay plain ints, which results can serialize. if isinstance(primary_index, IntegerLiteral): validate_qubit_in_range(primary_index.value) target = (self[name][primary_index.value],) elif isinstance(primary_index, RangeDefinition): - target = tuple(np.array(self[name])[convert_range_def_to_slice(primary_index)]) + target = tuple(self[name][convert_range_def_to_slice(primary_index)]) # Discrete set else: indices = convert_discrete_set_to_list(primary_index) for index in indices: validate_qubit_in_range(index) - target = tuple(np.array(self[name])[indices]) + target = tuple(self[name][index] for index in indices) if len(identifier.indices) == 1: return target @@ -811,6 +813,27 @@ def add_qubits(self, name: str, num_qubits: int | None = 1) -> None: self.num_qubits += num_qubits self.declare_qubit_alias(name, Identifier(name)) + def add_local_qubits(self, name: str, qubits: tuple[int, ...]) -> Identifier: + """ + Add the qubits of an alias that is declared in an inner scope, such as a subroutine + body, under a register name that no program can use. + + The qubit mapping is not scoped, so a register named ``name`` would replace a register + or alias of the same name from an enclosing scope, which arguments may refer to, and + would outlive the alias. The name holds the depth of the current scope, so an alias + with the same name in a nested scope gets its own register. + + Args: + name (str): The name of the alias. + qubits (tuple[int, ...]): The indices of the qubits the alias refers to. + + Returns: + Identifier: The identifier of the register that holds the qubits. + """ + register = Identifier(f"{len(self.symbol_table._scopes) - 1}{name}") + self.qubit_mapping[register.name] = qubits + return register + def get_qubits(self, qubits: Identifier | IndexedIdentifier) -> tuple[int]: """ Get qubit indices from a qubit identifier, possibly referring to a sub-index of diff --git a/test/unit_tests/braket/default_simulator/openqasm/test_interpreter.py b/test/unit_tests/braket/default_simulator/openqasm/test_interpreter.py index d4eb058b..50104b2b 100644 --- a/test/unit_tests/braket/default_simulator/openqasm/test_interpreter.py +++ b/test/unit_tests/braket/default_simulator/openqasm/test_interpreter.py @@ -1946,6 +1946,331 @@ def classical(bit[4] bits) { ) +@pytest.mark.parametrize( + "body, measured", + [ + ("bit b; b = measure arg[1];", [1]), + ("bit[2] b; b = measure arg[0:1];", [0, 1]), + ("bit[2] b; b = measure arg[{1, 0}];", [1, 0]), + ("bit[2] b; for int i in [0:1] { b[i] = measure arg[i]; }", [0, 1]), + ("bit[2] b; b[1] = measure arg[0];", [0]), + ("bit b; b = measure arg[-1];", [1]), + ], +) +@pytest.mark.parametrize( + "declaration, argument, first", + [("qubit[2] q;", "q", 0), ("qubit[3] q;", "q[1:2]", 1), ("qubit[4] q;", "q[{3, 1}]", None)], +) +def test_subroutine_qubit_array_argument_measurement(body, measured, declaration, argument, first): + """Measuring elements of a qubit array argument measures the caller's qubits, whether + the argument is a whole register or part of one.""" + qasm = f""" + def f(qubit[2] arg) {{ {body} }} + {declaration} + f({argument}); + """ + circuit = Interpreter().build_circuit(qasm) + covered = [3, 1] if first is None else [first, first + 1] + assert circuit.measured_qubits == [covered[i] for i in measured] + + +def test_subroutine_qubit_array_argument_reset(): + qasm = """ + def clear(qubit[2] arg) { + reset arg[1]; + } + qubit[3] q; + x q[2]; + clear(q[1:2]); + """ + context = Interpreter().run(qasm) + instructions = context.circuit.instructions + assert len(instructions) == 2 + assert isinstance(instructions[0], PauliX) + assert isinstance(instructions[1], Reset) + assert instructions[1].targets == (2,) + + +def test_subroutine_qubit_array_argument_barrier(): + class BarrierRecorder(ProgramContext): + def __init__(self): + super().__init__() + self.barriers = [] + + def add_barrier(self, target=None): + self.barriers.append(target) + + qasm = """ + def fence(qubit[2] arg) { + barrier arg[1], arg[0]; + } + qubit[3] q; + fence(q[1:2]); + """ + context = BarrierRecorder() + Interpreter(context=context).run(qasm) + assert context.barriers == [[2, 1]] + + +def test_subroutine_passes_element_of_qubit_array_argument(): + qasm = """ + def flip(qubit target) { + x target; + } + def peek(qubit target) -> bit { + bit b; + b = measure target; + return b; + } + def flip_and_peek_second(qubit[2] arg) -> bit { + flip(arg[1]); + return peek(arg[1]); + } + qubit[3] q; + bit result = flip_and_peek_second(q[1:2]); + """ + circuit = Interpreter().build_circuit(qasm) + assert len(circuit.instructions) == 1 + assert isinstance(circuit.instructions[0], PauliX) + assert circuit.instructions[0].targets == (2,) + assert circuit.measured_qubits == [2] + + +def test_subroutine_passes_part_of_qubit_array_argument(): + qasm = """ + def inner(qubit[2] part) { + h part; + x part[{1}]; + bit[2] b; + b = measure part[0:1]; + } + def outer(qubit[3] arg) { + inner(arg[1:2]); + } + qubit[4] q; + outer(q[1:3]); + """ + circuit = Interpreter().build_circuit(qasm) + assert [type(instruction) for instruction in circuit.instructions] == [ + Hadamard, + Hadamard, + PauliX, + ] + assert [instruction.targets for instruction in circuit.instructions] == [(2,), (3,), (3,)] + assert circuit.measured_qubits == [2, 3] + + +def test_subroutine_qubit_array_argument_index_out_of_range(): + qasm = """ + def f(qubit[2] arg) { + bit b; + b = measure arg[2]; + } + qubit[3] q; + f(q[1:2]); + """ + expected = "qubit register index `2` out of range for qubit register of length 2 `arg`." + with pytest.raises(IndexError, match=re.escape(expected)): + Interpreter().build_circuit(qasm) + + +def test_alias_of_subroutine_qubit_arguments(): + qasm = """ + def f(qubit[2] arg, qubit one) { + let a = arg; + let both = arg ++ one; + bit[2] b; + b[0] = measure a[1]; + b[1] = measure both[2]; + } + qubit[4] q; + f(q[1:2], q[0]); + """ + circuit = Interpreter().build_circuit(qasm) + assert circuit.measured_qubits == [2, 0] + + +def test_subroutine_qubit_argument_shadows_register(): + """A qubit argument named like a register refers to the caller's qubits inside the + subroutine, and the register is visible again after the subroutine returns.""" + qasm = """ + def clear(qubit[2] q) { + reset q[1]; + } + qubit[2] q; + qubit[2] r; + clear(r); + reset q[1]; + """ + context = Interpreter().run(qasm) + assert [instruction.targets for instruction in context.circuit.instructions] == [(3,), (1,)] + + +@pytest.mark.parametrize( + "statement", + [ + "bit b; b = measure r[0];", + "reset r[0];", + "barrier r[0];", + "let a = r;", + "bit[2] r; let a = r;", + ], +) +def test_names_that_are_not_qubits_raise(statement): + """Undeclared names, and names of classical variables, cannot be used as qubits.""" + with pytest.raises(KeyError, match=r"^'(Undefined key: )?r'$"): + Interpreter().build_circuit(f"qubit[2] q; {statement}") + + +def test_gate_parameter_named_like_register(): + """A gate parameter with the name of a register does not capture the register when the + register is passed to another parameter.""" + qasm = """ + gate g cin, tgt { + cnot cin, tgt; + } + qubit q0; + qubit cin; + g q0, cin; + """ + circuit = Interpreter().build_circuit(qasm) + assert len(circuit.instructions) == 1 + assert isinstance(circuit.instructions[0], CX) + assert circuit.instructions[0].targets == (0, 1) + + +def test_subroutine_parameters_named_like_other_registers(): + qasm = """ + def f(qubit[2] r, qubit[2] q) { + x q; + } + qubit[2] q; + qubit[2] r; + f(q, r); + """ + circuit = Interpreter().build_circuit(qasm) + assert [instruction.targets for instruction in circuit.instructions] == [(2,), (3,)] + + +@pytest.mark.parametrize( + "qasm, targets", + [ + ( + "gate g a, b { cnot a, b; } qubit a; qubit[2] q; ctrl @ g a, q[0], q[1];", + (0, 1, 2), + ), + ( + "gate g r, b { cnot r, b; } qubit[2] r; qubit[2] q; ctrl @ g r[0], q[0], q[1];", + (0, 2, 3), + ), + ( + ( + "gate inner a { x a; } gate outer a, b { ctrl @ inner a, b; } " + "qubit[2] a; qubit b; ctrl @ outer a[1], a[0], b;" + ), + (1, 0, 2), + ), + ], +) +def test_control_qubit_named_like_gate_parameter(qasm, targets): + """A control qubit added to the body of a gate is not captured by a gate parameter with + the name of its register.""" + circuit = Interpreter().build_circuit(qasm) + assert len(circuit.instructions) == 1 + assert circuit.instructions[0].targets == targets + + +@pytest.mark.parametrize("alias", ["let r = arg;", "let r = arg ++ one;"]) +def test_alias_in_subroutine_named_like_register(alias): + """An alias declared in a subroutine with the name of a register refers to its own qubits + inside the subroutine, and the register is visible again after the subroutine returns.""" + qasm = f""" + def f(qubit[2] arg, qubit one) {{ + {alias} + x r[0]; + }} + qubit[2] q; + qubit extra; + qubit r; + f(q, extra); + x r; + """ + circuit = Interpreter().build_circuit(qasm) + assert [instruction.targets for instruction in circuit.instructions] == [(0,), (3,)] + + +def test_alias_in_subroutine_keeps_arguments(): + """An alias declared in a subroutine does not change an argument that refers to an alias + of the same name in the caller.""" + qasm = """ + def f(qubit[2] arg, qubit a, qubit b) { + let both = a ++ b; + x arg[1]; + } + qubit[2] q; + qubit[2] r; + let both = q ++ r; + f(both[2:3], q[0], r[0]); + """ + circuit = Interpreter().build_circuit(qasm) + assert [instruction.targets for instruction in circuit.instructions] == [(3,)] + + +def test_aliases_named_alike_in_nested_subroutines(): + qasm = """ + def g(qubit a, qubit b) { + let both = b ++ a; + x both[0]; + } + def f(qubit a, qubit b) { + let both = a ++ b; + g(both[0], both[1]); + x both[0]; + } + qubit[2] q; + f(q[0], q[1]); + f(q[1], q[0]); + """ + circuit = Interpreter().build_circuit(qasm) + assert [instruction.targets for instruction in circuit.instructions] == [ + (1,), + (0,), + (0,), + (1,), + ] + + +@pytest.mark.parametrize( + "measurement", + [ + "bit[2] b; b = measure q[1:2];", + "bit b; b = measure q[{2}];", + "let view = q; bit b; b = measure view[2];", + "def f(qubit[2] arg) { bit b; b = measure arg[1]; } f(q[1:2]);", + "def f(qubit[3] arg) { bit[2] b; b = measure arg[{2, 0}]; } f(q);", + ], +) +def test_measured_qubits_are_ints(measurement): + """Measured qubits are plain ints however they are indexed, so results can serialize.""" + circuit = Interpreter().build_circuit(f"qubit[3] q; {measurement}") + assert circuit.measured_qubits + assert all(type(qubit) is int for qubit in circuit.measured_qubits) + + +def test_alias_in_subroutine_index_out_of_range(): + qasm = """ + def f(qubit a, qubit b) { + let both = a ++ b; + x both[2]; + } + qubit[2] q; + f(q[0], q[1]); + """ + expected = "qubit register index `2` out of range for qubit register of length 2 `both`." + with pytest.raises(IndexError, match=re.escape(expected)): + Interpreter().build_circuit(qasm) + + def test_builtin_functions(): qasm = """ const float[64] arccos_result = arccos(1); @@ -2080,6 +2405,7 @@ def test_noise(): ( "const int x = 4;", "qubit[2] q; h q[0:1];", + "qubit[3] q; x q[{0, 2}];", "gate my_x q { x q; }", "qubit[2] q; ctrl @ x q[0], q[1];", "qubit q; if (1) { x q; }", diff --git a/test/unit_tests/braket/default_simulator/test_mcm.py b/test/unit_tests/braket/default_simulator/test_mcm.py index 123e0f53..c3980e68 100644 --- a/test/unit_tests/braket/default_simulator/test_mcm.py +++ b/test/unit_tests/braket/default_simulator/test_mcm.py @@ -5586,3 +5586,185 @@ def test_asymmetric_path_shot_counts_preserve_alignment(self, simulator): assert set(counter) == {"01", "10"}, counter assert 800 < counter["01"] < 1200, counter assert 2800 < counter["10"] < 3200, counter + + +class TestBranchedSubroutineQubitArguments: + """Subroutine qubit arguments in programs that branch on mid-circuit measurements.""" + + def test_reset_element_of_qubit_array_argument_by_measurement(self, simulator): + qasm = """ + OPENQASM 3.0; + qubit[2] q; + output bit[2] c; + def clear_second(qubit[2] arg) { + bit m; + m = measure arg[1]; + if (m) { + x arg[1]; + } + } + x q; + clear_second(q); + c = measure q; + """ + result = simulator.run_openqasm(OpenQASMProgram(source=qasm, inputs={}), shots=100) + assert result.outputs == [{"c": [1, 0]}] * 100 + + @pytest.mark.parametrize( + "declarations, clear, after", + [ + ( + "qubit q; qubit r;", + "def clear(qubit q) { bit m; m = measure q; if (m) { x q; } }", + "x r; clear(r); x q; c[0] = measure r; c[1] = measure q;", + ), + ( + "qubit q; qubit r;", + "def clear(qubit q) { bit m; m = measure q; if (m) { x q; } }", + "x q; x r; clear(r); c[0] = measure r; c[1] = measure q;", + ), + ( + "qubit q; qubit r; def flip(qubit target) { x target; }", + "def clear(qubit q) { bit m; m = measure q; if (m) { x q; } }", + "x r; clear(r); flip(q); c[0] = measure r; c[1] = measure q;", + ), + ( + "qubit[2] q; qubit[2] r;", + "def clear(qubit[2] q) { bit m; m = measure q[0]; if (m) { x q[0]; } }", + "x r[0]; clear(r); x q[0]; c[0] = measure r[0]; c[1] = measure q[0];", + ), + ], + ) + def test_qubit_argument_out_of_scope_after_return(self, simulator, declarations, clear, after): + """A qubit argument named like a register shadows the register only inside the + subroutine, even when the subroutine branches on a mid-circuit measurement.""" + qasm = f""" + OPENQASM 3.0; + output bit[2] c; + {declarations} + {clear} + {after} + """ + result = simulator.run_openqasm(OpenQASMProgram(source=qasm, inputs={}), shots=100) + assert result.outputs == [{"c": [0, 1]}] * 100 + + @pytest.mark.parametrize( + "after", + [ + "if (k == 3) { x q[1]; }", + "bit r; r = measure q[0]; k = int(r) + 3; if (k == 4) { x q[1]; }", + ], + ) + def test_classical_variable_shadowed_by_qubit_argument(self, simulator, after): + """A classical variable keeps its value, and can still be written per path, after a + subroutine whose qubit argument has its name branches on a mid-circuit measurement.""" + qasm = f""" + OPENQASM 3.0; + qubit[2] q; + output bit[2] c; + int k = 3; + def f(qubit k) {{ bit m; m = measure k; if (m) {{ }} }} + x q[0]; + f(q[0]); + {after} + c = measure q; + """ + result = simulator.run_openqasm(OpenQASMProgram(source=qasm, inputs={}), shots=100) + assert result.outputs == [{"c": [1, 1]}] * 100 + + @pytest.mark.parametrize( + "program, expected", + [ + ( + """ + def f(qubit[2] arg) { + bit m; + h arg[1]; + m = measure arg[1]; + if (m) { x arg[1]; } + let r = arg; + x r[0]; + } + f(q); + x r; + """, + [1, 0, 1], + ), + ( + """ + let both = q ++ r; + def f(qubit[2] arg, qubit a, qubit b) { + bit m; + h a; + m = measure a; + if (m) { x a; } + let both = a ++ b; + x arg[1]; + x both[1]; + } + f(both[1:2], q[0], q[1]); + """, + [0, 1, 1], + ), + ], + ) + def test_alias_in_subroutine_after_branching(self, simulator, program, expected): + """An alias declared in a subroutine after a mid-circuit measurement refers to its own + qubits, and neither changes the arguments nor outlives the subroutine.""" + qasm = f""" + OPENQASM 3.0; + qubit[2] q; + qubit r; + output bit[3] c; + {program} + c[0] = measure q[0]; + c[1] = measure q[1]; + c[2] = measure r; + """ + result = simulator.run_openqasm(OpenQASMProgram(source=qasm, inputs={}), shots=100) + assert result.outputs == [{"c": expected}] * 100 + + @pytest.mark.parametrize( + "program, expected", + [ + ( + """ + def f(qubit arg) { + bit m; + x arg; + m = measure arg; + if (m) { int arg = 1; } + x arg; + } + f(q[1]); + """, + [0, 0], + ), + ( + """ + def f(qubit arg) { + bit m; + h arg; + m = measure arg; + if (m) { int arg = 1; } else { x arg; } + x arg; + } + f(q[1]); + """, + [0, 0], + ), + ("bit m; x q[0]; m = measure q[0]; if (m) { int q = 5; } x q[1];", [1, 1]), + ], + ) + def test_qubit_name_shadowed_in_branch(self, simulator, program, expected): + """A qubit argument or register that a block shadows with a classical variable after a + mid-circuit measurement refers to its qubits again after the block.""" + qasm = f""" + OPENQASM 3.0; + qubit[2] q; + output bit[2] c; + {program} + c = measure q; + """ + result = simulator.run_openqasm(OpenQASMProgram(source=qasm, inputs={}), shots=100) + assert result.outputs == [{"c": expected}] * 100