From: Dmitry Volyntsev Date: Tue, 14 Apr 2020 12:43:09 +0000 (+0000) Subject: Fixed String.prototype.replace() when function returns non-string. X-Git-Tag: 0.4.0~7 X-Git-Url: http://www.kaiwu.me/postgresql/commit/?a=commitdiff_plain;h=8a1ab45848edba012c3f54c6d0db67545c1bf82b;p=njs.git Fixed String.prototype.replace() when function returns non-string. This closes #303 issue on Github. --- diff --git a/src/njs_string.c b/src/njs_string.c index 9bc2990e..7e431a2d 100644 --- a/src/njs_string.c +++ b/src/njs_string.c @@ -3718,33 +3718,34 @@ njs_string_replace_regexp_function(njs_vm_t *vm, njs_value_t *this, r->part[0].size = captures[0]; ret = njs_function_apply(vm, r->function, arguments, n + 3, &r->retval); - if (njs_slow_path(ret != NJS_OK)) { - return ret; + goto exception; } - (void) njs_string_prop(&string, this); - - if (njs_is_string(&r->retval)) { - njs_string_replacement_copy(&r->part[r->empty ? 0 : 1], &r->retval); + if (njs_slow_path(!njs_is_string(&r->retval))) { + ret = njs_value_to_string(vm, &r->retval, &r->retval); + if (njs_slow_path(ret != NJS_OK)) { + goto exception; + } + } - if (njs_regexp_pattern(regex)->global) { - r->part += 2; + njs_string_replacement_copy(&r->part[r->empty ? 0 : 1], &r->retval); - if (r->part[0].start > (string.start + string.size)) { - return njs_string_replace_regexp_join(vm, r); - } + if (njs_regexp_pattern(regex)->global) { + r->part += 2; - return njs_string_replace_regexp(vm, this, regex, r); + if (r->part[0].start > (string.start + string.size)) { + return njs_string_replace_regexp_join(vm, r); } - return njs_string_replace_regexp_join(vm, r); + return njs_string_replace_regexp(vm, this, regex, r); } - njs_regex_match_data_free(r->match_data, vm->regex_context); + return njs_string_replace_regexp_join(vm, r); - njs_internal_error(vm, "unexpected retval type:%s", - njs_type_string(r->retval.type)); +exception: + + njs_regex_match_data_free(r->match_data, vm->regex_context); return NJS_ERROR; } diff --git a/src/test/njs_unit_test.c b/src/test/njs_unit_test.c index 48d7ed60..3642c6fc 100644 --- a/src/test/njs_unit_test.c +++ b/src/test/njs_unit_test.c @@ -7231,6 +7231,12 @@ static njs_unit_test_t njs_test[] = "{ return '|'+s+'|'+o+'|'+m+'|'+p+'|' })"), njs_str("abc|abcdefghdijklm|3|d|d|efghdijklm") }, + { njs_str("'abc'.replace(/b/, ()=>1)"), + njs_str("a1c") }, + + { njs_str("var n = 0; 'abbbc'.replace(/b/g, function() {return ++n;})"), + njs_str("a123c") }, + { njs_str("'abcdefghdijklm'.replace(/x/, 'X')"), njs_str("abcdefghdijklm") },