v8natives.js 55.5 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
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 28 29
// 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.

// This file relies on the fact that the following declarations have been made
// in runtime.js:
30 31 32 33 34
// var $Object = global.Object;
// var $Boolean = global.Boolean;
// var $Number = global.Number;
// var $Function = global.Function;
// var $Array = global.Array;
35 36
//
// in math.js:
37
// var $floor = MathFloor
38

39 40
var $isNaN = GlobalIsNaN;
var $isFinite = GlobalIsFinite;
41

42
// ----------------------------------------------------------------------------
43

44 45
// Helper function used to install functions on objects.
function InstallFunctions(object, attributes, functions) {
46
  if (functions.length >= 8) {
47
    %OptimizeObjectForAddingMultipleProperties(object, functions.length >> 1);
48
  }
49 50 51 52
  for (var i = 0; i < functions.length; i += 2) {
    var key = functions[i];
    var f = functions[i + 1];
    %FunctionSetName(f, key);
53
    %FunctionRemovePrototype(f);
54
    %SetProperty(object, key, f, attributes);
55
    %SetNativeFlag(f);
56
  }
57
  %ToFastProperties(object);
58
}
59

60

61
// Helper function to install a getter-only accessor property.
62 63 64 65 66 67 68 69
function InstallGetter(object, name, getter) {
  %FunctionSetName(getter, name);
  %FunctionRemovePrototype(getter);
  %DefineOrRedefineAccessorProperty(object, name, getter, null, DONT_ENUM);
  %SetNativeFlag(getter);
}


70 71 72 73 74 75 76 77 78 79 80 81
// Helper function to install a getter/setter accessor property.
function InstallGetterSetter(object, name, getter, setter) {
  %FunctionSetName(getter, name);
  %FunctionSetName(setter, name);
  %FunctionRemovePrototype(getter);
  %FunctionRemovePrototype(setter);
  %DefineOrRedefineAccessorProperty(object, name, getter, setter, DONT_ENUM);
  %SetNativeFlag(getter);
  %SetNativeFlag(setter);
}


82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
// Helper function for installing constant properties on objects.
function InstallConstants(object, constants) {
  if (constants.length >= 4) {
    %OptimizeObjectForAddingMultipleProperties(object, constants.length >> 1);
  }
  var attributes = DONT_ENUM | DONT_DELETE | READ_ONLY;
  for (var i = 0; i < constants.length; i += 2) {
    var name = constants[i];
    var k = constants[i + 1];
    %SetProperty(object, name, k, attributes);
  }
  %ToFastProperties(object);
}


97
// Prevents changes to the prototype of a built-in function.
98 99 100 101 102 103 104 105 106 107 108 109 110 111
// The "prototype" property of the function object is made non-configurable,
// and the prototype object is made non-extensible. The latter prevents
// changing the __proto__ property.
function SetUpLockedPrototype(constructor, fields, methods) {
  %CheckIsBootstrapping();
  var prototype = constructor.prototype;
  // Install functions first, because this function is used to initialize
  // PropertyDescriptor itself.
  var property_count = (methods.length >> 1) + (fields ? fields.length : 0);
  if (property_count >= 4) {
    %OptimizeObjectForAddingMultipleProperties(prototype, property_count);
  }
  if (fields) {
    for (var i = 0; i < fields.length; i++) {
112
      %SetProperty(prototype, fields[i], UNDEFINED, DONT_ENUM | DONT_DELETE);
113 114 115 116 117 118 119 120
    }
  }
  for (var i = 0; i < methods.length; i += 2) {
    var key = methods[i];
    var f = methods[i + 1];
    %SetProperty(prototype, key, f, DONT_ENUM | DONT_DELETE | READ_ONLY);
    %SetNativeFlag(f);
  }
121
  %SetPrototype(prototype, null);
122 123 124 125
  %ToFastProperties(prototype);
}


126
// ----------------------------------------------------------------------------
127 128 129


// ECMA 262 - 15.1.4
130
function GlobalIsNaN(number) {
131 132
  if (!IS_NUMBER(number)) number = NonNumberToNumber(number);
  return NUMBER_IS_NAN(number);
133
}
134 135 136


// ECMA 262 - 15.1.5
137
function GlobalIsFinite(number) {
138
  if (!IS_NUMBER(number)) number = NonNumberToNumber(number);
139
  return NUMBER_IS_FINITE(number);
140
}
141 142 143


// ECMA-262 - 15.1.2.2
144
function GlobalParseInt(string, radix) {
145
  if (IS_UNDEFINED(radix) || radix === 10 || radix === 0) {
146 147 148 149 150 151
    // Some people use parseInt instead of Math.floor.  This
    // optimization makes parseInt on a Smi 12 times faster (60ns
    // vs 800ns).  The following optimization makes parseInt on a
    // non-Smi number 9 times faster (230ns vs 2070ns).  Together
    // they make parseInt on a string 1.4% slower (274ns vs 270ns).
    if (%_IsSmi(string)) return string;
152
    if (IS_NUMBER(string) &&
153 154
        ((0.01 < string && string < 1e9) ||
            (-1e9 < string && string < -0.01))) {
155 156
      // Truncate number.
      return string | 0;
157
    }
158
    string = TO_STRING_INLINE(string);
159
    radix = radix | 0;
160
  } else {
161 162
    // The spec says ToString should be evaluated before ToInt32.
    string = TO_STRING_INLINE(string);
163
    radix = TO_INT32(radix);
164
    if (!(radix == 0 || (2 <= radix && radix <= 36))) {
165
      return NAN;
166
    }
167
  }
168

169 170 171 172 173
  if (%_HasCachedArrayIndex(string) &&
      (radix == 0 || radix == 10)) {
    return %_GetCachedArrayIndex(string);
  }
  return %StringParseInt(string, radix);
174
}
175 176 177


// ECMA-262 - 15.1.2.3
178
function GlobalParseFloat(string) {
179 180 181
  string = TO_STRING_INLINE(string);
  if (%_HasCachedArrayIndex(string)) return %_GetCachedArrayIndex(string);
  return %StringParseFloat(string);
182 183
}

184

185 186 187
function GlobalEval(x) {
  if (!IS_STRING(x)) return x;

188 189 190
  // For consistency with JSC we require the global object passed to
  // eval to be the global object from which 'eval' originated. This
  // is not mandated by the spec.
191 192
  // We only throw if the global has been detached, since we need the
  // receiver as this-value for the call.
193
  if (!%IsAttachedGlobal(global)) {
194
    throw new $EvalError('The "this" value passed to eval must ' +
195
                         'be the global object from which eval originated');
196
  }
197

198 199
  var global_receiver = %GlobalReceiver(global);

200
  var f = %CompileString(x, false);
201 202
  if (!IS_FUNCTION(f)) return f;

203
  return %_CallFunction(global_receiver, f);
204 205 206 207 208
}


// ----------------------------------------------------------------------------

209 210 211
// Set up global object.
function SetUpGlobal() {
  %CheckIsBootstrapping();
212

213 214
  var attributes = DONT_ENUM | DONT_DELETE | READ_ONLY;

215
  // ECMA 262 - 15.1.1.1.
216
  %SetProperty(global, "NaN", NAN, attributes);
217 218

  // ECMA-262 - 15.1.1.2.
219
  %SetProperty(global, "Infinity", INFINITY, attributes);
220 221

  // ECMA-262 - 15.1.1.3.
222
  %SetProperty(global, "undefined", UNDEFINED, attributes);
223

224
  // Set up non-enumerable function on the global object.
225 226 227 228 229
  InstallFunctions(global, DONT_ENUM, $Array(
    "isNaN", GlobalIsNaN,
    "isFinite", GlobalIsFinite,
    "parseInt", GlobalParseInt,
    "parseFloat", GlobalParseFloat,
230
    "eval", GlobalEval
231 232 233
  ));
}

234
SetUpGlobal();
235 236 237 238 239


// ----------------------------------------------------------------------------
// Object

240 241
// ECMA-262 - 15.2.4.2
function ObjectToString() {
242 243
  if (IS_UNDEFINED(this) && !IS_UNDETECTABLE(this)) return "[object Undefined]";
  if (IS_NULL(this)) return "[object Null]";
244
  return "[object " + %_ClassOf(ToObject(this)) + "]";
245
}
246 247


248 249
// ECMA-262 - 15.2.4.3
function ObjectToLocaleString() {
250
  CHECK_OBJECT_COERCIBLE(this, "Object.prototype.toLocaleString");
251
  return this.toString();
252
}
253 254


255 256
// ECMA-262 - 15.2.4.4
function ObjectValueOf() {
257
  return ToObject(this);
258
}
259 260


261 262
// ECMA-262 - 15.2.4.5
function ObjectHasOwnProperty(V) {
263
  if (%IsJSProxy(this)) {
264 265 266
    // TODO(rossberg): adjust once there is a story for symbols vs proxies.
    if (IS_SYMBOL(V)) return false;

267
    var handler = %GetHandler(this);
268
    return CallTrap1(handler, "hasOwn", DerivedHasOwnTrap, ToName(V));
269
  }
270
  return %HasLocalProperty(TO_OBJECT_INLINE(this), ToName(V));
271
}
272 273


