| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
#include "builtin/String.h" |
| 8 |
|
| 9 |
#include "mozilla/Attributes.h" |
| 10 |
#include "mozilla/CheckedInt.h" |
| 11 |
#include "mozilla/Compiler.h" |
| 12 |
#include "mozilla/FloatingPoint.h" |
| 13 |
#if JS_HAS_INTL_API |
| 14 |
# include "mozilla/intl/String.h" |
| 15 |
#endif |
| 16 |
#include "mozilla/Likely.h" |
| 17 |
#include "mozilla/Maybe.h" |
| 18 |
#include "mozilla/PodOperations.h" |
| 19 |
#include "mozilla/Range.h" |
| 20 |
#include "mozilla/SIMD.h" |
| 21 |
#include "mozilla/TextUtils.h" |
| 22 |
|
| 23 |
#include <algorithm> |
| 24 |
#include <limits> |
| 25 |
#include <string.h> |
| 26 |
#include <type_traits> |
| 27 |
|
| 28 |
#include "jsnum.h" |
| 29 |
#include "jstypes.h" |
| 30 |
|
| 31 |
#include "builtin/Array.h" |
| 32 |
#if JS_HAS_INTL_API |
| 33 |
# include "builtin/intl/CommonFunctions.h" |
| 34 |
# include "builtin/intl/FormatBuffer.h" |
| 35 |
#endif |
| 36 |
#include "builtin/RegExp.h" |
| 37 |
#include "gc/GC.h" |
| 38 |
#include "jit/InlinableNatives.h" |
| 39 |
#include "js/Conversions.h" |
| 40 |
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_* |
| 41 |
#if !JS_HAS_INTL_API |
| 42 |
# include "js/LocaleSensitive.h" |
| 43 |
#endif |
| 44 |
#include "js/Prefs.h" |
| 45 |
#include "js/Printer.h" |
| 46 |
#include "js/PropertyAndElement.h" // JS_DefineFunctions |
| 47 |
#include "js/PropertySpec.h" |
| 48 |
#include "js/StableStringChars.h" |
| 49 |
#include "js/UniquePtr.h" |
| 50 |
#include "util/StringBuilder.h" |
| 51 |
#include "util/Unicode.h" |
| 52 |
#include "vm/GlobalObject.h" |
| 53 |
#include "vm/JSContext.h" |
| 54 |
#include "vm/JSObject.h" |
| 55 |
#include "vm/RegExpObject.h" |
| 56 |
#include "vm/SelfHosting.h" |
| 57 |
#include "vm/StaticStrings.h" |
| 58 |
#include "vm/ToSource.h" // js::ValueToSource |
| 59 |
|
| 60 |
#include "vm/GeckoProfiler-inl.h" |
| 61 |
#include "vm/NativeObject-inl.h" |
| 62 |
#include "vm/StringObject-inl.h" |
| 63 |
#include "vm/StringType-inl.h" |
| 64 |
|
| 65 |
using namespace js; |
| 66 |
|
| 67 |
using mozilla::AsciiAlphanumericToNumber; |
| 68 |
using mozilla::CheckedInt; |
| 69 |
using mozilla::EnsureUtf16ValiditySpan; |
| 70 |
using mozilla::IsAsciiHexDigit; |
| 71 |
using mozilla::PodCopy; |
| 72 |
using mozilla::RangedPtr; |
| 73 |
using mozilla::SIMD; |
| 74 |
using mozilla::Span; |
| 75 |
using mozilla::Utf16ValidUpTo; |
| 76 |
|
| 77 |
using JS::AutoCheckCannotGC; |
| 78 |
using JS::AutoStableStringChars; |
| 79 |
|
| 80 |
static JSLinearString* ArgToLinearString(JSContext* cx, const CallArgs& args, |
| 81 |
unsigned argno) { |
| 82 |
if (argno >= args.length()) { |
| 83 |
return cx->names().undefined; |
| 84 |
} |
| 85 |
|
| 86 |
JSString* str = ToString<CanGC>(cx, args[argno]); |
| 87 |
if (!str) { |
| 88 |
return nullptr; |
| 89 |
} |
| 90 |
|
| 91 |
return str->ensureLinear(cx); |
| 92 |
} |
| 93 |
|
| 94 |
/* |
| 95 |
* Forward declarations for URI encode/decode and helper routines |
| 96 |
*/ |
| 97 |
static bool str_decodeURI(JSContext* cx, unsigned argc, Value* vp); |
| 98 |
|
| 99 |
static bool str_decodeURI_Component(JSContext* cx, unsigned argc, Value* vp); |
| 100 |
|
| 101 |
static bool str_encodeURI(JSContext* cx, unsigned argc, Value* vp); |
| 102 |
|
| 103 |
static bool str_encodeURI_Component(JSContext* cx, unsigned argc, Value* vp); |
| 104 |
|
| 105 |
/* |
| 106 |
* Global string methods |
| 107 |
*/ |
| 108 |
|
| 109 |
/* ES5 B.2.1 */ |
| 110 |
template <typename CharT> |
| 111 |
static bool Escape(JSContext* cx, const CharT* chars, uint32_t length, |
| 112 |
StringChars<Latin1Char>& newChars, uint32_t* newLengthOut) { |
| 113 |
// clang-format off |
| 114 |
static const uint8_t shouldPassThrough[128] = { |
| 115 |
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, |
| 116 |
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, |
| 117 |
0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1, /* !"#$%&'()*+,-./ */ |
| 118 |
1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0, /* 0123456789:;<=>? */ |
| 119 |
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* @ABCDEFGHIJKLMNO */ |
| 120 |
1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1, /* PQRSTUVWXYZ[\]^_ */ |
| 121 |
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* `abcdefghijklmno */ |
| 122 |
1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0, /* pqrstuvwxyz{\}~ DEL */ |
| 123 |
}; |
| 124 |
// clang-format on |
| 125 |
|
| 126 |
/* Take a first pass and see how big the result string will need to be. */ |
| 127 |
uint32_t newLength = length; |
| 128 |
for (size_t i = 0; i < length; i++) { |
| 129 |
char16_t ch = chars[i]; |
| 130 |
if (ch < 128 && shouldPassThrough[ch]) { |
| 131 |
continue; |
| 132 |
} |
| 133 |
|
| 134 |
/* |
| 135 |
* newlength is incremented below by at most 5 and at this point it must |
| 136 |
* be a valid string length, so this should never overflow uint32_t. |
| 137 |
*/ |
| 138 |
static_assert(JSString::MAX_LENGTH < UINT32_MAX - 5, |
| 139 |
"Adding 5 to valid string length should not overflow"); |
| 140 |
|
| 141 |
MOZ_ASSERT(newLength <= JSString::MAX_LENGTH); |
| 142 |
|
| 143 |
/* The character will be encoded as %XX or %uXXXX. */ |
| 144 |
newLength += (ch < 256) ? 2 : 5; |
| 145 |
|
| 146 |
if (MOZ_UNLIKELY(newLength > JSString::MAX_LENGTH)) { |
| 147 |
ReportAllocationOverflow(cx); |
| 148 |
return false; |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
if (newLength == length) { |
| 153 |
*newLengthOut = newLength; |
| 154 |
return true; |
| 155 |
} |
| 156 |
|
| 157 |
if (!newChars.maybeAlloc(cx, newLength)) { |
| 158 |
return false; |
| 159 |
} |
| 160 |
|
| 161 |
static const char digits[] = "0123456789ABCDEF"; |
| 162 |
|
| 163 |
JS::AutoCheckCannotGC nogc; |
| 164 |
Latin1Char* rawNewChars = newChars.data(nogc); |
| 165 |
size_t i, ni; |
| 166 |
for (i = 0, ni = 0; i < length; i++) { |
| 167 |
char16_t ch = chars[i]; |
| 168 |
if (ch < 128 && shouldPassThrough[ch]) { |
| 169 |
rawNewChars[ni++] = ch; |
| 170 |
} else if (ch < 256) { |
| 171 |
rawNewChars[ni++] = '%'; |
| 172 |
rawNewChars[ni++] = digits[ch >> 4]; |
| 173 |
rawNewChars[ni++] = digits[ch & 0xF]; |
| 174 |
} else { |
| 175 |
rawNewChars[ni++] = '%'; |
| 176 |
rawNewChars[ni++] = 'u'; |
| 177 |
rawNewChars[ni++] = digits[ch >> 12]; |
| 178 |
rawNewChars[ni++] = digits[(ch & 0xF00) >> 8]; |
| 179 |
rawNewChars[ni++] = digits[(ch & 0xF0) >> 4]; |
| 180 |
rawNewChars[ni++] = digits[ch & 0xF]; |
| 181 |
} |
| 182 |
} |
| 183 |
MOZ_ASSERT(ni == newLength); |
| 184 |
|
| 185 |
*newLengthOut = newLength; |
| 186 |
return true; |
| 187 |
} |
| 188 |
|
| 189 |
static bool str_escape(JSContext* cx, unsigned argc, Value* vp) { |
| 190 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "escape"); |
| 191 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 192 |
|
| 193 |
Rooted<JSLinearString*> str(cx, ArgToLinearString(cx, args, 0)); |
| 194 |
if (!str) { |
| 195 |
return false; |
| 196 |
} |
| 197 |
|
| 198 |
StringChars<Latin1Char> newChars(cx); |
| 199 |
uint32_t newLength = 0; // initialize to silence GCC warning |
| 200 |
if (str->hasLatin1Chars()) { |
| 201 |
AutoCheckCannotGC nogc; |
| 202 |
if (!Escape(cx, str->latin1Chars(nogc), str->length(), newChars, |
| 203 |
&newLength)) { |
| 204 |
return false; |
| 205 |
} |
| 206 |
} else { |
| 207 |
AutoCheckCannotGC nogc; |
| 208 |
if (!Escape(cx, str->twoByteChars(nogc), str->length(), newChars, |
| 209 |
&newLength)) { |
| 210 |
return false; |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
// Return input if no characters need to be escaped. |
| 215 |
if (newLength == str->length()) { |
| 216 |
args.rval().setString(str); |
| 217 |
return true; |
| 218 |
} |
| 219 |
|
| 220 |
JSString* res = newChars.toStringDontDeflateNonStatic<CanGC>(cx, newLength); |
| 221 |
if (!res) { |
| 222 |
return false; |
| 223 |
} |
| 224 |
|
| 225 |
args.rval().setString(res); |
| 226 |
return true; |
| 227 |
} |
| 228 |
|
| 229 |
template <typename CharT> |
| 230 |
static inline bool Unhex4(const RangedPtr<const CharT> chars, |
| 231 |
char16_t* result) { |
| 232 |
CharT a = chars[0], b = chars[1], c = chars[2], d = chars[3]; |
| 233 |
|
| 234 |
if (!(IsAsciiHexDigit(a) && IsAsciiHexDigit(b) && IsAsciiHexDigit(c) && |
| 235 |
IsAsciiHexDigit(d))) { |
| 236 |
return false; |
| 237 |
} |
| 238 |
|
| 239 |
char16_t unhex = AsciiAlphanumericToNumber(a); |
| 240 |
unhex = (unhex << 4) + AsciiAlphanumericToNumber(b); |
| 241 |
unhex = (unhex << 4) + AsciiAlphanumericToNumber(c); |
| 242 |
unhex = (unhex << 4) + AsciiAlphanumericToNumber(d); |
| 243 |
*result = unhex; |
| 244 |
return true; |
| 245 |
} |
| 246 |
|
| 247 |
template <typename CharT> |
| 248 |
static inline bool Unhex2(const RangedPtr<const CharT> chars, |
| 249 |
char16_t* result) { |
| 250 |
CharT a = chars[0], b = chars[1]; |
| 251 |
|
| 252 |
if (!(IsAsciiHexDigit(a) && IsAsciiHexDigit(b))) { |
| 253 |
return false; |
| 254 |
} |
| 255 |
|
| 256 |
*result = (AsciiAlphanumericToNumber(a) << 4) + AsciiAlphanumericToNumber(b); |
| 257 |
return true; |
| 258 |
} |
| 259 |
|
| 260 |
template <typename CharT> |
| 261 |
static bool Unescape(StringBuilder& sb, |
| 262 |
const mozilla::Range<const CharT> chars) { |
| 263 |
// Step 2. |
| 264 |
uint32_t length = chars.length(); |
| 265 |
|
| 266 |
/* |
| 267 |
* Note that the spec algorithm has been optimized to avoid building |
| 268 |
* a string in the case where no escapes are present. |
| 269 |
*/ |
| 270 |
bool building = false; |
| 271 |
|
| 272 |
#define ENSURE_BUILDING \ |
| 273 |
do { \ |
| 274 |
if (!building) { \ |
| 275 |
building = true; \ |
| 276 |
if (!sb.reserve(length)) return false; \ |
| 277 |
sb.infallibleAppend(chars.begin().get(), k); \ |
| 278 |
} \ |
| 279 |
} while (false); |
| 280 |
|
| 281 |
// Step 4. |
| 282 |
uint32_t k = 0; |
| 283 |
|
| 284 |
// Step 5. |
| 285 |
while (k < length) { |
| 286 |
// Step 5.a. |
| 287 |
char16_t c = chars[k]; |
| 288 |
|
| 289 |
// Step 5.b. |
| 290 |
if (c == '%') { |
| 291 |
static_assert(JSString::MAX_LENGTH < UINT32_MAX - 6, |
| 292 |
"String length is not near UINT32_MAX"); |
| 293 |
|
| 294 |
// Steps 5.b.i-ii. |
| 295 |
if (k + 6 <= length && chars[k + 1] == 'u') { |
| 296 |
if (Unhex4(chars.begin() + k + 2, &c)) { |
| 297 |
ENSURE_BUILDING |
| 298 |
k += 5; |
| 299 |
} |
| 300 |
} else if (k + 3 <= length) { |
| 301 |
if (Unhex2(chars.begin() + k + 1, &c)) { |
| 302 |
ENSURE_BUILDING |
| 303 |
k += 2; |
| 304 |
} |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
// Step 5.c. |
| 309 |
if (building && !sb.append(c)) { |
| 310 |
return false; |
| 311 |
} |
| 312 |
|
| 313 |
// Step 5.d. |
| 314 |
k += 1; |
| 315 |
} |
| 316 |
|
| 317 |
return true; |
| 318 |
#undef ENSURE_BUILDING |
| 319 |
} |
| 320 |
|
| 321 |
// ES2018 draft rev f83aa38282c2a60c6916ebc410bfdf105a0f6a54 |
| 322 |
// B.2.1.2 unescape ( string ) |
| 323 |
static bool str_unescape(JSContext* cx, unsigned argc, Value* vp) { |
| 324 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "unescape"); |
| 325 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 326 |
|
| 327 |
// Step 1. |
| 328 |
Rooted<JSLinearString*> str(cx, ArgToLinearString(cx, args, 0)); |
| 329 |
if (!str) { |
| 330 |
return false; |
| 331 |
} |
| 332 |
|
| 333 |
// Step 3. |
| 334 |
JSStringBuilder sb(cx); |
| 335 |
if (str->hasTwoByteChars() && !sb.ensureTwoByteChars()) { |
| 336 |
return false; |
| 337 |
} |
| 338 |
|
| 339 |
// Steps 2, 4-5. |
| 340 |
bool unescapeFailed = false; |
| 341 |
if (str->hasLatin1Chars()) { |
| 342 |
AutoCheckCannotGC nogc; |
| 343 |
unescapeFailed = !Unescape(sb, str->latin1Range(nogc)); |
| 344 |
} else { |
| 345 |
AutoCheckCannotGC nogc; |
| 346 |
unescapeFailed = !Unescape(sb, str->twoByteRange(nogc)); |
| 347 |
} |
| 348 |
if (unescapeFailed) { |
| 349 |
return false; |
| 350 |
} |
| 351 |
|
| 352 |
// Step 6. |
| 353 |
JSLinearString* result; |
| 354 |
if (!sb.empty()) { |
| 355 |
result = sb.finishString(); |
| 356 |
if (!result) { |
| 357 |
return false; |
| 358 |
} |
| 359 |
} else { |
| 360 |
result = str; |
| 361 |
} |
| 362 |
|
| 363 |
args.rval().setString(result); |
| 364 |
return true; |
| 365 |
} |
| 366 |
|
| 367 |
static bool str_uneval(JSContext* cx, unsigned argc, Value* vp) { |
| 368 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 369 |
JSString* str = ValueToSource(cx, args.get(0)); |
| 370 |
if (!str) { |
| 371 |
return false; |
| 372 |
} |
| 373 |
|
| 374 |
args.rval().setString(str); |
| 375 |
return true; |
| 376 |
} |
| 377 |
|
| 378 |
static const JSFunctionSpec string_functions[] = { |
| 379 |
JS_FN("escape", str_escape, 1, JSPROP_RESOLVING), |
| 380 |
JS_FN("unescape", str_unescape, 1, JSPROP_RESOLVING), |
| 381 |
JS_FN("uneval", str_uneval, 1, JSPROP_RESOLVING), |
| 382 |
JS_FN("decodeURI", str_decodeURI, 1, JSPROP_RESOLVING), |
| 383 |
JS_FN("encodeURI", str_encodeURI, 1, JSPROP_RESOLVING), |
| 384 |
JS_FN("decodeURIComponent", str_decodeURI_Component, 1, JSPROP_RESOLVING), |
| 385 |
JS_FN("encodeURIComponent", str_encodeURI_Component, 1, JSPROP_RESOLVING), |
| 386 |
JS_FS_END, |
| 387 |
}; |
| 388 |
|
| 389 |
static const unsigned STRING_ELEMENT_ATTRS = |
| 390 |
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT; |
| 391 |
|
| 392 |
static bool str_enumerate(JSContext* cx, HandleObject obj) { |
| 393 |
RootedString str(cx, obj->as<StringObject>().unbox()); |
| 394 |
js::StaticStrings& staticStrings = cx->staticStrings(); |
| 395 |
|
| 396 |
RootedValue value(cx); |
| 397 |
for (size_t i = 0, length = str->length(); i < length; i++) { |
| 398 |
JSString* str1 = staticStrings.getUnitStringForElement(cx, str, i); |
| 399 |
if (!str1) { |
| 400 |
return false; |
| 401 |
} |
| 402 |
value.setString(str1); |
| 403 |
if (!DefineDataElement(cx, obj, i, value, |
| 404 |
STRING_ELEMENT_ATTRS | JSPROP_RESOLVING)) { |
| 405 |
return false; |
| 406 |
} |
| 407 |
} |
| 408 |
|
| 409 |
return true; |
| 410 |
} |
| 411 |
|
| 412 |
static bool str_mayResolve(const JSAtomState&, jsid id, JSObject*) { |
| 413 |
// str_resolve ignores non-integer ids. |
| 414 |
return id.isInt(); |
| 415 |
} |
| 416 |
|
| 417 |
static bool str_resolve(JSContext* cx, HandleObject obj, HandleId id, |
| 418 |
bool* resolvedp) { |
| 419 |
if (!id.isInt()) { |
| 420 |
return true; |
| 421 |
} |
| 422 |
|
| 423 |
RootedString str(cx, obj->as<StringObject>().unbox()); |
| 424 |
|
| 425 |
int32_t slot = id.toInt(); |
| 426 |
if ((size_t)slot < str->length()) { |
| 427 |
JSString* str1 = |
| 428 |
cx->staticStrings().getUnitStringForElement(cx, str, size_t(slot)); |
| 429 |
if (!str1) { |
| 430 |
return false; |
| 431 |
} |
| 432 |
RootedValue value(cx, StringValue(str1)); |
| 433 |
if (!DefineDataElement(cx, obj, uint32_t(slot), value, |
| 434 |
STRING_ELEMENT_ATTRS | JSPROP_RESOLVING)) { |
| 435 |
return false; |
| 436 |
} |
| 437 |
*resolvedp = true; |
| 438 |
} |
| 439 |
return true; |
| 440 |
} |
| 441 |
|
| 442 |
static const JSClassOps StringObjectClassOps = { |
| 443 |
nullptr, // addProperty |
| 444 |
nullptr, // delProperty |
| 445 |
str_enumerate, // enumerate |
| 446 |
nullptr, // newEnumerate |
| 447 |
str_resolve, // resolve |
| 448 |
str_mayResolve, // mayResolve |
| 449 |
nullptr, // finalize |
| 450 |
nullptr, // call |
| 451 |
nullptr, // construct |
| 452 |
nullptr, // trace |
| 453 |
}; |
| 454 |
|
| 455 |
const JSClass StringObject::class_ = { |
| 456 |
"String", |
| 457 |
JSCLASS_HAS_RESERVED_SLOTS(StringObject::RESERVED_SLOTS) | |
| 458 |
JSCLASS_HAS_CACHED_PROTO(JSProto_String), |
| 459 |
&StringObjectClassOps, |
| 460 |
&StringObject::classSpec_, |
| 461 |
}; |
| 462 |
|
| 463 |
/* |
| 464 |
* Perform the initial |RequireObjectCoercible(thisv)| and |ToString(thisv)| |
| 465 |
* from nearly all String.prototype.* functions. |
| 466 |
*/ |
| 467 |
static MOZ_ALWAYS_INLINE JSString* ToStringForStringFunction( |
| 468 |
JSContext* cx, const char* funName, HandleValue thisv) { |
| 469 |
if (thisv.isString()) { |
| 470 |
return thisv.toString(); |
| 471 |
} |
| 472 |
|
| 473 |
if (thisv.isObject()) { |
| 474 |
if (thisv.toObject().is<StringObject>()) { |
| 475 |
StringObject* nobj = &thisv.toObject().as<StringObject>(); |
| 476 |
// We have to make sure that the ToPrimitive call from ToString |
| 477 |
// would be unobservable. |
| 478 |
if (HasNoToPrimitiveMethodPure(nobj, cx) && |
| 479 |
HasNativeMethodPure(nobj, cx->names().toString, str_toString, cx)) { |
| 480 |
return nobj->unbox(); |
| 481 |
} |
| 482 |
} |
| 483 |
} else if (thisv.isNullOrUndefined()) { |
| 484 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 485 |
JSMSG_INCOMPATIBLE_PROTO, "String", funName, |
| 486 |
thisv.isNull() ? "null" : "undefined"); |
| 487 |
return nullptr; |
| 488 |
} |
| 489 |
|
| 490 |
return ToStringSlow<CanGC>(cx, thisv); |
| 491 |
} |
| 492 |
|
| 493 |
MOZ_ALWAYS_INLINE bool IsString(HandleValue v) { |
| 494 |
return v.isString() || (v.isObject() && v.toObject().is<StringObject>()); |
| 495 |
} |
| 496 |
|
| 497 |
MOZ_ALWAYS_INLINE bool str_toSource_impl(JSContext* cx, const CallArgs& args) { |
| 498 |
MOZ_ASSERT(IsString(args.thisv())); |
| 499 |
|
| 500 |
JSString* str = ToString<CanGC>(cx, args.thisv()); |
| 501 |
if (!str) { |
| 502 |
return false; |
| 503 |
} |
| 504 |
|
| 505 |
UniqueChars quoted = QuoteString(cx, str, '"'); |
| 506 |
if (!quoted) { |
| 507 |
return false; |
| 508 |
} |
| 509 |
|
| 510 |
JSStringBuilder sb(cx); |
| 511 |
if (!sb.append("(new String(") || |
| 512 |
!sb.append(quoted.get(), strlen(quoted.get())) || !sb.append("))")) { |
| 513 |
return false; |
| 514 |
} |
| 515 |
|
| 516 |
JSString* result = sb.finishString(); |
| 517 |
if (!result) { |
| 518 |
return false; |
| 519 |
} |
| 520 |
args.rval().setString(result); |
| 521 |
return true; |
| 522 |
} |
| 523 |
|
| 524 |
static bool str_toSource(JSContext* cx, unsigned argc, Value* vp) { |
| 525 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 526 |
return CallNonGenericMethod<IsString, str_toSource_impl>(cx, args); |
| 527 |
} |
| 528 |
|
| 529 |
MOZ_ALWAYS_INLINE bool str_toString_impl(JSContext* cx, const CallArgs& args) { |
| 530 |
MOZ_ASSERT(IsString(args.thisv())); |
| 531 |
|
| 532 |
args.rval().setString( |
| 533 |
args.thisv().isString() |
| 534 |
? args.thisv().toString() |
| 535 |
: args.thisv().toObject().as<StringObject>().unbox()); |
| 536 |
return true; |
| 537 |
} |
| 538 |
|
| 539 |
bool js::str_toString(JSContext* cx, unsigned argc, Value* vp) { |
| 540 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 541 |
return CallNonGenericMethod<IsString, str_toString_impl>(cx, args); |
| 542 |
} |
| 543 |
|
| 544 |
template <typename DestChar, typename SrcChar> |
| 545 |
static inline void CopyChars(DestChar* destChars, const SrcChar* srcChars, |
| 546 |
size_t length) { |
| 547 |
if constexpr (std::is_same_v<DestChar, SrcChar>) { |
| 548 |
#if MOZ_IS_GCC |
| 549 |
// Directly call memcpy to work around bug 1863131. |
| 550 |
memcpy(destChars, srcChars, length * sizeof(DestChar)); |
| 551 |
#else |
| 552 |
PodCopy(destChars, srcChars, length); |
| 553 |
#endif |
| 554 |
} else { |
| 555 |
for (size_t i = 0; i < length; i++) { |
| 556 |
destChars[i] = srcChars[i]; |
| 557 |
} |
| 558 |
} |
| 559 |
} |
| 560 |
|
| 561 |
template <typename CharT> |
| 562 |
static inline void CopyChars(CharT* to, const JSLinearString* from, |
| 563 |
size_t begin, size_t length) { |
| 564 |
MOZ_ASSERT(begin + length <= from->length()); |
| 565 |
|
| 566 |
JS::AutoCheckCannotGC nogc; |
| 567 |
if (from->hasLatin1Chars()) { |
| 568 |
CopyChars(to, from->latin1Chars(nogc) + begin, length); |
| 569 |
} else { |
| 570 |
CopyChars(to, from->twoByteChars(nogc) + begin, length); |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
template <typename CharT> |
| 575 |
static JSLinearString* SubstringInlineString(JSContext* cx, |
| 576 |
Handle<JSLinearString*> left, |
| 577 |
Handle<JSLinearString*> right, |
| 578 |
size_t begin, size_t lhsLength, |
| 579 |
size_t rhsLength) { |
| 580 |
constexpr size_t MaxLength = std::is_same_v<CharT, Latin1Char> |
| 581 |
? JSFatInlineString::MAX_LENGTH_LATIN1 |
| 582 |
: JSFatInlineString::MAX_LENGTH_TWO_BYTE; |
| 583 |
|
| 584 |
size_t length = lhsLength + rhsLength; |
| 585 |
MOZ_ASSERT(length <= MaxLength, "total length fits in stack chars"); |
| 586 |
MOZ_ASSERT(JSInlineString::lengthFits<CharT>(length)); |
| 587 |
|
| 588 |
CharT chars[MaxLength] = {}; |
| 589 |
|
| 590 |
CopyChars(chars, left, begin, lhsLength); |
| 591 |
CopyChars(chars + lhsLength, right, 0, rhsLength); |
| 592 |
|
| 593 |
if (auto* str = cx->staticStrings().lookup(chars, length)) { |
| 594 |
return str; |
| 595 |
} |
| 596 |
return NewInlineString<CanGC>(cx, chars, length); |
| 597 |
} |
| 598 |
|
| 599 |
JSString* js::SubstringKernel(JSContext* cx, HandleString str, int32_t beginInt, |
| 600 |
int32_t lengthInt) { |
| 601 |
MOZ_ASSERT(0 <= beginInt); |
| 602 |
MOZ_ASSERT(0 <= lengthInt); |
| 603 |
MOZ_ASSERT(uint32_t(beginInt) <= str->length()); |
| 604 |
MOZ_ASSERT(uint32_t(lengthInt) <= str->length() - beginInt); |
| 605 |
|
| 606 |
uint32_t begin = beginInt; |
| 607 |
uint32_t len = lengthInt; |
| 608 |
|
| 609 |
/* |
| 610 |
* Optimization for one level deep ropes. |
| 611 |
* This is common for the following pattern: |
| 612 |
* |
| 613 |
* while() { |
| 614 |
* text = text.substr(0, x) + "bla" + text.substr(x) |
| 615 |
* text.charCodeAt(x + 1) |
| 616 |
* } |
| 617 |
*/ |
| 618 |
if (str->isRope()) { |
| 619 |
JSRope* rope = &str->asRope(); |
| 620 |
|
| 621 |
if (rope->length() == len) { |
| 622 |
// Substring is the full rope. |
| 623 |
MOZ_ASSERT(begin == 0); |
| 624 |
return rope; |
| 625 |
} |
| 626 |
|
| 627 |
if (begin + len <= rope->leftChild()->length()) { |
| 628 |
// Substring is fully contained within the rope's left child. |
| 629 |
return NewDependentString(cx, rope->leftChild(), begin, len); |
| 630 |
} |
| 631 |
|
| 632 |
if (begin >= rope->leftChild()->length()) { |
| 633 |
// Substring is fully contained within the rope's right child. |
| 634 |
begin -= rope->leftChild()->length(); |
| 635 |
return NewDependentString(cx, rope->rightChild(), begin, len); |
| 636 |
} |
| 637 |
|
| 638 |
// The substring spans both children. Avoid flattening the rope if the |
| 639 |
// children are both linear and the substring fits in an inline string. |
| 640 |
// |
| 641 |
// Note: we could handle longer substrings by allocating a new rope here, |
| 642 |
// but this can result in a lot more rope flattening later on. It's safer to |
| 643 |
// flatten the rope in this case. See bug 1922926. |
| 644 |
|
| 645 |
MOZ_ASSERT(begin < rope->leftChild()->length() && |
| 646 |
begin + len > rope->leftChild()->length()); |
| 647 |
|
| 648 |
bool fitsInline = rope->hasLatin1Chars() |
| 649 |
? JSInlineString::lengthFits<Latin1Char>(len) |
| 650 |
: JSInlineString::lengthFits<char16_t>(len); |
| 651 |
if (fitsInline && rope->leftChild()->isLinear() && |
| 652 |
rope->rightChild()->isLinear()) { |
| 653 |
Rooted<JSLinearString*> left(cx, &rope->leftChild()->asLinear()); |
| 654 |
Rooted<JSLinearString*> right(cx, &rope->rightChild()->asLinear()); |
| 655 |
|
| 656 |
size_t lhsLength = left->length() - begin; |
| 657 |
size_t rhsLength = len - lhsLength; |
| 658 |
|
| 659 |
if (rope->hasLatin1Chars()) { |
| 660 |
return SubstringInlineString<Latin1Char>(cx, left, right, begin, |
| 661 |
lhsLength, rhsLength); |
| 662 |
} |
| 663 |
return SubstringInlineString<char16_t>(cx, left, right, begin, lhsLength, |
| 664 |
rhsLength); |
| 665 |
} |
| 666 |
} |
| 667 |
|
| 668 |
return NewDependentString(cx, str, begin, len); |
| 669 |
} |
| 670 |
|
| 671 |
/** |
| 672 |
* U+03A3 GREEK CAPITAL LETTER SIGMA has two different lower case mappings |
| 673 |
* depending on its context: |
| 674 |
* When it's preceded by a cased character and not followed by another cased |
| 675 |
* character, its lower case form is U+03C2 GREEK SMALL LETTER FINAL SIGMA. |
| 676 |
* Otherwise its lower case mapping is U+03C3 GREEK SMALL LETTER SIGMA. |
| 677 |
* |
| 678 |
* Unicode 9.0, §3.13 Default Case Algorithms |
| 679 |
*/ |
| 680 |
static char16_t Final_Sigma(const char16_t* chars, size_t length, |
| 681 |
size_t index) { |
| 682 |
MOZ_ASSERT(index < length); |
| 683 |
MOZ_ASSERT(chars[index] == unicode::GREEK_CAPITAL_LETTER_SIGMA); |
| 684 |
MOZ_ASSERT(unicode::ToLowerCase(unicode::GREEK_CAPITAL_LETTER_SIGMA) == |
| 685 |
unicode::GREEK_SMALL_LETTER_SIGMA); |
| 686 |
|
| 687 |
#if JS_HAS_INTL_API |
| 688 |
// Tell the analysis the BinaryProperty.contains function pointer called by |
| 689 |
// mozilla::intl::String::Is{CaseIgnorable, Cased} cannot GC. |
| 690 |
JS::AutoSuppressGCAnalysis nogc; |
| 691 |
|
| 692 |
bool precededByCased = false; |
| 693 |
for (size_t i = index; i > 0;) { |
| 694 |
char16_t c = chars[--i]; |
| 695 |
char32_t codePoint = c; |
| 696 |
if (unicode::IsTrailSurrogate(c) && i > 0) { |
| 697 |
char16_t lead = chars[i - 1]; |
| 698 |
if (unicode::IsLeadSurrogate(lead)) { |
| 699 |
codePoint = unicode::UTF16Decode(lead, c); |
| 700 |
i--; |
| 701 |
} |
| 702 |
} |
| 703 |
|
| 704 |
// Ignore any characters with the property Case_Ignorable. |
| 705 |
// NB: We need to skip over all Case_Ignorable characters, even when |
| 706 |
// they also have the Cased binary property. |
| 707 |
if (mozilla::intl::String::IsCaseIgnorable(codePoint)) { |
| 708 |
continue; |
| 709 |
} |
| 710 |
|
| 711 |
precededByCased = mozilla::intl::String::IsCased(codePoint); |
| 712 |
break; |
| 713 |
} |
| 714 |
if (!precededByCased) { |
| 715 |
return unicode::GREEK_SMALL_LETTER_SIGMA; |
| 716 |
} |
| 717 |
|
| 718 |
bool followedByCased = false; |
| 719 |
for (size_t i = index + 1; i < length;) { |
| 720 |
char16_t c = chars[i++]; |
| 721 |
char32_t codePoint = c; |
| 722 |
if (unicode::IsLeadSurrogate(c) && i < length) { |
| 723 |
char16_t trail = chars[i]; |
| 724 |
if (unicode::IsTrailSurrogate(trail)) { |
| 725 |
codePoint = unicode::UTF16Decode(c, trail); |
| 726 |
i++; |
| 727 |
} |
| 728 |
} |
| 729 |
|
| 730 |
// Ignore any characters with the property Case_Ignorable. |
| 731 |
// NB: We need to skip over all Case_Ignorable characters, even when |
| 732 |
// they also have the Cased binary property. |
| 733 |
if (mozilla::intl::String::IsCaseIgnorable(codePoint)) { |
| 734 |
continue; |
| 735 |
} |
| 736 |
|
| 737 |
followedByCased = mozilla::intl::String::IsCased(codePoint); |
| 738 |
break; |
| 739 |
} |
| 740 |
if (!followedByCased) { |
| 741 |
return unicode::GREEK_SMALL_LETTER_FINAL_SIGMA; |
| 742 |
} |
| 743 |
#endif |
| 744 |
|
| 745 |
return unicode::GREEK_SMALL_LETTER_SIGMA; |
| 746 |
} |
| 747 |
|
| 748 |
// If |srcLength == destLength| is true, the destination buffer was allocated |
| 749 |
// with the same size as the source buffer. When we append characters which |
| 750 |
// have special casing mappings, we test |srcLength == destLength| to decide |
| 751 |
// if we need to back out and reallocate a sufficiently large destination |
| 752 |
// buffer. Otherwise the destination buffer was allocated with the correct |
| 753 |
// size to hold all lower case mapped characters, i.e. |
| 754 |
// |destLength == ToLowerCaseLength(srcChars, 0, srcLength)| is true. |
| 755 |
template <typename CharT> |
| 756 |
static size_t ToLowerCaseImpl(CharT* destChars, const CharT* srcChars, |
| 757 |
size_t startIndex, size_t srcLength, |
| 758 |
size_t destLength) { |
| 759 |
MOZ_ASSERT(startIndex < srcLength); |
| 760 |
MOZ_ASSERT(srcLength <= destLength); |
| 761 |
if constexpr (std::is_same_v<CharT, Latin1Char>) { |
| 762 |
MOZ_ASSERT(srcLength == destLength); |
| 763 |
} |
| 764 |
|
| 765 |
size_t j = startIndex; |
| 766 |
for (size_t i = startIndex; i < srcLength; i++) { |
| 767 |
CharT c = srcChars[i]; |
| 768 |
if constexpr (!std::is_same_v<CharT, Latin1Char>) { |
| 769 |
if (unicode::IsLeadSurrogate(c) && i + 1 < srcLength) { |
| 770 |
char16_t trail = srcChars[i + 1]; |
| 771 |
if (unicode::IsTrailSurrogate(trail)) { |
| 772 |
trail = unicode::ToLowerCaseNonBMPTrail(c, trail); |
| 773 |
destChars[j++] = c; |
| 774 |
destChars[j++] = trail; |
| 775 |
i++; |
| 776 |
continue; |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
// Special case: U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE |
| 781 |
// lowercases to <U+0069 U+0307>. |
| 782 |
if (c == unicode::LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) { |
| 783 |
// Return if the output buffer is too small. |
| 784 |
if (srcLength == destLength) { |
| 785 |
return i; |
| 786 |
} |
| 787 |
|
| 788 |
destChars[j++] = CharT('i'); |
| 789 |
destChars[j++] = CharT(unicode::COMBINING_DOT_ABOVE); |
| 790 |
continue; |
| 791 |
} |
| 792 |
|
| 793 |
// Special case: U+03A3 GREEK CAPITAL LETTER SIGMA lowercases to |
| 794 |
// one of two codepoints depending on context. |
| 795 |
if (c == unicode::GREEK_CAPITAL_LETTER_SIGMA) { |
| 796 |
destChars[j++] = Final_Sigma(srcChars, srcLength, i); |
| 797 |
continue; |
| 798 |
} |
| 799 |
} |
| 800 |
|
| 801 |
c = unicode::ToLowerCase(c); |
| 802 |
destChars[j++] = c; |
| 803 |
} |
| 804 |
|
| 805 |
MOZ_ASSERT(j == destLength); |
| 806 |
return srcLength; |
| 807 |
} |
| 808 |
|
| 809 |
static size_t ToLowerCaseLength(const char16_t* chars, size_t startIndex, |
| 810 |
size_t length) { |
| 811 |
size_t lowerLength = length; |
| 812 |
for (size_t i = startIndex; i < length; i++) { |
| 813 |
char16_t c = chars[i]; |
| 814 |
|
| 815 |
// U+0130 is lowercased to the two-element sequence <U+0069 U+0307>. |
| 816 |
if (c == unicode::LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) { |
| 817 |
lowerLength += 1; |
| 818 |
} |
| 819 |
} |
| 820 |
return lowerLength; |
| 821 |
} |
| 822 |
|
| 823 |
template <typename CharT> |
| 824 |
static JSLinearString* ToLowerCase(JSContext* cx, JSLinearString* str) { |
| 825 |
// Unlike toUpperCase, toLowerCase has the nice invariant that if the |
| 826 |
// input is a Latin-1 string, the output is also a Latin-1 string. |
| 827 |
|
| 828 |
StringChars<CharT> newChars(cx); |
| 829 |
|
| 830 |
const size_t length = str->length(); |
| 831 |
size_t resultLength; |
| 832 |
{ |
| 833 |
AutoCheckCannotGC nogc; |
| 834 |
const CharT* chars = str->chars<CharT>(nogc); |
| 835 |
|
| 836 |
// We don't need extra special casing checks in the loop below, |
| 837 |
// because U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE and U+03A3 |
| 838 |
// GREEK CAPITAL LETTER SIGMA already have simple lower case mappings. |
| 839 |
MOZ_ASSERT(unicode::ChangesWhenLowerCased( |
| 840 |
unicode::LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE), |
| 841 |
"U+0130 has a simple lower case mapping"); |
| 842 |
MOZ_ASSERT( |
| 843 |
unicode::ChangesWhenLowerCased(unicode::GREEK_CAPITAL_LETTER_SIGMA), |
| 844 |
"U+03A3 has a simple lower case mapping"); |
| 845 |
|
| 846 |
// One element Latin-1 strings can be directly retrieved from the |
| 847 |
// static strings cache. |
| 848 |
if constexpr (std::is_same_v<CharT, Latin1Char>) { |
| 849 |
if (length == 1) { |
| 850 |
CharT lower = unicode::ToLowerCase(chars[0]); |
| 851 |
MOZ_ASSERT(StaticStrings::hasUnit(lower)); |
| 852 |
|
| 853 |
return cx->staticStrings().getUnit(lower); |
| 854 |
} |
| 855 |
} |
| 856 |
|
| 857 |
// Look for the first character that changes when lowercased. |
| 858 |
size_t i = 0; |
| 859 |
for (; i < length; i++) { |
| 860 |
CharT c = chars[i]; |
| 861 |
if constexpr (!std::is_same_v<CharT, Latin1Char>) { |
| 862 |
if (unicode::IsLeadSurrogate(c) && i + 1 < length) { |
| 863 |
CharT trail = chars[i + 1]; |
| 864 |
if (unicode::IsTrailSurrogate(trail)) { |
| 865 |
if (unicode::ChangesWhenLowerCasedNonBMP(c, trail)) { |
| 866 |
break; |
| 867 |
} |
| 868 |
|
| 869 |
i++; |
| 870 |
continue; |
| 871 |
} |
| 872 |
} |
| 873 |
} |
| 874 |
if (unicode::ChangesWhenLowerCased(c)) { |
| 875 |
break; |
| 876 |
} |
| 877 |
} |
| 878 |
|
| 879 |
// If no character needs to change, return the input string. |
| 880 |
if (i == length) { |
| 881 |
return str; |
| 882 |
} |
| 883 |
|
| 884 |
resultLength = length; |
| 885 |
if (!newChars.maybeAlloc(cx, resultLength)) { |
| 886 |
return nullptr; |
| 887 |
} |
| 888 |
|
| 889 |
PodCopy(newChars.data(nogc), chars, i); |
| 890 |
|
| 891 |
size_t readChars = |
| 892 |
ToLowerCaseImpl(newChars.data(nogc), chars, i, length, resultLength); |
| 893 |
if constexpr (!std::is_same_v<CharT, Latin1Char>) { |
| 894 |
if (readChars < length) { |
| 895 |
resultLength = ToLowerCaseLength(chars, readChars, length); |
| 896 |
|
| 897 |
if (!newChars.maybeRealloc(cx, length, resultLength)) { |
| 898 |
return nullptr; |
| 899 |
} |
| 900 |
|
| 901 |
MOZ_ALWAYS_TRUE(length == ToLowerCaseImpl(newChars.data(nogc), chars, |
| 902 |
readChars, length, |
| 903 |
resultLength)); |
| 904 |
} |
| 905 |
} else { |
| 906 |
MOZ_ASSERT(readChars == length, |
| 907 |
"Latin-1 strings don't have special lower case mappings"); |
| 908 |
} |
| 909 |
} |
| 910 |
|
| 911 |
return newChars.template toStringDontDeflate<CanGC>(cx, resultLength); |
| 912 |
} |
| 913 |
|
| 914 |
JSLinearString* js::StringToLowerCase(JSContext* cx, JSString* string) { |
| 915 |
JSLinearString* linear = string->ensureLinear(cx); |
| 916 |
if (!linear) { |
| 917 |
return nullptr; |
| 918 |
} |
| 919 |
|
| 920 |
if (linear->hasLatin1Chars()) { |
| 921 |
return ToLowerCase<Latin1Char>(cx, linear); |
| 922 |
} |
| 923 |
return ToLowerCase<char16_t>(cx, linear); |
| 924 |
} |
| 925 |
|
| 926 |
static bool str_toLowerCase(JSContext* cx, unsigned argc, Value* vp) { |
| 927 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "toLowerCase"); |
| 928 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 929 |
|
| 930 |
JSString* str = ToStringForStringFunction(cx, "toLowerCase", args.thisv()); |
| 931 |
if (!str) { |
| 932 |
return false; |
| 933 |
} |
| 934 |
|
| 935 |
JSString* result = StringToLowerCase(cx, str); |
| 936 |
if (!result) { |
| 937 |
return false; |
| 938 |
} |
| 939 |
|
| 940 |
args.rval().setString(result); |
| 941 |
return true; |
| 942 |
} |
| 943 |
|
| 944 |
#if JS_HAS_INTL_API |
| 945 |
// String.prototype.toLocaleLowerCase is self-hosted when Intl is exposed, |
| 946 |
// with core functionality performed by the intrinsic below. |
| 947 |
|
| 948 |
static const char* CaseMappingLocale(JSContext* cx, JSString* str) { |
| 949 |
JSLinearString* locale = str->ensureLinear(cx); |
| 950 |
if (!locale) { |
| 951 |
return nullptr; |
| 952 |
} |
| 953 |
|
| 954 |
MOZ_ASSERT(locale->length() >= 2, "locale is a valid language tag"); |
| 955 |
|
| 956 |
// Lithuanian, Turkish, and Azeri have language dependent case mappings. |
| 957 |
static const char languagesWithSpecialCasing[][3] = {"lt", "tr", "az"}; |
| 958 |
|
| 959 |
// All strings in |languagesWithSpecialCasing| are of length two, so we |
| 960 |
// only need to compare the first two characters to find a matching locale. |
| 961 |
// ES2017 Intl, §9.2.2 BestAvailableLocale |
| 962 |
if (locale->length() == 2 || locale->latin1OrTwoByteChar(2) == '-') { |
| 963 |
for (const auto& language : languagesWithSpecialCasing) { |
| 964 |
if (locale->latin1OrTwoByteChar(0) == language[0] && |
| 965 |
locale->latin1OrTwoByteChar(1) == language[1]) { |
| 966 |
return language; |
| 967 |
} |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
return ""; // ICU root locale |
| 972 |
} |
| 973 |
|
| 974 |
static bool HasDefaultCasing(const char* locale) { return !strcmp(locale, ""); } |
| 975 |
|
| 976 |
bool js::intl_toLocaleLowerCase(JSContext* cx, unsigned argc, Value* vp) { |
| 977 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 978 |
MOZ_ASSERT(args.length() == 2); |
| 979 |
MOZ_ASSERT(args[0].isString()); |
| 980 |
MOZ_ASSERT(args[1].isString()); |
| 981 |
|
| 982 |
RootedString string(cx, args[0].toString()); |
| 983 |
|
| 984 |
const char* locale = CaseMappingLocale(cx, args[1].toString()); |
| 985 |
if (!locale) { |
| 986 |
return false; |
| 987 |
} |
| 988 |
|
| 989 |
// Call String.prototype.toLowerCase() for language independent casing. |
| 990 |
if (HasDefaultCasing(locale)) { |
| 991 |
JSString* str = StringToLowerCase(cx, string); |
| 992 |
if (!str) { |
| 993 |
return false; |
| 994 |
} |
| 995 |
|
| 996 |
args.rval().setString(str); |
| 997 |
return true; |
| 998 |
} |
| 999 |
|
| 1000 |
AutoStableStringChars inputChars(cx); |
| 1001 |
if (!inputChars.initTwoByte(cx, string)) { |
| 1002 |
return false; |
| 1003 |
} |
| 1004 |
mozilla::Range<const char16_t> input = inputChars.twoByteRange(); |
| 1005 |
|
| 1006 |
// Note: maximum case mapping length is three characters, so the result |
| 1007 |
// length might be > INT32_MAX. ICU will fail in this case. |
| 1008 |
static_assert(JSString::MAX_LENGTH <= INT32_MAX, |
| 1009 |
"String length must fit in int32_t for ICU"); |
| 1010 |
|
| 1011 |
static const size_t INLINE_CAPACITY = js::intl::INITIAL_CHAR_BUFFER_SIZE; |
| 1012 |
|
| 1013 |
intl::FormatBuffer<char16_t, INLINE_CAPACITY> buffer(cx); |
| 1014 |
|
| 1015 |
auto ok = mozilla::intl::String::ToLocaleLowerCase(locale, input, buffer); |
| 1016 |
if (ok.isErr()) { |
| 1017 |
intl::ReportInternalError(cx, ok.unwrapErr()); |
| 1018 |
return false; |
| 1019 |
} |
| 1020 |
|
| 1021 |
JSString* result = buffer.toString(cx); |
| 1022 |
if (!result) { |
| 1023 |
return false; |
| 1024 |
} |
| 1025 |
|
| 1026 |
args.rval().setString(result); |
| 1027 |
return true; |
| 1028 |
} |
| 1029 |
|
| 1030 |
#else |
| 1031 |
|
| 1032 |
// When the Intl API is not exposed, String.prototype.toLowerCase is implemented |
| 1033 |
// in C++. |
| 1034 |
static bool str_toLocaleLowerCase(JSContext* cx, unsigned argc, Value* vp) { |
| 1035 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", |
| 1036 |
"toLocaleLowerCase"); |
| 1037 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1038 |
|
| 1039 |
RootedString str( |
| 1040 |
cx, ToStringForStringFunction(cx, "toLocaleLowerCase", args.thisv())); |
| 1041 |
if (!str) { |
| 1042 |
return false; |
| 1043 |
} |
| 1044 |
|
| 1045 |
/* |
| 1046 |
* Forcefully ignore the first (or any) argument and return toLowerCase(), |
| 1047 |
* ECMA has reserved that argument, presumably for defining the locale. |
| 1048 |
*/ |
| 1049 |
if (cx->runtime()->localeCallbacks && |
| 1050 |
cx->runtime()->localeCallbacks->localeToLowerCase) { |
| 1051 |
RootedValue result(cx); |
| 1052 |
if (!cx->runtime()->localeCallbacks->localeToLowerCase(cx, str, &result)) { |
| 1053 |
return false; |
| 1054 |
} |
| 1055 |
|
| 1056 |
args.rval().set(result); |
| 1057 |
return true; |
| 1058 |
} |
| 1059 |
|
| 1060 |
Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx)); |
| 1061 |
if (!linear) { |
| 1062 |
return false; |
| 1063 |
} |
| 1064 |
|
| 1065 |
JSString* result = StringToLowerCase(cx, linear); |
| 1066 |
if (!result) { |
| 1067 |
return false; |
| 1068 |
} |
| 1069 |
|
| 1070 |
args.rval().setString(result); |
| 1071 |
return true; |
| 1072 |
} |
| 1073 |
|
| 1074 |
#endif // JS_HAS_INTL_API |
| 1075 |
|
| 1076 |
static inline bool ToUpperCaseHasSpecialCasing(Latin1Char charCode) { |
| 1077 |
// U+00DF LATIN SMALL LETTER SHARP S is the only Latin-1 code point with |
| 1078 |
// special casing rules, so detect it inline. |
| 1079 |
bool hasUpperCaseSpecialCasing = |
| 1080 |
charCode == unicode::LATIN_SMALL_LETTER_SHARP_S; |
| 1081 |
MOZ_ASSERT(hasUpperCaseSpecialCasing == |
| 1082 |
unicode::ChangesWhenUpperCasedSpecialCasing(charCode)); |
| 1083 |
|
| 1084 |
return hasUpperCaseSpecialCasing; |
| 1085 |
} |
| 1086 |
|
| 1087 |
static inline bool ToUpperCaseHasSpecialCasing(char16_t charCode) { |
| 1088 |
return unicode::ChangesWhenUpperCasedSpecialCasing(charCode); |
| 1089 |
} |
| 1090 |
|
| 1091 |
static inline size_t ToUpperCaseLengthSpecialCasing(Latin1Char charCode) { |
| 1092 |
// U+00DF LATIN SMALL LETTER SHARP S is uppercased to two 'S'. |
| 1093 |
MOZ_ASSERT(charCode == unicode::LATIN_SMALL_LETTER_SHARP_S); |
| 1094 |
|
| 1095 |
return 2; |
| 1096 |
} |
| 1097 |
|
| 1098 |
static inline size_t ToUpperCaseLengthSpecialCasing(char16_t charCode) { |
| 1099 |
MOZ_ASSERT(ToUpperCaseHasSpecialCasing(charCode)); |
| 1100 |
|
| 1101 |
return unicode::LengthUpperCaseSpecialCasing(charCode); |
| 1102 |
} |
| 1103 |
|
| 1104 |
static inline void ToUpperCaseAppendUpperCaseSpecialCasing(char16_t charCode, |
| 1105 |
Latin1Char* elements, |
| 1106 |
size_t* index) { |
| 1107 |
// U+00DF LATIN SMALL LETTER SHARP S is uppercased to two 'S'. |
| 1108 |
MOZ_ASSERT(charCode == unicode::LATIN_SMALL_LETTER_SHARP_S); |
| 1109 |
static_assert('S' <= JSString::MAX_LATIN1_CHAR, "'S' is a Latin-1 character"); |
| 1110 |
|
| 1111 |
elements[(*index)++] = 'S'; |
| 1112 |
elements[(*index)++] = 'S'; |
| 1113 |
} |
| 1114 |
|
| 1115 |
static inline void ToUpperCaseAppendUpperCaseSpecialCasing(char16_t charCode, |
| 1116 |
char16_t* elements, |
| 1117 |
size_t* index) { |
| 1118 |
unicode::AppendUpperCaseSpecialCasing(charCode, elements, index); |
| 1119 |
} |
| 1120 |
|
| 1121 |
// See ToLowerCaseImpl for an explanation of the parameters. |
| 1122 |
template <typename DestChar, typename SrcChar> |
| 1123 |
static size_t ToUpperCaseImpl(DestChar* destChars, const SrcChar* srcChars, |
| 1124 |
size_t startIndex, size_t srcLength, |
| 1125 |
size_t destLength) { |
| 1126 |
static_assert(std::is_same_v<SrcChar, Latin1Char> || |
| 1127 |
!std::is_same_v<DestChar, Latin1Char>, |
| 1128 |
"cannot write non-Latin-1 characters into Latin-1 string"); |
| 1129 |
MOZ_ASSERT(startIndex < srcLength); |
| 1130 |
MOZ_ASSERT(srcLength <= destLength); |
| 1131 |
|
| 1132 |
size_t j = startIndex; |
| 1133 |
for (size_t i = startIndex; i < srcLength; i++) { |
| 1134 |
char16_t c = srcChars[i]; |
| 1135 |
if constexpr (!std::is_same_v<DestChar, Latin1Char>) { |
| 1136 |
if (unicode::IsLeadSurrogate(c) && i + 1 < srcLength) { |
| 1137 |
char16_t trail = srcChars[i + 1]; |
| 1138 |
if (unicode::IsTrailSurrogate(trail)) { |
| 1139 |
trail = unicode::ToUpperCaseNonBMPTrail(c, trail); |
| 1140 |
destChars[j++] = c; |
| 1141 |
destChars[j++] = trail; |
| 1142 |
i++; |
| 1143 |
continue; |
| 1144 |
} |
| 1145 |
} |
| 1146 |
} |
| 1147 |
|
| 1148 |
if (MOZ_UNLIKELY(c > 0x7f && |
| 1149 |
ToUpperCaseHasSpecialCasing(static_cast<SrcChar>(c)))) { |
| 1150 |
// Return if the output buffer is too small. |
| 1151 |
if (srcLength == destLength) { |
| 1152 |
return i; |
| 1153 |
} |
| 1154 |
|
| 1155 |
ToUpperCaseAppendUpperCaseSpecialCasing(c, destChars, &j); |
| 1156 |
continue; |
| 1157 |
} |
| 1158 |
|
| 1159 |
c = unicode::ToUpperCase(c); |
| 1160 |
if constexpr (std::is_same_v<DestChar, Latin1Char>) { |
| 1161 |
MOZ_ASSERT(c <= JSString::MAX_LATIN1_CHAR); |
| 1162 |
} |
| 1163 |
destChars[j++] = c; |
| 1164 |
} |
| 1165 |
|
| 1166 |
MOZ_ASSERT(j == destLength); |
| 1167 |
return srcLength; |
| 1168 |
} |
| 1169 |
|
| 1170 |
template <typename CharT> |
| 1171 |
static size_t ToUpperCaseLength(const CharT* chars, size_t startIndex, |
| 1172 |
size_t length) { |
| 1173 |
size_t upperLength = length; |
| 1174 |
for (size_t i = startIndex; i < length; i++) { |
| 1175 |
char16_t c = chars[i]; |
| 1176 |
|
| 1177 |
if (c > 0x7f && ToUpperCaseHasSpecialCasing(static_cast<CharT>(c))) { |
| 1178 |
upperLength += ToUpperCaseLengthSpecialCasing(static_cast<CharT>(c)) - 1; |
| 1179 |
} |
| 1180 |
} |
| 1181 |
return upperLength; |
| 1182 |
} |
| 1183 |
|
| 1184 |
template <typename DestChar, typename SrcChar> |
| 1185 |
static inline bool ToUpperCase(JSContext* cx, StringChars<DestChar>& newChars, |
| 1186 |
const SrcChar* chars, size_t startIndex, |
| 1187 |
size_t length, size_t* resultLength) { |
| 1188 |
MOZ_ASSERT(startIndex < length); |
| 1189 |
|
| 1190 |
AutoCheckCannotGC nogc; |
| 1191 |
|
| 1192 |
*resultLength = length; |
| 1193 |
if (!newChars.maybeAlloc(cx, length)) { |
| 1194 |
return false; |
| 1195 |
} |
| 1196 |
|
| 1197 |
CopyChars(newChars.data(nogc), chars, startIndex); |
| 1198 |
|
| 1199 |
size_t readChars = |
| 1200 |
ToUpperCaseImpl(newChars.data(nogc), chars, startIndex, length, length); |
| 1201 |
if (readChars < length) { |
| 1202 |
size_t actualLength = ToUpperCaseLength(chars, readChars, length); |
| 1203 |
|
| 1204 |
*resultLength = actualLength; |
| 1205 |
if (!newChars.maybeRealloc(cx, length, actualLength)) { |
| 1206 |
return false; |
| 1207 |
} |
| 1208 |
|
| 1209 |
MOZ_ALWAYS_TRUE(length == ToUpperCaseImpl(newChars.data(nogc), chars, |
| 1210 |
readChars, length, actualLength)); |
| 1211 |
} |
| 1212 |
|
| 1213 |
return true; |
| 1214 |
} |
| 1215 |
|
| 1216 |
template <typename CharT> |
| 1217 |
static JSLinearString* ToUpperCase(JSContext* cx, JSLinearString* str) { |
| 1218 |
using Latin1StringChars = StringChars<Latin1Char>; |
| 1219 |
using TwoByteStringChars = StringChars<char16_t>; |
| 1220 |
|
| 1221 |
mozilla::MaybeOneOf<Latin1StringChars, TwoByteStringChars> newChars; |
| 1222 |
const size_t length = str->length(); |
| 1223 |
size_t resultLength; |
| 1224 |
{ |
| 1225 |
AutoCheckCannotGC nogc; |
| 1226 |
const CharT* chars = str->chars<CharT>(nogc); |
| 1227 |
|
| 1228 |
// Most one element Latin-1 strings can be directly retrieved from the |
| 1229 |
// static strings cache. |
| 1230 |
if constexpr (std::is_same_v<CharT, Latin1Char>) { |
| 1231 |
if (length == 1) { |
| 1232 |
Latin1Char c = chars[0]; |
| 1233 |
if (c != unicode::MICRO_SIGN && |
| 1234 |
c != unicode::LATIN_SMALL_LETTER_Y_WITH_DIAERESIS && |
| 1235 |
c != unicode::LATIN_SMALL_LETTER_SHARP_S) { |
| 1236 |
char16_t upper = unicode::ToUpperCase(c); |
| 1237 |
MOZ_ASSERT(upper <= JSString::MAX_LATIN1_CHAR); |
| 1238 |
MOZ_ASSERT(StaticStrings::hasUnit(upper)); |
| 1239 |
|
| 1240 |
return cx->staticStrings().getUnit(upper); |
| 1241 |
} |
| 1242 |
|
| 1243 |
MOZ_ASSERT(unicode::ToUpperCase(c) > JSString::MAX_LATIN1_CHAR || |
| 1244 |
ToUpperCaseHasSpecialCasing(c)); |
| 1245 |
} |
| 1246 |
} |
| 1247 |
|
| 1248 |
// Look for the first character that changes when uppercased. |
| 1249 |
size_t i = 0; |
| 1250 |
for (; i < length; i++) { |
| 1251 |
CharT c = chars[i]; |
| 1252 |
if constexpr (!std::is_same_v<CharT, Latin1Char>) { |
| 1253 |
if (unicode::IsLeadSurrogate(c) && i + 1 < length) { |
| 1254 |
CharT trail = chars[i + 1]; |
| 1255 |
if (unicode::IsTrailSurrogate(trail)) { |
| 1256 |
if (unicode::ChangesWhenUpperCasedNonBMP(c, trail)) { |
| 1257 |
break; |
| 1258 |
} |
| 1259 |
|
| 1260 |
i++; |
| 1261 |
continue; |
| 1262 |
} |
| 1263 |
} |
| 1264 |
} |
| 1265 |
if (unicode::ChangesWhenUpperCased(c)) { |
| 1266 |
break; |
| 1267 |
} |
| 1268 |
if (MOZ_UNLIKELY(c > 0x7f && ToUpperCaseHasSpecialCasing(c))) { |
| 1269 |
break; |
| 1270 |
} |
| 1271 |
} |
| 1272 |
|
| 1273 |
// If no character needs to change, return the input string. |
| 1274 |
if (i == length) { |
| 1275 |
return str; |
| 1276 |
} |
| 1277 |
|
| 1278 |
// The string changes when uppercased, so we must create a new string. |
| 1279 |
// Can it be Latin-1? |
| 1280 |
// |
| 1281 |
// If the original string is Latin-1, it can -- unless the string |
| 1282 |
// contains U+00B5 MICRO SIGN or U+00FF SMALL LETTER Y WITH DIAERESIS, |
| 1283 |
// the only Latin-1 codepoints that don't uppercase within Latin-1. |
| 1284 |
// Search for those codepoints to decide whether the new string can be |
| 1285 |
// Latin-1. |
| 1286 |
// If the original string is a two-byte string, its uppercase form is |
| 1287 |
// so rarely Latin-1 that we don't even consider creating a new |
| 1288 |
// Latin-1 string. |
| 1289 |
if constexpr (std::is_same_v<CharT, Latin1Char>) { |
| 1290 |
bool resultIsLatin1 = std::none_of(chars + i, chars + length, [](auto c) { |
| 1291 |
bool upperCaseIsTwoByte = |
| 1292 |
c == unicode::MICRO_SIGN || |
| 1293 |
c == unicode::LATIN_SMALL_LETTER_Y_WITH_DIAERESIS; |
| 1294 |
MOZ_ASSERT(upperCaseIsTwoByte == |
| 1295 |
(unicode::ToUpperCase(c) > JSString::MAX_LATIN1_CHAR)); |
| 1296 |
return upperCaseIsTwoByte; |
| 1297 |
}); |
| 1298 |
|
| 1299 |
if (resultIsLatin1) { |
| 1300 |
newChars.construct<Latin1StringChars>(cx); |
| 1301 |
|
| 1302 |
if (!ToUpperCase(cx, newChars.ref<Latin1StringChars>(), chars, i, |
| 1303 |
length, &resultLength)) { |
| 1304 |
return nullptr; |
| 1305 |
} |
| 1306 |
} else { |
| 1307 |
newChars.construct<TwoByteStringChars>(cx); |
| 1308 |
|
| 1309 |
if (!ToUpperCase(cx, newChars.ref<TwoByteStringChars>(), chars, i, |
| 1310 |
length, &resultLength)) { |
| 1311 |
return nullptr; |
| 1312 |
} |
| 1313 |
} |
| 1314 |
} else { |
| 1315 |
newChars.construct<TwoByteStringChars>(cx); |
| 1316 |
|
| 1317 |
if (!ToUpperCase(cx, newChars.ref<TwoByteStringChars>(), chars, i, length, |
| 1318 |
&resultLength)) { |
| 1319 |
return nullptr; |
| 1320 |
} |
| 1321 |
} |
| 1322 |
} |
| 1323 |
|
| 1324 |
auto toString = [&](auto& chars) { |
| 1325 |
return chars.template toStringDontDeflate<CanGC>(cx, resultLength); |
| 1326 |
}; |
| 1327 |
|
| 1328 |
return newChars.mapNonEmpty(toString); |
| 1329 |
} |
| 1330 |
|
| 1331 |
JSLinearString* js::StringToUpperCase(JSContext* cx, JSString* string) { |
| 1332 |
JSLinearString* linear = string->ensureLinear(cx); |
| 1333 |
if (!linear) { |
| 1334 |
return nullptr; |
| 1335 |
} |
| 1336 |
|
| 1337 |
if (linear->hasLatin1Chars()) { |
| 1338 |
return ToUpperCase<Latin1Char>(cx, linear); |
| 1339 |
} |
| 1340 |
return ToUpperCase<char16_t>(cx, linear); |
| 1341 |
} |
| 1342 |
|
| 1343 |
static bool str_toUpperCase(JSContext* cx, unsigned argc, Value* vp) { |
| 1344 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "toUpperCase"); |
| 1345 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1346 |
|
| 1347 |
JSString* str = ToStringForStringFunction(cx, "toUpperCase", args.thisv()); |
| 1348 |
if (!str) { |
| 1349 |
return false; |
| 1350 |
} |
| 1351 |
|
| 1352 |
JSString* result = StringToUpperCase(cx, str); |
| 1353 |
if (!result) { |
| 1354 |
return false; |
| 1355 |
} |
| 1356 |
|
| 1357 |
args.rval().setString(result); |
| 1358 |
return true; |
| 1359 |
} |
| 1360 |
|
| 1361 |
#if JS_HAS_INTL_API |
| 1362 |
// String.prototype.toLocaleUpperCase is self-hosted when Intl is exposed, |
| 1363 |
// with core functionality performed by the intrinsic below. |
| 1364 |
|
| 1365 |
bool js::intl_toLocaleUpperCase(JSContext* cx, unsigned argc, Value* vp) { |
| 1366 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1367 |
MOZ_ASSERT(args.length() == 2); |
| 1368 |
MOZ_ASSERT(args[0].isString()); |
| 1369 |
MOZ_ASSERT(args[1].isString()); |
| 1370 |
|
| 1371 |
RootedString string(cx, args[0].toString()); |
| 1372 |
|
| 1373 |
const char* locale = CaseMappingLocale(cx, args[1].toString()); |
| 1374 |
if (!locale) { |
| 1375 |
return false; |
| 1376 |
} |
| 1377 |
|
| 1378 |
// Call String.prototype.toUpperCase() for language independent casing. |
| 1379 |
if (HasDefaultCasing(locale)) { |
| 1380 |
JSString* str = js::StringToUpperCase(cx, string); |
| 1381 |
if (!str) { |
| 1382 |
return false; |
| 1383 |
} |
| 1384 |
|
| 1385 |
args.rval().setString(str); |
| 1386 |
return true; |
| 1387 |
} |
| 1388 |
|
| 1389 |
AutoStableStringChars inputChars(cx); |
| 1390 |
if (!inputChars.initTwoByte(cx, string)) { |
| 1391 |
return false; |
| 1392 |
} |
| 1393 |
mozilla::Range<const char16_t> input = inputChars.twoByteRange(); |
| 1394 |
|
| 1395 |
// Note: maximum case mapping length is three characters, so the result |
| 1396 |
// length might be > INT32_MAX. ICU will fail in this case. |
| 1397 |
static_assert(JSString::MAX_LENGTH <= INT32_MAX, |
| 1398 |
"String length must fit in int32_t for ICU"); |
| 1399 |
|
| 1400 |
static const size_t INLINE_CAPACITY = js::intl::INITIAL_CHAR_BUFFER_SIZE; |
| 1401 |
|
| 1402 |
intl::FormatBuffer<char16_t, INLINE_CAPACITY> buffer(cx); |
| 1403 |
|
| 1404 |
auto ok = mozilla::intl::String::ToLocaleUpperCase(locale, input, buffer); |
| 1405 |
if (ok.isErr()) { |
| 1406 |
intl::ReportInternalError(cx, ok.unwrapErr()); |
| 1407 |
return false; |
| 1408 |
} |
| 1409 |
|
| 1410 |
JSString* result = buffer.toString(cx); |
| 1411 |
if (!result) { |
| 1412 |
return false; |
| 1413 |
} |
| 1414 |
|
| 1415 |
args.rval().setString(result); |
| 1416 |
return true; |
| 1417 |
} |
| 1418 |
|
| 1419 |
#else |
| 1420 |
|
| 1421 |
// When the Intl API is not exposed, String.prototype.toUpperCase is implemented |
| 1422 |
// in C++. |
| 1423 |
static bool str_toLocaleUpperCase(JSContext* cx, unsigned argc, Value* vp) { |
| 1424 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", |
| 1425 |
"toLocaleUpperCase"); |
| 1426 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1427 |
|
| 1428 |
RootedString str( |
| 1429 |
cx, ToStringForStringFunction(cx, "toLocaleUpperCase", args.thisv())); |
| 1430 |
if (!str) { |
| 1431 |
return false; |
| 1432 |
} |
| 1433 |
|
| 1434 |
/* |
| 1435 |
* Forcefully ignore the first (or any) argument and return toUpperCase(), |
| 1436 |
* ECMA has reserved that argument, presumably for defining the locale. |
| 1437 |
*/ |
| 1438 |
if (cx->runtime()->localeCallbacks && |
| 1439 |
cx->runtime()->localeCallbacks->localeToUpperCase) { |
| 1440 |
RootedValue result(cx); |
| 1441 |
if (!cx->runtime()->localeCallbacks->localeToUpperCase(cx, str, &result)) { |
| 1442 |
return false; |
| 1443 |
} |
| 1444 |
|
| 1445 |
args.rval().set(result); |
| 1446 |
return true; |
| 1447 |
} |
| 1448 |
|
| 1449 |
Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx)); |
| 1450 |
if (!linear) { |
| 1451 |
return false; |
| 1452 |
} |
| 1453 |
|
| 1454 |
JSString* result = StringToUpperCase(cx, linear); |
| 1455 |
if (!result) { |
| 1456 |
return false; |
| 1457 |
} |
| 1458 |
|
| 1459 |
args.rval().setString(result); |
| 1460 |
return true; |
| 1461 |
} |
| 1462 |
|
| 1463 |
#endif // JS_HAS_INTL_API |
| 1464 |
|
| 1465 |
#if JS_HAS_INTL_API |
| 1466 |
|
| 1467 |
// String.prototype.localeCompare is self-hosted when Intl functionality is |
| 1468 |
// exposed, and the only intrinsics it requires are provided in the |
| 1469 |
// implementation of Intl.Collator. |
| 1470 |
|
| 1471 |
#else |
| 1472 |
|
| 1473 |
// String.prototype.localeCompare is implemented in C++ (delegating to |
| 1474 |
// JSLocaleCallbacks) when Intl functionality is not exposed. |
| 1475 |
static bool str_localeCompare(JSContext* cx, unsigned argc, Value* vp) { |
| 1476 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", |
| 1477 |
"localeCompare"); |
| 1478 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1479 |
|
| 1480 |
RootedString str( |
| 1481 |
cx, ToStringForStringFunction(cx, "localeCompare", args.thisv())); |
| 1482 |
if (!str) { |
| 1483 |
return false; |
| 1484 |
} |
| 1485 |
|
| 1486 |
RootedString thatStr(cx, ToString<CanGC>(cx, args.get(0))); |
| 1487 |
if (!thatStr) { |
| 1488 |
return false; |
| 1489 |
} |
| 1490 |
|
| 1491 |
if (cx->runtime()->localeCallbacks && |
| 1492 |
cx->runtime()->localeCallbacks->localeCompare) { |
| 1493 |
RootedValue result(cx); |
| 1494 |
if (!cx->runtime()->localeCallbacks->localeCompare(cx, str, thatStr, |
| 1495 |
&result)) { |
| 1496 |
return false; |
| 1497 |
} |
| 1498 |
|
| 1499 |
args.rval().set(result); |
| 1500 |
return true; |
| 1501 |
} |
| 1502 |
|
| 1503 |
int32_t result; |
| 1504 |
if (!CompareStrings(cx, str, thatStr, &result)) { |
| 1505 |
return false; |
| 1506 |
} |
| 1507 |
|
| 1508 |
args.rval().setInt32(result); |
| 1509 |
return true; |
| 1510 |
} |
| 1511 |
|
| 1512 |
#endif // JS_HAS_INTL_API |
| 1513 |
|
| 1514 |
#if JS_HAS_INTL_API |
| 1515 |
|
| 1516 |
// ES2017 draft rev 45e890512fd77add72cc0ee742785f9f6f6482de |
| 1517 |
// 21.1.3.12 String.prototype.normalize ( [ form ] ) |
| 1518 |
// |
| 1519 |
// String.prototype.normalize is only implementable if ICU's normalization |
| 1520 |
// functionality is available. |
| 1521 |
static bool str_normalize(JSContext* cx, unsigned argc, Value* vp) { |
| 1522 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "normalize"); |
| 1523 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1524 |
|
| 1525 |
// Steps 1-2. |
| 1526 |
RootedString str(cx, |
| 1527 |
ToStringForStringFunction(cx, "normalize", args.thisv())); |
| 1528 |
if (!str) { |
| 1529 |
return false; |
| 1530 |
} |
| 1531 |
|
| 1532 |
using NormalizationForm = mozilla::intl::String::NormalizationForm; |
| 1533 |
|
| 1534 |
NormalizationForm form; |
| 1535 |
if (!args.hasDefined(0)) { |
| 1536 |
// Step 3. |
| 1537 |
form = NormalizationForm::NFC; |
| 1538 |
} else { |
| 1539 |
// Step 4. |
| 1540 |
JSLinearString* formStr = ArgToLinearString(cx, args, 0); |
| 1541 |
if (!formStr) { |
| 1542 |
return false; |
| 1543 |
} |
| 1544 |
|
| 1545 |
// Step 5. |
| 1546 |
if (EqualStrings(formStr, cx->names().NFC)) { |
| 1547 |
form = NormalizationForm::NFC; |
| 1548 |
} else if (EqualStrings(formStr, cx->names().NFD)) { |
| 1549 |
form = NormalizationForm::NFD; |
| 1550 |
} else if (EqualStrings(formStr, cx->names().NFKC)) { |
| 1551 |
form = NormalizationForm::NFKC; |
| 1552 |
} else if (EqualStrings(formStr, cx->names().NFKD)) { |
| 1553 |
form = NormalizationForm::NFKD; |
| 1554 |
} else { |
| 1555 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 1556 |
JSMSG_INVALID_NORMALIZE_FORM); |
| 1557 |
return false; |
| 1558 |
} |
| 1559 |
} |
| 1560 |
|
| 1561 |
// Latin-1 strings are already in Normalization Form C. |
| 1562 |
if (form == NormalizationForm::NFC && str->hasLatin1Chars()) { |
| 1563 |
// Step 7. |
| 1564 |
args.rval().setString(str); |
| 1565 |
return true; |
| 1566 |
} |
| 1567 |
|
| 1568 |
// Step 6. |
| 1569 |
AutoStableStringChars stableChars(cx); |
| 1570 |
if (!stableChars.initTwoByte(cx, str)) { |
| 1571 |
return false; |
| 1572 |
} |
| 1573 |
|
| 1574 |
mozilla::Range<const char16_t> srcChars = stableChars.twoByteRange(); |
| 1575 |
|
| 1576 |
static const size_t INLINE_CAPACITY = js::intl::INITIAL_CHAR_BUFFER_SIZE; |
| 1577 |
|
| 1578 |
intl::FormatBuffer<char16_t, INLINE_CAPACITY> buffer(cx); |
| 1579 |
|
| 1580 |
auto alreadyNormalized = |
| 1581 |
mozilla::intl::String::Normalize(form, srcChars, buffer); |
| 1582 |
if (alreadyNormalized.isErr()) { |
| 1583 |
intl::ReportInternalError(cx, alreadyNormalized.unwrapErr()); |
| 1584 |
return false; |
| 1585 |
} |
| 1586 |
|
| 1587 |
using AlreadyNormalized = mozilla::intl::String::AlreadyNormalized; |
| 1588 |
|
| 1589 |
// Return if the input string is already normalized. |
| 1590 |
if (alreadyNormalized.unwrap() == AlreadyNormalized::Yes) { |
| 1591 |
// Step 7. |
| 1592 |
args.rval().setString(str); |
| 1593 |
return true; |
| 1594 |
} |
| 1595 |
|
| 1596 |
JSString* ns = buffer.toString(cx); |
| 1597 |
if (!ns) { |
| 1598 |
return false; |
| 1599 |
} |
| 1600 |
|
| 1601 |
// Step 7. |
| 1602 |
args.rval().setString(ns); |
| 1603 |
return true; |
| 1604 |
} |
| 1605 |
|
| 1606 |
#endif // JS_HAS_INTL_API |
| 1607 |
|
| 1608 |
/** |
| 1609 |
* IsStringWellFormedUnicode ( string ) |
| 1610 |
* https://tc39.es/ecma262/#sec-isstringwellformedunicode |
| 1611 |
*/ |
| 1612 |
static bool IsStringWellFormedUnicode(JSContext* cx, HandleString str, |
| 1613 |
size_t* isWellFormedUpTo) { |
| 1614 |
MOZ_ASSERT(isWellFormedUpTo); |
| 1615 |
*isWellFormedUpTo = 0; |
| 1616 |
|
| 1617 |
size_t len = str->length(); |
| 1618 |
|
| 1619 |
// Latin1 chars are well-formed. |
| 1620 |
if (str->hasLatin1Chars()) { |
| 1621 |
*isWellFormedUpTo = len; |
| 1622 |
return true; |
| 1623 |
} |
| 1624 |
|
| 1625 |
JSLinearString* linear = str->ensureLinear(cx); |
| 1626 |
if (!linear) { |
| 1627 |
return false; |
| 1628 |
} |
| 1629 |
|
| 1630 |
{ |
| 1631 |
AutoCheckCannotGC nogc; |
| 1632 |
*isWellFormedUpTo = Utf16ValidUpTo(Span{linear->twoByteChars(nogc), len}); |
| 1633 |
} |
| 1634 |
return true; |
| 1635 |
} |
| 1636 |
|
| 1637 |
/** |
| 1638 |
* Well-Formed Unicode Strings (Stage 3 proposal) |
| 1639 |
* |
| 1640 |
* String.prototype.isWellFormed |
| 1641 |
* https://tc39.es/proposal-is-usv-string/#sec-string.prototype.iswellformed |
| 1642 |
*/ |
| 1643 |
static bool str_isWellFormed(JSContext* cx, unsigned argc, Value* vp) { |
| 1644 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "isWellFormed"); |
| 1645 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1646 |
|
| 1647 |
// Step 1. Let O be ? RequireObjectCoercible(this value). |
| 1648 |
// Step 2. Let S be ? ToString(O). |
| 1649 |
RootedString str(cx, |
| 1650 |
ToStringForStringFunction(cx, "isWellFormed", args.thisv())); |
| 1651 |
if (!str) { |
| 1652 |
return false; |
| 1653 |
} |
| 1654 |
|
| 1655 |
// Step 3. Return IsStringWellFormedUnicode(S). |
| 1656 |
size_t isWellFormedUpTo; |
| 1657 |
if (!IsStringWellFormedUnicode(cx, str, &isWellFormedUpTo)) { |
| 1658 |
return false; |
| 1659 |
} |
| 1660 |
MOZ_ASSERT(isWellFormedUpTo <= str->length()); |
| 1661 |
|
| 1662 |
args.rval().setBoolean(isWellFormedUpTo == str->length()); |
| 1663 |
return true; |
| 1664 |
} |
| 1665 |
|
| 1666 |
/** |
| 1667 |
* Well-Formed Unicode Strings (Stage 3 proposal) |
| 1668 |
* |
| 1669 |
* String.prototype.toWellFormed |
| 1670 |
* https://tc39.es/proposal-is-usv-string/#sec-string.prototype.towellformed |
| 1671 |
*/ |
| 1672 |
static bool str_toWellFormed(JSContext* cx, unsigned argc, Value* vp) { |
| 1673 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "toWellFormed"); |
| 1674 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1675 |
|
| 1676 |
// Step 1. Let O be ? RequireObjectCoercible(this value). |
| 1677 |
// Step 2. Let S be ? ToString(O). |
| 1678 |
RootedString str(cx, |
| 1679 |
ToStringForStringFunction(cx, "toWellFormed", args.thisv())); |
| 1680 |
if (!str) { |
| 1681 |
return false; |
| 1682 |
} |
| 1683 |
|
| 1684 |
// Step 3. Let strLen be the length of S. |
| 1685 |
size_t len = str->length(); |
| 1686 |
|
| 1687 |
// If the string itself is well-formed, return it. |
| 1688 |
size_t isWellFormedUpTo; |
| 1689 |
if (!IsStringWellFormedUnicode(cx, str, &isWellFormedUpTo)) { |
| 1690 |
return false; |
| 1691 |
} |
| 1692 |
if (isWellFormedUpTo == len) { |
| 1693 |
args.rval().setString(str); |
| 1694 |
return true; |
| 1695 |
} |
| 1696 |
MOZ_ASSERT(isWellFormedUpTo < len); |
| 1697 |
|
| 1698 |
// Step 4-6 |
| 1699 |
StringChars<char16_t> newChars(cx); |
| 1700 |
if (!newChars.maybeAlloc(cx, len)) { |
| 1701 |
return false; |
| 1702 |
} |
| 1703 |
|
| 1704 |
{ |
| 1705 |
AutoCheckCannotGC nogc; |
| 1706 |
|
| 1707 |
JSLinearString* linear = str->ensureLinear(cx); |
| 1708 |
MOZ_ASSERT(linear, "IsStringWellFormedUnicode linearized the string"); |
| 1709 |
|
| 1710 |
PodCopy(newChars.data(nogc), linear->twoByteChars(nogc), len); |
| 1711 |
|
| 1712 |
auto span = mozilla::Span{newChars.data(nogc), len}; |
| 1713 |
|
| 1714 |
// Replace the character. |
| 1715 |
span[isWellFormedUpTo] = unicode::REPLACEMENT_CHARACTER; |
| 1716 |
|
| 1717 |
// Check any remaining characters. |
| 1718 |
auto remaining = span.From(isWellFormedUpTo + 1); |
| 1719 |
if (!remaining.IsEmpty()) { |
| 1720 |
EnsureUtf16ValiditySpan(remaining); |
| 1721 |
} |
| 1722 |
} |
| 1723 |
|
| 1724 |
JSString* result = newChars.toStringDontDeflateNonStatic<CanGC>(cx, len); |
| 1725 |
if (!result) { |
| 1726 |
return false; |
| 1727 |
} |
| 1728 |
|
| 1729 |
// Step 7. Return result. |
| 1730 |
args.rval().setString(result); |
| 1731 |
return true; |
| 1732 |
} |
| 1733 |
|
| 1734 |
// Clamp |value| to a string index between 0 and |length|. |
| 1735 |
static MOZ_ALWAYS_INLINE bool ToClampedStringIndex(JSContext* cx, |
| 1736 |
Handle<Value> value, |
| 1737 |
uint32_t length, |
| 1738 |
uint32_t* result) { |
| 1739 |
// Handle the common case of int32 indices first. |
| 1740 |
if (value.isInt32()) { |
| 1741 |
int32_t i = value.toInt32(); |
| 1742 |
*result = std::min(uint32_t(std::max(i, 0)), length); |
| 1743 |
return true; |
| 1744 |
} |
| 1745 |
|
| 1746 |
double d; |
| 1747 |
if (!ToInteger(cx, value, &d)) { |
| 1748 |
return false; |
| 1749 |
} |
| 1750 |
*result = uint32_t(std::clamp(d, 0.0, double(length))); |
| 1751 |
return true; |
| 1752 |
} |
| 1753 |
|
| 1754 |
// Return |Some(index)| if |value| is a string index between 0 and |length|. |
| 1755 |
// Otherwise return |Nothing|. |
| 1756 |
static MOZ_ALWAYS_INLINE bool ToStringIndex(JSContext* cx, Handle<Value> value, |
| 1757 |
size_t length, |
| 1758 |
mozilla::Maybe<size_t>* result) { |
| 1759 |
// Handle the common case of int32 indices first. |
| 1760 |
if (MOZ_LIKELY(value.isInt32())) { |
| 1761 |
size_t index = size_t(value.toInt32()); |
| 1762 |
if (index < length) { |
| 1763 |
*result = mozilla::Some(index); |
| 1764 |
} |
| 1765 |
return true; |
| 1766 |
} |
| 1767 |
|
| 1768 |
double index = 0.0; |
| 1769 |
if (!ToInteger(cx, value, &index)) { |
| 1770 |
return false; |
| 1771 |
} |
| 1772 |
if (0 <= index && index < length) { |
| 1773 |
*result = mozilla::Some(size_t(index)); |
| 1774 |
} |
| 1775 |
return true; |
| 1776 |
} |
| 1777 |
|
| 1778 |
// Return |Some(index)| if |value| is a relative string index between 0 and |
| 1779 |
// |length|. Otherwise return |Nothing|. |
| 1780 |
static MOZ_ALWAYS_INLINE bool ToRelativeStringIndex( |
| 1781 |
JSContext* cx, Handle<Value> value, size_t length, |
| 1782 |
mozilla::Maybe<size_t>* result) { |
| 1783 |
// Handle the common case of int32 indices first. |
| 1784 |
if (MOZ_LIKELY(value.isInt32())) { |
| 1785 |
int32_t index = value.toInt32(); |
| 1786 |
if (index < 0) { |
| 1787 |
index += int32_t(length); |
| 1788 |
} |
| 1789 |
if (size_t(index) < length) { |
| 1790 |
*result = mozilla::Some(size_t(index)); |
| 1791 |
} |
| 1792 |
return true; |
| 1793 |
} |
| 1794 |
|
| 1795 |
double index = 0.0; |
| 1796 |
if (!ToInteger(cx, value, &index)) { |
| 1797 |
return false; |
| 1798 |
} |
| 1799 |
if (index < 0) { |
| 1800 |
index += length; |
| 1801 |
} |
| 1802 |
if (0 <= index && index < length) { |
| 1803 |
*result = mozilla::Some(size_t(index)); |
| 1804 |
} |
| 1805 |
return true; |
| 1806 |
} |
| 1807 |
|
| 1808 |
/** |
| 1809 |
* 22.1.3.2 String.prototype.charAt ( pos ) |
| 1810 |
* |
| 1811 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 1812 |
*/ |
| 1813 |
static bool str_charAt(JSContext* cx, unsigned argc, Value* vp) { |
| 1814 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "charAt"); |
| 1815 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1816 |
|
| 1817 |
// Steps 1-2. |
| 1818 |
RootedString str(cx, ToStringForStringFunction(cx, "charAt", args.thisv())); |
| 1819 |
if (!str) { |
| 1820 |
return false; |
| 1821 |
} |
| 1822 |
|
| 1823 |
// Step 3. |
| 1824 |
mozilla::Maybe<size_t> index{}; |
| 1825 |
if (!ToStringIndex(cx, args.get(0), str->length(), &index)) { |
| 1826 |
return false; |
| 1827 |
} |
| 1828 |
|
| 1829 |
// Steps 4-5. |
| 1830 |
if (index.isNothing()) { |
| 1831 |
args.rval().setString(cx->runtime()->emptyString); |
| 1832 |
return true; |
| 1833 |
} |
| 1834 |
MOZ_ASSERT(*index < str->length()); |
| 1835 |
|
| 1836 |
// Step 6. |
| 1837 |
auto* result = cx->staticStrings().getUnitStringForElement(cx, str, *index); |
| 1838 |
if (!result) { |
| 1839 |
return false; |
| 1840 |
} |
| 1841 |
args.rval().setString(result); |
| 1842 |
return true; |
| 1843 |
} |
| 1844 |
|
| 1845 |
/** |
| 1846 |
* 22.1.3.3 String.prototype.charCodeAt ( pos ) |
| 1847 |
* |
| 1848 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 1849 |
*/ |
| 1850 |
bool js::str_charCodeAt(JSContext* cx, unsigned argc, Value* vp) { |
| 1851 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "charCodeAt"); |
| 1852 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1853 |
|
| 1854 |
// Steps 1-2. |
| 1855 |
RootedString str(cx, |
| 1856 |
ToStringForStringFunction(cx, "charCodeAt", args.thisv())); |
| 1857 |
if (!str) { |
| 1858 |
return false; |
| 1859 |
} |
| 1860 |
|
| 1861 |
// Step 3. |
| 1862 |
mozilla::Maybe<size_t> index{}; |
| 1863 |
if (!ToStringIndex(cx, args.get(0), str->length(), &index)) { |
| 1864 |
return false; |
| 1865 |
} |
| 1866 |
|
| 1867 |
// Steps 4-5. |
| 1868 |
if (index.isNothing()) { |
| 1869 |
args.rval().setNaN(); |
| 1870 |
return true; |
| 1871 |
} |
| 1872 |
MOZ_ASSERT(*index < str->length()); |
| 1873 |
|
| 1874 |
// Step 6. |
| 1875 |
char16_t c; |
| 1876 |
if (!str->getChar(cx, *index, &c)) { |
| 1877 |
return false; |
| 1878 |
} |
| 1879 |
args.rval().setInt32(c); |
| 1880 |
return true; |
| 1881 |
} |
| 1882 |
|
| 1883 |
/** |
| 1884 |
* 22.1.3.4 String.prototype.codePointAt ( pos ) |
| 1885 |
* |
| 1886 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 1887 |
*/ |
| 1888 |
bool js::str_codePointAt(JSContext* cx, unsigned argc, Value* vp) { |
| 1889 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "codePointAt"); |
| 1890 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1891 |
|
| 1892 |
// Steps 1-2. |
| 1893 |
RootedString str(cx, |
| 1894 |
ToStringForStringFunction(cx, "codePointAt", args.thisv())); |
| 1895 |
if (!str) { |
| 1896 |
return false; |
| 1897 |
} |
| 1898 |
|
| 1899 |
// Step 3. |
| 1900 |
mozilla::Maybe<size_t> index{}; |
| 1901 |
if (!ToStringIndex(cx, args.get(0), str->length(), &index)) { |
| 1902 |
return false; |
| 1903 |
} |
| 1904 |
|
| 1905 |
// Steps 4-5. |
| 1906 |
if (index.isNothing()) { |
| 1907 |
args.rval().setUndefined(); |
| 1908 |
return true; |
| 1909 |
} |
| 1910 |
MOZ_ASSERT(*index < str->length()); |
| 1911 |
|
| 1912 |
// Step 6. |
| 1913 |
char32_t codePoint; |
| 1914 |
if (!str->getCodePoint(cx, *index, &codePoint)) { |
| 1915 |
return false; |
| 1916 |
} |
| 1917 |
|
| 1918 |
// Step 7. |
| 1919 |
args.rval().setInt32(codePoint); |
| 1920 |
return true; |
| 1921 |
} |
| 1922 |
|
| 1923 |
/** |
| 1924 |
* 22.1.3.1 String.prototype.at ( index ) |
| 1925 |
* |
| 1926 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 1927 |
*/ |
| 1928 |
static bool str_at(JSContext* cx, unsigned argc, Value* vp) { |
| 1929 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "at"); |
| 1930 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1931 |
|
| 1932 |
// Steps 1-2. |
| 1933 |
RootedString str(cx, ToStringForStringFunction(cx, "at", args.thisv())); |
| 1934 |
if (!str) { |
| 1935 |
return false; |
| 1936 |
} |
| 1937 |
|
| 1938 |
// Steps 3-6. |
| 1939 |
mozilla::Maybe<size_t> index{}; |
| 1940 |
if (!ToRelativeStringIndex(cx, args.get(0), str->length(), &index)) { |
| 1941 |
return false; |
| 1942 |
} |
| 1943 |
|
| 1944 |
// Step 7. |
| 1945 |
if (index.isNothing()) { |
| 1946 |
args.rval().setUndefined(); |
| 1947 |
return true; |
| 1948 |
} |
| 1949 |
MOZ_ASSERT(*index < str->length()); |
| 1950 |
|
| 1951 |
// Step 8. |
| 1952 |
auto* result = cx->staticStrings().getUnitStringForElement(cx, str, *index); |
| 1953 |
if (!result) { |
| 1954 |
return false; |
| 1955 |
} |
| 1956 |
args.rval().setString(result); |
| 1957 |
return true; |
| 1958 |
} |
| 1959 |
|
| 1960 |
/* |
| 1961 |
* Boyer-Moore-Horspool superlinear search for pat:patlen in text:textlen. |
| 1962 |
* The patlen argument must be positive and no greater than sBMHPatLenMax. |
| 1963 |
* |
| 1964 |
* Return the index of pat in text, or -1 if not found. |
| 1965 |
*/ |
| 1966 |
static const uint32_t sBMHCharSetSize = 256; /* ISO-Latin-1 */ |
| 1967 |
static const uint32_t sBMHPatLenMax = 255; /* skip table element is uint8_t */ |
| 1968 |
static const int sBMHBadPattern = |
| 1969 |
-2; /* return value if pat is not ISO-Latin-1 */ |
| 1970 |
|
| 1971 |
template <typename TextChar, typename PatChar> |
| 1972 |
static int BoyerMooreHorspool(const TextChar* text, uint32_t textLen, |
| 1973 |
const PatChar* pat, uint32_t patLen) { |
| 1974 |
MOZ_ASSERT(0 < patLen && patLen <= sBMHPatLenMax); |
| 1975 |
|
| 1976 |
uint8_t skip[sBMHCharSetSize]; |
| 1977 |
for (uint32_t i = 0; i < sBMHCharSetSize; i++) { |
| 1978 |
skip[i] = uint8_t(patLen); |
| 1979 |
} |
| 1980 |
|
| 1981 |
uint32_t patLast = patLen - 1; |
| 1982 |
for (uint32_t i = 0; i < patLast; i++) { |
| 1983 |
char16_t c = pat[i]; |
| 1984 |
if (c >= sBMHCharSetSize) { |
| 1985 |
return sBMHBadPattern; |
| 1986 |
} |
| 1987 |
skip[c] = uint8_t(patLast - i); |
| 1988 |
} |
| 1989 |
|
| 1990 |
for (uint32_t k = patLast; k < textLen;) { |
| 1991 |
for (uint32_t i = k, j = patLast;; i--, j--) { |
| 1992 |
if (text[i] != pat[j]) { |
| 1993 |
break; |
| 1994 |
} |
| 1995 |
if (j == 0) { |
| 1996 |
return static_cast<int>(i); /* safe: max string size */ |
| 1997 |
} |
| 1998 |
} |
| 1999 |
|
| 2000 |
char16_t c = text[k]; |
| 2001 |
k += (c >= sBMHCharSetSize) ? patLen : skip[c]; |
| 2002 |
} |
| 2003 |
return -1; |
| 2004 |
} |
| 2005 |
|
| 2006 |
template <typename TextChar, typename PatChar> |
| 2007 |
struct MemCmp { |
| 2008 |
using Extent = uint32_t; |
| 2009 |
static MOZ_ALWAYS_INLINE Extent computeExtent(const PatChar*, |
| 2010 |
uint32_t patLen) { |
| 2011 |
return (patLen - 2) * sizeof(PatChar); |
| 2012 |
} |
| 2013 |
static MOZ_ALWAYS_INLINE bool match(const PatChar* p, const TextChar* t, |
| 2014 |
Extent extent) { |
| 2015 |
MOZ_ASSERT(sizeof(TextChar) == sizeof(PatChar)); |
| 2016 |
return memcmp(p, t, extent) == 0; |
| 2017 |
} |
| 2018 |
}; |
| 2019 |
|
| 2020 |
template <typename TextChar, typename PatChar> |
| 2021 |
struct ManualCmp { |
| 2022 |
using Extent = const PatChar*; |
| 2023 |
static MOZ_ALWAYS_INLINE Extent computeExtent(const PatChar* pat, |
| 2024 |
uint32_t patLen) { |
| 2025 |
return pat + patLen; |
| 2026 |
} |
| 2027 |
static MOZ_ALWAYS_INLINE bool match(const PatChar* p, const TextChar* t, |
| 2028 |
Extent extent) { |
| 2029 |
for (; p != extent; ++p, ++t) { |
| 2030 |
if (*p != *t) { |
| 2031 |
return false; |
| 2032 |
} |
| 2033 |
} |
| 2034 |
return true; |
| 2035 |
} |
| 2036 |
}; |
| 2037 |
|
| 2038 |
template <class InnerMatch, typename TextChar, typename PatChar> |
| 2039 |
static int Matcher(const TextChar* text, uint32_t textlen, const PatChar* pat, |
| 2040 |
uint32_t patlen) { |
| 2041 |
MOZ_ASSERT(patlen > 1); |
| 2042 |
|
| 2043 |
const typename InnerMatch::Extent extent = |
| 2044 |
InnerMatch::computeExtent(pat, patlen); |
| 2045 |
|
| 2046 |
uint32_t i = 0; |
| 2047 |
uint32_t n = textlen - patlen + 1; |
| 2048 |
|
| 2049 |
while (i < n) { |
| 2050 |
const TextChar* pos; |
| 2051 |
|
| 2052 |
// This is a bit awkward. Consider the case where we're searching "abcdef" |
| 2053 |
// for "def". n will be 4, because we know in advance that the last place we |
| 2054 |
// can *start* a successful search will be at 'd'. However, if we just use n |
| 2055 |
// - i, then our first search will be looking through "abcd" for "de", |
| 2056 |
// because our memchr2xN functions search for two characters at a time. So |
| 2057 |
// we just have to compensate by adding 1. This will never exceed textlen |
| 2058 |
// because we know patlen is at least two. |
| 2059 |
size_t searchLen = n - i + 1; |
| 2060 |
if (sizeof(TextChar) == 1) { |
| 2061 |
MOZ_ASSERT(pat[0] <= 0xff); |
| 2062 |
pos = (TextChar*)SIMD::memchr2x8((char*)text + i, pat[0], pat[1], |
| 2063 |
searchLen); |
| 2064 |
} else { |
| 2065 |
pos = (TextChar*)SIMD::memchr2x16((char16_t*)(text + i), char16_t(pat[0]), |
| 2066 |
char16_t(pat[1]), searchLen); |
| 2067 |
} |
| 2068 |
|
| 2069 |
if (pos == nullptr) { |
| 2070 |
return -1; |
| 2071 |
} |
| 2072 |
|
| 2073 |
i = static_cast<uint32_t>(pos - text); |
| 2074 |
const uint32_t inlineLookaheadChars = 2; |
| 2075 |
if (InnerMatch::match(pat + inlineLookaheadChars, |
| 2076 |
text + i + inlineLookaheadChars, extent)) { |
| 2077 |
return i; |
| 2078 |
} |
| 2079 |
|
| 2080 |
i += 1; |
| 2081 |
} |
| 2082 |
return -1; |
| 2083 |
} |
| 2084 |
|
| 2085 |
template <typename TextChar, typename PatChar> |
| 2086 |
static MOZ_ALWAYS_INLINE int StringMatch(const TextChar* text, uint32_t textLen, |
| 2087 |
const PatChar* pat, uint32_t patLen) { |
| 2088 |
if (patLen == 0) { |
| 2089 |
return 0; |
| 2090 |
} |
| 2091 |
if (textLen < patLen) { |
| 2092 |
return -1; |
| 2093 |
} |
| 2094 |
|
| 2095 |
if (sizeof(TextChar) == 1 && sizeof(PatChar) > 1 && pat[0] > 0xff) { |
| 2096 |
return -1; |
| 2097 |
} |
| 2098 |
|
| 2099 |
if (patLen == 1) { |
| 2100 |
const TextChar* pos; |
| 2101 |
if (sizeof(TextChar) == 1) { |
| 2102 |
MOZ_ASSERT(pat[0] <= 0xff); |
| 2103 |
pos = (TextChar*)SIMD::memchr8((char*)text, pat[0], textLen); |
| 2104 |
} else { |
| 2105 |
pos = |
| 2106 |
(TextChar*)SIMD::memchr16((char16_t*)text, char16_t(pat[0]), textLen); |
| 2107 |
} |
| 2108 |
|
| 2109 |
if (pos == nullptr) { |
| 2110 |
return -1; |
| 2111 |
} |
| 2112 |
|
| 2113 |
return pos - text; |
| 2114 |
} |
| 2115 |
|
| 2116 |
// We use a fast two-character-wide search in Matcher below, so we need to |
| 2117 |
// validate that pat[1] isn't outside the latin1 range up front if the |
| 2118 |
// sizes are different. |
| 2119 |
if (sizeof(TextChar) == 1 && sizeof(PatChar) > 1 && pat[1] > 0xff) { |
| 2120 |
return -1; |
| 2121 |
} |
| 2122 |
|
| 2123 |
/* |
| 2124 |
* If the text or pattern string is short, BMH will be more expensive than |
| 2125 |
* the basic linear scan due to initialization cost and a more complex loop |
| 2126 |
* body. While the correct threshold is input-dependent, we can make a few |
| 2127 |
* conservative observations: |
| 2128 |
* - When |textLen| is "big enough", the initialization time will be |
| 2129 |
* proportionally small, so the worst-case slowdown is minimized. |
| 2130 |
* - When |patLen| is "too small", even the best case for BMH will be |
| 2131 |
* slower than a simple scan for large |textLen| due to the more complex |
| 2132 |
* loop body of BMH. |
| 2133 |
* From this, the values for "big enough" and "too small" are determined |
| 2134 |
* empirically. See bug 526348. |
| 2135 |
*/ |
| 2136 |
if (textLen >= 512 && patLen >= 11 && patLen <= sBMHPatLenMax) { |
| 2137 |
int index = BoyerMooreHorspool(text, textLen, pat, patLen); |
| 2138 |
if (index != sBMHBadPattern) { |
| 2139 |
return index; |
| 2140 |
} |
| 2141 |
} |
| 2142 |
|
| 2143 |
/* |
| 2144 |
* For big patterns with large potential overlap we want the SIMD-optimized |
| 2145 |
* speed of memcmp. For small patterns, a simple loop is faster. We also can't |
| 2146 |
* use memcmp if one of the strings is TwoByte and the other is Latin-1. |
| 2147 |
*/ |
| 2148 |
return (patLen > 128 && std::is_same_v<TextChar, PatChar>) |
| 2149 |
? Matcher<MemCmp<TextChar, PatChar>, TextChar, PatChar>( |
| 2150 |
text, textLen, pat, patLen) |
| 2151 |
: Matcher<ManualCmp<TextChar, PatChar>, TextChar, PatChar>( |
| 2152 |
text, textLen, pat, patLen); |
| 2153 |
} |
| 2154 |
|
| 2155 |
static int32_t StringMatch(const JSLinearString* text, |
| 2156 |
const JSLinearString* pat, uint32_t start = 0) { |
| 2157 |
MOZ_ASSERT(start <= text->length()); |
| 2158 |
uint32_t textLen = text->length() - start; |
| 2159 |
uint32_t patLen = pat->length(); |
| 2160 |
|
| 2161 |
int match; |
| 2162 |
AutoCheckCannotGC nogc; |
| 2163 |
if (text->hasLatin1Chars()) { |
| 2164 |
const Latin1Char* textChars = text->latin1Chars(nogc) + start; |
| 2165 |
if (pat->hasLatin1Chars()) { |
| 2166 |
match = StringMatch(textChars, textLen, pat->latin1Chars(nogc), patLen); |
| 2167 |
} else { |
| 2168 |
match = StringMatch(textChars, textLen, pat->twoByteChars(nogc), patLen); |
| 2169 |
} |
| 2170 |
} else { |
| 2171 |
const char16_t* textChars = text->twoByteChars(nogc) + start; |
| 2172 |
if (pat->hasLatin1Chars()) { |
| 2173 |
match = StringMatch(textChars, textLen, pat->latin1Chars(nogc), patLen); |
| 2174 |
} else { |
| 2175 |
match = StringMatch(textChars, textLen, pat->twoByteChars(nogc), patLen); |
| 2176 |
} |
| 2177 |
} |
| 2178 |
|
| 2179 |
return (match == -1) ? -1 : start + match; |
| 2180 |
} |
| 2181 |
|
| 2182 |
static const size_t sRopeMatchThresholdRatioLog2 = 4; |
| 2183 |
|
| 2184 |
int js::StringFindPattern(const JSLinearString* text, const JSLinearString* pat, |
| 2185 |
size_t start) { |
| 2186 |
return StringMatch(text, pat, start); |
| 2187 |
} |
| 2188 |
|
| 2189 |
using LinearStringVector = Vector<JSLinearString*, 16, SystemAllocPolicy>; |
| 2190 |
|
| 2191 |
template <typename TextChar, typename PatChar> |
| 2192 |
static int RopeMatchImpl(const AutoCheckCannotGC& nogc, |
| 2193 |
LinearStringVector& strings, const PatChar* pat, |
| 2194 |
size_t patLen) { |
| 2195 |
/* Absolute offset from the beginning of the logical text string. */ |
| 2196 |
int pos = 0; |
| 2197 |
|
| 2198 |
for (JSLinearString** outerp = strings.begin(); outerp != strings.end(); |
| 2199 |
++outerp) { |
| 2200 |
/* Try to find a match within 'outer'. */ |
| 2201 |
JSLinearString* outer = *outerp; |
| 2202 |
const TextChar* chars = outer->chars<TextChar>(nogc); |
| 2203 |
size_t len = outer->length(); |
| 2204 |
int matchResult = StringMatch(chars, len, pat, patLen); |
| 2205 |
if (matchResult != -1) { |
| 2206 |
/* Matched! */ |
| 2207 |
return pos + matchResult; |
| 2208 |
} |
| 2209 |
|
| 2210 |
/* Try to find a match starting in 'outer' and running into other nodes. */ |
| 2211 |
const TextChar* const text = chars + (patLen > len ? 0 : len - patLen + 1); |
| 2212 |
const TextChar* const textend = chars + len; |
| 2213 |
const PatChar p0 = *pat; |
| 2214 |
const PatChar* const p1 = pat + 1; |
| 2215 |
const PatChar* const patend = pat + patLen; |
| 2216 |
for (const TextChar* t = text; t != textend;) { |
| 2217 |
if (*t++ != p0) { |
| 2218 |
continue; |
| 2219 |
} |
| 2220 |
|
| 2221 |
JSLinearString** innerp = outerp; |
| 2222 |
const TextChar* ttend = textend; |
| 2223 |
const TextChar* tt = t; |
| 2224 |
for (const PatChar* pp = p1; pp != patend; ++pp, ++tt) { |
| 2225 |
while (tt == ttend) { |
| 2226 |
if (++innerp == strings.end()) { |
| 2227 |
return -1; |
| 2228 |
} |
| 2229 |
|
| 2230 |
JSLinearString* inner = *innerp; |
| 2231 |
tt = inner->chars<TextChar>(nogc); |
| 2232 |
ttend = tt + inner->length(); |
| 2233 |
} |
| 2234 |
if (*pp != *tt) { |
| 2235 |
goto break_continue; |
| 2236 |
} |
| 2237 |
} |
| 2238 |
|
| 2239 |
/* Matched! */ |
| 2240 |
return pos + (t - chars) - 1; /* -1 because of *t++ above */ |
| 2241 |
|
| 2242 |
break_continue:; |
| 2243 |
} |
| 2244 |
|
| 2245 |
pos += len; |
| 2246 |
} |
| 2247 |
|
| 2248 |
return -1; |
| 2249 |
} |
| 2250 |
|
| 2251 |
/* |
| 2252 |
* RopeMatch takes the text to search and the pattern to search for in the text. |
| 2253 |
* RopeMatch returns false on OOM and otherwise returns the match index through |
| 2254 |
* the 'match' outparam (-1 for not found). |
| 2255 |
*/ |
| 2256 |
static bool RopeMatch(JSContext* cx, JSRope* text, const JSLinearString* pat, |
| 2257 |
int* match) { |
| 2258 |
uint32_t patLen = pat->length(); |
| 2259 |
if (patLen == 0) { |
| 2260 |
*match = 0; |
| 2261 |
return true; |
| 2262 |
} |
| 2263 |
if (text->length() < patLen) { |
| 2264 |
*match = -1; |
| 2265 |
return true; |
| 2266 |
} |
| 2267 |
|
| 2268 |
/* |
| 2269 |
* List of leaf nodes in the rope. If we run out of memory when trying to |
| 2270 |
* append to this list, we can still fall back to StringMatch, so use the |
| 2271 |
* system allocator so we don't report OOM in that case. |
| 2272 |
*/ |
| 2273 |
LinearStringVector strings; |
| 2274 |
|
| 2275 |
/* |
| 2276 |
* We don't want to do rope matching if there is a poor node-to-char ratio, |
| 2277 |
* since this means spending a lot of time in the match loop below. We also |
| 2278 |
* need to build the list of leaf nodes. Do both here: iterate over the |
| 2279 |
* nodes so long as there are not too many. |
| 2280 |
* |
| 2281 |
* We also don't use rope matching if the rope contains both Latin-1 and |
| 2282 |
* TwoByte nodes, to simplify the match algorithm. |
| 2283 |
*/ |
| 2284 |
{ |
| 2285 |
size_t threshold = text->length() >> sRopeMatchThresholdRatioLog2; |
| 2286 |
StringSegmentRange r(cx); |
| 2287 |
if (!r.init(text)) { |
| 2288 |
return false; |
| 2289 |
} |
| 2290 |
|
| 2291 |
bool textIsLatin1 = text->hasLatin1Chars(); |
| 2292 |
while (!r.empty()) { |
| 2293 |
if (threshold-- == 0 || r.front()->hasLatin1Chars() != textIsLatin1 || |
| 2294 |
!strings.append(r.front())) { |
| 2295 |
JSLinearString* linear = text->ensureLinear(cx); |
| 2296 |
if (!linear) { |
| 2297 |
return false; |
| 2298 |
} |
| 2299 |
|
| 2300 |
*match = StringMatch(linear, pat); |
| 2301 |
return true; |
| 2302 |
} |
| 2303 |
if (!r.popFront()) { |
| 2304 |
return false; |
| 2305 |
} |
| 2306 |
} |
| 2307 |
} |
| 2308 |
|
| 2309 |
AutoCheckCannotGC nogc; |
| 2310 |
if (text->hasLatin1Chars()) { |
| 2311 |
if (pat->hasLatin1Chars()) { |
| 2312 |
*match = RopeMatchImpl<Latin1Char>(nogc, strings, pat->latin1Chars(nogc), |
| 2313 |
patLen); |
| 2314 |
} else { |
| 2315 |
*match = RopeMatchImpl<Latin1Char>(nogc, strings, pat->twoByteChars(nogc), |
| 2316 |
patLen); |
| 2317 |
} |
| 2318 |
} else { |
| 2319 |
if (pat->hasLatin1Chars()) { |
| 2320 |
*match = RopeMatchImpl<char16_t>(nogc, strings, pat->latin1Chars(nogc), |
| 2321 |
patLen); |
| 2322 |
} else { |
| 2323 |
*match = RopeMatchImpl<char16_t>(nogc, strings, pat->twoByteChars(nogc), |
| 2324 |
patLen); |
| 2325 |
} |
| 2326 |
} |
| 2327 |
|
| 2328 |
return true; |
| 2329 |
} |
| 2330 |
|
| 2331 |
static MOZ_ALWAYS_INLINE bool ReportErrorIfFirstArgIsRegExp( |
| 2332 |
JSContext* cx, const CallArgs& args) { |
| 2333 |
// Only call IsRegExp if the first argument is definitely an object, so we |
| 2334 |
// don't pay the cost of an additional function call in the common case. |
| 2335 |
if (args.length() == 0 || !args[0].isObject()) { |
| 2336 |
return true; |
| 2337 |
} |
| 2338 |
|
| 2339 |
bool isRegExp; |
| 2340 |
if (!IsRegExp(cx, args[0], &isRegExp)) { |
| 2341 |
return false; |
| 2342 |
} |
| 2343 |
|
| 2344 |
if (isRegExp) { |
| 2345 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 2346 |
JSMSG_INVALID_ARG_TYPE, "first", "", |
| 2347 |
"Regular Expression"); |
| 2348 |
return false; |
| 2349 |
} |
| 2350 |
return true; |
| 2351 |
} |
| 2352 |
|
| 2353 |
// ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b |
| 2354 |
// 22.1.3.8 String.prototype.includes ( searchString [ , position ] ) |
| 2355 |
bool js::str_includes(JSContext* cx, unsigned argc, Value* vp) { |
| 2356 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "includes"); |
| 2357 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2358 |
|
| 2359 |
// Steps 1-2. |
| 2360 |
RootedString str(cx, ToStringForStringFunction(cx, "includes", args.thisv())); |
| 2361 |
if (!str) { |
| 2362 |
return false; |
| 2363 |
} |
| 2364 |
|
| 2365 |
// Steps 3-4. |
| 2366 |
if (!ReportErrorIfFirstArgIsRegExp(cx, args)) { |
| 2367 |
return false; |
| 2368 |
} |
| 2369 |
|
| 2370 |
// Step 5. |
| 2371 |
Rooted<JSLinearString*> searchStr(cx, ArgToLinearString(cx, args, 0)); |
| 2372 |
if (!searchStr) { |
| 2373 |
return false; |
| 2374 |
} |
| 2375 |
|
| 2376 |
// Steps 6-9. |
| 2377 |
uint32_t start = 0; |
| 2378 |
if (args.hasDefined(1)) { |
| 2379 |
if (!ToClampedStringIndex(cx, args[1], str->length(), &start)) { |
| 2380 |
return false; |
| 2381 |
} |
| 2382 |
} |
| 2383 |
|
| 2384 |
// Steps 10-12. |
| 2385 |
JSLinearString* text = str->ensureLinear(cx); |
| 2386 |
if (!text) { |
| 2387 |
return false; |
| 2388 |
} |
| 2389 |
|
| 2390 |
args.rval().setBoolean(StringMatch(text, searchStr, start) != -1); |
| 2391 |
return true; |
| 2392 |
} |
| 2393 |
|
| 2394 |
bool js::StringIncludes(JSContext* cx, HandleString string, |
| 2395 |
HandleString searchString, bool* result) { |
| 2396 |
JSLinearString* text = string->ensureLinear(cx); |
| 2397 |
if (!text) { |
| 2398 |
return false; |
| 2399 |
} |
| 2400 |
|
| 2401 |
JSLinearString* searchStr = searchString->ensureLinear(cx); |
| 2402 |
if (!searchStr) { |
| 2403 |
return false; |
| 2404 |
} |
| 2405 |
|
| 2406 |
*result = StringMatch(text, searchStr, 0) != -1; |
| 2407 |
return true; |
| 2408 |
} |
| 2409 |
|
| 2410 |
// ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b |
| 2411 |
// 22.1.3.9 String.prototype.indexOf ( searchString [ , position ] ) |
| 2412 |
bool js::str_indexOf(JSContext* cx, unsigned argc, Value* vp) { |
| 2413 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "indexOf"); |
| 2414 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2415 |
|
| 2416 |
// Steps 1-2. |
| 2417 |
RootedString str(cx, ToStringForStringFunction(cx, "indexOf", args.thisv())); |
| 2418 |
if (!str) { |
| 2419 |
return false; |
| 2420 |
} |
| 2421 |
|
| 2422 |
// Step 3. |
| 2423 |
Rooted<JSLinearString*> searchStr(cx, ArgToLinearString(cx, args, 0)); |
| 2424 |
if (!searchStr) { |
| 2425 |
return false; |
| 2426 |
} |
| 2427 |
|
| 2428 |
// Steps 4-7. |
| 2429 |
uint32_t start = 0; |
| 2430 |
if (args.hasDefined(1)) { |
| 2431 |
if (!ToClampedStringIndex(cx, args[1], str->length(), &start)) { |
| 2432 |
return false; |
| 2433 |
} |
| 2434 |
} |
| 2435 |
|
| 2436 |
if (str == searchStr) { |
| 2437 |
// AngularJS often invokes "false".indexOf("false"). This check should |
| 2438 |
// be cheap enough to not hurt anything else. |
| 2439 |
args.rval().setInt32(start == 0 ? 0 : -1); |
| 2440 |
return true; |
| 2441 |
} |
| 2442 |
|
| 2443 |
// Steps 8-10. |
| 2444 |
JSLinearString* text = str->ensureLinear(cx); |
| 2445 |
if (!text) { |
| 2446 |
return false; |
| 2447 |
} |
| 2448 |
|
| 2449 |
args.rval().setInt32(StringMatch(text, searchStr, start)); |
| 2450 |
return true; |
| 2451 |
} |
| 2452 |
|
| 2453 |
bool js::StringIndexOf(JSContext* cx, HandleString string, |
| 2454 |
HandleString searchString, int32_t* result) { |
| 2455 |
if (string == searchString) { |
| 2456 |
*result = 0; |
| 2457 |
return true; |
| 2458 |
} |
| 2459 |
|
| 2460 |
JSLinearString* text = string->ensureLinear(cx); |
| 2461 |
if (!text) { |
| 2462 |
return false; |
| 2463 |
} |
| 2464 |
|
| 2465 |
JSLinearString* searchStr = searchString->ensureLinear(cx); |
| 2466 |
if (!searchStr) { |
| 2467 |
return false; |
| 2468 |
} |
| 2469 |
|
| 2470 |
*result = StringMatch(text, searchStr, 0); |
| 2471 |
return true; |
| 2472 |
} |
| 2473 |
|
| 2474 |
template <typename TextChar, typename PatChar> |
| 2475 |
static int32_t LastIndexOfImpl(const TextChar* text, size_t textLen, |
| 2476 |
const PatChar* pat, size_t patLen, |
| 2477 |
size_t start) { |
| 2478 |
MOZ_ASSERT(patLen > 0); |
| 2479 |
MOZ_ASSERT(patLen <= textLen); |
| 2480 |
MOZ_ASSERT(start <= textLen - patLen); |
| 2481 |
|
| 2482 |
const PatChar p0 = *pat; |
| 2483 |
const PatChar* patNext = pat + 1; |
| 2484 |
const PatChar* patEnd = pat + patLen; |
| 2485 |
|
| 2486 |
for (const TextChar* t = text + start; t >= text; --t) { |
| 2487 |
if (*t == p0) { |
| 2488 |
const TextChar* t1 = t + 1; |
| 2489 |
for (const PatChar* p1 = patNext; p1 < patEnd; ++p1, ++t1) { |
| 2490 |
if (*t1 != *p1) { |
| 2491 |
goto break_continue; |
| 2492 |
} |
| 2493 |
} |
| 2494 |
|
| 2495 |
return static_cast<int32_t>(t - text); |
| 2496 |
} |
| 2497 |
break_continue:; |
| 2498 |
} |
| 2499 |
|
| 2500 |
return -1; |
| 2501 |
} |
| 2502 |
|
| 2503 |
static int32_t LastIndexOf(const JSLinearString* text, |
| 2504 |
const JSLinearString* searchStr, size_t start) { |
| 2505 |
AutoCheckCannotGC nogc; |
| 2506 |
|
| 2507 |
size_t len = text->length(); |
| 2508 |
size_t searchLen = searchStr->length(); |
| 2509 |
|
| 2510 |
if (text->hasLatin1Chars()) { |
| 2511 |
const Latin1Char* textChars = text->latin1Chars(nogc); |
| 2512 |
if (searchStr->hasLatin1Chars()) { |
| 2513 |
return LastIndexOfImpl(textChars, len, searchStr->latin1Chars(nogc), |
| 2514 |
searchLen, start); |
| 2515 |
} |
| 2516 |
return LastIndexOfImpl(textChars, len, searchStr->twoByteChars(nogc), |
| 2517 |
searchLen, start); |
| 2518 |
} |
| 2519 |
|
| 2520 |
const char16_t* textChars = text->twoByteChars(nogc); |
| 2521 |
if (searchStr->hasLatin1Chars()) { |
| 2522 |
return LastIndexOfImpl(textChars, len, searchStr->latin1Chars(nogc), |
| 2523 |
searchLen, start); |
| 2524 |
} |
| 2525 |
return LastIndexOfImpl(textChars, len, searchStr->twoByteChars(nogc), |
| 2526 |
searchLen, start); |
| 2527 |
} |
| 2528 |
|
| 2529 |
// ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b |
| 2530 |
// 22.1.3.11 String.prototype.lastIndexOf ( searchString [ , position ] ) |
| 2531 |
static bool str_lastIndexOf(JSContext* cx, unsigned argc, Value* vp) { |
| 2532 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "lastIndexOf"); |
| 2533 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2534 |
|
| 2535 |
// Steps 1-2. |
| 2536 |
RootedString str(cx, |
| 2537 |
ToStringForStringFunction(cx, "lastIndexOf", args.thisv())); |
| 2538 |
if (!str) { |
| 2539 |
return false; |
| 2540 |
} |
| 2541 |
|
| 2542 |
// Step 3. |
| 2543 |
Rooted<JSLinearString*> searchStr(cx, ArgToLinearString(cx, args, 0)); |
| 2544 |
if (!searchStr) { |
| 2545 |
return false; |
| 2546 |
} |
| 2547 |
|
| 2548 |
// Step 7. |
| 2549 |
size_t len = str->length(); |
| 2550 |
|
| 2551 |
// Step 8. |
| 2552 |
size_t searchLen = searchStr->length(); |
| 2553 |
|
| 2554 |
// Steps 4-6 and 9. |
| 2555 |
int start = len - searchLen; // Start searching here |
| 2556 |
if (args.hasDefined(1)) { |
| 2557 |
if (args[1].isInt32()) { |
| 2558 |
int i = args[1].toInt32(); |
| 2559 |
if (i <= 0) { |
| 2560 |
start = 0; |
| 2561 |
} else if (i < start) { |
| 2562 |
start = i; |
| 2563 |
} |
| 2564 |
} else { |
| 2565 |
double d; |
| 2566 |
if (!ToNumber(cx, args[1], &d)) { |
| 2567 |
return false; |
| 2568 |
} |
| 2569 |
if (!std::isnan(d)) { |
| 2570 |
d = JS::ToInteger(d); |
| 2571 |
if (d <= 0) { |
| 2572 |
start = 0; |
| 2573 |
} else if (d < start) { |
| 2574 |
start = int(d); |
| 2575 |
} |
| 2576 |
} |
| 2577 |
} |
| 2578 |
} |
| 2579 |
|
| 2580 |
if (str == searchStr) { |
| 2581 |
args.rval().setInt32(0); |
| 2582 |
return true; |
| 2583 |
} |
| 2584 |
|
| 2585 |
if (searchLen > len) { |
| 2586 |
args.rval().setInt32(-1); |
| 2587 |
return true; |
| 2588 |
} |
| 2589 |
|
| 2590 |
if (searchLen == 0) { |
| 2591 |
args.rval().setInt32(start); |
| 2592 |
return true; |
| 2593 |
} |
| 2594 |
MOZ_ASSERT(0 <= start && size_t(start) < len); |
| 2595 |
|
| 2596 |
JSLinearString* text = str->ensureLinear(cx); |
| 2597 |
if (!text) { |
| 2598 |
return false; |
| 2599 |
} |
| 2600 |
|
| 2601 |
// Step 10-12. |
| 2602 |
args.rval().setInt32(LastIndexOf(text, searchStr, start)); |
| 2603 |
return true; |
| 2604 |
} |
| 2605 |
|
| 2606 |
bool js::StringLastIndexOf(JSContext* cx, HandleString string, |
| 2607 |
HandleString searchString, int32_t* result) { |
| 2608 |
if (string == searchString) { |
| 2609 |
*result = 0; |
| 2610 |
return true; |
| 2611 |
} |
| 2612 |
|
| 2613 |
size_t len = string->length(); |
| 2614 |
size_t searchLen = searchString->length(); |
| 2615 |
|
| 2616 |
if (searchLen > len) { |
| 2617 |
*result = -1; |
| 2618 |
return true; |
| 2619 |
} |
| 2620 |
|
| 2621 |
MOZ_ASSERT(len >= searchLen); |
| 2622 |
size_t start = len - searchLen; |
| 2623 |
|
| 2624 |
if (searchLen == 0) { |
| 2625 |
*result = start; |
| 2626 |
return true; |
| 2627 |
} |
| 2628 |
MOZ_ASSERT(start < len); |
| 2629 |
|
| 2630 |
JSLinearString* text = string->ensureLinear(cx); |
| 2631 |
if (!text) { |
| 2632 |
return false; |
| 2633 |
} |
| 2634 |
|
| 2635 |
JSLinearString* searchStr = searchString->ensureLinear(cx); |
| 2636 |
if (!searchStr) { |
| 2637 |
return false; |
| 2638 |
} |
| 2639 |
|
| 2640 |
*result = LastIndexOf(text, searchStr, start); |
| 2641 |
return true; |
| 2642 |
} |
| 2643 |
|
| 2644 |
// ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b |
| 2645 |
// 22.1.3.24 String.prototype.startsWith ( searchString [ , position ] ) |
| 2646 |
bool js::str_startsWith(JSContext* cx, unsigned argc, Value* vp) { |
| 2647 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "startsWith"); |
| 2648 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2649 |
|
| 2650 |
// Steps 1-2. |
| 2651 |
RootedString str(cx, |
| 2652 |
ToStringForStringFunction(cx, "startsWith", args.thisv())); |
| 2653 |
if (!str) { |
| 2654 |
return false; |
| 2655 |
} |
| 2656 |
|
| 2657 |
// Steps 3-4. |
| 2658 |
if (!ReportErrorIfFirstArgIsRegExp(cx, args)) { |
| 2659 |
return false; |
| 2660 |
} |
| 2661 |
|
| 2662 |
// Step 5. |
| 2663 |
Rooted<JSLinearString*> searchStr(cx, ArgToLinearString(cx, args, 0)); |
| 2664 |
if (!searchStr) { |
| 2665 |
return false; |
| 2666 |
} |
| 2667 |
|
| 2668 |
// Step 6. |
| 2669 |
uint32_t textLen = str->length(); |
| 2670 |
|
| 2671 |
// Steps 7-8. |
| 2672 |
uint32_t start = 0; |
| 2673 |
if (args.hasDefined(1)) { |
| 2674 |
if (!ToClampedStringIndex(cx, args[1], textLen, &start)) { |
| 2675 |
return false; |
| 2676 |
} |
| 2677 |
} |
| 2678 |
|
| 2679 |
// Step 9. |
| 2680 |
uint32_t searchLen = searchStr->length(); |
| 2681 |
|
| 2682 |
// Step 12. |
| 2683 |
if (searchLen + start < searchLen || searchLen + start > textLen) { |
| 2684 |
args.rval().setBoolean(false); |
| 2685 |
return true; |
| 2686 |
} |
| 2687 |
|
| 2688 |
// Steps 10-11 and 13-15. |
| 2689 |
JSLinearString* text = str->ensureLinear(cx); |
| 2690 |
if (!text) { |
| 2691 |
return false; |
| 2692 |
} |
| 2693 |
|
| 2694 |
args.rval().setBoolean(HasSubstringAt(text, searchStr, start)); |
| 2695 |
return true; |
| 2696 |
} |
| 2697 |
|
| 2698 |
bool js::StringStartsWith(JSContext* cx, HandleString string, |
| 2699 |
HandleString searchString, bool* result) { |
| 2700 |
if (searchString->length() > string->length()) { |
| 2701 |
*result = false; |
| 2702 |
return true; |
| 2703 |
} |
| 2704 |
|
| 2705 |
JSLinearString* str = string->ensureLinear(cx); |
| 2706 |
if (!str) { |
| 2707 |
return false; |
| 2708 |
} |
| 2709 |
|
| 2710 |
JSLinearString* searchStr = searchString->ensureLinear(cx); |
| 2711 |
if (!searchStr) { |
| 2712 |
return false; |
| 2713 |
} |
| 2714 |
|
| 2715 |
*result = HasSubstringAt(str, searchStr, 0); |
| 2716 |
return true; |
| 2717 |
} |
| 2718 |
|
| 2719 |
// ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b |
| 2720 |
// 22.1.3.7 String.prototype.endsWith ( searchString [ , endPosition ] ) |
| 2721 |
bool js::str_endsWith(JSContext* cx, unsigned argc, Value* vp) { |
| 2722 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "endsWith"); |
| 2723 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2724 |
|
| 2725 |
// Steps 1-2. |
| 2726 |
RootedString str(cx, ToStringForStringFunction(cx, "endsWith", args.thisv())); |
| 2727 |
if (!str) { |
| 2728 |
return false; |
| 2729 |
} |
| 2730 |
|
| 2731 |
// Steps 3-4. |
| 2732 |
if (!ReportErrorIfFirstArgIsRegExp(cx, args)) { |
| 2733 |
return false; |
| 2734 |
} |
| 2735 |
|
| 2736 |
// Step 5. |
| 2737 |
Rooted<JSLinearString*> searchStr(cx, ArgToLinearString(cx, args, 0)); |
| 2738 |
if (!searchStr) { |
| 2739 |
return false; |
| 2740 |
} |
| 2741 |
|
| 2742 |
// Step 6. |
| 2743 |
uint32_t textLen = str->length(); |
| 2744 |
|
| 2745 |
// Steps 7-8. |
| 2746 |
uint32_t end = textLen; |
| 2747 |
if (args.hasDefined(1)) { |
| 2748 |
if (!ToClampedStringIndex(cx, args[1], textLen, &end)) { |
| 2749 |
return false; |
| 2750 |
} |
| 2751 |
} |
| 2752 |
|
| 2753 |
// Step 9. |
| 2754 |
uint32_t searchLen = searchStr->length(); |
| 2755 |
|
| 2756 |
// Step 12 (reordered). |
| 2757 |
if (searchLen > end) { |
| 2758 |
args.rval().setBoolean(false); |
| 2759 |
return true; |
| 2760 |
} |
| 2761 |
|
| 2762 |
// Step 11. |
| 2763 |
uint32_t start = end - searchLen; |
| 2764 |
|
| 2765 |
// Steps 10 and 13-15. |
| 2766 |
JSLinearString* text = str->ensureLinear(cx); |
| 2767 |
if (!text) { |
| 2768 |
return false; |
| 2769 |
} |
| 2770 |
|
| 2771 |
args.rval().setBoolean(HasSubstringAt(text, searchStr, start)); |
| 2772 |
return true; |
| 2773 |
} |
| 2774 |
|
| 2775 |
bool js::StringEndsWith(JSContext* cx, HandleString string, |
| 2776 |
HandleString searchString, bool* result) { |
| 2777 |
if (searchString->length() > string->length()) { |
| 2778 |
*result = false; |
| 2779 |
return true; |
| 2780 |
} |
| 2781 |
|
| 2782 |
JSLinearString* str = string->ensureLinear(cx); |
| 2783 |
if (!str) { |
| 2784 |
return false; |
| 2785 |
} |
| 2786 |
|
| 2787 |
JSLinearString* searchStr = searchString->ensureLinear(cx); |
| 2788 |
if (!searchStr) { |
| 2789 |
return false; |
| 2790 |
} |
| 2791 |
|
| 2792 |
uint32_t start = str->length() - searchStr->length(); |
| 2793 |
|
| 2794 |
*result = HasSubstringAt(str, searchStr, start); |
| 2795 |
return true; |
| 2796 |
} |
| 2797 |
|
| 2798 |
template <typename CharT> |
| 2799 |
static void TrimString(const CharT* chars, bool trimStart, bool trimEnd, |
| 2800 |
size_t length, size_t* pBegin, size_t* pEnd) { |
| 2801 |
size_t begin = 0, end = length; |
| 2802 |
|
| 2803 |
if (trimStart) { |
| 2804 |
while (begin < length && unicode::IsSpace(chars[begin])) { |
| 2805 |
++begin; |
| 2806 |
} |
| 2807 |
} |
| 2808 |
|
| 2809 |
if (trimEnd) { |
| 2810 |
while (end > begin && unicode::IsSpace(chars[end - 1])) { |
| 2811 |
--end; |
| 2812 |
} |
| 2813 |
} |
| 2814 |
|
| 2815 |
*pBegin = begin; |
| 2816 |
*pEnd = end; |
| 2817 |
} |
| 2818 |
|
| 2819 |
static JSLinearString* TrimString(JSContext* cx, JSString* str, bool trimStart, |
| 2820 |
bool trimEnd) { |
| 2821 |
JSLinearString* linear = str->ensureLinear(cx); |
| 2822 |
if (!linear) { |
| 2823 |
return nullptr; |
| 2824 |
} |
| 2825 |
|
| 2826 |
size_t length = linear->length(); |
| 2827 |
size_t begin, end; |
| 2828 |
if (linear->hasLatin1Chars()) { |
| 2829 |
AutoCheckCannotGC nogc; |
| 2830 |
TrimString(linear->latin1Chars(nogc), trimStart, trimEnd, length, &begin, |
| 2831 |
&end); |
| 2832 |
} else { |
| 2833 |
AutoCheckCannotGC nogc; |
| 2834 |
TrimString(linear->twoByteChars(nogc), trimStart, trimEnd, length, &begin, |
| 2835 |
&end); |
| 2836 |
} |
| 2837 |
|
| 2838 |
return NewDependentString(cx, linear, begin, end - begin); |
| 2839 |
} |
| 2840 |
|
| 2841 |
JSString* js::StringTrim(JSContext* cx, HandleString string) { |
| 2842 |
return TrimString(cx, string, true, true); |
| 2843 |
} |
| 2844 |
|
| 2845 |
JSString* js::StringTrimStart(JSContext* cx, HandleString string) { |
| 2846 |
return TrimString(cx, string, true, false); |
| 2847 |
} |
| 2848 |
|
| 2849 |
JSString* js::StringTrimEnd(JSContext* cx, HandleString string) { |
| 2850 |
return TrimString(cx, string, false, true); |
| 2851 |
} |
| 2852 |
|
| 2853 |
static bool TrimString(JSContext* cx, const CallArgs& args, const char* funName, |
| 2854 |
bool trimStart, bool trimEnd) { |
| 2855 |
JSString* str = ToStringForStringFunction(cx, funName, args.thisv()); |
| 2856 |
if (!str) { |
| 2857 |
return false; |
| 2858 |
} |
| 2859 |
|
| 2860 |
JSLinearString* result = TrimString(cx, str, trimStart, trimEnd); |
| 2861 |
if (!result) { |
| 2862 |
return false; |
| 2863 |
} |
| 2864 |
|
| 2865 |
args.rval().setString(result); |
| 2866 |
return true; |
| 2867 |
} |
| 2868 |
|
| 2869 |
static bool str_trim(JSContext* cx, unsigned argc, Value* vp) { |
| 2870 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "trim"); |
| 2871 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2872 |
return TrimString(cx, args, "trim", true, true); |
| 2873 |
} |
| 2874 |
|
| 2875 |
static bool str_trimStart(JSContext* cx, unsigned argc, Value* vp) { |
| 2876 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "trimStart"); |
| 2877 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2878 |
return TrimString(cx, args, "trimStart", true, false); |
| 2879 |
} |
| 2880 |
|
| 2881 |
static bool str_trimEnd(JSContext* cx, unsigned argc, Value* vp) { |
| 2882 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "String.prototype", "trimEnd"); |
| 2883 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2884 |
return TrimString(cx, args, "trimEnd", false, true); |
| 2885 |
} |
| 2886 |
|
| 2887 |
// Utility for building a rope (lazy concatenation) of strings. |
| 2888 |
class RopeBuilder { |
| 2889 |
JSContext* cx; |
| 2890 |
RootedString res; |
| 2891 |
|
| 2892 |
RopeBuilder(const RopeBuilder& other) = delete; |
| 2893 |
void operator=(const RopeBuilder& other) = delete; |
| 2894 |
|
| 2895 |
public: |
| 2896 |
explicit RopeBuilder(JSContext* cx) |
| 2897 |
: cx(cx), res(cx, cx->runtime()->emptyString) {} |
| 2898 |
|
| 2899 |
inline bool append(HandleString str) { |
| 2900 |
res = ConcatStrings<CanGC>(cx, res, str); |
| 2901 |
return !!res; |
| 2902 |
} |
| 2903 |
|
| 2904 |
inline JSString* result() { return res; } |
| 2905 |
}; |
| 2906 |
|
| 2907 |
namespace { |
| 2908 |
|
| 2909 |
template <typename CharT> |
| 2910 |
static uint32_t FindDollarIndex(const CharT* chars, size_t length) { |
| 2911 |
if (const CharT* p = js_strchr_limit(chars, '$', chars + length)) { |
| 2912 |
uint32_t dollarIndex = p - chars; |
| 2913 |
MOZ_ASSERT(dollarIndex < length); |
| 2914 |
return dollarIndex; |
| 2915 |
} |
| 2916 |
return UINT32_MAX; |
| 2917 |
} |
| 2918 |
|
| 2919 |
} /* anonymous namespace */ |
| 2920 |
|
| 2921 |
/* |
| 2922 |
* Constructs a result string that looks like: |
| 2923 |
* |
| 2924 |
* newstring = string[:matchStart] + repstr + string[matchEnd:] |
| 2925 |
*/ |
| 2926 |
static JSString* BuildFlatReplacement(JSContext* cx, HandleString textstr, |
| 2927 |
Handle<JSLinearString*> repstr, |
| 2928 |
size_t matchStart, size_t patternLength) { |
| 2929 |
size_t matchEnd = matchStart + patternLength; |
| 2930 |
|
| 2931 |
RootedString resultStr(cx, NewDependentString(cx, textstr, 0, matchStart)); |
| 2932 |
if (!resultStr) { |
| 2933 |
return nullptr; |
| 2934 |
} |
| 2935 |
|
| 2936 |
resultStr = ConcatStrings<CanGC>(cx, resultStr, repstr); |
| 2937 |
if (!resultStr) { |
| 2938 |
return nullptr; |
| 2939 |
} |
| 2940 |
|
| 2941 |
MOZ_ASSERT(textstr->length() >= matchEnd); |
| 2942 |
RootedString rest(cx, NewDependentString(cx, textstr, matchEnd, |
| 2943 |
textstr->length() - matchEnd)); |
| 2944 |
if (!rest) { |
| 2945 |
return nullptr; |
| 2946 |
} |
| 2947 |
|
| 2948 |
return ConcatStrings<CanGC>(cx, resultStr, rest); |
| 2949 |
} |
| 2950 |
|
| 2951 |
static JSString* BuildFlatRopeReplacement(JSContext* cx, HandleString textstr, |
| 2952 |
Handle<JSLinearString*> repstr, |
| 2953 |
size_t match, size_t patternLength) { |
| 2954 |
MOZ_ASSERT(textstr->isRope()); |
| 2955 |
|
| 2956 |
size_t matchEnd = match + patternLength; |
| 2957 |
|
| 2958 |
/* |
| 2959 |
* If we are replacing over a rope, avoid flattening it by iterating |
| 2960 |
* through it, building a new rope. |
| 2961 |
*/ |
| 2962 |
StringSegmentRange r(cx); |
| 2963 |
if (!r.init(textstr)) { |
| 2964 |
return nullptr; |
| 2965 |
} |
| 2966 |
|
| 2967 |
RopeBuilder builder(cx); |
| 2968 |
|
| 2969 |
/* |
| 2970 |
* Special case when the pattern string is '', which matches to the |
| 2971 |
* head of the string and doesn't overlap with any component of the rope. |
| 2972 |
*/ |
| 2973 |
if (patternLength == 0) { |
| 2974 |
MOZ_ASSERT(match == 0); |
| 2975 |
if (!builder.append(repstr)) { |
| 2976 |
return nullptr; |
| 2977 |
} |
| 2978 |
} |
| 2979 |
|
| 2980 |
size_t pos = 0; |
| 2981 |
while (!r.empty()) { |
| 2982 |
RootedString str(cx, r.front()); |
| 2983 |
size_t len = str->length(); |
| 2984 |
size_t strEnd = pos + len; |
| 2985 |
if (pos < matchEnd && strEnd > match) { |
| 2986 |
/* |
| 2987 |
* We need to special-case any part of the rope that overlaps |
| 2988 |
* with the replacement string. |
| 2989 |
*/ |
| 2990 |
if (match >= pos) { |
| 2991 |
/* |
| 2992 |
* If this part of the rope overlaps with the left side of |
| 2993 |
* the pattern, then it must be the only one to overlap with |
| 2994 |
* the first character in the pattern, so we include the |
| 2995 |
* replacement string here. |
| 2996 |
*/ |
| 2997 |
RootedString leftSide(cx, NewDependentString(cx, str, 0, match - pos)); |
| 2998 |
if (!leftSide || !builder.append(leftSide) || !builder.append(repstr)) { |
| 2999 |
return nullptr; |
| 3000 |
} |
| 3001 |
} |
| 3002 |
|
| 3003 |
/* |
| 3004 |
* If str runs off the end of the matched string, append the |
| 3005 |
* last part of str. |
| 3006 |
*/ |
| 3007 |
if (strEnd > matchEnd) { |
| 3008 |
RootedString rightSide( |
| 3009 |
cx, NewDependentString(cx, str, matchEnd - pos, strEnd - matchEnd)); |
| 3010 |
if (!rightSide || !builder.append(rightSide)) { |
| 3011 |
return nullptr; |
| 3012 |
} |
| 3013 |
} |
| 3014 |
} else { |
| 3015 |
if (!builder.append(str)) { |
| 3016 |
return nullptr; |
| 3017 |
} |
| 3018 |
} |
| 3019 |
pos += str->length(); |
| 3020 |
if (!r.popFront()) { |
| 3021 |
return nullptr; |
| 3022 |
} |
| 3023 |
} |
| 3024 |
|
| 3025 |
return builder.result(); |
| 3026 |
} |
| 3027 |
|
| 3028 |
template <typename CharT> |
| 3029 |
static bool AppendDollarReplacement(StringBuilder& newReplaceChars, |
| 3030 |
size_t firstDollarIndex, size_t matchStart, |
| 3031 |
size_t matchLimit, |
| 3032 |
const JSLinearString* text, |
| 3033 |
const CharT* repChars, size_t repLength) { |
| 3034 |
MOZ_ASSERT(firstDollarIndex < repLength); |
| 3035 |
MOZ_ASSERT(matchStart <= matchLimit); |
| 3036 |
MOZ_ASSERT(matchLimit <= text->length()); |
| 3037 |
|
| 3038 |
// Move the pre-dollar chunk in bulk. |
| 3039 |
if (!newReplaceChars.append(repChars, firstDollarIndex)) { |
| 3040 |
return false; |
| 3041 |
} |
| 3042 |
|
| 3043 |
// Move the rest char-by-char, interpreting dollars as we encounter them. |
| 3044 |
const CharT* repLimit = repChars + repLength; |
| 3045 |
for (const CharT* it = repChars + firstDollarIndex; it < repLimit; ++it) { |
| 3046 |
if (*it != '$' || it == repLimit - 1) { |
| 3047 |
if (!newReplaceChars.append(*it)) { |
| 3048 |
return false; |
| 3049 |
} |
| 3050 |
continue; |
| 3051 |
} |
| 3052 |
|
| 3053 |
switch (*(it + 1)) { |
| 3054 |
case '$': |
| 3055 |
// Eat one of the dollars. |
| 3056 |
if (!newReplaceChars.append(*it)) { |
| 3057 |
return false; |
| 3058 |
} |
| 3059 |
break; |
| 3060 |
case '&': |
| 3061 |
if (!newReplaceChars.appendSubstring(text, matchStart, |
| 3062 |
matchLimit - matchStart)) { |
| 3063 |
return false; |
| 3064 |
} |
| 3065 |
break; |
| 3066 |
case '`': |
| 3067 |
if (!newReplaceChars.appendSubstring(text, 0, matchStart)) { |
| 3068 |
return false; |
| 3069 |
} |
| 3070 |
break; |
| 3071 |
case '\'': |
| 3072 |
if (!newReplaceChars.appendSubstring(text, matchLimit, |
| 3073 |
text->length() - matchLimit)) { |
| 3074 |
return false; |
| 3075 |
} |
| 3076 |
break; |
| 3077 |
default: |
| 3078 |
// The dollar we saw was not special (no matter what its mother told |
| 3079 |
// it). |
| 3080 |
if (!newReplaceChars.append(*it)) { |
| 3081 |
return false; |
| 3082 |
} |
| 3083 |
continue; |
| 3084 |
} |
| 3085 |
++it; // We always eat an extra char in the above switch. |
| 3086 |
} |
| 3087 |
|
| 3088 |
return true; |
| 3089 |
} |
| 3090 |
|
| 3091 |
/* |
| 3092 |
* Perform a linear-scan dollar substitution on the replacement text. |
| 3093 |
*/ |
| 3094 |
static JSLinearString* InterpretDollarReplacement( |
| 3095 |
JSContext* cx, HandleString textstrArg, Handle<JSLinearString*> repstr, |
| 3096 |
uint32_t firstDollarIndex, size_t matchStart, size_t patternLength) { |
| 3097 |
Rooted<JSLinearString*> textstr(cx, textstrArg->ensureLinear(cx)); |
| 3098 |
if (!textstr) { |
| 3099 |
return nullptr; |
| 3100 |
} |
| 3101 |
|
| 3102 |
size_t matchLimit = matchStart + patternLength; |
| 3103 |
|
| 3104 |
/* |
| 3105 |
* Most probably: |
| 3106 |
* |
| 3107 |
* len(newstr) >= len(orig) - len(match) + len(replacement) |
| 3108 |
* |
| 3109 |
* Note that dollar vars _could_ make the resulting text smaller than this. |
| 3110 |
*/ |
| 3111 |
JSStringBuilder newReplaceChars(cx); |
| 3112 |
if (repstr->hasTwoByteChars() && !newReplaceChars.ensureTwoByteChars()) { |
| 3113 |
return nullptr; |
| 3114 |
} |
| 3115 |
|
| 3116 |
if (!newReplaceChars.reserve(textstr->length() - patternLength + |
| 3117 |
repstr->length())) { |
| 3118 |
return nullptr; |
| 3119 |
} |
| 3120 |
|
| 3121 |
bool res; |
| 3122 |
if (repstr->hasLatin1Chars()) { |
| 3123 |
AutoCheckCannotGC nogc; |
| 3124 |
res = AppendDollarReplacement(newReplaceChars, firstDollarIndex, matchStart, |
| 3125 |
matchLimit, textstr, |
| 3126 |
repstr->latin1Chars(nogc), repstr->length()); |
| 3127 |
} else { |
| 3128 |
AutoCheckCannotGC nogc; |
| 3129 |
res = AppendDollarReplacement(newReplaceChars, firstDollarIndex, matchStart, |
| 3130 |
matchLimit, textstr, |
| 3131 |
repstr->twoByteChars(nogc), repstr->length()); |
| 3132 |
} |
| 3133 |
if (!res) { |
| 3134 |
return nullptr; |
| 3135 |
} |
| 3136 |
|
| 3137 |
return newReplaceChars.finishString(); |
| 3138 |
} |
| 3139 |
|
| 3140 |
template <typename StrChar, typename RepChar> |
| 3141 |
static bool StrFlatReplaceGlobal(JSContext* cx, const JSLinearString* str, |
| 3142 |
const JSLinearString* pat, |
| 3143 |
const JSLinearString* rep, StringBuilder& sb) { |
| 3144 |
MOZ_ASSERT(str->length() > 0); |
| 3145 |
|
| 3146 |
AutoCheckCannotGC nogc; |
| 3147 |
const StrChar* strChars = str->chars<StrChar>(nogc); |
| 3148 |
const RepChar* repChars = rep->chars<RepChar>(nogc); |
| 3149 |
|
| 3150 |
// The pattern is empty, so we interleave the replacement string in-between |
| 3151 |
// each character. |
| 3152 |
if (!pat->length()) { |
| 3153 |
CheckedInt<uint32_t> strLength(str->length()); |
| 3154 |
CheckedInt<uint32_t> repLength(rep->length()); |
| 3155 |
CheckedInt<uint32_t> length = repLength * (strLength - 1) + strLength; |
| 3156 |
if (!length.isValid()) { |
| 3157 |
ReportAllocationOverflow(cx); |
| 3158 |
return false; |
| 3159 |
} |
| 3160 |
|
| 3161 |
if (!sb.reserve(length.value())) { |
| 3162 |
return false; |
| 3163 |
} |
| 3164 |
|
| 3165 |
for (unsigned i = 0; i < str->length() - 1; ++i, ++strChars) { |
| 3166 |
sb.infallibleAppend(*strChars); |
| 3167 |
sb.infallibleAppend(repChars, rep->length()); |
| 3168 |
} |
| 3169 |
sb.infallibleAppend(*strChars); |
| 3170 |
return true; |
| 3171 |
} |
| 3172 |
|
| 3173 |
// If it's true, we are sure that the result's length is, at least, the same |
| 3174 |
// length as |str->length()|. |
| 3175 |
if (rep->length() >= pat->length()) { |
| 3176 |
if (!sb.reserve(str->length())) { |
| 3177 |
return false; |
| 3178 |
} |
| 3179 |
} |
| 3180 |
|
| 3181 |
uint32_t start = 0; |
| 3182 |
for (;;) { |
| 3183 |
int match = StringMatch(str, pat, start); |
| 3184 |
if (match < 0) { |
| 3185 |
break; |
| 3186 |
} |
| 3187 |
if (!sb.append(strChars + start, match - start)) { |
| 3188 |
return false; |
| 3189 |
} |
| 3190 |
if (!sb.append(repChars, rep->length())) { |
| 3191 |
return false; |
| 3192 |
} |
| 3193 |
start = match + pat->length(); |
| 3194 |
} |
| 3195 |
|
| 3196 |
if (!sb.append(strChars + start, str->length() - start)) { |
| 3197 |
return false; |
| 3198 |
} |
| 3199 |
|
| 3200 |
return true; |
| 3201 |
} |
| 3202 |
|
| 3203 |
// This is identical to "str.split(pattern).join(replacement)" except that we |
| 3204 |
// do some deforestation optimization in Ion. |
| 3205 |
JSString* js::StringFlatReplaceString(JSContext* cx, HandleString string, |
| 3206 |
HandleString pattern, |
| 3207 |
HandleString replacement) { |
| 3208 |
MOZ_ASSERT(string); |
| 3209 |
MOZ_ASSERT(pattern); |
| 3210 |
MOZ_ASSERT(replacement); |
| 3211 |
|
| 3212 |
if (!string->length()) { |
| 3213 |
return string; |
| 3214 |
} |
| 3215 |
|
| 3216 |
Rooted<JSLinearString*> linearRepl(cx, replacement->ensureLinear(cx)); |
| 3217 |
if (!linearRepl) { |
| 3218 |
return nullptr; |
| 3219 |
} |
| 3220 |
|
| 3221 |
Rooted<JSLinearString*> linearPat(cx, pattern->ensureLinear(cx)); |
| 3222 |
if (!linearPat) { |
| 3223 |
return nullptr; |
| 3224 |
} |
| 3225 |
|
| 3226 |
Rooted<JSLinearString*> linearStr(cx, string->ensureLinear(cx)); |
| 3227 |
if (!linearStr) { |
| 3228 |
return nullptr; |
| 3229 |
} |
| 3230 |
|
| 3231 |
JSStringBuilder sb(cx); |
| 3232 |
if (linearStr->hasTwoByteChars()) { |
| 3233 |
if (!sb.ensureTwoByteChars()) { |
| 3234 |
return nullptr; |
| 3235 |
} |
| 3236 |
if (linearRepl->hasTwoByteChars()) { |
| 3237 |
if (!StrFlatReplaceGlobal<char16_t, char16_t>(cx, linearStr, linearPat, |
| 3238 |
linearRepl, sb)) { |
| 3239 |
return nullptr; |
| 3240 |
} |
| 3241 |
} else { |
| 3242 |
if (!StrFlatReplaceGlobal<char16_t, Latin1Char>(cx, linearStr, linearPat, |
| 3243 |
linearRepl, sb)) { |
| 3244 |
return nullptr; |
| 3245 |
} |
| 3246 |
} |
| 3247 |
} else { |
| 3248 |
if (linearRepl->hasTwoByteChars()) { |
| 3249 |
if (!sb.ensureTwoByteChars()) { |
| 3250 |
return nullptr; |
| 3251 |
} |
| 3252 |
if (!StrFlatReplaceGlobal<Latin1Char, char16_t>(cx, linearStr, linearPat, |
| 3253 |
linearRepl, sb)) { |
| 3254 |
return nullptr; |
| 3255 |
} |
| 3256 |
} else { |
| 3257 |
if (!StrFlatReplaceGlobal<Latin1Char, Latin1Char>( |
| 3258 |
cx, linearStr, linearPat, linearRepl, sb)) { |
| 3259 |
return nullptr; |
| 3260 |
} |
| 3261 |
} |
| 3262 |
} |
| 3263 |
|
| 3264 |
return sb.finishString(); |
| 3265 |
} |
| 3266 |
|
| 3267 |
JSString* js::str_replace_string_raw(JSContext* cx, HandleString string, |
| 3268 |
HandleString pattern, |
| 3269 |
HandleString replacement) { |
| 3270 |
Rooted<JSLinearString*> pat(cx, pattern->ensureLinear(cx)); |
| 3271 |
if (!pat) { |
| 3272 |
return nullptr; |
| 3273 |
} |
| 3274 |
|
| 3275 |
/* |
| 3276 |
* |string| could be a rope, so we want to avoid flattening it for as |
| 3277 |
* long as possible. |
| 3278 |
*/ |
| 3279 |
int32_t match; |
| 3280 |
if (string->isRope()) { |
| 3281 |
if (!RopeMatch(cx, &string->asRope(), pat, &match)) { |
| 3282 |
return nullptr; |
| 3283 |
} |
| 3284 |
} else { |
| 3285 |
match = StringMatch(&string->asLinear(), pat, 0); |
| 3286 |
} |
| 3287 |
|
| 3288 |
if (match < 0) { |
| 3289 |
return string; |
| 3290 |
} |
| 3291 |
|
| 3292 |
Rooted<JSLinearString*> repl(cx, replacement->ensureLinear(cx)); |
| 3293 |
if (!repl) { |
| 3294 |
return nullptr; |
| 3295 |
} |
| 3296 |
uint32_t dollarIndex; |
| 3297 |
{ |
| 3298 |
AutoCheckCannotGC nogc; |
| 3299 |
dollarIndex = |
| 3300 |
repl->hasLatin1Chars() |
| 3301 |
? FindDollarIndex(repl->latin1Chars(nogc), repl->length()) |
| 3302 |
: FindDollarIndex(repl->twoByteChars(nogc), repl->length()); |
| 3303 |
} |
| 3304 |
|
| 3305 |
size_t patternLength = pat->length(); |
| 3306 |
|
| 3307 |
if (dollarIndex != UINT32_MAX) { |
| 3308 |
repl = InterpretDollarReplacement(cx, string, repl, dollarIndex, match, |
| 3309 |
patternLength); |
| 3310 |
if (!repl) { |
| 3311 |
return nullptr; |
| 3312 |
} |
| 3313 |
} else if (string->isRope()) { |
| 3314 |
return BuildFlatRopeReplacement(cx, string, repl, match, patternLength); |
| 3315 |
} |
| 3316 |
return BuildFlatReplacement(cx, string, repl, match, patternLength); |
| 3317 |
} |
| 3318 |
|
| 3319 |
template <typename StrChar, typename RepChar> |
| 3320 |
static bool ReplaceAllInternal(const AutoCheckCannotGC& nogc, |
| 3321 |
const JSLinearString* string, |
| 3322 |
const JSLinearString* searchString, |
| 3323 |
const JSLinearString* replaceString, |
| 3324 |
const int32_t startPosition, |
| 3325 |
JSStringBuilder& result) { |
| 3326 |
// Step 7. |
| 3327 |
const size_t stringLength = string->length(); |
| 3328 |
const size_t searchLength = searchString->length(); |
| 3329 |
const size_t replaceLength = replaceString->length(); |
| 3330 |
|
| 3331 |
MOZ_ASSERT(stringLength > 0); |
| 3332 |
MOZ_ASSERT(searchLength > 0); |
| 3333 |
MOZ_ASSERT(stringLength >= searchLength); |
| 3334 |
|
| 3335 |
// Step 12. |
| 3336 |
uint32_t endOfLastMatch = 0; |
| 3337 |
|
| 3338 |
const StrChar* strChars = string->chars<StrChar>(nogc); |
| 3339 |
const RepChar* repChars = replaceString->chars<RepChar>(nogc); |
| 3340 |
|
| 3341 |
uint32_t dollarIndex = FindDollarIndex(repChars, replaceLength); |
| 3342 |
|
| 3343 |
// If it's true, we are sure that the result's length is, at least, the same |
| 3344 |
// length as |str->length()|. |
| 3345 |
if (replaceLength >= searchLength) { |
| 3346 |
if (!result.reserve(stringLength)) { |
| 3347 |
return false; |
| 3348 |
} |
| 3349 |
} |
| 3350 |
|
| 3351 |
int32_t position = startPosition; |
| 3352 |
do { |
| 3353 |
// Step 14.c. |
| 3354 |
// Append the substring before the current match. |
| 3355 |
if (!result.append(strChars + endOfLastMatch, position - endOfLastMatch)) { |
| 3356 |
return false; |
| 3357 |
} |
| 3358 |
|
| 3359 |
// Steps 14.a-b and 14.d. |
| 3360 |
// Append the replacement. |
| 3361 |
if (dollarIndex != UINT32_MAX) { |
| 3362 |
size_t matchLimit = position + searchLength; |
| 3363 |
if (!AppendDollarReplacement(result, dollarIndex, position, matchLimit, |
| 3364 |
string, repChars, replaceLength)) { |
| 3365 |
return false; |
| 3366 |
} |
| 3367 |
} else { |
| 3368 |
if (!result.append(repChars, replaceLength)) { |
| 3369 |
return false; |
| 3370 |
} |
| 3371 |
} |
| 3372 |
|
| 3373 |
// Step 14.e. |
| 3374 |
endOfLastMatch = position + searchLength; |
| 3375 |
|
| 3376 |
// Step 11. |
| 3377 |
// Find the next match. |
| 3378 |
position = StringMatch(string, searchString, endOfLastMatch); |
| 3379 |
} while (position >= 0); |
| 3380 |
|
| 3381 |
// Step 15. |
| 3382 |
// Append the substring after the last match. |
| 3383 |
return result.append(strChars + endOfLastMatch, |
| 3384 |
stringLength - endOfLastMatch); |
| 3385 |
} |
| 3386 |
|
| 3387 |
// https://tc39.es/proposal-string-replaceall/#sec-string.prototype.replaceall |
| 3388 |
// Steps 7-16 when functionalReplace is false and searchString is not empty. |
| 3389 |
// |
| 3390 |
// The steps are quite different, for performance. Loops in steps 11 and 14 |
| 3391 |
// are fused. GetSubstitution is optimized away when possible. |
| 3392 |
template <typename StrChar, typename RepChar> |
| 3393 |
static JSString* ReplaceAll(JSContext* cx, JSLinearString* string, |
| 3394 |
const JSLinearString* searchString, |
| 3395 |
const JSLinearString* replaceString) { |
| 3396 |
// Step 7 moved into ReplaceAll_internal. |
| 3397 |
|
| 3398 |
// Step 8 (advanceBy is equal to searchLength when searchLength > 0). |
| 3399 |
|
| 3400 |
// Step 9 (not needed in this implementation). |
| 3401 |
|
| 3402 |
// Step 10. |
| 3403 |
// Find the first match. |
| 3404 |
int32_t position = StringMatch(string, searchString, 0); |
| 3405 |
|
| 3406 |
// Nothing to replace, so return early. |
| 3407 |
if (position < 0) { |
| 3408 |
return string; |
| 3409 |
} |
| 3410 |
|
| 3411 |
// Steps 11, 12 moved into ReplaceAll_internal. |
| 3412 |
|
| 3413 |
// Step 13. |
| 3414 |
JSStringBuilder result(cx); |
| 3415 |
if constexpr (std::is_same_v<StrChar, char16_t> || |
| 3416 |
std::is_same_v<RepChar, char16_t>) { |
| 3417 |
if (!result.ensureTwoByteChars()) { |
| 3418 |
return nullptr; |
| 3419 |
} |
| 3420 |
} |
| 3421 |
|
| 3422 |
bool internalFailure = false; |
| 3423 |
{ |
| 3424 |
AutoCheckCannotGC nogc; |
| 3425 |
internalFailure = !ReplaceAllInternal<StrChar, RepChar>( |
| 3426 |
nogc, string, searchString, replaceString, position, result); |
| 3427 |
} |
| 3428 |
if (internalFailure) { |
| 3429 |
return nullptr; |
| 3430 |
} |
| 3431 |
|
| 3432 |
// Step 16. |
| 3433 |
return result.finishString(); |
| 3434 |
} |
| 3435 |
|
| 3436 |
template <typename StrChar, typename RepChar> |
| 3437 |
static bool ReplaceAllInterleaveInternal(const AutoCheckCannotGC& nogc, |
| 3438 |
JSContext* cx, |
| 3439 |
const JSLinearString* string, |
| 3440 |
const JSLinearString* replaceString, |
| 3441 |
JSStringBuilder& result) { |
| 3442 |
// Step 7. |
| 3443 |
const size_t stringLength = string->length(); |
| 3444 |
const size_t replaceLength = replaceString->length(); |
| 3445 |
|
| 3446 |
const StrChar* strChars = string->chars<StrChar>(nogc); |
| 3447 |
const RepChar* repChars = replaceString->chars<RepChar>(nogc); |
| 3448 |
|
| 3449 |
uint32_t dollarIndex = FindDollarIndex(repChars, replaceLength); |
| 3450 |
|
| 3451 |
if (dollarIndex != UINT32_MAX) { |
| 3452 |
if (!result.reserve(stringLength)) { |
| 3453 |
return false; |
| 3454 |
} |
| 3455 |
} else { |
| 3456 |
// Compute the exact result length when no substitutions take place. |
| 3457 |
CheckedInt<uint32_t> strLength(stringLength); |
| 3458 |
CheckedInt<uint32_t> repLength(replaceLength); |
| 3459 |
CheckedInt<uint32_t> length = strLength + (strLength + 1) * repLength; |
| 3460 |
if (!length.isValid()) { |
| 3461 |
ReportAllocationOverflow(cx); |
| 3462 |
return false; |
| 3463 |
} |
| 3464 |
|
| 3465 |
if (!result.reserve(length.value())) { |
| 3466 |
return false; |
| 3467 |
} |
| 3468 |
} |
| 3469 |
|
| 3470 |
auto appendReplacement = [&](size_t match) { |
| 3471 |
if (dollarIndex != UINT32_MAX) { |
| 3472 |
return AppendDollarReplacement(result, dollarIndex, match, match, string, |
| 3473 |
repChars, replaceLength); |
| 3474 |
} |
| 3475 |
return result.append(repChars, replaceLength); |
| 3476 |
}; |
| 3477 |
|
| 3478 |
for (size_t index = 0; index < stringLength; index++) { |
| 3479 |
// Steps 11, 14.a-b and 14.d. |
| 3480 |
// The empty string matches before each character. |
| 3481 |
if (!appendReplacement(index)) { |
| 3482 |
return false; |
| 3483 |
} |
| 3484 |
|
| 3485 |
// Step 14.c. |
| 3486 |
if (!result.append(strChars[index])) { |
| 3487 |
return false; |
| 3488 |
} |
| 3489 |
} |
| 3490 |
|
| 3491 |
// Steps 11, 14.a-b and 14.d. |
| 3492 |
// The empty string also matches at the end of the string. |
| 3493 |
return appendReplacement(stringLength); |
| 3494 |
|
| 3495 |
// Step 15 (not applicable when searchString is the empty string). |
| 3496 |
} |
| 3497 |
|
| 3498 |
// https://tc39.es/proposal-string-replaceall/#sec-string.prototype.replaceall |
| 3499 |
// Steps 7-16 when functionalReplace is false and searchString is the empty |
| 3500 |
// string. |
| 3501 |
// |
| 3502 |
// The steps are quite different, for performance. Loops in steps 11 and 14 |
| 3503 |
// are fused. GetSubstitution is optimized away when possible. |
| 3504 |
template <typename StrChar, typename RepChar> |
| 3505 |
static JSString* ReplaceAllInterleave(JSContext* cx, |
| 3506 |
const JSLinearString* string, |
| 3507 |
const JSLinearString* replaceString) { |
| 3508 |
// Step 7 moved into ReplaceAllInterleavedInternal. |
| 3509 |
|
| 3510 |
// Step 8 (advanceBy is 1 when searchString is the empty string). |
| 3511 |
|
| 3512 |
// Steps 9-12 (trivial when searchString is the empty string). |
| 3513 |
|
| 3514 |
// Step 13. |
| 3515 |
JSStringBuilder result(cx); |
| 3516 |
if constexpr (std::is_same_v<StrChar, char16_t> || |
| 3517 |
std::is_same_v<RepChar, char16_t>) { |
| 3518 |
if (!result.ensureTwoByteChars()) { |
| 3519 |
return nullptr; |
| 3520 |
} |
| 3521 |
} |
| 3522 |
|
| 3523 |
bool internalFailure = false; |
| 3524 |
{ |
| 3525 |
AutoCheckCannotGC nogc; |
| 3526 |
internalFailure = !ReplaceAllInterleaveInternal<StrChar, RepChar>( |
| 3527 |
nogc, cx, string, replaceString, result); |
| 3528 |
} |
| 3529 |
if (internalFailure) { |
| 3530 |
return nullptr; |
| 3531 |
} |
| 3532 |
|
| 3533 |
// Step 16. |
| 3534 |
return result.finishString(); |
| 3535 |
} |
| 3536 |
|
| 3537 |
// String.prototype.replaceAll (Stage 3 proposal) |
| 3538 |
// https://tc39.es/proposal-string-replaceall/ |
| 3539 |
// |
| 3540 |
// String.prototype.replaceAll ( searchValue, replaceValue ) |
| 3541 |
// |
| 3542 |
// Steps 7-16 when functionalReplace is false. |
| 3543 |
JSString* js::str_replaceAll_string_raw(JSContext* cx, HandleString string, |
| 3544 |
HandleString searchString, |
| 3545 |
HandleString replaceString) { |
| 3546 |
const size_t stringLength = string->length(); |
| 3547 |
const size_t searchLength = searchString->length(); |
| 3548 |
|
| 3549 |
// Directly return when we're guaranteed to find no match. |
| 3550 |
if (searchLength > stringLength) { |
| 3551 |
return string; |
| 3552 |
} |
| 3553 |
|
| 3554 |
Rooted<JSLinearString*> str(cx, string->ensureLinear(cx)); |
| 3555 |
if (!str) { |
| 3556 |
return nullptr; |
| 3557 |
} |
| 3558 |
|
| 3559 |
Rooted<JSLinearString*> repl(cx, replaceString->ensureLinear(cx)); |
| 3560 |
if (!repl) { |
| 3561 |
return nullptr; |
| 3562 |
} |
| 3563 |
|
| 3564 |
Rooted<JSLinearString*> search(cx, searchString->ensureLinear(cx)); |
| 3565 |
if (!search) { |
| 3566 |
return nullptr; |
| 3567 |
} |
| 3568 |
|
| 3569 |
// The pattern is empty, so we interleave the replacement string in-between |
| 3570 |
// each character. |
| 3571 |
if (searchLength == 0) { |
| 3572 |
if (str->hasTwoByteChars()) { |
| 3573 |
if (repl->hasTwoByteChars()) { |
| 3574 |
return ReplaceAllInterleave<char16_t, char16_t>(cx, str, repl); |
| 3575 |
} |
| 3576 |
return ReplaceAllInterleave<char16_t, Latin1Char>(cx, str, repl); |
| 3577 |
} |
| 3578 |
if (repl->hasTwoByteChars()) { |
| 3579 |
return ReplaceAllInterleave<Latin1Char, char16_t>(cx, str, repl); |
| 3580 |
} |
| 3581 |
return ReplaceAllInterleave<Latin1Char, Latin1Char>(cx, str, repl); |
| 3582 |
} |
| 3583 |
|
| 3584 |
MOZ_ASSERT(stringLength > 0); |
| 3585 |
|
| 3586 |
if (str->hasTwoByteChars()) { |
| 3587 |
if (repl->hasTwoByteChars()) { |
| 3588 |
return ReplaceAll<char16_t, char16_t>(cx, str, search, repl); |
| 3589 |
} |
| 3590 |
return ReplaceAll<char16_t, Latin1Char>(cx, str, search, repl); |
| 3591 |
} |
| 3592 |
if (repl->hasTwoByteChars()) { |
| 3593 |
return ReplaceAll<Latin1Char, char16_t>(cx, str, search, repl); |
| 3594 |
} |
| 3595 |
return ReplaceAll<Latin1Char, Latin1Char>(cx, str, search, repl); |
| 3596 |
} |
| 3597 |
|
| 3598 |
static ArrayObject* SingleElementStringArray(JSContext* cx, |
| 3599 |
Handle<JSLinearString*> str) { |
| 3600 |
ArrayObject* array = NewDenseFullyAllocatedArray(cx, 1); |
| 3601 |
if (!array) { |
| 3602 |
return nullptr; |
| 3603 |
} |
| 3604 |
array->setDenseInitializedLength(1); |
| 3605 |
array->initDenseElement(0, StringValue(str)); |
| 3606 |
return array; |
| 3607 |
} |
| 3608 |
|
| 3609 |
// ES 2016 draft Mar 25, 2016 21.1.3.17 steps 4, 8, 12-18. |
| 3610 |
static ArrayObject* SplitHelper(JSContext* cx, Handle<JSLinearString*> str, |
| 3611 |
uint32_t limit, Handle<JSLinearString*> sep) { |
| 3612 |
size_t strLength = str->length(); |
| 3613 |
size_t sepLength = sep->length(); |
| 3614 |
MOZ_ASSERT(sepLength != 0); |
| 3615 |
|
| 3616 |
// Step 12. |
| 3617 |
if (strLength == 0) { |
| 3618 |
// Step 12.a. |
| 3619 |
int match = StringMatch(str, sep, 0); |
| 3620 |
|
| 3621 |
// Step 12.b. |
| 3622 |
if (match != -1) { |
| 3623 |
return NewDenseEmptyArray(cx); |
| 3624 |
} |
| 3625 |
|
| 3626 |
// Steps 12.c-e. |
| 3627 |
return SingleElementStringArray(cx, str); |
| 3628 |
} |
| 3629 |
|
| 3630 |
// Step 3 (reordered). |
| 3631 |
Rooted<ArrayObject*> substrings(cx, NewDenseEmptyArray(cx)); |
| 3632 |
if (!substrings) { |
| 3633 |
return nullptr; |
| 3634 |
} |
| 3635 |
|
| 3636 |
// Switch to allocating in the tenured heap if we fill the nursery. |
| 3637 |
AutoSelectGCHeap gcHeap(cx); |
| 3638 |
|
| 3639 |
// Step 8 (reordered). |
| 3640 |
size_t lastEndIndex = 0; |
| 3641 |
|
| 3642 |
// Step 13. |
| 3643 |
size_t index = 0; |
| 3644 |
|
| 3645 |
// Step 14. |
| 3646 |
while (index != strLength) { |
| 3647 |
// Step 14.a. |
| 3648 |
int match = StringMatch(str, sep, index); |
| 3649 |
|
| 3650 |
// Step 14.b. |
| 3651 |
// |
| 3652 |
// Our match algorithm differs from the spec in that it returns the |
| 3653 |
// next index at which a match happens. If no match happens we're |
| 3654 |
// done. |
| 3655 |
// |
| 3656 |
// But what if the match is at the end of the string (and the string is |
| 3657 |
// not empty)? Per 14.c.i this shouldn't be a match, so we have to |
| 3658 |
// specially exclude it. Thus this case should hold: |
| 3659 |
// |
| 3660 |
// var a = "abc".split(/\b/); |
| 3661 |
// assertEq(a.length, 1); |
| 3662 |
// assertEq(a[0], "abc"); |
| 3663 |
if (match == -1) { |
| 3664 |
break; |
| 3665 |
} |
| 3666 |
|
| 3667 |
// Step 14.c. |
| 3668 |
size_t endIndex = match + sepLength; |
| 3669 |
|
| 3670 |
// Step 14.c.i. |
| 3671 |
if (endIndex == lastEndIndex) { |
| 3672 |
index++; |
| 3673 |
continue; |
| 3674 |
} |
| 3675 |
|
| 3676 |
// Step 14.c.ii. |
| 3677 |
MOZ_ASSERT(lastEndIndex < endIndex); |
| 3678 |
MOZ_ASSERT(sepLength <= strLength); |
| 3679 |
MOZ_ASSERT(lastEndIndex + sepLength <= endIndex); |
| 3680 |
|
| 3681 |
// Step 14.c.ii.1. |
| 3682 |
size_t subLength = size_t(endIndex - sepLength - lastEndIndex); |
| 3683 |
JSString* sub = |
| 3684 |
NewDependentString(cx, str, lastEndIndex, subLength, gcHeap); |
| 3685 |
|
| 3686 |
// Steps 14.c.ii.2-4. |
| 3687 |
if (!sub || !NewbornArrayPush(cx, substrings, StringValue(sub))) { |
| 3688 |
return nullptr; |
| 3689 |
} |
| 3690 |
|
| 3691 |
// Step 14.c.ii.5. |
| 3692 |
if (substrings->length() == limit) { |
| 3693 |
return substrings; |
| 3694 |
} |
| 3695 |
|
| 3696 |
// Step 14.c.ii.6. |
| 3697 |
index = endIndex; |
| 3698 |
|
| 3699 |
// Step 14.c.ii.7. |
| 3700 |
lastEndIndex = index; |
| 3701 |
} |
| 3702 |
|
| 3703 |
// Step 15. |
| 3704 |
size_t subLength = strLength - lastEndIndex; |
| 3705 |
JSString* sub = NewDependentString(cx, str, lastEndIndex, subLength, gcHeap); |
| 3706 |
|
| 3707 |
// Steps 16-17. |
| 3708 |
if (!sub || !NewbornArrayPush(cx, substrings, StringValue(sub))) { |
| 3709 |
return nullptr; |
| 3710 |
} |
| 3711 |
|
| 3712 |
// Step 18. |
| 3713 |
return substrings; |
| 3714 |
} |
| 3715 |
|
| 3716 |
// Fast-path for splitting a string into a character array via split(""). |
| 3717 |
static ArrayObject* CharSplitHelper(JSContext* cx, Handle<JSLinearString*> str, |
| 3718 |
uint32_t limit) { |
| 3719 |
size_t strLength = str->length(); |
| 3720 |
if (strLength == 0) { |
| 3721 |
return NewDenseEmptyArray(cx); |
| 3722 |
} |
| 3723 |
|
| 3724 |
js::StaticStrings& staticStrings = cx->staticStrings(); |
| 3725 |
uint32_t resultlen = (limit < strLength ? limit : strLength); |
| 3726 |
MOZ_ASSERT(limit > 0 && resultlen > 0, |
| 3727 |
"Neither limit nor strLength is zero, so resultlen is greater " |
| 3728 |
"than zero."); |
| 3729 |
|
| 3730 |
Rooted<ArrayObject*> splits(cx, NewDenseFullyAllocatedArray(cx, resultlen)); |
| 3731 |
if (!splits) { |
| 3732 |
return nullptr; |
| 3733 |
} |
| 3734 |
|
| 3735 |
if (str->hasLatin1Chars()) { |
| 3736 |
splits->setDenseInitializedLength(resultlen); |
| 3737 |
|
| 3738 |
JS::AutoCheckCannotGC nogc; |
| 3739 |
const Latin1Char* latin1Chars = str->latin1Chars(nogc); |
| 3740 |
for (size_t i = 0; i < resultlen; ++i) { |
| 3741 |
Latin1Char c = latin1Chars[i]; |
| 3742 |
MOZ_ASSERT(staticStrings.hasUnit(c)); |
| 3743 |
splits->initDenseElement(i, StringValue(staticStrings.getUnit(c))); |
| 3744 |
} |
| 3745 |
} else { |
| 3746 |
splits->ensureDenseInitializedLength(0, resultlen); |
| 3747 |
|
| 3748 |
for (size_t i = 0; i < resultlen; ++i) { |
| 3749 |
JSString* sub = staticStrings.getUnitStringForElement(cx, str, i); |
| 3750 |
if (!sub) { |
| 3751 |
return nullptr; |
| 3752 |
} |
| 3753 |
splits->initDenseElement(i, StringValue(sub)); |
| 3754 |
} |
| 3755 |
} |
| 3756 |
|
| 3757 |
return splits; |
| 3758 |
} |
| 3759 |
|
| 3760 |
template <typename TextChar> |
| 3761 |
static MOZ_ALWAYS_INLINE ArrayObject* SplitSingleCharHelper( |
| 3762 |
JSContext* cx, Handle<JSLinearString*> str, const TextChar* text, |
| 3763 |
uint32_t textLen, char16_t patCh) { |
| 3764 |
// Count the number of occurrences of patCh within text. |
| 3765 |
uint32_t count = 0; |
| 3766 |
for (size_t index = 0; index < textLen; index++) { |
| 3767 |
if (static_cast<char16_t>(text[index]) == patCh) { |
| 3768 |
count++; |
| 3769 |
} |
| 3770 |
} |
| 3771 |
|
| 3772 |
// Handle zero-occurrence case - return input string in an array. |
| 3773 |
if (count == 0) { |
| 3774 |
return SingleElementStringArray(cx, str); |
| 3775 |
} |
| 3776 |
|
| 3777 |
// Create the result array for the substring values. |
| 3778 |
Rooted<ArrayObject*> splits(cx, NewDenseFullyAllocatedArray(cx, count + 1)); |
| 3779 |
if (!splits) { |
| 3780 |
return nullptr; |
| 3781 |
} |
| 3782 |
splits->ensureDenseInitializedLength(0, count + 1); |
| 3783 |
|
| 3784 |
// Add substrings. |
| 3785 |
uint32_t splitsIndex = 0; |
| 3786 |
size_t lastEndIndex = 0; |
| 3787 |
for (size_t index = 0; index < textLen; index++) { |
| 3788 |
if (static_cast<char16_t>(text[index]) == patCh) { |
| 3789 |
size_t subLength = size_t(index - lastEndIndex); |
| 3790 |
JSString* sub = NewDependentString(cx, str, lastEndIndex, subLength); |
| 3791 |
if (!sub) { |
| 3792 |
return nullptr; |
| 3793 |
} |
| 3794 |
splits->initDenseElement(splitsIndex++, StringValue(sub)); |
| 3795 |
lastEndIndex = index + 1; |
| 3796 |
} |
| 3797 |
} |
| 3798 |
|
| 3799 |
// Add substring for tail of string (after last match). |
| 3800 |
JSString* sub = |
| 3801 |
NewDependentString(cx, str, lastEndIndex, textLen - lastEndIndex); |
| 3802 |
if (!sub) { |
| 3803 |
return nullptr; |
| 3804 |
} |
| 3805 |
splits->initDenseElement(splitsIndex++, StringValue(sub)); |
| 3806 |
|
| 3807 |
return splits; |
| 3808 |
} |
| 3809 |
|
| 3810 |
// ES 2016 draft Mar 25, 2016 21.1.3.17 steps 4, 8, 12-18. |
| 3811 |
static ArrayObject* SplitSingleCharHelper(JSContext* cx, |
| 3812 |
Handle<JSLinearString*> str, |
| 3813 |
char16_t ch) { |
| 3814 |
// Step 12. |
| 3815 |
size_t strLength = str->length(); |
| 3816 |
|
| 3817 |
AutoStableStringChars linearChars(cx); |
| 3818 |
if (!linearChars.init(cx, str)) { |
| 3819 |
return nullptr; |
| 3820 |
} |
| 3821 |
|
| 3822 |
if (linearChars.isLatin1()) { |
| 3823 |
return SplitSingleCharHelper(cx, str, linearChars.latin1Chars(), strLength, |
| 3824 |
ch); |
| 3825 |
} |
| 3826 |
|
| 3827 |
return SplitSingleCharHelper(cx, str, linearChars.twoByteChars(), strLength, |
| 3828 |
ch); |
| 3829 |
} |
| 3830 |
|
| 3831 |
// ES 2016 draft Mar 25, 2016 21.1.3.17 steps 4, 8, 12-18. |
| 3832 |
ArrayObject* js::StringSplitString(JSContext* cx, HandleString str, |
| 3833 |
HandleString sep, uint32_t limit) { |
| 3834 |
MOZ_ASSERT(limit > 0, "Only called for strictly positive limit."); |
| 3835 |
|
| 3836 |
Rooted<JSLinearString*> linearStr(cx, str->ensureLinear(cx)); |
| 3837 |
if (!linearStr) { |
| 3838 |
return nullptr; |
| 3839 |
} |
| 3840 |
|
| 3841 |
Rooted<JSLinearString*> linearSep(cx, sep->ensureLinear(cx)); |
| 3842 |
if (!linearSep) { |
| 3843 |
return nullptr; |
| 3844 |
} |
| 3845 |
|
| 3846 |
if (linearSep->length() == 0) { |
| 3847 |
return CharSplitHelper(cx, linearStr, limit); |
| 3848 |
} |
| 3849 |
|
| 3850 |
if (linearSep->length() == 1 && limit >= static_cast<uint32_t>(INT32_MAX)) { |
| 3851 |
char16_t ch = linearSep->latin1OrTwoByteChar(0); |
| 3852 |
return SplitSingleCharHelper(cx, linearStr, ch); |
| 3853 |
} |
| 3854 |
|
| 3855 |
return SplitHelper(cx, linearStr, limit, linearSep); |
| 3856 |
} |
| 3857 |
|
| 3858 |
static const JSFunctionSpec string_methods[] = { |
| 3859 |
JS_FN("toSource", str_toSource, 0, 0), |
| 3860 |
|
| 3861 |
/* Java-like methods. */ |
| 3862 |
JS_INLINABLE_FN("toString", str_toString, 0, 0, StringToString), |
| 3863 |
JS_INLINABLE_FN("valueOf", str_toString, 0, 0, StringValueOf), |
| 3864 |
JS_INLINABLE_FN("toLowerCase", str_toLowerCase, 0, 0, StringToLowerCase), |
| 3865 |
JS_INLINABLE_FN("toUpperCase", str_toUpperCase, 0, 0, StringToUpperCase), |
| 3866 |
JS_INLINABLE_FN("charAt", str_charAt, 1, 0, StringCharAt), |
| 3867 |
JS_INLINABLE_FN("charCodeAt", str_charCodeAt, 1, 0, StringCharCodeAt), |
| 3868 |
JS_INLINABLE_FN("codePointAt", str_codePointAt, 1, 0, StringCodePointAt), |
| 3869 |
JS_INLINABLE_FN("at", str_at, 1, 0, StringAt), |
| 3870 |
JS_SELF_HOSTED_FN("substring", "String_substring", 2, 0), |
| 3871 |
JS_SELF_HOSTED_FN("padStart", "String_pad_start", 2, 0), |
| 3872 |
JS_SELF_HOSTED_FN("padEnd", "String_pad_end", 2, 0), |
| 3873 |
JS_INLINABLE_FN("includes", str_includes, 1, 0, StringIncludes), |
| 3874 |
JS_INLINABLE_FN("indexOf", str_indexOf, 1, 0, StringIndexOf), |
| 3875 |
JS_INLINABLE_FN("lastIndexOf", str_lastIndexOf, 1, 0, StringLastIndexOf), |
| 3876 |
JS_INLINABLE_FN("startsWith", str_startsWith, 1, 0, StringStartsWith), |
| 3877 |
JS_INLINABLE_FN("endsWith", str_endsWith, 1, 0, StringEndsWith), |
| 3878 |
JS_INLINABLE_FN("trim", str_trim, 0, 0, StringTrim), |
| 3879 |
JS_INLINABLE_FN("trimStart", str_trimStart, 0, 0, StringTrimStart), |
| 3880 |
JS_INLINABLE_FN("trimEnd", str_trimEnd, 0, 0, StringTrimEnd), |
| 3881 |
#if JS_HAS_INTL_API |
| 3882 |
JS_SELF_HOSTED_FN("toLocaleLowerCase", "String_toLocaleLowerCase", 0, 0), |
| 3883 |
JS_SELF_HOSTED_FN("toLocaleUpperCase", "String_toLocaleUpperCase", 0, 0), |
| 3884 |
JS_SELF_HOSTED_FN("localeCompare", "String_localeCompare", 1, 0), |
| 3885 |
#else |
| 3886 |
JS_FN("toLocaleLowerCase", str_toLocaleLowerCase, 0, 0), |
| 3887 |
JS_FN("toLocaleUpperCase", str_toLocaleUpperCase, 0, 0), |
| 3888 |
JS_FN("localeCompare", str_localeCompare, 1, 0), |
| 3889 |
#endif |
| 3890 |
JS_SELF_HOSTED_FN("repeat", "String_repeat", 1, 0), |
| 3891 |
#if JS_HAS_INTL_API |
| 3892 |
JS_FN("normalize", str_normalize, 0, 0), |
| 3893 |
#endif |
| 3894 |
|
| 3895 |
/* Perl-ish methods (search is actually Python-esque). */ |
| 3896 |
JS_SELF_HOSTED_FN("match", "String_match", 1, 0), |
| 3897 |
JS_SELF_HOSTED_FN("matchAll", "String_matchAll", 1, 0), |
| 3898 |
JS_SELF_HOSTED_FN("search", "String_search", 1, 0), |
| 3899 |
JS_SELF_HOSTED_FN("replace", "String_replace", 2, 0), |
| 3900 |
JS_SELF_HOSTED_FN("replaceAll", "String_replaceAll", 2, 0), |
| 3901 |
JS_SELF_HOSTED_FN("split", "String_split", 2, 0), |
| 3902 |
JS_SELF_HOSTED_FN("substr", "String_substr", 2, 0), |
| 3903 |
|
| 3904 |
/* Python-esque sequence methods. */ |
| 3905 |
JS_SELF_HOSTED_FN("concat", "String_concat", 1, 0), |
| 3906 |
JS_SELF_HOSTED_FN("slice", "String_slice", 2, 0), |
| 3907 |
|
| 3908 |
/* HTML string methods. */ |
| 3909 |
JS_SELF_HOSTED_FN("bold", "String_bold", 0, 0), |
| 3910 |
JS_SELF_HOSTED_FN("italics", "String_italics", 0, 0), |
| 3911 |
JS_SELF_HOSTED_FN("fixed", "String_fixed", 0, 0), |
| 3912 |
JS_SELF_HOSTED_FN("strike", "String_strike", 0, 0), |
| 3913 |
JS_SELF_HOSTED_FN("small", "String_small", 0, 0), |
| 3914 |
JS_SELF_HOSTED_FN("big", "String_big", 0, 0), |
| 3915 |
JS_SELF_HOSTED_FN("blink", "String_blink", 0, 0), |
| 3916 |
JS_SELF_HOSTED_FN("sup", "String_sup", 0, 0), |
| 3917 |
JS_SELF_HOSTED_FN("sub", "String_sub", 0, 0), |
| 3918 |
JS_SELF_HOSTED_FN("anchor", "String_anchor", 1, 0), |
| 3919 |
JS_SELF_HOSTED_FN("link", "String_link", 1, 0), |
| 3920 |
JS_SELF_HOSTED_FN("fontcolor", "String_fontcolor", 1, 0), |
| 3921 |
JS_SELF_HOSTED_FN("fontsize", "String_fontsize", 1, 0), |
| 3922 |
|
| 3923 |
JS_SELF_HOSTED_SYM_FN(iterator, "String_iterator", 0, 0), |
| 3924 |
|
| 3925 |
/* well-formed unicode strings */ |
| 3926 |
JS_FN("isWellFormed", str_isWellFormed, 0, 0), |
| 3927 |
JS_FN("toWellFormed", str_toWellFormed, 0, 0), |
| 3928 |
|
| 3929 |
JS_FS_END, |
| 3930 |
}; |
| 3931 |
|
| 3932 |
// ES6 rev 27 (2014 Aug 24) 21.1.1 |
| 3933 |
bool js::StringConstructor(JSContext* cx, unsigned argc, Value* vp) { |
| 3934 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3935 |
|
| 3936 |
RootedString str(cx); |
| 3937 |
if (args.length() > 0) { |
| 3938 |
if (!args.isConstructing() && args[0].isSymbol()) { |
| 3939 |
return js::SymbolDescriptiveString(cx, args[0].toSymbol(), args.rval()); |
| 3940 |
} |
| 3941 |
|
| 3942 |
str = ToString<CanGC>(cx, args[0]); |
| 3943 |
if (!str) { |
| 3944 |
return false; |
| 3945 |
} |
| 3946 |
} else { |
| 3947 |
str = cx->runtime()->emptyString; |
| 3948 |
} |
| 3949 |
|
| 3950 |
if (args.isConstructing()) { |
| 3951 |
RootedObject proto(cx); |
| 3952 |
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_String, &proto)) { |
| 3953 |
return false; |
| 3954 |
} |
| 3955 |
|
| 3956 |
StringObject* strobj = StringObject::create(cx, str, proto); |
| 3957 |
if (!strobj) { |
| 3958 |
return false; |
| 3959 |
} |
| 3960 |
args.rval().setObject(*strobj); |
| 3961 |
return true; |
| 3962 |
} |
| 3963 |
|
| 3964 |
args.rval().setString(str); |
| 3965 |
return true; |
| 3966 |
} |
| 3967 |
|
| 3968 |
static inline JSLinearString* CodeUnitToString(JSContext* cx, char16_t code) { |
| 3969 |
if (StaticStrings::hasUnit(code)) { |
| 3970 |
return cx->staticStrings().getUnit(code); |
| 3971 |
} |
| 3972 |
return NewInlineString<CanGC>(cx, {code}, 1); |
| 3973 |
} |
| 3974 |
|
| 3975 |
JSLinearString* js::StringFromCharCode(JSContext* cx, int32_t charCode) { |
| 3976 |
return CodeUnitToString(cx, char16_t(charCode)); |
| 3977 |
} |
| 3978 |
|
| 3979 |
JSLinearString* js::StringFromCodePoint(JSContext* cx, char32_t codePoint) { |
| 3980 |
MOZ_ASSERT(codePoint <= unicode::NonBMPMax); |
| 3981 |
|
| 3982 |
if (!unicode::IsSupplementary(codePoint)) { |
| 3983 |
return CodeUnitToString(cx, char16_t(codePoint)); |
| 3984 |
} |
| 3985 |
|
| 3986 |
char16_t chars[] = {unicode::LeadSurrogate(codePoint), |
| 3987 |
unicode::TrailSurrogate(codePoint)}; |
| 3988 |
return NewInlineString<CanGC>(cx, chars, 2); |
| 3989 |
} |
| 3990 |
|
| 3991 |
// Inspect arguments to guess the output string type. |
| 3992 |
static bool GuessFromCharCodeIsLatin1(const CallArgs& args) { |
| 3993 |
// Arbitrarily chosen number of samples to inspect. |
| 3994 |
constexpr unsigned SampleSize = 8; |
| 3995 |
|
| 3996 |
for (unsigned i = 0; i < std::min(args.length(), SampleSize); i++) { |
| 3997 |
auto v = args[i]; |
| 3998 |
if (v.isInt32() && uint16_t(v.toInt32()) > JSString::MAX_LATIN1_CHAR) { |
| 3999 |
return false; |
| 4000 |
} |
| 4001 |
} |
| 4002 |
return true; |
| 4003 |
} |
| 4004 |
|
| 4005 |
/** |
| 4006 |
* 22.1.2.1 String.fromCharCode ( ...codeUnits ) |
| 4007 |
* |
| 4008 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 4009 |
*/ |
| 4010 |
bool js::str_fromCharCode(JSContext* cx, unsigned argc, Value* vp) { |
| 4011 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4012 |
|
| 4013 |
MOZ_ASSERT(args.length() <= ARGS_LENGTH_MAX); |
| 4014 |
|
| 4015 |
// Optimize the single-char case. |
| 4016 |
if (args.length() == 1) { |
| 4017 |
uint16_t code; |
| 4018 |
if (!ToUint16(cx, args[0], &code)) { |
| 4019 |
return false; |
| 4020 |
} |
| 4021 |
|
| 4022 |
JSString* str = CodeUnitToString(cx, char16_t(code)); |
| 4023 |
if (!str) { |
| 4024 |
return false; |
| 4025 |
} |
| 4026 |
|
| 4027 |
args.rval().setString(str); |
| 4028 |
return true; |
| 4029 |
} |
| 4030 |
|
| 4031 |
// Optimize the case where the result will be a Latin-1 string. |
| 4032 |
StringChars<Latin1Char> latin1Chars(cx); |
| 4033 |
|
| 4034 |
unsigned i = 0; |
| 4035 |
uint16_t firstTwoByteChar = 0; |
| 4036 |
if (GuessFromCharCodeIsLatin1(args)) { |
| 4037 |
if (!latin1Chars.maybeAlloc(cx, args.length())) { |
| 4038 |
return false; |
| 4039 |
} |
| 4040 |
|
| 4041 |
for (; i < args.length(); i++) { |
| 4042 |
uint16_t code; |
| 4043 |
if (!ToUint16(cx, args[i], &code)) { |
| 4044 |
return false; |
| 4045 |
} |
| 4046 |
|
| 4047 |
if (code > JSString::MAX_LATIN1_CHAR) { |
| 4048 |
firstTwoByteChar = code; |
| 4049 |
break; |
| 4050 |
} |
| 4051 |
|
| 4052 |
AutoCheckCannotGC nogc; |
| 4053 |
latin1Chars.data(nogc)[i] = code; |
| 4054 |
} |
| 4055 |
|
| 4056 |
if (i == args.length()) { |
| 4057 |
JSString* str = latin1Chars.toStringDontDeflate<CanGC>(cx, args.length()); |
| 4058 |
if (!str) { |
| 4059 |
return false; |
| 4060 |
} |
| 4061 |
|
| 4062 |
args.rval().setString(str); |
| 4063 |
return true; |
| 4064 |
} |
| 4065 |
} |
| 4066 |
|
| 4067 |
StringChars<char16_t> twoByteChars(cx); |
| 4068 |
if (!twoByteChars.maybeAlloc(cx, args.length())) { |
| 4069 |
return false; |
| 4070 |
} |
| 4071 |
|
| 4072 |
// Copy the already processed characters. |
| 4073 |
if (i > 0) { |
| 4074 |
AutoCheckCannotGC nogc; |
| 4075 |
std::copy_n(latin1Chars.data(nogc), i, twoByteChars.data(nogc)); |
| 4076 |
} |
| 4077 |
|
| 4078 |
// Copy the first two-byte character, if present. |
| 4079 |
if (firstTwoByteChar > 0) { |
| 4080 |
MOZ_ASSERT(firstTwoByteChar > JSString::MAX_LATIN1_CHAR); |
| 4081 |
|
| 4082 |
AutoCheckCannotGC nogc; |
| 4083 |
twoByteChars.data(nogc)[i++] = char16_t(firstTwoByteChar); |
| 4084 |
} |
| 4085 |
|
| 4086 |
for (; i < args.length(); i++) { |
| 4087 |
uint16_t code; |
| 4088 |
if (!ToUint16(cx, args[i], &code)) { |
| 4089 |
return false; |
| 4090 |
} |
| 4091 |
|
| 4092 |
AutoCheckCannotGC nogc; |
| 4093 |
twoByteChars.data(nogc)[i] = code; |
| 4094 |
} |
| 4095 |
|
| 4096 |
JSString* str = twoByteChars.toStringDontDeflate<CanGC>(cx, args.length()); |
| 4097 |
if (!str) { |
| 4098 |
return false; |
| 4099 |
} |
| 4100 |
|
| 4101 |
args.rval().setString(str); |
| 4102 |
return true; |
| 4103 |
} |
| 4104 |
|
| 4105 |
/** |
| 4106 |
* 22.1.2.2 String.fromCodePoint ( ...codePoints ) |
| 4107 |
* |
| 4108 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 4109 |
*/ |
| 4110 |
static MOZ_ALWAYS_INLINE bool ToCodePoint(JSContext* cx, HandleValue code, |
| 4111 |
char32_t* codePoint) { |
| 4112 |
// String.fromCodePoint, Steps 2.a-d. |
| 4113 |
|
| 4114 |
// Fast path for the common case - the input is already an int32. |
| 4115 |
if (code.isInt32()) { |
| 4116 |
// Step 2.a. |
| 4117 |
int32_t nextCP = code.toInt32(); |
| 4118 |
|
| 4119 |
// Steps 2.b-d. |
| 4120 |
if (MOZ_LIKELY(uint32_t(nextCP) <= unicode::NonBMPMax)) { |
| 4121 |
*codePoint = char32_t(nextCP); |
| 4122 |
return true; |
| 4123 |
} |
| 4124 |
} |
| 4125 |
|
| 4126 |
// Step 2.a. |
| 4127 |
double nextCP; |
| 4128 |
if (!ToNumber(cx, code, &nextCP)) { |
| 4129 |
return false; |
| 4130 |
} |
| 4131 |
|
| 4132 |
// Steps 2.b-c. |
| 4133 |
if (JS::ToInteger(nextCP) != nextCP || nextCP < 0 || |
| 4134 |
nextCP > unicode::NonBMPMax) { |
| 4135 |
ToCStringBuf cbuf; |
| 4136 |
const char* numStr = NumberToCString(&cbuf, nextCP); |
| 4137 |
MOZ_ASSERT(numStr); |
| 4138 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 4139 |
JSMSG_NOT_A_CODEPOINT, numStr); |
| 4140 |
return false; |
| 4141 |
} |
| 4142 |
|
| 4143 |
// Steps 2.d. |
| 4144 |
*codePoint = char32_t(nextCP); |
| 4145 |
return true; |
| 4146 |
} |
| 4147 |
|
| 4148 |
/** |
| 4149 |
* 22.1.2.2 String.fromCodePoint ( ...codePoints ) |
| 4150 |
* |
| 4151 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 4152 |
*/ |
| 4153 |
static bool str_fromCodePoint_few_args(JSContext* cx, const CallArgs& args) { |
| 4154 |
MOZ_ASSERT(args.length() <= JSFatInlineString::MAX_LENGTH_TWO_BYTE / 2); |
| 4155 |
|
| 4156 |
// Step 1. |
| 4157 |
char16_t elements[JSFatInlineString::MAX_LENGTH_TWO_BYTE]; |
| 4158 |
|
| 4159 |
// Step 2. |
| 4160 |
unsigned length = 0; |
| 4161 |
for (unsigned nextIndex = 0; nextIndex < args.length(); nextIndex++) { |
| 4162 |
// Steps 2.a-c. |
| 4163 |
char32_t codePoint; |
| 4164 |
if (!ToCodePoint(cx, args[nextIndex], &codePoint)) { |
| 4165 |
return false; |
| 4166 |
} |
| 4167 |
|
| 4168 |
// Step 2.d. |
| 4169 |
unicode::UTF16Encode(codePoint, elements, &length); |
| 4170 |
} |
| 4171 |
|
| 4172 |
// Steps 3-4. |
| 4173 |
JSString* str = NewStringCopyN<CanGC>(cx, elements, length); |
| 4174 |
if (!str) { |
| 4175 |
return false; |
| 4176 |
} |
| 4177 |
|
| 4178 |
args.rval().setString(str); |
| 4179 |
return true; |
| 4180 |
} |
| 4181 |
|
| 4182 |
/** |
| 4183 |
* 22.1.2.2 String.fromCodePoint ( ...codePoints ) |
| 4184 |
* |
| 4185 |
* ES2024 draft rev 7d2644968bd56d54d2886c012d18698ff3f72c35 |
| 4186 |
*/ |
| 4187 |
bool js::str_fromCodePoint(JSContext* cx, unsigned argc, Value* vp) { |
| 4188 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4189 |
|
| 4190 |
// Optimize the single code-point case. |
| 4191 |
if (args.length() == 1) { |
| 4192 |
// Step 1. (Omitted) |
| 4193 |
|
| 4194 |
// Step 2. |
| 4195 |
char32_t codePoint; |
| 4196 |
if (!ToCodePoint(cx, args[0], &codePoint)) { |
| 4197 |
return false; |
| 4198 |
} |
| 4199 |
|
| 4200 |
// Steps 3-4. |
| 4201 |
JSString* str = StringFromCodePoint(cx, codePoint); |
| 4202 |
if (!str) { |
| 4203 |
return false; |
| 4204 |
} |
| 4205 |
|
| 4206 |
args.rval().setString(str); |
| 4207 |
return true; |
| 4208 |
} |
| 4209 |
|
| 4210 |
// Optimize the case where the result will definitely fit in an inline |
| 4211 |
// string (thin or fat) and so we don't need to malloc the chars. (We could |
| 4212 |
// cover some cases where |args.length()| goes up to |
| 4213 |
// JSFatInlineString::MAX_LENGTH_LATIN1 / 2 if we also checked if the chars |
| 4214 |
// are all Latin-1, but it doesn't seem worth the effort.) |
| 4215 |
if (args.length() <= JSFatInlineString::MAX_LENGTH_TWO_BYTE / 2) { |
| 4216 |
return str_fromCodePoint_few_args(cx, args); |
| 4217 |
} |
| 4218 |
|
| 4219 |
// Step 1. |
| 4220 |
static_assert( |
| 4221 |
ARGS_LENGTH_MAX < std::numeric_limits<decltype(args.length())>::max() / 2, |
| 4222 |
"|args.length() * 2| does not overflow"); |
| 4223 |
auto elements = cx->make_pod_arena_array<char16_t>(js::StringBufferArena, |
| 4224 |
args.length() * 2); |
| 4225 |
if (!elements) { |
| 4226 |
return false; |
| 4227 |
} |
| 4228 |
|
| 4229 |
// Steps 2. |
| 4230 |
unsigned length = 0; |
| 4231 |
for (unsigned nextIndex = 0; nextIndex < args.length(); nextIndex++) { |
| 4232 |
// Steps 2.a-c. |
| 4233 |
char32_t codePoint; |
| 4234 |
if (!ToCodePoint(cx, args[nextIndex], &codePoint)) { |
| 4235 |
return false; |
| 4236 |
} |
| 4237 |
|
| 4238 |
// Step 2.d. |
| 4239 |
unicode::UTF16Encode(codePoint, elements.get(), &length); |
| 4240 |
} |
| 4241 |
|
| 4242 |
// Steps 3-4. |
| 4243 |
JSString* str = NewString<CanGC>(cx, std::move(elements), length); |
| 4244 |
if (!str) { |
| 4245 |
return false; |
| 4246 |
} |
| 4247 |
|
| 4248 |
args.rval().setString(str); |
| 4249 |
return true; |
| 4250 |
} |
| 4251 |
|
| 4252 |
static const JSFunctionSpec string_static_methods[] = { |
| 4253 |
JS_INLINABLE_FN("fromCharCode", js::str_fromCharCode, 1, 0, |
| 4254 |
StringFromCharCode), |
| 4255 |
JS_INLINABLE_FN("fromCodePoint", js::str_fromCodePoint, 1, 0, |
| 4256 |
StringFromCodePoint), |
| 4257 |
|
| 4258 |
JS_SELF_HOSTED_FN("raw", "String_static_raw", 1, 0), |
| 4259 |
JS_FS_END, |
| 4260 |
}; |
| 4261 |
|
| 4262 |
/* static */ |
| 4263 |
SharedShape* StringObject::assignInitialShape(JSContext* cx, |
| 4264 |
Handle<StringObject*> obj) { |
| 4265 |
MOZ_ASSERT(obj->empty()); |
| 4266 |
|
| 4267 |
if (!NativeObject::addPropertyInReservedSlot(cx, obj, cx->names().length, |
| 4268 |
LENGTH_SLOT, {})) { |
| 4269 |
return nullptr; |
| 4270 |
} |
| 4271 |
|
| 4272 |
return obj->sharedShape(); |
| 4273 |
} |
| 4274 |
|
| 4275 |
JSObject* StringObject::createPrototype(JSContext* cx, JSProtoKey key) { |
| 4276 |
Rooted<JSString*> empty(cx, cx->runtime()->emptyString); |
| 4277 |
|
| 4278 |
// Because the `length` property of a StringObject is both non-configurable |
| 4279 |
// and non-writable, we need to take the slow path of proxy result |
| 4280 |
// validation for them, and so we need to ensure that the initial ObjectFlags |
| 4281 |
// reflect that. Normally this would be handled for us, but the special |
| 4282 |
// SharedShape::ensureInitialCustomShape path which ultimately takes us |
| 4283 |
// through StringObject::assignInitialShape which adds the problematic |
| 4284 |
// property sneaks past our flag setting logic and results in a failed |
| 4285 |
// lookup of the initial shape in SharedShape::insertInitialShape. |
| 4286 |
Rooted<StringObject*> proto( |
| 4287 |
cx, GlobalObject::createBlankPrototype<StringObject>( |
| 4288 |
cx, cx->global(), |
| 4289 |
ObjectFlags({ObjectFlag::NeedsProxyGetSetResultValidation}))); |
| 4290 |
if (!proto) { |
| 4291 |
return nullptr; |
| 4292 |
} |
| 4293 |
if (!StringObject::init(cx, proto, empty)) { |
| 4294 |
return nullptr; |
| 4295 |
} |
| 4296 |
return proto; |
| 4297 |
} |
| 4298 |
|
| 4299 |
static bool StringClassFinish(JSContext* cx, HandleObject ctor, |
| 4300 |
HandleObject proto) { |
| 4301 |
Handle<NativeObject*> nativeProto = proto.as<NativeObject>(); |
| 4302 |
|
| 4303 |
// Create "trimLeft" as an alias for "trimStart". |
| 4304 |
RootedValue trimFn(cx); |
| 4305 |
RootedId trimId(cx, NameToId(cx->names().trimStart)); |
| 4306 |
RootedId trimAliasId(cx, NameToId(cx->names().trimLeft)); |
| 4307 |
if (!NativeGetProperty(cx, nativeProto, trimId, &trimFn) || |
| 4308 |
!NativeDefineDataProperty(cx, nativeProto, trimAliasId, trimFn, 0)) { |
| 4309 |
return false; |
| 4310 |
} |
| 4311 |
|
| 4312 |
// Create "trimRight" as an alias for "trimEnd". |
| 4313 |
trimId = NameToId(cx->names().trimEnd); |
| 4314 |
trimAliasId = NameToId(cx->names().trimRight); |
| 4315 |
if (!NativeGetProperty(cx, nativeProto, trimId, &trimFn) || |
| 4316 |
!NativeDefineDataProperty(cx, nativeProto, trimAliasId, trimFn, 0)) { |
| 4317 |
return false; |
| 4318 |
} |
| 4319 |
|
| 4320 |
/* |
| 4321 |
* Define escape/unescape, the URI encode/decode functions, and maybe |
| 4322 |
* uneval on the global object. |
| 4323 |
*/ |
| 4324 |
if (!JS_DefineFunctions(cx, cx->global(), string_functions)) { |
| 4325 |
return false; |
| 4326 |
} |
| 4327 |
|
| 4328 |
return true; |
| 4329 |
} |
| 4330 |
|
| 4331 |
const ClassSpec StringObject::classSpec_ = { |
| 4332 |
GenericCreateConstructor<StringConstructor, 1, gc::AllocKind::FUNCTION, |
| 4333 |
&jit::JitInfo_String>, |
| 4334 |
StringObject::createPrototype, |
| 4335 |
string_static_methods, |
| 4336 |
nullptr, |
| 4337 |
string_methods, |
| 4338 |
nullptr, |
| 4339 |
StringClassFinish, |
| 4340 |
}; |
| 4341 |
|
| 4342 |
#define ____ false |
| 4343 |
|
| 4344 |
/* |
| 4345 |
* Uri reserved chars + #: |
| 4346 |
* - 35: # |
| 4347 |
* - 36: $ |
| 4348 |
* - 38: & |
| 4349 |
* - 43: + |
| 4350 |
* - 44: , |
| 4351 |
* - 47: / |
| 4352 |
* - 58: : |
| 4353 |
* - 59: ; |
| 4354 |
* - 61: = |
| 4355 |
* - 63: ? |
| 4356 |
* - 64: @ |
| 4357 |
*/ |
| 4358 |
static const bool js_isUriReservedPlusPound[] = { |
| 4359 |
// clang-format off |
| 4360 |
/* 0 1 2 3 4 5 6 7 8 9 */ |
| 4361 |
/* 0 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4362 |
/* 1 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4363 |
/* 2 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4364 |
/* 3 */ ____, ____, ____, ____, ____, true, true, ____, true, ____, |
| 4365 |
/* 4 */ ____, ____, ____, true, true, ____, ____, true, ____, ____, |
| 4366 |
/* 5 */ ____, ____, ____, ____, ____, ____, ____, ____, true, true, |
| 4367 |
/* 6 */ ____, true, ____, true, true, ____, ____, ____, ____, ____, |
| 4368 |
/* 7 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4369 |
/* 8 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4370 |
/* 9 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4371 |
/* 10 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4372 |
/* 11 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4373 |
/* 12 */ ____, ____, ____, ____, ____, ____, ____, ____ |
| 4374 |
// clang-format on |
| 4375 |
}; |
| 4376 |
|
| 4377 |
/* |
| 4378 |
* Uri unescaped chars: |
| 4379 |
* - 33: ! |
| 4380 |
* - 39: ' |
| 4381 |
* - 40: ( |
| 4382 |
* - 41: ) |
| 4383 |
* - 42: * |
| 4384 |
* - 45: - |
| 4385 |
* - 46: . |
| 4386 |
* - 48..57: 0-9 |
| 4387 |
* - 65..90: A-Z |
| 4388 |
* - 95: _ |
| 4389 |
* - 97..122: a-z |
| 4390 |
* - 126: ~ |
| 4391 |
*/ |
| 4392 |
static const bool js_isUriUnescaped[] = { |
| 4393 |
// clang-format off |
| 4394 |
/* 0 1 2 3 4 5 6 7 8 9 */ |
| 4395 |
/* 0 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4396 |
/* 1 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4397 |
/* 2 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____, |
| 4398 |
/* 3 */ ____, ____, ____, true, ____, ____, ____, ____, ____, true, |
| 4399 |
/* 4 */ true, true, true, ____, ____, true, true, ____, true, true, |
| 4400 |
/* 5 */ true, true, true, true, true, true, true, true, ____, ____, |
| 4401 |
/* 6 */ ____, ____, ____, ____, ____, true, true, true, true, true, |
| 4402 |
/* 7 */ true, true, true, true, true, true, true, true, true, true, |
| 4403 |
/* 8 */ true, true, true, true, true, true, true, true, true, true, |
| 4404 |
/* 9 */ true, ____, ____, ____, ____, true, ____, true, true, true, |
| 4405 |
/* 10 */ true, true, true, true, true, true, true, true, true, true, |
| 4406 |
/* 11 */ true, true, true, true, true, true, true, true, true, true, |
| 4407 |
/* 12 */ true, true, true, ____, ____, ____, true, ____ |
| 4408 |
// clang-format on |
| 4409 |
}; |
| 4410 |
|
| 4411 |
#undef ____ |
| 4412 |
|
| 4413 |
static inline bool TransferBufferToString(JSStringBuilder& sb, JSString* str, |
| 4414 |
MutableHandleValue rval) { |
| 4415 |
if (!sb.empty()) { |
| 4416 |
str = sb.finishString(); |
| 4417 |
if (!str) { |
| 4418 |
return false; |
| 4419 |
} |
| 4420 |
} |
| 4421 |
rval.setString(str); |
| 4422 |
return true; |
| 4423 |
} |
| 4424 |
|
| 4425 |
/* |
| 4426 |
* ECMA 3, 15.1.3 URI Handling Function Properties |
| 4427 |
* |
| 4428 |
* The following are implementations of the algorithms |
| 4429 |
* given in the ECMA specification for the hidden functions |
| 4430 |
* 'Encode' and 'Decode'. |
| 4431 |
*/ |
| 4432 |
enum EncodeResult { Encode_Failure, Encode_BadUri, Encode_Success }; |
| 4433 |
|
| 4434 |
// Bug 1403318: GCC sometimes inlines this Encode function rather than the |
| 4435 |
// caller Encode function. Annotate both functions with MOZ_NEVER_INLINE resp. |
| 4436 |
// MOZ_ALWAYS_INLINE to ensure we get the desired inlining behavior. |
| 4437 |
template <typename CharT> |
| 4438 |
static MOZ_NEVER_INLINE EncodeResult Encode(StringBuilder& sb, |
| 4439 |
const CharT* chars, size_t length, |
| 4440 |
const bool* unescapedSet) { |
| 4441 |
Latin1Char hexBuf[3]; |
| 4442 |
hexBuf[0] = '%'; |
| 4443 |
|
| 4444 |
auto appendEncoded = [&sb, &hexBuf](Latin1Char c) { |
| 4445 |
static const char HexDigits[] = "0123456789ABCDEF"; /* NB: uppercase */ |
| 4446 |
|
| 4447 |
hexBuf[1] = HexDigits[c >> 4]; |
| 4448 |
hexBuf[2] = HexDigits[c & 0xf]; |
| 4449 |
return sb.append(hexBuf, 3); |
| 4450 |
}; |
| 4451 |
|
| 4452 |
auto appendRange = [&sb, chars, length](size_t start, size_t end) { |
| 4453 |
MOZ_ASSERT(start <= end); |
| 4454 |
|
| 4455 |
if (start < end) { |
| 4456 |
if (start == 0) { |
| 4457 |
if (!sb.reserve(length)) { |
| 4458 |
return false; |
| 4459 |
} |
| 4460 |
} |
| 4461 |
return sb.append(chars + start, chars + end); |
| 4462 |
} |
| 4463 |
return true; |
| 4464 |
}; |
| 4465 |
|
| 4466 |
size_t startAppend = 0; |
| 4467 |
for (size_t k = 0; k < length; k++) { |
| 4468 |
CharT c = chars[k]; |
| 4469 |
if (c < 128 && |
| 4470 |
(js_isUriUnescaped[c] || (unescapedSet && unescapedSet[c]))) { |
| 4471 |
continue; |
| 4472 |
} else { |
| 4473 |
if (!appendRange(startAppend, k)) { |
| 4474 |
return Encode_Failure; |
| 4475 |
} |
| 4476 |
|
| 4477 |
if constexpr (std::is_same_v<CharT, Latin1Char>) { |
| 4478 |
if (c < 0x80) { |
| 4479 |
if (!appendEncoded(c)) { |
| 4480 |
return Encode_Failure; |
| 4481 |
} |
| 4482 |
} else { |
| 4483 |
if (!appendEncoded(0xC0 | (c >> 6)) || |
| 4484 |
!appendEncoded(0x80 | (c & 0x3F))) { |
| 4485 |
return Encode_Failure; |
| 4486 |
} |
| 4487 |
} |
| 4488 |
} else { |
| 4489 |
if (unicode::IsTrailSurrogate(c)) { |
| 4490 |
return Encode_BadUri; |
| 4491 |
} |
| 4492 |
|
| 4493 |
char32_t v; |
| 4494 |
if (!unicode::IsLeadSurrogate(c)) { |
| 4495 |
v = c; |
| 4496 |
} else { |
| 4497 |
k++; |
| 4498 |
if (k == length) { |
| 4499 |
return Encode_BadUri; |
| 4500 |
} |
| 4501 |
|
| 4502 |
char16_t c2 = chars[k]; |
| 4503 |
if (!unicode::IsTrailSurrogate(c2)) { |
| 4504 |
return Encode_BadUri; |
| 4505 |
} |
| 4506 |
|
| 4507 |
v = unicode::UTF16Decode(c, c2); |
| 4508 |
} |
| 4509 |
|
| 4510 |
uint8_t utf8buf[4]; |
| 4511 |
size_t L = OneUcs4ToUtf8Char(utf8buf, v); |
| 4512 |
for (size_t j = 0; j < L; j++) { |
| 4513 |
if (!appendEncoded(utf8buf[j])) { |
| 4514 |
return Encode_Failure; |
| 4515 |
} |
| 4516 |
} |
| 4517 |
} |
| 4518 |
|
| 4519 |
startAppend = k + 1; |
| 4520 |
} |
| 4521 |
} |
| 4522 |
|
| 4523 |
if (startAppend > 0) { |
| 4524 |
if (!appendRange(startAppend, length)) { |
| 4525 |
return Encode_Failure; |
| 4526 |
} |
| 4527 |
} |
| 4528 |
|
| 4529 |
return Encode_Success; |
| 4530 |
} |
| 4531 |
|
| 4532 |
static MOZ_ALWAYS_INLINE bool Encode(JSContext* cx, Handle<JSLinearString*> str, |
| 4533 |
const bool* unescapedSet, |
| 4534 |
MutableHandleValue rval) { |
| 4535 |
size_t length = str->length(); |
| 4536 |
if (length == 0) { |
| 4537 |
rval.setString(cx->runtime()->emptyString); |
| 4538 |
return true; |
| 4539 |
} |
| 4540 |
|
| 4541 |
JSStringBuilder sb(cx); |
| 4542 |
|
| 4543 |
EncodeResult res; |
| 4544 |
if (str->hasLatin1Chars()) { |
| 4545 |
AutoCheckCannotGC nogc; |
| 4546 |
res = Encode(sb, str->latin1Chars(nogc), str->length(), unescapedSet); |
| 4547 |
} else { |
| 4548 |
AutoCheckCannotGC nogc; |
| 4549 |
res = Encode(sb, str->twoByteChars(nogc), str->length(), unescapedSet); |
| 4550 |
} |
| 4551 |
|
| 4552 |
if (res == Encode_Failure) { |
| 4553 |
return false; |
| 4554 |
} |
| 4555 |
|
| 4556 |
if (res == Encode_BadUri) { |
| 4557 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_URI); |
| 4558 |
return false; |
| 4559 |
} |
| 4560 |
|
| 4561 |
MOZ_ASSERT(res == Encode_Success); |
| 4562 |
return TransferBufferToString(sb, str, rval); |
| 4563 |
} |
| 4564 |
|
| 4565 |
enum DecodeResult { Decode_Failure, Decode_BadUri, Decode_Success }; |
| 4566 |
|
| 4567 |
template <typename CharT> |
| 4568 |
static DecodeResult Decode(StringBuilder& sb, const CharT* chars, size_t length, |
| 4569 |
const bool* reservedSet) { |
| 4570 |
auto appendRange = [&sb, chars](size_t start, size_t end) { |
| 4571 |
MOZ_ASSERT(start <= end); |
| 4572 |
|
| 4573 |
if (start < end) { |
| 4574 |
return sb.append(chars + start, chars + end); |
| 4575 |
} |
| 4576 |
return true; |
| 4577 |
}; |
| 4578 |
|
| 4579 |
size_t startAppend = 0; |
| 4580 |
for (size_t k = 0; k < length; k++) { |
| 4581 |
CharT c = chars[k]; |
| 4582 |
if (c == '%') { |
| 4583 |
size_t start = k; |
| 4584 |
if ((k + 2) >= length) { |
| 4585 |
return Decode_BadUri; |
| 4586 |
} |
| 4587 |
|
| 4588 |
if (!IsAsciiHexDigit(chars[k + 1]) || !IsAsciiHexDigit(chars[k + 2])) { |
| 4589 |
return Decode_BadUri; |
| 4590 |
} |
| 4591 |
|
| 4592 |
uint32_t B = AsciiAlphanumericToNumber(chars[k + 1]) * 16 + |
| 4593 |
AsciiAlphanumericToNumber(chars[k + 2]); |
| 4594 |
k += 2; |
| 4595 |
if (B < 128) { |
| 4596 |
Latin1Char ch = Latin1Char(B); |
| 4597 |
if (reservedSet && reservedSet[ch]) { |
| 4598 |
continue; |
| 4599 |
} |
| 4600 |
|
| 4601 |
if (!appendRange(startAppend, start)) { |
| 4602 |
return Decode_Failure; |
| 4603 |
} |
| 4604 |
if (!sb.append(ch)) { |
| 4605 |
return Decode_Failure; |
| 4606 |
} |
| 4607 |
} else { |
| 4608 |
int n = 1; |
| 4609 |
while (B & (0x80 >> n)) { |
| 4610 |
n++; |
| 4611 |
} |
| 4612 |
|
| 4613 |
if (n == 1 || n > 4) { |
| 4614 |
return Decode_BadUri; |
| 4615 |
} |
| 4616 |
|
| 4617 |
uint8_t octets[4]; |
| 4618 |
octets[0] = (uint8_t)B; |
| 4619 |
if (k + 3 * (n - 1) >= length) { |
| 4620 |
return Decode_BadUri; |
| 4621 |
} |
| 4622 |
|
| 4623 |
for (int j = 1; j < n; j++) { |
| 4624 |
k++; |
| 4625 |
if (chars[k] != '%') { |
| 4626 |
return Decode_BadUri; |
| 4627 |
} |
| 4628 |
|
| 4629 |
if (!IsAsciiHexDigit(chars[k + 1]) || |
| 4630 |
!IsAsciiHexDigit(chars[k + 2])) { |
| 4631 |
return Decode_BadUri; |
| 4632 |
} |
| 4633 |
|
| 4634 |
B = AsciiAlphanumericToNumber(chars[k + 1]) * 16 + |
| 4635 |
AsciiAlphanumericToNumber(chars[k + 2]); |
| 4636 |
if ((B & 0xC0) != 0x80) { |
| 4637 |
return Decode_BadUri; |
| 4638 |
} |
| 4639 |
|
| 4640 |
k += 2; |
| 4641 |
octets[j] = char(B); |
| 4642 |
} |
| 4643 |
|
| 4644 |
if (!appendRange(startAppend, start)) { |
| 4645 |
return Decode_Failure; |
| 4646 |
} |
| 4647 |
|
| 4648 |
char32_t v = JS::Utf8ToOneUcs4Char(octets, n); |
| 4649 |
MOZ_ASSERT(v >= 128); |
| 4650 |
if (v >= unicode::NonBMPMin) { |
| 4651 |
if (v > unicode::NonBMPMax) { |
| 4652 |
return Decode_BadUri; |
| 4653 |
} |
| 4654 |
|
| 4655 |
if (!sb.append(unicode::LeadSurrogate(v))) { |
| 4656 |
return Decode_Failure; |
| 4657 |
} |
| 4658 |
if (!sb.append(unicode::TrailSurrogate(v))) { |
| 4659 |
return Decode_Failure; |
| 4660 |
} |
| 4661 |
} else { |
| 4662 |
if (!sb.append(char16_t(v))) { |
| 4663 |
return Decode_Failure; |
| 4664 |
} |
| 4665 |
} |
| 4666 |
} |
| 4667 |
|
| 4668 |
startAppend = k + 1; |
| 4669 |
} |
| 4670 |
} |
| 4671 |
|
| 4672 |
if (startAppend > 0) { |
| 4673 |
if (!appendRange(startAppend, length)) { |
| 4674 |
return Decode_Failure; |
| 4675 |
} |
| 4676 |
} |
| 4677 |
|
| 4678 |
return Decode_Success; |
| 4679 |
} |
| 4680 |
|
| 4681 |
static bool Decode(JSContext* cx, Handle<JSLinearString*> str, |
| 4682 |
const bool* reservedSet, MutableHandleValue rval) { |
| 4683 |
size_t length = str->length(); |
| 4684 |
if (length == 0) { |
| 4685 |
rval.setString(cx->runtime()->emptyString); |
| 4686 |
return true; |
| 4687 |
} |
| 4688 |
|
| 4689 |
JSStringBuilder sb(cx); |
| 4690 |
|
| 4691 |
DecodeResult res; |
| 4692 |
if (str->hasLatin1Chars()) { |
| 4693 |
AutoCheckCannotGC nogc; |
| 4694 |
res = Decode(sb, str->latin1Chars(nogc), str->length(), reservedSet); |
| 4695 |
} else { |
| 4696 |
AutoCheckCannotGC nogc; |
| 4697 |
res = Decode(sb, str->twoByteChars(nogc), str->length(), reservedSet); |
| 4698 |
} |
| 4699 |
|
| 4700 |
if (res == Decode_Failure) { |
| 4701 |
return false; |
| 4702 |
} |
| 4703 |
|
| 4704 |
if (res == Decode_BadUri) { |
| 4705 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_URI); |
| 4706 |
return false; |
| 4707 |
} |
| 4708 |
|
| 4709 |
MOZ_ASSERT(res == Decode_Success); |
| 4710 |
return TransferBufferToString(sb, str, rval); |
| 4711 |
} |
| 4712 |
|
| 4713 |
static bool str_decodeURI(JSContext* cx, unsigned argc, Value* vp) { |
| 4714 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "decodeURI"); |
| 4715 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4716 |
Rooted<JSLinearString*> str(cx, ArgToLinearString(cx, args, 0)); |
| 4717 |
if (!str) { |
| 4718 |
return false; |
| 4719 |
} |
| 4720 |
|
| 4721 |
return Decode(cx, str, js_isUriReservedPlusPound, args.rval()); |
| 4722 |
} |
| 4723 |
|
| 4724 |
static bool str_decodeURI_Component(JSContext* cx, unsigned argc, Value* vp) { |
| 4725 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "decodeURIComponent"); |
| 4726 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4727 |
Rooted<JSLinearString*> str(cx, ArgToLinearString(cx, args, 0)); |
| 4728 |
if (!str) { |
| 4729 |
return false; |
| 4730 |
} |
| 4731 |
|
| 4732 |
return Decode(cx, str, nullptr, args.rval()); |
| 4733 |
} |
| 4734 |
|
| 4735 |
static bool str_encodeURI(JSContext* cx, unsigned argc, Value* vp) { |
| 4736 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "encodeURI"); |
| 4737 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4738 |
Rooted<JSLinearString*> str(cx, ArgToLinearString(cx, args, 0)); |
| 4739 |
if (!str) { |
| 4740 |
return false; |
| 4741 |
} |
| 4742 |
|
| 4743 |
return Encode(cx, str, js_isUriReservedPlusPound, args.rval()); |
| 4744 |
} |
| 4745 |
|
| 4746 |
static bool str_encodeURI_Component(JSContext* cx, unsigned argc, Value* vp) { |
| 4747 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "encodeURIComponent"); |
| 4748 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4749 |
Rooted<JSLinearString*> str(cx, ArgToLinearString(cx, args, 0)); |
| 4750 |
if (!str) { |
| 4751 |
return false; |
| 4752 |
} |
| 4753 |
|
| 4754 |
return Encode(cx, str, nullptr, args.rval()); |
| 4755 |
} |
| 4756 |
|
| 4757 |
JSString* js::EncodeURI(JSContext* cx, const char* chars, size_t length) { |
| 4758 |
JSStringBuilder sb(cx); |
| 4759 |
EncodeResult result = Encode(sb, reinterpret_cast<const Latin1Char*>(chars), |
| 4760 |
length, js_isUriReservedPlusPound); |
| 4761 |
if (result == EncodeResult::Encode_Failure) { |
| 4762 |
return nullptr; |
| 4763 |
} |
| 4764 |
if (result == EncodeResult::Encode_BadUri) { |
| 4765 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_URI); |
| 4766 |
return nullptr; |
| 4767 |
} |
| 4768 |
if (sb.empty()) { |
| 4769 |
return NewStringCopyN<CanGC>(cx, chars, length); |
| 4770 |
} |
| 4771 |
return sb.finishString(); |
| 4772 |
} |
| 4773 |
|
| 4774 |
static bool FlatStringMatchHelper(JSContext* cx, HandleString str, |
| 4775 |
HandleString pattern, bool* isFlat, |
| 4776 |
int32_t* match) { |
| 4777 |
Rooted<JSLinearString*> linearPattern(cx, pattern->ensureLinear(cx)); |
| 4778 |
if (!linearPattern) { |
| 4779 |
return false; |
| 4780 |
} |
| 4781 |
|
| 4782 |
static const size_t MAX_FLAT_PAT_LEN = 256; |
| 4783 |
if (linearPattern->length() > MAX_FLAT_PAT_LEN || |
| 4784 |
StringHasRegExpMetaChars(linearPattern)) { |
| 4785 |
*isFlat = false; |
| 4786 |
return true; |
| 4787 |
} |
| 4788 |
|
| 4789 |
*isFlat = true; |
| 4790 |
if (str->isRope()) { |
| 4791 |
if (!RopeMatch(cx, &str->asRope(), linearPattern, match)) { |
| 4792 |
return false; |
| 4793 |
} |
| 4794 |
} else { |
| 4795 |
*match = StringMatch(&str->asLinear(), linearPattern); |
| 4796 |
} |
| 4797 |
|
| 4798 |
return true; |
| 4799 |
} |
| 4800 |
|
| 4801 |
static bool BuildFlatMatchArray(JSContext* cx, HandleString str, |
| 4802 |
HandleString pattern, int32_t match, |
| 4803 |
MutableHandleValue rval) { |
| 4804 |
if (match < 0) { |
| 4805 |
rval.setNull(); |
| 4806 |
return true; |
| 4807 |
} |
| 4808 |
|
| 4809 |
// Get the shape for the match result object. |
| 4810 |
Rooted<SharedShape*> shape( |
| 4811 |
cx, cx->global()->regExpRealm().getOrCreateMatchResultShape(cx)); |
| 4812 |
if (!shape) { |
| 4813 |
return false; |
| 4814 |
} |
| 4815 |
|
| 4816 |
Rooted<ArrayObject*> arr(cx, |
| 4817 |
NewDenseFullyAllocatedArrayWithShape(cx, 1, shape)); |
| 4818 |
if (!arr) { |
| 4819 |
return false; |
| 4820 |
} |
| 4821 |
|
| 4822 |
// Store a Value for each pair. |
| 4823 |
arr->setDenseInitializedLength(1); |
| 4824 |
arr->initDenseElement(0, StringValue(pattern)); |
| 4825 |
|
| 4826 |
// Set the |index| property. |
| 4827 |
arr->initSlot(RegExpRealm::MatchResultObjectIndexSlot, Int32Value(match)); |
| 4828 |
|
| 4829 |
// Set the |input| property. |
| 4830 |
arr->initSlot(RegExpRealm::MatchResultObjectInputSlot, StringValue(str)); |
| 4831 |
|
| 4832 |
#ifdef DEBUG |
| 4833 |
RootedValue test(cx); |
| 4834 |
RootedId id(cx, NameToId(cx->names().index)); |
| 4835 |
if (!NativeGetProperty(cx, arr, id, &test)) { |
| 4836 |
return false; |
| 4837 |
} |
| 4838 |
MOZ_ASSERT(test == arr->getSlot(0)); |
| 4839 |
id = NameToId(cx->names().input); |
| 4840 |
if (!NativeGetProperty(cx, arr, id, &test)) { |
| 4841 |
return false; |
| 4842 |
} |
| 4843 |
MOZ_ASSERT(test == arr->getSlot(1)); |
| 4844 |
#endif |
| 4845 |
|
| 4846 |
rval.setObject(*arr); |
| 4847 |
return true; |
| 4848 |
} |
| 4849 |
|
| 4850 |
bool js::FlatStringMatch(JSContext* cx, unsigned argc, Value* vp) { |
| 4851 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4852 |
MOZ_ASSERT(args.length() == 2); |
| 4853 |
MOZ_ASSERT(args[0].isString()); |
| 4854 |
MOZ_ASSERT(args[1].isString()); |
| 4855 |
MOZ_ASSERT(cx->realm()->realmFuses.optimizeRegExpPrototypeFuse.intact()); |
| 4856 |
|
| 4857 |
RootedString str(cx, args[0].toString()); |
| 4858 |
RootedString pattern(cx, args[1].toString()); |
| 4859 |
|
| 4860 |
bool isFlat = false; |
| 4861 |
int32_t match = 0; |
| 4862 |
if (!FlatStringMatchHelper(cx, str, pattern, &isFlat, &match)) { |
| 4863 |
return false; |
| 4864 |
} |
| 4865 |
|
| 4866 |
if (!isFlat) { |
| 4867 |
args.rval().setUndefined(); |
| 4868 |
return true; |
| 4869 |
} |
| 4870 |
|
| 4871 |
return BuildFlatMatchArray(cx, str, pattern, match, args.rval()); |
| 4872 |
} |
| 4873 |
|
| 4874 |
bool js::FlatStringSearch(JSContext* cx, unsigned argc, Value* vp) { |
| 4875 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4876 |
MOZ_ASSERT(args.length() == 2); |
| 4877 |
MOZ_ASSERT(args[0].isString()); |
| 4878 |
MOZ_ASSERT(args[1].isString()); |
| 4879 |
MOZ_ASSERT(cx->realm()->realmFuses.optimizeRegExpPrototypeFuse.intact()); |
| 4880 |
|
| 4881 |
RootedString str(cx, args[0].toString()); |
| 4882 |
RootedString pattern(cx, args[1].toString()); |
| 4883 |
|
| 4884 |
bool isFlat = false; |
| 4885 |
int32_t match = 0; |
| 4886 |
if (!FlatStringMatchHelper(cx, str, pattern, &isFlat, &match)) { |
| 4887 |
return false; |
| 4888 |
} |
| 4889 |
|
| 4890 |
if (!isFlat) { |
| 4891 |
args.rval().setInt32(-2); |
| 4892 |
return true; |
| 4893 |
} |
| 4894 |
|
| 4895 |
args.rval().setInt32(match); |
| 4896 |
return true; |
| 4897 |
} |