mirror-debugger.js 76.8 KB
Newer Older
1
// Copyright 2006-2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
// Handle id counters.
6
var next_handle_ = 0;
7 8 9
var next_transient_handle_ = -1;

// Mirror cache.
10
var mirror_cache_ = [];
11 12 13 14 15 16 17
var mirror_cache_enabled_ = true;


function ToggleMirrorCache(value) {
  mirror_cache_enabled_ = value;
  next_handle_ = 0;
  mirror_cache_ = [];
18 19 20
}


21 22
// Wrapper to check whether an object is a Promise.  The call may not work
// if promises are not enabled.
23
// TODO(yangguo): remove try-catch once promises are enabled by default.
24 25
function ObjectIsPromise(value) {
  try {
26 27
    return IS_SPEC_OBJECT(value) &&
           !IS_UNDEFINED(%DebugGetProperty(value, builtins.promiseStatus));
28 29 30 31 32 33
  } catch (e) {
    return false;
  }
}


34 35 36 37
/**
 * Returns the mirror for a specified value or object.
 *
 * @param {value or Object} value the value or object to retreive the mirror for
38 39
 * @param {boolean} transient indicate whether this object is transient and
 *    should not be added to the mirror cache. The default is not transient.
40 41
 * @returns {Mirror} the mirror reflects the passed value or object
 */
42
function MakeMirror(value, opt_transient) {
43
  var mirror;
44 45

  // Look for non transient mirrors in the mirror cache.
46
  if (!opt_transient && mirror_cache_enabled_) {
47 48 49 50 51 52 53 54 55 56
    for (id in mirror_cache_) {
      mirror = mirror_cache_[id];
      if (mirror.value() === value) {
        return mirror;
      }
      // Special check for NaN as NaN == NaN is false.
      if (mirror.isNumber() && isNaN(mirror.value()) &&
          typeof value == 'number' && isNaN(value)) {
        return mirror;
      }
57
    }
58
  }
59

60 61 62 63 64 65 66 67 68 69
  if (IS_UNDEFINED(value)) {
    mirror = new UndefinedMirror();
  } else if (IS_NULL(value)) {
    mirror = new NullMirror();
  } else if (IS_BOOLEAN(value)) {
    mirror = new BooleanMirror(value);
  } else if (IS_NUMBER(value)) {
    mirror = new NumberMirror(value);
  } else if (IS_STRING(value)) {
    mirror = new StringMirror(value);
70 71
  } else if (IS_SYMBOL(value)) {
    mirror = new SymbolMirror(value);
72 73 74 75 76 77 78 79 80 81
  } else if (IS_ARRAY(value)) {
    mirror = new ArrayMirror(value);
  } else if (IS_DATE(value)) {
    mirror = new DateMirror(value);
  } else if (IS_FUNCTION(value)) {
    mirror = new FunctionMirror(value);
  } else if (IS_REGEXP(value)) {
    mirror = new RegExpMirror(value);
  } else if (IS_ERROR(value)) {
    mirror = new ErrorMirror(value);
82 83
  } else if (IS_SCRIPT(value)) {
    mirror = new ScriptMirror(value);
84 85
  } else if (IS_MAP(value) || IS_WEAKMAP(value)) {
    mirror = new MapMirror(value);
86 87
  } else if (IS_SET(value) || IS_WEAKSET(value)) {
    mirror = new SetMirror(value);
88 89
  } else if (ObjectIsPromise(value)) {
    mirror = new PromiseMirror(value);
90 91
  } else if (IS_GENERATOR(value)) {
    mirror = new GeneratorMirror(value);
92
  } else {
93
    mirror = new ObjectMirror(value, OBJECT_TYPE, opt_transient);
94 95
  }

96
  if (mirror_cache_enabled_) mirror_cache_[mirror.handle()] = mirror;
97 98 99 100
  return mirror;
}


101 102 103 104 105 106 107 108
/**
 * Returns the mirror for a specified mirror handle.
 *
 * @param {number} handle the handle to find the mirror for
 * @returns {Mirror or undefiend} the mirror with the requested handle or
 *     undefined if no mirror with the requested handle was found
 */
function LookupMirror(handle) {
109
  if (!mirror_cache_enabled_) throw new Error("Mirror cache is disabled");
110 111 112
  return mirror_cache_[handle];
}

113

114 115 116 117 118 119
/**
 * Returns the mirror for the undefined value.
 *
 * @returns {Mirror} the mirror reflects the undefined value
 */
function GetUndefinedMirror() {
120
  return MakeMirror(UNDEFINED);
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
}


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be revritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype
 * @param {function} superCtor Constructor function to inherit prototype from
 */
function inherits(ctor, superCtor) {
  var tempCtor = function(){};
  tempCtor.prototype = superCtor.prototype;
  ctor.super_ = superCtor.prototype;
  ctor.prototype = new tempCtor();
  ctor.prototype.constructor = ctor;
}


// Type names of the different mirrors.
147 148 149 150 151
var UNDEFINED_TYPE = 'undefined';
var NULL_TYPE = 'null';
var BOOLEAN_TYPE = 'boolean';
var NUMBER_TYPE = 'number';
var STRING_TYPE = 'string';
152
var SYMBOL_TYPE = 'symbol';
153 154 155 156 157
var OBJECT_TYPE = 'object';
var FUNCTION_TYPE = 'function';
var REGEXP_TYPE = 'regexp';
var ERROR_TYPE = 'error';
var PROPERTY_TYPE = 'property';
158
var INTERNAL_PROPERTY_TYPE = 'internalProperty';
159 160 161 162
var FRAME_TYPE = 'frame';
var SCRIPT_TYPE = 'script';
var CONTEXT_TYPE = 'context';
var SCOPE_TYPE = 'scope';
163
var PROMISE_TYPE = 'promise';
164
var MAP_TYPE = 'map';
165
var SET_TYPE = 'set';
166
var GENERATOR_TYPE = 'generator';
167 168

// Maximum length when sending strings through the JSON protocol.
169
var kMaxProtocolStringLength = 80;
170 171

// Different kind of properties.
172
var PropertyKind = {};
173 174 175 176
PropertyKind.Named   = 1;
PropertyKind.Indexed = 2;


177
// A copy of the PropertyType enum from property-details.h
178
var PropertyType = {};
179 180
PropertyType.Normal                  = 0;
PropertyType.Field                   = 1;
181
PropertyType.Constant                = 2;
182
PropertyType.Callbacks               = 3;
183

184 185

// Different attributes for a property.
186
var PropertyAttribute = {};
187 188 189 190 191 192
PropertyAttribute.None       = NONE;
PropertyAttribute.ReadOnly   = READ_ONLY;
PropertyAttribute.DontEnum   = DONT_ENUM;
PropertyAttribute.DontDelete = DONT_DELETE;


193
// A copy of the scope types from runtime.cc.
194 195 196 197 198 199
var ScopeType = { Global: 0,
                  Local: 1,
                  With: 2,
                  Closure: 3,
                  Catch: 4,
                  Block: 5 };
200 201


202 203 204 205 206 207 208
// Mirror hierarchy:
//   - Mirror
//     - ValueMirror
//       - UndefinedMirror
//       - NullMirror
//       - NumberMirror
//       - StringMirror
209
//       - SymbolMirror
210
//       - ObjectMirror
211 212 213 214 215 216
//         - FunctionMirror
//           - UnresolvedFunctionMirror
//         - ArrayMirror
//         - DateMirror
//         - RegExpMirror
//         - ErrorMirror
217
//         - PromiseMirror
218
//         - MapMirror
219
//         - SetMirror
220
//         - GeneratorMirror
221
//     - PropertyMirror
222
//     - InternalPropertyMirror
223 224 225 226 227 228 229 230 231 232 233
//     - FrameMirror
//     - ScriptMirror


/**
 * Base class for all mirror objects.
 * @param {string} type The type of the mirror
 * @constructor
 */
function Mirror(type) {
  this.type_ = type;
234
}
235 236 237 238 239 240 241


Mirror.prototype.type = function() {
  return this.type_;
};


242 243 244 245 246 247
/**
 * Check whether the mirror reflects a value.
 * @returns {boolean} True if the mirror reflects a value.
 */
Mirror.prototype.isValue = function() {
  return this instanceof ValueMirror;
248
};
249 250


251 252 253 254 255 256
/**
 * Check whether the mirror reflects the undefined value.
 * @returns {boolean} True if the mirror reflects the undefined value.
 */
Mirror.prototype.isUndefined = function() {
  return this instanceof UndefinedMirror;
257
};
258 259 260 261 262 263 264 265


/**
 * Check whether the mirror reflects the null value.
 * @returns {boolean} True if the mirror reflects the null value
 */
Mirror.prototype.isNull = function() {
  return this instanceof NullMirror;
266
};
267 268 269 270 271 272 273 274


/**
 * Check whether the mirror reflects a boolean value.
 * @returns {boolean} True if the mirror reflects a boolean value
 */
Mirror.prototype.isBoolean = function() {
  return this instanceof BooleanMirror;
275
};
276 277 278 279 280 281 282 283


/**
 * Check whether the mirror reflects a number value.
 * @returns {boolean} True if the mirror reflects a number value
 */
Mirror.prototype.isNumber = function() {
  return this instanceof NumberMirror;
284
};
285 286 287 288 289 290 291 292


/**
 * Check whether the mirror reflects a string value.
 * @returns {boolean} True if the mirror reflects a string value
 */
Mirror.prototype.isString = function() {
  return this instanceof StringMirror;
293
};
294 295


296 297 298 299 300 301 302 303 304
/**
 * Check whether the mirror reflects a symbol.
 * @returns {boolean} True if the mirror reflects a symbol
 */
Mirror.prototype.isSymbol = function() {
  return this instanceof SymbolMirror;
};


305 306 307 308 309 310
/**
 * Check whether the mirror reflects an object.
 * @returns {boolean} True if the mirror reflects an object
 */
Mirror.prototype.isObject = function() {
  return this instanceof ObjectMirror;
311
};
312 313 314 315 316 317 318 319


/**
 * Check whether the mirror reflects a function.
 * @returns {boolean} True if the mirror reflects a function
 */
Mirror.prototype.isFunction = function() {
  return this instanceof FunctionMirror;
320
};
321 322 323 324 325 326 327 328


/**
 * Check whether the mirror reflects an unresolved function.
 * @returns {boolean} True if the mirror reflects an unresolved function
 */
Mirror.prototype.isUnresolvedFunction = function() {
  return this instanceof UnresolvedFunctionMirror;
329
};
330 331 332 333 334 335 336 337


/**
 * Check whether the mirror reflects an array.
 * @returns {boolean} True if the mirror reflects an array
 */
Mirror.prototype.isArray = function() {
  return this instanceof ArrayMirror;
338
};
339 340 341 342 343 344 345 346


/**
 * Check whether the mirror reflects a date.
 * @returns {boolean} True if the mirror reflects a date
 */
Mirror.prototype.isDate = function() {
  return this instanceof DateMirror;
347
};
348 349 350 351 352 353 354 355


/**
 * Check whether the mirror reflects a regular expression.
 * @returns {boolean} True if the mirror reflects a regular expression
 */
Mirror.prototype.isRegExp = function() {
  return this instanceof RegExpMirror;
356
};
357 358 359 360 361 362 363 364


/**
 * Check whether the mirror reflects an error.
 * @returns {boolean} True if the mirror reflects an error
 */
Mirror.prototype.isError = function() {
  return this instanceof ErrorMirror;
365
};
366 367


