NativeString.java 40.5 KB
Newer Older
J
jlaskey 已提交
1
/*
J
jlaskey 已提交
2
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
J
jlaskey 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.objects;

28
import static jdk.nashorn.internal.lookup.Lookup.MH;
J
jlaskey 已提交
29 30 31 32 33 34 35 36 37
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.JSType.isRepresentableAsInt;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
38
import java.util.LinkedList;
J
jlaskey 已提交
39
import java.util.List;
40
import java.util.Locale;
41 42 43
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
44
import jdk.nashorn.internal.lookup.MethodHandleFactory;
J
jlaskey 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
import jdk.nashorn.internal.objects.annotations.Attribute;
import jdk.nashorn.internal.objects.annotations.Constructor;
import jdk.nashorn.internal.objects.annotations.Function;
import jdk.nashorn.internal.objects.annotations.Getter;
import jdk.nashorn.internal.objects.annotations.ScriptClass;
import jdk.nashorn.internal.objects.annotations.SpecializedConstructor;
import jdk.nashorn.internal.objects.annotations.SpecializedFunction;
import jdk.nashorn.internal.objects.annotations.Where;
import jdk.nashorn.internal.runtime.ConsString;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
import jdk.nashorn.internal.runtime.linker.NashornGuards;
import jdk.nashorn.internal.runtime.linker.PrimitiveLookup;


/**
 * ECMA 15.5 String Objects.
 */
@ScriptClass("String")
public final class NativeString extends ScriptObject {

    private final CharSequence value;

71
    static final MethodHandle WRAPFILTER = findWrapFilter();
J
jlaskey 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    NativeString(final CharSequence value) {
        this(value, Global.instance().getStringPrototype());
    }

    private NativeString(final CharSequence value, final ScriptObject proto) {
        assert value instanceof String || value instanceof ConsString;
        this.value = value;
        this.setProto(proto);
    }

    @Override
    public String safeToString() {
        return "[String " + toString() + "]";
    }

    @Override
    public String toString() {
        return getStringValue();
    }

    @Override
    public boolean equals(final Object other) {
        if (other instanceof NativeString) {
            return getStringValue().equals(((NativeString) other).getStringValue());
        }

        return false;
    }

    @Override
    public int hashCode() {
        return getStringValue().hashCode();
    }

    private String getStringValue() {
        return value instanceof String ? (String) value : value.toString();
    }

    private CharSequence getValue() {
        return value;
    }

    @Override
    public String getClassName() {
        return "String";
    }

    @Override
    public Object getLength() {
        return value.length();
    }

125 126 127 128 129 130 131 132 133 134 135 136 137
    // This is to support length as method call as well.
    @Override
    protected GuardedInvocation findGetMethod(final CallSiteDescriptor desc, final LinkRequest request, final String operator) {
        final String name = desc.getNameToken(2);

        // if str.length(), then let the bean linker handle it
        if ("length".equals(name) && "getMethod".equals(operator)) {
            return null;
        }

        return super.findGetMethod(desc, request, operator);
    }

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    // This is to provide array-like access to string characters without creating a NativeString wrapper.
    @Override
    protected GuardedInvocation findGetIndexMethod(final CallSiteDescriptor desc, final LinkRequest request) {
        final Object self = request.getReceiver();
        final Class<?> returnType = desc.getMethodType().returnType();

        if (returnType == Object.class && (self instanceof String || self instanceof ConsString)) {
            try {
                MethodHandle mh = MethodHandles.lookup().findStatic(NativeString.class, "get", desc.getMethodType());
                return new GuardedInvocation(mh, NashornGuards.getInstanceOf2Guard(String.class, ConsString.class));
            } catch (final NoSuchMethodException | IllegalAccessException e) {
                // Shouldn't happen. Fall back to super
            }
        }
        return super.findGetIndexMethod(desc, request);
    }

    @SuppressWarnings("unused")
    private static Object get(final Object self, final Object key) {
        final CharSequence cs = JSType.toCharSequence(self);
158
        final int index = ArrayIndex.getArrayIndex(key);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        if (index >= 0 && index < cs.length()) {
            return String.valueOf(cs.charAt(index));
        }
        return ((ScriptObject) Global.toObject(self)).get(key);
    }

    @SuppressWarnings("unused")
    private static Object get(final Object self, final double key) {
        if (isRepresentableAsInt(key)) {
            return get(self, (int)key);
        }
        return ((ScriptObject) Global.toObject(self)).get(key);
    }

    @SuppressWarnings("unused")
    private static Object get(final Object self, final long key) {
        final CharSequence cs = JSType.toCharSequence(self);
        if (key >= 0 && key < cs.length()) {
            return String.valueOf(cs.charAt((int)key));
        }
        return ((ScriptObject) Global.toObject(self)).get(key);
    }

