Commit 0f72a8695 for llama.cpp
commit 0f72a8695adfe759481a4e2f46b440e71fd255f2
Author: Nakul Lagwal <NLagwal@proton.me>
Date: Mon Nov 30 19:06:42 2026 +0530
jinja : fix negative string indexing (#33370)
* jinja : fix negative string indexing
* jinja : avoid redundant casts in negative index path
diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp
index 433707d71..12905f8a7 100644
--- a/common/jinja/runtime.cpp
+++ b/common/jinja/runtime.cpp
@@ -951,8 +951,17 @@ value member_expression::execute_impl(context & ctx) const {
val = arr->as_array().at(static_cast<size_t>(index));
}
} else { // value_string
- if (index >= 0) {
- const auto byte = cast_val<value_string>(object)->val_str.byte_at(static_cast<size_t>(index));
+ const auto * str = cast_val<value_string>(object);
+ const auto len = str->val_str.length();
+ if (index < 0) {
+ // Avoid negating INT64_MIN.
+ const uint64_t distance = static_cast<uint64_t>(-(index + 1)) + 1;
+ index = distance <= len
+ ? static_cast<int64_t>(len - distance)
+ : -1;
+ }
+ if (index >= 0 && static_cast<uint64_t>(index) < len) {
+ const auto byte = str->val_str.byte_at(static_cast<size_t>(index));
if (byte) {
val = mk_val<value_string>(std::string(1, *byte));
}
diff --git a/tests/test-jinja.cpp b/tests/test-jinja.cpp
index e86966c41..dce4f62d3 100644
--- a/tests/test-jinja.cpp
+++ b/tests/test-jinja.cpp
@@ -670,6 +670,24 @@ static void test_expressions(testing & t) {
"fedc"
);
+ test_template(t, "string index negative",
+ "{{ 'abc'[-1] }}{{ 'abc'[-2] }}{{ 'abc'[-3] }}",
+ json::object(),
+ "cba"
+ );
+
+ test_template(t, "string index negative out of range",
+ "{{ 'abc'[-4] is undefined }}{{ 'abc'[3] is undefined }}",
+ json::object(),
+ "TrueTrue"
+ );
+
+ test_template(t, "string index negative on multipart string",
+ "{% set s = a + 'bc' %}{{ s[-1] }}{{ s[-3] }}",
+ {{"a", "a"}},
+ "ca"
+ );
+
test_template(t, "string slice negative start, stop and step",
"{{ 'abcdef'[-1:-5:-1] }}",
json::object(),