Files
palemoon27/js/src/builtin/RegExp.cpp
T
roytam1 7adb8133f5 import changes from `dev' branch of rmottola/Arctic-Fox:
- missing bit of 989499 and some other files (23b0597ba6)
- Bug 1233666 - Remove hacks for getting frame pointer for x86/x64 gcc. r=glandium (bfe8f59916)
- Bug 1176266: In TimeStamp_posix.cpp, check for XP_LINUX instead of LINUX, and add missing #include, to allow strrchr usage. r=BenWa (56c725cffa)
- Bug 1167230 - Don't pack ProfileEntry on ARM. r=shu (89f880e0cb)
- Bug 1209779 - Ensure that all null elements are written when streaming profiler JSON; r=shu (2bae5addc6)
- missing bit of Bug 1141712 - Make LUL (55f1276545)
- Bug 1061800 - Add breakpad ids to profiler in Linux. r=BenWa (994fd1a941)
- Bug 829621 - Compute the breakpad-id for OS X. r=BenWa. (e129580174)
- missing of  Bug 938157 - Lightweight CFI/EXIDX (b355dc3140)
- Bug 1193838 - Allow ProfileGatherer to gather profiles from exiting processes. r=BenWa (5ab1a6a3c9)
- align some missing stuff (5ebecd2364)
- align some missing stuff (b8ff7aa361)
- Bug 1164315 - Update key fingerprint for bitbucket.org; r=me (c1a3fbd930)
- Bug 1178955 - Refactor config path selection; r=smacleod (89552bb0ac)
- Bug 1195445 - Update host key fingerprint for bugzilla.mozilla.org (3783541088)
- Bug 1218903 - Update bmo fingerprint. r=fubar, a=Tomcat (5b836fc585)
- Bug 1178955 - Print config path on failure; r=smacleod (f5499f3771)
- Bug 1185113 - Support setting more secure file permissions; r=smacleod (7dbf6b22fd)
- Bug 1184229 - Detect multiple version-control-tools repos in Mercurial config; r=smacleod (16c24072a9)
- Bug 978514 - mach mercurial-setup: Use mqext from the version-control-tools repo (1fa5765e8a)
- Bug 1178955 - Don't pass config paths to updater; r=smacleod (80fcb05121)
- Bug 1197527 - Don't unnecessarily attempt to create extensions directory in MercurialUpdater; r=gps (9b049c3ff8)
- Bug 1164812 - mach mercurial-setup: Always mark the v-c-t repo as needing update (bd631208bd)
- Bug 1197527 - Always clone version-control-tools in MercurialSetupWizard; r=gps (6990e8f589)
- Bug 1197527 - Consolidate obtaining hg path into mozversioncontrol.get_hg_path; r=gps (e0b029a8e9)
- Bug 1200458 - Skip permission check for .hgrc on Windows in hgsetup wizard. r=gps DONTBUILD (cc5b0d6daf)
- Bug 1168466 - Bump minimum Mercurial version; r=smacleod (7fde47cfbe)
- Bug 1185113 - Clarify language around Bugzilla credentials; r=smacleod (9166fdfbf9)
- Bug 1185112 - Don't prompt for Bugzilla username/password if cookies defined; r=smacleod (cd87c96823)
- Bug 1188931 - Fix hgsetup wizard. r=gps (68a6b46be4)
- Bug 1200461 - Prompt for Bugzilla API Key instead of password; r=smacleod (780fb5d85d)
- Bug 1228580 - ./mach mercurial-setup should use ~ to set up extension paths, not my literal home directory. r=gps (7a0c839880)
- Bug 1231192 - Mark Mercurial 3.5.2 as oldest non-legacy version; r=smacleod (8f69483333)
- Bug 1231192 - Bump some minimum Mercurial version; r=smacleod (916c56a852)
- Bug 1162093 - Add "push-to-try" from version-control-tools to the mercurial setup wizard prompt.;r=gps (d29c7cf63a)
- Bug 1168466 - Prompt to install bundleclone extension; r=smacleod (780ce90a08)
- Bug 1185557 - Print relevant config options; r=smacleod (2f3f7e0161)
- Bug 1231192 - Support clonebundles feature; r=smacleod (dcba1ccd34)
- Bug 1231192 - Offer to install hg wip; r=smacleod (c42ebce5c8)
- Bug 1231192 - Only install host fingerprints if not running secure Python+hg; r=smacleod (3154a2497b)
- Bug 1178955 - Error when semicolon comments are seen; r=smacleod (e1f7081bb6)
- Bug 1231989 - Prompt to install hgwatchman extension; r=ahal (0eddf0c1c8)
- Bug 1178955 - Print line number for parse errors; r=smacleod (5369468cf1)
- Bug 1185557 - Only prompt to install progress on Mercurial <3.5; r=smacleod (401f362265)
- Bug 1232747 - Check for ssl.SSLContext existence; r=dminor (d505b07c5c)
- Bug 1144629 - UnicodeDecodeError in ./mach mercurial-setup. r=gps, r=glandium (611d3ec83e)
- Bug 1216970 - Make the copying more obvious in ProfilerImpl::GetStacktrace. r=froydnj (085625e113)
- Bug 1190466 - tools/rb/find-leakers.pl re-written in Python r=mccr8 (4bfdcad13e)
- Bug 1116478 - Open web content handlers in the proper tab in e10s. r=billm (ff8e11f45e)
- Bug 1213437 - Less data copying when handling structured clones in MessageManager, r=baku (c4e2a13253)
- const-var (69d17f312d)
- Bug 1203090 - Ensure we always use '/' as the starting path separator for the DOM path of the Directorys initially returned by HTMLInputElement.getFilesAndDirectories. r=baku (1325bbc40c)
- Bug 1209975 - Stop using dom::Promise::MaybeRejectBrokenly() in GetDirectoryListingTask. r=baku (2106790950)
- Bug 1209924 - Implement a general filtering mechanism for Directory::GetFilesAndDirectories, and add filtering of sensitive files/directories. r=baku (27b4a26262)
- Force a repaint after DXGI device resets. (bug 1188019, r=bas) (09c999e6e5)
- Bug 1163911 - Make responsive images block the document load event while the load task is queued. r=jst (0ee0e3db79)
- Bug 1166138 - Make img srcset react to resize/viewport changes, r=jdm (91674519e6)
- Bug 1194893 - Pref for default file upload directory. r=smaug (ec6d33d983)
- bug 1116409: switch update server to sha2 cert; update in-tree pinning. r=rstrong,snorp,mfinkle,dkeeler (7c8f631f27)
- bug 1116409: fix cert pinning on backup cert for aus5.mozilla.org. r=typofix (3c690cbc6d)
- Bug 1167048 - Change default font for Thai script from serif to sans-serif. r=smontagu (15dc86c389)
- Bug 1205570 - fix up font prefs for x-math lang group. r=heycam (03f1820752)
- Bug 1071769: Use DrawTargetTiled on B2G. r=Bas (b80ce768f1)
- fix misspatch of 1149343 (541dd7aac8)
- Bug 1199766 - Disable ICE TCP SO gathering via user pref. r=bwc (80cdc9c662)
- Bug 1187472 - only log UDP and TCP candidate gathering failures. r=bwc (bc3dcb02d0)
- Bug 1190615 - Skip non-UDP STUN servers for UDP sockets. r=bwc (a2d1d914b5)
- Bug 1187775 - skip host and reflexive ICE candidates if relay-only. r=bwc (7e2cba1685)
- Bug 1185198 - use port 9 for TCP active candidates. r=bwc (0a89cb199d)
- Bug 1177921 - Fix typo in STUN server name. r=drno (1ad43ced6b)
- Bug 1178349 - Enable ice_unittests on desktop linux on CI. r=bwc (ce5ece8264)
- Bug 1189041 - Add option to only gather addresses for default route. r=bwc (3651f2ff06)
- Bug 1189040: add a whitelist for network interfaces to use with ICE/webrtc r=ekr (6f693af72c)
- Bug 1189198 - don't start STUN transactions with a protocol mis-match. r=mtseng (a3b410e2a8)
- Bug 1208096 - Handle various failure cases for TURN gathering better. r=drno (1d8e173448)
- Bug 1211389 - Make absolutely sure the relay->srflx pointer doesn't dangle. r=drno (d59b0bf08d)
- Bug 1215616: use base address for server rflx ICE candidates r=bwc (89d07331ac)
- Bug 1207451 - removed framing from multi_tcp API. r=bwc (317f40f490)
- Bug 1186590 - Part 1 - Enable interface prioritizer on all platforms. r=drno (036a69fdb3)
- Bug 1194019 - New defaults for gather tests. r=bwc (8343ceab56)
- Bug 1144933: Only check that remote candidate is loopback in TestLoopbackOnlySortOf. r=drno (1f53d824e4)
- Bug 1186590 - Part 2 - Move hard-coded interface priority list into nrinterfaceprioritizer, and simplify some functions. r=drno (9f20fad21b)
- Bug 1152137 - Part 1: Test case. r=ekr (6b50f06d90)
- Bug 1152137 - Part 2: Remove attributes that could not be initted properly instead of just freeing them. r=ekr (ccdf81294a)
- Bug 1200763 - Remove hard-coded STUN IP address from ice_unittest, and do a DNS lookup instead. r=drno (ae54a83363)
- Bug 1208176 - Part 1: Add a couple of interface names. r=drno (b7ead0b476)
- Bug 1208176 - Part 2: Add a one-sided trickle test case to ice_unittest. r=drno (ad6afedb1c)
- Bug 1037618 - Relax candidate verification for TCP. r=bwc (0cad14c89e)
- Bug 1208176 - Part 3: Be forgiving when we see prflx instead of host candidates in ice_unittest. r=drno (50bdec2ba3)
- Bug 1035428: Re-register writeable callback after partially servicing the send queue. r=drno (2fdb7880fa)
- Bug 1135753 - Mark some overridden virtual functions in WebRTC as MOZ_OVERRIDE; r=mt (97f451c97d)
- Bug 950660: Part 4: Bridge TCPSocketChild to nr_socket r=bwc,jdm (654587b321)
- Bug 971357: Log STUN responses at INFO instead of DEBUG. r=ekr (81b500df17)
- Bug 1006809 - update triggered check behavior to RFC 5245. r+bwc r=mjf (31b718b5e5)
- Bug 1208278 - improved STUN request timeout handling. r=bwc (cf470fb12f)
- Bug 1142964 - Fix ICE tiebreaker on Windows. r=bwc (0d2fd78252)
- Bug 1219557 - don't pair candidates from different reserved networks. r=mt r=bwc (24d3e5106c)
- Bug 1220441 - Improve gather trickle ice unit tests. r=bwc r=mjf (96f76c6c8c)
- Bug 1205421 - fix DNS resolution of STUN server in ice_unittest. r=bwc (5d5b153358)
- Bug 1206465 - removed ice_ctx from TestStunTcpServer. r=bwc (9a0df03894)
- ug 1008792 - Check for valid pointer before using. r=bwc (7660fd0a71)
- Bug 1233101 - Use MOZ_LIKELY in js_new etc to help branch prediction; r=terrence (31fb244734)
- Bug 1225565 - Fix module import cycle detection r=shu (370dc26ee8)
- Bug 1225558 - Improve module error messages r=shu (83b6038bb3)
- Bug 1225561 - Don't allow a module to export non-existent local bindings r=shu (41f065891a)
- Bug 1233124 - Remove mis-named duplicate typedefs for rooted import and export entries r=terrence (17a60bdb39)
- Bug 1208464 - Implement proposed ES7 functions Object.values and Object.entries. r=evilpie (615193d0fb)
- Bug 1226549 - added assert check for matches pointer in for prevent null dereference. r=hv1989 (d321ad0385)
- Bug 1232113 - "Make the format specifiers in JS_snprintf() invocations more portable". r=jcoppeard (7c58b79a53)
- Bug 1232446 - Re-enable method calls in SelfHosted code using new anti-content checks. (r=till) (ba7dc22ff8)
- Bug 1232159 - Stop using pseudo-Uint32Array in SelfHosted code. (r=till) (c325f8ff58)
- Bug 1226235 - Print file and line info for failing assert in self-hosted code. r=efaust (4a8d54d38b)
- fix misspatch (fca2efc1f1)
- Bug 1186003 - Switch automated builds to Gtk+3. r=mshal (658ad843b7)
- Bug 1181342 - tooltool manifests and build-clang config for clang 3.6 r=rail (6264b4df68)
- Bug 1181342 - Follow up to use the unpack feature of tooltool instead of setup.sh r=glandium (96bb3b2062)
- Bug 1181255 - Mozconfigs for tsan builds. r=glandium (19250f4cc1)
- Bug 1181255 - Get tsan builds on gtk3. r=glandium (e5ffd1c02f)
- Bug 1187664 - Create a fontconfig cache so that Firefox doesn't have to do it itself when run on build automation. r=mshal (8ce567bd4c)
- Bug 1188780 - Include debug symbols in gtk3 tooltool package. r=mshal (a5b573aa58)
- Bug 1188780: remove setup.sh invocations, as they fail outside the mock environment; r=glandium a=RyanVM (058e306cac)
- Bug 1178513 - Fix non-unified bustage. r=wchen (543d1e5497)
- Bug 1162789 - Add a comment explaining why mForm is not set to null during unlink (eaa2a82048)
- Bug 1189655 - Define MOZ_HAVE_CXX11_CONSTEXPR on VS2015 or later. r=Waldo (2d134e3b41)
- Bug 1231758 - Fix bogus assertion in BCE for Annex B function assignment. (r=jorendorff) (701b2530b9)
- Bug 1233100 - Ensure that derived constructor bad return value errors are thrown before leaving the containing block. (r=shu) (52f5bcf0a5)
- Bug 1232022, 1232449 - Address forgotten review nits and fix bogus error message. (rs=Waldo) (dfd9d5e388)
- Bug 1233121 - Refactor ObjectBox tracing r=terrence (876a140535)
- Bug 1231647 - Check for duplicate exported let and const in modules r=shu (99f53ad443)
2023-06-22 10:38:22 +08:00

1057 lines
33 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "builtin/RegExp.h"
#include "mozilla/TypeTraits.h"
#include "jscntxt.h"
#include "irregexp/RegExpParser.h"
#include "jit/InlinableNatives.h"
#include "vm/RegExpStatics.h"
#include "vm/StringBuffer.h"
#include "vm/Unicode.h"
#include "jsobjinlines.h"
#include "vm/NativeObject-inl.h"
using namespace js;
using namespace js::unicode;
using mozilla::ArrayLength;
using mozilla::Maybe;
bool
js::CreateRegExpMatchResult(JSContext* cx, HandleString input, const MatchPairs& matches,
MutableHandleValue rval)
{
MOZ_ASSERT(input);
/*
* Create the (slow) result array for a match.
*
* Array contents:
* 0: matched string
* 1..pairCount-1: paren matches
* input: input string
* index: start index for the match
*/
/* Get the templateObject that defines the shape and type of the output object */
JSObject* templateObject = cx->compartment()->regExps.getOrCreateMatchResultTemplateObject(cx);
if (!templateObject)
return false;
size_t numPairs = matches.length();
MOZ_ASSERT(numPairs > 0);
RootedArrayObject arr(cx, NewDenseFullyAllocatedArrayWithTemplate(cx, numPairs, templateObject));
if (!arr)
return false;
/* Store a Value for each pair. */
for (size_t i = 0; i < numPairs; i++) {
const MatchPair& pair = matches[i];
if (pair.isUndefined()) {
MOZ_ASSERT(i != 0); /* Since we had a match, first pair must be present. */
arr->setDenseInitializedLength(i + 1);
arr->initDenseElement(i, UndefinedValue());
} else {
JSLinearString* str = NewDependentString(cx, input, pair.start, pair.length());
if (!str)
return false;
arr->setDenseInitializedLength(i + 1);
arr->initDenseElement(i, StringValue(str));
}
}
/* Set the |index| property. (TemplateObject positions it in slot 0) */
arr->setSlot(0, Int32Value(matches[0].start));
/* Set the |input| property. (TemplateObject positions it in slot 1) */
arr->setSlot(1, StringValue(input));
#ifdef DEBUG
RootedValue test(cx);
RootedId id(cx, NameToId(cx->names().index));
if (!NativeGetProperty(cx, arr, id, &test))
return false;
MOZ_ASSERT(test == arr->getSlot(0));
id = NameToId(cx->names().input);
if (!NativeGetProperty(cx, arr, id, &test))
return false;
MOZ_ASSERT(test == arr->getSlot(1));
#endif
rval.setObject(*arr);
return true;
}
static RegExpRunStatus
ExecuteRegExpImpl(JSContext* cx, RegExpStatics* res, RegExpShared& re, HandleLinearString input,
size_t searchIndex, MatchPairs* matches)
{
RegExpRunStatus status = re.execute(cx, input, searchIndex, matches);
if (status == RegExpRunStatus_Success && res) {
if (matches) {
if (!res->updateFromMatchPairs(cx, input, *matches))
return RegExpRunStatus_Error;
} else {
res->updateLazily(cx, input, &re, searchIndex);
}
}
return status;
}
/* Legacy ExecuteRegExp behavior is baked into the JSAPI. */
bool
js::ExecuteRegExpLegacy(JSContext* cx, RegExpStatics* res, RegExpObject& reobj,
HandleLinearString input, size_t* lastIndex, bool test,
MutableHandleValue rval)
{
RegExpGuard shared(cx);
if (!reobj.getShared(cx, &shared))
return false;
ScopedMatchPairs matches(&cx->tempLifoAlloc());
RegExpRunStatus status = ExecuteRegExpImpl(cx, res, *shared, input, *lastIndex, &matches);
if (status == RegExpRunStatus_Error)
return false;
if (status == RegExpRunStatus_Success_NotFound) {
/* ExecuteRegExp() previously returned an array or null. */
rval.setNull();
return true;
}
*lastIndex = matches[0].limit;
if (test) {
/* Forbid an array, as an optimization. */
rval.setBoolean(true);
return true;
}
return CreateRegExpMatchResult(cx, input, matches, rval);
}
/*
* ES6 21.2.3.2.2. Because this function only ever returns |obj| in the spec,
* provided by the user, we omit it and just return the usual success/failure.
*/
static bool
RegExpInitialize(JSContext* cx, Handle<RegExpObject*> obj, HandleValue patternValue,
HandleValue flagsValue, RegExpStaticsUse staticsUse)
{
RootedAtom pattern(cx);
if (patternValue.isUndefined()) {
/* Step 1. */
pattern = cx->runtime()->emptyString;
} else {
/* Steps 2-3. */
pattern = ToAtom<CanGC>(cx, patternValue);
if (!pattern)
return false;
}
/* Step 4. */
RegExpFlag flags = RegExpFlag(0);
if (!flagsValue.isUndefined()) {
/* Steps 5-6. */
RootedString flagStr(cx, ToString<CanGC>(cx, flagsValue));
if (!flagStr)
return false;
/* Step 7. */
if (!ParseRegExpFlags(cx, flagStr, &flags))
return false;
}
/* Steps 9-10. */
CompileOptions options(cx);
frontend::TokenStream dummyTokenStream(cx, options, nullptr, 0, nullptr);
if (!irregexp::ParsePatternSyntax(dummyTokenStream, cx->tempLifoAlloc(), pattern,
flags & UnicodeFlag))
{
return false;
}
if (staticsUse == UseRegExpStatics) {
RegExpStatics* res = cx->global()->getRegExpStatics(cx);
if (!res)
return false;
flags = RegExpFlag(flags | res->getFlags());
}
/* Steps 11-15. */
if (!RegExpObject::initFromAtom(cx, obj, pattern, flags))
return false;
/* Step 16. */
return true;
}
MOZ_ALWAYS_INLINE bool
IsRegExpObject(HandleValue v)
{
return v.isObject() && v.toObject().is<RegExpObject>();
}
/* ES6 draft rc3 7.2.8. */
bool
js::IsRegExp(JSContext* cx, HandleValue value, bool* result)
{
/* Step 1. */
if (!value.isObject()) {
*result = false;
return true;
}
RootedObject obj(cx, &value.toObject());
/* Steps 2-3. */
RootedValue isRegExp(cx);
RootedId matchId(cx, SYMBOL_TO_JSID(cx->wellKnownSymbols().match));
if (!GetProperty(cx, obj, obj, matchId, &isRegExp))
return false;
/* Step 4. */
if (!isRegExp.isUndefined()) {
*result = ToBoolean(isRegExp);
return true;
}
/* Steps 5-6. */
ESClassValue cls;
if (!GetClassOfValue(cx, value, &cls))
return false;
*result = cls == ESClass_RegExp;
return true;
}
/* ES6 B.2.5.1. */
MOZ_ALWAYS_INLINE bool
regexp_compile_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> regexp(cx, &args.thisv().toObject().as<RegExpObject>());
// Step 3.
RootedValue patternValue(cx, args.get(0));
ESClassValue cls;
if (!GetClassOfValue(cx, patternValue, &cls))
return false;
if (cls == ESClass_RegExp) {
// Step 3a.
if (args.hasDefined(1)) {
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_NEWREGEXP_FLAGGED);
return false;
}
// Beware! |patternObj| might be a proxy into another compartment, so
// don't assume |patternObj.is<RegExpObject>()|. For the same reason,
// don't reuse the RegExpShared below.
RootedObject patternObj(cx, &patternValue.toObject());
RootedAtom sourceAtom(cx);
RegExpFlag flags;
{
// Step 3b.
RegExpGuard g(cx);
if (!RegExpToShared(cx, patternObj, &g))
return false;
sourceAtom = g->getSource();
flags = g->getFlags();
}
// Step 5.
if (!RegExpObject::initFromAtom(cx, regexp, sourceAtom, flags))
return false;
args.rval().setObject(*regexp);
return true;
}
// Step 4.
RootedValue P(cx, patternValue);
RootedValue F(cx, args.get(1));
// Step 5.
if (!RegExpInitialize(cx, regexp, P, F, UseRegExpStatics))
return false;
args.rval().setObject(*regexp);
return true;
}
static bool
regexp_compile(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
/* Steps 1-2. */
return CallNonGenericMethod<IsRegExpObject, regexp_compile_impl>(cx, args);
}
/* ES6 21.2.3.1. */
bool
js::regexp_construct(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1-2.
bool patternIsRegExp;
if (!IsRegExp(cx, args.get(0), &patternIsRegExp))
return false;
// We can delay step 3 and step 4a until later, during
// GetPrototypeFromCallableConstructor calls. Accessing the new.target
// and the callee from the stack is unobservable.
if (!args.isConstructing()) {
// Step 4b.
if (patternIsRegExp && !args.hasDefined(1)) {
RootedObject patternObj(cx, &args[0].toObject());
// Steps 4b.i-ii.
RootedValue patternConstructor(cx);
if (!GetProperty(cx, patternObj, patternObj, cx->names().constructor, &patternConstructor))
return false;
// Step 4b.iii.
if (patternConstructor.isObject() && patternConstructor.toObject() == args.callee()) {
args.rval().set(args[0]);
return true;
}
}
}
RootedValue patternValue(cx, args.get(0));
// Step 5.
ESClassValue cls;
if (!GetClassOfValue(cx, patternValue, &cls))
return false;
if (cls == ESClass_RegExp) {
// Beware! |patternObj| might be a proxy into another compartment, so
// don't assume |patternObj.is<RegExpObject>()|. For the same reason,
// don't reuse the RegExpShared below.
RootedObject patternObj(cx, &patternValue.toObject());
// Step 5
RootedAtom sourceAtom(cx);
RegExpFlag flags;
{
// Step 5.a.
RegExpGuard g(cx);
if (!RegExpToShared(cx, patternObj, &g))
return false;
sourceAtom = g->getSource();
if (!args.hasDefined(1)) {
// Step 5b.
flags = g->getFlags();
}
}
// Steps 8-9.
RootedObject proto(cx);
if (!GetPrototypeFromCallableConstructor(cx, args, &proto))
return false;
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, proto));
if (!regexp)
return false;
// Step 10.
if (args.hasDefined(1)) {
// Step 5c / 21.2.3.2.2 RegExpInitialize step 5.
flags = RegExpFlag(0);
RootedString flagStr(cx, ToString<CanGC>(cx, args[1]));
if (!flagStr)
return false;
if (!ParseRegExpFlags(cx, flagStr, &flags))
return false;
}
if (!RegExpObject::initFromAtom(cx, regexp, sourceAtom, flags))
return false;
args.rval().setObject(*regexp);
return true;
}
RootedValue P(cx);
RootedValue F(cx);
// Step 6.
if (patternIsRegExp) {
RootedObject patternObj(cx, &patternValue.toObject());
// Steps 6a-b.
if (!GetProperty(cx, patternObj, patternObj, cx->names().source, &P))
return false;
// Steps 6c-d.
F = args.get(1);
if (F.isUndefined()) {
if (!GetProperty(cx, patternObj, patternObj, cx->names().flags, &F))
return false;
}
} else {
// Steps 7a-b.
P = patternValue;
F = args.get(1);
}
// Steps 8-9.
RootedObject proto(cx);
if (!GetPrototypeFromCallableConstructor(cx, args, &proto))
return false;
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, proto));
if (!regexp)
return false;
// Step 10.
if (!RegExpInitialize(cx, regexp, P, F, UseRegExpStatics))
return false;
args.rval().setObject(*regexp);
return true;
}
bool
js::regexp_construct_no_statics(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1 || args.length() == 2);
MOZ_ASSERT(args[0].isString());
MOZ_ASSERT_IF(args.length() == 2, args[1].isString());
MOZ_ASSERT(!args.isConstructing());
/* Steps 1-6 are not required since pattern is always string. */
/* Steps 7-10. */
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx));
if (!regexp)
return false;
if (!RegExpInitialize(cx, regexp, args[0], args.get(1), DontUseRegExpStatics))
return false;
args.rval().setObject(*regexp);
return true;
}
/* ES6 draft rev32 21.2.5.4. */
MOZ_ALWAYS_INLINE bool
regexp_global_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> reObj(cx, &args.thisv().toObject().as<RegExpObject>());
/* Steps 4-6. */
args.rval().setBoolean(reObj->global());
return true;
}
static bool
regexp_global(JSContext* cx, unsigned argc, JS::Value* vp)
{
/* Steps 1-3. */
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsRegExpObject, regexp_global_impl>(cx, args);
}
/* ES6 draft rev32 21.2.5.5. */
MOZ_ALWAYS_INLINE bool
regexp_ignoreCase_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> reObj(cx, &args.thisv().toObject().as<RegExpObject>());
/* Steps 4-6. */
args.rval().setBoolean(reObj->ignoreCase());
return true;
}
static bool
regexp_ignoreCase(JSContext* cx, unsigned argc, JS::Value* vp)
{
/* Steps 1-3. */
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsRegExpObject, regexp_ignoreCase_impl>(cx, args);
}
/* ES6 draft rev32 21.2.5.7. */
MOZ_ALWAYS_INLINE bool
regexp_multiline_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> reObj(cx, &args.thisv().toObject().as<RegExpObject>());
/* Steps 4-6. */
args.rval().setBoolean(reObj->multiline());
return true;
}
static bool
regexp_multiline(JSContext* cx, unsigned argc, JS::Value* vp)
{
/* Steps 1-3. */
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsRegExpObject, regexp_multiline_impl>(cx, args);
}
/* ES6 draft rev32 21.2.5.10. */
MOZ_ALWAYS_INLINE bool
regexp_source_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> reObj(cx, &args.thisv().toObject().as<RegExpObject>());
/* Step 5. */
RootedAtom src(cx, reObj->getSource());
if (!src)
return false;
/* Step 7. */
RootedString str(cx, EscapeRegExpPattern(cx, src));
if (!str)
return false;
args.rval().setString(str);
return true;
}
static bool
regexp_source(JSContext* cx, unsigned argc, JS::Value* vp)
{
/* Steps 1-4. */
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsRegExpObject, regexp_source_impl>(cx, args);
}
/* ES6 draft rev32 21.2.5.12. */
MOZ_ALWAYS_INLINE bool
regexp_sticky_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> reObj(cx, &args.thisv().toObject().as<RegExpObject>());
/* Steps 4-6. */
args.rval().setBoolean(reObj->sticky());
return true;
}
static bool
regexp_sticky(JSContext* cx, unsigned argc, JS::Value* vp)
{
/* Steps 1-3. */
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsRegExpObject, regexp_sticky_impl>(cx, args);
}
/* ES6 21.2.5.15. */
MOZ_ALWAYS_INLINE bool
regexp_unicode_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
/* Steps 4-6. */
args.rval().setBoolean(args.thisv().toObject().as<RegExpObject>().unicode());
return true;
}
static bool
regexp_unicode(JSContext* cx, unsigned argc, JS::Value* vp)
{
/* Steps 1-3. */
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsRegExpObject, regexp_unicode_impl>(cx, args);
}
const JSPropertySpec js::regexp_properties[] = {
JS_SELF_HOSTED_GET("flags", "RegExpFlagsGetter", 0),
JS_PSG("global", regexp_global, 0),
JS_PSG("ignoreCase", regexp_ignoreCase, 0),
JS_PSG("multiline", regexp_multiline, 0),
JS_PSG("source", regexp_source, 0),
JS_PSG("sticky", regexp_sticky, 0),
JS_PSG("unicode", regexp_unicode, 0),
JS_PS_END
};
const JSFunctionSpec js::regexp_methods[] = {
#if JS_HAS_TOSOURCE
JS_SELF_HOSTED_FN(js_toSource_str, "RegExpToString", 0, 0),
#endif
JS_SELF_HOSTED_FN(js_toString_str, "RegExpToString", 0, 0),
JS_FN("compile", regexp_compile, 2,0),
JS_INLINABLE_FN("exec", regexp_exec, 1,0, RegExpExec),
JS_INLINABLE_FN("test", regexp_test, 1,0, RegExpTest),
JS_FS_END
};
#define STATIC_PAREN_GETTER_CODE(parenNum) \
if (!res->createParen(cx, parenNum, args.rval())) \
return false; \
if (args.rval().isUndefined()) \
args.rval().setString(cx->runtime()->emptyString); \
return true
/*
* RegExp static properties.
*
* RegExp class static properties and their Perl counterparts:
*
* RegExp.input $_
* RegExp.multiline $*
* RegExp.lastMatch $&
* RegExp.lastParen $+
* RegExp.leftContext $`
* RegExp.rightContext $'
*/
#define DEFINE_STATIC_GETTER(name, code) \
static bool \
name(JSContext* cx, unsigned argc, Value* vp) \
{ \
CallArgs args = CallArgsFromVp(argc, vp); \
RegExpStatics* res = cx->global()->getRegExpStatics(cx); \
if (!res) \
return false; \
code; \
}
DEFINE_STATIC_GETTER(static_input_getter, return res->createPendingInput(cx, args.rval()))
DEFINE_STATIC_GETTER(static_lastMatch_getter, return res->createLastMatch(cx, args.rval()))
DEFINE_STATIC_GETTER(static_lastParen_getter, return res->createLastParen(cx, args.rval()))
DEFINE_STATIC_GETTER(static_leftContext_getter, return res->createLeftContext(cx, args.rval()))
DEFINE_STATIC_GETTER(static_rightContext_getter, return res->createRightContext(cx, args.rval()))
DEFINE_STATIC_GETTER(static_paren1_getter, STATIC_PAREN_GETTER_CODE(1))
DEFINE_STATIC_GETTER(static_paren2_getter, STATIC_PAREN_GETTER_CODE(2))
DEFINE_STATIC_GETTER(static_paren3_getter, STATIC_PAREN_GETTER_CODE(3))
DEFINE_STATIC_GETTER(static_paren4_getter, STATIC_PAREN_GETTER_CODE(4))
DEFINE_STATIC_GETTER(static_paren5_getter, STATIC_PAREN_GETTER_CODE(5))
DEFINE_STATIC_GETTER(static_paren6_getter, STATIC_PAREN_GETTER_CODE(6))
DEFINE_STATIC_GETTER(static_paren7_getter, STATIC_PAREN_GETTER_CODE(7))
DEFINE_STATIC_GETTER(static_paren8_getter, STATIC_PAREN_GETTER_CODE(8))
DEFINE_STATIC_GETTER(static_paren9_getter, STATIC_PAREN_GETTER_CODE(9))
#define DEFINE_STATIC_SETTER(name, code) \
static bool \
name(JSContext* cx, unsigned argc, Value* vp) \
{ \
RegExpStatics* res = cx->global()->getRegExpStatics(cx); \
if (!res) \
return false; \
code; \
return true; \
}
static bool
static_input_setter(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RegExpStatics* res = cx->global()->getRegExpStatics(cx);
if (!res)
return false;
RootedString str(cx, ToString<CanGC>(cx, args.get(0)));
if (!str)
return false;
res->setPendingInput(str);
args.rval().setString(str);
return true;
}
static bool
WarnOnceAboutRegExpMultiline(JSContext* cx)
{
if (!cx->compartment()->warnedAboutRegExpMultiline) {
if (!JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING, GetErrorMessage, nullptr,
JSMSG_DEPRECATED_REGEXP_MULTILINE))
{
return false;
}
cx->compartment()->warnedAboutRegExpMultiline = true;
}
return true;
}
static bool
static_multiline_getter(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RegExpStatics* res = cx->global()->getRegExpStatics(cx);
if (!res)
return false;
if (!WarnOnceAboutRegExpMultiline(cx))
return false;
args.rval().setBoolean(res->multiline());
return true;
}
static bool
static_multiline_setter(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RegExpStatics* res = cx->global()->getRegExpStatics(cx);
if (!res)
return false;
if (!WarnOnceAboutRegExpMultiline(cx))
return false;
bool b = ToBoolean(args.get(0));
res->setMultiline(cx, b);
args.rval().setBoolean(b);
return true;
}
const JSPropertySpec js::regexp_static_props[] = {
JS_PSGS("input", static_input_getter, static_input_setter,
JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSGS("multiline", static_multiline_getter, static_multiline_setter,
JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("lastMatch", static_lastMatch_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("lastParen", static_lastParen_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("leftContext", static_leftContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("rightContext", static_rightContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$1", static_paren1_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$2", static_paren2_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$3", static_paren3_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$4", static_paren4_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$5", static_paren5_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$6", static_paren6_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$7", static_paren7_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$8", static_paren8_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$9", static_paren9_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSGS("$_", static_input_getter, static_input_setter, JSPROP_PERMANENT),
JS_PSGS("$*", static_multiline_getter, static_multiline_setter, JSPROP_PERMANENT),
JS_PSG("$&", static_lastMatch_getter, JSPROP_PERMANENT),
JS_PSG("$+", static_lastParen_getter, JSPROP_PERMANENT),
JS_PSG("$`", static_leftContext_getter, JSPROP_PERMANENT),
JS_PSG("$'", static_rightContext_getter, JSPROP_PERMANENT),
JS_PS_END
};
JSObject*
js::CreateRegExpPrototype(JSContext* cx, JSProtoKey key)
{
MOZ_ASSERT(key == JSProto_RegExp);
Rooted<RegExpObject*> proto(cx, cx->global()->createBlankPrototype<RegExpObject>(cx));
if (!proto)
return nullptr;
proto->NativeObject::setPrivate(nullptr);
RootedAtom source(cx, cx->names().empty);
if (!RegExpObject::initFromAtom(cx, proto, source, RegExpFlag(0)))
return nullptr;
return proto;
}
static bool
ReportLastIndexNonwritable(JSContext* cx)
{
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_READ_ONLY, "\"lastIndex\"");
return false;
}
static bool
SetLastIndex(JSContext* cx, Handle<RegExpObject*> reobj, double lastIndex)
{
if (!reobj->lookup(cx, cx->names().lastIndex)->writable())
return ReportLastIndexNonwritable(cx);
reobj->setLastIndex(lastIndex);
return true;
}
template <typename CharT>
static bool
IsTrailSurrogateWithLeadSurrogateImpl(JSContext* cx, HandleLinearString input, size_t index)
{
JS::AutoCheckCannotGC nogc;
MOZ_ASSERT(index > 0 && index < input->length());
const CharT* inputChars = input->chars<CharT>(nogc);
return unicode::IsTrailSurrogate(inputChars[index]) &&
unicode::IsLeadSurrogate(inputChars[index - 1]);
}
static bool
IsTrailSurrogateWithLeadSurrogate(JSContext* cx, HandleLinearString input, int32_t index)
{
if (index <= 0 || size_t(index) >= input->length())
return false;
return input->hasLatin1Chars()
? IsTrailSurrogateWithLeadSurrogateImpl<Latin1Char>(cx, input, index)
: IsTrailSurrogateWithLeadSurrogateImpl<char16_t>(cx, input, index);
}
/* ES6 final draft 21.2.5.2.2. */
RegExpRunStatus
js::ExecuteRegExp(JSContext* cx, HandleObject regexp, HandleString string,
MatchPairs* matches, RegExpStaticsUpdate staticsUpdate)
{
/*
* WARNING: Despite the presence of spec step comment numbers, this
* algorithm isn't consistent with any ES6 version, draft or
* otherwise. YOU HAVE BEEN WARNED.
*/
/* Steps 1-2 performed by the caller. */
Rooted<RegExpObject*> reobj(cx, &regexp->as<RegExpObject>());
RegExpGuard re(cx);
if (!reobj->getShared(cx, &re))
return RegExpRunStatus_Error;
RegExpStatics* res;
if (staticsUpdate == UpdateRegExpStatics) {
res = cx->global()->getRegExpStatics(cx);
if (!res)
return RegExpRunStatus_Error;
} else {
res = nullptr;
}
RootedLinearString input(cx, string->ensureLinear(cx));
if (!input)
return RegExpRunStatus_Error;
/* Step 3. */
size_t length = input->length();
/* Steps 4-5. */
RootedValue lastIndex(cx, reobj->getLastIndex());
int searchIndex;
if (lastIndex.isInt32()) {
/* Aggressively avoid doubles. */
searchIndex = lastIndex.toInt32();
} else {
double d;
if (!ToInteger(cx, lastIndex, &d))
return RegExpRunStatus_Error;
/* Inlined steps 6-10, 15.a with doubles to detect failure case. */
if (reobj->needUpdateLastIndex() && (d < 0 || d > length)) {
/* Steps 15.a.i-ii. */
if (!SetLastIndex(cx, reobj, 0))
return RegExpRunStatus_Error;
/* Step 15.a.iii. */
return RegExpRunStatus_Success_NotFound;
}
searchIndex = int(d);
}
/*
* Steps 6-10.
*
* Also make sure that we have a MatchPairs for regexps which update their
* last index, as we won't compute the last index otherwise.
*/
Maybe<ScopedMatchPairs> alternateMatches;
if (!reobj->needUpdateLastIndex()) {
searchIndex = 0;
} else if (!matches) {
alternateMatches.emplace(&cx->tempLifoAlloc());
matches = &alternateMatches.ref();
}
/* Step 15.a. */
if (searchIndex < 0 || size_t(searchIndex) > length) {
/* Steps 15.a.i-ii. */
if (!SetLastIndex(cx, reobj, 0))
return RegExpRunStatus_Error;
/* Step 15.a.iii. */
return RegExpRunStatus_Success_NotFound;
}
/* Steps 12-13. */
if (reobj->unicode()) {
/*
* ES6 21.2.2.2 step 2.
* Let listIndex be the index into Input of the character that was
* obtained from element index of str.
*
* In the spec, pattern match is performed with decoded Unicode code
* points, but our implementation performs it with UTF-16 encoded
* string. In step 2, we should decrement searchIndex (index) if it
* points the trail surrogate that has corresponding lead surrogate.
*
* var r = /\uD83D\uDC38/ug;
* r.lastIndex = 1;
* var str = "\uD83D\uDC38";
* var result = r.exec(str); // pattern match starts from index 0
* print(result.index); // prints 0
*
* Note: this doesn't match the current spec text and result in
* different values for `result.index` under certain conditions.
* However, the spec will change to match our implementation's
* behavior. See https://github.com/tc39/ecma262/issues/128.
*/
if (IsTrailSurrogateWithLeadSurrogate(cx, input, searchIndex))
searchIndex--;
}
/* Step 14-29. */
RegExpRunStatus status = ExecuteRegExpImpl(cx, res, *re, input, searchIndex, matches);
if (status == RegExpRunStatus_Error)
return RegExpRunStatus_Error;
if (status == RegExpRunStatus_Success_NotFound) {
/* Steps 15.a.i-ii. */
if (!SetLastIndex(cx, reobj, 0))
return RegExpRunStatus_Error;
} else if (reobj->needUpdateLastIndex()) {
/* Steps 18.a-b. */
MOZ_ASSERT(matches && !matches->empty());
if (!SetLastIndex(cx, reobj, (*matches)[0].limit))
return RegExpRunStatus_Error;
}
return status;
}
/* ES5 15.10.6.2 (and 15.10.6.3, which calls 15.10.6.2). */
static RegExpRunStatus
ExecuteRegExp(JSContext* cx, const CallArgs& args, MatchPairs* matches)
{
/* Step 1 (a) was performed by CallNonGenericMethod. */
RootedObject regexp(cx, &args.thisv().toObject());
/* Step 2. */
RootedString string(cx, ToString<CanGC>(cx, args.get(0)));
if (!string)
return RegExpRunStatus_Error;
return ExecuteRegExp(cx, regexp, string, matches, UpdateRegExpStatics);
}
/* ES5 15.10.6.2. */
static bool
regexp_exec_impl(JSContext* cx, HandleObject regexp, HandleString string,
RegExpStaticsUpdate staticsUpdate, MutableHandleValue rval)
{
/* Execute regular expression and gather matches. */
ScopedMatchPairs matches(&cx->tempLifoAlloc());
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, &matches, staticsUpdate);
if (status == RegExpRunStatus_Error)
return false;
if (status == RegExpRunStatus_Success_NotFound) {
rval.setNull();
return true;
}
return CreateRegExpMatchResult(cx, string, matches, rval);
}
static bool
regexp_exec_impl(JSContext* cx, const CallArgs& args)
{
RootedObject regexp(cx, &args.thisv().toObject());
RootedString string(cx, ToString<CanGC>(cx, args.get(0)));
if (!string)
return false;
return regexp_exec_impl(cx, regexp, string, UpdateRegExpStatics, args.rval());
}
bool
js::regexp_exec(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod(cx, IsRegExpObject, regexp_exec_impl, args);
}
/* Separate interface for use by IonMonkey. */
bool
js::regexp_exec_raw(JSContext* cx, HandleObject regexp, HandleString input,
MatchPairs* maybeMatches, MutableHandleValue output)
{
// The MatchPairs will always be passed in, but RegExp execution was
// successful only if the pairs have actually been filled in.
if (maybeMatches && maybeMatches->pairsRaw()[0] >= 0)
return CreateRegExpMatchResult(cx, input, *maybeMatches, output);
return regexp_exec_impl(cx, regexp, input, UpdateRegExpStatics, output);
}
bool
js::regexp_exec_no_statics(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
return regexp_exec_impl(cx, regexp, string, DontUpdateRegExpStatics, args.rval());
}
/* ES5 15.10.6.3. */
static bool
regexp_test_impl(JSContext* cx, const CallArgs& args)
{
RegExpRunStatus status = ExecuteRegExp(cx, args, nullptr);
args.rval().setBoolean(status == RegExpRunStatus_Success);
return status != RegExpRunStatus_Error;
}
/* Separate interface for use by IonMonkey. */
bool
js::regexp_test_raw(JSContext* cx, HandleObject regexp, HandleString input, bool* result)
{
RegExpRunStatus status = ExecuteRegExp(cx, regexp, input, nullptr, UpdateRegExpStatics);
*result = (status == RegExpRunStatus_Success);
return status != RegExpRunStatus_Error;
}
bool
js::regexp_test(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod(cx, IsRegExpObject, regexp_test_impl, args);
}
bool
js::regexp_test_no_statics(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, nullptr, DontUpdateRegExpStatics);
args.rval().setBoolean(status == RegExpRunStatus_Success);
return status != RegExpRunStatus_Error;
}