274 275
// ECMA-262 - 15.2.4.6
function ObjectIsPrototypeOf(V) {
276
  CHECK_OBJECT_COERCIBLE(this, "Object.prototype.isPrototypeOf");
277
  if (!IS_SPEC_OBJECT(V)) return false;
278
  return %IsInPrototypeChain(this, V);
279
}
280 281


282 283
// ECMA-262 - 15.2.4.6
function ObjectPropertyIsEnumerable(V) {
284
  var P = ToName(V);
285
  if (%IsJSProxy(this)) {
286 287 288
    // TODO(rossberg): adjust once there is a story for symbols vs proxies.
    if (IS_SYMBOL(V)) return false;

289 290 291 292
    var desc = GetOwnProperty(this, P);
    return IS_UNDEFINED(desc) ? false : desc.isEnumerable();
  }
  return %IsPropertyEnumerable(ToObject(this), P);
293
}
294 295 296


// Extensions for providing property getters and setters.
297
function ObjectDefineGetter(name, fun) {
298 299 300
  var receiver = this;
  if (receiver == null && !IS_UNDETECTABLE(receiver)) {
    receiver = %GlobalReceiver(global);
301
  }
302
  if (!IS_SPEC_FUNCTION(fun)) {
303 304
    throw new $TypeError(
        'Object.prototype.__defineGetter__: Expecting function');
305
  }
306 307 308 309
  var desc = new PropertyDescriptor();
  desc.setGet(fun);
  desc.setEnumerable(true);
  desc.setConfigurable(true);
310
  DefineOwnProperty(ToObject(receiver), ToName(name), desc, false);
311
}
312 313


314
function ObjectLookupGetter(name) {
315 316 317
  var receiver = this;
  if (receiver == null && !IS_UNDETECTABLE(receiver)) {
    receiver = %GlobalReceiver(global);
318
  }
319
  return %LookupAccessor(ToObject(receiver), ToName(name), GETTER);
320
}
321 322


323
function ObjectDefineSetter(name, fun) {
324 325 326
  var receiver = this;
  if (receiver == null && !IS_UNDETECTABLE(receiver)) {
    receiver = %GlobalReceiver(global);
327
  }
328
  if (!IS_SPEC_FUNCTION(fun)) {
329 330 331
    throw new $TypeError(
        'Object.prototype.__defineSetter__: Expecting function');
  }
332 333 334 335
  var desc = new PropertyDescriptor();
  desc.setSet(fun);
  desc.setEnumerable(true);
  desc.setConfigurable(true);
336
  DefineOwnProperty(ToObject(receiver), ToName(name), desc, false);
337
}
338 339


340
function ObjectLookupSetter(name) {
341 342 343
  var receiver = this;
  if (receiver == null && !IS_UNDETECTABLE(receiver)) {
    receiver = %GlobalReceiver(global);
344
  }
345
  return %LookupAccessor(ToObject(receiver), ToName(name), SETTER);
346
}
347 348


349
function ObjectKeys(obj) {
350
  if (!IS_SPEC_OBJECT(obj)) {
351
    throw MakeTypeError("called_on_non_object", ["Object.keys"]);
352
  }
353 354
  if (%IsJSProxy(obj)) {
    var handler = %GetHandler(obj);
355
    var names = CallTrap0(handler, "keys", DerivedKeysTrap);
356
    return ToNameArray(names, "keys", false);
357
  }
358 359 360 361
  return %LocalKeys(obj);
}


362 363 364
// ES5 8.10.1.
function IsAccessorDescriptor(desc) {
  if (IS_UNDEFINED(desc)) return false;
365
  return desc.hasGetter() || desc.hasSetter();
366 367 368 369 370 371
}


// ES5 8.10.2.
function IsDataDescriptor(desc) {
  if (IS_UNDEFINED(desc)) return false;
372
  return desc.hasValue() || desc.hasWritable();
373 374 375 376 377
}


// ES5 8.10.3.
function IsGenericDescriptor(desc) {
378
  if (IS_UNDEFINED(desc)) return false;
379 380 381 382 383 384 385 386
  return !(IsAccessorDescriptor(desc) || IsDataDescriptor(desc));
}


function IsInconsistentDescriptor(desc) {
  return IsAccessorDescriptor(desc) && IsDataDescriptor(desc);
}

387

388 389
// ES5 8.10.4
function FromPropertyDescriptor(desc) {
390
  if (IS_UNDEFINED(desc)) return desc;
391

392
  if (IsDataDescriptor(desc)) {
393 394 395 396
    return { value: desc.getValue(),
             writable: desc.isWritable(),
             enumerable: desc.isEnumerable(),
             configurable: desc.isConfigurable() };
397
  }
398 399
  // Must be an AccessorDescriptor then. We never return a generic descriptor.
  return { get: desc.getGet(),
400
           set: desc.getSet(),
401 402
           enumerable: desc.isEnumerable(),
           configurable: desc.isConfigurable() };
403
}
404

405

406 407 408 409
// Harmony Proxies
function FromGenericPropertyDescriptor(desc) {
  if (IS_UNDEFINED(desc)) return desc;
  var obj = new $Object();
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

  if (desc.hasValue()) {
    %IgnoreAttributesAndSetProperty(obj, "value", desc.getValue(), NONE);
  }
  if (desc.hasWritable()) {
    %IgnoreAttributesAndSetProperty(obj, "writable", desc.isWritable(), NONE);
  }
  if (desc.hasGetter()) {
    %IgnoreAttributesAndSetProperty(obj, "get", desc.getGet(), NONE);
  }
  if (desc.hasSetter()) {
    %IgnoreAttributesAndSetProperty(obj, "set", desc.getSet(), NONE);
  }
  if (desc.hasEnumerable()) {
    %IgnoreAttributesAndSetProperty(obj, "enumerable",
                                    desc.isEnumerable(), NONE);
  }
  if (desc.hasConfigurable()) {
    %IgnoreAttributesAndSetProperty(obj, "configurable",
                                    desc.isConfigurable(), NONE);
  }
431 432 433
  return obj;
}

434

435 436
// ES5 8.10.5.
function ToPropertyDescriptor(obj) {
437
  if (!IS_SPEC_OBJECT(obj)) {
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    throw MakeTypeError("property_desc_object", [obj]);
  }
  var desc = new PropertyDescriptor();

  if ("enumerable" in obj) {
    desc.setEnumerable(ToBoolean(obj.enumerable));
  }

  if ("configurable" in obj) {
    desc.setConfigurable(ToBoolean(obj.configurable));
  }

  if ("value" in obj) {
    desc.setValue(obj.value);
  }

  if ("writable" in obj) {
    desc.setWritable(ToBoolean(obj.writable));
  }

  if ("get" in obj) {
    var get = obj.get;
460
    if (!IS_UNDEFINED(get) && !IS_SPEC_FUNCTION(get)) {
461 462 463 464 465 466 467
      throw MakeTypeError("getter_must_be_callable", [get]);
    }
    desc.setGet(get);
  }

  if ("set" in obj) {
    var set = obj.set;
468
    if (!IS_UNDEFINED(set) && !IS_SPEC_FUNCTION(set)) {
469 470 471 472 473 474 475 476 477 478 479 480
      throw MakeTypeError("setter_must_be_callable", [set]);
    }
    desc.setSet(set);
  }

  if (IsInconsistentDescriptor(desc)) {
    throw MakeTypeError("value_and_accessor", [obj]);
  }
  return desc;
}


481 482
// For Harmony proxies.
function ToCompletePropertyDescriptor(obj) {
483
  var desc = ToPropertyDescriptor(obj);
484
  if (IsGenericDescriptor(desc) || IsDataDescriptor(desc)) {
485
    if (!desc.hasValue()) desc.setValue(UNDEFINED);
486
    if (!desc.hasWritable()) desc.setWritable(false);
487 488
  } else {
    // Is accessor descriptor.
489 490
    if (!desc.hasGetter()) desc.setGet(UNDEFINED);
    if (!desc.hasSetter()) desc.setSet(UNDEFINED);
491
  }
492 493
  if (!desc.hasEnumerable()) desc.setEnumerable(false);
  if (!desc.hasConfigurable()) desc.setConfigurable(false);
494 495 496 497
  return desc;
}


