regexp.js 15.6 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 25 26 27 28 29 30 31 32 33 34
  // 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' : '');
    pattern = pattern.source;
  }

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

  var global = false;
  var ignoreCase = false;
  var multiline = false;
  for (var i = 0; i < flags.length; i++) {
35
    var c = %_CallFunction(flags, i, StringCharAt);
36 37
    switch (c) {
      case 'g':
38 39 40
        if (global) {
          throw MakeSyntaxError("invalid_regexp_flags", [flags]);
        }
41 42 43
        global = true;
        break;
      case 'i':
44 45 46
        if (ignoreCase) {
          throw MakeSyntaxError("invalid_regexp_flags", [flags]);
        }
47 48 49
        ignoreCase = true;
        break;
      case 'm':
50 51 52
        if (multiline) {
          throw MakeSyntaxError("invalid_regexp_flags", [flags]);
        }
53 54 55
        multiline = true;
        break;
      default:
56
        throw MakeSyntaxError("invalid_regexp_flags", [flags]);
57 58 59
    }
  }

60
  %RegExpInitializeObject(object, pattern, global, ignoreCase, multiline);
61 62 63

  // Call internal function to compile the pattern.
  %RegExpCompile(object, pattern, flags);
64
}
65 66 67


function RegExpConstructor(pattern, flags) {
68
  if (%_IsConstructCall()) {
69
    DoConstructRegExp(this, pattern, flags);
70 71 72 73 74 75 76
  } 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);
  }
77
}
78 79 80

// Deprecated RegExp.prototype.compile method.  We behave like the constructor
// were called again.  In SpiderMonkey, this method returns the regexp object.
81
// In JSC, it returns undefined.  For compatibility with JSC, we match their
82
// behavior.
83
function RegExpCompile(pattern, flags) {
84
  // Both JSC and SpiderMonkey treat a missing pattern argument as the
85
  // empty subject string, and an actual undefined value passed as the
86
  // pattern as the string 'undefined'.  Note that JSC is inconsistent
87 88
  // here, treating undefined values differently in
  // RegExp.prototype.compile and in the constructor, where they are
89
  // the empty string.  For compatibility with JSC, we match their
90
  // behavior.
91 92 93 94 95
  if (this == $RegExp.prototype) {
    // We don't allow recompiling RegExp.prototype.
    throw MakeTypeError('incompatible_method_receiver',
                        ['RegExp.prototype.compile', this]);
  }
96
  if (IS_UNDEFINED(pattern) && %_ArgumentsLength() != 0) {
97
    DoConstructRegExp(this, 'undefined', flags);
98
  } else {
99
    DoConstructRegExp(this, pattern, flags);
100 101 102 103 104
  }
}


function DoRegExpExec(regexp, string, index) {
105 106 107
  var result = %_RegExpExec(regexp, string, index, lastMatchInfo);
  if (result !== null) lastMatchInfoOverride = null;
  return result;
108 109
}

110

111 112
function BuildResultFromMatchInfo(lastMatchInfo, s) {
  var numResults = NUMBER_OF_CAPTURES(lastMatchInfo) >> 1;
113 114 115
  var start = lastMatchInfo[CAPTURE0];
  var end = lastMatchInfo[CAPTURE1];
  var result = %_RegExpConstructResult(numResults, start, s);
116
  result[0] = %_SubString(s, start, end);
117 118 119
  var j = REGEXP_FIRST_CAPTURE + 2;
  for (var i = 1; i < numResults; i++) {
    start = lastMatchInfo[j++];
120 121
    if (start != -1) {
      end = lastMatchInfo[j];
122
      result[i] = %_SubString(s, start, end);
123
    }
124
    j++;
125 126 127 128 129 130 131
  }
  return result;
}


function RegExpExecNoTests(regexp, string, start) {
  // Must be called with RegExp, string and positive integer as arguments.
132
  var matchInfo = %_RegExpExec(regexp, string, start, lastMatchInfo);
133
  if (matchInfo !== null) {
134 135
    lastMatchInfoOverride = null;
    return BuildResultFromMatchInfo(matchInfo, string);
136
  }
137
  regexp.lastIndex = 0;
138
  return null;
139 140 141
}


