[njs] Fixed String.prototype.replace() when function returns non-string.
Dmitry Volyntsev
xeioex at nginx.com
Tue Apr 14 12:48:29 UTC 2020
details: https://hg.nginx.org/njs/rev/3a650363913a
branches:
changeset: 1373:3a650363913a
user: Dmitry Volyntsev <xeioex at nginx.com>
date: Tue Apr 14 12:43:09 2020 +0000
description:
Fixed String.prototype.replace() when function returns non-string.
This closes #303 issue on Github.
diffstat:
src/njs_string.c | 47 ++++++++++++++++++++++++-----------------------
src/test/njs_unit_test.c | 6 ++++++
2 files changed, 30 insertions(+), 23 deletions(-)
diffs (78 lines):
diff -r c6f1ae6d8fac -r 3a650363913a src/njs_string.c
--- a/src/njs_string.c Tue Apr 14 12:42:05 2020 +0000
+++ b/src/njs_string.c Tue Apr 14 12:43:09 2020 +0000
@@ -3718,34 +3718,35 @@ njs_string_replace_regexp_function(njs_v
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;
- }
-
- (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_regexp_pattern(regex)->global) {
- r->part += 2;
-
- if (r->part[0].start > (string.start + string.size)) {
- return njs_string_replace_regexp_join(vm, r);
- }
-
- return njs_string_replace_regexp(vm, this, regex, r);
+ goto exception;
+ }
+
+ 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;
}
-
- return njs_string_replace_regexp_join(vm, r);
- }
+ }
+
+ njs_string_replacement_copy(&r->part[r->empty ? 0 : 1], &r->retval);
+
+ if (njs_regexp_pattern(regex)->global) {
+ r->part += 2;
+
+ if (r->part[0].start > (string.start + string.size)) {
+ return njs_string_replace_regexp_join(vm, r);
+ }
+
+ return njs_string_replace_regexp(vm, this, regex, r);
+ }
+
+ return njs_string_replace_regexp_join(vm, r);
+
+exception:
njs_regex_match_data_free(r->match_data, vm->regex_context);
- njs_internal_error(vm, "unexpected retval type:%s",
- njs_type_string(r->retval.type));
-
return NJS_ERROR;
}
diff -r c6f1ae6d8fac -r 3a650363913a src/test/njs_unit_test.c
--- a/src/test/njs_unit_test.c Tue Apr 14 12:42:05 2020 +0000
+++ b/src/test/njs_unit_test.c Tue Apr 14 12:43:09 2020 +0000
@@ -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") },
More information about the nginx-devel
mailing list