Skip to content

Commit 70bc029

Browse files
Convert python slice into AST node (#73)
* add slice to to_ast * add test with oqpy variables
1 parent 4bb47dd commit 70bc029

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

oqpy/base.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,12 @@ def to_ast(program: Program, item: AstConvertible) -> ast.Expression:
507507
if program.simplify_constants:
508508
return detect_and_convert_constants(item, program)
509509
return ast.FloatLiteral(item)
510+
if isinstance(item, slice):
511+
return ast.RangeDefinition(
512+
to_ast(program, item.start) if item.start is not None else None,
513+
to_ast(program, item.stop - 1) if item.stop is not None else None,
514+
to_ast(program, item.step) if item.step is not None else None,
515+
)
510516
if isinstance(item, Iterable):
511517
return ast.ArrayLiteral([to_ast(program, i) for i in item])
512518
if isinstance(item, ast.Expression):

tests/test_directives.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2398,8 +2398,12 @@ def test_qubit_array():
23982398
prog.gate([q[0], q[1]], "cnot")
23992399
prog.gate([q[oqpy.Range(0, i)]], "cnot")
24002400

2401-
with pytest.raises(TypeError):
2402-
prog.gate([q[0:2]], "cnot")
2401+
prog.gate(q[0:2:1], "cnot")
2402+
prog.gate(q[0:2], "cnot")
2403+
prog.gate(q[0:], "cnot")
2404+
prog.gate(q[:2], "cnot")
2405+
prog.gate(q[:], "cnot")
2406+
prog.gate(q[i : i : IntVar(1, "j")], "cnot")
24032407

24042408
s = oqpy.Qubit("s")
24052409
with pytest.raises(TypeError):
@@ -2410,9 +2414,16 @@ def test_qubit_array():
24102414
OPENQASM 3.0;
24112415
qubit[2] q;
24122416
int[32] i = 2;
2417+
int[32] j = 1;
24132418
h q[0];
24142419
cnot q[0], q[1];
24152420
cnot q[0:i - 1];
2421+
cnot q[0:1:1];
2422+
cnot q[0:1];
2423+
cnot q[0:];
2424+
cnot q[:1];
2425+
cnot q[:];
2426+
cnot q[i:j:i - 1];
24162427
"""
24172428
).strip()
24182429

0 commit comments

Comments
 (0)