Skip to content

Commit 85ced05

Browse files
authored
Merge pull request #2619 from hankluo6/array_size
Simplify array size determination for negative index
2 parents 1e5523f + 2e4057f commit 85ced05

File tree

3 files changed

+23
-8
lines changed

3 files changed

+23
-8
lines changed

integration_tests/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,7 @@ RUN(NAME array_expr_06 LABELS cpython llvm c)
435435
RUN(NAME array_expr_07 LABELS cpython llvm c)
436436
RUN(NAME array_expr_08 LABELS cpython llvm c)
437437
RUN(NAME array_expr_09 LABELS cpython llvm c)
438+
RUN(NAME array_expr_10 LABELS cpython llvm c)
438439
RUN(NAME array_size_01 LABELS cpython llvm c)
439440
RUN(NAME array_size_02 LABELS cpython llvm c)
440441
RUN(NAME array_01 LABELS cpython llvm wasm c)

integration_tests/array_expr_10.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from lpython import i32
2+
from numpy import empty, int32, array
3+
4+
def foo(x: i32[:]):
5+
print(x[3], x[4], x[-1], x[-2])
6+
assert x[-1] == 5
7+
assert x[-2] == 4
8+
assert x[-3] == 3
9+
assert x[-4] == 2
10+
assert x[-5] == 1
11+
12+
def main():
13+
x: i32[5] = empty(5, dtype=int32)
14+
x = array([1, 2, 3, 4, 5])
15+
foo(x)
16+
17+
main()

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3907,15 +3907,12 @@ class CommonVisitor : public AST::BaseVisitor<Struct> {
39073907
ASR::ttype_t *int_type = ASRUtils::TYPE(ASR::make_Integer_t(
39083908
al, loc, 4));
39093909
ASR::expr_t *neg_idx = ASRUtils::expr_value(index);
3910-
ASR::expr_t *dim_size;
3911-
if (ASRUtils::extract_physical_type(type) != ASR::array_physical_typeType::DescriptorArray)
3912-
dim_size = ASR::down_cast<ASR::Array_t>(type)->m_dims[idx].m_length;
3913-
else {
3914-
ASR::expr_t *idx_expr = ASRUtils::EXPR(ASR::make_IntegerConstant_t(al, loc, idx + 1, int_type));
3915-
dim_size = ASRUtils::EXPR(ASRUtils::make_ArraySize_t_util(al, loc, value, idx_expr, int_type, nullptr, false));
3916-
}
3910+
// null if the dimension is not known at compile time
3911+
ASR::expr_t *dim_size = ASR::down_cast<ASR::Array_t>(type)->m_dims[idx].m_length;
3912+
ASR::expr_t *idx_expr = ASRUtils::EXPR(ASR::make_IntegerConstant_t(al, loc, idx + 1, int_type));
3913+
ASR::expr_t *size_expr = ASRUtils::EXPR(ASRUtils::make_ArraySize_t_util(al, loc, value, idx_expr, int_type, dim_size, false));
39173914
index = ASRUtils::EXPR(ASR::make_IntegerBinOp_t(al, loc,
3918-
dim_size, ASR::binopType::Add, neg_idx, int_type, nullptr));
3915+
size_expr, ASR::binopType::Add, neg_idx, int_type, nullptr));
39193916
}
39203917
}
39213918
} else {

0 commit comments

Comments
 (0)