regexp.js 15.3 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6 7 8
// This file relies on the fact that the following declaration has been made
// in runtime.js:
// var $Object = global.Object;
// var $Array = global.Array;
9

10
var $RegExp = global.RegExp;
11

12 13
// -------------------------------------------------------------------

14 15
// A recursive descent parser for Patterns according to the grammar of
// ECMA-262 15.10.1, with deviations noted below.
16
function DoConstructRegExp(object, pattern, flags) {
17 18 19 20 21 22 23 24
  // RegExp : Called as constructor; see ECMA-262, section 15.10.4.
  if (IS_REGEXP(pattern)) {
    if (!IS_UNDEFINED(flags)) {
      throw MakeTypeError('regexp_flags', []);
    }
    flags = (pattern.global ? 'g' : '')
        + (pattern.ignoreCase ? 'i' : '')
        + (pattern.multiline ? 'm' : '');
25 26
    if (harmony_regexps)
        flags += (pattern.sticky ? 'y' : '');
27 28 29 30 31 32
    pattern = pattern.source;
  }

  pattern = IS_UNDEFINED(pattern) ? '' : ToString(pattern);
  flags = IS_UNDEFINED(flags) ? '' : ToString(flags);

33
  %RegExpInitializeAndCompile(object, pattern, flags);
34
}
35 36 37


function RegExpConstructor(pattern, flags) {
38
  if (%_IsConstructCall()) {
39
    DoConstructRegExp(this, pattern, flags);
40 41 42 43 44 45 46
  } else {
    // RegExp : Called as function; see ECMA-262, section 15.10.3.1.
    if (IS_REGEXP(pattern) && IS_UNDEFINED(flags)) {
      return pattern;
    }
    return new $RegExp(pattern, flags);
  }
47
}
48 49 50

// Deprecated RegExp.prototype.compile method.  We behave like the constructor
// were called again.  In SpiderMonkey, this method returns the regexp object.
51
// In JSC, it returns undefined.  For compatibility with JSC, we match their
52
// behavior.
53
function RegExpCompileJS(pattern, flags) {
54
  // Both JSC and SpiderMonkey treat a missing pattern argument as the
55
  // empty subject string, and an actual undefined value passed as the
56
  // pattern as the string 'undefined'.  Note that JSC is inconsistent
57 58
  // here, treating undefined values differently in
  // RegExp.prototype.compile and in the constructor, where they are
59
  // the empty string.  For compatibility with JSC, we match their
60
  // behavior.
61 62 63 64 65
  if (this == $RegExp.prototype) {
    // We don't allow recompiling RegExp.prototype.
    throw MakeTypeError('incompatible_method_receiver',
                        ['RegExp.prototype.compile', this]);
  }
66
  if (IS_UNDEFINED(pattern) && %_ArgumentsLength() != 0) {
67
    DoConstructRegExp(this, 'undefined', flags);
68
  } else {
69
    DoConstructRegExp(this, pattern, flags);
70 71 72 73 74
  }
}


function DoRegExpExec(regexp, string, index) {
75 76 77
  var result = %_RegExpExec(regexp, string, index, lastMatchInfo);
  if (result !== null) lastMatchInfoOverride = null;
  return result;
78 79
}

80

81 82 83 84 85 86 87
// This is kind of performance sensitive, so we want to avoid unnecessary
// type checks on inputs. But we also don't want to inline it several times
// manually, so we use a macro :-)
macro RETURN_NEW_RESULT_FROM_MATCH_INFO(MATCHINFO, STRING)
  var numResults = NUMBER_OF_CAPTURES(MATCHINFO) >> 1;
  var start = MATCHINFO[CAPTURE0];
  var end = MATCHINFO[CAPTURE1];
88 89 90
  // Calculate the substring of the first match before creating the result array
  // to avoid an unnecessary write barrier storing the first result.
  var first = %_SubString(STRING, start, end);
91
  var result = %_RegExpConstructResult(numResults, start, STRING);
92 93
  result[0] = first;
  if (numResults == 1) return result;
94 95
  var j = REGEXP_FIRST_CAPTURE + 2;
  for (var i = 1; i < numResults; i++) {
96
    start = MATCHINFO[j++];
97
    if (start != -1) {
98 99
      end = MATCHINFO[j];
      result[i] = %_SubString(STRING, start, end);
100
    }
101
    j++;
102 103
  }
  return result;
104
endmacro
105 106 107 108


