|
38 | 38 | from oqpy.program import Program
|
39 | 39 |
|
40 | 40 |
|
41 |
| -__all__ = ["If", "Else", "ForIn", "While"] |
| 41 | +__all__ = ["If", "Else", "ForIn", "While", "Range"] |
42 | 42 |
|
43 | 43 |
|
44 | 44 | @contextlib.contextmanager
|
@@ -129,18 +129,40 @@ def ForIn(
|
129 | 129 | iterator = (make_duration(i) for i in iterator)
|
130 | 130 |
|
131 | 131 | set_declaration = ast.DiscreteSet([to_ast(program, i) for i in iterator])
|
132 |
| - elif isinstance(iterator, _ClassicalVar): |
133 |
| - set_declaration = to_ast(program, iterator) |
134 |
| - assert isinstance(set_declaration, ast.Identifier), type(set_declaration) |
135 | 132 | else:
|
136 |
| - raise TypeError(f"'{type(iterator)}' object is not iterable") |
| 133 | + set_declaration = to_ast(program, iterator) |
137 | 134 |
|
138 | 135 | stmt = ast.ForInLoop(
|
139 | 136 | identifier_type.type_cls(), var.to_ast(program), set_declaration, state.body
|
140 | 137 | )
|
141 | 138 | program._add_statement(stmt)
|
142 | 139 |
|
143 | 140 |
|
| 141 | +class Range: |
| 142 | + """AstConvertible which creates an integer range. |
| 143 | +
|
| 144 | + Unlike builtin python range, this allows the components to be AstConvertible, |
| 145 | + instead of just int. |
| 146 | + """ |
| 147 | + |
| 148 | + def __init__(self, start: AstConvertible, stop: AstConvertible, step: AstConvertible = 1): |
| 149 | + self.start = start |
| 150 | + self.stop = stop |
| 151 | + self.step = step |
| 152 | + |
| 153 | + def to_ast(self, program: Program) -> ast.Expression: |
| 154 | + """Convert to an ast.RangeDefinition.""" |
| 155 | + return ast.RangeDefinition( |
| 156 | + to_ast(program, self.start), |
| 157 | + ast.BinaryExpression( |
| 158 | + lhs=to_ast(program, self.stop), |
| 159 | + op=ast.BinaryOperator["-"], |
| 160 | + rhs=ast.IntegerLiteral(value=1), |
| 161 | + ), |
| 162 | + to_ast(program, self.step) if self.step != 1 else None, |
| 163 | + ) |
| 164 | + |
| 165 | + |
144 | 166 | @contextlib.contextmanager
|
145 | 167 | def While(program: Program, condition: OQPyExpression) -> Iterator[None]:
|
146 | 168 | """Context manager for looping a repeating a portion of a program while a condition is True.
|
|
0 commit comments