498 499 500
function PropertyDescriptor() {
  // Initialize here so they are all in-object and have the same map.
  // Default values from ES5 8.6.1.
501
  this.value_ = UNDEFINED;
502 503 504 505
  this.hasValue_ = false;
  this.writable_ = false;
  this.hasWritable_ = false;
  this.enumerable_ = false;
506
  this.hasEnumerable_ = false;
507
  this.configurable_ = false;
508
  this.hasConfigurable_ = false;
509
  this.get_ = UNDEFINED;
510
  this.hasGetter_ = false;
511
  this.set_ = UNDEFINED;
512 513 514
  this.hasSetter_ = false;
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
SetUpLockedPrototype(PropertyDescriptor, $Array(
    "value_",
    "hasValue_",
    "writable_",
    "hasWritable_",
    "enumerable_",
    "hasEnumerable_",
    "configurable_",
    "hasConfigurable_",
    "get_",
    "hasGetter_",
    "set_",
    "hasSetter_"
  ), $Array(
    "toString", function() {
      return "[object PropertyDescriptor]";
    },
    "setValue", function(value) {
      this.value_ = value;
      this.hasValue_ = true;
    },
    "getValue", function() {
      return this.value_;
    },
    "hasValue", function() {
      return this.hasValue_;
    },
    "setEnumerable", function(enumerable) {
      this.enumerable_ = enumerable;
        this.hasEnumerable_ = true;
    },
    "isEnumerable", function () {
      return this.enumerable_;
    },
    "hasEnumerable", function() {
      return this.hasEnumerable_;
    },
    "setWritable", function(writable) {
      this.writable_ = writable;
      this.hasWritable_ = true;
    },
    "isWritable", function() {
      return this.writable_;
    },
    "hasWritable", function() {
      return this.hasWritable_;
    },
    "setConfigurable", function(configurable) {
      this.configurable_ = configurable;
      this.hasConfigurable_ = true;
    },
    "hasConfigurable", function() {
      return this.hasConfigurable_;
    },
    "isConfigurable", function() {
      return this.configurable_;
    },
    "setGet", function(get) {
      this.get_ = get;
        this.hasGetter_ = true;
    },
    "getGet", function() {
      return this.get_;
    },
    "hasGetter", function() {
      return this.hasGetter_;
    },
    "setSet", function(set) {
      this.set_ = set;
      this.hasSetter_ = true;
    },
    "getSet", function() {
      return this.set_;
    },
    "hasSetter", function() {
      return this.hasSetter_;
  }));
592 593


594 595 596 597
// Converts an array returned from Runtime_GetOwnProperty to an actual
// property descriptor. For a description of the array layout please
// see the runtime.cc file.
function ConvertDescriptorArrayToDescriptor(desc_array) {
598
  if (desc_array === false) {
599 600
    throw 'Internal error: invalid desc_array';
  }
601

602
  if (IS_UNDEFINED(desc_array)) {
603
    return UNDEFINED;
604
  }
605

606 607 608 609 610
  var desc = new PropertyDescriptor();
  // This is an accessor.
  if (desc_array[IS_ACCESSOR_INDEX]) {
    desc.setGet(desc_array[GETTER_INDEX]);
    desc.setSet(desc_array[SETTER_INDEX]);
611
  } else {
612 613
    desc.setValue(desc_array[VALUE_INDEX]);
    desc.setWritable(desc_array[WRITABLE_INDEX]);
614
  }
615 616
  desc.setEnumerable(desc_array[ENUMERABLE_INDEX]);
  desc.setConfigurable(desc_array[CONFIGURABLE_INDEX]);
617 618 619 620 621

  return desc;
}


622 623 624 625 626 627 628 629
// For Harmony proxies.
function GetTrap(handler, name, defaultTrap) {
  var trap = handler[name];
  if (IS_UNDEFINED(trap)) {
    if (IS_UNDEFINED(defaultTrap)) {
      throw MakeTypeError("handler_trap_missing", [handler, name]);
    }
    trap = defaultTrap;
630
  } else if (!IS_SPEC_FUNCTION(trap)) {
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    throw MakeTypeError("handler_trap_must_be_callable", [handler, name]);
  }
  return trap;
}


function CallTrap0(handler, name, defaultTrap) {
  return %_CallFunction(handler, GetTrap(handler, name, defaultTrap));
}


function CallTrap1(handler, name, defaultTrap, x) {
  return %_CallFunction(handler, x, GetTrap(handler, name, defaultTrap));
}


function CallTrap2(handler, name, defaultTrap, x, y) {
  return %_CallFunction(handler, x, y, GetTrap(handler, name, defaultTrap));
}


652
// ES5 section 8.12.1.
653
function GetOwnProperty(obj, v) {
654
  var p = ToName(v);
655
  if (%IsJSProxy(obj)) {
656
    // TODO(rossberg): adjust once there is a story for symbols vs proxies.
657
    if (IS_SYMBOL(v)) return UNDEFINED;
658

659
    var handler = %GetHandler(obj);
660 661
    var descriptor = CallTrap1(
                         handler, "getOwnPropertyDescriptor", UNDEFINED, p);
662 663 664 665 666 667 668 669 670
    if (IS_UNDEFINED(descriptor)) return descriptor;
    var desc = ToCompletePropertyDescriptor(descriptor);
    if (!desc.isConfigurable()) {
      throw MakeTypeError("proxy_prop_not_configurable",
                          [handler, "getOwnPropertyDescriptor", p, descriptor]);
    }
    return desc;
  }

671 672 673
  // GetOwnProperty returns an array indexed by the constants
  // defined in macros.py.
  // If p is not a property on obj undefined is returned.
674
  var props = %GetOwnProperty(ToObject(obj), p);
675 676

  // A false value here means that access checks failed.
677
  if (props === false) return UNDEFINED;
678 679 680 681 682

  return ConvertDescriptorArrayToDescriptor(props);
}


683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
// ES5 section 8.12.7.
function Delete(obj, p, should_throw) {
  var desc = GetOwnProperty(obj, p);
  if (IS_UNDEFINED(desc)) return true;
  if (desc.isConfigurable()) {
    %DeleteProperty(obj, p, 0);
    return true;
  } else if (should_throw) {
    throw MakeTypeError("define_disallowed", [p]);
  } else {
    return;
  }
}


698 699
// Harmony proxies.
function DefineProxyProperty(obj, p, attributes, should_throw) {
700 701 702
  // TODO(rossberg): adjust once there is a story for symbols vs proxies.
  if (IS_SYMBOL(p)) return false;

703
  var handler = %GetHandler(obj);
704
  var result = CallTrap2(handler, "defineProperty", UNDEFINED, p, attributes);
705 706
  if (!ToBoolean(result)) {
    if (should_throw) {
707 708
      throw MakeTypeError("handler_returned_false",
                          [handler, "defineProperty"]);
709 710 711 712 713 714 715 716
    } else {
      return false;
    }
  }
  return true;
}


717
// ES5 8.12.9.
718
function DefineObjectProperty(obj, p, desc, should_throw) {
719
  var current_or_access = %GetOwnProperty(ToObject(obj), ToName(p));
720
  // A false value here means that access checks failed.
721
  if (current_or_access === false) return UNDEFINED;
722 723

  var current = ConvertDescriptorArrayToDescriptor(current_or_access);
724 725 726 727
  var extensible = %IsExtensible(ToObject(obj));

  // Error handling according to spec.
  // Step 3
728 729
  if (IS_UNDEFINED(current) && !extensible) {
    if (should_throw) {
730
      throw MakeTypeError("define_disallowed", [p]);
731
    } else {
732
      return false;
733 734
    }
  }
735

736
  if (!IS_UNDEFINED(current)) {
737
    // Step 5 and 6
738 739 740 741
    if ((IsGenericDescriptor(desc) ||
         IsDataDescriptor(desc) == IsDataDescriptor(current)) &&
        (!desc.hasEnumerable() ||
         SameValue(desc.isEnumerable(), current.isEnumerable())) &&
742
        (!desc.hasConfigurable() ||
743
         SameValue(desc.isConfigurable(), current.isConfigurable())) &&
744
        (!desc.hasWritable() ||
745 746 747 748 749 750 751 752 753
         SameValue(desc.isWritable(), current.isWritable())) &&
        (!desc.hasValue() ||
         SameValue(desc.getValue(), current.getValue())) &&
        (!desc.hasGetter() ||
         SameValue(desc.getGet(), current.getGet())) &&
        (!desc.hasSetter() ||
         SameValue(desc.getSet(), current.getSet()))) {
      return true;
    }
754 755 756 757
    if (!current.isConfigurable()) {
      // Step 7
      if (desc.isConfigurable() ||
          (desc.hasEnumerable() &&
758
           desc.isEnumerable() != current.isEnumerable())) {
759
        if (should_throw) {
760
          throw MakeTypeError("redefine_disallowed", [p]);
761
        } else {
762
          return false;
763
        }
764
      }
765 766 767
      // Step 8
      if (!IsGenericDescriptor(desc)) {
        // Step 9a
768
        if (IsDataDescriptor(current) != IsDataDescriptor(desc)) {
769
          if (should_throw) {
770
            throw MakeTypeError("redefine_disallowed", [p]);
771
          } else {
772
            return false;
773
          }
774
        }
775 776
        // Step 10a
        if (IsDataDescriptor(current) && IsDataDescriptor(desc)) {
777
          if (!current.isWritable() && desc.isWritable()) {
778
            if (should_throw) {
779
              throw MakeTypeError("redefine_disallowed", [p]);
780
            } else {
781
              return false;
782
            }
783
          }
784 785
          if (!current.isWritable() && desc.hasValue() &&
              !SameValue(desc.getValue(), current.getValue())) {
786
            if (should_throw) {
787
              throw MakeTypeError("redefine_disallowed", [p]);
788
            } else {
789
              return false;
790
            }
791 792 793 794
          }
        }
        // Step 11
        if (IsAccessorDescriptor(desc) && IsAccessorDescriptor(current)) {
795
          if (desc.hasSetter() && !SameValue(desc.getSet(), current.getSet())) {
796
            if (should_throw) {
797
              throw MakeTypeError("redefine_disallowed", [p]);
798
            } else {
799
              return false;
800
            }
801
          }
802
          if (desc.hasGetter() && !SameValue(desc.getGet(),current.getGet())) {
803
            if (should_throw) {
804
              throw MakeTypeError("redefine_disallowed", [p]);
805
            } else {
806
              return false;
807
            }
808
          }
809
        }
810 811 812 813
      }
    }
  }

814
  // Send flags - enumerable and configurable are common - writable is
815 816 817 818 819 820 821 822
  // only send to the data descriptor.
  // Take special care if enumerable and configurable is not defined on
  // desc (we need to preserve the existing values from current).
  var flag = NONE;
  if (desc.hasEnumerable()) {
    flag |= desc.isEnumerable() ? 0 : DONT_ENUM;
  } else if (!IS_UNDEFINED(current)) {
    flag |= current.isEnumerable() ? 0 : DONT_ENUM;
823
  } else {
824 825 826 827 828 829 830 831 832 833
    flag |= DONT_ENUM;
  }

  if (desc.hasConfigurable()) {
    flag |= desc.isConfigurable() ? 0 : DONT_DELETE;
  } else if (!IS_UNDEFINED(current)) {
    flag |= current.isConfigurable() ? 0 : DONT_DELETE;
  } else
    flag |= DONT_DELETE;

834 835 836 837 838 839 840 841 842 843
  if (IsDataDescriptor(desc) ||
      (IsGenericDescriptor(desc) &&
       (IS_UNDEFINED(current) || IsDataDescriptor(current)))) {
    // There are 3 cases that lead here:
    // Step 4a - defining a new data property.
    // Steps 9b & 12 - replacing an existing accessor property with a data
    //                 property.
    // Step 12 - updating an existing data property with a data or generic
    //           descriptor.

844 845 846 847 848 849 850
    if (desc.hasWritable()) {
      flag |= desc.isWritable() ? 0 : READ_ONLY;
    } else if (!IS_UNDEFINED(current)) {
      flag |= current.isWritable() ? 0 : READ_ONLY;
    } else {
      flag |= READ_ONLY;
    }
851

852
    var value = UNDEFINED;  // Default value is undefined.
lrn@chromium.org's avatar
lrn@chromium.org committed
853 854
    if (desc.hasValue()) {
      value = desc.getValue();
855
    } else if (!IS_UNDEFINED(current) && IsDataDescriptor(current)) {
lrn@chromium.org's avatar
lrn@chromium.org committed
856 857
      value = current.getValue();
    }
858

lrn@chromium.org's avatar
lrn@chromium.org committed
859
    %DefineOrRedefineDataProperty(obj, p, value, flag);
860
  } else {
861 862 863 864 865 866
    // There are 3 cases that lead here:
    // Step 4b - defining a new accessor property.
    // Steps 9c & 12 - replacing an existing data property with an accessor
    //                 property.
    // Step 12 - updating an existing accessor property with an accessor
    //           descriptor.
867 868 869
    var getter = desc.hasGetter() ? desc.getGet() : null;
    var setter = desc.hasSetter() ? desc.getSet() : null;
    %DefineOrRedefineAccessorProperty(obj, p, getter, setter, flag);
870 871 872 873 874
  }
  return true;
}


875 876 877 878 879 880 881
// ES5 section 15.4.5.1.
function DefineArrayProperty(obj, p, desc, should_throw) {
  // Note that the length of an array is not actually stored as part of the
  // property, hence we use generated code throughout this function instead of
  // DefineObjectProperty() to modify its value.

  // Step 3 - Special handling for length property.
882
  if (p === "length") {
883
    var length = obj.length;
884
    var old_length = length;
885 886 887 888 889 890 891 892
    if (!desc.hasValue()) {
      return DefineObjectProperty(obj, "length", desc, should_throw);
    }
    var new_length = ToUint32(desc.getValue());
    if (new_length != ToNumber(desc.getValue())) {
      throw new $RangeError('defineProperty() array length out of range');
    }
    var length_desc = GetOwnProperty(obj, "length");
893 894 895 896 897 898 899 900
    if (new_length != length && !length_desc.isWritable()) {
      if (should_throw) {
        throw MakeTypeError("redefine_disallowed", [p]);
      } else {
        return false;
      }
    }
    var threw = false;
901 902 903 904 905 906 907 908 909 910

    var emit_splice = %IsObserved(obj) && new_length !== old_length;
    var removed;
    if (emit_splice) {
      BeginPerformSplice(obj);
      removed = [];
      if (new_length < old_length)
        removed.length = old_length - new_length;
    }

911
    while (new_length < length--) {
912 913 914 915 916 917 918
      var index = ToString(length);
      if (emit_splice) {
        var deletedDesc = GetOwnProperty(obj, index);
        if (deletedDesc && deletedDesc.hasValue())
          removed[length - new_length] = deletedDesc.getValue();
      }
      if (!Delete(obj, index, false)) {
919 920 921 922 923
        new_length = length + 1;
        threw = true;
        break;
      }
    }
924 925
    // Make sure the below call to DefineObjectProperty() doesn't overwrite
    // any magic "length" property by removing the value.
926 927 928 929
    // TODO(mstarzinger): This hack should be removed once we have addressed the
    // respective TODO in Runtime_DefineOrRedefineDataProperty.
    // For the time being, we need a hack to prevent Object.observe from
    // generating two change records.
930
    obj.length = new_length;
931
    desc.value_ = UNDEFINED;
932
    desc.hasValue_ = false;
933
    threw = !DefineObjectProperty(obj, "length", desc, should_throw) || threw;
934 935 936 937 938 939 940
    if (emit_splice) {
      EndPerformSplice(obj);
      EnqueueSpliceRecord(obj,
          new_length < old_length ? new_length : old_length,
          removed,
          new_length > old_length ? new_length - old_length : 0);
    }
941
    if (threw) {
942 943 944 945 946 947 948 949 950 951 952
      if (should_throw) {
        throw MakeTypeError("redefine_disallowed", [p]);
      } else {
        return false;
      }
    }
    return true;
  }

  // Step 4 - Special handling for array index.
  var index = ToUint32(p);
953
  var emit_splice = false;
954
  if (ToString(index) == p && index != 4294967295) {
955
    var length = obj.length;
956 957 958 959 960
    if (index >= length && %IsObserved(obj)) {
      emit_splice = true;
      BeginPerformSplice(obj);
    }

961 962 963
    var length_desc = GetOwnProperty(obj, "length");
    if ((index >= length && !length_desc.isWritable()) ||
        !DefineObjectProperty(obj, p, desc, true)) {
964 965
      if (emit_splice)
        EndPerformSplice(obj);
966 967 968 969 970 971 972 973 974
      if (should_throw) {
        throw MakeTypeError("define_disallowed", [p]);
      } else {
        return false;
      }
    }
    if (index >= length) {
      obj.length = index + 1;
    }
975 976
    if (emit_splice) {
      EndPerformSplice(obj);
977
      EnqueueSpliceRecord(obj, length, [], index + 1 - length);
978
    }
979 980 981 982 983 984 985 986 987 988 989
    return true;
  }

  // Step 5 - Fallback to default implementation.
  return DefineObjectProperty(obj, p, desc, should_throw);
}


// ES5 section 8.12.9, ES5 section 15.4.5.1 and Harmony proxies.
function DefineOwnProperty(obj, p, desc, should_throw) {
  if (%IsJSProxy(obj)) {
990 991 992
    // TODO(rossberg): adjust once there is a story for symbols vs proxies.
    if (IS_SYMBOL(p)) return false;

993 994 995 996 997 998 999 1000 1001 1002
    var attributes = FromGenericPropertyDescriptor(desc);
    return DefineProxyProperty(obj, p, attributes, should_throw);
  } else if (IS_ARRAY(obj)) {
    return DefineArrayProperty(obj, p, desc, should_throw);
  } else {
    return DefineObjectProperty(obj, p, desc, should_throw);
  }
}


1003 1004
// ES5 section 15.2.3.2.
function ObjectGetPrototypeOf(obj) {
1005
  if (!IS_SPEC_OBJECT(obj)) {
1006
    throw MakeTypeError("called_on_non_object", ["Object.getPrototypeOf"]);
1007
  }
1008
  return %GetPrototype(obj);
1009 1010
}

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
// ES6 section 19.1.2.19.
function ObjectSetPrototypeOf(obj, proto) {
  CHECK_OBJECT_COERCIBLE(obj, "Object.setPrototypeOf");

  if (proto !== null && !IS_SPEC_OBJECT(proto)) {
    throw MakeTypeError("proto_object_or_null", [proto]);
  }

  if (IS_SPEC_OBJECT(obj)) {
    %SetPrototype(obj, proto);
  }

  return obj;
}

1026

1027
// ES5 section 15.2.3.3
1028
function ObjectGetOwnPropertyDescriptor(obj, p) {
1029
  if (!IS_SPEC_OBJECT(obj)) {
1030 1031
    throw MakeTypeError("called_on_non_object",
                        ["Object.getOwnPropertyDescriptor"]);
1032
  }
1033 1034 1035 1036 1037
  var desc = GetOwnProperty(obj, p);
  return FromPropertyDescriptor(desc);
}


1038
// For Harmony proxies
1039
function ToNameArray(obj, trap, includeSymbols) {
1040 1041 1042 1043 1044
  if (!IS_SPEC_OBJECT(obj)) {
    throw MakeTypeError("proxy_non_object_prop_names", [obj, trap]);
  }
  var n = ToUint32(obj.length);
  var array = new $Array(n);
1045
  var realLength = 0;
1046
  var names = { __proto__: null };  // TODO(rossberg): use sets once ready.
1047
  for (var index = 0; index < n; index++) {
1048
    var s = ToName(obj[index]);
1049
    // TODO(rossberg): adjust once there is a story for symbols vs proxies.
1050
    if (IS_SYMBOL(s) && !includeSymbols) continue;
1051
    if (%HasLocalProperty(names, s)) {
1052
      throw MakeTypeError("proxy_repeated_prop_name", [obj, trap, s]);
1053 1054
    }
    array[index] = s;
1055
    ++realLength;
1056
    names[s] = 0;
1057
  }
1058
  array.length = realLength;
1059 1060 1061 1062
  return array;
}


1063
function ObjectGetOwnPropertyKeys(obj, symbolsOnly) {
1064
  var nameArrays = new InternalArray();
1065 1066 1067
  var filter = symbolsOnly ?
      PROPERTY_ATTRIBUTES_STRING | PROPERTY_ATTRIBUTES_PRIVATE_SYMBOL :
      PROPERTY_ATTRIBUTES_SYMBOLIC;
1068

1069 1070
  // Find all the indexed properties.

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  // Only get the local element names if we want to include string keys.
  if (!symbolsOnly) {
    var localElementNames = %GetLocalElementNames(obj);
    for (var i = 0; i < localElementNames.length; ++i) {
      localElementNames[i] = %_NumberToString(localElementNames[i]);
    }
    nameArrays.push(localElementNames);

    // Get names for indexed interceptor properties.
    var interceptorInfo = %GetInterceptorInfo(obj);
    if ((interceptorInfo & 1) != 0) {
      var indexedInterceptorNames = %GetIndexedInterceptorElementNames(obj);
      if (!IS_UNDEFINED(indexedInterceptorNames)) {
        nameArrays.push(indexedInterceptorNames);
      }
1086
    }
1087 1088 1089 1090 1091
  }

  // Find all the named properties.

  // Get the local property names.
1092
  nameArrays.push(%GetLocalPropertyNames(obj, filter));
1093 1094

  // Get names for named interceptor properties if any.
1095
  if ((interceptorInfo & 2) != 0) {
1096 1097
    var namedInterceptorNames =
        %GetNamedInterceptorPropertyNames(obj);
1098 1099
    if (!IS_UNDEFINED(namedInterceptorNames)) {
      nameArrays.push(namedInterceptorNames);
1100 1101 1102
    }
  }

1103 1104 1105 1106 1107
  var propertyNames =
      %Apply(InternalArray.prototype.concat,
             nameArrays[0], nameArrays, 1, nameArrays.length - 1);

  // Property names are expected to be unique strings,
1108 1109
  // but interceptors can interfere with that assumption.
  if (interceptorInfo != 0) {
1110
    var seenKeys = { __proto__: null };
1111 1112
    var j = 0;
    for (var i = 0; i < propertyNames.length; ++i) {
1113 1114 1115 1116 1117 1118
      var name = propertyNames[i];
      if (symbolsOnly) {
        if (!IS_SYMBOL(name) || IS_PRIVATE(name)) continue;
      } else {
        if (IS_SYMBOL(name)) continue;
        name = ToString(name);
1119
      }
1120 1121
      if (seenKeys[name]) continue;
      seenKeys[name] = true;
1122
      propertyNames[j++] = name;
1123
    }
1124
    propertyNames.length = j;
1125
  }
1126

1127 1128 1129 1130
  return propertyNames;
}


1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
// ES5 section 15.2.3.4.
function ObjectGetOwnPropertyNames(obj) {
  if (!IS_SPEC_OBJECT(obj)) {
    throw MakeTypeError("called_on_non_object", ["Object.getOwnPropertyNames"]);
  }
  // Special handling for proxies.
  if (%IsJSProxy(obj)) {
    var handler = %GetHandler(obj);
    var names = CallTrap0(handler, "getOwnPropertyNames", UNDEFINED);
    return ToNameArray(names, "getOwnPropertyNames", false);
  }

  return ObjectGetOwnPropertyKeys(obj, false);
}


1147 1148
// ES5 section 15.2.3.5.
function ObjectCreate(proto, properties) {
1149
  if (!IS_SPEC_OBJECT(proto) && proto !== null) {
1150 1151
    throw MakeTypeError("proto_object_or_null", [proto]);
  }
1152
  var obj = { __proto__: proto };
1153 1154 1155 1156 1157
  if (!IS_UNDEFINED(properties)) ObjectDefineProperties(obj, properties);
  return obj;
}


1158 1159
// ES5 section 15.2.3.6.
function ObjectDefineProperty(obj, p, attributes) {
1160
  if (!IS_SPEC_OBJECT(obj)) {
1161
    throw MakeTypeError("called_on_non_object", ["Object.defineProperty"]);
1162
  }
1163
  var name = ToName(p);
1164 1165 1166 1167
  if (%IsJSProxy(obj)) {
    // Clone the attributes object for protection.
    // TODO(rossberg): not spec'ed yet, so not sure if this should involve
    // non-own properties as it does (or non-enumerable ones, as it doesn't?).
1168
    var attributesClone = { __proto__: null };
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    for (var a in attributes) {
      attributesClone[a] = attributes[a];
    }
    DefineProxyProperty(obj, name, attributesClone, true);
    // The following would implement the spec as in the current proposal,
    // but after recent comments on es-discuss, is most likely obsolete.
    /*
    var defineObj = FromGenericPropertyDescriptor(desc);
    var names = ObjectGetOwnPropertyNames(attributes);
    var standardNames =
      {value: 0, writable: 0, get: 0, set: 0, enumerable: 0, configurable: 0};
    for (var i = 0; i < names.length; i++) {
      var N = names[i];
      if (!(%HasLocalProperty(standardNames, N))) {
        var attr = GetOwnProperty(attributes, N);
        DefineOwnProperty(descObj, N, attr, true);
      }
    }
    // This is really confusing the types, but it is what the proxies spec
    // currently requires:
    desc = descObj;
    */
  } else {
    var desc = ToPropertyDescriptor(attributes);
    DefineOwnProperty(obj, name, desc, true);
  }
1195 1196 1197 1198
  return obj;
}


1199
function GetOwnEnumerablePropertyNames(properties) {
1200
  var names = new InternalArray();
1201 1202 1203 1204 1205 1206 1207 1208 1209
  for (var key in properties) {
    if (%HasLocalProperty(properties, key)) {
      names.push(key);
    }
  }
  return names;
}


1210
// ES5 section 15.2.3.7.
1211
function ObjectDefineProperties(obj, properties) {
1212
  if (!IS_SPEC_OBJECT(obj)) {
1213
    throw MakeTypeError("called_on_non_object", ["Object.defineProperties"]);
1214
  }
1215
  var props = ToObject(properties);
1216
  var names = GetOwnEnumerablePropertyNames(props);
1217
  var descriptors = new InternalArray();
1218
  for (var i = 0; i < names.length; i++) {
1219 1220 1221 1222
    descriptors.push(ToPropertyDescriptor(props[names[i]]));
  }
  for (var i = 0; i < names.length; i++) {
    DefineOwnProperty(obj, names[i], descriptors[i], true);
1223
  }
1224
  return obj;
1225 1226 1227
}


1228 1229 1230
// Harmony proxies.
function ProxyFix(obj) {
  var handler = %GetHandler(obj);
1231
  var props = CallTrap0(handler, "fix", UNDEFINED);
1232 1233 1234
  if (IS_UNDEFINED(props)) {
    throw MakeTypeError("handler_returned_undefined", [handler, "fix"]);
  }
1235

1236
  if (%IsJSFunctionProxy(obj)) {
1237 1238 1239 1240 1241
    var callTrap = %GetCallTrap(obj);
    var constructTrap = %GetConstructTrap(obj);
    var code = DelegateCallAndConstruct(callTrap, constructTrap);
    %Fix(obj);  // becomes a regular function
    %SetCode(obj, code);
1242 1243 1244 1245
    // TODO(rossberg): What about length and other properties? Not specified.
    // We just put in some half-reasonable defaults for now.
    var prototype = new $Object();
    $Object.defineProperty(prototype, "constructor",
1246 1247 1248 1249
      {value: obj, writable: true, enumerable: false, configurable: true});
    // TODO(v8:1530): defineProperty does not handle prototype and length.
    %FunctionSetPrototype(obj, prototype);
    obj.length = 0;
1250 1251 1252
  } else {
    %Fix(obj);
  }
1253 1254 1255 1256
  ObjectDefineProperties(obj, props);
}


1257 1258
// ES5 section 15.2.3.8.
function ObjectSeal(obj) {
1259
  if (!IS_SPEC_OBJECT(obj)) {
1260
    throw MakeTypeError("called_on_non_object", ["Object.seal"]);
1261
  }
1262 1263 1264
  if (%IsJSProxy(obj)) {
    ProxyFix(obj);
  }
1265
  var names = ObjectGetOwnPropertyNames(obj);
1266 1267
  for (var i = 0; i < names.length; i++) {
    var name = names[i];
1268
    var desc = GetOwnProperty(obj, name);
1269 1270 1271 1272
    if (desc.isConfigurable()) {
      desc.setConfigurable(false);
      DefineOwnProperty(obj, name, desc, true);
    }
1273
  }
1274 1275
  %PreventExtensions(obj);
  return obj;
1276 1277 1278
}


1279 1280
// ES5 section 15.2.3.9.
function ObjectFreeze(obj) {
1281
  if (!IS_SPEC_OBJECT(obj)) {
1282
    throw MakeTypeError("called_on_non_object", ["Object.freeze"]);
1283
  }
1284
  var isProxy = %IsJSProxy(obj);
1285
  if (isProxy || %HasSloppyArgumentsElements(obj) || %IsObserved(obj)) {
1286 1287
    if (isProxy) {
      ProxyFix(obj);
1288
    }
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
    var names = ObjectGetOwnPropertyNames(obj);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      var desc = GetOwnProperty(obj, name);
      if (desc.isWritable() || desc.isConfigurable()) {
        if (IsDataDescriptor(desc)) desc.setWritable(false);
        desc.setConfigurable(false);
        DefineOwnProperty(obj, name, desc, true);
      }
    }
    %PreventExtensions(obj);
  } else {
    // TODO(adamk): Is it worth going to this fast path if the
    // object's properties are already in dictionary mode?
    %ObjectFreeze(obj);
1304
  }
1305
  return obj;
1306 1307 1308
}