function RegExpExecNoTests(regexp, string, start) {
  // Must be called with RegExp, string and positive integer as arguments.
109
  var matchInfo = %_RegExpExec(regexp, string, start, lastMatchInfo);
110
  if (matchInfo !== null) {
111
    lastMatchInfoOverride = null;
112
    RETURN_NEW_RESULT_FROM_MATCH_INFO(matchInfo, string);
113
  }
114
  regexp.lastIndex = 0;
115
  return null;
116 117 118
}


119
function RegExpExec(string) {
120 121 122 123 124
  if (!IS_REGEXP(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['RegExp.prototype.exec', this]);
  }

125
  string = TO_STRING_INLINE(string);
126
  var lastIndex = this.lastIndex;
127

128 129 130
  // Conversion is required by the ES5 specification (RegExp.prototype.exec
  // algorithm, step 5) even if the value is discarded for non-global RegExps.
  var i = TO_INTEGER(lastIndex);
131

132 133
  var updateLastIndex = this.global || (harmony_regexps && this.sticky);
  if (updateLastIndex) {
134
    if (i < 0 || i > string.length) {
135 136 137 138 139
      this.lastIndex = 0;
      return null;
    }
  } else {
    i = 0;
140 141
  }

142
  // matchIndices is either null or the lastMatchInfo array.
143
  var matchIndices = %_RegExpExec(this, string, i, lastMatchInfo);
144

145
  if (IS_NULL(matchIndices)) {
146
    this.lastIndex = 0;
147
    return null;
148
  }
149 150

  // Successful match.
151
  lastMatchInfoOverride = null;
152
  if (updateLastIndex) {
153 154
    this.lastIndex = lastMatchInfo[CAPTURE1];
  }
155
  RETURN_NEW_RESULT_FROM_MATCH_INFO(matchIndices, string);
156
}
157 158


159 160 161 162
// One-element cache for the simplified test regexp.
var regexp_key;
var regexp_val;

163
// Section 15.10.6.3 doesn't actually make sense, but the intention seems to be
164 165 166
// that test is defined in terms of String.prototype.exec. However, it probably
// means the original value of String.prototype.exec, which is what everybody
// else implements.
167
function RegExpTest(string) {
168
  if (!IS_REGEXP(this)) {
169
    throw MakeTypeError('incompatible_method_receiver',
170 171
                        ['RegExp.prototype.test', this]);
  }
172
  string = TO_STRING_INLINE(string);
173

174 175
  var lastIndex = this.lastIndex;

176 177 178
  // Conversion is required by the ES5 specification (RegExp.prototype.exec
  // algorithm, step 5) even if the value is discarded for non-global RegExps.
  var i = TO_INTEGER(lastIndex);
179

180
  if (this.global || (harmony_regexps && this.sticky)) {
181
    if (i < 0 || i > string.length) {
182 183 184
      this.lastIndex = 0;
      return false;
    }
185
    // matchIndices is either null or the lastMatchInfo array.
186
    var matchIndices = %_RegExpExec(this, string, i, lastMatchInfo);
187
    if (IS_NULL(matchIndices)) {
188 189
      this.lastIndex = 0;
      return false;
190
    }
191 192
    lastMatchInfoOverride = null;
    this.lastIndex = lastMatchInfo[CAPTURE1];
193
    return true;
194
  } else {
195 196 197 198
    // Non-global, non-sticky regexp.
    // Remove irrelevant preceeding '.*' in a test regexp.  The expression
    // checks whether this.source starts with '.*' and that the third char is
    // not a '?'.  But see https://code.google.com/p/v8/issues/detail?id=3560
199
    var regexp = this;
200 201
    if (regexp.source.length >= 3 &&
        %_StringCharCodeAt(regexp.source, 0) == 46 &&  // '.'
202 203 204
        %_StringCharCodeAt(regexp.source, 1) == 42 &&  // '*'
        %_StringCharCodeAt(regexp.source, 2) != 63) {  // '?'
      regexp = TrimRegExp(regexp);
205
    }
206
    // matchIndices is either null or the lastMatchInfo array.
207
    var matchIndices = %_RegExpExec(regexp, string, 0, lastMatchInfo);
208
    if (IS_NULL(matchIndices)) {
209 210 211
      this.lastIndex = 0;
      return false;
    }
212 213
    lastMatchInfoOverride = null;
    return true;
214
  }
215
}
216

217 218 219 220
function TrimRegExp(regexp) {
  if (!%_ObjectEquals(regexp_key, regexp)) {
    regexp_key = regexp;
    regexp_val =
221
      new $RegExp(%_SubString(regexp.source, 2, regexp.source.length),
222 223 224 225 226 227
                  (regexp.ignoreCase ? regexp.multiline ? "im" : "i"
                                     : regexp.multiline ? "m" : ""));
  }
  return regexp_val;
}

