Skip to content

Commit 35c6c16

Browse files
committed
Handle negative index constants in ASR
1 parent fae10c3 commit 35c6c16

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
@@ -2586,6 +2586,19 @@ class CommonVisitor : public AST::BaseVisitor<Derived> {
25862586
}
25872587
ai.m_right = index;
25882588
if (ASRUtils::is_character(*type)) {
2589+
ASR::expr_t* val = ASRUtils::expr_value(index);
2590+
if (val && ASR::is_a<ASR::IntegerConstant_t>(*val)) {
2591+
if (ASR::down_cast<ASR::IntegerConstant_t>(val)->m_n < 0) {
2592+
// Replace `x[-1]` to `x[len(x)+(-1)]`
2593+
ASR::ttype_t *int_type = ASRUtils::TYPE(ASR::make_Integer_t(
2594+
al, loc, 4, nullptr, 0));
2595+
ASR::expr_t *list_len = ASRUtils::EXPR(ASR::make_StringLen_t(
2596+
al, loc, value, int_type, nullptr));
2597+
ASR::expr_t *neg_idx = ASRUtils::expr_value(index);
2598+
index = ASRUtils::EXPR(ASR::make_IntegerBinOp_t(al, loc,
2599+
list_len, ASR::binopType::Add, neg_idx, int_type, nullptr));
2600+
}
2601+
}
25892602
index = index_add_one(loc, index);
25902603
ai.m_right = index;
25912604
tmp = ASR::make_StringItem_t(al, loc, value, index, type, nullptr);

0 commit comments

Comments
 (0)