1309 1310
// ES5 section 15.2.3.10
function ObjectPreventExtension(obj) {
1311
  if (!IS_SPEC_OBJECT(obj)) {
1312
    throw MakeTypeError("called_on_non_object", ["Object.preventExtension"]);
1313
  }
1314 1315 1316
  if (%IsJSProxy(obj)) {
    ProxyFix(obj);
  }
1317 1318 1319 1320 1321
  %PreventExtensions(obj);
  return obj;
}


1322 1323
// ES5 section 15.2.3.11
function ObjectIsSealed(obj) {
1324
  if (!IS_SPEC_OBJECT(obj)) {
1325
    throw MakeTypeError("called_on_non_object", ["Object.isSealed"]);
1326
  }
1327 1328 1329
  if (%IsJSProxy(obj)) {
    return false;
  }
1330 1331 1332
  if (%IsExtensible(obj)) {
    return false;
  }
1333
  var names = ObjectGetOwnPropertyNames(obj);
1334 1335
  for (var i = 0; i < names.length; i++) {
    var name = names[i];
1336
    var desc = GetOwnProperty(obj, name);
1337
    if (desc.isConfigurable()) return false;
1338
  }
1339
  return true;
1340 1341 1342
}


1343 1344
// ES5 section 15.2.3.12
function ObjectIsFrozen(obj) {
1345
  if (!IS_SPEC_OBJECT(obj)) {
1346
    throw MakeTypeError("called_on_non_object", ["Object.isFrozen"]);
1347
  }
1348 1349 1350
  if (%IsJSProxy(obj)) {
    return false;
  }
1351 1352 1353
  if (%IsExtensible(obj)) {
    return false;
  }
1354
  var names = ObjectGetOwnPropertyNames(obj);
1355 1356
  for (var i = 0; i < names.length; i++) {
    var name = names[i];
1357
    var desc = GetOwnProperty(obj, name);
1358 1359
    if (IsDataDescriptor(desc) && desc.isWritable()) return false;
    if (desc.isConfigurable()) return false;
1360
  }
1361
  return true;
1362 1363 1364
}