228 229

function RegExpToString() {
230 231 232 233
  if (!IS_REGEXP(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['RegExp.prototype.toString', this]);
  }
234
  var result = '/' + this.source + '/';
235 236 237
  if (this.global) result += 'g';
  if (this.ignoreCase) result += 'i';
  if (this.multiline) result += 'm';
238
  if (harmony_regexps && this.sticky) result += 'y';
239
  return result;
240
}
241 242 243 244 245 246 247


// Getters for the static properties lastMatch, lastParen, leftContext, and
// rightContext of the RegExp constructor.  The properties are computed based
// on the captures array of the last successful match and the subject string
// of the last successful match.
function RegExpGetLastMatch() {
248
  if (lastMatchInfoOverride !== null) {
249
    return OVERRIDE_MATCH(lastMatchInfoOverride);
250
  }
251
  var regExpSubject = LAST_SUBJECT(lastMatchInfo);
252 253 254
  return %_SubString(regExpSubject,
                     lastMatchInfo[CAPTURE0],
                     lastMatchInfo[CAPTURE1]);
255 256
}

257 258

function RegExpGetLastParen() {
259 260
  if (lastMatchInfoOverride) {
    var override = lastMatchInfoOverride;
261
    if (override.length <= 3) return '';
262 263
    return override[override.length - 3];
  }
264 265
  var length = NUMBER_OF_CAPTURES(lastMatchInfo);
  if (length <= 2) return '';  // There were no captures.
266 267 268
  // We match the SpiderMonkey behavior: return the substring defined by the
  // last pair (after the first pair) of elements of the capture array even if
  // it is empty.
269 270 271 272
  var regExpSubject = LAST_SUBJECT(lastMatchInfo);
  var start = lastMatchInfo[CAPTURE(length - 2)];
  var end = lastMatchInfo[CAPTURE(length - 1)];
  if (start != -1 && end != -1) {
273
    return %_SubString(regExpSubject, start, end);
274 275
  }
  return "";
276 277
}

278 279

function RegExpGetLeftContext() {
280 281 282 283 284 285 286
  var start_index;
  var subject;
  if (!lastMatchInfoOverride) {
    start_index = lastMatchInfo[CAPTURE0];
    subject = LAST_SUBJECT(lastMatchInfo);
  } else {
    var override = lastMatchInfoOverride;
287 288
    start_index = OVERRIDE_POS(override);
    subject = OVERRIDE_SUBJECT(override);
289
  }
290
  return %_SubString(subject, 0, start_index);
291 292
}

293 294

function RegExpGetRightContext() {
295 296 297 298 299 300 301
  var start_index;
  var subject;
  if (!lastMatchInfoOverride) {
    start_index = lastMatchInfo[CAPTURE1];
    subject = LAST_SUBJECT(lastMatchInfo);
  } else {
    var override = lastMatchInfoOverride;
302 303 304
    subject = OVERRIDE_SUBJECT(override);
    var match = OVERRIDE_MATCH(override);
    start_index = OVERRIDE_POS(override) + match.length;
305
  }
306
  return %_SubString(subject, start_index, subject.length);
307
}
308 309 310 311


// The properties $1..$9 are the first nine capturing substrings of the last
// successful match, or ''.  The function RegExpMakeCaptureGetter will be
312
// called with indices from 1 to 9.
313 314
function RegExpMakeCaptureGetter(n) {
  return function() {
315
    if (lastMatchInfoOverride) {
316 317 318
      if (n < lastMatchInfoOverride.length - 2) {
        return OVERRIDE_CAPTURE(lastMatchInfoOverride, n);
      }
319 320
      return '';
    }
321
    var index = n * 2;
322 323 324
    if (index >= NUMBER_OF_CAPTURES(lastMatchInfo)) return '';
    var matchStart = lastMatchInfo[CAPTURE(index)];
    var matchEnd = lastMatchInfo[CAPTURE(index + 1)];
325
    if (matchStart == -1 || matchEnd == -1) return '';
326
    return %_SubString(LAST_SUBJECT(lastMatchInfo), matchStart, matchEnd);
327
  };
328
}
329 330


