string-startswith.tq 2.68 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include 'src/builtins/builtins-regexp-gen.h'

namespace string {
  extern macro RegExpBuiltinsAssembler::IsRegExp(implicit context:
                                                     Context)(Object): bool;

  // TODO(ryzokuken): Add RequireObjectCoercible to base.tq and update callsites
  macro RequireObjectCoercible(implicit context: Context)(argument: Object):
      Object {
    if (IsNullOrUndefined(argument)) {
15
      ThrowTypeError(kCalledOnNullOrUndefined, 'String.prototype.startsWith');
16 17 18 19 20 21
    }
    return argument;
  }

  // https://tc39.github.io/ecma262/#sec-string.prototype.startswith
  transitioning javascript builtin StringPrototypeStartsWith(
22
      js-implicit context: Context, receiver: Object)(...arguments): Boolean {
23 24 25 26 27 28 29 30 31 32 33 34
    const searchString: Object = arguments[0];
    const position: Object = arguments[1];

    // 1. Let O be ? RequireObjectCoercible(this value).
    const object: Object = RequireObjectCoercible(receiver);

    // 2. Let S be ? ToString(O).
    const string: String = ToString_Inline(context, object);

    // 3. Let isRegExp be ? IsRegExp(searchString).
    // 4. If isRegExp is true, throw a TypeError exception.
    if (IsRegExp(searchString)) {
35
      ThrowTypeError(kFirstArgumentNotRegExp, 'String.prototype.startsWith');
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    }

    // 5. Let searchStr be ? ToString(searchString).
    const searchStr: String = ToString_Inline(context, searchString);

    // 6. Let pos be ? ToInteger(position).
    const pos: Number = ToInteger_Inline(context, position);

    // 7. Assert: If position is undefined, then pos is 0.
    // 8. Let len be the length of S.
    const len: Number = string.length_smi;

    // 9. Let start be min(max(pos, 0), len).
    const start: Number = NumberMin(NumberMax(pos, 0), len);

    // 10. Let searchLength be the length of searchStr.
    const searchLength: Smi = searchStr.length_smi;

    // 11. If searchLength + start is greater than len, return false.
    if (searchLength + start > len) return False;

    // 12. If the sequence of code units of S starting at start of length
    // searchLength is the same as the full code unit sequence of searchStr,
    // return true.
60
    // 13. Otherwise, return false.
61 62
    try {
      // Fast Path: If both strings are direct and relevant indices are Smis.
63 64
      return TryFastStringCompareSequence(
          string, searchStr, start, searchLength) otherwise Slow;
65 66 67
    }
    label Slow {
      // Slow Path: If either of the string is indirect, bail into runtime.
68
      return StringCompareSequence(context, string, searchStr, start);
69 70 71
    }
  }
}