symbols.js 16.7 KB
Newer Older
1 2 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
// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

28
// Flags: --expose-gc --allow-natives-syntax
29 30 31

var symbols = []

32 33 34 35 36 37 38 39 40 41 42

// Returns true if the string is a valid
// serialization of Symbols added to the 'symbols'
// array. Adjust if you extend 'symbols' with other
// values.
function isValidSymbolString(s) {
  return ["Symbol(66)", "Symbol()"].indexOf(s) >= 0;
}


// Test different forms of constructor calls.
43
function TestNew() {
44 45
  function indirectSymbol() { return Symbol() }
  function indirect() { return indirectSymbol() }
46
  for (var i = 0; i < 2; ++i) {
47
    %PrepareFunctionForOptimization(indirect);
48 49
    for (var j = 0; j < 5; ++j) {
      symbols.push(Symbol())
50 51 52
      symbols.push(Symbol(undefined))
      symbols.push(Symbol("66"))
      symbols.push(Symbol(66))
53 54
      symbols.push(Symbol().valueOf())
      symbols.push(indirect())
55 56 57 58
    }
    %OptimizeFunctionOnNextCall(indirect)
    indirect()  // Call once before GC throws away type feedback.
    gc()        // Promote existing symbols and then allocate some more.
59
  }
60 61
  assertThrows(function () { Symbol(Symbol()) }, TypeError)
  assertThrows(function () { new Symbol(66) }, TypeError)
62 63 64 65 66 67
}
TestNew()


function TestType() {
  for (var i in symbols) {
68 69
    assertEquals("symbol", typeof symbols[i])
    assertTrue(typeof symbols[i] === "symbol")
70
    assertFalse(%SymbolIsPrivate(symbols[i]))
71 72 73 74 75
  }
}
TestType()


76 77 78 79 80 81 82 83 84 85 86
function TestPrototype() {
  assertSame(Object.prototype, Symbol.prototype.__proto__)
  assertSame(Symbol.prototype, Symbol().__proto__)
  assertSame(Symbol.prototype, Object(Symbol()).__proto__)
  for (var i in symbols) {
    assertSame(Symbol.prototype, symbols[i].__proto__)
  }
}
TestPrototype()


87
function TestConstructor() {
88
  assertEquals(0, Symbol.length);
89
  assertSame(Function.prototype, Symbol.__proto__)
90 91 92 93 94 95 96 97 98 99 100 101
  assertFalse(Object === Symbol.prototype.constructor)
  assertFalse(Symbol === Object.prototype.constructor)
  assertSame(Symbol, Symbol.prototype.constructor)
  assertSame(Symbol, Symbol().__proto__.constructor)
  assertSame(Symbol, Object(Symbol()).__proto__.constructor)
  for (var i in symbols) {
    assertSame(Symbol, symbols[i].__proto__.constructor)
  }
}
TestConstructor()


102
function TestValueOf() {
103
  for (var i in symbols) {
104
    assertTrue(symbols[i] === Object(symbols[i]).valueOf())
105
    assertTrue(symbols[i] === symbols[i].valueOf())
106
    assertTrue(Symbol.prototype.valueOf.call(Object(symbols[i])) === symbols[i])
107
    assertTrue(Symbol.prototype.valueOf.call(symbols[i]) === symbols[i])
108 109
  }
}
110
TestValueOf()
111 112


113 114
function TestToString() {
  for (var i in symbols) {
115 116
    assertThrows(function() { new String(symbols[i]) }, TypeError)
    assertEquals(symbols[i].toString(), String(symbols[i]))
117
    assertThrows(function() { symbols[i] + "" }, TypeError)
118
    assertThrows(function() { String(Object(symbols[i])) }, TypeError)
119 120 121 122 123 124
    assertTrue(isValidSymbolString(symbols[i].toString()))
    assertTrue(isValidSymbolString(Object(symbols[i]).toString()))
    assertTrue(
      isValidSymbolString(Symbol.prototype.toString.call(symbols[i])))
    assertEquals(
      "[object Symbol]", Object.prototype.toString.call(symbols[i]))
125 126 127 128 129 130 131
  }
}
TestToString()


