Skip to content

Commit a4ac84d

Browse files
author
Fabrice Bellard
committed
Adjust lastIndex to leading surrogate when inside a surrogate pair in unicode RegExp (initial patch by auvred)
1 parent d9ec8f1 commit a4ac84d

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

‎libregexp.c‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3163,6 +3163,7 @@ int lre_exec(uint8_t **capture,
31633163
REExecContext s_s, *s = &s_s;
31643164
int re_flags, i, alloca_size, ret;
31653165
StackInt *stack_buf;
3166+
const uint8_t *cptr;
31663167

31673168
re_flags = lre_get_flags(bc_buf);
31683169
s->is_unicode = (re_flags & (LRE_FLAG_UNICODE | LRE_FLAG_UNICODE_SETS)) != 0;
@@ -3187,8 +3188,17 @@ int lre_exec(uint8_t **capture,
31873188
capture[i] = NULL;
31883189
alloca_size = s->stack_size_max * sizeof(stack_buf[0]);
31893190
stack_buf = alloca(alloca_size);
3191+
3192+
cptr = cbuf + (cindex << cbuf_type);
3193+
if (0 < cindex && cindex < clen && s->is_unicode) {
3194+
const uint16_t *p = (const uint16_t *)cptr;
3195+
if (is_lo_surrogate(*p) && is_hi_surrogate(p[-1])) {
3196+
cptr = (const uint8_t *)(p - 1);
3197+
}
3198+
}
3199+
31903200
ret = lre_exec_backtrack(s, capture, stack_buf, 0, bc_buf + RE_HEADER_LEN,
3191-
cbuf + (cindex << cbuf_type), FALSE);
3201+
cptr, FALSE);
31923202
lre_realloc(s->opaque, s->state_stack, 0);
31933203
return ret;
31943204
}

‎tests/test_builtin.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,23 @@ function test_regexp()
779779
/* Note: SpiderMonkey and v8 may not be correct */
780780
assert("abcAbC".replace(/[\q{BC|A}]/gvi,"X"), "XXXX");
781781
assert("abcAbC".replace(/[\q{BC|A}--a]/gvi,"X"), "aXAX");
782+
783+
/* case where lastIndex points to the second element of a
784+
surrogate pair */
785+
a = /(?:)/gu;
786+
a.lastIndex = 1;
787+
a.exec("🐱");
788+
assert(a.lastIndex, 0);
789+
790+
a.lastIndex = 1;
791+
a.exec("a\udc00");
792+
assert(a.lastIndex, 1);
793+
794+
a = /\u{10000}/vgd;
795+
a.lastIndex = 1;
796+
a = a.exec("\u{10000}_\u{10000}");
797+
assert(a.indices[0][0], 0);
798+
assert(a.indices[0][1], 2);
782799
}
783800

784801
function test_symbol()

0 commit comments

Comments
 (0)