331 332 333 334 335 336
// Property of the builtins object for recording the result of the last
// regexp match.  The property lastMatchInfo includes the matchIndices
// array of the last successful regexp match (an array of start/end index
// pairs for the match and all the captured substrings), the invariant is
// that there are at least two capture indeces.  The array also contains
// the subject string for the last successful match.
337
var lastMatchInfo = new InternalPackedArray(
338 339
    2,                 // REGEXP_NUMBER_OF_CAPTURES
    "",                // Last subject.
340
    UNDEFINED,         // Last input - settable with RegExpSetInput.
341
    0,                 // REGEXP_FIRST_CAPTURE + 0
342 343
    0                  // REGEXP_FIRST_CAPTURE + 1
);
344

345 346
// Override last match info with an array of actual substrings.
// Used internally by replace regexp with function.
347 348
// The array has the format of an "apply" argument for a replacement
// function.
349 350
var lastMatchInfoOverride = null;

351 352
// -------------------------------------------------------------------

353 354
function SetUpRegExp() {
  %CheckIsBootstrapping();
355
  %FunctionSetInstanceClassName($RegExp, 'RegExp');
356
  %AddNamedProperty($RegExp.prototype, 'constructor', $RegExp, DONT_ENUM);
357 358 359 360 361 362
  %SetCode($RegExp, RegExpConstructor);

  InstallFunctions($RegExp.prototype, DONT_ENUM, $Array(
    "exec", RegExpExec,
    "test", RegExpTest,
    "toString", RegExpToString,
363
    "compile", RegExpCompileJS
364 365 366 367 368
  ));

  // The length of compile is 1 in SpiderMonkey.
  %FunctionSetLength($RegExp.prototype.compile, 1);

369
  // The properties `input` and `$_` are aliases for each other.  When this
370
  // value is set the value it is set to is coerced to a string.
371
  // Getter and setter for the input.
372
  var RegExpGetInput = function() {
373
    var regExpInput = LAST_INPUT(lastMatchInfo);
374
    return IS_UNDEFINED(regExpInput) ? "" : regExpInput;
375 376
  };
  var RegExpSetInput = function(string) {
377
    LAST_INPUT(lastMatchInfo) = ToString(string);
378
  };
379

380
  %OptimizeObjectForAddingMultipleProperties($RegExp, 22);
381 382 383 384
  %DefineAccessorPropertyUnchecked($RegExp, 'input', RegExpGetInput,
                                   RegExpSetInput, DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, '$_', RegExpGetInput,
                                   RegExpSetInput, DONT_ENUM | DONT_DELETE);
385 386 387 388 389

  // The properties multiline and $* are aliases for each other.  When this
  // value is set in SpiderMonkey, the value it is set to is coerced to a
  // boolean.  We mimic that behavior with a slight difference: in SpiderMonkey
  // the value of the expression 'RegExp.multiline = null' (for instance) is the
390 391
  // boolean false (i.e., the value after coercion), while in V8 it is the value
  // null (i.e., the value before coercion).
392 393 394

  // Getter and setter for multiline.
  var multiline = false;
395 396
  var RegExpGetMultiline = function() { return multiline; };
  var RegExpSetMultiline = function(flag) { multiline = flag ? true : false; };
397

398 399 400 401 402
  %DefineAccessorPropertyUnchecked($RegExp, 'multiline', RegExpGetMultiline,
                                   RegExpSetMultiline, DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, '$*', RegExpGetMultiline,
                                   RegExpSetMultiline,
                                   DONT_ENUM | DONT_DELETE);
403 404


405
  var NoOpSetter = function(ignored) {};
406 407 408


  // Static properties set by a successful match.
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
  %DefineAccessorPropertyUnchecked($RegExp, 'lastMatch', RegExpGetLastMatch,
                                   NoOpSetter, DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, '$&', RegExpGetLastMatch,
                                   NoOpSetter, DONT_ENUM | DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, 'lastParen', RegExpGetLastParen,
                                   NoOpSetter, DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, '$+', RegExpGetLastParen,
                                   NoOpSetter, DONT_ENUM | DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, 'leftContext',
                                   RegExpGetLeftContext, NoOpSetter,
                                   DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, '$`', RegExpGetLeftContext,
                                   NoOpSetter, DONT_ENUM | DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, 'rightContext',
                                   RegExpGetRightContext, NoOpSetter,
                                   DONT_DELETE);
  %DefineAccessorPropertyUnchecked($RegExp, "$'", RegExpGetRightContext,
                                   NoOpSetter, DONT_ENUM | DONT_DELETE);
427

428
  for (var i = 1; i < 10; ++i) {
429 430 431
    %DefineAccessorPropertyUnchecked($RegExp, '$' + i,
                                     RegExpMakeCaptureGetter(i), NoOpSetter,
                                     DONT_DELETE);
432
  }
433
  %ToFastProperties($RegExp);
434 435
}

436
SetUpRegExp();