    private static Object get(final Object self, final int key) {
        final CharSequence cs = JSType.toCharSequence(self);
        if (key >= 0 && key < cs.length()) {
            return String.valueOf(cs.charAt(key));
        }
        return ((ScriptObject) Global.toObject(self)).get(key);
    }

J
jlaskey 已提交
190 191 192
    // String characters can be accessed with array-like indexing..
    @Override
    public Object get(final Object key) {
193
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        if (index >= 0 && index < value.length()) {
            return String.valueOf(value.charAt(index));
        }
        return super.get(key);
    }

    @Override
    public Object get(final double key) {
        if (isRepresentableAsInt(key)) {
            return get((int)key);
        }
        return super.get(key);
    }

    @Override
    public Object get(final long key) {
        if (key >= 0 && key < value.length()) {
            return String.valueOf(value.charAt((int)key));
        }
        return super.get(key);
    }

    @Override
    public Object get(final int key) {
        if (key >= 0 && key < value.length()) {
            return String.valueOf(value.charAt(key));
        }
        return super.get(key);
    }

    @Override
    public int getInt(final Object key) {
        return JSType.toInt32(get(key));
    }

    @Override
    public int getInt(final double key) {
        return JSType.toInt32(get(key));
    }

    @Override
    public int getInt(final long key) {
        return JSType.toInt32(get(key));
    }

    @Override
    public int getInt(final int key) {
        return JSType.toInt32(get(key));
    }

    @Override
    public long getLong(final Object key) {
        return JSType.toUint32(get(key));
    }

    @Override
    public long getLong(final double key) {
        return JSType.toUint32(get(key));
    }

    @Override
    public long getLong(final long key) {
        return JSType.toUint32(get(key));
    }

    @Override
    public long getLong(final int key) {
        return JSType.toUint32(get(key));
    }

    @Override
    public double getDouble(final Object key) {
        return JSType.toNumber(get(key));
    }

    @Override
    public double getDouble(final double key) {
        return JSType.toNumber(get(key));
    }

    @Override
    public double getDouble(final long key) {
        return JSType.toNumber(get(key));
    }

    @Override
    public double getDouble(final int key) {
        return JSType.toNumber(get(key));
    }

    @Override
    public boolean has(final Object key) {
286
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
287 288 289 290 291 292 293 294 295 296
        return isValid(index) || super.has(key);
    }

    @Override
    public boolean has(final int key) {
        return isValid(key) || super.has(key);
    }

    @Override
    public boolean has(final long key) {
297
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
298 299 300 301 302
        return isValid(index) || super.has(key);
    }

    @Override
    public boolean has(final double key) {
303
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
304 305 306 307 308
        return isValid(index) || super.has(key);
    }

    @Override
    public boolean hasOwnProperty(final Object key) {
309
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
310 311 312 313 314 315 316 317 318 319
        return isValid(index) || super.hasOwnProperty(key);
    }

    @Override
    public boolean hasOwnProperty(final int key) {
        return isValid(key) || super.hasOwnProperty(key);
    }

    @Override
    public boolean hasOwnProperty(final long key) {
320
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
321 322 323 324 325
        return isValid(index) || super.hasOwnProperty(key);
    }

    @Override
    public boolean hasOwnProperty(final double key) {
326
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
327 328 329 330 331 332 333 334 335 336
        return isValid(index) || super.hasOwnProperty(key);
    }

    @Override
    public boolean delete(final int key, final boolean strict) {
        return checkDeleteIndex(key, strict)? false : super.delete(key, strict);
    }

    @Override
    public boolean delete(final long key, final boolean strict) {
337
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
338 339 340 341 342
        return checkDeleteIndex(index, strict)? false : super.delete(key, strict);
    }

    @Override
    public boolean delete(final double key, final boolean strict) {
343
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
344 345 346 347 348
        return checkDeleteIndex(index, strict)? false : super.delete(key, strict);
    }

    @Override
    public boolean delete(final Object key, final boolean strict) {
349
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
350 351 352 353 354 355
        return checkDeleteIndex(index, strict)? false : super.delete(key, strict);
    }

    private boolean checkDeleteIndex(final int index, final boolean strict) {
        if (isValid(index)) {
            if (strict) {
356
                throw typeError("cant.delete.property", Integer.toString(index), ScriptRuntime.safeToString(this));
J
jlaskey 已提交
357 358 359 360 361 362 363 364 365
            }
            return true;
        }

        return false;
    }