142
function RegExpExec(string) {
143 144 145 146 147
  if (!IS_REGEXP(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['RegExp.prototype.exec', this]);
  }

148
  string = TO_STRING_INLINE(string);
149
  var lastIndex = this.lastIndex;
150

151 152 153
  // 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);
154 155

  var global = this.global;
156
  if (global) {
157
    if (i < 0 || i > string.length) {
158 159 160 161 162
      this.lastIndex = 0;
      return null;
    }
  } else {
    i = 0;
163 164
  }

165
  // matchIndices is either null or the lastMatchInfo array.
166
  var matchIndices = %_RegExpExec(this, string, i, lastMatchInfo);
167

168
  if (IS_NULL(matchIndices)) {
169
    this.lastIndex = 0;
170
    return null;
171
  }
172 173

  // Successful match.
174
  lastMatchInfoOverride = null;
175
  if (global) {
176 177
    this.lastIndex = lastMatchInfo[CAPTURE1];
  }
178
  return BuildResultFromMatchInfo(matchIndices, string);
179
}
180 181


182 183 184 185
// One-element cache for the simplified test regexp.
var regexp_key;
var regexp_val;

186
// Section 15.10.6.3 doesn't actually make sense, but the intention seems to be
187 188 189
// 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.
190
function RegExpTest(string) {
191
  if (!IS_REGEXP(this)) {
192
    throw MakeTypeError('incompatible_method_receiver',
193 194
                        ['RegExp.prototype.test', this]);
  }
195
  string = TO_STRING_INLINE(string);
196

197 198
  var lastIndex = this.lastIndex;

199 200 201
  // 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);
202

203
  if (this.global) {
204
    if (i < 0 || i > string.length) {
205 206 207
      this.lastIndex = 0;
      return false;
    }
208
    // matchIndices is either null or the lastMatchInfo array.
209
    var matchIndices = %_RegExpExec(this, string, i, lastMatchInfo);
210
    if (IS_NULL(matchIndices)) {
211 212
      this.lastIndex = 0;
      return false;
213
    }
214 215
    lastMatchInfoOverride = null;
    this.lastIndex = lastMatchInfo[CAPTURE1];
216
    return true;
217 218
  } else {
    // Non-global regexp.
219 220
    // Remove irrelevant preceeding '.*' in a non-global test regexp.
    // The expression checks whether this.source starts with '.*' and
221
    // that the third char is not a '?'.
222 223 224 225 226
    var regexp = this;
    if (%_StringCharCodeAt(regexp.source, 0) == 46 &&  // '.'
        %_StringCharCodeAt(regexp.source, 1) == 42 &&  // '*'
        %_StringCharCodeAt(regexp.source, 2) != 63) {  // '?'
      regexp = TrimRegExp(regexp);
227
    }
228
    // matchIndices is either null or the lastMatchInfo array.
229
    var matchIndices = %_RegExpExec(regexp, string, 0, lastMatchInfo);
230
    if (IS_NULL(matchIndices)) {
231 232 233
      this.lastIndex = 0;
      return false;
    }
234 235
    lastMatchInfoOverride = null;
    return true;
236
  }
237
}
238

239 240 241 242
function TrimRegExp(regexp) {
  if (!%_ObjectEquals(regexp_key, regexp)) {
    regexp_key = regexp;
    regexp_val =
243
      new $RegExp(%_SubString(regexp.source, 2, regexp.source.length),
244 245 246 247 248 249
                  (regexp.ignoreCase ? regexp.multiline ? "im" : "i"
                                     : regexp.multiline ? "m" : ""));
  }
  return regexp_val;
}

250 251

function RegExpToString() {
252 253 254 255
  if (!IS_REGEXP(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['RegExp.prototype.toString', this]);
  }
256
  var result = '/' + this.source + '/';
257 258 259
  if (this.global) result += 'g';
  if (this.ignoreCase) result += 'i';
  if (this.multiline) result += 'm';
260
  return result;
261
}
262 263 264 265 266 267 268


// 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() {
269
  if (lastMatchInfoOverride !== null) {
270
    return OVERRIDE_MATCH(lastMatchInfoOverride);
271
  }
