Skip to content

Commit

Permalink
Merge pull request lcompilers#1138 from Smit-create/i-1124
Browse files Browse the repository at this point in the history
C: Fix negative string index
  • Loading branch information
certik committed Sep 23, 2022
2 parents 44e62f2 + 728ce0c commit 91cb772
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
11 changes: 11 additions & 0 deletions integration_tests/test_str_03.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,16 @@ def test_int():
l: i64 = 4
print("abc:", i, j, k, l)


def test_issue_1124():
a: str
a = "012345"
assert a[-1] == "5"
assert a[-1] == a[5]
assert a[-2] == a[4]
assert a[-4] == "2"


test_new_line()
test_int()
test_issue_1124()
13 changes: 13 additions & 0 deletions src/lpython/semantics/python_ast_to_asr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2686,6 +2686,19 @@ class CommonVisitor : public AST::BaseVisitor<Derived> {
}
ai.m_right = index;
if (ASRUtils::is_character(*type)) {
ASR::expr_t* val = ASRUtils::expr_value(index);
if (val && ASR::is_a<ASR::IntegerConstant_t>(*val)) {
if (ASR::down_cast<ASR::IntegerConstant_t>(val)->m_n < 0) {
// Replace `x[-1]` to `x[len(x)+(-1)]`
ASR::ttype_t *int_type = ASRUtils::TYPE(ASR::make_Integer_t(
al, loc, 4, nullptr, 0));
ASR::expr_t *list_len = ASRUtils::EXPR(ASR::make_StringLen_t(
al, loc, value, int_type, nullptr));
ASR::expr_t *neg_idx = ASRUtils::expr_value(index);
index = ASRUtils::EXPR(ASR::make_IntegerBinOp_t(al, loc,
list_len, ASR::binopType::Add, neg_idx, int_type, nullptr));
}
}
index = index_add_one(loc, index);
ai.m_right = index;
tmp = ASR::make_StringItem_t(al, loc, value, index, type, nullptr);
Expand Down

0 comments on commit 91cb772

Please sign in to comment.