    @Override
    public Object getOwnPropertyDescriptor(final String key) {
366
        final int index = ArrayIndex.getArrayIndex(key);
J
jlaskey 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        if (index >= 0 && index < value.length()) {
            final Global global = Global.instance();
            return global.newDataDescriptor(String.valueOf(value.charAt(index)), false, true, false);
        }

        return super.getOwnPropertyDescriptor(key);
    }

    /**
     * return a List of own keys associated with the object.
     * @param all True if to include non-enumerable keys.
     * @return Array of keys.
     */
    @Override
    public String[] getOwnKeys(final boolean all) {
        final List<Object> keys = new ArrayList<>();

        // add string index keys
        for (int i = 0; i < value.length(); i++) {
            keys.add(JSType.toString(i));
        }

        // add super class properties
        keys.addAll(Arrays.asList(super.getOwnKeys(all)));
        return keys.toArray(new String[keys.size()]);
    }

    /**
     * ECMA 15.5.3 String.length
     * @param self self reference
     * @return     value of length property for string
     */
    @Getter(attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_WRITABLE | Attribute.NOT_CONFIGURABLE)
    public static Object length(final Object self) {
        return getCharSequence(self).length();
    }

    /**
     * ECMA 15.5.3.2 String.fromCharCode ( [ char0 [ , char1 [ , ... ] ] ] )
     * @param self  self reference
     * @param args  array of arguments to be interpreted as char
     * @return string with arguments translated to charcodes
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1, where = Where.CONSTRUCTOR)
    public static Object fromCharCode(final Object self, final Object... args) {
        final char[] buf = new char[args.length];
        int index = 0;
        for (final Object arg : args) {
            buf[index++] = (char)JSType.toUint16(arg);
        }
        return new String(buf);
    }

    /**
     * ECMA 15.5.3.2 - specialization for one char
     * @param self  self reference
     * @param value one argument to be interpreted as char
     * @return string with one charcode
     */
    @SpecializedFunction
    public static Object fromCharCode(final Object self, final Object value) {
        try {
            return "" + (char)JSType.toUint16(((Number)value).doubleValue());
        } catch (final ClassCastException e) {
            return fromCharCode(self, new Object[] { value });
        }
    }

    /**
     * ECMA 15.5.3.2 - specialization for one char of int type
     * @param self  self reference
     * @param value one argument to be interpreted as char
     * @return string with one charcode
     */
    @SpecializedFunction
    public static Object fromCharCode(final Object self, final int value) {
        return "" + (char)(value & 0xffff);
    }

    /**
     * ECMA 15.5.3.2 - specialization for one char of long type
     * @param self  self reference
     * @param value one argument to be interpreted as char
     * @return string with one charcode
     */
    @SpecializedFunction
    public static Object fromCharCode(final Object self, final long value) {
        return "" + (char)((int)value & 0xffff);
    }

    /**
     * ECMA 15.5.3.2 - specialization for one char of double type
     * @param self  self reference
     * @param value one argument to be interpreted as char
     * @return string with one charcode
     */
    @SpecializedFunction
    public static Object fromCharCode(final Object self, final double value) {
        return "" + (char)JSType.toUint16(value);
    }

    /**
     * ECMA 15.5.4.2 String.prototype.toString ( )
     * @param self self reference
     * @return self as string
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object toString(final Object self) {
        return getString(self);
    }

    /**
     * ECMA 15.5.4.3 String.prototype.valueOf ( )
     * @param self self reference
     * @return self as string
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object valueOf(final Object self) {
        return getString(self);
    }

    /**
     * ECMA 15.5.4.4 String.prototype.charAt (pos)
     * @param self self reference
     * @param pos  position in string
     * @return string representing the char at the given position
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object charAt(final Object self, final Object pos) {
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
        return charAt(self, JSType.toInteger(pos));
    }

    /**
     * ECMA 15.5.4.4 String.prototype.charAt (pos) - specialized version for double position
     * @param self self reference
     * @param pos  position in string
     * @return string representing the char at the given position
     */
    @SpecializedFunction
    public static String charAt(final Object self, final double pos) {
        return charAt(self, (int)pos);
    }

    /**
     * ECMA 15.5.4.4 String.prototype.charAt (pos) - specialized version for int position
     * @param self self reference
     * @param pos  position in string
     * @return string representing the char at the given position
     */
    @SpecializedFunction
    public static String charAt(final Object self, final int pos) {
        final String str = checkObjectToString(self);
        return (pos < 0 || pos >= str.length()) ? "" : String.valueOf(str.charAt(pos));
J
jlaskey 已提交
520 521 522 523 524 525 526 527 528 529
    }

