Skip to content

Commit 8cd2f2a

Browse files
Adding str slicing
1 parent c251f64 commit 8cd2f2a

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

integration_tests/test_str_01.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,16 @@ def test_str_index():
2525
a = "012345"
2626
assert a[2] == "2"
2727

28+
def test_str_slice():
29+
a: str
30+
a = "012345"
31+
assert a[2:4] == "23"
32+
assert a[2:3] == a[2]
33+
2834
def check():
2935
f()
3036
test_str_concat()
3137
test_str_index()
38+
test_str_slice()
3239

3340
check()

src/libasr/codegen/asr_to_llvm.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,15 +1079,17 @@ class ASRToLLVMVisitor : public ASR::BaseVisitor<ASRToLLVMVisitor>
10791079
//throw CodeGenError("Only string(a:b) for a,b variables for now.", x.base.base.loc);
10801080
// Use the "right" index for now
10811081
this->visit_expr_wrapper(x.m_args[0].m_right, true);
1082-
llvm::Value *idx = tmp;
1082+
llvm::Value *idx2 = tmp;
1083+
this->visit_expr_wrapper(x.m_args[0].m_left, true);
1084+
llvm::Value *idx1 = tmp;
10831085
// idx = builder->CreateSub(idx, llvm::ConstantInt::get(context, llvm::APInt(32, 1)));
10841086
//std::vector<llvm::Value*> idx_vec = {llvm::ConstantInt::get(context, llvm::APInt(32, 0)), idx};
10851087
// std::vector<llvm::Value*> idx_vec = {idx};
10861088
llvm::Value *str = CreateLoad(array);
10871089
// llvm::Value *p = CreateGEP(str, idx_vec);
10881090
// TODO: Currently the string starts at the right location, but goes to the end of the original string.
10891091
// We have to allocate a new string, copy it and add null termination.
1090-
llvm::Value *p = lfortran_str_copy(str, idx, idx);
1092+
llvm::Value *p = lfortran_str_copy(str, idx1, idx2);
10911093

10921094
tmp = builder->CreateAlloca(character_type, nullptr);
10931095
builder->CreateStore(p, tmp);

src/runtime/impure/lfortran_intrinsics.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -606,8 +606,11 @@ LFORTRAN_API void _lfortran_strcat(char** s1, char** s2, char** dest)
606606

607607
// idx1 and idx2 both start from 1
608608
LFORTRAN_API char* _lfortran_str_copy(char* s, int32_t idx1, int32_t idx2) {
609-
char* dest_char = (char*)malloc(idx2-idx1+2);
610-
for (int i=idx1; i <= idx2; i++)
609+
if (idx2 == idx1) {
610+
idx2 = idx1 + 1;
611+
}
612+
char* dest_char = (char*)malloc(idx2-idx1+1);
613+
for (int i=idx1; i < idx2; i++)
611614
{
612615
dest_char[i-idx1] = s[i-1];
613616
}

0 commit comments

Comments
 (0)