368 369 370 371 372 373 374 375 376
/**
 * Check whether the mirror reflects a promise.
 * @returns {boolean} True if the mirror reflects a promise
 */
Mirror.prototype.isPromise = function() {
  return this instanceof PromiseMirror;
};


377 378 379 380 381 382 383 384 385
/**
 * Check whether the mirror reflects a generator object.
 * @returns {boolean} True if the mirror reflects a generator object
 */
Mirror.prototype.isGenerator = function() {
  return this instanceof GeneratorMirror;
};


386 387 388 389 390 391
/**
 * Check whether the mirror reflects a property.
 * @returns {boolean} True if the mirror reflects a property
 */
Mirror.prototype.isProperty = function() {
  return this instanceof PropertyMirror;
392
};
393 394


395 396 397 398 399 400 401 402 403
/**
 * Check whether the mirror reflects an internal property.
 * @returns {boolean} True if the mirror reflects an internal property
 */
Mirror.prototype.isInternalProperty = function() {
  return this instanceof InternalPropertyMirror;
};


404 405 406 407 408 409
/**
 * Check whether the mirror reflects a stack frame.
 * @returns {boolean} True if the mirror reflects a stack frame
 */
Mirror.prototype.isFrame = function() {
  return this instanceof FrameMirror;
410
};
411 412


413 414 415 416 417 418
/**
 * Check whether the mirror reflects a script.
 * @returns {boolean} True if the mirror reflects a script
 */
Mirror.prototype.isScript = function() {
  return this instanceof ScriptMirror;
419
};
420 421


422 423 424 425 426 427
/**
 * Check whether the mirror reflects a context.
 * @returns {boolean} True if the mirror reflects a context
 */
Mirror.prototype.isContext = function() {
  return this instanceof ContextMirror;
428
};
429 430


431 432 433 434 435 436
/**
 * Check whether the mirror reflects a scope.
 * @returns {boolean} True if the mirror reflects a scope
 */
Mirror.prototype.isScope = function() {
  return this instanceof ScopeMirror;
437
};
438 439


440 441 442 443 444 445 446 447 448
/**
 * Check whether the mirror reflects a map.
 * @returns {boolean} True if the mirror reflects a map
 */
Mirror.prototype.isMap = function() {
  return this instanceof MapMirror;
};


449 450 451 452 453 454 455 456 457
/**
 * Check whether the mirror reflects a set.
 * @returns {boolean} True if the mirror reflects a set
 */
Mirror.prototype.isSet = function() {
  return this instanceof SetMirror;
};


458 459 460 461
/**
 * Allocate a handle id for this object.
 */
Mirror.prototype.allocateHandle_ = function() {
462
  if (mirror_cache_enabled_) this.handle_ = next_handle_++;
463
};
464 465


466 467 468 469 470 471
/**
 * Allocate a transient handle id for this object. Transient handles are
 * negative.
 */
Mirror.prototype.allocateTransientHandle_ = function() {
  this.handle_ = next_transient_handle_--;
472
};
473 474


475 476
Mirror.prototype.toText = function() {
  // Simpel to text which is used when on specialization in subclass.
477
  return "#<" + this.constructor.name + ">";
478
};
479 480 481 482 483 484


/**
 * Base class for all value mirror objects.
 * @param {string} type The type of the mirror
 * @param {value} value The value reflected by this mirror
485 486
 * @param {boolean} transient indicate whether this object is transient with a
 *    transient handle
487 488 489
 * @constructor
 * @extends Mirror
 */
490
function ValueMirror(type, value, transient) {
491
  %_CallFunction(this, type, Mirror);
492
  this.value_ = value;
493 494 495 496 497
  if (!transient) {
    this.allocateHandle_();
  } else {
    this.allocateTransientHandle_();
  }
498
}
499 500 501
inherits(ValueMirror, Mirror);


502 503 504 505 506
Mirror.prototype.handle = function() {
  return this.handle_;
};


507 508 509 510 511 512 513 514 515 516
/**
 * Check whether this is a primitive value.
 * @return {boolean} True if the mirror reflects a primitive value
 */
ValueMirror.prototype.isPrimitive = function() {
  var type = this.type();
  return type === 'undefined' ||
         type === 'null' ||
         type === 'boolean' ||
         type === 'number' ||
517 518
         type === 'string' ||
         type === 'symbol';
519 520 521
};


522
/**
523 524 525 526 527 528 529 530 531 532 533 534 535 536
 * Get the actual value reflected by this mirror.
 * @return {value} The value reflected by this mirror
 */
ValueMirror.prototype.value = function() {
  return this.value_;
};


/**
 * Mirror object for Undefined.
 * @constructor
 * @extends ValueMirror
 */
function UndefinedMirror() {
537
  %_CallFunction(this, UNDEFINED_TYPE, UNDEFINED, ValueMirror);
538
}
539 540 541 542 543
inherits(UndefinedMirror, ValueMirror);


UndefinedMirror.prototype.toText = function() {
  return 'undefined';
544
};
545 546 547 548 549 550 551 552


/**
 * Mirror object for null.
 * @constructor
 * @extends ValueMirror
 */
function NullMirror() {
553
  %_CallFunction(this, NULL_TYPE, null, ValueMirror);
554
}
555 556 557 558 559
inherits(NullMirror, ValueMirror);


NullMirror.prototype.toText = function() {
  return 'null';
560
};
561 562 563 564 565 566 567 568 569


/**
 * Mirror object for boolean values.
 * @param {boolean} value The boolean value reflected by this mirror
 * @constructor
 * @extends ValueMirror
 */
function BooleanMirror(value) {
570
  %_CallFunction(this, BOOLEAN_TYPE, value, ValueMirror);
571
}
572 573 574 575 576
inherits(BooleanMirror, ValueMirror);


BooleanMirror.prototype.toText = function() {
  return this.value_ ? 'true' : 'false';
577
};
578 579 580 581 582 583 584 585 586


/**
 * Mirror object for number values.
 * @param {number} value The number value reflected by this mirror
 * @constructor
 * @extends ValueMirror
 */
function NumberMirror(value) {
587
  %_CallFunction(this, NUMBER_TYPE, value, ValueMirror);
588
}
589 590 591 592
inherits(NumberMirror, ValueMirror);


NumberMirror.prototype.toText = function() {
593
  return %_NumberToString(this.value_);
594
};
595 596 597 598 599 600 601 602 603


/**
 * Mirror object for string values.
 * @param {string} value The string value reflected by this mirror
 * @constructor
 * @extends ValueMirror
 */
function StringMirror(value) {
604
  %_CallFunction(this, STRING_TYPE, value, ValueMirror);
605
}
606 607 608 609 610 611 612
inherits(StringMirror, ValueMirror);


StringMirror.prototype.length = function() {
  return this.value_.length;
};

613 614 615
StringMirror.prototype.getTruncatedValue = function(maxLength) {
  if (maxLength != -1 && this.length() > maxLength) {
    return this.value_.substring(0, maxLength) +
616 617
           '... (length: ' + this.length() + ')';
  }
618
  return this.value_;
619
};
620 621 622

StringMirror.prototype.toText = function() {
  return this.getTruncatedValue(kMaxProtocolStringLength);
623
};
624 625


626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
/**
 * Mirror object for a Symbol
 * @param {Object} value The Symbol
 * @constructor
 * @extends Mirror
 */
function SymbolMirror(value) {
  %_CallFunction(this, SYMBOL_TYPE, value, ValueMirror);
}
inherits(SymbolMirror, ValueMirror);


SymbolMirror.prototype.description = function() {
  return %SymbolDescription(%_ValueOf(this.value_));
}


SymbolMirror.prototype.toText = function() {
  return %_CallFunction(this.value_, builtins.SymbolToString);
}


648 649 650
/**
 * Mirror object for objects.
 * @param {object} value The object reflected by this mirror
651 652
 * @param {boolean} transient indicate whether this object is transient with a
 *    transient handle
653 654 655
 * @constructor
 * @extends ValueMirror
 */
656
function ObjectMirror(value, type, transient) {
657
  %_CallFunction(this, type || OBJECT_TYPE, value, transient, ValueMirror);
658
}
659 660 661 662
inherits(ObjectMirror, ValueMirror);


ObjectMirror.prototype.className = function() {
663
  return %_ClassOf(this.value_);
664 665 666 667 668 669 670 671 672 673 674 675 676 677
};


ObjectMirror.prototype.constructorFunction = function() {
  return MakeMirror(%DebugGetProperty(this.value_, 'constructor'));
};


ObjectMirror.prototype.prototypeObject = function() {
  return MakeMirror(%DebugGetProperty(this.value_, 'prototype'));
};


ObjectMirror.prototype.protoObject = function() {
678
  return MakeMirror(%DebugGetPrototype(this.value_));
679 680 681 682 683
};


ObjectMirror.prototype.hasNamedInterceptor = function() {
  // Get information on interceptors for this object.
684
  var x = %GetInterceptorInfo(this.value_);
685 686 687 688 689 690
  return (x & 2) != 0;
};


ObjectMirror.prototype.hasIndexedInterceptor = function() {
  // Get information on interceptors for this object.
691
  var x = %GetInterceptorInfo(this.value_);
692 693 694 695
  return (x & 1) != 0;
};


696 697 698 699 700 701 702 703 704 705 706 707 708
// Get all own property names except for private symbols.
function TryGetPropertyNames(object) {
  try {
    // TODO(yangguo): Should there be a special debugger implementation of
    // %GetOwnPropertyNames that doesn't perform access checks?
    return %GetOwnPropertyNames(object, PROPERTY_ATTRIBUTES_PRIVATE_SYMBOL);
  } catch (e) {
    // Might have hit a failed access check.
    return [];
  }
}


709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
/**
 * Return the property names for this object.
 * @param {number} kind Indicate whether named, indexed or both kinds of
 *     properties are requested
 * @param {number} limit Limit the number of names returend to the specified
       value
 * @return {Array} Property names for this object
 */
ObjectMirror.prototype.propertyNames = function(kind, limit) {
  // Find kind and limit and allocate array for the result
  kind = kind || PropertyKind.Named | PropertyKind.Indexed;

  var propertyNames;
  var elementNames;
  var total = 0;
724

725
  // Find all the named properties.
726
  if (kind & PropertyKind.Named) {
727
    propertyNames = TryGetPropertyNames(this.value_);
728
    total += propertyNames.length;
729 730 731 732

    // Get names for named interceptor properties if any.
    if (this.hasNamedInterceptor() && (kind & PropertyKind.Named)) {
      var namedInterceptorNames =
733
          %GetNamedInterceptorPropertyNames(this.value_);
734 735 736 737 738
      if (namedInterceptorNames) {
        propertyNames = propertyNames.concat(namedInterceptorNames);
        total += namedInterceptorNames.length;
      }
    }
739
  }
740 741

  // Find all the indexed properties.
742
  if (kind & PropertyKind.Indexed) {
743 744
    // Get own element names.
    elementNames = %GetOwnElementNames(this.value_);
745
    total += elementNames.length;
746 747 748 749

    // Get names for indexed interceptor properties.
    if (this.hasIndexedInterceptor() && (kind & PropertyKind.Indexed)) {
      var indexedInterceptorNames =
750
          %GetIndexedInterceptorElementNames(this.value_);
751 752 753 754 755
      if (indexedInterceptorNames) {
        elementNames = elementNames.concat(indexedInterceptorNames);
        total += indexedInterceptorNames.length;
      }
    }
756 757 758 759 760
  }
  limit = Math.min(limit || total, total);

  var names = new Array(limit);
  var index = 0;
761

762 763 764 765 766 767
  // Copy names for named properties.
  if (kind & PropertyKind.Named) {
    for (var i = 0; index < limit && i < propertyNames.length; i++) {
      names[index++] = propertyNames[i];
    }
  }
768

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
  // Copy names for indexed properties.
  if (kind & PropertyKind.Indexed) {
    for (var i = 0; index < limit && i < elementNames.length; i++) {
      names[index++] = elementNames[i];
    }
  }

  return names;
};