272
  var regExpSubject = LAST_SUBJECT(lastMatchInfo);
273 274 275
  return %_SubString(regExpSubject,
                     lastMatchInfo[CAPTURE0],
                     lastMatchInfo[CAPTURE1]);
276 277
}

278 279

function RegExpGetLastParen() {
280 281
  if (lastMatchInfoOverride) {
    var override = lastMatchInfoOverride;
282
    if (override.length <= 3) return '';
283 284
    return override[override.length - 3];
  }
285 286
  var length = NUMBER_OF_CAPTURES(lastMatchInfo);
  if (length <= 2) return '';  // There were no captures.
287 288 289
  // 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.
290 291 292 293
  var regExpSubject = LAST_SUBJECT(lastMatchInfo);
  var start = lastMatchInfo[CAPTURE(length - 2)];
  var end = lastMatchInfo[CAPTURE(length - 1)];
  if (start != -1 && end != -1) {
294
    return %_SubString(regExpSubject, start, end);
295 296
  }
  return "";
297 298
}

299 300

function RegExpGetLeftContext() {
301 302 303 304 305 306 307
  var start_index;
  var subject;
  if (!lastMatchInfoOverride) {
    start_index = lastMatchInfo[CAPTURE0];
    subject = LAST_SUBJECT(lastMatchInfo);
  } else {
    var override = lastMatchInfoOverride;
308 309
    start_index = OVERRIDE_POS(override);
    subject = OVERRIDE_SUBJECT(override);
310
  }
311
  return %_SubString(subject, 0, start_index);
312 313
}

314 315

function RegExpGetRightContext() {
316 317 318 319 320 321 322
  var start_index;
  var subject;
  if (!lastMatchInfoOverride) {
    start_index = lastMatchInfo[CAPTURE1];
    subject = LAST_SUBJECT(lastMatchInfo);
  } else {
    var override = lastMatchInfoOverride;
323 324 325
    subject = OVERRIDE_SUBJECT(override);
    var match = OVERRIDE_MATCH(override);
    start_index = OVERRIDE_POS(override) + match.length;
326
  }
327
  return %_SubString(subject, start_index, subject.length);
328
}
329 330 331 332


// The properties $1..$9 are the first nine capturing substrings of the last
// successful match, or ''.  The function RegExpMakeCaptureGetter will be
333
// called with indices from 1 to 9.
334 335
function RegExpMakeCaptureGetter(n) {
  return function() {
336
    if (lastMatchInfoOverride) {
337 338 339
      if (n < lastMatchInfoOverride.length - 2) {
        return OVERRIDE_CAPTURE(lastMatchInfoOverride, n);
      }
340 341
      return '';
    }
342
    var index = n * 2;
343 344 345
    if (index >= NUMBER_OF_CAPTURES(lastMatchInfo)) return '';
    var matchStart = lastMatchInfo[CAPTURE(index)];
    var matchEnd = lastMatchInfo[CAPTURE(index + 1)];
346
    if (matchStart == -1 || matchEnd == -1) return '';
347
    return %_SubString(LAST_SUBJECT(lastMatchInfo), matchStart, matchEnd);
348
  };
349
}
350 351


352 353 354 355 356 357
// 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.
358
var lastMatchInfo = new InternalPackedArray(
359 360
    2,                 // REGEXP_NUMBER_OF_CAPTURES
    "",                // Last subject.
361
    UNDEFINED,         // Last input - settable with RegExpSetInput.
362
    0,                 // REGEXP_FIRST_CAPTURE + 0
363 364
    0                  // REGEXP_FIRST_CAPTURE + 1
);
365

366 367
// Override last match info with an array of actual substrings.
// Used internally by replace regexp with function.
368 369
// The array has the format of an "apply" argument for a replacement
// function.
370 371
var lastMatchInfoOverride = null;

372 373
// -------------------------------------------------------------------

