1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 var $regexpLastMatchInfoOverride;
7 (function(global, utils) {
9 %CheckIsBootstrapping();
11 // -------------------------------------------------------------------
14 var FLAG_harmony_regexps;
15 var FLAG_harmony_unicode_regexps;
16 var GlobalRegExp = global.RegExp;
17 var InternalPackedArray = utils.InternalPackedArray;
20 utils.Import(function(from) {
21 ToNumber = from.ToNumber;
24 utils.ImportFromExperimental(function(from) {
25 FLAG_harmony_regexps = from.FLAG_harmony_regexps;
26 FLAG_harmony_unicode_regexps = from.FLAG_harmony_unicode_regexps;
29 // -------------------------------------------------------------------
31 // Property of the builtins object for recording the result of the last
32 // regexp match. The property RegExpLastMatchInfo includes the matchIndices
33 // array of the last successful regexp match (an array of start/end index
34 // pairs for the match and all the captured substrings), the invariant is
35 // that there are at least two capture indeces. The array also contains
36 // the subject string for the last successful match.
37 var RegExpLastMatchInfo = new InternalPackedArray(
38 2, // REGEXP_NUMBER_OF_CAPTURES
40 UNDEFINED, // Last input - settable with RegExpSetInput.
41 0, // REGEXP_FIRST_CAPTURE + 0
42 0 // REGEXP_FIRST_CAPTURE + 1
45 // Override last match info with an array of actual substrings.
46 // Used internally by replace regexp with function.
47 // The array has the format of an "apply" argument for a replacement
49 $regexpLastMatchInfoOverride = null;
51 // -------------------------------------------------------------------
53 // A recursive descent parser for Patterns according to the grammar of
54 // ECMA-262 15.10.1, with deviations noted below.
55 function DoConstructRegExp(object, pattern, flags) {
56 // RegExp : Called as constructor; see ECMA-262, section 15.10.4.
57 if (IS_REGEXP(pattern)) {
58 if (!IS_UNDEFINED(flags)) throw MakeTypeError(kRegExpFlags);
59 flags = (pattern.global ? 'g' : '')
60 + (pattern.ignoreCase ? 'i' : '')
61 + (pattern.multiline ? 'm' : '');
62 if (FLAG_harmony_unicode_regexps)
63 flags += (pattern.unicode ? 'u' : '');
64 if (FLAG_harmony_regexps)
65 flags += (pattern.sticky ? 'y' : '');
66 pattern = pattern.source;
69 pattern = IS_UNDEFINED(pattern) ? '' : $toString(pattern);
70 flags = IS_UNDEFINED(flags) ? '' : $toString(flags);
72 %RegExpInitializeAndCompile(object, pattern, flags);
76 function RegExpConstructor(pattern, flags) {
77 if (%_IsConstructCall()) {
78 DoConstructRegExp(this, pattern, flags);
80 // RegExp : Called as function; see ECMA-262, section 15.10.3.1.
81 if (IS_REGEXP(pattern) && IS_UNDEFINED(flags)) {
84 return new GlobalRegExp(pattern, flags);
88 // Deprecated RegExp.prototype.compile method. We behave like the constructor
89 // were called again. In SpiderMonkey, this method returns the regexp object.
90 // In JSC, it returns undefined. For compatibility with JSC, we match their
92 function RegExpCompileJS(pattern, flags) {
93 // Both JSC and SpiderMonkey treat a missing pattern argument as the
94 // empty subject string, and an actual undefined value passed as the
95 // pattern as the string 'undefined'. Note that JSC is inconsistent
96 // here, treating undefined values differently in
97 // RegExp.prototype.compile and in the constructor, where they are
98 // the empty string. For compatibility with JSC, we match their
100 if (this == GlobalRegExp.prototype) {
101 // We don't allow recompiling RegExp.prototype.
102 throw MakeTypeError(kIncompatibleMethodReceiver,
103 'RegExp.prototype.compile', this);
105 if (IS_UNDEFINED(pattern) && %_ArgumentsLength() != 0) {
106 DoConstructRegExp(this, 'undefined', flags);
108 DoConstructRegExp(this, pattern, flags);
113 function DoRegExpExec(regexp, string, index) {
114 var result = %_RegExpExec(regexp, string, index, RegExpLastMatchInfo);
115 if (result !== null) $regexpLastMatchInfoOverride = null;
120 // This is kind of performance sensitive, so we want to avoid unnecessary
121 // type checks on inputs. But we also don't want to inline it several times
122 // manually, so we use a macro :-)
123 macro RETURN_NEW_RESULT_FROM_MATCH_INFO(MATCHINFO, STRING)
124 var numResults = NUMBER_OF_CAPTURES(MATCHINFO) >> 1;
125 var start = MATCHINFO[CAPTURE0];
126 var end = MATCHINFO[CAPTURE1];
127 // Calculate the substring of the first match before creating the result array
128 // to avoid an unnecessary write barrier storing the first result.
129 var first = %_SubString(STRING, start, end);
130 var result = %_RegExpConstructResult(numResults, start, STRING);
132 if (numResults == 1) return result;
133 var j = REGEXP_FIRST_CAPTURE + 2;
134 for (var i = 1; i < numResults; i++) {
135 start = MATCHINFO[j++];
138 result[i] = %_SubString(STRING, start, end);
146 function RegExpExecNoTests(regexp, string, start) {
147 // Must be called with RegExp, string and positive integer as arguments.
148 var matchInfo = %_RegExpExec(regexp, string, start, RegExpLastMatchInfo);
149 if (matchInfo !== null) {
150 $regexpLastMatchInfoOverride = null;
151 RETURN_NEW_RESULT_FROM_MATCH_INFO(matchInfo, string);
153 regexp.lastIndex = 0;
158 function RegExpExecJS(string) {
159 if (!IS_REGEXP(this)) {
160 throw MakeTypeError(kIncompatibleMethodReceiver,
161 'RegExp.prototype.exec', this);
164 string = TO_STRING_INLINE(string);
165 var lastIndex = this.lastIndex;
167 // Conversion is required by the ES5 specification (RegExp.prototype.exec
168 // algorithm, step 5) even if the value is discarded for non-global RegExps.
169 var i = TO_INTEGER(lastIndex);
171 var updateLastIndex = this.global || (FLAG_harmony_regexps && this.sticky);
172 if (updateLastIndex) {
173 if (i < 0 || i > string.length) {
181 // matchIndices is either null or the RegExpLastMatchInfo array.
182 var matchIndices = %_RegExpExec(this, string, i, RegExpLastMatchInfo);
184 if (IS_NULL(matchIndices)) {
190 $regexpLastMatchInfoOverride = null;
191 if (updateLastIndex) {
192 this.lastIndex = RegExpLastMatchInfo[CAPTURE1];
194 RETURN_NEW_RESULT_FROM_MATCH_INFO(matchIndices, string);
198 // One-element cache for the simplified test regexp.
202 // Section 15.10.6.3 doesn't actually make sense, but the intention seems to be
203 // that test is defined in terms of String.prototype.exec. However, it probably
204 // means the original value of String.prototype.exec, which is what everybody
206 function RegExpTest(string) {
207 if (!IS_REGEXP(this)) {
208 throw MakeTypeError(kIncompatibleMethodReceiver,
209 'RegExp.prototype.test', this);
211 string = TO_STRING_INLINE(string);
213 var lastIndex = this.lastIndex;
215 // Conversion is required by the ES5 specification (RegExp.prototype.exec
216 // algorithm, step 5) even if the value is discarded for non-global RegExps.
217 var i = TO_INTEGER(lastIndex);
219 if (this.global || (FLAG_harmony_regexps && this.sticky)) {
220 if (i < 0 || i > string.length) {
224 // matchIndices is either null or the RegExpLastMatchInfo array.
225 var matchIndices = %_RegExpExec(this, string, i, RegExpLastMatchInfo);
226 if (IS_NULL(matchIndices)) {
230 $regexpLastMatchInfoOverride = null;
231 this.lastIndex = RegExpLastMatchInfo[CAPTURE1];
234 // Non-global, non-sticky regexp.
235 // Remove irrelevant preceeding '.*' in a test regexp. The expression
236 // checks whether this.source starts with '.*' and that the third char is
237 // not a '?'. But see https://code.google.com/p/v8/issues/detail?id=3560
239 if (regexp.source.length >= 3 &&
240 %_StringCharCodeAt(regexp.source, 0) == 46 && // '.'
241 %_StringCharCodeAt(regexp.source, 1) == 42 && // '*'
242 %_StringCharCodeAt(regexp.source, 2) != 63) { // '?'
243 regexp = TrimRegExp(regexp);
245 // matchIndices is either null or the RegExpLastMatchInfo array.
246 var matchIndices = %_RegExpExec(regexp, string, 0, RegExpLastMatchInfo);
247 if (IS_NULL(matchIndices)) {
251 $regexpLastMatchInfoOverride = null;
256 function TrimRegExp(regexp) {
257 if (!%_ObjectEquals(regexp_key, regexp)) {
260 new GlobalRegExp(%_SubString(regexp.source, 2, regexp.source.length),
261 (regexp.ignoreCase ? regexp.multiline ? "im" : "i"
262 : regexp.multiline ? "m" : ""));
268 function RegExpToString() {
269 if (!IS_REGEXP(this)) {
270 throw MakeTypeError(kIncompatibleMethodReceiver,
271 'RegExp.prototype.toString', this);
273 var result = '/' + this.source + '/';
274 if (this.global) result += 'g';
275 if (this.ignoreCase) result += 'i';
276 if (this.multiline) result += 'm';
277 if (FLAG_harmony_unicode_regexps && this.unicode) result += 'u';
278 if (FLAG_harmony_regexps && this.sticky) result += 'y';
283 // Getters for the static properties lastMatch, lastParen, leftContext, and
284 // rightContext of the RegExp constructor. The properties are computed based
285 // on the captures array of the last successful match and the subject string
286 // of the last successful match.
287 function RegExpGetLastMatch() {
288 if ($regexpLastMatchInfoOverride !== null) {
289 return OVERRIDE_MATCH($regexpLastMatchInfoOverride);
291 var regExpSubject = LAST_SUBJECT(RegExpLastMatchInfo);
292 return %_SubString(regExpSubject,
293 RegExpLastMatchInfo[CAPTURE0],
294 RegExpLastMatchInfo[CAPTURE1]);
298 function RegExpGetLastParen() {
299 if ($regexpLastMatchInfoOverride) {
300 var override = $regexpLastMatchInfoOverride;
301 if (override.length <= 3) return '';
302 return override[override.length - 3];
304 var length = NUMBER_OF_CAPTURES(RegExpLastMatchInfo);
305 if (length <= 2) return ''; // There were no captures.
306 // We match the SpiderMonkey behavior: return the substring defined by the
307 // last pair (after the first pair) of elements of the capture array even if
309 var regExpSubject = LAST_SUBJECT(RegExpLastMatchInfo);
310 var start = RegExpLastMatchInfo[CAPTURE(length - 2)];
311 var end = RegExpLastMatchInfo[CAPTURE(length - 1)];
312 if (start != -1 && end != -1) {
313 return %_SubString(regExpSubject, start, end);
319 function RegExpGetLeftContext() {
322 if (!$regexpLastMatchInfoOverride) {
323 start_index = RegExpLastMatchInfo[CAPTURE0];
324 subject = LAST_SUBJECT(RegExpLastMatchInfo);
326 var override = $regexpLastMatchInfoOverride;
327 start_index = OVERRIDE_POS(override);
328 subject = OVERRIDE_SUBJECT(override);
330 return %_SubString(subject, 0, start_index);
334 function RegExpGetRightContext() {
337 if (!$regexpLastMatchInfoOverride) {
338 start_index = RegExpLastMatchInfo[CAPTURE1];
339 subject = LAST_SUBJECT(RegExpLastMatchInfo);
341 var override = $regexpLastMatchInfoOverride;
342 subject = OVERRIDE_SUBJECT(override);
343 var match = OVERRIDE_MATCH(override);
344 start_index = OVERRIDE_POS(override) + match.length;
346 return %_SubString(subject, start_index, subject.length);
350 // The properties $1..$9 are the first nine capturing substrings of the last
351 // successful match, or ''. The function RegExpMakeCaptureGetter will be
352 // called with indices from 1 to 9.
353 function RegExpMakeCaptureGetter(n) {
354 return function foo() {
355 if ($regexpLastMatchInfoOverride) {
356 if (n < $regexpLastMatchInfoOverride.length - 2) {
357 return OVERRIDE_CAPTURE($regexpLastMatchInfoOverride, n);
362 if (index >= NUMBER_OF_CAPTURES(RegExpLastMatchInfo)) return '';
363 var matchStart = RegExpLastMatchInfo[CAPTURE(index)];
364 var matchEnd = RegExpLastMatchInfo[CAPTURE(index + 1)];
365 if (matchStart == -1 || matchEnd == -1) return '';
366 return %_SubString(LAST_SUBJECT(RegExpLastMatchInfo), matchStart, matchEnd);
370 // -------------------------------------------------------------------
372 %FunctionSetInstanceClassName(GlobalRegExp, 'RegExp');
374 GlobalRegExp.prototype, 'constructor', GlobalRegExp, DONT_ENUM);
375 %SetCode(GlobalRegExp, RegExpConstructor);
377 utils.InstallFunctions(GlobalRegExp.prototype, DONT_ENUM, [
378 "exec", RegExpExecJS,
380 "toString", RegExpToString,
381 "compile", RegExpCompileJS
384 // The length of compile is 1 in SpiderMonkey.
385 %FunctionSetLength(GlobalRegExp.prototype.compile, 1);
387 // The properties `input` and `$_` are aliases for each other. When this
388 // value is set the value it is set to is coerced to a string.
389 // Getter and setter for the input.
390 var RegExpGetInput = function() {
391 var regExpInput = LAST_INPUT(RegExpLastMatchInfo);
392 return IS_UNDEFINED(regExpInput) ? "" : regExpInput;
394 var RegExpSetInput = function(string) {
395 LAST_INPUT(RegExpLastMatchInfo) = $toString(string);
398 %OptimizeObjectForAddingMultipleProperties(GlobalRegExp, 22);
399 %DefineAccessorPropertyUnchecked(GlobalRegExp, 'input', RegExpGetInput,
400 RegExpSetInput, DONT_DELETE);
401 %DefineAccessorPropertyUnchecked(GlobalRegExp, '$_', RegExpGetInput,
402 RegExpSetInput, DONT_ENUM | DONT_DELETE);
404 // The properties multiline and $* are aliases for each other. When this
405 // value is set in SpiderMonkey, the value it is set to is coerced to a
406 // boolean. We mimic that behavior with a slight difference: in SpiderMonkey
407 // the value of the expression 'RegExp.multiline = null' (for instance) is the
408 // boolean false (i.e., the value after coercion), while in V8 it is the value
409 // null (i.e., the value before coercion).
411 // Getter and setter for multiline.
412 var multiline = false;
413 var RegExpGetMultiline = function() { return multiline; };
414 var RegExpSetMultiline = function(flag) { multiline = flag ? true : false; };
416 %DefineAccessorPropertyUnchecked(GlobalRegExp, 'multiline', RegExpGetMultiline,
417 RegExpSetMultiline, DONT_DELETE);
418 %DefineAccessorPropertyUnchecked(GlobalRegExp, '$*', RegExpGetMultiline,
420 DONT_ENUM | DONT_DELETE);
423 var NoOpSetter = function(ignored) {};
426 // Static properties set by a successful match.
427 %DefineAccessorPropertyUnchecked(GlobalRegExp, 'lastMatch', RegExpGetLastMatch,
428 NoOpSetter, DONT_DELETE);
429 %DefineAccessorPropertyUnchecked(GlobalRegExp, '$&', RegExpGetLastMatch,
430 NoOpSetter, DONT_ENUM | DONT_DELETE);
431 %DefineAccessorPropertyUnchecked(GlobalRegExp, 'lastParen', RegExpGetLastParen,
432 NoOpSetter, DONT_DELETE);
433 %DefineAccessorPropertyUnchecked(GlobalRegExp, '$+', RegExpGetLastParen,
434 NoOpSetter, DONT_ENUM | DONT_DELETE);
435 %DefineAccessorPropertyUnchecked(GlobalRegExp, 'leftContext',
436 RegExpGetLeftContext, NoOpSetter,
438 %DefineAccessorPropertyUnchecked(GlobalRegExp, '$`', RegExpGetLeftContext,
439 NoOpSetter, DONT_ENUM | DONT_DELETE);
440 %DefineAccessorPropertyUnchecked(GlobalRegExp, 'rightContext',
441 RegExpGetRightContext, NoOpSetter,
443 %DefineAccessorPropertyUnchecked(GlobalRegExp, "$'", RegExpGetRightContext,
444 NoOpSetter, DONT_ENUM | DONT_DELETE);
446 for (var i = 1; i < 10; ++i) {
447 %DefineAccessorPropertyUnchecked(GlobalRegExp, '$' + i,
448 RegExpMakeCaptureGetter(i), NoOpSetter,
451 %ToFastProperties(GlobalRegExp);
453 // -------------------------------------------------------------------
456 utils.Export(function(to) {
457 to.RegExpExec = DoRegExpExec;
458 to.RegExpExecNoTests = RegExpExecNoTests;
459 to.RegExpLastMatchInfo = RegExpLastMatchInfo;
460 to.RegExpTest = RegExpTest;