/**
 * Return the properties for this object as an array of PropertyMirror objects.
 * @param {number} kind Indicate whether named, indexed or both kinds of
 *     properties are requested
784
 * @param {number} limit Limit the number of properties returned to the
785 786 787 788 789 790 791 792 793 794 795 796 797 798
       specified value
 * @return {Array} Property mirrors for this object
 */
ObjectMirror.prototype.properties = function(kind, limit) {
  var names = this.propertyNames(kind, limit);
  var properties = new Array(names.length);
  for (var i = 0; i < names.length; i++) {
    properties[i] = this.property(names[i]);
  }

  return properties;
};


799 800 801 802 803 804 805 806 807 808
/**
 * Return the internal properties for this object as an array of
 * InternalPropertyMirror objects.
 * @return {Array} Property mirrors for this object
 */
ObjectMirror.prototype.internalProperties = function() {
  return ObjectMirror.GetInternalProperties(this.value_);
}


809
ObjectMirror.prototype.property = function(name) {
810
  var details = %DebugGetPropertyDetails(this.value_, %ToName(name));
811
  if (details) {
812
    return new PropertyMirror(this, name, details);
813 814 815
  }

  // Nothing found.
816
  return GetUndefinedMirror();
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
};



/**
 * Try to find a property from its value.
 * @param {Mirror} value The property value to look for
 * @return {PropertyMirror} The property with the specified value. If no
 *     property was found with the specified value UndefinedMirror is returned
 */
ObjectMirror.prototype.lookupProperty = function(value) {
  var properties = this.properties();

  // Look for property value in properties.
  for (var i = 0; i < properties.length; i++) {

    // Skip properties which are defined through assessors.
    var property = properties[i];
    if (property.propertyType() != PropertyType.Callbacks) {
836
      if (%_ObjectEquals(property.value_, value.value_)) {
837 838 839 840 841 842
        return property;
      }
    }
  }

  // Nothing found.
843
  return GetUndefinedMirror();
844 845 846 847 848
};


/**
 * Returns objects which has direct references to this object
849 850
 * @param {number} opt_max_objects Optional parameter specifying the maximum
 *     number of referencing objects to return.
851 852
 * @return {Array} The objects which has direct references to this object.
 */
853 854 855 856
ObjectMirror.prototype.referencedBy = function(opt_max_objects) {
  // Find all objects with direct references to this object.
  var result = %DebugReferencedBy(this.value_,
                                  Mirror.prototype, opt_max_objects || 0);
857

858
  // Make mirrors for all the references found.
859 860 861
  for (var i = 0; i < result.length; i++) {
    result[i] = MakeMirror(result[i]);
  }
862

863 864 865 866 867 868 869
  return result;
};


ObjectMirror.prototype.toText = function() {
  var name;
  var ctor = this.constructorFunction();
870
  if (!ctor.isFunction()) {
871 872 873 874 875 876 877
    name = this.className();
  } else {
    name = ctor.name();
    if (!name) {
      name = this.className();
    }
  }
878
  return '#<' + name + '>';
879 880 881
};


882 883
/**
 * Return the internal properties of the value, such as [[PrimitiveValue]] of
884 885
 * scalar wrapper objects, properties of the bound function and properties of
 * the promise.
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
 * This method is done static to be accessible from Debug API with the bare
 * values without mirrors.
 * @return {Array} array (possibly empty) of InternalProperty instances
 */
ObjectMirror.GetInternalProperties = function(value) {
  if (IS_STRING_WRAPPER(value) || IS_NUMBER_WRAPPER(value) ||
      IS_BOOLEAN_WRAPPER(value)) {
    var primitiveValue = %_ValueOf(value);
    return [new InternalPropertyMirror("[[PrimitiveValue]]", primitiveValue)];
  } else if (IS_FUNCTION(value)) {
    var bindings = %BoundFunctionGetBindings(value);
    var result = [];
    if (bindings && IS_ARRAY(bindings)) {
      result.push(new InternalPropertyMirror("[[TargetFunction]]",
                                             bindings[0]));
      result.push(new InternalPropertyMirror("[[BoundThis]]", bindings[1]));
      var boundArgs = [];
      for (var i = 2; i < bindings.length; i++) {
        boundArgs.push(bindings[i]);
      }
      result.push(new InternalPropertyMirror("[[BoundArgs]]", boundArgs));
    }
    return result;
909 910 911 912 913 914 915
  } else if (ObjectIsPromise(value)) {
    var result = [];
    result.push(new InternalPropertyMirror("[[PromiseStatus]]",
                                           PromiseGetStatus_(value)));
    result.push(new InternalPropertyMirror("[[PromiseValue]]",
                                           PromiseGetValue_(value)));
    return result;
916 917 918 919 920
  }
  return [];
}


921 922 923 924 925 926 927
/**
 * Mirror object for functions.
 * @param {function} value The function object reflected by this mirror.
 * @constructor
 * @extends ObjectMirror
 */
function FunctionMirror(value) {
928
  %_CallFunction(this, value, FUNCTION_TYPE, ObjectMirror);
929
  this.resolved_ = true;
930
}
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
inherits(FunctionMirror, ObjectMirror);


/**
 * Returns whether the function is resolved.
 * @return {boolean} True if the function is resolved. Unresolved functions can
 *     only originate as functions from stack frames
 */
FunctionMirror.prototype.resolved = function() {
  return this.resolved_;
};


/**
 * Returns the name of the function.
 * @return {string} Name of the function
 */
FunctionMirror.prototype.name = function() {
  return %FunctionGetName(this.value_);
};


953 954 955 956 957 958 959 960 961
/**
 * Returns the inferred name of the function.
 * @return {string} Name of the function
 */
FunctionMirror.prototype.inferredName = function() {
  return %FunctionGetInferredName(this.value_);
};


962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
/**
 * Returns the source code for the function.
 * @return {string or undefined} The source code for the function. If the
 *     function is not resolved undefined will be returned.
 */
FunctionMirror.prototype.source = function() {
  // Return source if function is resolved. Otherwise just fall through to
  // return undefined.
  if (this.resolved()) {
    return builtins.FunctionSourceString(this.value_);
  }
};


/**
 * Returns the script object for the function.
 * @return {ScriptMirror or undefined} Script object for the function or
 *     undefined if the function has no script
 */
FunctionMirror.prototype.script = function() {
  // Return script if function is resolved. Otherwise just fall through
  // to return undefined.
  if (this.resolved()) {
985 986 987
    if (this.script_) {
      return this.script_;
    }
988 989
    var script = %FunctionGetScript(this.value_);
    if (script) {
990
      return this.script_ = MakeMirror(script);
991 992 993 994 995
    }
  }
};


996 997 998 999 1000 1001
/**
 * Returns the script source position for the function. Only makes sense
 * for functions which has a script defined.
 * @return {Number or undefined} in-script position for the function
 */
FunctionMirror.prototype.sourcePosition_ = function() {
1002 1003
  // Return position if function is resolved. Otherwise just fall
  // through to return undefined.
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  if (this.resolved()) {
    return %FunctionGetScriptSourcePosition(this.value_);
  }
};


/**
 * Returns the script source location object for the function. Only makes sense
 * for functions which has a script defined.
 * @return {Location or undefined} in-script location for the function begin
 */
FunctionMirror.prototype.sourceLocation = function() {
1016 1017 1018 1019 1020
  if (this.resolved()) {
    var script = this.script();
    if (script) {
      return script.locationFromPosition(this.sourcePosition_(), true);
    }
1021 1022 1023 1024
  }
};


1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
/**
 * Returns objects constructed by this function.
 * @param {number} opt_max_instances Optional parameter specifying the maximum
 *     number of instances to return.
 * @return {Array or undefined} The objects constructed by this function.
 */
FunctionMirror.prototype.constructedBy = function(opt_max_instances) {
  if (this.resolved()) {
    // Find all objects constructed from this function.
    var result = %DebugConstructedBy(this.value_, opt_max_instances || 0);
1035

1036 1037 1038 1039
    // Make mirrors for all the instances found.
    for (var i = 0; i < result.length; i++) {
      result[i] = MakeMirror(result[i]);
    }
1040

1041 1042 1043 1044 1045 1046 1047
    return result;
  } else {
    return [];
  }
};


1048 1049
FunctionMirror.prototype.scopeCount = function() {
  if (this.resolved()) {
1050 1051 1052 1053
    if (IS_UNDEFINED(this.scopeCount_)) {
      this.scopeCount_ = %GetFunctionScopeCount(this.value());
    }
    return this.scopeCount_;
1054 1055 1056 1057 1058 1059 1060 1061
  } else {
    return 0;
  }
};


FunctionMirror.prototype.scope = function(index) {
  if (this.resolved()) {
1062
    return new ScopeMirror(UNDEFINED, this, index);
1063 1064 1065 1066
  }
};


1067 1068
FunctionMirror.prototype.toText = function() {
  return this.source();
1069
};
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081


/**
 * Mirror object for unresolved functions.
 * @param {string} value The name for the unresolved function reflected by this
 *     mirror.
 * @constructor
 * @extends ObjectMirror
 */
function UnresolvedFunctionMirror(value) {
  // Construct this using the ValueMirror as an unresolved function is not a
  // real object but just a string.
1082
  %_CallFunction(this, FUNCTION_TYPE, value, ValueMirror);
1083 1084 1085
  this.propertyCount_ = 0;
  this.elementCount_ = 0;
  this.resolved_ = false;
1086
}
1087 1088 1089 1090 1091 1092 1093 1094 1095
inherits(UnresolvedFunctionMirror, FunctionMirror);


UnresolvedFunctionMirror.prototype.className = function() {
  return 'Function';
};


UnresolvedFunctionMirror.prototype.constructorFunction = function() {
1096
  return GetUndefinedMirror();
1097 1098 1099 1100
};


UnresolvedFunctionMirror.prototype.prototypeObject = function() {
1101
  return GetUndefinedMirror();
1102 1103 1104 1105
};


UnresolvedFunctionMirror.prototype.protoObject = function() {
1106
  return GetUndefinedMirror();
1107 1108 1109 1110 1111 1112 1113 1114
};


UnresolvedFunctionMirror.prototype.name = function() {
  return this.value_;
};


1115 1116 1117 1118 1119
UnresolvedFunctionMirror.prototype.inferredName = function() {
  return undefined;
};


1120 1121
UnresolvedFunctionMirror.prototype.propertyNames = function(kind, limit) {
  return [];
1122
};
1123 1124 1125 1126 1127 1128 1129 1130 1131


/**
 * Mirror object for arrays.
 * @param {Array} value The Array object reflected by this mirror
 * @constructor
 * @extends ObjectMirror
 */
function ArrayMirror(value) {
1132
  %_CallFunction(this, value, ObjectMirror);
1133
}
1134 1135 1136 1137 1138 1139 1140 1141
inherits(ArrayMirror, ObjectMirror);


ArrayMirror.prototype.length = function() {
  return this.value_.length;
};