374 375
function SetUpRegExp() {
  %CheckIsBootstrapping();
376
  %FunctionSetInstanceClassName($RegExp, 'RegExp');
377
  %SetProperty($RegExp.prototype, 'constructor', $RegExp, DONT_ENUM);
378 379 380 381 382 383
  %SetCode($RegExp, RegExpConstructor);

  InstallFunctions($RegExp.prototype, DONT_ENUM, $Array(
    "exec", RegExpExec,
    "test", RegExpTest,
    "toString", RegExpToString,
384
    "compile", RegExpCompile
385 386 387 388 389 390
  ));

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

  // The properties input, $input, and $_ are aliases for each other.  When this
391
  // value is set the value it is set to is coerced to a string.
392
  // Getter and setter for the input.
393
  var RegExpGetInput = function() {
394
    var regExpInput = LAST_INPUT(lastMatchInfo);
395
    return IS_UNDEFINED(regExpInput) ? "" : regExpInput;
396 397
  };
  var RegExpSetInput = function(string) {
398
    LAST_INPUT(lastMatchInfo) = ToString(string);
399
  };
400

401
  %OptimizeObjectForAddingMultipleProperties($RegExp, 22);
402 403 404 405 406 407
  %DefineOrRedefineAccessorProperty($RegExp, 'input', RegExpGetInput,
                                    RegExpSetInput, DONT_DELETE);
  %DefineOrRedefineAccessorProperty($RegExp, '$_', RegExpGetInput,
                                    RegExpSetInput, DONT_ENUM | DONT_DELETE);
  %DefineOrRedefineAccessorProperty($RegExp, '$input', RegExpGetInput,
                                    RegExpSetInput, DONT_ENUM | DONT_DELETE);
408 409 410 411 412

  // 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
413 414
  // boolean false (i.e., the value after coercion), while in V8 it is the value
  // null (i.e., the value before coercion).
415 416 417

  // Getter and setter for multiline.
  var multiline = false;
418 419
  var RegExpGetMultiline = function() { return multiline; };
  var RegExpSetMultiline = function(flag) { multiline = flag ? true : false; };
420

421
  %DefineOrRedefineAccessorProperty($RegExp, 'multiline', RegExpGetMultiline,
422
                                    RegExpSetMultiline, DONT_DELETE);
423 424
  %DefineOrRedefineAccessorProperty($RegExp, '$*', RegExpGetMultiline,
                                    RegExpSetMultiline,
425
                                    DONT_ENUM | DONT_DELETE);
426 427


428
  var NoOpSetter = function(ignored) {};
429 430 431


  // Static properties set by a successful match.
432 433 434 435 436 437 438 439 440 441
  %DefineOrRedefineAccessorProperty($RegExp, 'lastMatch', RegExpGetLastMatch,
                                    NoOpSetter, DONT_DELETE);
  %DefineOrRedefineAccessorProperty($RegExp, '$&', RegExpGetLastMatch,
                                    NoOpSetter, DONT_ENUM | DONT_DELETE);
  %DefineOrRedefineAccessorProperty($RegExp, 'lastParen', RegExpGetLastParen,
                                    NoOpSetter, DONT_DELETE);
  %DefineOrRedefineAccessorProperty($RegExp, '$+', RegExpGetLastParen,
                                    NoOpSetter, DONT_ENUM | DONT_DELETE);
  %DefineOrRedefineAccessorProperty($RegExp, 'leftContext',
                                    RegExpGetLeftContext, NoOpSetter,
442
                                    DONT_DELETE);
443 444 445 446
  %DefineOrRedefineAccessorProperty($RegExp, '$`', RegExpGetLeftContext,
                                    NoOpSetter, DONT_ENUM | DONT_DELETE);
  %DefineOrRedefineAccessorProperty($RegExp, 'rightContext',
                                    RegExpGetRightContext, NoOpSetter,
447
                                    DONT_DELETE);
448 449
  %DefineOrRedefineAccessorProperty($RegExp, "$'", RegExpGetRightContext,
                                    NoOpSetter, DONT_ENUM | DONT_DELETE);
450

451
  for (var i = 1; i < 10; ++i) {
452 453
    %DefineOrRedefineAccessorProperty($RegExp, '$' + i,
                                      RegExpMakeCaptureGetter(i), NoOpSetter,
454
                                      DONT_DELETE);
455
  }
456
  %ToFastProperties($RegExp);
457 458
}

459
SetUpRegExp();