1365 1366
// ES5 section 15.2.3.13
function ObjectIsExtensible(obj) {
1367
  if (!IS_SPEC_OBJECT(obj)) {
1368
    throw MakeTypeError("called_on_non_object", ["Object.isExtensible"]);
1369
  }
1370 1371 1372
  if (%IsJSProxy(obj)) {
    return true;
  }
1373 1374 1375 1376
  return %IsExtensible(obj);
}


1377 1378 1379
// Harmony egal.
function ObjectIs(obj1, obj2) {
  if (obj1 === obj2) {
1380
    return (obj1 !== 0) || (1 / obj1 === 1 / obj2);
1381 1382 1383 1384 1385 1386
  } else {
    return (obj1 !== obj1) && (obj2 !== obj2);
  }
}


1387
// ECMA-262, Edition 6, section B.2.2.1.1
1388
function ObjectGetProto() {
1389
  return %GetPrototype(ToObject(this));
1390 1391 1392
}


1393 1394 1395 1396
// ECMA-262, Edition 6, section B.2.2.1.2
function ObjectSetProto(proto) {
  CHECK_OBJECT_COERCIBLE(this, "Object.prototype.__proto__");

1397
  if ((IS_SPEC_OBJECT(proto) || IS_NULL(proto)) && IS_SPEC_OBJECT(this)) {
1398 1399
    %SetPrototype(this, proto);
  }
1400 1401 1402
}


