Skip to content

Commit 2ee6de7

Browse files
authored
Merge pull request #1099 from Thirumalai-Shaktivel/neg_index
Implement negative indexing in Lists
2 parents 245eb5c + f8d73dd commit 2ee6de7

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

integration_tests/test_list_01.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,30 @@ def test_list_02():
4242
for j in range(len(y)):
4343
assert x[j] == y[j]
4444

45+
# Negative Indexing
46+
def test_list_03():
47+
x: list[f64] = []
48+
49+
i: i32
50+
for i in range(2):
51+
x.append(float(i))
52+
53+
assert x[1] == x[-1]
54+
assert x[0] == x[-2]
55+
assert x[-1] == 1.0
56+
assert x[-2] == 0.0
57+
58+
size: i32 = 2
59+
for i in range(100):
60+
x.append((i * size)/2)
61+
size = len(x)
62+
63+
for i in range(size):
64+
assert x[i] == x[((i-len(x)) + size) % size]
65+
4566
def tests():
4667
test_list_01()
4768
test_list_02()
69+
test_list_03()
4870

4971
tests()

src/lpython/semantics/python_ast_to_asr.cpp

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

25162516
} else if (ASR::is_a<ASR::List_t>(*type)) {
25172517
index = ASRUtils::EXPR(tmp);
2518+
ASR::expr_t* val = ASRUtils::expr_value(index);
2519+
if (val && ASR::is_a<ASR::IntegerConstant_t>(*val)) {
2520+
if (ASR::down_cast<ASR::IntegerConstant_t>(val)->m_n < 0) {
2521+
// Replace `x[-1]` to `x[len(x)+(-1)]`
2522+
ASR::ttype_t *int_type = ASRUtils::TYPE(ASR::make_Integer_t(
2523+
al, loc, 4, nullptr, 0));
2524+
ASR::expr_t *list_len = ASRUtils::EXPR(ASR::make_ListLen_t(
2525+
al, loc, value, int_type, nullptr));
2526+
ASR::expr_t *neg_idx = ASRUtils::expr_value(index);
2527+
index = ASRUtils::EXPR(ASR::make_IntegerBinOp_t(al, loc,
2528+
list_len, ASR::binopType::Add, neg_idx, int_type, nullptr));
2529+
}
2530+
}
25182531
tmp = make_ListItem_t(al, loc, value, index,
25192532
ASR::down_cast<ASR::List_t>(type)->m_type, nullptr);
25202533
return false;

0 commit comments

Comments
 (0)