1142 1143
ArrayMirror.prototype.indexedPropertiesFromRange = function(opt_from_index,
                                                            opt_to_index) {
1144 1145 1146 1147 1148
  var from_index = opt_from_index || 0;
  var to_index = opt_to_index || this.length() - 1;
  if (from_index > to_index) return new Array();
  var values = new Array(to_index - from_index + 1);
  for (var i = from_index; i <= to_index; i++) {
1149
    var details = %DebugGetPropertyDetails(this.value_, %ToString(i));
1150 1151
    var value;
    if (details) {
1152
      value = new PropertyMirror(this, i, details);
1153
    } else {
1154
      value = GetUndefinedMirror();
1155 1156 1157 1158
    }
    values[i - from_index] = value;
  }
  return values;
1159
};
1160 1161 1162 1163 1164 1165 1166 1167 1168


/**
 * Mirror object for dates.
 * @param {Date} value The Date object reflected by this mirror
 * @constructor
 * @extends ObjectMirror
 */
function DateMirror(value) {
1169
  %_CallFunction(this, value, ObjectMirror);
1170
}
1171 1172 1173 1174
inherits(DateMirror, ObjectMirror);


DateMirror.prototype.toText = function() {
1175 1176
  var s = JSON.stringify(this.value_);
  return s.substring(1, s.length - 1);  // cut quotes
1177
};
1178 1179 1180 1181 1182 1183 1184 1185 1186


/**
 * Mirror object for regular expressions.
 * @param {RegExp} value The RegExp object reflected by this mirror
 * @constructor
 * @extends ObjectMirror
 */
function RegExpMirror(value) {
1187
  %_CallFunction(this, value, REGEXP_TYPE, ObjectMirror);
1188
}
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
inherits(RegExpMirror, ObjectMirror);


/**
 * Returns the source to the regular expression.
 * @return {string or undefined} The source to the regular expression
 */
RegExpMirror.prototype.source = function() {
  return this.value_.source;
};


/**
 * Returns whether this regular expression has the global (g) flag set.
 * @return {boolean} Value of the global flag
 */
RegExpMirror.prototype.global = function() {
  return this.value_.global;
};


/**
 * Returns whether this regular expression has the ignore case (i) flag set.
 * @return {boolean} Value of the ignore case flag
 */
RegExpMirror.prototype.ignoreCase = function() {
  return this.value_.ignoreCase;
};


/**
 * Returns whether this regular expression has the multiline (m) flag set.
 * @return {boolean} Value of the multiline flag
 */
RegExpMirror.prototype.multiline = function() {
  return this.value_.multiline;
};


RegExpMirror.prototype.toText = function() {
  // Simpel to text which is used when on specialization in subclass.
  return "/" + this.source() + "/";
1231
};
1232 1233 1234 1235 1236 1237 1238 1239 1240


/**
 * Mirror object for error objects.
 * @param {Error} value The error object reflected by this mirror
 * @constructor
 * @extends ObjectMirror
 */
function ErrorMirror(value) {
1241
  %_CallFunction(this, value, ERROR_TYPE, ObjectMirror);
1242
}
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
inherits(ErrorMirror, ObjectMirror);


/**
 * Returns the message for this eror object.
 * @return {string or undefined} The message for this eror object
 */
ErrorMirror.prototype.message = function() {
  return this.value_.message;
};


ErrorMirror.prototype.toText = function() {
  // Use the same text representation as in messages.js.
  var text;
  try {
1259
    str = %_CallFunction(this.value_, builtins.ErrorToString);
1260
  } catch (e) {
1261
    str = '#<Error>';
1262 1263
  }
  return str;
1264
};
1265 1266


1267 1268
/**
 * Mirror object for a Promise object.
1269
 * @param {Object} value The Promise object
1270
 * @constructor
1271
 * @extends ObjectMirror
1272 1273 1274 1275 1276 1277 1278
 */
function PromiseMirror(value) {
  %_CallFunction(this, value, PROMISE_TYPE, ObjectMirror);
}
inherits(PromiseMirror, ObjectMirror);


1279 1280
function PromiseGetStatus_(value) {
  var status = %DebugGetProperty(value, builtins.promiseStatus);
1281 1282 1283
  if (status == 0) return "pending";
  if (status == 1) return "resolved";
  return "rejected";
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
}


function PromiseGetValue_(value) {
  return %DebugGetProperty(value, builtins.promiseValue);
}


PromiseMirror.prototype.status = function() {
  return PromiseGetStatus_(this.value_);
1294 1295 1296
};


1297
PromiseMirror.prototype.promiseValue = function() {
1298
  return MakeMirror(PromiseGetValue_(this.value_));
1299 1300 1301
};


1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
function MapMirror(value) {
  %_CallFunction(this, value, MAP_TYPE, ObjectMirror);
}
inherits(MapMirror, ObjectMirror);


/**
 * Returns an array of key/value pairs of a map.
 * This will keep keys alive for WeakMaps.
 *
 * @returns {Array.<Object>} Array of key/value pairs of a map.
 */
MapMirror.prototype.entries = function() {
  var result = [];

  if (IS_WEAKMAP(this.value_)) {
    var entries = %GetWeakMapEntries(this.value_);
    for (var i = 0; i < entries.length; i += 2) {
      result.push({
        key: entries[i],
        value: entries[i + 1]
      });
    }
    return result;
  }

  var iter = %_CallFunction(this.value_, builtins.MapEntries);
  var next;
  while (!(next = iter.next()).done) {
    result.push({
      key: next.value[0],
      value: next.value[1]
    });
  }
  return result;
};


1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
function SetMirror(value) {
  %_CallFunction(this, value, SET_TYPE, ObjectMirror);
}
inherits(SetMirror, ObjectMirror);


/**
 * Returns an array of elements of a set.
 * This will keep elements alive for WeakSets.
 *
 * @returns {Array.<Object>} Array of elements of a set.
 */
SetMirror.prototype.values = function() {
  if (IS_WEAKSET(this.value_)) {
    return %GetWeakSetValues(this.value_);
  }

  var result = [];
  var iter = %_CallFunction(this.value_, builtins.SetValues);
  var next;
  while (!(next = iter.next()).done) {
    result.push(next.value);
  }
  return result;
};


1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
/**
 * Mirror object for a Generator object.
 * @param {Object} data The Generator object
 * @constructor
 * @extends Mirror
 */
function GeneratorMirror(value) {
  %_CallFunction(this, value, GENERATOR_TYPE, ObjectMirror);
}
inherits(GeneratorMirror, ObjectMirror);


GeneratorMirror.prototype.status = function() {
  var continuation = %GeneratorGetContinuation(this.value_);
  if (continuation < 0) return "running";
  if (continuation == 0) return "closed";
  return "suspended";
};


GeneratorMirror.prototype.sourcePosition_ = function() {
  return %GeneratorGetSourcePosition(this.value_);
};


GeneratorMirror.prototype.sourceLocation = function() {
  var pos = this.sourcePosition_();
  if (!IS_UNDEFINED(pos)) {
    var script = this.func().script();
    if (script) {
      return script.locationFromPosition(pos, true);
    }
  }
};


GeneratorMirror.prototype.func = function() {
  if (!this.func_) {
    this.func_ = MakeMirror(%GeneratorGetFunction(this.value_));
  }
  return this.func_;
};


GeneratorMirror.prototype.context = function() {
  if (!this.context_) {
    this.context_ = new ContextMirror(%GeneratorGetContext(this.value_));
  }
  return this.context_;
};


GeneratorMirror.prototype.receiver = function() {
  if (!this.receiver_) {
    this.receiver_ = MakeMirror(%GeneratorGetReceiver(this.value_));
  }
  return this.receiver_;
};


1427 1428 1429 1430
/**
 * Base mirror object for properties.
 * @param {ObjectMirror} mirror The mirror object having this property
 * @param {string} name The name of the property
1431
 * @param {Array} details Details about the property
1432 1433 1434
 * @constructor
 * @extends Mirror
 */
1435
function PropertyMirror(mirror, name, details) {
1436
  %_CallFunction(this, PROPERTY_TYPE, Mirror);
1437 1438
  this.mirror_ = mirror;
  this.name_ = name;
1439 1440
  this.value_ = details[0];
  this.details_ = details[1];
1441 1442 1443 1444 1445
  this.is_interceptor_ = details[2];
  if (details.length > 3) {
    this.exception_ = details[3];
    this.getter_ = details[4];
    this.setter_ = details[5];
1446
  }
1447
}
1448 1449 1450 1451 1452
inherits(PropertyMirror, Mirror);


PropertyMirror.prototype.isReadOnly = function() {
  return (this.attributes() & PropertyAttribute.ReadOnly) != 0;
1453
};
1454 1455 1456 1457


PropertyMirror.prototype.isEnum = function() {
  return (this.attributes() & PropertyAttribute.DontEnum) == 0;
1458
};
1459 1460 1461 1462


PropertyMirror.prototype.canDelete = function() {
  return (this.attributes() & PropertyAttribute.DontDelete) == 0;
1463
};
1464 1465 1466 1467


PropertyMirror.prototype.name = function() {
  return this.name_;
1468
};
1469 1470 1471 1472 1473 1474 1475 1476 1477


PropertyMirror.prototype.isIndexed = function() {
  for (var i = 0; i < this.name_.length; i++) {
    if (this.name_[i] < '0' || '9' < this.name_[i]) {
      return false;
    }
  }
  return true;
1478
};
1479 1480 1481


PropertyMirror.prototype.value = function() {
1482
  return MakeMirror(this.value_, false);
1483
};
1484 1485 1486 1487 1488 1489 1490 1491


/**
 * Returns whether this property value is an exception.
 * @return {booolean} True if this property value is an exception
 */
PropertyMirror.prototype.isException = function() {
  return this.exception_ ? true : false;
1492
};
1493 1494 1495 1496


PropertyMirror.prototype.attributes = function() {
  return %DebugPropertyAttributesFromDetails(this.details_);
1497
};
1498 1499 1500 1501


PropertyMirror.prototype.propertyType = function() {
  return %DebugPropertyTypeFromDetails(this.details_);
1502
};
1503 1504 1505 1506


PropertyMirror.prototype.insertionIndex = function() {
  return %DebugPropertyIndexFromDetails(this.details_);
1507
};
1508 1509 1510


/**
1511 1512
 * Returns whether this property has a getter defined through __defineGetter__.
 * @return {booolean} True if this property has a getter
1513
 */
1514 1515
PropertyMirror.prototype.hasGetter = function() {
  return this.getter_ ? true : false;
1516
};
1517 1518 1519


/**
1520 1521
 * Returns whether this property has a setter defined through __defineSetter__.
 * @return {booolean} True if this property has a setter
1522
 */
1523 1524
PropertyMirror.prototype.hasSetter = function() {
  return this.setter_ ? true : false;
1525
};
1526 1527 1528


/**
1529 1530 1531
 * Returns the getter for this property defined through __defineGetter__.
 * @return {Mirror} FunctionMirror reflecting the getter function or
 *     UndefinedMirror if there is no getter for this property
1532
 */
1533 1534 1535 1536
PropertyMirror.prototype.getter = function() {
  if (this.hasGetter()) {
    return MakeMirror(this.getter_);
  } else {
1537
    return GetUndefinedMirror();
1538
  }
1539
};
1540 1541 1542


/**
1543 1544 1545
 * Returns the setter for this property defined through __defineSetter__.
 * @return {Mirror} FunctionMirror reflecting the setter function or
 *     UndefinedMirror if there is no setter for this property
1546
 */
1547 1548 1549 1550
PropertyMirror.prototype.setter = function() {
  if (this.hasSetter()) {
    return MakeMirror(this.setter_);
  } else {
1551
    return GetUndefinedMirror();
1552
  }
1553
};
1554 1555 1556


/**
1557 1558
 * Returns whether this property is natively implemented by the host or a set
 * through JavaScript code.
1559
 * @return {boolean} True if the property is
1560
 *     UndefinedMirror if there is no setter for this property
1561
 */
1562
PropertyMirror.prototype.isNative = function() {
1563
  return this.is_interceptor_ ||
1564 1565
         ((this.propertyType() == PropertyType.Callbacks) &&
          !this.hasGetter() && !this.hasSetter());
1566
};
1567 1568


1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
/**
 * Mirror object for internal properties. Internal property reflects properties
 * not accessible from user code such as [[BoundThis]] in bound function.
 * Their names are merely symbolic.
 * @param {string} name The name of the property
 * @param {value} property value
 * @constructor
 * @extends Mirror
 */
function InternalPropertyMirror(name, value) {
  %_CallFunction(this, INTERNAL_PROPERTY_TYPE, Mirror);
  this.name_ = name;
  this.value_ = value;
}
inherits(InternalPropertyMirror, Mirror);


InternalPropertyMirror.prototype.name = function() {
  return this.name_;
};


InternalPropertyMirror.prototype.value = function() {
  return MakeMirror(this.value_, false);
};


1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
var kFrameDetailsFrameIdIndex = 0;
var kFrameDetailsReceiverIndex = 1;
var kFrameDetailsFunctionIndex = 2;
var kFrameDetailsArgumentCountIndex = 3;
var kFrameDetailsLocalCountIndex = 4;
var kFrameDetailsSourcePositionIndex = 5;
var kFrameDetailsConstructCallIndex = 6;
var kFrameDetailsAtReturnIndex = 7;
var kFrameDetailsFlagsIndex = 8;
var kFrameDetailsFirstDynamicIndex = 9;
1606

1607 1608 1609
var kFrameDetailsNameIndex = 0;
var kFrameDetailsValueIndex = 1;
var kFrameDetailsNameValueSize = 2;
1610

1611 1612 1613
var kFrameDetailsFlagDebuggerFrameMask = 1 << 0;
var kFrameDetailsFlagOptimizedFrameMask = 1 << 1;
var kFrameDetailsFlagInlinedFrameIndexMask = 7 << 2;
1614

1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
/**
 * Wrapper for the frame details information retreived from the VM. The frame
 * details from the VM is an array with the following content. See runtime.cc
 * Runtime_GetFrameDetails.
 *     0: Id
 *     1: Receiver
 *     2: Function
 *     3: Argument count
 *     4: Local count
 *     5: Source position
 *     6: Construct call
1626
 *     7: Is at return
1627
 *     8: Flags (debugger frame, optimized frame, inlined frame index)
1628 1629
 *     Arguments name, value
 *     Locals name, value
1630
 *     Return value if any
1631 1632 1633 1634 1635 1636 1637
 * @param {number} break_id Current break id
 * @param {number} index Frame number
 * @constructor
 */
function FrameDetails(break_id, index) {
  this.break_id_ = break_id;
  this.details_ = %GetFrameDetails(break_id, index);
1638
}
1639 1640 1641 1642 1643


FrameDetails.prototype.frameId = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsFrameIdIndex];
1644
};
1645 1646 1647 1648 1649


FrameDetails.prototype.receiver = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsReceiverIndex];
1650
};
1651 1652 1653 1654 1655


FrameDetails.prototype.func = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsFunctionIndex];
1656
};
1657 1658 1659 1660 1661


FrameDetails.prototype.isConstructCall = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsConstructCallIndex];
1662
};
1663 1664


1665 1666 1667
FrameDetails.prototype.isAtReturn = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsAtReturnIndex];
1668
};
1669 1670


1671 1672
FrameDetails.prototype.isDebuggerFrame = function() {
  %CheckExecutionState(this.break_id_);
1673
  var f = kFrameDetailsFlagDebuggerFrameMask;
1674
  return (this.details_[kFrameDetailsFlagsIndex] & f) == f;
1675
};
1676 1677 1678 1679


FrameDetails.prototype.isOptimizedFrame = function() {
  %CheckExecutionState(this.break_id_);
1680
  var f = kFrameDetailsFlagOptimizedFrameMask;
1681
  return (this.details_[kFrameDetailsFlagsIndex] & f) == f;
1682
};
1683 1684 1685


FrameDetails.prototype.isInlinedFrame = function() {
1686
  return this.inlinedFrameIndex() > 0;
1687
};
1688 1689 1690


FrameDetails.prototype.inlinedFrameIndex = function() {
1691
  %CheckExecutionState(this.break_id_);
1692
  var f = kFrameDetailsFlagInlinedFrameIndexMask;
1693 1694
  return (this.details_[kFrameDetailsFlagsIndex] & f) >> 2;
};
1695 1696 1697 1698 1699


FrameDetails.prototype.argumentCount = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsArgumentCountIndex];
1700
};
1701 1702 1703 1704 1705 1706 1707


FrameDetails.prototype.argumentName = function(index) {
  %CheckExecutionState(this.break_id_);
  if (index >= 0 && index < this.argumentCount()) {
    return this.details_[kFrameDetailsFirstDynamicIndex +
                         index * kFrameDetailsNameValueSize +
1708
                         kFrameDetailsNameIndex];
1709
  }
1710
};
1711 1712 1713 1714 1715 1716 1717


FrameDetails.prototype.argumentValue = function(index) {
  %CheckExecutionState(this.break_id_);
  if (index >= 0 && index < this.argumentCount()) {
    return this.details_[kFrameDetailsFirstDynamicIndex +
                         index * kFrameDetailsNameValueSize +
1718
                         kFrameDetailsValueIndex];
1719
  }
1720
};
1721 1722 1723 1724 1725


FrameDetails.prototype.localCount = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsLocalCountIndex];
1726
};
1727 1728 1729 1730 1731


FrameDetails.prototype.sourcePosition = function() {
  %CheckExecutionState(this.break_id_);
  return this.details_[kFrameDetailsSourcePositionIndex];
1732
};
1733 1734 1735 1736 1737


FrameDetails.prototype.localName = function(index) {
  %CheckExecutionState(this.break_id_);
  if (index >= 0 && index < this.localCount()) {
1738
    var locals_offset = kFrameDetailsFirstDynamicIndex +
1739
                        this.argumentCount() * kFrameDetailsNameValueSize;
1740 1741
    return this.details_[locals_offset +
                         index * kFrameDetailsNameValueSize +
1742
                         kFrameDetailsNameIndex];
1743
  }
1744
};
1745 1746 1747 1748 1749


FrameDetails.prototype.localValue = function(index) {
  %CheckExecutionState(this.break_id_);
  if (index >= 0 && index < this.localCount()) {
1750
    var locals_offset = kFrameDetailsFirstDynamicIndex +
1751
                        this.argumentCount() * kFrameDetailsNameValueSize;
1752 1753
    return this.details_[locals_offset +
                         index * kFrameDetailsNameValueSize +
1754
                         kFrameDetailsValueIndex];
1755
  }
1756
};
1757 1758


1759 1760 1761 1762 1763 1764 1765 1766
FrameDetails.prototype.returnValue = function() {
  %CheckExecutionState(this.break_id_);
  var return_value_offset =
      kFrameDetailsFirstDynamicIndex +
      (this.argumentCount() + this.localCount()) * kFrameDetailsNameValueSize;
  if (this.details_[kFrameDetailsAtReturnIndex]) {
    return this.details_[return_value_offset];
  }
1767
};
1768 1769


1770
FrameDetails.prototype.scopeCount = function() {
1771 1772 1773 1774
  if (IS_UNDEFINED(this.scopeCount_)) {
    this.scopeCount_ = %GetScopeCount(this.break_id_, this.frameId());
  }
  return this.scopeCount_;
1775
};
1776 1777


1778 1779 1780 1781 1782
FrameDetails.prototype.stepInPositionsImpl = function() {
  return %GetStepInPositions(this.break_id_, this.frameId());
};


1783 1784 1785 1786 1787 1788 1789 1790 1791
/**
 * Mirror object for stack frames.
 * @param {number} break_id The break id in the VM for which this frame is
       valid
 * @param {number} index The frame index (top frame is index 0)
 * @constructor
 * @extends Mirror
 */
function FrameMirror(break_id, index) {
1792
  %_CallFunction(this, FRAME_TYPE, Mirror);
1793 1794 1795
  this.break_id_ = break_id;
  this.index_ = index;
  this.details_ = new FrameDetails(break_id, index);
1796
}
1797 1798 1799
inherits(FrameMirror, Mirror);


1800 1801 1802 1803 1804
FrameMirror.prototype.details = function() {
  return this.details_;
};


1805 1806 1807 1808 1809 1810
FrameMirror.prototype.index = function() {
  return this.index_;
};


FrameMirror.prototype.func = function() {
1811 1812 1813 1814
  if (this.func_) {
    return this.func_;
  }

1815 1816
  // Get the function for this frame from the VM.
  var f = this.details_.func();
1817

1818 1819 1820 1821
  // Create a function mirror. NOTE: MakeMirror cannot be used here as the
  // value returned from the VM might be a string if the function for the
  // frame is unresolved.
  if (IS_FUNCTION(f)) {
1822
    return this.func_ = MakeMirror(f);
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
  } else {
    return new UnresolvedFunctionMirror(f);
  }
};


FrameMirror.prototype.receiver = function() {
  return MakeMirror(this.details_.receiver());
};


FrameMirror.prototype.isConstructCall = function() {
  return this.details_.isConstructCall();
};


1839 1840 1841 1842 1843
FrameMirror.prototype.isAtReturn = function() {
  return this.details_.isAtReturn();
};


1844 1845 1846 1847 1848
FrameMirror.prototype.isDebuggerFrame = function() {
  return this.details_.isDebuggerFrame();
};


1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
FrameMirror.prototype.isOptimizedFrame = function() {
  return this.details_.isOptimizedFrame();
};


FrameMirror.prototype.isInlinedFrame = function() {
  return this.details_.isInlinedFrame();
};


1859 1860 1861 1862 1863
FrameMirror.prototype.inlinedFrameIndex = function() {
  return this.details_.inlinedFrameIndex();
};


1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
FrameMirror.prototype.argumentCount = function() {
  return this.details_.argumentCount();
};


FrameMirror.prototype.argumentName = function(index) {
  return this.details_.argumentName(index);
};


FrameMirror.prototype.argumentValue = function(index) {
  return MakeMirror(this.details_.argumentValue(index));
};


FrameMirror.prototype.localCount = function() {
  return this.details_.localCount();
};


FrameMirror.prototype.localName = function(index) {
  return this.details_.localName(index);
};


FrameMirror.prototype.localValue = function(index) {
  return MakeMirror(this.details_.localValue(index));
};


1894 1895 1896 1897 1898
FrameMirror.prototype.returnValue = function() {
  return MakeMirror(this.details_.returnValue());
};


1899 1900 1901 1902 1903 1904
FrameMirror.prototype.sourcePosition = function() {
  return this.details_.sourcePosition();
};


FrameMirror.prototype.sourceLocation = function() {
1905 1906 1907 1908 1909 1910
  var func = this.func();
  if (func.resolved()) {
    var script = func.script();
    if (script) {
      return script.locationFromPosition(this.sourcePosition(), true);
    }
1911 1912 1913 1914 1915
  }
};


