Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Negative variable indexing do not work for lists #1533

Open
@anutosh491

Description

@anutosh491

What works

def main0():
    l: list[i32] = [1, 2, 3]
    x: i32 = 2
    print(l[1], l[-1], l[x])

main0()

(lf) anutosh491@spbhat68:~/lpython/lpython$ ./src/bin/lpython examples/expr2.py 
2 3 3

What doesn't work

(lf) anutosh491@spbhat68:~/lpython/lpython$ cat examples/expr2.py 
def main0():
    l: list[i32] = [1, 2, 3]
    x: i32 = -2
    print(l[x])

main0()

(lf) anutosh491@spbhat68:~/lpython/lpython$ ./src/bin/lpython examples/expr2.py 
IndexError: List index is out of range. Index range is (0, 2), but the given index is -2

(lf) anutosh491@spbhat68:~/lpython/lpython$ python examples/expr2.py 
2

So basically what's happening is , it follows the expected code flow and through the code block responsible for handling negative indexing . But here the val comes out to be a null pointer when indexing is done through a variable .

} else if (ASR::is_a<ASR::List_t>(*type)) {
index = ASRUtils::EXPR(tmp);
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)]`

The positive index remains unaffected though (it skips this block ) and still works out well through the code which follows

tmp = make_ListItem_t(al, loc, value, index,
                                      ASR::down_cast<ASR::List_t>(type)->m_type, nullptr);
                return false;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions