Skip to content

Commit 8a74b77

Browse files
Implement Negative Indexing in the ASR
1 parent 2cd0648 commit 8a74b77

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2349,6 +2349,19 @@ class CommonVisitor : public AST::BaseVisitor<Derived> {
23492349

23502350
} else if (ASR::is_a<ASR::List_t>(*type)) {
23512351
index = ASRUtils::EXPR(tmp);
2352+
ASR::expr_t* val = ASRUtils::expr_value(index);
2353+
if (val && ASR::is_a<ASR::IntegerConstant_t>(*val)) {
2354+
if (ASR::down_cast<ASR::IntegerConstant_t>(val)->m_n < 0) {
2355+
// Replace `x[-1]` to `x[len(x)+(-1)]`
2356+
ASR::ttype_t *int_type = ASRUtils::TYPE(ASR::make_Integer_t(
2357+
al, loc, 4, nullptr, 0));
2358+
ASR::expr_t *list_len = ASRUtils::EXPR(ASR::make_ListLen_t(
2359+
al, loc, value, int_type, nullptr));
2360+
ASR::expr_t *neg_idx = ASRUtils::expr_value(index);
2361+
index = ASRUtils::EXPR(ASR::make_IntegerBinOp_t(al, loc,
2362+
list_len, ASR::binopType::Add, neg_idx, int_type, nullptr));
2363+
}
2364+
}
23522365
tmp = make_ListItem_t(al, loc, value, index,
23532366
ASR::down_cast<ASR::List_t>(type)->m_type, nullptr);
23542367
return false;

0 commit comments

Comments
 (0)