function TestToBoolean() {
  for (var i in symbols) {
132 133
    assertTrue(Boolean(Object(symbols[i])))
    assertFalse(!Object(symbols[i]))
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    assertTrue(Boolean(symbols[i]).valueOf())
    assertFalse(!symbols[i])
    assertTrue(!!symbols[i])
    assertTrue(symbols[i] && true)
    assertFalse(!symbols[i] && false)
    assertTrue(!symbols[i] || true)
    assertEquals(1, symbols[i] ? 1 : 2)
    assertEquals(2, !symbols[i] ? 1 : 2)
    if (!symbols[i]) assertUnreachable();
    if (symbols[i]) {} else assertUnreachable();
  }
}
TestToBoolean()


function TestToNumber() {
  for (var i in symbols) {
151 152
    assertThrows(function() { Number(Object(symbols[i])) }, TypeError)
    assertThrows(function() { +Object(symbols[i]) }, TypeError)
153 154
    assertThrows(function() { Number(symbols[i]) }, TypeError)
    assertThrows(function() { symbols[i] + 0 }, TypeError)
155 156 157 158 159
  }
}
TestToNumber()


160
function TestEquality() {
161
  // Every symbol should equal itself, and non-strictly equal its wrapper.
162 163 164 165 166 167
  for (var i in symbols) {
    assertSame(symbols[i], symbols[i])
    assertEquals(symbols[i], symbols[i])
    assertTrue(Object.is(symbols[i], symbols[i]))
    assertTrue(symbols[i] === symbols[i])
    assertTrue(symbols[i] == symbols[i])
168 169
    assertFalse(symbols[i] === Object(symbols[i]))
    assertFalse(Object(symbols[i]) === symbols[i])
170 171
    assertTrue(symbols[i] == Object(symbols[i]))
    assertTrue(Object(symbols[i]) == symbols[i])
172 173 174 175 176 177
    assertTrue(symbols[i] === symbols[i].valueOf())
    assertTrue(symbols[i].valueOf() === symbols[i])
    assertTrue(symbols[i] == symbols[i].valueOf())
    assertTrue(symbols[i].valueOf() == symbols[i])
    assertFalse(Object(symbols[i]) === Object(symbols[i]))
    assertEquals(Object(symbols[i]).valueOf(), Object(symbols[i]).valueOf())
178 179 180 181 182 183 184 185 186
  }

  // All symbols should be distinct.
  for (var i = 0; i < symbols.length; ++i) {
    for (var j = i + 1; j < symbols.length; ++j) {
      assertFalse(Object.is(symbols[i], symbols[j]))
      assertFalse(symbols[i] === symbols[j])
      assertFalse(symbols[i] == symbols[j])
    }
187 188 189 190 191 192 193 194 195 196 197
  }

  // Symbols should not be equal to any other value (and the test terminates).
  var values = [347, 1.275, NaN, "string", null, undefined, {}, function() {}]
  for (var i in symbols) {
    for (var j in values) {
      assertFalse(symbols[i] === values[j])
      assertFalse(values[j] === symbols[i])
      assertFalse(symbols[i] == values[j])
      assertFalse(values[j] == symbols[i])
    }
198 199 200 201 202 203 204
  }
}
TestEquality()


function TestGet() {
  for (var i in symbols) {
205
    assertTrue(isValidSymbolString(symbols[i].toString()))
206
    assertEquals(symbols[i], symbols[i].valueOf())
207 208 209 210 211 212 213 214 215 216 217 218
    assertEquals(undefined, symbols[i].a)
    assertEquals(undefined, symbols[i]["a" + "b"])
    assertEquals(undefined, symbols[i]["" + "1"])
    assertEquals(undefined, symbols[i][62])
  }
}
TestGet()