    /**
     * ECMA 15.5.4.5 String.prototype.charCodeAt (pos)
     * @param self self reference
     * @param pos  position in string
     * @return number representing charcode at position
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object charCodeAt(final Object self, final Object pos) {
530 531
        return charCodeAt(self, JSType.toInteger(pos));
    }
J
jlaskey 已提交
532

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    /**
     * ECMA 15.5.4.5 String.prototype.charCodeAt (pos) - specialized version for double position
     * @param self self reference
     * @param pos  position in string
     * @return number representing charcode at position
     */
    @SpecializedFunction
    public static double charCodeAt(final Object self, final double pos) {
        return charCodeAt(self, (int) pos);
    }

    /**
     * ECMA 15.5.4.5 String.prototype.charCodeAt (pos) - specialized version for int position
     * @param self self reference
     * @param pos  position in string
     * @return number representing charcode at position
     */
    @SpecializedFunction
    public static double charCodeAt(final Object self, final int pos) {
        final String str = checkObjectToString(self);
        return (pos < 0 || pos >= str.length()) ? Double.NaN :  str.charAt(pos);
J
jlaskey 已提交
554 555 556 557 558 559 560 561 562 563
    }

    /**
     * ECMA 15.5.4.6 String.prototype.concat ( [ string1 [ , string2 [ , ... ] ] ] )
     * @param self self reference
     * @param args list of string to concatenate
     * @return concatenated string
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
    public static Object concat(final Object self, final Object... args) {
564
        CharSequence cs = checkObjectToString(self);
J
jlaskey 已提交
565 566
        if (args != null) {
            for (final Object obj : args) {
567
                cs = new ConsString(cs, JSType.toCharSequence(obj));
J
jlaskey 已提交
568 569
            }
        }
570
        return cs;
J
jlaskey 已提交
571 572 573 574 575 576 577 578 579 580 581
    }

    /**
     * ECMA 15.5.4.7 String.prototype.indexOf (searchString, position)
     * @param self   self reference
     * @param search string to search for
     * @param pos    position to start search
     * @return position of first match or -1
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
    public static Object indexOf(final Object self, final Object search, final Object pos) {
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
        final String str = checkObjectToString(self);
        return str.indexOf(JSType.toString(search), JSType.toInteger(pos));
    }

    /**
     * ECMA 15.5.4.7 String.prototype.indexOf (searchString, position) specialized for no position parameter
     * @param self   self reference
     * @param search string to search for
     * @return position of first match or -1
     */
    @SpecializedFunction
    public static int indexOf(final Object self, final Object search) {
        return indexOf(self, search, 0);
    }

    /**
     * ECMA 15.5.4.7 String.prototype.indexOf (searchString, position) specialized for double position parameter
     * @param self   self reference
     * @param search string to search for
     * @param pos    position to start search
     * @return position of first match or -1
     */
    @SpecializedFunction
    public static int indexOf(final Object self, final Object search, final double pos) {
        return indexOf(self, search, (int) pos);
    }

    /**
     * ECMA 15.5.4.7 String.prototype.indexOf (searchString, position) specialized for int position parameter
     * @param self   self reference
     * @param search string to search for
     * @param pos    position to start search
     * @return position of first match or -1
     */
    @SpecializedFunction
    public static int indexOf(final Object self, final Object search, final int pos) {
        return checkObjectToString(self).indexOf(JSType.toString(search), pos);
J
jlaskey 已提交
619 620 621 622 623 624 625 626 627 628 629 630
    }

