Skip to content

Convert python slice into AST node #73

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 2 commits into from
Sep 27, 2023
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
6 changes: 6 additions & 0 deletions oqpy/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,12 @@ def to_ast(program: Program, item: AstConvertible) -> ast.Expression:
if program.simplify_constants:
return detect_and_convert_constants(item, program)
return ast.FloatLiteral(item)
if isinstance(item, slice):
return ast.RangeDefinition(
to_ast(program, item.start) if item.start is not None else None,
to_ast(program, item.stop - 1) if item.stop is not None else None,
to_ast(program, item.step) if item.step is not None else None,
)
if isinstance(item, Iterable):
return ast.ArrayLiteral([to_ast(program, i) for i in item])
if isinstance(item, ast.Expression):
Expand Down
15 changes: 13 additions & 2 deletions tests/test_directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -2398,8 +2398,12 @@ def test_qubit_array():
prog.gate([q[0], q[1]], "cnot")
prog.gate([q[oqpy.Range(0, i)]], "cnot")

with pytest.raises(TypeError):
prog.gate([q[0:2]], "cnot")
prog.gate(q[0:2:1], "cnot")
prog.gate(q[0:2], "cnot")
prog.gate(q[0:], "cnot")
prog.gate(q[:2], "cnot")
prog.gate(q[:], "cnot")
prog.gate(q[i : i : IntVar(1, "j")], "cnot")

s = oqpy.Qubit("s")
with pytest.raises(TypeError):
Expand All @@ -2410,9 +2414,16 @@ def test_qubit_array():
OPENQASM 3.0;
qubit[2] q;
int[32] i = 2;
int[32] j = 1;
h q[0];
cnot q[0], q[1];
cnot q[0:i - 1];
cnot q[0:1:1];
cnot q[0:1];
cnot q[0:];
cnot q[:1];
cnot q[:];
cnot q[i:j:i - 1];
"""
).strip()

Expand Down