Skip to content

Commit 11e2f0b

Browse files
authored
Merge pull request #1883 from Smit-create/i-1882
ASR: Support Constant List iteration
2 parents 29b40b1 + c41a398 commit 11e2f0b

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

integration_tests/test_list_11.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,20 @@
33
def return_empty_list_of_tuples() -> list[i32]:
44
return []
55

6+
7+
def test_issue_1882():
8+
i: i32
9+
x: list[i32]
10+
x = [2, 3, 4]
11+
for i in [1, 2, 3]:
12+
assert i + 1 == x[i - 1]
13+
14+
615
def main0():
716
x: list[i32] = return_empty_list_of_tuples()
817
print(len(x))
918

1019
assert len(x) == 0
20+
test_issue_1882()
1121

1222
main0()

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5200,6 +5200,34 @@ class BodyVisitor : public CommonVisitor<BodyVisitor> {
52005200
throw SemanticError("Only Name is supported for Subscript",
52015201
sbt->base.base.loc);
52025202
}
5203+
} else if (AST::is_a<AST::List_t>(*x.m_iter)) {
5204+
visit_expr(*x.m_iter);
5205+
ASR::expr_t *target = ASRUtils::EXPR(tmp);
5206+
ASR::ttype_t *loop_src_var_ttype = ASRUtils::expr_type(target);
5207+
5208+
// Create a temporary variable that will contain the evaluated value of List
5209+
std::string tmp_assign_name = current_scope->get_unique_name("__tmp_assign_for_loop");
5210+
SetChar variable_dependencies_vec;
5211+
variable_dependencies_vec.reserve(al, 1);
5212+
ASRUtils::collect_variable_dependencies(al, variable_dependencies_vec, loop_src_var_ttype);
5213+
ASR::asr_t* tmp_assign_variable = ASR::make_Variable_t(al, target->base.loc, current_scope,
5214+
s2c(al, tmp_assign_name), variable_dependencies_vec.p, variable_dependencies_vec.size(),
5215+
ASR::intentType::Local, nullptr, nullptr, ASR::storage_typeType::Default,
5216+
loop_src_var_ttype, nullptr, ASR::abiType::Source, ASR::accessType::Public, ASR::presenceType::Required, false
5217+
);
5218+
ASR::symbol_t *tmp_assign_variable_sym = ASR::down_cast<ASR::symbol_t>(tmp_assign_variable);
5219+
current_scope->add_symbol(tmp_assign_name, tmp_assign_variable_sym);
5220+
5221+
// Assign the List expr to temporary variable
5222+
ASR::asr_t* assign = ASR::make_Assignment_t(al, x.base.base.loc,
5223+
ASRUtils::EXPR(ASR::make_Var_t(al, x.base.base.loc, tmp_assign_variable_sym)),
5224+
target, nullptr);
5225+
current_body->push_back(al, ASRUtils::STMT(assign));
5226+
loop_end = for_iterable_helper(tmp_assign_name, x.base.base.loc);
5227+
for_iter_type = loop_end;
5228+
LCOMPILERS_ASSERT(loop_end);
5229+
loop_src_var_name = tmp_assign_name;
5230+
is_explicit_iterator_required = true;
52035231
} else {
52045232
throw SemanticError("Only function call `range(..)` supported as for loop iteration for now",
52055233
x.base.base.loc);

0 commit comments

Comments
 (0)