    /**
     * ECMA 15.5.4.8 String.prototype.lastIndexOf (searchString, position)
     * @param self   self reference
     * @param search string to search for
     * @param pos    position to start search
     * @return last position of match or -1
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
    public static Object lastIndexOf(final Object self, final Object search, final Object pos) {

631
        final String str       = checkObjectToString(self);
J
jlaskey 已提交
632
        final String searchStr = JSType.toString(search);
633
        final int length       = str.length();
J
jlaskey 已提交
634

635
        int end;
J
jlaskey 已提交
636 637

        if (pos == UNDEFINED) {
638
            end = length;
J
jlaskey 已提交
639 640
        } else {
            final double numPos = JSType.toNumber(pos);
641 642 643 644 645 646
            end = Double.isNaN(numPos) ? length : (int)numPos;
            if (end < 0) {
                end = 0;
            } else if (end > length) {
                end = length;
            }
J
jlaskey 已提交
647 648
        }

649 650

        return str.lastIndexOf(searchStr, end);
J
jlaskey 已提交
651 652 653 654 655 656 657 658 659 660 661
    }

    /**
     * ECMA 15.5.4.9 String.prototype.localeCompare (that)
     * @param self self reference
     * @param that comparison object
     * @return result of locale sensitive comparison operation between {@code self} and {@code that}
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object localeCompare(final Object self, final Object that) {

662
        final String   str      = checkObjectToString(self);
663
        final Collator collator = Collator.getInstance(Global.getEnv()._locale);
J
jlaskey 已提交
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679

        collator.setStrength(Collator.IDENTICAL);
        collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);

        return (double)collator.compare(str, JSType.toString(that));
    }

    /**
     * ECMA 15.5.4.10 String.prototype.match (regexp)
     * @param self   self reference
     * @param regexp regexp expression
     * @return array of regexp matches
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object match(final Object self, final Object regexp) {

680
        final String str = checkObjectToString(self);
J
jlaskey 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726

        NativeRegExp nativeRegExp;
        if (regexp == UNDEFINED) {
            nativeRegExp = new NativeRegExp("");
        } else {
            nativeRegExp = Global.toRegExp(regexp);
        }

        if (!nativeRegExp.getGlobal()) {
            return nativeRegExp.exec(str);
        }

        nativeRegExp.setLastIndex(0);

        int previousLastIndex = 0;
        final List<Object> matches = new ArrayList<>();

        Object result;
        while ((result = nativeRegExp.exec(str)) != null) {
            final int thisIndex = nativeRegExp.getLastIndex();
            if (thisIndex == previousLastIndex) {
                nativeRegExp.setLastIndex(thisIndex + 1);
                previousLastIndex = thisIndex + 1;
            } else {
                previousLastIndex = thisIndex;
            }
            matches.add(((ScriptObject)result).get(0));
        }

        if (matches.isEmpty()) {
            return null;
        }

        return new NativeArray(matches.toArray());
    }

    /**
     * ECMA 15.5.4.11 String.prototype.replace (searchValue, replaceValue)
     * @param self        self reference
     * @param string      item to replace
     * @param replacement item to replace it with
     * @return string after replacement
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object replace(final Object self, final Object string, final Object replacement) {

727
        final String str = checkObjectToString(self);
J
jlaskey 已提交
728 729 730 731 732

        final NativeRegExp nativeRegExp;
        if (string instanceof NativeRegExp) {
            nativeRegExp = (NativeRegExp) string;
        } else {
H
hannesw 已提交
733
            nativeRegExp = NativeRegExp.flatRegExp(JSType.toString(string));
J
jlaskey 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
        }

        if (replacement instanceof ScriptFunction) {
            return nativeRegExp.replace(str, "", (ScriptFunction)replacement);
        }

        return nativeRegExp.replace(str, JSType.toString(replacement), null);
    }

    /**
     * ECMA 15.5.4.12 String.prototype.search (regexp)
     *
     * @param self    self reference
     * @param string  string to search for
     * @return offset where match occurred
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object search(final Object self, final Object string) {

753
        final String       str          = checkObjectToString(self);
J
jlaskey 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
        final NativeRegExp nativeRegExp = Global.toRegExp(string == UNDEFINED ? "" : string);

        return nativeRegExp.search(str);
    }

    /**
     * ECMA 15.5.4.13 String.prototype.slice (start, end)
     *
     * @param self  self reference
     * @param start start position for slice
     * @param end   end position for slice
     * @return sliced out substring
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object slice(final Object self, final Object start, final Object end) {

770 771 772 773 774 775
        final String str      = checkObjectToString(self);
        if (end == UNDEFINED) {
            return slice(str, JSType.toInteger(start));
        }
        return slice(str, JSType.toInteger(start), JSType.toInteger(end));
    }
J
jlaskey 已提交
776

777 778 779 780 781 782 783 784 785 786 787
    /**
     * ECMA 15.5.4.13 String.prototype.slice (start, end) specialized for single int parameter
     *
     * @param self  self reference
     * @param start start position for slice
     * @return sliced out substring
     */
    @SpecializedFunction
    public static Object slice(final Object self, final int start) {
        final String str = checkObjectToString(self);
        final int from = (start < 0) ? Math.max(str.length() + start, 0) : Math.min(start, str.length());
J
jlaskey 已提交
788

789 790
        return str.substring(from);
    }
J
jlaskey 已提交
791

792 793 794 795 796 797 798 799 800 801 802
    /**
     * ECMA 15.5.4.13 String.prototype.slice (start, end) specialized for single double parameter
     *
     * @param self  self reference
     * @param start start position for slice
     * @return sliced out substring
     */
    @SpecializedFunction
    public static Object slice(final Object self, final double start) {
        return slice(self, (int)start);
    }
J
jlaskey 已提交
803

804 805 806 807 808
    /**
     * ECMA 15.5.4.13 String.prototype.slice (start, end) specialized for two int parameters
     *
     * @param self  self reference
     * @param start start position for slice
809
     * @param end   end position for slice
810 811 812 813 814 815 816 817 818 819
     * @return sliced out substring
     */
    @SpecializedFunction
    public static Object slice(final Object self, final int start, final int end) {

        final String str = checkObjectToString(self);
        final int len    = str.length();

        final int from = (start < 0) ? Math.max(len + start, 0) : Math.min(start, len);
        final int to   = (end < 0)   ? Math.max(len + end, 0)   : Math.min(end, len);
J
jlaskey 已提交
820

821 822 823 824 825 826 827 828
        return str.substring(Math.min(from, to), to);
    }