FrameMirror.prototype.sourceLine = function() {
1916 1917 1918
  var location = this.sourceLocation();
  if (location) {
    return location.line;
1919 1920 1921 1922 1923
  }
};


FrameMirror.prototype.sourceColumn = function() {
1924 1925 1926
  var location = this.sourceLocation();
  if (location) {
    return location.column;
1927 1928 1929 1930 1931
  }
};


FrameMirror.prototype.sourceLineText = function() {
1932 1933 1934
  var location = this.sourceLocation();
  if (location) {
    return location.sourceText();
1935 1936 1937 1938
  }
};


1939 1940 1941 1942 1943 1944
FrameMirror.prototype.scopeCount = function() {
  return this.details_.scopeCount();
};


FrameMirror.prototype.scope = function(index) {
1945
  return new ScopeMirror(this, UNDEFINED, index);
1946 1947 1948
};


1949
FrameMirror.prototype.allScopes = function(opt_ignore_nested_scopes) {
1950 1951
  var scopeDetails = %GetAllScopesDetails(this.break_id_,
                                          this.details_.frameId(),
1952 1953
                                          this.details_.inlinedFrameIndex(),
                                          !!opt_ignore_nested_scopes);
1954 1955 1956 1957 1958 1959 1960 1961
  var result = [];
  for (var i = 0; i < scopeDetails.length; ++i) {
    result.push(new ScopeMirror(this, UNDEFINED, i, scopeDetails[i]));
  }
  return result;
};


1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
FrameMirror.prototype.stepInPositions = function() {
  var script = this.func().script();
  var funcOffset = this.func().sourcePosition_();

  var stepInRaw = this.details_.stepInPositionsImpl();
  var result = [];
  if (stepInRaw) {
    for (var i = 0; i < stepInRaw.length; i++) {
      var posStruct = {};
      var offset = script.locationFromPosition(funcOffset + stepInRaw[i],
                                               true);
      serializeLocationFields(offset, posStruct);
      var item = {
        position: posStruct
      };
      result.push(item);
    }
  }

  return result;
};


1985 1986
FrameMirror.prototype.evaluate = function(source, disable_break,
                                          opt_context_object) {
1987 1988 1989 1990 1991 1992
  return MakeMirror(%DebugEvaluate(this.break_id_,
                                   this.details_.frameId(),
                                   this.details_.inlinedFrameIndex(),
                                   source,
                                   Boolean(disable_break),
                                   opt_context_object));
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
};


FrameMirror.prototype.invocationText = function() {
  // Format frame invoaction (receiver, function and arguments).
  var result = '';
  var func = this.func();
  var receiver = this.receiver();
  if (this.isConstructCall()) {
    // For constructor frames display new followed by the function name.
    result += 'new ';
    result += func.name() ? func.name() : '[anonymous]';
2005
  } else if (this.isDebuggerFrame()) {
2006 2007 2008
    result += '[debugger]';
  } else {
    // If the receiver has a className which is 'global' don't display it.
2009 2010
    var display_receiver =
      !receiver.className || (receiver.className() != 'global');
2011 2012 2013 2014 2015
    if (display_receiver) {
      result += receiver.toText();
    }
    // Try to find the function as a property in the receiver. Include the
    // prototype chain in the lookup.
2016
    var property = GetUndefinedMirror();
2017 2018 2019 2020
    if (receiver.isObject()) {
      for (var r = receiver;
           !r.isNull() && property.isUndefined();
           r = r.protoObject()) {
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
        property = r.lookupProperty(func);
      }
    }
    if (!property.isUndefined()) {
      // The function invoked was found on the receiver. Use the property name
      // for the backtrace.
      if (!property.isIndexed()) {
        if (display_receiver) {
          result += '.';
        }
        result += property.name();
      } else {
        result += '[';
        result += property.name();
        result += ']';
      }
      // Also known as - if the name in the function doesn't match the name
      // under which it was looked up.
      if (func.name() && func.name() != property.name()) {
        result += '(aka ' + func.name() + ')';
2041
      }
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
    } else {
      // The function invoked was not found on the receiver. Use the function
      // name if available for the backtrace.
      if (display_receiver) {
        result += '.';
      }
      result += func.name() ? func.name() : '[anonymous]';
    }
  }

  // Render arguments for normal frames.
  if (!this.isDebuggerFrame()) {
    result += '(';
    for (var i = 0; i < this.argumentCount(); i++) {
      if (i != 0) result += ', ';
      if (this.argumentName(i)) {
        result += this.argumentName(i);
        result += '=';
      }
      result += this.argumentValue(i).toText();
    }
    result += ')';
  }
2065

2066 2067 2068 2069
  if (this.isAtReturn()) {
    result += ' returning ';
    result += this.returnValue().toText();
  }
2070

2071
  return result;
2072
};
2073 2074 2075 2076 2077 2078 2079


FrameMirror.prototype.sourceAndPositionText = function() {
  // Format source and position.
  var result = '';
  var func = this.func();
  if (func.resolved()) {
2080 2081 2082 2083
    var script = func.script();
    if (script) {
      if (script.name()) {
        result += script.name();
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
      } else {
        result += '[unnamed]';
      }
      if (!this.isDebuggerFrame()) {
        var location = this.sourceLocation();
        result += ' line ';
        result += !IS_UNDEFINED(location) ? (location.line + 1) : '?';
        result += ' column ';
        result += !IS_UNDEFINED(location) ? (location.column + 1) : '?';
        if (!IS_UNDEFINED(this.sourcePosition())) {
          result += ' (position ' + (this.sourcePosition() + 1) + ')';
        }
      }
    } else {
      result += '[no source]';
    }
  } else {
    result += '[unresolved]';
  }

  return result;
2105
};
2106 2107 2108 2109 2110


FrameMirror.prototype.localsText = function() {
  // Format local variables.
  var result = '';
2111
  var locals_count = this.localCount();
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
  if (locals_count > 0) {
    for (var i = 0; i < locals_count; ++i) {
      result += '      var ';
      result += this.localName(i);
      result += ' = ';
      result += this.localValue(i).toText();
      if (i < locals_count - 1) result += '\n';
    }
  }

  return result;
2123
};
2124 2125


2126 2127 2128 2129 2130 2131 2132 2133 2134
FrameMirror.prototype.restart = function() {
  var result = %LiveEditRestartFrame(this.break_id_, this.index_);
  if (IS_UNDEFINED(result)) {
    result = "Failed to find requested frame";
  }
  return result;
};


2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
FrameMirror.prototype.toText = function(opt_locals) {
  var result = '';
  result += '#' + (this.index() <= 9 ? '0' : '') + this.index();
  result += ' ';
  result += this.invocationText();
  result += ' ';
  result += this.sourceAndPositionText();
  if (opt_locals) {
    result += '\n';
    result += this.localsText();
  }
  return result;
2147
};
2148 2149


2150 2151
var kScopeDetailsTypeIndex = 0;
var kScopeDetailsObjectIndex = 1;
2152

2153
function ScopeDetails(frame, fun, index, opt_details) {
2154 2155
  if (frame) {
    this.break_id_ = frame.break_id_;
2156 2157
    this.details_ = opt_details ||
                    %GetScopeDetails(frame.break_id_,
2158 2159 2160
                                     frame.details_.frameId(),
                                     frame.details_.inlinedFrameIndex(),
                                     index);
2161 2162
    this.frame_id_ = frame.details_.frameId();
    this.inlined_frame_id_ = frame.details_.inlinedFrameIndex();
2163
  } else {
2164
    this.details_ = opt_details || %GetFunctionScopeDetails(fun.value(), index);
2165
    this.fun_value_ = fun.value();
2166 2167
    this.break_id_ = undefined;
  }
2168
  this.index_ = index;
2169 2170 2171 2172
}


ScopeDetails.prototype.type = function() {
2173 2174 2175
  if (!IS_UNDEFINED(this.break_id_)) {
    %CheckExecutionState(this.break_id_);
  }
2176
  return this.details_[kScopeDetailsTypeIndex];
2177
};
2178 2179 2180


ScopeDetails.prototype.object = function() {
2181 2182 2183
  if (!IS_UNDEFINED(this.break_id_)) {
    %CheckExecutionState(this.break_id_);
  }
2184
  return this.details_[kScopeDetailsObjectIndex];
2185
};
2186 2187


2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
ScopeDetails.prototype.setVariableValueImpl = function(name, new_value) {
  var raw_res;
  if (!IS_UNDEFINED(this.break_id_)) {
    %CheckExecutionState(this.break_id_);
    raw_res = %SetScopeVariableValue(this.break_id_, this.frame_id_,
        this.inlined_frame_id_, this.index_, name, new_value);
  } else {
    raw_res = %SetScopeVariableValue(this.fun_value_, null, null, this.index_,
        name, new_value);
  }
  if (!raw_res) {
    throw new Error("Failed to set variable value");
  }
};


2204
/**
2205 2206
 * Mirror object for scope of frame or function. Either frame or function must
 * be specified.
2207
 * @param {FrameMirror} frame The frame this scope is a part of
2208
 * @param {FunctionMirror} function The function this scope is a part of
2209
 * @param {number} index The scope index in the frame
2210
 * @param {Array=} opt_details Raw scope details data
2211 2212 2213
 * @constructor
 * @extends Mirror
 */
2214
function ScopeMirror(frame, function, index, opt_details) {
2215
  %_CallFunction(this, SCOPE_TYPE, Mirror);
2216 2217 2218 2219 2220
  if (frame) {
    this.frame_index_ = frame.index_;
  } else {
    this.frame_index_ = undefined;
  }
2221
  this.scope_index_ = index;
2222
  this.details_ = new ScopeDetails(frame, function, index, opt_details);
2223 2224 2225 2226
}
inherits(ScopeMirror, Mirror);


2227 2228 2229 2230 2231
ScopeMirror.prototype.details = function() {
  return this.details_;
};


2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
ScopeMirror.prototype.frameIndex = function() {
  return this.frame_index_;
};


ScopeMirror.prototype.scopeIndex = function() {
  return this.scope_index_;
};


ScopeMirror.prototype.scopeType = function() {
  return this.details_.type();
};


ScopeMirror.prototype.scopeObject = function() {
  // For local and closure scopes create a transient mirror as these objects are
  // created on the fly materializing the local or closure scopes and
  // therefore will not preserve identity.
  var transient = this.scopeType() == ScopeType.Local ||
                  this.scopeType() == ScopeType.Closure;
  return MakeMirror(this.details_.object(), transient);
};


2257 2258 2259 2260 2261
ScopeMirror.prototype.setVariableValue = function(name, new_value) {
  this.details_.setVariableValueImpl(name, new_value);
};


2262 2263 2264 2265 2266 2267 2268
/**
 * Mirror object for script source.
 * @param {Script} script The script object
 * @constructor
 * @extends Mirror
 */
function ScriptMirror(script) {
2269
  %_CallFunction(this, SCRIPT_TYPE, Mirror);
2270
  this.script_ = script;
2271
  this.context_ = new ContextMirror(script.context_data);
2272
  this.allocateHandle_();
2273
}
2274 2275 2276
inherits(ScriptMirror, Mirror);


2277 2278 2279 2280 2281
ScriptMirror.prototype.value = function() {
  return this.script_;
};


2282
ScriptMirror.prototype.name = function() {
2283
  return this.script_.name || this.script_.nameOrSourceURL();
2284 2285 2286
};


2287 2288 2289 2290 2291
ScriptMirror.prototype.id = function() {
  return this.script_.id;
};


