Skip to content

Commit 91cb772

Browse files
authored
Merge pull request #1138 from Smit-create/i-1124
C: Fix negative string index
2 parents 44e62f2 + 728ce0c commit 91cb772

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

integration_tests/test_str_03.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,16 @@ def test_int():
1010
l: i64 = 4
1111
print("abc:", i, j, k, l)
1212

13+
14+
def test_issue_1124():
15+
a: str
16+
a = "012345"
17+
assert a[-1] == "5"
18+
assert a[-1] == a[5]
19+
assert a[-2] == a[4]
20+
assert a[-4] == "2"
21+
22+
1323
test_new_line()
1424
test_int()
25+
test_issue_1124()

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2686,6 +2686,19 @@ class CommonVisitor : public AST::BaseVisitor<Derived> {
26862686
}
26872687
ai.m_right = index;
26882688
if (ASRUtils::is_character(*type)) {
2689+
ASR::expr_t* val = ASRUtils::expr_value(index);
2690+
if (val && ASR::is_a<ASR::IntegerConstant_t>(*val)) {
2691+
if (ASR::down_cast<ASR::IntegerConstant_t>(val)->m_n < 0) {
2692+
// Replace `x[-1]` to `x[len(x)+(-1)]`
2693+
ASR::ttype_t *int_type = ASRUtils::TYPE(ASR::make_Integer_t(
2694+
al, loc, 4, nullptr, 0));
2695+
ASR::expr_t *list_len = ASRUtils::EXPR(ASR::make_StringLen_t(
2696+
al, loc, value, int_type, nullptr));
2697+
ASR::expr_t *neg_idx = ASRUtils::expr_value(index);
2698+
index = ASRUtils::EXPR(ASR::make_IntegerBinOp_t(al, loc,
2699+
list_len, ASR::binopType::Add, neg_idx, int_type, nullptr));
2700+
}
2701+
}
26892702
index = index_add_one(loc, index);
26902703
ai.m_right = index;
26912704
tmp = ASR::make_StringItem_t(al, loc, value, index, type, nullptr);

0 commit comments

Comments
 (0)