    /**
     * ECMA 15.5.4.13 String.prototype.slice (start, end) specialized for two double parameters
     *
     * @param self  self reference
     * @param start start position for slice
829
     * @param end   end position for slice
830 831 832 833 834
     * @return sliced out substring
     */
    @SpecializedFunction
    public static Object slice(final Object self, final double start, final double end) {
        return slice(self, (int)start, (int)end);
J
jlaskey 已提交
835 836 837 838 839 840 841 842 843 844 845 846
    }

    /**
     * ECMA 15.5.4.14 String.prototype.split (separator, limit)
     *
     * @param self      self reference
     * @param separator separator for split
     * @param limit     limit for splits
     * @return array object in which splits have been placed
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object split(final Object self, final Object separator, final Object limit) {
847
        final String str = checkObjectToString(self);
848
        final long lim = (limit == UNDEFINED) ? JSType.MAX_UINT : JSType.toUint32(limit);
J
jlaskey 已提交
849 850

        if (separator == UNDEFINED) {
851
            return lim == 0 ? new NativeArray() : new NativeArray(new Object[]{str});
J
jlaskey 已提交
852 853 854 855 856 857
        }

        if (separator instanceof NativeRegExp) {
            return ((NativeRegExp) separator).split(str, lim);
        }

858 859 860 861 862
        // when separator is a string, it is treated as a literal search string to be used for splitting.
        return splitString(str, JSType.toString(separator), lim);
    }

    private static Object splitString(String str, String separator, long limit) {
863
        if (separator.isEmpty()) {
864 865 866
            final int length = (int) Math.min(str.length(), limit);
            final Object[] array = new Object[length];
            for (int i = 0; i < length; i++) {
867 868 869 870 871 872 873 874 875
                array[i] = String.valueOf(str.charAt(i));
            }
            return new NativeArray(array);
        }

        final List<String> elements = new LinkedList<>();
        final int strLength = str.length();
        final int sepLength = separator.length();
        int pos = 0;
876
        int n = 0;
877

878
        while (pos < strLength && n < limit) {
879 880 881 882 883
            int found = str.indexOf(separator, pos);
            if (found == -1) {
                break;
            }
            elements.add(str.substring(pos, found));
884
            n++;
885 886
            pos = found + sepLength;
        }
887
        if (pos <= strLength && n < limit) {
888 889 890 891
            elements.add(str.substring(pos));
        }

        return new NativeArray(elements.toArray());
J
jlaskey 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
    }

    /**
     * ECMA B.2.3 String.prototype.substr (start, length)
     *
     * @param self   self reference
     * @param start  start position
     * @param length length of section
     * @return substring given start and length of section
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object substr(final Object self, final Object start, final Object length) {
        final String str       = JSType.toString(self);
        final int    strLength = str.length();

        int intStart = JSType.toInteger(start);
        if (intStart < 0) {
            intStart = Math.max(intStart + strLength, 0);
        }

        final int intLen = Math.min(Math.max((length == UNDEFINED) ? Integer.MAX_VALUE : JSType.toInteger(length), 0), strLength - intStart);

        return intLen <= 0 ? "" : str.substring(intStart, intStart + intLen);
    }

    /**
     * ECMA 15.5.4.15 String.prototype.substring (start, end)
     *
     * @param self  self reference
     * @param start start position of substring
     * @param end   end position of substring
     * @return substring given start and end indexes
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object substring(final Object self, final Object start, final Object end) {

928 929 930 931 932 933
        final String str = checkObjectToString(self);
        if (end == UNDEFINED) {
            return substring(str, JSType.toInteger(start));
        }
        return substring(str, JSType.toInteger(start), JSType.toInteger(end));
    }
J
jlaskey 已提交
934

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
    /**
     * ECMA 15.5.4.15 String.prototype.substring (start, end) specialized for int start parameter
     *
     * @param self  self reference
     * @param start start position of substring
     * @return substring given start and end indexes
     */
    @SpecializedFunction
    public static String substring(final Object self, final int start) {
        final String str = checkObjectToString(self);
        if (start < 0) {
            return str;
        } else if (start >= str.length()) {
            return "";
        } else {
            return str.substring(start);
        }
    }