2292 2293 2294 2295 2296
ScriptMirror.prototype.source = function() {
  return this.script_.source;
};


2297 2298 2299 2300 2301
ScriptMirror.prototype.setSource = function(source) {
  %DebugSetScriptSource(this.script_, source);
};


2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
ScriptMirror.prototype.lineOffset = function() {
  return this.script_.line_offset;
};


ScriptMirror.prototype.columnOffset = function() {
  return this.script_.column_offset;
};


2312 2313 2314 2315 2316
ScriptMirror.prototype.data = function() {
  return this.script_.data;
};


2317 2318 2319 2320 2321
ScriptMirror.prototype.scriptType = function() {
  return this.script_.type;
};


2322 2323 2324 2325 2326
ScriptMirror.prototype.compilationType = function() {
  return this.script_.compilation_type;
};


2327 2328 2329 2330 2331
ScriptMirror.prototype.lineCount = function() {
  return this.script_.lineCount();
};


2332 2333 2334
ScriptMirror.prototype.locationFromPosition = function(
    position, include_resource_offset) {
  return this.script_.locationFromPosition(position, include_resource_offset);
2335
};
2336 2337 2338 2339


ScriptMirror.prototype.sourceSlice = function (opt_from_line, opt_to_line) {
  return this.script_.sourceSlice(opt_from_line, opt_to_line);
2340
};
2341 2342


2343 2344 2345 2346 2347
ScriptMirror.prototype.context = function() {
  return this.context_;
};


2348 2349 2350 2351 2352 2353 2354
ScriptMirror.prototype.evalFromScript = function() {
  return MakeMirror(this.script_.eval_from_script);
};


ScriptMirror.prototype.evalFromFunctionName = function() {
  return MakeMirror(this.script_.eval_from_function_name);
2355 2356 2357 2358
};


ScriptMirror.prototype.evalFromLocation = function() {
2359 2360 2361 2362
  var eval_from_script = this.evalFromScript();
  if (!eval_from_script.isUndefined()) {
    var position = this.script_.eval_from_script_position;
    return eval_from_script.locationFromPosition(position, true);
2363 2364 2365 2366
  }
};


2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
ScriptMirror.prototype.toText = function() {
  var result = '';
  result += this.name();
  result += ' (lines: ';
  if (this.lineOffset() > 0) {
    result += this.lineOffset();
    result += '-';
    result += this.lineOffset() + this.lineCount() - 1;
  } else {
    result += this.lineCount();
  }
  result += ')';
  return result;
2380
};
2381 2382


2383 2384 2385 2386 2387 2388 2389
/**
 * Mirror object for context.
 * @param {Object} data The context data
 * @constructor
 * @extends Mirror
 */
function ContextMirror(data) {
2390
  %_CallFunction(this, CONTEXT_TYPE, Mirror);
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
  this.data_ = data;
  this.allocateHandle_();
}
inherits(ContextMirror, Mirror);


ContextMirror.prototype.data = function() {
  return this.data_;
};


2402 2403 2404 2405
/**
 * Returns a mirror serializer
 *
 * @param {boolean} details Set to true to include details
2406 2407 2408
 * @param {Object} options Options comtrolling the serialization
 *     The following options can be set:
 *       includeSource: include ths full source of scripts
2409 2410
 * @returns {MirrorSerializer} mirror serializer
 */
2411 2412
function MakeMirrorSerializer(details, options) {
  return new JSONProtocolSerializer(details, options);
2413 2414 2415 2416 2417 2418 2419 2420 2421
}


/**
 * Object for serializing a mirror objects and its direct references.
 * @param {boolean} details Indicates whether to include details for the mirror
 *     serialized
 * @constructor
 */
2422
function JSONProtocolSerializer(details, options) {
2423
  this.details_ = details;
2424
  this.options_ = options;
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
  this.mirrors_ = [ ];
}


/**
 * Returns a serialization of an object reference. The referenced object are
 * added to the serialization state.
 *
 * @param {Mirror} mirror The mirror to serialize
 * @returns {String} JSON serialization
 */
JSONProtocolSerializer.prototype.serializeReference = function(mirror) {
  return this.serialize_(mirror, true, true);
2438
};
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450


/**
 * Returns a serialization of an object value. The referenced objects are
 * added to the serialization state.
 *
 * @param {Mirror} mirror The mirror to serialize
 * @returns {String} JSON serialization
 */
JSONProtocolSerializer.prototype.serializeValue = function(mirror) {
  var json = this.serialize_(mirror, false, true);
  return json;
2451
};
2452 2453 2454 2455 2456


/**
 * Returns a serialization of all the objects referenced.
 *
2457 2458 2459
 * @param {Mirror} mirror The mirror to serialize.
 * @returns {Array.<Object>} Array of the referenced objects converted to
 *     protcol objects.
2460 2461
 */
JSONProtocolSerializer.prototype.serializeReferencedObjects = function() {
2462 2463
  // Collect the protocol representation of the referenced objects in an array.
  var content = [];
2464

2465 2466
  // Get the number of referenced objects.
  var count = this.mirrors_.length;
2467

2468 2469 2470 2471
  for (var i = 0; i < count; i++) {
    content.push(this.serialize_(this.mirrors_[i], false, false));
  }

2472
  return content;
2473
};
2474 2475


2476 2477
JSONProtocolSerializer.prototype.includeSource_ = function() {
  return this.options_ && this.options_.includeSource;
2478
};
2479 2480


2481 2482
JSONProtocolSerializer.prototype.inlineRefs_ = function() {
  return this.options_ && this.options_.inlineRefs;
2483
};
2484 2485


2486 2487 2488 2489 2490 2491
JSONProtocolSerializer.prototype.maxStringLength_ = function() {
  if (IS_UNDEFINED(this.options_) ||
      IS_UNDEFINED(this.options_.maxStringLength)) {
    return kMaxProtocolStringLength;
  }
  return this.options_.maxStringLength;
2492
};
2493 2494


2495 2496 2497 2498 2499 2500 2501
JSONProtocolSerializer.prototype.add_ = function(mirror) {
  // If this mirror is already in the list just return.
  for (var i = 0; i < this.mirrors_.length; i++) {
    if (this.mirrors_[i] === mirror) {
      return;
    }
  }
2502

2503 2504
  // Add the mirror to the list of mirrors to be serialized.
  this.mirrors_.push(mirror);
2505
};
2506 2507


2508 2509 2510 2511 2512 2513
/**
 * Formats mirror object to protocol reference object with some data that can
 * be used to display the value in debugger.
 * @param {Mirror} mirror Mirror to serialize.
 * @return {Object} Protocol reference object.
 */
2514
JSONProtocolSerializer.prototype.serializeReferenceWithDisplayData_ =
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
    function(mirror) {
  var o = {};
  o.ref = mirror.handle();
  o.type = mirror.type();
  switch (mirror.type()) {
    case UNDEFINED_TYPE:
    case NULL_TYPE:
    case BOOLEAN_TYPE:
    case NUMBER_TYPE:
      o.value = mirror.value();
      break;
    case STRING_TYPE:
2527
      o.value = mirror.getTruncatedValue(this.maxStringLength_());
2528
      break;
2529 2530 2531
    case SYMBOL_TYPE:
      o.description = mirror.description();
      break;
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
    case FUNCTION_TYPE:
      o.name = mirror.name();
      o.inferredName = mirror.inferredName();
      if (mirror.script()) {
        o.scriptId = mirror.script().id();
      }
      break;
    case ERROR_TYPE:
    case REGEXP_TYPE:
      o.value = mirror.toText();
      break;
    case OBJECT_TYPE:
      o.className = mirror.className();
      break;
  }
  return o;
};

2550

2551 2552
JSONProtocolSerializer.prototype.serialize_ = function(mirror, reference,
                                                       details) {
2553 2554 2555
  // If serializing a reference to a mirror just return the reference and add
  // the mirror to the referenced mirrors.
  if (reference &&
2556
      (mirror.isValue() || mirror.isScript() || mirror.isContext())) {
2557
    if (this.inlineRefs_() && mirror.isValue()) {
2558 2559 2560 2561 2562
      return this.serializeReferenceWithDisplayData_(mirror);
    } else {
      this.add_(mirror);
      return {'ref' : mirror.handle()};
    }
2563
  }
2564

2565 2566
  // Collect the JSON property/value pairs.
  var content = {};
2567

2568
  // Add the mirror handle.
2569
  if (mirror.isValue() || mirror.isScript() || mirror.isContext()) {
2570
    content.handle = mirror.handle();
2571 2572 2573
  }

  // Always add the type.
2574
  content.type = mirror.type();
2575 2576 2577 2578 2579 2580 2581 2582 2583

  switch (mirror.type()) {
    case UNDEFINED_TYPE:
    case NULL_TYPE:
      // Undefined and null are represented just by their type.
      break;

    case BOOLEAN_TYPE:
      // Boolean values are simply represented by their value.
2584
      content.value = mirror.value();
2585 2586 2587 2588
      break;

    case NUMBER_TYPE:
      // Number values are simply represented by their value.
2589
      content.value = NumberToJSON_(mirror.value());
2590 2591 2592 2593
      break;

    case STRING_TYPE:
      // String values might have their value cropped to keep down size.
2594 2595 2596
      if (this.maxStringLength_() != -1 &&
          mirror.length() > this.maxStringLength_()) {
        var str = mirror.getTruncatedValue(this.maxStringLength_());
2597 2598
        content.value = str;
        content.fromIndex = 0;
2599
        content.toIndex = this.maxStringLength_();
2600
      } else {
2601
        content.value = mirror.value();
2602
      }
2603
      content.length = mirror.length();
2604 2605
      break;

2606 2607 2608 2609
    case SYMBOL_TYPE:
      content.description = mirror.description();
      break;

2610 2611 2612 2613
    case OBJECT_TYPE:
    case FUNCTION_TYPE:
    case ERROR_TYPE:
    case REGEXP_TYPE:
2614
    case PROMISE_TYPE:
2615
    case GENERATOR_TYPE:
2616
      // Add object representation.
2617
      this.serializeObject_(mirror, content, details);
2618 2619 2620
      break;

    case PROPERTY_TYPE:
2621 2622
    case INTERNAL_PROPERTY_TYPE:
      throw new Error('PropertyMirror cannot be serialized independently');
2623 2624 2625 2626 2627 2628 2629
      break;

    case FRAME_TYPE:
      // Add object representation.
      this.serializeFrame_(mirror, content);
      break;

2630 2631 2632 2633 2634
    case SCOPE_TYPE:
      // Add object representation.
      this.serializeScope_(mirror, content);
      break;

2635
    case SCRIPT_TYPE:
2636
      // Script is represented by id, name and source attributes.
2637
      if (mirror.name()) {
2638
        content.name = mirror.name();
2639
      }
2640 2641 2642 2643
      content.id = mirror.id();
      content.lineOffset = mirror.lineOffset();
      content.columnOffset = mirror.columnOffset();
      content.lineCount = mirror.lineCount();
2644
      if (mirror.data()) {
2645
        content.data = mirror.data();
2646 2647
      }
      if (this.includeSource_()) {
2648
        content.source = mirror.source();
2649 2650
      } else {
        var sourceStart = mirror.source().substring(0, 80);
2651
        content.sourceStart = sourceStart;
2652
      }
2653 2654
      content.sourceLength = mirror.source().length;
      content.scriptType = mirror.scriptType();
2655
      content.compilationType = mirror.compilationType();
2656 2657 2658
      // For compilation type eval emit information on the script from which
      // eval was called if a script is present.
      if (mirror.compilationType() == 1 &&
2659
          mirror.evalFromScript()) {
2660
        content.evalFromScript =
2661
            this.serializeReference(mirror.evalFromScript());
2662
        var evalFromLocation = mirror.evalFromLocation();
2663 2664 2665 2666
        if (evalFromLocation) {
          content.evalFromLocation = { line: evalFromLocation.line,
                                       column: evalFromLocation.column };
        }
2667 2668 2669
        if (mirror.evalFromFunctionName()) {
          content.evalFromFunctionName = mirror.evalFromFunctionName();
        }
2670
      }
2671
      if (mirror.context()) {
2672
        content.context = this.serializeReference(mirror.context());
2673 2674 2675 2676
      }
      break;

    case CONTEXT_TYPE:
2677
      content.data = mirror.data();
2678 2679 2680 2681
      break;
  }

  // Always add the text representation.
2682
  content.text = mirror.toText();
2683

2684
  // Create and return the JSON string.
2685
  return content;
2686
};
2687 2688