function TestSet() {
  for (var i in symbols) {
    symbols[i].toString = 0
219
    assertTrue(isValidSymbolString(symbols[i].toString()))
220 221
    symbols[i].valueOf = 0
    assertEquals(symbols[i], symbols[i].valueOf())
222 223 224 225 226 227 228 229 230 231 232
    symbols[i].a = 0
    assertEquals(undefined, symbols[i].a)
    symbols[i]["a" + "b"] = 0
    assertEquals(undefined, symbols[i]["a" + "b"])
    symbols[i][62] = 0
    assertEquals(undefined, symbols[i][62])
  }
}
TestSet()


233 234 235 236 237 238 239 240 241 242 243 244
// Test Symbol wrapping/boxing over non-builtins.
Symbol.prototype.getThisProto = function () {
  return Object.getPrototypeOf(this);
}
function TestCall() {
  for (var i in symbols) {
    assertTrue(symbols[i].getThisProto() === Symbol.prototype)
  }
}
TestCall()


245 246
function TestCollections() {
  var set = new Set
247
  var map = new Map
248
  for (var i in symbols) {
249
    set.add(symbols[i])
250 251
    map.set(symbols[i], i)
  }
252 253
  assertEquals(symbols.length, set.size)
  assertEquals(symbols.length, map.size)
254
  for (var i in symbols) {
255
    assertTrue(set.has(symbols[i]))
256 257 258
    assertTrue(map.has(symbols[i]))
    assertEquals(i, map.get(symbols[i]))
  }
259 260 261 262 263 264
  for (var i in symbols) {
    assertTrue(set.delete(symbols[i]))
    assertTrue(map.delete(symbols[i]))
  }
  assertEquals(0, set.size)
  assertEquals(0, map.size)
265
}
266
TestCollections()
267 268 269 270



function TestKeySet(obj) {
271
  assertTrue(%HasFastProperties(obj))
272 273 274
  // Set the even symbols via assignment.
  for (var i = 0; i < symbols.length; i += 2) {
    obj[symbols[i]] = i
275 276
    // Object should remain in fast mode until too many properties were added.
    assertTrue(%HasFastProperties(obj) || i >= 30)
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  }
}


function TestKeyDefine(obj) {
  // Set the odd symbols via defineProperty (as non-enumerable).
  for (var i = 1; i < symbols.length; i += 2) {
    Object.defineProperty(obj, symbols[i], {value: i, configurable: true})
  }
}


function TestKeyGet(obj) {
  var obj2 = Object.create(obj)
  for (var i in symbols) {
    assertEquals(i|0, obj[symbols[i]])
    assertEquals(i|0, obj2[symbols[i]])
  }
}


298
function TestKeyHas(obj) {
299 300 301 302 303 304 305 306
  for (var i in symbols) {
    assertTrue(symbols[i] in obj)
    assertTrue(Object.hasOwnProperty.call(obj, symbols[i]))
  }
}


function TestKeyEnum(obj) {
307
  for (var name in obj) {
308
    assertEquals("string", typeof name)
309 310 311 312
  }
}


313
function TestKeyNames(obj) {
314
  assertEquals(0, Object.keys(obj).length)
315 316

  var names = Object.getOwnPropertyNames(obj)
317 318
  for (var i in names) {
    assertEquals("string", typeof names[i])
319
  }
320 321 322
}


323 324 325 326 327 328 329 330 331
function TestGetOwnPropertySymbols(obj) {
  var syms = Object.getOwnPropertySymbols(obj)
  assertEquals(syms.length, symbols.length)
  for (var i in syms) {
    assertEquals("symbol", typeof syms[i])
  }
}


332 333
function TestKeyDescriptor(obj) {
  for (var i in symbols) {
334
    var desc = Object.getOwnPropertyDescriptor(obj, symbols[i])
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    assertEquals(i|0, desc.value)
    assertTrue(desc.configurable)
    assertEquals(i % 2 == 0, desc.writable)
    assertEquals(i % 2 == 0, desc.enumerable)
    assertEquals(i % 2 == 0,
        Object.prototype.propertyIsEnumerable.call(obj, symbols[i]))
  }
}


function TestKeyDelete(obj) {
  for (var i in symbols) {
    delete obj[symbols[i]]
  }
  for (var i in symbols) {
    assertEquals(undefined, Object.getOwnPropertyDescriptor(obj, symbols[i]))
  }
}