    /**
     * ECMA 15.5.4.15 String.prototype.substring (start, end) specialized for double start parameter
     *
     * @param self  self reference
     * @param start start position of substring
     * @return substring given start and end indexes
     */
    @SpecializedFunction
    public static String substring(final Object self, final double start) {
        return substring(self, (int)start);
    }
J
jlaskey 已提交
965

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    /**
     * ECMA 15.5.4.15 String.prototype.substring (start, end) specialized for int start and end parameters
     *
     * @param self  self reference
     * @param start start position of substring
     * @param end   end position of substring
     * @return substring given start and end indexes
     */
    @SpecializedFunction
    public static String substring(final Object self, final int start, final int end) {
        final String str = checkObjectToString(self);
        final int len = str.length();
        final int validStart = start < 0 ? 0 : (start > len ? len : start);
        final int validEnd   = end < 0 ? 0 : (end > len ? len : end);

        if (validStart < validEnd) {
            return str.substring(validStart, validEnd);
J
jlaskey 已提交
983
        }
984
        return str.substring(validEnd, validStart);
985 986 987 988 989 990 991 992 993 994 995 996 997
    }

    /**
     * ECMA 15.5.4.15 String.prototype.substring (start, end) specialized for double start and end parameters
     *
     * @param self  self reference
     * @param start start position of substring
     * @param end   end position of substring
     * @return substring given start and end indexes
     */
    @SpecializedFunction
    public static String substring(final Object self, final double start, final double end) {
        return substring(self, (int)start, (int)end);
J
jlaskey 已提交
998 999 1000 1001 1002 1003 1004 1005 1006
    }

    /**
     * ECMA 15.5.4.16 String.prototype.toLowerCase ( )
     * @param self self reference
     * @return string to lower case
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object toLowerCase(final Object self) {
1007
        return checkObjectToString(self).toLowerCase(Locale.ROOT);
J
jlaskey 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016
    }

    /**
     * ECMA 15.5.4.17 String.prototype.toLocaleLowerCase ( )
     * @param self self reference
     * @return string to locale sensitive lower case
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object toLocaleLowerCase(final Object self) {
1017
        return checkObjectToString(self).toLowerCase(Global.getEnv()._locale);
J
jlaskey 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026
    }

    /**
     * ECMA 15.5.4.18 String.prototype.toUpperCase ( )
     * @param self self reference
     * @return string to upper case
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object toUpperCase(final Object self) {
1027
        return checkObjectToString(self).toUpperCase(Locale.ROOT);
J
jlaskey 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036
    }

    /**
     * ECMA 15.5.4.19 String.prototype.toLocaleUpperCase ( )
     * @param self self reference
     * @return string to locale sensitive upper case
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object toLocaleUpperCase(final Object self) {
1037
        return checkObjectToString(self).toUpperCase(Global.getEnv()._locale);
J
jlaskey 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    }

    /**
     * ECMA 15.5.4.20 String.prototype.trim ( )
     * @param self self reference
     * @return string trimmed from whitespace
     */
    @Function(attributes = Attribute.NOT_ENUMERABLE)
    public static Object trim(final Object self) {

1048 1049
        final String str = checkObjectToString(self);
        final int len = str.length();
J
jlaskey 已提交
1050
        int start = 0;
1051
        int end   = len - 1;
J
jlaskey 已提交
1052

1053
        while (start <= end && ScriptRuntime.isJSWhitespace(str.charAt(start))) {
J
jlaskey 已提交
1054 1055
            start++;
        }
1056
        while (end > start && ScriptRuntime.isJSWhitespace(str.charAt(end))) {
J
jlaskey 已提交
1057 1058 1059
            end--;
        }

1060
        return start == 0 && end + 1 == len ? str : str.substring(start, end + 1);
J
jlaskey 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    }

    private static Object newObj(final Object self, final CharSequence str) {
        if (self instanceof ScriptObject) {
            return new NativeString(str, ((ScriptObject)self).getProto());
        }
        return new NativeString(str, Global.instance().getStringPrototype());
    }

    /**
     * ECMA 15.5.2.1 new String ( [ value ] )
     *
     * Constructor
     *
     * @param newObj is this constructor invoked with the new operator
     * @param self   self reference
     * @param args   arguments (a value)
     *
     * @return new NativeString, empty string if no args, extraneous args ignored
     */
    @Constructor(arity = 1)
    public static Object constructor(final boolean newObj, final Object self, final Object... args) {
        final CharSequence str = (args.length > 0) ? JSType.toCharSequence(args[0]) : "";
        return newObj ? newObj(self, str) : str.toString();
    }

    /**
     * ECMA 15.5.2.1 new String ( [ value ] ) - special version with no args
     *
     * Constructor
     *
     * @param newObj is this constructor invoked with the new operator
     * @param self   self reference
     *
     * @return new NativeString ("")
     */
    @SpecializedConstructor
    public static Object constructor(final boolean newObj, final Object self) {
        return newObj ? newObj(self, "") : "";
    }

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    /**
     * ECMA 15.5.2.1 new String ( [ value ] ) - special version with one arg
     *
     * Constructor
     *
     * @param newObj is this constructor invoked with the new operator
     * @param self   self reference
     * @param arg    argument
     *
     * @return new NativeString (arg)
     */
    @SpecializedConstructor
    public static Object constructor(final boolean newObj, final Object self, final Object arg) {
1115 1116
        final CharSequence str = JSType.toCharSequence(arg);
        return newObj ? newObj(self, str) : str.toString();
1117
    }
J
jlaskey 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

    /**
     * ECMA 15.5.2.1 new String ( [ value ] ) - special version with exactly one {@code int} arg
     *
     * Constructor
     *
     * @param newObj is this constructor invoked with the new operator
     * @param self   self reference
     * @param arg    the arg
     *
     * @return new NativeString containing the string representation of the arg
     */
    @SpecializedConstructor
    public static Object constructor(final boolean newObj, final Object self, final int arg) {
1132
        final String str = JSType.toString(arg);
J
jlaskey 已提交
1133 1134 1135 1136 1137 1138
        return newObj ? newObj(self, str) : str;
    }

    /**
     * Lookup the appropriate method for an invoke dynamic call.
     *
1139
     * @param request  the link request
J
jlaskey 已提交
1140 1141 1142
     * @param receiver receiver of call
     * @return Link to be invoked at call site.
     */
1143
    public static GuardedInvocation lookupPrimitive(final LinkRequest request, final Object receiver) {
J
jlaskey 已提交
1144
        final MethodHandle guard = NashornGuards.getInstanceOf2Guard(String.class, ConsString.class);
1145
        return PrimitiveLookup.lookupPrimitive(request, guard, new NativeString((CharSequence)receiver), WRAPFILTER);
J
jlaskey 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    }

    @SuppressWarnings("unused")
    private static NativeString wrapFilter(final Object receiver) {
        return new NativeString((CharSequence)receiver);
    }

    private static CharSequence getCharSequence(final Object self) {
        if (self instanceof String || self instanceof ConsString) {
            return (CharSequence)self;
        } else if (self instanceof NativeString) {
            return ((NativeString)self).getValue();
        } else if (self != null && self == Global.instance().getStringPrototype()) {
            return "";
        } else {
1161
            throw typeError("not.a.string", ScriptRuntime.safeToString(self));
J
jlaskey 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        }
    }

    private static String getString(final Object self) {
        if (self instanceof String) {
            return (String)self;
        } else if (self instanceof ConsString) {
            return self.toString();
        } else if (self instanceof NativeString) {
            return ((NativeString)self).getStringValue();
        } else if (self != null && self == Global.instance().getStringPrototype()) {
            return "";
        } else {
1175
            throw typeError( "not.a.string", ScriptRuntime.safeToString(self));
J
jlaskey 已提交
1176 1177 1178
        }
    }

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
    /**
     * Combines ECMA 9.10 CheckObjectCoercible and ECMA 9.8 ToString with a shortcut for strings.
     *
     * @param self the object
     * @return the object as string
     */
    private static String checkObjectToString(final Object self) {
        if (self instanceof String) {
            return (String)self;
        } else if (self instanceof ConsString) {
            return self.toString();
        } else {
            Global.checkObjectCoercible(self);
            return JSType.toString(self);
        }
    }

J
jlaskey 已提交
1196 1197 1198 1199 1200 1201 1202 1203
    private boolean isValid(final int key) {
        return key >= 0 && key < value.length();
    }

    private static MethodHandle findWrapFilter() {
        try {
            return MethodHandles.lookup().findStatic(NativeString.class, "wrapFilter", MH.type(NativeString.class, Object.class));
        } catch (final NoSuchMethodException | IllegalAccessException e) {
1204
            throw new MethodHandleFactory.LookupException(e);
J
jlaskey 已提交
1205 1206 1207
        }
    }
}