2689 2690 2691 2692 2693 2694 2695 2696 2697
/**
 * Serialize object information to the following JSON format.
 *
 *   {"className":"<class name>",
 *    "constructorFunction":{"ref":<number>},
 *    "protoObject":{"ref":<number>},
 *    "prototypeObject":{"ref":<number>},
 *    "namedInterceptor":<boolean>,
 *    "indexedInterceptor":<boolean>,
2698 2699
 *    "properties":[<properties>],
 *    "internalProperties":[<internal properties>]}
2700 2701 2702 2703
 */
JSONProtocolSerializer.prototype.serializeObject_ = function(mirror, content,
                                                             details) {
  // Add general object properties.
2704 2705 2706 2707 2708
  content.className = mirror.className();
  content.constructorFunction =
      this.serializeReference(mirror.constructorFunction());
  content.protoObject = this.serializeReference(mirror.protoObject());
  content.prototypeObject = this.serializeReference(mirror.prototypeObject());
2709 2710

  // Add flags to indicate whether there are interceptors.
2711
  if (mirror.hasNamedInterceptor()) {
2712
    content.namedInterceptor = true;
2713 2714
  }
  if (mirror.hasIndexedInterceptor()) {
2715
    content.indexedInterceptor = true;
2716
  }
2717

2718 2719
  if (mirror.isFunction()) {
    // Add function specific properties.
2720
    content.name = mirror.name();
2721
    if (!IS_UNDEFINED(mirror.inferredName())) {
2722
      content.inferredName = mirror.inferredName();
2723
    }
2724
    content.resolved = mirror.resolved();
2725
    if (mirror.resolved()) {
2726
      content.source = mirror.source();
2727 2728
    }
    if (mirror.script()) {
2729
      content.script = this.serializeReference(mirror.script());
2730
      content.scriptId = mirror.script().id();
2731

2732
      serializeLocationFields(mirror.sourceLocation(), content);
2733
    }
2734 2735 2736 2737 2738 2739 2740 2741 2742

    content.scopes = [];
    for (var i = 0; i < mirror.scopeCount(); i++) {
      var scope = mirror.scope(i);
      content.scopes.push({
        type: scope.scopeType(),
        index: i
      });
    }
2743 2744
  }

2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
  if (mirror.isGenerator()) {
    // Add generator specific properties.

    // Either 'running', 'closed', or 'suspended'.
    content.status = mirror.status();

    content.func = this.serializeReference(mirror.func())
    content.receiver = this.serializeReference(mirror.receiver())

    // If the generator is suspended, the content add line/column properties.
    serializeLocationFields(mirror.sourceLocation(), content);

    // TODO(wingo): Also serialize a reference to the context (scope chain).
  }

2760
  if (mirror.isDate()) {
2761
    // Add date specific properties.
2762
    content.value = mirror.value();
2763
  }
2764

2765 2766 2767
  if (mirror.isPromise()) {
    // Add promise specific properties.
    content.status = mirror.status();
2768
    content.promiseValue = this.serializeReference(mirror.promiseValue());
2769 2770
  }

2771 2772 2773 2774 2775
  // Add actual properties - named properties followed by indexed properties.
  var propertyNames = mirror.propertyNames(PropertyKind.Named);
  var propertyIndexes = mirror.propertyNames(PropertyKind.Indexed);
  var p = new Array(propertyNames.length + propertyIndexes.length);
  for (var i = 0; i < propertyNames.length; i++) {
2776 2777
    var propertyMirror = mirror.property(propertyNames[i]);
    p[i] = this.serializeProperty_(propertyMirror);
2778
    if (details) {
2779
      this.add_(propertyMirror.value());
2780 2781 2782
    }
  }
  for (var i = 0; i < propertyIndexes.length; i++) {
2783 2784
    var propertyMirror = mirror.property(propertyIndexes[i]);
    p[propertyNames.length + i] = this.serializeProperty_(propertyMirror);
2785
    if (details) {
2786
      this.add_(propertyMirror.value());
2787 2788
    }
  }
2789
  content.properties = p;
2790 2791 2792 2793 2794 2795 2796 2797 2798

  var internalProperties = mirror.internalProperties();
  if (internalProperties.length > 0) {
    var ip = [];
    for (var i = 0; i < internalProperties.length; i++) {
      ip.push(this.serializeInternalProperty_(internalProperties[i]));
    }
    content.internalProperties = ip;
  }
2799
};
2800 2801


2802 2803 2804 2805 2806 2807
/**
 * Serialize location information to the following JSON format:
 *
 *   "position":"<position>",
 *   "line":"<line>",
 *   "column":"<column>",
2808
 *
2809 2810 2811 2812 2813
 * @param {SourceLocation} location The location to serialize, may be undefined.
 */
function serializeLocationFields (location, content) {
  if (!location) {
    return;
2814
  }
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
  content.position = location.position;
  var line = location.line;
  if (!IS_UNDEFINED(line)) {
    content.line = line;
  }
  var column = location.column;
  if (!IS_UNDEFINED(column)) {
    content.column = column;
  }
}


2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
/**
 * Serialize property information to the following JSON format for building the
 * array of properties.
 *
 *   {"name":"<property name>",
 *    "attributes":<number>,
 *    "propertyType":<number>,
 *    "ref":<number>}
 *
 * If the attribute for the property is PropertyAttribute.None it is not added.
 * If the propertyType for the property is PropertyType.Normal it is not added.
 * Here are a couple of examples.
 *
 *   {"name":"hello","ref":1}
 *   {"name":"length","attributes":7,"propertyType":3,"ref":2}
 *
2843 2844
 * @param {PropertyMirror} propertyMirror The property to serialize.
 * @returns {Object} Protocol object representing the property.
2845
 */
2846 2847
JSONProtocolSerializer.prototype.serializeProperty_ = function(propertyMirror) {
  var result = {};
2848

2849
  result.name = propertyMirror.name();
2850
  var propertyValue = propertyMirror.value();
2851
  if (this.inlineRefs_() && propertyValue.isValue()) {
2852 2853 2854 2855 2856 2857 2858 2859 2860
    result.value = this.serializeReferenceWithDisplayData_(propertyValue);
  } else {
    if (propertyMirror.attributes() != PropertyAttribute.None) {
      result.attributes = propertyMirror.attributes();
    }
    if (propertyMirror.propertyType() != PropertyType.Normal) {
      result.propertyType = propertyMirror.propertyType();
    }
    result.ref = propertyValue.handle();
2861
  }
2862
  return result;
2863
};
2864 2865


2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
/**
 * Serialize internal property information to the following JSON format for
 * building the array of properties.
 *
 *   {"name":"<property name>",
 *    "ref":<number>}
 *
 *   {"name":"[[BoundThis]]","ref":117}
 *
 * @param {InternalPropertyMirror} propertyMirror The property to serialize.
 * @returns {Object} Protocol object representing the property.
 */
JSONProtocolSerializer.prototype.serializeInternalProperty_ =
    function(propertyMirror) {
  var result = {};

  result.name = propertyMirror.name();
  var propertyValue = propertyMirror.value();
  if (this.inlineRefs_() && propertyValue.isValue()) {
    result.value = this.serializeReferenceWithDisplayData_(propertyValue);
  } else {
    result.ref = propertyValue.handle();
  }
  return result;
};


2893
JSONProtocolSerializer.prototype.serializeFrame_ = function(mirror, content) {
2894 2895
  content.index = mirror.index();
  content.receiver = this.serializeReference(mirror.receiver());
2896
  var func = mirror.func();
2897
  content.func = this.serializeReference(func);
2898 2899 2900
  var script = func.script();
  if (script) {
    content.script = this.serializeReference(script);
2901
  }
2902
  content.constructCall = mirror.isConstructCall();
2903 2904 2905 2906
  content.atReturn = mirror.isAtReturn();
  if (mirror.isAtReturn()) {
    content.returnValue = this.serializeReference(mirror.returnValue());
  }
2907
  content.debuggerFrame = mirror.isDebuggerFrame();
2908 2909
  var x = new Array(mirror.argumentCount());
  for (var i = 0; i < mirror.argumentCount(); i++) {
2910
    var arg = {};
2911
    var argument_name = mirror.argumentName(i);
2912
    if (argument_name) {
2913
      arg.name = argument_name;
2914
    }
2915 2916
    arg.value = this.serializeReference(mirror.argumentValue(i));
    x[i] = arg;
2917
  }
2918
  content.arguments = x;
2919 2920
  var x = new Array(mirror.localCount());
  for (var i = 0; i < mirror.localCount(); i++) {
2921 2922 2923 2924
    var local = {};
    local.name = mirror.localName(i);
    local.value = this.serializeReference(mirror.localValue(i));
    x[i] = local;
2925
  }
2926
  content.locals = x;
2927
  serializeLocationFields(mirror.sourceLocation(), content);
2928 2929
  var source_line_text = mirror.sourceLineText();
  if (!IS_UNDEFINED(source_line_text)) {
2930
    content.sourceLineText = source_line_text;
2931
  }
2932

2933 2934 2935 2936 2937 2938 2939 2940
  content.scopes = [];
  for (var i = 0; i < mirror.scopeCount(); i++) {
    var scope = mirror.scope(i);
    content.scopes.push({
      type: scope.scopeType(),
      index: i
    });
  }
2941
};
2942 2943


2944 2945 2946 2947
JSONProtocolSerializer.prototype.serializeScope_ = function(mirror, content) {
  content.index = mirror.scopeIndex();
  content.frameIndex = mirror.frameIndex();
  content.type = mirror.scopeType();
2948 2949 2950
  content.object = this.inlineRefs_() ?
                   this.serializeValue(mirror.scopeObject()) :
                   this.serializeReference(mirror.scopeObject());
2951
};
2952 2953


2954
/**
2955 2956
 * Convert a number to a protocol value. For all finite numbers the number
 * itself is returned. For non finite numbers NaN, Infinite and
2957
 * -Infinite the string representation "NaN", "Infinite" or "-Infinite"
2958
 * (not including the quotes) is returned.
2959
 *
2960 2961
 * @param {number} value The number value to convert to a protocol value.
 * @returns {number|string} Protocol value.
2962
 */
2963
function NumberToJSON_(value) {
2964
  if (isNaN(value)) {
2965
    return 'NaN';
2966
  }
2967
  if (!NUMBER_IS_FINITE(value)) {
2968
    if (value > 0) {
2969
      return 'Infinity';
2970
    } else {
2971
      return '-Infinity';
2972 2973
    }
  }
2974
  return value;
2975
}