355
var objs = [{}, [], Object.create({}), Object(1), new Map, function(){}]
356 357 358 359 360 361 362 363

for (var i in objs) {
  var obj = objs[i]
  TestKeySet(obj)
  TestKeyDefine(obj)
  TestKeyGet(obj)
  TestKeyHas(obj)
  TestKeyEnum(obj)
364
  TestKeyNames(obj)
365
  TestGetOwnPropertySymbols(obj)
366 367 368
  TestKeyDescriptor(obj)
  TestKeyDelete(obj)
}
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
function TestDefineProperties() {
  var properties = {}
  for (var i in symbols) {
    Object.defineProperty(
        properties, symbols[i], {value: {value: i}, enumerable: i % 2 === 0})
  }
  var o = Object.defineProperties({}, properties)
  for (var i in symbols) {
    assertEquals(i % 2 === 0, symbols[i] in o)
  }
}
TestDefineProperties()


function TestCreate() {
  var properties = {}
  for (var i in symbols) {
    Object.defineProperty(
      properties, symbols[i], {value: {value: i}, enumerable: i % 2 === 0})
  }
  var o = Object.create(Object.prototype, properties)
  for (var i in symbols) {
    assertEquals(i % 2 === 0, symbols[i] in o)
  }
}
TestCreate()


399 400 401 402 403 404 405 406 407
function TestCachedKeyAfterScavenge() {
  gc();
  // Keyed property lookup are cached.  Hereby we assume that the keys are
  // tenured, so that we only have to clear the cache between mark compacts,
  // but not between scavenges.  This must also apply for symbol keys.
  var key = Symbol("key");
  var a = {};
  a[key] = "abc";

408
  for (var i = 0; i < 100000; i++) {
409 410 411 412
    a[key] += "a";  // Allocations cause a scavenge.
  }
}
TestCachedKeyAfterScavenge();
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


function TestGetOwnPropertySymbolsWithProto() {
  // We need to be have fast properties to have insertion order for property
  // keys. The current limit is currently 30 properties.
  var syms = symbols.slice(0, 30);
  var proto = {}
  var object = Object.create(proto)
  for (var i = 0; i < syms.length; i++) {
    // Even on object, odd on proto.
    if (i % 2) {
      proto[syms[i]] = i
    } else {
      object[syms[i]] = i
    }
  }

  assertTrue(%HasFastProperties(object));

  var objectOwnSymbols = Object.getOwnPropertySymbols(object)
  assertEquals(objectOwnSymbols.length, syms.length / 2)

  for (var i = 0; i < objectOwnSymbols.length; i++) {
    assertEquals(objectOwnSymbols[i], syms[i * 2])
  }
}
TestGetOwnPropertySymbolsWithProto()


442 443
function TestWellKnown() {
  var symbols = [
444
    "hasInstance",
445
    // TODO(rossberg): reactivate once implemented.
446
    // "isConcatSpreadable", "isRegExp",
447
    "iterator", /* "toStringTag", */ "unscopables"
448
  ]
449

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
  for (var i in symbols) {
    var name = symbols[i]
    var desc = Object.getOwnPropertyDescriptor(Symbol, name)
    assertSame("symbol", typeof desc.value)
    assertSame("Symbol(Symbol." + name + ")", desc.value.toString())
    assertFalse(desc.writable)
    assertFalse(desc.configurable)
    assertFalse(desc.enumerable)

    assertFalse(Symbol.for("Symbol." + name) === desc.value)
    assertTrue(Symbol.keyFor(desc.value) === undefined)
  }
}
TestWellKnown()


