Skip to content

Closure scope when translating to openqasm2 #3491

@jon-wurtz

Description

@jon-wurtz

Required prerequisites

  • Consult the security policy. If reporting a security vulnerability, do not report the bug using this form. Use the process described in the policy to report the issue.
  • Make sure you've read the documentation. Your issue may be addressed there.
  • Search the issue tracker to verify that this hasn't already been reported. +1 or comment there if it has.
  • If possible, make a PR with a failing test to give us a starting point to work on!

Describe the bug

Variables declared in a function scope and captured within closure are not appropriately captured outside closure.

Steps to reproduce the bug

def make_foo():
    N = 4
    @cudaq.kernel
    def foo():
        q = cudaq.qvector(N)
        for i in range(N):
            h(q[i])
    return foo
foo_kernel = make_foo()
@cudaq.kernel
def bar():
    foo_kernel()

qasm_string = cudaq.translate(bar, format="openqasm2")

raises the error
CompilerError: <ipython-input-14-c51fd9788594>:7: error: Invalid variable name requested - 'N' is not defined within the quantum kernel it is used in. (offending source -> N)

If bar is declared within the scope of make_foo, the program works correctly

def make_bar():
    N = 4
    @cudaq.kernel
    def foo():
        q = cudaq.qvector(N)
        for i in range(N):
            h(q[i])
    return foo

    @cudaq.kernel
    def bar():
        foo()
    return bar
qasm_string = cudaq.translate(make_bar(), format="openqasm2")

Expected behavior

The translation function should work without error (make_foo and make_bar)

Is this a regression? If it is, put the last known working version (or commit) here.

Not a regression

Environment

  • CUDA-Q version:
  • Python version:
  • C++ compiler:
  • Operating system:

Suggestions

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions