Skip to content

C: Fix negative string index #1138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 23, 2022
Merged

C: Fix negative string index #1138

merged 2 commits into from
Sep 23, 2022

Conversation

Smit-create
Copy link
Collaborator

Fixes #1124

@Smit-create Smit-create changed the title Handle constant negative string index in ASR C: Fix negative string index Sep 23, 2022
@Smit-create Smit-create added bug Something isn't working c Label for C language related changes labels Sep 23, 2022
# runtime tests
k: i32 = len(a); i: i32
for i in range(k):
assert a[-i-1] == a[k-i-1]
Copy link
Contributor

@certik certik Sep 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the same reason as discussed in the PR for negative list indices, we should not allow runtime negative string indices, because they can't be implemented in LLVM/C with high performance (that is, without an extra check for every index access).

We can however allow compile time negative value, because there is no runtime penalty.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh okay, get it. I'll revert the last two commits.

@@ -806,8 +806,9 @@ R"(
std::string idx = std::move(src);
this->visit_expr(*x.m_arg);
std::string str = std::move(src);
idx = "((" + idx + " - 1) >= 0 ? (" + idx + " - 1) : (strlen(" + str + ") + " + idx + " - 1))";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change should not be done, as it slows down every index access, see above.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed this. Thanks!

Copy link
Contributor

@certik certik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good!

@certik certik merged commit 91cb772 into lcompilers:main Sep 23, 2022
@Smit-create Smit-create deleted the i-1124 branch September 24, 2022 06:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working c Label for C language related changes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

visit_StringItem bug -C backend
3 participants