function TestRegistry() {
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 496 497
  var symbol1 = Symbol.for("x1")
  var symbol2 = Symbol.for("x2")
  assertFalse(symbol1 === symbol2)

  assertSame(symbol1, Symbol.for("x1"))
  assertSame(symbol2, Symbol.for("x2"))
  assertSame("x1", Symbol.keyFor(symbol1))
  assertSame("x2", Symbol.keyFor(symbol2))

  assertSame(Symbol.for("1"), Symbol.for(1))
  assertThrows(function() { Symbol.keyFor("bla") }, TypeError)
  assertThrows(function() { Symbol.keyFor({}) }, TypeError)

  var realm = Realm.create()
  assertFalse(Symbol === Realm.eval(realm, "Symbol"))
  assertFalse(Symbol.for === Realm.eval(realm, "Symbol.for"))
  assertFalse(Symbol.keyFor === Realm.eval(realm, "Symbol.keyFor"))
  assertSame(Symbol.create, Realm.eval(realm, "Symbol.create"))
  assertSame(Symbol.iterator, Realm.eval(realm, "Symbol.iterator"))

  assertSame(symbol1, Realm.eval(realm, "Symbol.for")("x1"))
  assertSame(symbol1, Realm.eval(realm, "Symbol.for('x1')"))
  assertSame("x1", Realm.eval(realm, "Symbol.keyFor")(symbol1))
  Realm.shared = symbol1
  assertSame("x1", Realm.eval(realm, "Symbol.keyFor(Realm.shared)"))

  var symbol3 = Realm.eval(realm, "Symbol.for('x3')")
  assertFalse(symbol1 === symbol3)
  assertFalse(symbol2 === symbol3)
  assertSame(symbol3, Symbol.for("x3"))
  assertSame("x3", Symbol.keyFor(symbol3))
498
}
499
TestRegistry()
500 501 502 503 504 505 506 507


function TestGetOwnPropertySymbolsOnPrimitives() {
  assertEquals(Object.getOwnPropertySymbols(true), []);
  assertEquals(Object.getOwnPropertySymbols(5000), []);
  assertEquals(Object.getOwnPropertySymbols("OK"), []);
}
TestGetOwnPropertySymbolsOnPrimitives();
508 509 510


function TestComparison() {
511 512 513 514 515 516 517 518 519 520 521 522
  function lt() { var a = Symbol(); var b = Symbol(); a < b; }
  function gt() { var a = Symbol(); var b = Symbol(); a > b; }
  function le() { var a = Symbol(); var b = Symbol(); a <= b; }
  function ge() { var a = Symbol(); var b = Symbol(); a >= b; }
  function lt_same() { var a = Symbol(); a < a; }
  function gt_same() { var a = Symbol(); a > a; }
  function le_same() { var a = Symbol(); a <= a; }
  function ge_same() { var a = Symbol(); a >= a; }

  var throwFuncs = [lt, gt, le, ge, lt_same, gt_same, le_same, ge_same];

  for (var f of throwFuncs) {
523
    %PrepareFunctionForOptimization(f);
524 525 526 527 528
    assertThrows(f, TypeError);
    %OptimizeFunctionOnNextCall(f);
    assertThrows(f, TypeError);
    assertThrows(f, TypeError);
  }
529 530
}
TestComparison();
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553


// Make sure that throws occur in the context of the Symbol function.
function TestContext() {
  var r = Realm.create();
  var rSymbol = Realm.eval(r, "Symbol");
  var rError = Realm.eval(r, "TypeError");

  function verifier(symbol, error) {
    try {
      new symbol();
    } catch(e) {
      return e.__proto__ === error.__proto__;
    }
    assertTrue(false);  // should never get here.
  }

  assertTrue(verifier(Symbol, TypeError()));
  assertTrue(verifier(rSymbol, rError()));
  assertFalse(verifier(Symbol, rError()));
  assertFalse(verifier(rSymbol, TypeError()));
}
TestContext();
554 555 556 557


function TestStringify(expected, input) {
  assertEquals(expected, JSON.stringify(input));
558 559 560
  assertEquals(expected, JSON.stringify(input, (key, value) => value));
  assertEquals(JSON.stringify(input, null, "="),
               JSON.stringify(input, (key, value) => value, "="));
561 562 563 564 565 566 567 568
}

TestStringify(undefined, Symbol("a"));
TestStringify('[{}]', [Object(Symbol())]);
var symbol_wrapper = Object(Symbol("a"))
TestStringify('{}', symbol_wrapper);
symbol_wrapper.a = 1;
TestStringify('{"a":1}', symbol_wrapper);