1403
function ObjectConstructor(x) {
1404
  if (%_IsConstructCall()) {
1405 1406 1407 1408 1409 1410
    if (x == null) return this;
    return ToObject(x);
  } else {
    if (x == null) return { };
    return ToObject(x);
  }
1411
}
1412 1413 1414


// ----------------------------------------------------------------------------
1415
// Object
1416

1417 1418
function SetUpObject() {
  %CheckIsBootstrapping();
1419

1420
  %SetNativeFlag($Object);
1421
  %SetCode($Object, ObjectConstructor);
1422 1423
  %SetExpectedNumberOfProperties($Object, 4);

1424 1425
  %SetProperty($Object.prototype, "constructor", $Object, DONT_ENUM);

1426
  // Set up non-enumerable functions on the Object.prototype object.
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
  InstallFunctions($Object.prototype, DONT_ENUM, $Array(
    "toString", ObjectToString,
    "toLocaleString", ObjectToLocaleString,
    "valueOf", ObjectValueOf,
    "hasOwnProperty", ObjectHasOwnProperty,
    "isPrototypeOf", ObjectIsPrototypeOf,
    "propertyIsEnumerable", ObjectPropertyIsEnumerable,
    "__defineGetter__", ObjectDefineGetter,
    "__lookupGetter__", ObjectLookupGetter,
    "__defineSetter__", ObjectDefineSetter,
    "__lookupSetter__", ObjectLookupSetter
  ));
1439 1440 1441 1442
  InstallGetterSetter($Object.prototype, "__proto__",
                      ObjectGetProto, ObjectSetProto);

  // Set up non-enumerable functions in the Object object.
1443
  InstallFunctions($Object, DONT_ENUM, $Array(
1444
    "keys", ObjectKeys,
1445
    "create", ObjectCreate,
1446 1447
    "defineProperty", ObjectDefineProperty,
    "defineProperties", ObjectDefineProperties,
1448
    "freeze", ObjectFreeze,
1449
    "getPrototypeOf", ObjectGetPrototypeOf,
1450
    "setPrototypeOf", ObjectSetPrototypeOf,
1451
    "getOwnPropertyDescriptor", ObjectGetOwnPropertyDescriptor,
1452
    "getOwnPropertyNames", ObjectGetOwnPropertyNames,
1453
    // getOwnPropertySymbols is added in symbol.js.
1454
    "is", ObjectIs,
1455
    "isExtensible", ObjectIsExtensible,
1456
    "isFrozen", ObjectIsFrozen,
1457 1458 1459
    "isSealed", ObjectIsSealed,
    "preventExtensions", ObjectPreventExtension,
    "seal", ObjectSeal
1460 1461
    // deliverChangeRecords, getNotifier, observe and unobserve are added
    // in object-observe.js.
1462
  ));
1463
}
1464

1465
SetUpObject();
1466

1467

1468 1469 1470
// ----------------------------------------------------------------------------
// Boolean

1471 1472 1473 1474 1475 1476 1477 1478 1479
function BooleanConstructor(x) {
  if (%_IsConstructCall()) {
    %_SetValueOf(this, ToBoolean(x));
  } else {
    return ToBoolean(x);
  }
}


1480
function BooleanToString() {
1481 1482
  // NOTE: Both Boolean objects and values can enter here as
  // 'this'. This is not as dictated by ECMA-262.
1483 1484 1485 1486 1487 1488 1489 1490
  var b = this;
  if (!IS_BOOLEAN(b)) {
    if (!IS_BOOLEAN_WRAPPER(b)) {
      throw new $TypeError('Boolean.prototype.toString is not generic');
    }
    b = %_ValueOf(b);
  }
  return b ? 'true' : 'false';
1491
}
1492 1493


1494
function BooleanValueOf() {
1495 1496
  // NOTE: Both Boolean objects and values can enter here as
  // 'this'. This is not as dictated by ECMA-262.
1497
  if (!IS_BOOLEAN(this) && !IS_BOOLEAN_WRAPPER(this)) {
1498
    throw new $TypeError('Boolean.prototype.valueOf is not generic');
1499
  }
1500
  return %_ValueOf(this);
1501 1502 1503 1504
}


// ----------------------------------------------------------------------------
1505

1506 1507
function SetUpBoolean () {
  %CheckIsBootstrapping();
1508 1509 1510 1511 1512

  %SetCode($Boolean, BooleanConstructor);
  %FunctionSetPrototype($Boolean, new $Boolean(false));
  %SetProperty($Boolean.prototype, "constructor", $Boolean, DONT_ENUM);

1513 1514
  InstallFunctions($Boolean.prototype, DONT_ENUM, $Array(
    "toString", BooleanToString,
1515
    "valueOf", BooleanValueOf
1516 1517 1518
  ));
}

1519 1520
SetUpBoolean();

1521

1522 1523 1524
// ----------------------------------------------------------------------------
// Number

1525
function NumberConstructor(x) {
1526
  var value = %_ArgumentsLength() == 0 ? 0 : ToNumber(x);
1527
  if (%_IsConstructCall()) {
1528 1529 1530 1531
    %_SetValueOf(this, value);
  } else {
    return value;
  }
1532
}
1533 1534 1535


// ECMA-262 section 15.7.4.2.
1536
function NumberToString(radix) {
1537 1538 1539 1540
  // NOTE: Both Number objects and values can enter here as
  // 'this'. This is not as dictated by ECMA-262.
  var number = this;
  if (!IS_NUMBER(this)) {
1541
    if (!IS_NUMBER_WRAPPER(this)) {
1542
      throw new $TypeError('Number.prototype.toString is not generic');
1543
    }
1544 1545 1546 1547 1548
    // Get the value of this number in case it's an object.
    number = %_ValueOf(this);
  }
  // Fast case: Convert number in radix 10.
  if (IS_UNDEFINED(radix) || radix === 10) {
1549
    return %_NumberToString(number);
1550 1551 1552 1553 1554 1555 1556 1557 1558
  }

  // Convert the radix to an integer and check the range.
  radix = TO_INTEGER(radix);
  if (radix < 2 || radix > 36) {
    throw new $RangeError('toString() radix argument must be between 2 and 36');
  }
  // Convert the number to a string in the given radix.
  return %NumberToRadixString(number, radix);
1559
}
1560 1561 1562


// ECMA-262 section 15.7.4.3
1563
function NumberToLocaleString() {
1564
  return %_CallFunction(this, NumberToString);
1565
}
1566 1567 1568


// ECMA-262 section 15.7.4.4
1569
function NumberValueOf() {
1570 1571
  // NOTE: Both Number objects and values can enter here as
  // 'this'. This is not as dictated by ECMA-262.
1572
  if (!IS_NUMBER(this) && !IS_NUMBER_WRAPPER(this)) {
1573
    throw new $TypeError('Number.prototype.valueOf is not generic');
1574
  }
1575
  return %_ValueOf(this);
1576
}
1577 1578 1579


// ECMA-262 section 15.7.4.5
1580
function NumberToFixed(fractionDigits) {
1581 1582 1583 1584 1585 1586 1587 1588 1589
  var x = this;
  if (!IS_NUMBER(this)) {
    if (!IS_NUMBER_WRAPPER(this)) {
      throw MakeTypeError("incompatible_method_receiver",
                          ["Number.prototype.toFixed", this]);
    }
    // Get the value of this number in case it's an object.
    x = %_ValueOf(this);
  }
1590
  var f = TO_INTEGER(fractionDigits);
1591

1592 1593 1594
  if (f < 0 || f > 20) {
    throw new $RangeError("toFixed() digits argument must be between 0 and 20");
  }
1595 1596

  if (NUMBER_IS_NAN(x)) return "NaN";
1597 1598
  if (x == INFINITY) return "Infinity";
  if (x == -INFINITY) return "-Infinity";
1599

1600
  return %NumberToFixed(x, f);
1601
}
1602 1603 1604


// ECMA-262 section 15.7.4.6
1605
function NumberToExponential(fractionDigits) {
1606 1607 1608 1609 1610
  var x = this;
  if (!IS_NUMBER(this)) {
    if (!IS_NUMBER_WRAPPER(this)) {
      throw MakeTypeError("incompatible_method_receiver",
                          ["Number.prototype.toExponential", this]);
1611
    }
1612 1613
    // Get the value of this number in case it's an object.
    x = %_ValueOf(this);
1614
  }
1615
  var f = IS_UNDEFINED(fractionDigits) ? UNDEFINED : TO_INTEGER(fractionDigits);
1616 1617

  if (NUMBER_IS_NAN(x)) return "NaN";
1618 1619
  if (x == INFINITY) return "Infinity";
  if (x == -INFINITY) return "-Infinity";
1620 1621 1622 1623 1624

  if (IS_UNDEFINED(f)) {
    f = -1;  // Signal for runtime function that f is not defined.
  } else if (f < 0 || f > 20) {
    throw new $RangeError("toExponential() argument must be between 0 and 20");
1625
  }
1626
  return %NumberToExponential(x, f);
1627
}
1628 1629 1630


// ECMA-262 section 15.7.4.7
1631
function NumberToPrecision(precision) {
1632 1633 1634 1635 1636 1637 1638 1639
  var x = this;
  if (!IS_NUMBER(this)) {
    if (!IS_NUMBER_WRAPPER(this)) {
      throw MakeTypeError("incompatible_method_receiver",
                          ["Number.prototype.toPrecision", this]);
    }
    // Get the value of this number in case it's an object.
    x = %_ValueOf(this);
1640
  }
1641 1642
  if (IS_UNDEFINED(precision)) return ToString(%_ValueOf(this));
  var p = TO_INTEGER(precision);
1643 1644

  if (NUMBER_IS_NAN(x)) return "NaN";
1645 1646
  if (x == INFINITY) return "Infinity";
  if (x == -INFINITY) return "-Infinity";
1647

1648 1649 1650 1651
  if (p < 1 || p > 21) {
    throw new $RangeError("toPrecision() argument must be between 1 and 21");
  }
  return %NumberToPrecision(x, p);
1652 1653 1654
}


1655 1656 1657 1658 1659 1660
// Harmony isFinite.
function NumberIsFinite(number) {
  return IS_NUMBER(number) && NUMBER_IS_FINITE(number);
}


1661 1662 1663 1664 1665 1666
// Harmony isInteger
function NumberIsInteger(number) {
  return NumberIsFinite(number) && TO_INTEGER(number) == number;
}


1667 1668 1669 1670 1671 1672
// Harmony isNaN.
function NumberIsNaN(number) {
  return IS_NUMBER(number) && NUMBER_IS_NAN(number);
}


1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
// Harmony isSafeInteger
function NumberIsSafeInteger(number) {
  if (NumberIsFinite(number)) {
    var integral = TO_INTEGER(number);
    if (integral == number)
      return MathAbs(integral) <= $Number.MAX_SAFE_INTEGER;
  }
  return false;
}


1684 1685
// ----------------------------------------------------------------------------

1686 1687
function SetUpNumber() {
  %CheckIsBootstrapping();
1688 1689 1690 1691

  %SetCode($Number, NumberConstructor);
  %FunctionSetPrototype($Number, new $Number(0));

1692
  %OptimizeObjectForAddingMultipleProperties($Number.prototype, 8);
1693
  // Set up the constructor property on the Number prototype object.
1694 1695
  %SetProperty($Number.prototype, "constructor", $Number, DONT_ENUM);

1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
  InstallConstants($Number, $Array(
      // ECMA-262 section 15.7.3.1.
      "MAX_VALUE", 1.7976931348623157e+308,
      // ECMA-262 section 15.7.3.2.
      "MIN_VALUE", 5e-324,
      // ECMA-262 section 15.7.3.3.
      "NaN", NAN,
      // ECMA-262 section 15.7.3.4.
      "NEGATIVE_INFINITY", -INFINITY,
      // ECMA-262 section 15.7.3.5.
      "POSITIVE_INFINITY", INFINITY,

      // --- Harmony constants (no spec refs until settled.)

      "MAX_SAFE_INTEGER", %_MathPow(2, 53) - 1,
      "MIN_SAFE_INTEGER", -%_MathPow(2, 53) + 1,
      "EPSILON", %_MathPow(2, -52)
  ));
1714

1715
  // Set up non-enumerable functions on the Number prototype object.
1716 1717 1718 1719 1720 1721
  InstallFunctions($Number.prototype, DONT_ENUM, $Array(
    "toString", NumberToString,
    "toLocaleString", NumberToLocaleString,
    "valueOf", NumberValueOf,
    "toFixed", NumberToFixed,
    "toExponential", NumberToExponential,
1722
    "toPrecision", NumberToPrecision
1723
  ));
1724 1725

  // Harmony Number constructor additions
1726 1727
  InstallFunctions($Number, DONT_ENUM, $Array(
    "isFinite", NumberIsFinite,
1728 1729 1730 1731 1732
    "isInteger", NumberIsInteger,
    "isNaN", NumberIsNaN,
    "isSafeInteger", NumberIsSafeInteger,
    "parseInt", GlobalParseInt,
    "parseFloat", GlobalParseFloat
1733
  ));
1734 1735
}

1736
SetUpNumber();
1737

1738 1739 1740 1741 1742

// ----------------------------------------------------------------------------
// Function

function FunctionSourceString(func) {
1743 1744 1745 1746
  while (%IsJSFunctionProxy(func)) {
    func = %GetCallTrap(func);
  }

1747
  if (!IS_FUNCTION(func)) {
1748
    throw new $TypeError('Function.prototype.toString is not generic');
1749
  }
1750 1751

  var source = %FunctionGetSourceCode(func);
1752
  if (!IS_STRING(source) || %FunctionIsBuiltin(func)) {
1753 1754 1755 1756 1757 1758 1759 1760 1761
    var name = %FunctionGetName(func);
    if (name) {
      // Mimic what KJS does.
      return 'function ' + name + '() { [native code] }';
    } else {
      return 'function () { [native code] }';
    }
  }

1762 1763 1764
  var name = %FunctionNameShouldPrintAsAnonymous(func)
      ? 'anonymous'
      : %FunctionGetName(func);
1765 1766
  var head = %FunctionIsGenerator(func) ? 'function* ' : 'function ';
  return head + name + source;
1767
}
1768 1769


1770
function FunctionToString() {
1771
  return FunctionSourceString(this);
1772
}
1773 1774


1775 1776
// ES5 15.3.4.5
function FunctionBind(this_arg) { // Length is 1.
1777
  if (!IS_SPEC_FUNCTION(this)) {
1778 1779 1780
    throw new $TypeError('Bind must be called on a function');
  }
  var boundFunction = function () {
1781 1782
    // Poison .arguments and .caller, but is otherwise not detectable.
    "use strict";
1783 1784 1785 1786
    // This function must not use any object literals (Object, Array, RegExp),
    // since the literals-array is being used to store the bound data.
    if (%_IsConstructCall()) {
      return %NewObjectFromBound(boundFunction);
1787
    }
1788
    var bindings = %BoundFunctionGetBindings(boundFunction);
1789

1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
    var argc = %_ArgumentsLength();
    if (argc == 0) {
      return %Apply(bindings[0], bindings[1], bindings, 2, bindings.length - 2);
    }
    if (bindings.length === 2) {
      return %Apply(bindings[0], bindings[1], arguments, 0, argc);
    }
    var bound_argc = bindings.length - 2;
    var argv = new InternalArray(bound_argc + argc);
    for (var i = 0; i < bound_argc; i++) {
      argv[i] = bindings[i + 2];
    }
    for (var j = 0; j < argc; j++) {
      argv[i++] = %_Arguments(j);
    }
    return %Apply(bindings[0], bindings[1], argv, 0, bound_argc + argc);
  };

  %FunctionRemovePrototype(boundFunction);
  var new_length = 0;
  if (%_ClassOf(this) == "Function") {
    // Function or FunctionProxy.
    var old_length = this.length;
    // FunctionProxies might provide a non-UInt32 value. If so, ignore it.
    if ((typeof old_length === "number") &&
        ((old_length >>> 0) === old_length)) {
1816
      var argc = %_ArgumentsLength();
1817 1818 1819 1820
      if (argc > 0) argc--;  // Don't count the thisArg as parameter.
      new_length = old_length - argc;
      if (new_length < 0) new_length = 0;
    }
1821
  }
1822 1823
  // This runtime function finds any remaining arguments on the stack,
  // so we don't pass the arguments object.
1824 1825
  var result = %FunctionBindArguments(boundFunction, this,
                                      this_arg, new_length);
1826 1827 1828 1829 1830 1831

  // We already have caller and arguments properties on functions,
  // which are non-configurable. It therefore makes no sence to
  // try to redefine these as defined by the spec. The spec says
  // that bind should make these throw a TypeError if get or set
  // is called and make them non-enumerable and non-configurable.
1832
  // To be consistent with our normal functions we leave this as it is.
1833
  // TODO(lrn): Do set these to be thrower.
1834 1835 1836 1837
  return result;
}


1838 1839
function NewFunctionString(arguments, function_token) {
  var n = arguments.length;
1840 1841
  var p = '';
  if (n > 1) {
1842 1843 1844 1845
    p = ToString(arguments[0]);
    for (var i = 1; i < n - 1; i++) {
      p += ',' + ToString(arguments[i]);
    }
1846 1847 1848
    // If the formal parameters string include ) - an illegal
    // character - it may make the combined function expression
    // compile. We avoid this problem by checking for this early on.
1849
    if (%_CallFunction(p, ')', StringIndexOf) != -1) {
1850
      throw MakeSyntaxError('paren_in_arg_string', []);
1851
    }
1852 1853 1854 1855
    // If the formal parameters include an unbalanced block comment, the
    // function must be rejected. Since JavaScript does not allow nested
    // comments we can include a trailing block comment to catch this.
    p += '\n/' + '**/';
1856
  }
1857 1858 1859
  var body = (n > 0) ? ToString(arguments[n - 1]) : '';
  return '(' + function_token + '(' + p + ') {\n' + body + '\n})';
}
1860

1861 1862 1863

function FunctionConstructor(arg1) {  // length == 1
  var source = NewFunctionString(arguments, 'function');
1864
  var global_receiver = %GlobalReceiver(global);
1865 1866
  // Compile the string in the constructor and not a helper so that errors
  // appear to come from here.
1867
  var f = %_CallFunction(global_receiver, %CompileString(source, true));
1868
  %FunctionMarkNameShouldPrintAsAnonymous(f);
1869
  return f;
1870
}
1871

1872 1873 1874

// ----------------------------------------------------------------------------

1875 1876
function SetUpFunction() {
  %CheckIsBootstrapping();
1877

1878
  %SetCode($Function, FunctionConstructor);
1879
  %SetProperty($Function.prototype, "constructor", $Function, DONT_ENUM);
1880

1881
  InstallFunctions($Function.prototype, DONT_ENUM, $Array(
1882
    "bind", FunctionBind,
1883 1884 1885 1886
    "toString", FunctionToString
  ));
}

1887
SetUpFunction();
rossberg@chromium.org's avatar
rossberg@chromium.org committed
1888 1889 1890 1891 1892 1893 1894 1895


//----------------------------------------------------------------------------

// TODO(rossberg): very simple abstraction for generic microtask queue.
// Eventually, we should move to a real event queue that allows to maintain
// relative ordering of different kinds of tasks.

1896 1897 1898 1899 1900 1901 1902
function GetMicrotaskQueue() {
  var microtaskState = %GetMicrotaskState();
  if (IS_UNDEFINED(microtaskState.queue)) {
    microtaskState.queue = new InternalArray;
  }
  return microtaskState.queue;
}
rossberg@chromium.org's avatar
rossberg@chromium.org committed
1903 1904 1905

function RunMicrotasks() {
  while (%SetMicrotaskPending(false)) {
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
    var microtaskState = %GetMicrotaskState();
    if (IS_UNDEFINED(microtaskState.queue))
      return;

    var microtasks = microtaskState.queue;
    microtaskState.queue = new InternalArray;

    for (var i = 0; i < microtasks.length; i++) {
      microtasks[i]();
    }
rossberg@chromium.org's avatar
rossberg@chromium.org committed
1916 1917
  }
}
1918 1919 1920 1921 1922

function EnqueueExternalMicrotask(fn) {
  GetMicrotaskQueue().push(fn);
  %SetMicrotaskPending(true);
}