Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / v8 / src / mirror-debugger.js
1 // Copyright 2006-2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Handle id counters.
6 var next_handle_ = 0;
7 var next_transient_handle_ = -1;
8
9 // Mirror cache.
10 var mirror_cache_ = [];
11
12
13 /**
14  * Clear the mirror handle cache.
15  */
16 function ClearMirrorCache() {
17   next_handle_ = 0;
18   mirror_cache_ = [];
19 }
20
21
22 // Wrapper to check whether an object is a Promise.  The call may not work
23 // if promises are not enabled.
24 // TODO(yangguo): remove this wrapper once promises are enabled by default.
25 function ObjectIsPromise(value) {
26   try {
27     return %IsPromise(value);
28   } catch (e) {
29     return false;
30   }
31 }
32
33
34 /**
35  * Returns the mirror for a specified value or object.
36  *
37  * @param {value or Object} value the value or object to retreive the mirror for
38  * @param {boolean} transient indicate whether this object is transient and
39  *    should not be added to the mirror cache. The default is not transient.
40  * @returns {Mirror} the mirror reflects the passed value or object
41  */
42 function MakeMirror(value, opt_transient) {
43   var mirror;
44
45   // Look for non transient mirrors in the mirror cache.
46   if (!opt_transient) {
47     for (id in mirror_cache_) {
48       mirror = mirror_cache_[id];
49       if (mirror.value() === value) {
50         return mirror;
51       }
52       // Special check for NaN as NaN == NaN is false.
53       if (mirror.isNumber() && isNaN(mirror.value()) &&
54           typeof value == 'number' && isNaN(value)) {
55         return mirror;
56       }
57     }
58   }
59
60   if (IS_UNDEFINED(value)) {
61     mirror = new UndefinedMirror();
62   } else if (IS_NULL(value)) {
63     mirror = new NullMirror();
64   } else if (IS_BOOLEAN(value)) {
65     mirror = new BooleanMirror(value);
66   } else if (IS_NUMBER(value)) {
67     mirror = new NumberMirror(value);
68   } else if (IS_STRING(value)) {
69     mirror = new StringMirror(value);
70   } else if (IS_ARRAY(value)) {
71     mirror = new ArrayMirror(value);
72   } else if (IS_DATE(value)) {
73     mirror = new DateMirror(value);
74   } else if (IS_FUNCTION(value)) {
75     mirror = new FunctionMirror(value);
76   } else if (IS_REGEXP(value)) {
77     mirror = new RegExpMirror(value);
78   } else if (IS_ERROR(value)) {
79     mirror = new ErrorMirror(value);
80   } else if (IS_SCRIPT(value)) {
81     mirror = new ScriptMirror(value);
82   } else if (ObjectIsPromise(value)) {
83     mirror = new PromiseMirror(value);
84   } else {
85     mirror = new ObjectMirror(value, OBJECT_TYPE, opt_transient);
86   }
87
88   mirror_cache_[mirror.handle()] = mirror;
89   return mirror;
90 }
91
92
93 /**
94  * Returns the mirror for a specified mirror handle.
95  *
96  * @param {number} handle the handle to find the mirror for
97  * @returns {Mirror or undefiend} the mirror with the requested handle or
98  *     undefined if no mirror with the requested handle was found
99  */
100 function LookupMirror(handle) {
101   return mirror_cache_[handle];
102 }
103
104
105 /**
106  * Returns the mirror for the undefined value.
107  *
108  * @returns {Mirror} the mirror reflects the undefined value
109  */
110 function GetUndefinedMirror() {
111   return MakeMirror(UNDEFINED);
112 }
113
114
115 /**
116  * Inherit the prototype methods from one constructor into another.
117  *
118  * The Function.prototype.inherits from lang.js rewritten as a standalone
119  * function (not on Function.prototype). NOTE: If this file is to be loaded
120  * during bootstrapping this function needs to be revritten using some native
121  * functions as prototype setup using normal JavaScript does not work as
122  * expected during bootstrapping (see mirror.js in r114903).
123  *
124  * @param {function} ctor Constructor function which needs to inherit the
125  *     prototype
126  * @param {function} superCtor Constructor function to inherit prototype from
127  */
128 function inherits(ctor, superCtor) {
129   var tempCtor = function(){};
130   tempCtor.prototype = superCtor.prototype;
131   ctor.super_ = superCtor.prototype;
132   ctor.prototype = new tempCtor();
133   ctor.prototype.constructor = ctor;
134 }
135
136
137 // Type names of the different mirrors.
138 var UNDEFINED_TYPE = 'undefined';
139 var NULL_TYPE = 'null';
140 var BOOLEAN_TYPE = 'boolean';
141 var NUMBER_TYPE = 'number';
142 var STRING_TYPE = 'string';
143 var OBJECT_TYPE = 'object';
144 var FUNCTION_TYPE = 'function';
145 var REGEXP_TYPE = 'regexp';
146 var ERROR_TYPE = 'error';
147 var PROPERTY_TYPE = 'property';
148 var INTERNAL_PROPERTY_TYPE = 'internalProperty';
149 var FRAME_TYPE = 'frame';
150 var SCRIPT_TYPE = 'script';
151 var CONTEXT_TYPE = 'context';
152 var SCOPE_TYPE = 'scope';
153 var PROMISE_TYPE = 'promise';
154
155 // Maximum length when sending strings through the JSON protocol.
156 var kMaxProtocolStringLength = 80;
157
158 // Different kind of properties.
159 var PropertyKind = {};
160 PropertyKind.Named   = 1;
161 PropertyKind.Indexed = 2;
162
163
164 // A copy of the PropertyType enum from global.h
165 var PropertyType = {};
166 PropertyType.Normal                  = 0;
167 PropertyType.Field                   = 1;
168 PropertyType.Constant                = 2;
169 PropertyType.Callbacks               = 3;
170 PropertyType.Handler                 = 4;
171 PropertyType.Interceptor             = 5;
172 PropertyType.Transition              = 6;
173 PropertyType.Nonexistent             = 7;
174
175
176 // Different attributes for a property.
177 var PropertyAttribute = {};
178 PropertyAttribute.None       = NONE;
179 PropertyAttribute.ReadOnly   = READ_ONLY;
180 PropertyAttribute.DontEnum   = DONT_ENUM;
181 PropertyAttribute.DontDelete = DONT_DELETE;
182
183
184 // A copy of the scope types from runtime.cc.
185 var ScopeType = { Global: 0,
186                   Local: 1,
187                   With: 2,
188                   Closure: 3,
189                   Catch: 4,
190                   Block: 5 };
191
192
193 // Mirror hierarchy:
194 //   - Mirror
195 //     - ValueMirror
196 //       - UndefinedMirror
197 //       - NullMirror
198 //       - NumberMirror
199 //       - StringMirror
200 //       - ObjectMirror
201 //         - FunctionMirror
202 //           - UnresolvedFunctionMirror
203 //         - ArrayMirror
204 //         - DateMirror
205 //         - RegExpMirror
206 //         - ErrorMirror
207 //         - PromiseMirror
208 //     - PropertyMirror
209 //     - InternalPropertyMirror
210 //     - FrameMirror
211 //     - ScriptMirror
212
213
214 /**
215  * Base class for all mirror objects.
216  * @param {string} type The type of the mirror
217  * @constructor
218  */
219 function Mirror(type) {
220   this.type_ = type;
221 }
222
223
224 Mirror.prototype.type = function() {
225   return this.type_;
226 };
227
228
229 /**
230  * Check whether the mirror reflects a value.
231  * @returns {boolean} True if the mirror reflects a value.
232  */
233 Mirror.prototype.isValue = function() {
234   return this instanceof ValueMirror;
235 };
236
237
238 /**
239  * Check whether the mirror reflects the undefined value.
240  * @returns {boolean} True if the mirror reflects the undefined value.
241  */
242 Mirror.prototype.isUndefined = function() {
243   return this instanceof UndefinedMirror;
244 };
245
246
247 /**
248  * Check whether the mirror reflects the null value.
249  * @returns {boolean} True if the mirror reflects the null value
250  */
251 Mirror.prototype.isNull = function() {
252   return this instanceof NullMirror;
253 };
254
255
256 /**
257  * Check whether the mirror reflects a boolean value.
258  * @returns {boolean} True if the mirror reflects a boolean value
259  */
260 Mirror.prototype.isBoolean = function() {
261   return this instanceof BooleanMirror;
262 };
263
264
265 /**
266  * Check whether the mirror reflects a number value.
267  * @returns {boolean} True if the mirror reflects a number value
268  */
269 Mirror.prototype.isNumber = function() {
270   return this instanceof NumberMirror;
271 };
272
273
274 /**
275  * Check whether the mirror reflects a string value.
276  * @returns {boolean} True if the mirror reflects a string value
277  */
278 Mirror.prototype.isString = function() {
279   return this instanceof StringMirror;
280 };
281
282
283 /**
284  * Check whether the mirror reflects an object.
285  * @returns {boolean} True if the mirror reflects an object
286  */
287 Mirror.prototype.isObject = function() {
288   return this instanceof ObjectMirror;
289 };
290
291
292 /**
293  * Check whether the mirror reflects a function.
294  * @returns {boolean} True if the mirror reflects a function
295  */
296 Mirror.prototype.isFunction = function() {
297   return this instanceof FunctionMirror;
298 };
299
300
301 /**
302  * Check whether the mirror reflects an unresolved function.
303  * @returns {boolean} True if the mirror reflects an unresolved function
304  */
305 Mirror.prototype.isUnresolvedFunction = function() {
306   return this instanceof UnresolvedFunctionMirror;
307 };
308
309
310 /**
311  * Check whether the mirror reflects an array.
312  * @returns {boolean} True if the mirror reflects an array
313  */
314 Mirror.prototype.isArray = function() {
315   return this instanceof ArrayMirror;
316 };
317
318
319 /**
320  * Check whether the mirror reflects a date.
321  * @returns {boolean} True if the mirror reflects a date
322  */
323 Mirror.prototype.isDate = function() {
324   return this instanceof DateMirror;
325 };
326
327
328 /**
329  * Check whether the mirror reflects a regular expression.
330  * @returns {boolean} True if the mirror reflects a regular expression
331  */
332 Mirror.prototype.isRegExp = function() {
333   return this instanceof RegExpMirror;
334 };
335
336
337 /**
338  * Check whether the mirror reflects an error.
339  * @returns {boolean} True if the mirror reflects an error
340  */
341 Mirror.prototype.isError = function() {
342   return this instanceof ErrorMirror;
343 };
344
345
346 /**
347  * Check whether the mirror reflects a promise.
348  * @returns {boolean} True if the mirror reflects a promise
349  */
350 Mirror.prototype.isPromise = function() {
351   return this instanceof PromiseMirror;
352 };
353
354
355 /**
356  * Check whether the mirror reflects a property.
357  * @returns {boolean} True if the mirror reflects a property
358  */
359 Mirror.prototype.isProperty = function() {
360   return this instanceof PropertyMirror;
361 };
362
363
364 /**
365  * Check whether the mirror reflects an internal property.
366  * @returns {boolean} True if the mirror reflects an internal property
367  */
368 Mirror.prototype.isInternalProperty = function() {
369   return this instanceof InternalPropertyMirror;
370 };
371
372
373 /**
374  * Check whether the mirror reflects a stack frame.
375  * @returns {boolean} True if the mirror reflects a stack frame
376  */
377 Mirror.prototype.isFrame = function() {
378   return this instanceof FrameMirror;
379 };
380
381
382 /**
383  * Check whether the mirror reflects a script.
384  * @returns {boolean} True if the mirror reflects a script
385  */
386 Mirror.prototype.isScript = function() {
387   return this instanceof ScriptMirror;
388 };
389
390
391 /**
392  * Check whether the mirror reflects a context.
393  * @returns {boolean} True if the mirror reflects a context
394  */
395 Mirror.prototype.isContext = function() {
396   return this instanceof ContextMirror;
397 };
398
399
400 /**
401  * Check whether the mirror reflects a scope.
402  * @returns {boolean} True if the mirror reflects a scope
403  */
404 Mirror.prototype.isScope = function() {
405   return this instanceof ScopeMirror;
406 };
407
408
409 /**
410  * Allocate a handle id for this object.
411  */
412 Mirror.prototype.allocateHandle_ = function() {
413   this.handle_ = next_handle_++;
414 };
415
416
417 /**
418  * Allocate a transient handle id for this object. Transient handles are
419  * negative.
420  */
421 Mirror.prototype.allocateTransientHandle_ = function() {
422   this.handle_ = next_transient_handle_--;
423 };
424
425
426 Mirror.prototype.toText = function() {
427   // Simpel to text which is used when on specialization in subclass.
428   return "#<" + this.constructor.name + ">";
429 };
430
431
432 /**
433  * Base class for all value mirror objects.
434  * @param {string} type The type of the mirror
435  * @param {value} value The value reflected by this mirror
436  * @param {boolean} transient indicate whether this object is transient with a
437  *    transient handle
438  * @constructor
439  * @extends Mirror
440  */
441 function ValueMirror(type, value, transient) {
442   %_CallFunction(this, type, Mirror);
443   this.value_ = value;
444   if (!transient) {
445     this.allocateHandle_();
446   } else {
447     this.allocateTransientHandle_();
448   }
449 }
450 inherits(ValueMirror, Mirror);
451
452
453 Mirror.prototype.handle = function() {
454   return this.handle_;
455 };
456
457
458 /**
459  * Check whether this is a primitive value.
460  * @return {boolean} True if the mirror reflects a primitive value
461  */
462 ValueMirror.prototype.isPrimitive = function() {
463   var type = this.type();
464   return type === 'undefined' ||
465          type === 'null' ||
466          type === 'boolean' ||
467          type === 'number' ||
468          type === 'string';
469 };
470
471
472 /**
473  * Get the actual value reflected by this mirror.
474  * @return {value} The value reflected by this mirror
475  */
476 ValueMirror.prototype.value = function() {
477   return this.value_;
478 };
479
480
481 /**
482  * Mirror object for Undefined.
483  * @constructor
484  * @extends ValueMirror
485  */
486 function UndefinedMirror() {
487   %_CallFunction(this, UNDEFINED_TYPE, UNDEFINED, ValueMirror);
488 }
489 inherits(UndefinedMirror, ValueMirror);
490
491
492 UndefinedMirror.prototype.toText = function() {
493   return 'undefined';
494 };
495
496
497 /**
498  * Mirror object for null.
499  * @constructor
500  * @extends ValueMirror
501  */
502 function NullMirror() {
503   %_CallFunction(this, NULL_TYPE, null, ValueMirror);
504 }
505 inherits(NullMirror, ValueMirror);
506
507
508 NullMirror.prototype.toText = function() {
509   return 'null';
510 };
511
512
513 /**
514  * Mirror object for boolean values.
515  * @param {boolean} value The boolean value reflected by this mirror
516  * @constructor
517  * @extends ValueMirror
518  */
519 function BooleanMirror(value) {
520   %_CallFunction(this, BOOLEAN_TYPE, value, ValueMirror);
521 }
522 inherits(BooleanMirror, ValueMirror);
523
524
525 BooleanMirror.prototype.toText = function() {
526   return this.value_ ? 'true' : 'false';
527 };
528
529
530 /**
531  * Mirror object for number values.
532  * @param {number} value The number value reflected by this mirror
533  * @constructor
534  * @extends ValueMirror
535  */
536 function NumberMirror(value) {
537   %_CallFunction(this, NUMBER_TYPE, value, ValueMirror);
538 }
539 inherits(NumberMirror, ValueMirror);
540
541
542 NumberMirror.prototype.toText = function() {
543   return %_NumberToString(this.value_);
544 };
545
546
547 /**
548  * Mirror object for string values.
549  * @param {string} value The string value reflected by this mirror
550  * @constructor
551  * @extends ValueMirror
552  */
553 function StringMirror(value) {
554   %_CallFunction(this, STRING_TYPE, value, ValueMirror);
555 }
556 inherits(StringMirror, ValueMirror);
557
558
559 StringMirror.prototype.length = function() {
560   return this.value_.length;
561 };
562
563 StringMirror.prototype.getTruncatedValue = function(maxLength) {
564   if (maxLength != -1 && this.length() > maxLength) {
565     return this.value_.substring(0, maxLength) +
566            '... (length: ' + this.length() + ')';
567   }
568   return this.value_;
569 };
570
571 StringMirror.prototype.toText = function() {
572   return this.getTruncatedValue(kMaxProtocolStringLength);
573 };
574
575
576 /**
577  * Mirror object for objects.
578  * @param {object} value The object reflected by this mirror
579  * @param {boolean} transient indicate whether this object is transient with a
580  *    transient handle
581  * @constructor
582  * @extends ValueMirror
583  */
584 function ObjectMirror(value, type, transient) {
585   %_CallFunction(this, type || OBJECT_TYPE, value, transient, ValueMirror);
586 }
587 inherits(ObjectMirror, ValueMirror);
588
589
590 ObjectMirror.prototype.className = function() {
591   return %_ClassOf(this.value_);
592 };
593
594
595 ObjectMirror.prototype.constructorFunction = function() {
596   return MakeMirror(%DebugGetProperty(this.value_, 'constructor'));
597 };
598
599
600 ObjectMirror.prototype.prototypeObject = function() {
601   return MakeMirror(%DebugGetProperty(this.value_, 'prototype'));
602 };
603
604
605 ObjectMirror.prototype.protoObject = function() {
606   return MakeMirror(%DebugGetPrototype(this.value_));
607 };
608
609
610 ObjectMirror.prototype.hasNamedInterceptor = function() {
611   // Get information on interceptors for this object.
612   var x = %GetInterceptorInfo(this.value_);
613   return (x & 2) != 0;
614 };
615
616
617 ObjectMirror.prototype.hasIndexedInterceptor = function() {
618   // Get information on interceptors for this object.
619   var x = %GetInterceptorInfo(this.value_);
620   return (x & 1) != 0;
621 };
622
623
624 /**
625  * Return the property names for this object.
626  * @param {number} kind Indicate whether named, indexed or both kinds of
627  *     properties are requested
628  * @param {number} limit Limit the number of names returend to the specified
629        value
630  * @return {Array} Property names for this object
631  */
632 ObjectMirror.prototype.propertyNames = function(kind, limit) {
633   // Find kind and limit and allocate array for the result
634   kind = kind || PropertyKind.Named | PropertyKind.Indexed;
635
636   var propertyNames;
637   var elementNames;
638   var total = 0;
639
640   // Find all the named properties.
641   if (kind & PropertyKind.Named) {
642     // Get all the local property names except for private symbols.
643     propertyNames =
644         %GetLocalPropertyNames(this.value_, PROPERTY_ATTRIBUTES_PRIVATE_SYMBOL);
645     total += propertyNames.length;
646
647     // Get names for named interceptor properties if any.
648     if (this.hasNamedInterceptor() && (kind & PropertyKind.Named)) {
649       var namedInterceptorNames =
650           %GetNamedInterceptorPropertyNames(this.value_);
651       if (namedInterceptorNames) {
652         propertyNames = propertyNames.concat(namedInterceptorNames);
653         total += namedInterceptorNames.length;
654       }
655     }
656   }
657
658   // Find all the indexed properties.
659   if (kind & PropertyKind.Indexed) {
660     // Get the local element names.
661     elementNames = %GetLocalElementNames(this.value_);
662     total += elementNames.length;
663
664     // Get names for indexed interceptor properties.
665     if (this.hasIndexedInterceptor() && (kind & PropertyKind.Indexed)) {
666       var indexedInterceptorNames =
667           %GetIndexedInterceptorElementNames(this.value_);
668       if (indexedInterceptorNames) {
669         elementNames = elementNames.concat(indexedInterceptorNames);
670         total += indexedInterceptorNames.length;
671       }
672     }
673   }
674   limit = Math.min(limit || total, total);
675
676   var names = new Array(limit);
677   var index = 0;
678
679   // Copy names for named properties.
680   if (kind & PropertyKind.Named) {
681     for (var i = 0; index < limit && i < propertyNames.length; i++) {
682       names[index++] = propertyNames[i];
683     }
684   }
685
686   // Copy names for indexed properties.
687   if (kind & PropertyKind.Indexed) {
688     for (var i = 0; index < limit && i < elementNames.length; i++) {
689       names[index++] = elementNames[i];
690     }
691   }
692
693   return names;
694 };
695
696
697 /**
698  * Return the properties for this object as an array of PropertyMirror objects.
699  * @param {number} kind Indicate whether named, indexed or both kinds of
700  *     properties are requested
701  * @param {number} limit Limit the number of properties returned to the
702        specified value
703  * @return {Array} Property mirrors for this object
704  */
705 ObjectMirror.prototype.properties = function(kind, limit) {
706   var names = this.propertyNames(kind, limit);
707   var properties = new Array(names.length);
708   for (var i = 0; i < names.length; i++) {
709     properties[i] = this.property(names[i]);
710   }
711
712   return properties;
713 };
714
715
716 /**
717  * Return the internal properties for this object as an array of
718  * InternalPropertyMirror objects.
719  * @return {Array} Property mirrors for this object
720  */
721 ObjectMirror.prototype.internalProperties = function() {
722   return ObjectMirror.GetInternalProperties(this.value_);
723 }
724
725
726 ObjectMirror.prototype.property = function(name) {
727   var details = %DebugGetPropertyDetails(this.value_, %ToString(name));
728   if (details) {
729     return new PropertyMirror(this, name, details);
730   }
731
732   // Nothing found.
733   return GetUndefinedMirror();
734 };
735
736
737
738 /**
739  * Try to find a property from its value.
740  * @param {Mirror} value The property value to look for
741  * @return {PropertyMirror} The property with the specified value. If no
742  *     property was found with the specified value UndefinedMirror is returned
743  */
744 ObjectMirror.prototype.lookupProperty = function(value) {
745   var properties = this.properties();
746
747   // Look for property value in properties.
748   for (var i = 0; i < properties.length; i++) {
749
750     // Skip properties which are defined through assessors.
751     var property = properties[i];
752     if (property.propertyType() != PropertyType.Callbacks) {
753       if (%_ObjectEquals(property.value_, value.value_)) {
754         return property;
755       }
756     }
757   }
758
759   // Nothing found.
760   return GetUndefinedMirror();
761 };
762
763
764 /**
765  * Returns objects which has direct references to this object
766  * @param {number} opt_max_objects Optional parameter specifying the maximum
767  *     number of referencing objects to return.
768  * @return {Array} The objects which has direct references to this object.
769  */
770 ObjectMirror.prototype.referencedBy = function(opt_max_objects) {
771   // Find all objects with direct references to this object.
772   var result = %DebugReferencedBy(this.value_,
773                                   Mirror.prototype, opt_max_objects || 0);
774
775   // Make mirrors for all the references found.
776   for (var i = 0; i < result.length; i++) {
777     result[i] = MakeMirror(result[i]);
778   }
779
780   return result;
781 };
782
783
784 ObjectMirror.prototype.toText = function() {
785   var name;
786   var ctor = this.constructorFunction();
787   if (!ctor.isFunction()) {
788     name = this.className();
789   } else {
790     name = ctor.name();
791     if (!name) {
792       name = this.className();
793     }
794   }
795   return '#<' + name + '>';
796 };
797
798
799 /**
800  * Return the internal properties of the value, such as [[PrimitiveValue]] of
801  * scalar wrapper objects and properties of the bound function.
802  * This method is done static to be accessible from Debug API with the bare
803  * values without mirrors.
804  * @return {Array} array (possibly empty) of InternalProperty instances
805  */
806 ObjectMirror.GetInternalProperties = function(value) {
807   if (IS_STRING_WRAPPER(value) || IS_NUMBER_WRAPPER(value) ||
808       IS_BOOLEAN_WRAPPER(value)) {
809     var primitiveValue = %_ValueOf(value);
810     return [new InternalPropertyMirror("[[PrimitiveValue]]", primitiveValue)];
811   } else if (IS_FUNCTION(value)) {
812     var bindings = %BoundFunctionGetBindings(value);
813     var result = [];
814     if (bindings && IS_ARRAY(bindings)) {
815       result.push(new InternalPropertyMirror("[[TargetFunction]]",
816                                              bindings[0]));
817       result.push(new InternalPropertyMirror("[[BoundThis]]", bindings[1]));
818       var boundArgs = [];
819       for (var i = 2; i < bindings.length; i++) {
820         boundArgs.push(bindings[i]);
821       }
822       result.push(new InternalPropertyMirror("[[BoundArgs]]", boundArgs));
823     }
824     return result;
825   }
826   return [];
827 }
828
829
830 /**
831  * Mirror object for functions.
832  * @param {function} value The function object reflected by this mirror.
833  * @constructor
834  * @extends ObjectMirror
835  */
836 function FunctionMirror(value) {
837   %_CallFunction(this, value, FUNCTION_TYPE, ObjectMirror);
838   this.resolved_ = true;
839 }
840 inherits(FunctionMirror, ObjectMirror);
841
842
843 /**
844  * Returns whether the function is resolved.
845  * @return {boolean} True if the function is resolved. Unresolved functions can
846  *     only originate as functions from stack frames
847  */
848 FunctionMirror.prototype.resolved = function() {
849   return this.resolved_;
850 };
851
852
853 /**
854  * Returns the name of the function.
855  * @return {string} Name of the function
856  */
857 FunctionMirror.prototype.name = function() {
858   return %FunctionGetName(this.value_);
859 };
860
861
862 /**
863  * Returns the inferred name of the function.
864  * @return {string} Name of the function
865  */
866 FunctionMirror.prototype.inferredName = function() {
867   return %FunctionGetInferredName(this.value_);
868 };
869
870
871 /**
872  * Returns the source code for the function.
873  * @return {string or undefined} The source code for the function. If the
874  *     function is not resolved undefined will be returned.
875  */
876 FunctionMirror.prototype.source = function() {
877   // Return source if function is resolved. Otherwise just fall through to
878   // return undefined.
879   if (this.resolved()) {
880     return builtins.FunctionSourceString(this.value_);
881   }
882 };
883
884
885 /**
886  * Returns the script object for the function.
887  * @return {ScriptMirror or undefined} Script object for the function or
888  *     undefined if the function has no script
889  */
890 FunctionMirror.prototype.script = function() {
891   // Return script if function is resolved. Otherwise just fall through
892   // to return undefined.
893   if (this.resolved()) {
894     if (this.script_) {
895       return this.script_;
896     }
897     var script = %FunctionGetScript(this.value_);
898     if (script) {
899       return this.script_ = MakeMirror(script);
900     }
901   }
902 };
903
904
905 /**
906  * Returns the script source position for the function. Only makes sense
907  * for functions which has a script defined.
908  * @return {Number or undefined} in-script position for the function
909  */
910 FunctionMirror.prototype.sourcePosition_ = function() {
911   // Return script if function is resolved. Otherwise just fall through
912   // to return undefined.
913   if (this.resolved()) {
914     return %FunctionGetScriptSourcePosition(this.value_);
915   }
916 };
917
918
919 /**
920  * Returns the script source location object for the function. Only makes sense
921  * for functions which has a script defined.
922  * @return {Location or undefined} in-script location for the function begin
923  */
924 FunctionMirror.prototype.sourceLocation = function() {
925   if (this.resolved()) {
926     var script = this.script();
927     if (script) {
928       return script.locationFromPosition(this.sourcePosition_(), true);
929     }
930   }
931 };
932
933
934 /**
935  * Returns objects constructed by this function.
936  * @param {number} opt_max_instances Optional parameter specifying the maximum
937  *     number of instances to return.
938  * @return {Array or undefined} The objects constructed by this function.
939  */
940 FunctionMirror.prototype.constructedBy = function(opt_max_instances) {
941   if (this.resolved()) {
942     // Find all objects constructed from this function.
943     var result = %DebugConstructedBy(this.value_, opt_max_instances || 0);
944
945     // Make mirrors for all the instances found.
946     for (var i = 0; i < result.length; i++) {
947       result[i] = MakeMirror(result[i]);
948     }
949
950     return result;
951   } else {
952     return [];
953   }
954 };
955
956
957 FunctionMirror.prototype.scopeCount = function() {
958   if (this.resolved()) {
959     if (IS_UNDEFINED(this.scopeCount_)) {
960       this.scopeCount_ = %GetFunctionScopeCount(this.value());
961     }
962     return this.scopeCount_;
963   } else {
964     return 0;
965   }
966 };
967
968
969 FunctionMirror.prototype.scope = function(index) {
970   if (this.resolved()) {
971     return new ScopeMirror(UNDEFINED, this, index);
972   }
973 };
974
975
976 FunctionMirror.prototype.toText = function() {
977   return this.source();
978 };
979
980
981 /**
982  * Mirror object for unresolved functions.
983  * @param {string} value The name for the unresolved function reflected by this
984  *     mirror.
985  * @constructor
986  * @extends ObjectMirror
987  */
988 function UnresolvedFunctionMirror(value) {
989   // Construct this using the ValueMirror as an unresolved function is not a
990   // real object but just a string.
991   %_CallFunction(this, FUNCTION_TYPE, value, ValueMirror);
992   this.propertyCount_ = 0;
993   this.elementCount_ = 0;
994   this.resolved_ = false;
995 }
996 inherits(UnresolvedFunctionMirror, FunctionMirror);
997
998
999 UnresolvedFunctionMirror.prototype.className = function() {
1000   return 'Function';
1001 };
1002
1003
1004 UnresolvedFunctionMirror.prototype.constructorFunction = function() {
1005   return GetUndefinedMirror();
1006 };
1007
1008
1009 UnresolvedFunctionMirror.prototype.prototypeObject = function() {
1010   return GetUndefinedMirror();
1011 };
1012
1013
1014 UnresolvedFunctionMirror.prototype.protoObject = function() {
1015   return GetUndefinedMirror();
1016 };
1017
1018
1019 UnresolvedFunctionMirror.prototype.name = function() {
1020   return this.value_;
1021 };
1022
1023
1024 UnresolvedFunctionMirror.prototype.inferredName = function() {
1025   return undefined;
1026 };
1027
1028
1029 UnresolvedFunctionMirror.prototype.propertyNames = function(kind, limit) {
1030   return [];
1031 };
1032
1033
1034 /**
1035  * Mirror object for arrays.
1036  * @param {Array} value The Array object reflected by this mirror
1037  * @constructor
1038  * @extends ObjectMirror
1039  */
1040 function ArrayMirror(value) {
1041   %_CallFunction(this, value, ObjectMirror);
1042 }
1043 inherits(ArrayMirror, ObjectMirror);
1044
1045
1046 ArrayMirror.prototype.length = function() {
1047   return this.value_.length;
1048 };
1049
1050
1051 ArrayMirror.prototype.indexedPropertiesFromRange = function(opt_from_index,
1052                                                             opt_to_index) {
1053   var from_index = opt_from_index || 0;
1054   var to_index = opt_to_index || this.length() - 1;
1055   if (from_index > to_index) return new Array();
1056   var values = new Array(to_index - from_index + 1);
1057   for (var i = from_index; i <= to_index; i++) {
1058     var details = %DebugGetPropertyDetails(this.value_, %ToString(i));
1059     var value;
1060     if (details) {
1061       value = new PropertyMirror(this, i, details);
1062     } else {
1063       value = GetUndefinedMirror();
1064     }
1065     values[i - from_index] = value;
1066   }
1067   return values;
1068 };
1069
1070
1071 /**
1072  * Mirror object for dates.
1073  * @param {Date} value The Date object reflected by this mirror
1074  * @constructor
1075  * @extends ObjectMirror
1076  */
1077 function DateMirror(value) {
1078   %_CallFunction(this, value, ObjectMirror);
1079 }
1080 inherits(DateMirror, ObjectMirror);
1081
1082
1083 DateMirror.prototype.toText = function() {
1084   var s = JSON.stringify(this.value_);
1085   return s.substring(1, s.length - 1);  // cut quotes
1086 };
1087
1088
1089 /**
1090  * Mirror object for regular expressions.
1091  * @param {RegExp} value The RegExp object reflected by this mirror
1092  * @constructor
1093  * @extends ObjectMirror
1094  */
1095 function RegExpMirror(value) {
1096   %_CallFunction(this, value, REGEXP_TYPE, ObjectMirror);
1097 }
1098 inherits(RegExpMirror, ObjectMirror);
1099
1100
1101 /**
1102  * Returns the source to the regular expression.
1103  * @return {string or undefined} The source to the regular expression
1104  */
1105 RegExpMirror.prototype.source = function() {
1106   return this.value_.source;
1107 };
1108
1109
1110 /**
1111  * Returns whether this regular expression has the global (g) flag set.
1112  * @return {boolean} Value of the global flag
1113  */
1114 RegExpMirror.prototype.global = function() {
1115   return this.value_.global;
1116 };
1117
1118
1119 /**
1120  * Returns whether this regular expression has the ignore case (i) flag set.
1121  * @return {boolean} Value of the ignore case flag
1122  */
1123 RegExpMirror.prototype.ignoreCase = function() {
1124   return this.value_.ignoreCase;
1125 };
1126
1127
1128 /**
1129  * Returns whether this regular expression has the multiline (m) flag set.
1130  * @return {boolean} Value of the multiline flag
1131  */
1132 RegExpMirror.prototype.multiline = function() {
1133   return this.value_.multiline;
1134 };
1135
1136
1137 RegExpMirror.prototype.toText = function() {
1138   // Simpel to text which is used when on specialization in subclass.
1139   return "/" + this.source() + "/";
1140 };
1141
1142
1143 /**
1144  * Mirror object for error objects.
1145  * @param {Error} value The error object reflected by this mirror
1146  * @constructor
1147  * @extends ObjectMirror
1148  */
1149 function ErrorMirror(value) {
1150   %_CallFunction(this, value, ERROR_TYPE, ObjectMirror);
1151 }
1152 inherits(ErrorMirror, ObjectMirror);
1153
1154
1155 /**
1156  * Returns the message for this eror object.
1157  * @return {string or undefined} The message for this eror object
1158  */
1159 ErrorMirror.prototype.message = function() {
1160   return this.value_.message;
1161 };
1162
1163
1164 ErrorMirror.prototype.toText = function() {
1165   // Use the same text representation as in messages.js.
1166   var text;
1167   try {
1168     str = %_CallFunction(this.value_, builtins.ErrorToString);
1169   } catch (e) {
1170     str = '#<Error>';
1171   }
1172   return str;
1173 };
1174
1175
1176 /**
1177  * Mirror object for a Promise object.
1178  * @param {Object} data The Promise object
1179  * @constructor
1180  * @extends Mirror
1181  */
1182 function PromiseMirror(value) {
1183   %_CallFunction(this, value, PROMISE_TYPE, ObjectMirror);
1184 }
1185 inherits(PromiseMirror, ObjectMirror);
1186
1187
1188 PromiseMirror.prototype.status = function() {
1189   var status = builtins.GetPromiseStatus(this.value_);
1190   if (status == 0) return "pending";
1191   if (status == 1) return "resolved";
1192   return "rejected";
1193 };
1194
1195
1196 PromiseMirror.prototype.promiseValue = function() {
1197   return builtins.GetPromiseValue(this.value_);
1198 };
1199
1200
1201 /**
1202  * Base mirror object for properties.
1203  * @param {ObjectMirror} mirror The mirror object having this property
1204  * @param {string} name The name of the property
1205  * @param {Array} details Details about the property
1206  * @constructor
1207  * @extends Mirror
1208  */
1209 function PropertyMirror(mirror, name, details) {
1210   %_CallFunction(this, PROPERTY_TYPE, Mirror);
1211   this.mirror_ = mirror;
1212   this.name_ = name;
1213   this.value_ = details[0];
1214   this.details_ = details[1];
1215   if (details.length > 2) {
1216     this.exception_ = details[2];
1217     this.getter_ = details[3];
1218     this.setter_ = details[4];
1219   }
1220 }
1221 inherits(PropertyMirror, Mirror);
1222
1223
1224 PropertyMirror.prototype.isReadOnly = function() {
1225   return (this.attributes() & PropertyAttribute.ReadOnly) != 0;
1226 };
1227
1228
1229 PropertyMirror.prototype.isEnum = function() {
1230   return (this.attributes() & PropertyAttribute.DontEnum) == 0;
1231 };
1232
1233
1234 PropertyMirror.prototype.canDelete = function() {
1235   return (this.attributes() & PropertyAttribute.DontDelete) == 0;
1236 };
1237
1238
1239 PropertyMirror.prototype.name = function() {
1240   return this.name_;
1241 };
1242
1243
1244 PropertyMirror.prototype.isIndexed = function() {
1245   for (var i = 0; i < this.name_.length; i++) {
1246     if (this.name_[i] < '0' || '9' < this.name_[i]) {
1247       return false;
1248     }
1249   }
1250   return true;
1251 };
1252
1253
1254 PropertyMirror.prototype.value = function() {
1255   return MakeMirror(this.value_, false);
1256 };
1257
1258
1259 /**
1260  * Returns whether this property value is an exception.
1261  * @return {booolean} True if this property value is an exception
1262  */
1263 PropertyMirror.prototype.isException = function() {
1264   return this.exception_ ? true : false;
1265 };
1266
1267
1268 PropertyMirror.prototype.attributes = function() {
1269   return %DebugPropertyAttributesFromDetails(this.details_);
1270 };
1271
1272
1273 PropertyMirror.prototype.propertyType = function() {
1274   return %DebugPropertyTypeFromDetails(this.details_);
1275 };
1276
1277
1278 PropertyMirror.prototype.insertionIndex = function() {
1279   return %DebugPropertyIndexFromDetails(this.details_);
1280 };
1281
1282
1283 /**
1284  * Returns whether this property has a getter defined through __defineGetter__.
1285  * @return {booolean} True if this property has a getter
1286  */
1287 PropertyMirror.prototype.hasGetter = function() {
1288   return this.getter_ ? true : false;
1289 };
1290
1291
1292 /**
1293  * Returns whether this property has a setter defined through __defineSetter__.
1294  * @return {booolean} True if this property has a setter
1295  */
1296 PropertyMirror.prototype.hasSetter = function() {
1297   return this.setter_ ? true : false;
1298 };
1299
1300
1301 /**
1302  * Returns the getter for this property defined through __defineGetter__.
1303  * @return {Mirror} FunctionMirror reflecting the getter function or
1304  *     UndefinedMirror if there is no getter for this property
1305  */
1306 PropertyMirror.prototype.getter = function() {
1307   if (this.hasGetter()) {
1308     return MakeMirror(this.getter_);
1309   } else {
1310     return GetUndefinedMirror();
1311   }
1312 };
1313
1314
1315 /**
1316  * Returns the setter for this property defined through __defineSetter__.
1317  * @return {Mirror} FunctionMirror reflecting the setter function or
1318  *     UndefinedMirror if there is no setter for this property
1319  */
1320 PropertyMirror.prototype.setter = function() {
1321   if (this.hasSetter()) {
1322     return MakeMirror(this.setter_);
1323   } else {
1324     return GetUndefinedMirror();
1325   }
1326 };
1327
1328
1329 /**
1330  * Returns whether this property is natively implemented by the host or a set
1331  * through JavaScript code.
1332  * @return {boolean} True if the property is
1333  *     UndefinedMirror if there is no setter for this property
1334  */
1335 PropertyMirror.prototype.isNative = function() {
1336   return (this.propertyType() == PropertyType.Interceptor) ||
1337          ((this.propertyType() == PropertyType.Callbacks) &&
1338           !this.hasGetter() && !this.hasSetter());
1339 };
1340
1341
1342 /**
1343  * Mirror object for internal properties. Internal property reflects properties
1344  * not accessible from user code such as [[BoundThis]] in bound function.
1345  * Their names are merely symbolic.
1346  * @param {string} name The name of the property
1347  * @param {value} property value
1348  * @constructor
1349  * @extends Mirror
1350  */
1351 function InternalPropertyMirror(name, value) {
1352   %_CallFunction(this, INTERNAL_PROPERTY_TYPE, Mirror);
1353   this.name_ = name;
1354   this.value_ = value;
1355 }
1356 inherits(InternalPropertyMirror, Mirror);
1357
1358
1359 InternalPropertyMirror.prototype.name = function() {
1360   return this.name_;
1361 };
1362
1363
1364 InternalPropertyMirror.prototype.value = function() {
1365   return MakeMirror(this.value_, false);
1366 };
1367
1368
1369 var kFrameDetailsFrameIdIndex = 0;
1370 var kFrameDetailsReceiverIndex = 1;
1371 var kFrameDetailsFunctionIndex = 2;
1372 var kFrameDetailsArgumentCountIndex = 3;
1373 var kFrameDetailsLocalCountIndex = 4;
1374 var kFrameDetailsSourcePositionIndex = 5;
1375 var kFrameDetailsConstructCallIndex = 6;
1376 var kFrameDetailsAtReturnIndex = 7;
1377 var kFrameDetailsFlagsIndex = 8;
1378 var kFrameDetailsFirstDynamicIndex = 9;
1379
1380 var kFrameDetailsNameIndex = 0;
1381 var kFrameDetailsValueIndex = 1;
1382 var kFrameDetailsNameValueSize = 2;
1383
1384 var kFrameDetailsFlagDebuggerFrameMask = 1 << 0;
1385 var kFrameDetailsFlagOptimizedFrameMask = 1 << 1;
1386 var kFrameDetailsFlagInlinedFrameIndexMask = 7 << 2;
1387
1388 /**
1389  * Wrapper for the frame details information retreived from the VM. The frame
1390  * details from the VM is an array with the following content. See runtime.cc
1391  * Runtime_GetFrameDetails.
1392  *     0: Id
1393  *     1: Receiver
1394  *     2: Function
1395  *     3: Argument count
1396  *     4: Local count
1397  *     5: Source position
1398  *     6: Construct call
1399  *     7: Is at return
1400  *     8: Flags (debugger frame, optimized frame, inlined frame index)
1401  *     Arguments name, value
1402  *     Locals name, value
1403  *     Return value if any
1404  * @param {number} break_id Current break id
1405  * @param {number} index Frame number
1406  * @constructor
1407  */
1408 function FrameDetails(break_id, index) {
1409   this.break_id_ = break_id;
1410   this.details_ = %GetFrameDetails(break_id, index);
1411 }
1412
1413
1414 FrameDetails.prototype.frameId = function() {
1415   %CheckExecutionState(this.break_id_);
1416   return this.details_[kFrameDetailsFrameIdIndex];
1417 };
1418
1419
1420 FrameDetails.prototype.receiver = function() {
1421   %CheckExecutionState(this.break_id_);
1422   return this.details_[kFrameDetailsReceiverIndex];
1423 };
1424
1425
1426 FrameDetails.prototype.func = function() {
1427   %CheckExecutionState(this.break_id_);
1428   return this.details_[kFrameDetailsFunctionIndex];
1429 };
1430
1431
1432 FrameDetails.prototype.isConstructCall = function() {
1433   %CheckExecutionState(this.break_id_);
1434   return this.details_[kFrameDetailsConstructCallIndex];
1435 };
1436
1437
1438 FrameDetails.prototype.isAtReturn = function() {
1439   %CheckExecutionState(this.break_id_);
1440   return this.details_[kFrameDetailsAtReturnIndex];
1441 };
1442
1443
1444 FrameDetails.prototype.isDebuggerFrame = function() {
1445   %CheckExecutionState(this.break_id_);
1446   var f = kFrameDetailsFlagDebuggerFrameMask;
1447   return (this.details_[kFrameDetailsFlagsIndex] & f) == f;
1448 };
1449
1450
1451 FrameDetails.prototype.isOptimizedFrame = function() {
1452   %CheckExecutionState(this.break_id_);
1453   var f = kFrameDetailsFlagOptimizedFrameMask;
1454   return (this.details_[kFrameDetailsFlagsIndex] & f) == f;
1455 };
1456
1457
1458 FrameDetails.prototype.isInlinedFrame = function() {
1459   return this.inlinedFrameIndex() > 0;
1460 };
1461
1462
1463 FrameDetails.prototype.inlinedFrameIndex = function() {
1464   %CheckExecutionState(this.break_id_);
1465   var f = kFrameDetailsFlagInlinedFrameIndexMask;
1466   return (this.details_[kFrameDetailsFlagsIndex] & f) >> 2;
1467 };
1468
1469
1470 FrameDetails.prototype.argumentCount = function() {
1471   %CheckExecutionState(this.break_id_);
1472   return this.details_[kFrameDetailsArgumentCountIndex];
1473 };
1474
1475
1476 FrameDetails.prototype.argumentName = function(index) {
1477   %CheckExecutionState(this.break_id_);
1478   if (index >= 0 && index < this.argumentCount()) {
1479     return this.details_[kFrameDetailsFirstDynamicIndex +
1480                          index * kFrameDetailsNameValueSize +
1481                          kFrameDetailsNameIndex];
1482   }
1483 };
1484
1485
1486 FrameDetails.prototype.argumentValue = function(index) {
1487   %CheckExecutionState(this.break_id_);
1488   if (index >= 0 && index < this.argumentCount()) {
1489     return this.details_[kFrameDetailsFirstDynamicIndex +
1490                          index * kFrameDetailsNameValueSize +
1491                          kFrameDetailsValueIndex];
1492   }
1493 };
1494
1495
1496 FrameDetails.prototype.localCount = function() {
1497   %CheckExecutionState(this.break_id_);
1498   return this.details_[kFrameDetailsLocalCountIndex];
1499 };
1500
1501
1502 FrameDetails.prototype.sourcePosition = function() {
1503   %CheckExecutionState(this.break_id_);
1504   return this.details_[kFrameDetailsSourcePositionIndex];
1505 };
1506
1507
1508 FrameDetails.prototype.localName = function(index) {
1509   %CheckExecutionState(this.break_id_);
1510   if (index >= 0 && index < this.localCount()) {
1511     var locals_offset = kFrameDetailsFirstDynamicIndex +
1512                         this.argumentCount() * kFrameDetailsNameValueSize;
1513     return this.details_[locals_offset +
1514                          index * kFrameDetailsNameValueSize +
1515                          kFrameDetailsNameIndex];
1516   }
1517 };
1518
1519
1520 FrameDetails.prototype.localValue = function(index) {
1521   %CheckExecutionState(this.break_id_);
1522   if (index >= 0 && index < this.localCount()) {
1523     var locals_offset = kFrameDetailsFirstDynamicIndex +
1524                         this.argumentCount() * kFrameDetailsNameValueSize;
1525     return this.details_[locals_offset +
1526                          index * kFrameDetailsNameValueSize +
1527                          kFrameDetailsValueIndex];
1528   }
1529 };
1530
1531
1532 FrameDetails.prototype.returnValue = function() {
1533   %CheckExecutionState(this.break_id_);
1534   var return_value_offset =
1535       kFrameDetailsFirstDynamicIndex +
1536       (this.argumentCount() + this.localCount()) * kFrameDetailsNameValueSize;
1537   if (this.details_[kFrameDetailsAtReturnIndex]) {
1538     return this.details_[return_value_offset];
1539   }
1540 };
1541
1542
1543 FrameDetails.prototype.scopeCount = function() {
1544   if (IS_UNDEFINED(this.scopeCount_)) {
1545     this.scopeCount_ = %GetScopeCount(this.break_id_, this.frameId());
1546   }
1547   return this.scopeCount_;
1548 };
1549
1550
1551 FrameDetails.prototype.stepInPositionsImpl = function() {
1552   return %GetStepInPositions(this.break_id_, this.frameId());
1553 };
1554
1555
1556 /**
1557  * Mirror object for stack frames.
1558  * @param {number} break_id The break id in the VM for which this frame is
1559        valid
1560  * @param {number} index The frame index (top frame is index 0)
1561  * @constructor
1562  * @extends Mirror
1563  */
1564 function FrameMirror(break_id, index) {
1565   %_CallFunction(this, FRAME_TYPE, Mirror);
1566   this.break_id_ = break_id;
1567   this.index_ = index;
1568   this.details_ = new FrameDetails(break_id, index);
1569 }
1570 inherits(FrameMirror, Mirror);
1571
1572
1573 FrameMirror.prototype.details = function() {
1574   return this.details_;
1575 };
1576
1577
1578 FrameMirror.prototype.index = function() {
1579   return this.index_;
1580 };
1581
1582
1583 FrameMirror.prototype.func = function() {
1584   if (this.func_) {
1585     return this.func_;
1586   }
1587
1588   // Get the function for this frame from the VM.
1589   var f = this.details_.func();
1590
1591   // Create a function mirror. NOTE: MakeMirror cannot be used here as the
1592   // value returned from the VM might be a string if the function for the
1593   // frame is unresolved.
1594   if (IS_FUNCTION(f)) {
1595     return this.func_ = MakeMirror(f);
1596   } else {
1597     return new UnresolvedFunctionMirror(f);
1598   }
1599 };
1600
1601
1602 FrameMirror.prototype.receiver = function() {
1603   return MakeMirror(this.details_.receiver());
1604 };
1605
1606
1607 FrameMirror.prototype.isConstructCall = function() {
1608   return this.details_.isConstructCall();
1609 };
1610
1611
1612 FrameMirror.prototype.isAtReturn = function() {
1613   return this.details_.isAtReturn();
1614 };
1615
1616
1617 FrameMirror.prototype.isDebuggerFrame = function() {
1618   return this.details_.isDebuggerFrame();
1619 };
1620
1621
1622 FrameMirror.prototype.isOptimizedFrame = function() {
1623   return this.details_.isOptimizedFrame();
1624 };
1625
1626
1627 FrameMirror.prototype.isInlinedFrame = function() {
1628   return this.details_.isInlinedFrame();
1629 };
1630
1631
1632 FrameMirror.prototype.inlinedFrameIndex = function() {
1633   return this.details_.inlinedFrameIndex();
1634 };
1635
1636
1637 FrameMirror.prototype.argumentCount = function() {
1638   return this.details_.argumentCount();
1639 };
1640
1641
1642 FrameMirror.prototype.argumentName = function(index) {
1643   return this.details_.argumentName(index);
1644 };
1645
1646
1647 FrameMirror.prototype.argumentValue = function(index) {
1648   return MakeMirror(this.details_.argumentValue(index));
1649 };
1650
1651
1652 FrameMirror.prototype.localCount = function() {
1653   return this.details_.localCount();
1654 };
1655
1656
1657 FrameMirror.prototype.localName = function(index) {
1658   return this.details_.localName(index);
1659 };
1660
1661
1662 FrameMirror.prototype.localValue = function(index) {
1663   return MakeMirror(this.details_.localValue(index));
1664 };
1665
1666
1667 FrameMirror.prototype.returnValue = function() {
1668   return MakeMirror(this.details_.returnValue());
1669 };
1670
1671
1672 FrameMirror.prototype.sourcePosition = function() {
1673   return this.details_.sourcePosition();
1674 };
1675
1676
1677 FrameMirror.prototype.sourceLocation = function() {
1678   var func = this.func();
1679   if (func.resolved()) {
1680     var script = func.script();
1681     if (script) {
1682       return script.locationFromPosition(this.sourcePosition(), true);
1683     }
1684   }
1685 };
1686
1687
1688 FrameMirror.prototype.sourceLine = function() {
1689   var location = this.sourceLocation();
1690   if (location) {
1691     return location.line;
1692   }
1693 };
1694
1695
1696 FrameMirror.prototype.sourceColumn = function() {
1697   var location = this.sourceLocation();
1698   if (location) {
1699     return location.column;
1700   }
1701 };
1702
1703
1704 FrameMirror.prototype.sourceLineText = function() {
1705   var location = this.sourceLocation();
1706   if (location) {
1707     return location.sourceText();
1708   }
1709 };
1710
1711
1712 FrameMirror.prototype.scopeCount = function() {
1713   return this.details_.scopeCount();
1714 };
1715
1716
1717 FrameMirror.prototype.scope = function(index) {
1718   return new ScopeMirror(this, UNDEFINED, index);
1719 };
1720
1721
1722 FrameMirror.prototype.allScopes = function(opt_ignore_nested_scopes) {
1723   var scopeDetails = %GetAllScopesDetails(this.break_id_,
1724                                           this.details_.frameId(),
1725                                           this.details_.inlinedFrameIndex(),
1726                                           !!opt_ignore_nested_scopes);
1727   var result = [];
1728   for (var i = 0; i < scopeDetails.length; ++i) {
1729     result.push(new ScopeMirror(this, UNDEFINED, i, scopeDetails[i]));
1730   }
1731   return result;
1732 };
1733
1734
1735 FrameMirror.prototype.stepInPositions = function() {
1736   var script = this.func().script();
1737   var funcOffset = this.func().sourcePosition_();
1738
1739   var stepInRaw = this.details_.stepInPositionsImpl();
1740   var result = [];
1741   if (stepInRaw) {
1742     for (var i = 0; i < stepInRaw.length; i++) {
1743       var posStruct = {};
1744       var offset = script.locationFromPosition(funcOffset + stepInRaw[i],
1745                                                true);
1746       serializeLocationFields(offset, posStruct);
1747       var item = {
1748         position: posStruct
1749       };
1750       result.push(item);
1751     }
1752   }
1753
1754   return result;
1755 };
1756
1757
1758 FrameMirror.prototype.evaluate = function(source, disable_break,
1759                                           opt_context_object) {
1760   return MakeMirror(%DebugEvaluate(this.break_id_,
1761                                    this.details_.frameId(),
1762                                    this.details_.inlinedFrameIndex(),
1763                                    source,
1764                                    Boolean(disable_break),
1765                                    opt_context_object));
1766 };
1767
1768
1769 FrameMirror.prototype.invocationText = function() {
1770   // Format frame invoaction (receiver, function and arguments).
1771   var result = '';
1772   var func = this.func();
1773   var receiver = this.receiver();
1774   if (this.isConstructCall()) {
1775     // For constructor frames display new followed by the function name.
1776     result += 'new ';
1777     result += func.name() ? func.name() : '[anonymous]';
1778   } else if (this.isDebuggerFrame()) {
1779     result += '[debugger]';
1780   } else {
1781     // If the receiver has a className which is 'global' don't display it.
1782     var display_receiver =
1783       !receiver.className || (receiver.className() != 'global');
1784     if (display_receiver) {
1785       result += receiver.toText();
1786     }
1787     // Try to find the function as a property in the receiver. Include the
1788     // prototype chain in the lookup.
1789     var property = GetUndefinedMirror();
1790     if (receiver.isObject()) {
1791       for (var r = receiver;
1792            !r.isNull() && property.isUndefined();
1793            r = r.protoObject()) {
1794         property = r.lookupProperty(func);
1795       }
1796     }
1797     if (!property.isUndefined()) {
1798       // The function invoked was found on the receiver. Use the property name
1799       // for the backtrace.
1800       if (!property.isIndexed()) {
1801         if (display_receiver) {
1802           result += '.';
1803         }
1804         result += property.name();
1805       } else {
1806         result += '[';
1807         result += property.name();
1808         result += ']';
1809       }
1810       // Also known as - if the name in the function doesn't match the name
1811       // under which it was looked up.
1812       if (func.name() && func.name() != property.name()) {
1813         result += '(aka ' + func.name() + ')';
1814       }
1815     } else {
1816       // The function invoked was not found on the receiver. Use the function
1817       // name if available for the backtrace.
1818       if (display_receiver) {
1819         result += '.';
1820       }
1821       result += func.name() ? func.name() : '[anonymous]';
1822     }
1823   }
1824
1825   // Render arguments for normal frames.
1826   if (!this.isDebuggerFrame()) {
1827     result += '(';
1828     for (var i = 0; i < this.argumentCount(); i++) {
1829       if (i != 0) result += ', ';
1830       if (this.argumentName(i)) {
1831         result += this.argumentName(i);
1832         result += '=';
1833       }
1834       result += this.argumentValue(i).toText();
1835     }
1836     result += ')';
1837   }
1838
1839   if (this.isAtReturn()) {
1840     result += ' returning ';
1841     result += this.returnValue().toText();
1842   }
1843
1844   return result;
1845 };
1846
1847
1848 FrameMirror.prototype.sourceAndPositionText = function() {
1849   // Format source and position.
1850   var result = '';
1851   var func = this.func();
1852   if (func.resolved()) {
1853     var script = func.script();
1854     if (script) {
1855       if (script.name()) {
1856         result += script.name();
1857       } else {
1858         result += '[unnamed]';
1859       }
1860       if (!this.isDebuggerFrame()) {
1861         var location = this.sourceLocation();
1862         result += ' line ';
1863         result += !IS_UNDEFINED(location) ? (location.line + 1) : '?';
1864         result += ' column ';
1865         result += !IS_UNDEFINED(location) ? (location.column + 1) : '?';
1866         if (!IS_UNDEFINED(this.sourcePosition())) {
1867           result += ' (position ' + (this.sourcePosition() + 1) + ')';
1868         }
1869       }
1870     } else {
1871       result += '[no source]';
1872     }
1873   } else {
1874     result += '[unresolved]';
1875   }
1876
1877   return result;
1878 };
1879
1880
1881 FrameMirror.prototype.localsText = function() {
1882   // Format local variables.
1883   var result = '';
1884   var locals_count = this.localCount();
1885   if (locals_count > 0) {
1886     for (var i = 0; i < locals_count; ++i) {
1887       result += '      var ';
1888       result += this.localName(i);
1889       result += ' = ';
1890       result += this.localValue(i).toText();
1891       if (i < locals_count - 1) result += '\n';
1892     }
1893   }
1894
1895   return result;
1896 };
1897
1898
1899 FrameMirror.prototype.restart = function() {
1900   var result = %LiveEditRestartFrame(this.break_id_, this.index_);
1901   if (IS_UNDEFINED(result)) {
1902     result = "Failed to find requested frame";
1903   }
1904   return result;
1905 };
1906
1907
1908 FrameMirror.prototype.toText = function(opt_locals) {
1909   var result = '';
1910   result += '#' + (this.index() <= 9 ? '0' : '') + this.index();
1911   result += ' ';
1912   result += this.invocationText();
1913   result += ' ';
1914   result += this.sourceAndPositionText();
1915   if (opt_locals) {
1916     result += '\n';
1917     result += this.localsText();
1918   }
1919   return result;
1920 };
1921
1922
1923 var kScopeDetailsTypeIndex = 0;
1924 var kScopeDetailsObjectIndex = 1;
1925
1926 function ScopeDetails(frame, fun, index, opt_details) {
1927   if (frame) {
1928     this.break_id_ = frame.break_id_;
1929     this.details_ = opt_details ||
1930                     %GetScopeDetails(frame.break_id_,
1931                                      frame.details_.frameId(),
1932                                      frame.details_.inlinedFrameIndex(),
1933                                      index);
1934     this.frame_id_ = frame.details_.frameId();
1935     this.inlined_frame_id_ = frame.details_.inlinedFrameIndex();
1936   } else {
1937     this.details_ = opt_details || %GetFunctionScopeDetails(fun.value(), index);
1938     this.fun_value_ = fun.value();
1939     this.break_id_ = undefined;
1940   }
1941   this.index_ = index;
1942 }
1943
1944
1945 ScopeDetails.prototype.type = function() {
1946   if (!IS_UNDEFINED(this.break_id_)) {
1947     %CheckExecutionState(this.break_id_);
1948   }
1949   return this.details_[kScopeDetailsTypeIndex];
1950 };
1951
1952
1953 ScopeDetails.prototype.object = function() {
1954   if (!IS_UNDEFINED(this.break_id_)) {
1955     %CheckExecutionState(this.break_id_);
1956   }
1957   return this.details_[kScopeDetailsObjectIndex];
1958 };
1959
1960
1961 ScopeDetails.prototype.setVariableValueImpl = function(name, new_value) {
1962   var raw_res;
1963   if (!IS_UNDEFINED(this.break_id_)) {
1964     %CheckExecutionState(this.break_id_);
1965     raw_res = %SetScopeVariableValue(this.break_id_, this.frame_id_,
1966         this.inlined_frame_id_, this.index_, name, new_value);
1967   } else {
1968     raw_res = %SetScopeVariableValue(this.fun_value_, null, null, this.index_,
1969         name, new_value);
1970   }
1971   if (!raw_res) {
1972     throw new Error("Failed to set variable value");
1973   }
1974 };
1975
1976
1977 /**
1978  * Mirror object for scope of frame or function. Either frame or function must
1979  * be specified.
1980  * @param {FrameMirror} frame The frame this scope is a part of
1981  * @param {FunctionMirror} function The function this scope is a part of
1982  * @param {number} index The scope index in the frame
1983  * @param {Array=} opt_details Raw scope details data
1984  * @constructor
1985  * @extends Mirror
1986  */
1987 function ScopeMirror(frame, function, index, opt_details) {
1988   %_CallFunction(this, SCOPE_TYPE, Mirror);
1989   if (frame) {
1990     this.frame_index_ = frame.index_;
1991   } else {
1992     this.frame_index_ = undefined;
1993   }
1994   this.scope_index_ = index;
1995   this.details_ = new ScopeDetails(frame, function, index, opt_details);
1996 }
1997 inherits(ScopeMirror, Mirror);
1998
1999
2000 ScopeMirror.prototype.details = function() {
2001   return this.details_;
2002 };
2003
2004
2005 ScopeMirror.prototype.frameIndex = function() {
2006   return this.frame_index_;
2007 };
2008
2009
2010 ScopeMirror.prototype.scopeIndex = function() {
2011   return this.scope_index_;
2012 };
2013
2014
2015 ScopeMirror.prototype.scopeType = function() {
2016   return this.details_.type();
2017 };
2018
2019
2020 ScopeMirror.prototype.scopeObject = function() {
2021   // For local and closure scopes create a transient mirror as these objects are
2022   // created on the fly materializing the local or closure scopes and
2023   // therefore will not preserve identity.
2024   var transient = this.scopeType() == ScopeType.Local ||
2025                   this.scopeType() == ScopeType.Closure;
2026   return MakeMirror(this.details_.object(), transient);
2027 };
2028
2029
2030 ScopeMirror.prototype.setVariableValue = function(name, new_value) {
2031   this.details_.setVariableValueImpl(name, new_value);
2032 };
2033
2034
2035 /**
2036  * Mirror object for script source.
2037  * @param {Script} script The script object
2038  * @constructor
2039  * @extends Mirror
2040  */
2041 function ScriptMirror(script) {
2042   %_CallFunction(this, SCRIPT_TYPE, Mirror);
2043   this.script_ = script;
2044   this.context_ = new ContextMirror(script.context_data);
2045   this.allocateHandle_();
2046 }
2047 inherits(ScriptMirror, Mirror);
2048
2049
2050 ScriptMirror.prototype.value = function() {
2051   return this.script_;
2052 };
2053
2054
2055 ScriptMirror.prototype.name = function() {
2056   return this.script_.name || this.script_.nameOrSourceURL();
2057 };
2058
2059
2060 ScriptMirror.prototype.id = function() {
2061   return this.script_.id;
2062 };
2063
2064
2065 ScriptMirror.prototype.source = function() {
2066   return this.script_.source;
2067 };
2068
2069
2070 ScriptMirror.prototype.setSource = function(source) {
2071   %DebugSetScriptSource(this.script_, source);
2072 };
2073
2074
2075 ScriptMirror.prototype.lineOffset = function() {
2076   return this.script_.line_offset;
2077 };
2078
2079
2080 ScriptMirror.prototype.columnOffset = function() {
2081   return this.script_.column_offset;
2082 };
2083
2084
2085 ScriptMirror.prototype.data = function() {
2086   return this.script_.data;
2087 };
2088
2089
2090 ScriptMirror.prototype.scriptType = function() {
2091   return this.script_.type;
2092 };
2093
2094
2095 ScriptMirror.prototype.compilationType = function() {
2096   return this.script_.compilation_type;
2097 };
2098
2099
2100 ScriptMirror.prototype.lineCount = function() {
2101   return this.script_.lineCount();
2102 };
2103
2104
2105 ScriptMirror.prototype.locationFromPosition = function(
2106     position, include_resource_offset) {
2107   return this.script_.locationFromPosition(position, include_resource_offset);
2108 };
2109
2110
2111 ScriptMirror.prototype.sourceSlice = function (opt_from_line, opt_to_line) {
2112   return this.script_.sourceSlice(opt_from_line, opt_to_line);
2113 };
2114
2115
2116 ScriptMirror.prototype.context = function() {
2117   return this.context_;
2118 };
2119
2120
2121 ScriptMirror.prototype.evalFromScript = function() {
2122   return MakeMirror(this.script_.eval_from_script);
2123 };
2124
2125
2126 ScriptMirror.prototype.evalFromFunctionName = function() {
2127   return MakeMirror(this.script_.eval_from_function_name);
2128 };
2129
2130
2131 ScriptMirror.prototype.evalFromLocation = function() {
2132   var eval_from_script = this.evalFromScript();
2133   if (!eval_from_script.isUndefined()) {
2134     var position = this.script_.eval_from_script_position;
2135     return eval_from_script.locationFromPosition(position, true);
2136   }
2137 };
2138
2139
2140 ScriptMirror.prototype.toText = function() {
2141   var result = '';
2142   result += this.name();
2143   result += ' (lines: ';
2144   if (this.lineOffset() > 0) {
2145     result += this.lineOffset();
2146     result += '-';
2147     result += this.lineOffset() + this.lineCount() - 1;
2148   } else {
2149     result += this.lineCount();
2150   }
2151   result += ')';
2152   return result;
2153 };
2154
2155
2156 /**
2157  * Mirror object for context.
2158  * @param {Object} data The context data
2159  * @constructor
2160  * @extends Mirror
2161  */
2162 function ContextMirror(data) {
2163   %_CallFunction(this, CONTEXT_TYPE, Mirror);
2164   this.data_ = data;
2165   this.allocateHandle_();
2166 }
2167 inherits(ContextMirror, Mirror);
2168
2169
2170 ContextMirror.prototype.data = function() {
2171   return this.data_;
2172 };
2173
2174
2175 /**
2176  * Returns a mirror serializer
2177  *
2178  * @param {boolean} details Set to true to include details
2179  * @param {Object} options Options comtrolling the serialization
2180  *     The following options can be set:
2181  *       includeSource: include ths full source of scripts
2182  * @returns {MirrorSerializer} mirror serializer
2183  */
2184 function MakeMirrorSerializer(details, options) {
2185   return new JSONProtocolSerializer(details, options);
2186 }
2187
2188
2189 /**
2190  * Object for serializing a mirror objects and its direct references.
2191  * @param {boolean} details Indicates whether to include details for the mirror
2192  *     serialized
2193  * @constructor
2194  */
2195 function JSONProtocolSerializer(details, options) {
2196   this.details_ = details;
2197   this.options_ = options;
2198   this.mirrors_ = [ ];
2199 }
2200
2201
2202 /**
2203  * Returns a serialization of an object reference. The referenced object are
2204  * added to the serialization state.
2205  *
2206  * @param {Mirror} mirror The mirror to serialize
2207  * @returns {String} JSON serialization
2208  */
2209 JSONProtocolSerializer.prototype.serializeReference = function(mirror) {
2210   return this.serialize_(mirror, true, true);
2211 };
2212
2213
2214 /**
2215  * Returns a serialization of an object value. The referenced objects are
2216  * added to the serialization state.
2217  *
2218  * @param {Mirror} mirror The mirror to serialize
2219  * @returns {String} JSON serialization
2220  */
2221 JSONProtocolSerializer.prototype.serializeValue = function(mirror) {
2222   var json = this.serialize_(mirror, false, true);
2223   return json;
2224 };
2225
2226
2227 /**
2228  * Returns a serialization of all the objects referenced.
2229  *
2230  * @param {Mirror} mirror The mirror to serialize.
2231  * @returns {Array.<Object>} Array of the referenced objects converted to
2232  *     protcol objects.
2233  */
2234 JSONProtocolSerializer.prototype.serializeReferencedObjects = function() {
2235   // Collect the protocol representation of the referenced objects in an array.
2236   var content = [];
2237
2238   // Get the number of referenced objects.
2239   var count = this.mirrors_.length;
2240
2241   for (var i = 0; i < count; i++) {
2242     content.push(this.serialize_(this.mirrors_[i], false, false));
2243   }
2244
2245   return content;
2246 };
2247
2248
2249 JSONProtocolSerializer.prototype.includeSource_ = function() {
2250   return this.options_ && this.options_.includeSource;
2251 };
2252
2253
2254 JSONProtocolSerializer.prototype.inlineRefs_ = function() {
2255   return this.options_ && this.options_.inlineRefs;
2256 };
2257
2258
2259 JSONProtocolSerializer.prototype.maxStringLength_ = function() {
2260   if (IS_UNDEFINED(this.options_) ||
2261       IS_UNDEFINED(this.options_.maxStringLength)) {
2262     return kMaxProtocolStringLength;
2263   }
2264   return this.options_.maxStringLength;
2265 };
2266
2267
2268 JSONProtocolSerializer.prototype.add_ = function(mirror) {
2269   // If this mirror is already in the list just return.
2270   for (var i = 0; i < this.mirrors_.length; i++) {
2271     if (this.mirrors_[i] === mirror) {
2272       return;
2273     }
2274   }
2275
2276   // Add the mirror to the list of mirrors to be serialized.
2277   this.mirrors_.push(mirror);
2278 };
2279
2280
2281 /**
2282  * Formats mirror object to protocol reference object with some data that can
2283  * be used to display the value in debugger.
2284  * @param {Mirror} mirror Mirror to serialize.
2285  * @return {Object} Protocol reference object.
2286  */
2287 JSONProtocolSerializer.prototype.serializeReferenceWithDisplayData_ =
2288     function(mirror) {
2289   var o = {};
2290   o.ref = mirror.handle();
2291   o.type = mirror.type();
2292   switch (mirror.type()) {
2293     case UNDEFINED_TYPE:
2294     case NULL_TYPE:
2295     case BOOLEAN_TYPE:
2296     case NUMBER_TYPE:
2297       o.value = mirror.value();
2298       break;
2299     case STRING_TYPE:
2300       o.value = mirror.getTruncatedValue(this.maxStringLength_());
2301       break;
2302     case FUNCTION_TYPE:
2303       o.name = mirror.name();
2304       o.inferredName = mirror.inferredName();
2305       if (mirror.script()) {
2306         o.scriptId = mirror.script().id();
2307       }
2308       break;
2309     case ERROR_TYPE:
2310     case REGEXP_TYPE:
2311       o.value = mirror.toText();
2312       break;
2313     case OBJECT_TYPE:
2314       o.className = mirror.className();
2315       break;
2316   }
2317   return o;
2318 };
2319
2320
2321 JSONProtocolSerializer.prototype.serialize_ = function(mirror, reference,
2322                                                        details) {
2323   // If serializing a reference to a mirror just return the reference and add
2324   // the mirror to the referenced mirrors.
2325   if (reference &&
2326       (mirror.isValue() || mirror.isScript() || mirror.isContext())) {
2327     if (this.inlineRefs_() && mirror.isValue()) {
2328       return this.serializeReferenceWithDisplayData_(mirror);
2329     } else {
2330       this.add_(mirror);
2331       return {'ref' : mirror.handle()};
2332     }
2333   }
2334
2335   // Collect the JSON property/value pairs.
2336   var content = {};
2337
2338   // Add the mirror handle.
2339   if (mirror.isValue() || mirror.isScript() || mirror.isContext()) {
2340     content.handle = mirror.handle();
2341   }
2342
2343   // Always add the type.
2344   content.type = mirror.type();
2345
2346   switch (mirror.type()) {
2347     case UNDEFINED_TYPE:
2348     case NULL_TYPE:
2349       // Undefined and null are represented just by their type.
2350       break;
2351
2352     case BOOLEAN_TYPE:
2353       // Boolean values are simply represented by their value.
2354       content.value = mirror.value();
2355       break;
2356
2357     case NUMBER_TYPE:
2358       // Number values are simply represented by their value.
2359       content.value = NumberToJSON_(mirror.value());
2360       break;
2361
2362     case STRING_TYPE:
2363       // String values might have their value cropped to keep down size.
2364       if (this.maxStringLength_() != -1 &&
2365           mirror.length() > this.maxStringLength_()) {
2366         var str = mirror.getTruncatedValue(this.maxStringLength_());
2367         content.value = str;
2368         content.fromIndex = 0;
2369         content.toIndex = this.maxStringLength_();
2370       } else {
2371         content.value = mirror.value();
2372       }
2373       content.length = mirror.length();
2374       break;
2375
2376     case OBJECT_TYPE:
2377     case FUNCTION_TYPE:
2378     case ERROR_TYPE:
2379     case REGEXP_TYPE:
2380     case PROMISE_TYPE:
2381       // Add object representation.
2382       this.serializeObject_(mirror, content, details);
2383       break;
2384
2385     case PROPERTY_TYPE:
2386     case INTERNAL_PROPERTY_TYPE:
2387       throw new Error('PropertyMirror cannot be serialized independently');
2388       break;
2389
2390     case FRAME_TYPE:
2391       // Add object representation.
2392       this.serializeFrame_(mirror, content);
2393       break;
2394
2395     case SCOPE_TYPE:
2396       // Add object representation.
2397       this.serializeScope_(mirror, content);
2398       break;
2399
2400     case SCRIPT_TYPE:
2401       // Script is represented by id, name and source attributes.
2402       if (mirror.name()) {
2403         content.name = mirror.name();
2404       }
2405       content.id = mirror.id();
2406       content.lineOffset = mirror.lineOffset();
2407       content.columnOffset = mirror.columnOffset();
2408       content.lineCount = mirror.lineCount();
2409       if (mirror.data()) {
2410         content.data = mirror.data();
2411       }
2412       if (this.includeSource_()) {
2413         content.source = mirror.source();
2414       } else {
2415         var sourceStart = mirror.source().substring(0, 80);
2416         content.sourceStart = sourceStart;
2417       }
2418       content.sourceLength = mirror.source().length;
2419       content.scriptType = mirror.scriptType();
2420       content.compilationType = mirror.compilationType();
2421       // For compilation type eval emit information on the script from which
2422       // eval was called if a script is present.
2423       if (mirror.compilationType() == 1 &&
2424           mirror.evalFromScript()) {
2425         content.evalFromScript =
2426             this.serializeReference(mirror.evalFromScript());
2427         var evalFromLocation = mirror.evalFromLocation();
2428         if (evalFromLocation) {
2429           content.evalFromLocation = { line: evalFromLocation.line,
2430                                        column: evalFromLocation.column };
2431         }
2432         if (mirror.evalFromFunctionName()) {
2433           content.evalFromFunctionName = mirror.evalFromFunctionName();
2434         }
2435       }
2436       if (mirror.context()) {
2437         content.context = this.serializeReference(mirror.context());
2438       }
2439       break;
2440
2441     case CONTEXT_TYPE:
2442       content.data = mirror.data();
2443       break;
2444   }
2445
2446   // Always add the text representation.
2447   content.text = mirror.toText();
2448
2449   // Create and return the JSON string.
2450   return content;
2451 };
2452
2453
2454 /**
2455  * Serialize object information to the following JSON format.
2456  *
2457  *   {"className":"<class name>",
2458  *    "constructorFunction":{"ref":<number>},
2459  *    "protoObject":{"ref":<number>},
2460  *    "prototypeObject":{"ref":<number>},
2461  *    "namedInterceptor":<boolean>,
2462  *    "indexedInterceptor":<boolean>,
2463  *    "properties":[<properties>],
2464  *    "internalProperties":[<internal properties>]}
2465  */
2466 JSONProtocolSerializer.prototype.serializeObject_ = function(mirror, content,
2467                                                              details) {
2468   // Add general object properties.
2469   content.className = mirror.className();
2470   content.constructorFunction =
2471       this.serializeReference(mirror.constructorFunction());
2472   content.protoObject = this.serializeReference(mirror.protoObject());
2473   content.prototypeObject = this.serializeReference(mirror.prototypeObject());
2474
2475   // Add flags to indicate whether there are interceptors.
2476   if (mirror.hasNamedInterceptor()) {
2477     content.namedInterceptor = true;
2478   }
2479   if (mirror.hasIndexedInterceptor()) {
2480     content.indexedInterceptor = true;
2481   }
2482
2483   if (mirror.isFunction()) {
2484     // Add function specific properties.
2485     content.name = mirror.name();
2486     if (!IS_UNDEFINED(mirror.inferredName())) {
2487       content.inferredName = mirror.inferredName();
2488     }
2489     content.resolved = mirror.resolved();
2490     if (mirror.resolved()) {
2491       content.source = mirror.source();
2492     }
2493     if (mirror.script()) {
2494       content.script = this.serializeReference(mirror.script());
2495       content.scriptId = mirror.script().id();
2496
2497       serializeLocationFields(mirror.sourceLocation(), content);
2498     }
2499
2500     content.scopes = [];
2501     for (var i = 0; i < mirror.scopeCount(); i++) {
2502       var scope = mirror.scope(i);
2503       content.scopes.push({
2504         type: scope.scopeType(),
2505         index: i
2506       });
2507     }
2508   }
2509
2510   if (mirror.isDate()) {
2511     // Add date specific properties.
2512     content.value = mirror.value();
2513   }
2514
2515   if (mirror.isPromise()) {
2516     // Add promise specific properties.
2517     content.status = mirror.status();
2518     content.promiseValue = mirror.promiseValue();
2519   }
2520
2521   // Add actual properties - named properties followed by indexed properties.
2522   var propertyNames = mirror.propertyNames(PropertyKind.Named);
2523   var propertyIndexes = mirror.propertyNames(PropertyKind.Indexed);
2524   var p = new Array(propertyNames.length + propertyIndexes.length);
2525   for (var i = 0; i < propertyNames.length; i++) {
2526     var propertyMirror = mirror.property(propertyNames[i]);
2527     p[i] = this.serializeProperty_(propertyMirror);
2528     if (details) {
2529       this.add_(propertyMirror.value());
2530     }
2531   }
2532   for (var i = 0; i < propertyIndexes.length; i++) {
2533     var propertyMirror = mirror.property(propertyIndexes[i]);
2534     p[propertyNames.length + i] = this.serializeProperty_(propertyMirror);
2535     if (details) {
2536       this.add_(propertyMirror.value());
2537     }
2538   }
2539   content.properties = p;
2540
2541   var internalProperties = mirror.internalProperties();
2542   if (internalProperties.length > 0) {
2543     var ip = [];
2544     for (var i = 0; i < internalProperties.length; i++) {
2545       ip.push(this.serializeInternalProperty_(internalProperties[i]));
2546     }
2547     content.internalProperties = ip;
2548   }
2549 };
2550
2551
2552 /**
2553  * Serialize location information to the following JSON format:
2554  *
2555  *   "position":"<position>",
2556  *   "line":"<line>",
2557  *   "column":"<column>",
2558  *
2559  * @param {SourceLocation} location The location to serialize, may be undefined.
2560  */
2561 function serializeLocationFields (location, content) {
2562   if (!location) {
2563     return;
2564   }
2565   content.position = location.position;
2566   var line = location.line;
2567   if (!IS_UNDEFINED(line)) {
2568     content.line = line;
2569   }
2570   var column = location.column;
2571   if (!IS_UNDEFINED(column)) {
2572     content.column = column;
2573   }
2574 }
2575
2576
2577 /**
2578  * Serialize property information to the following JSON format for building the
2579  * array of properties.
2580  *
2581  *   {"name":"<property name>",
2582  *    "attributes":<number>,
2583  *    "propertyType":<number>,
2584  *    "ref":<number>}
2585  *
2586  * If the attribute for the property is PropertyAttribute.None it is not added.
2587  * If the propertyType for the property is PropertyType.Normal it is not added.
2588  * Here are a couple of examples.
2589  *
2590  *   {"name":"hello","ref":1}
2591  *   {"name":"length","attributes":7,"propertyType":3,"ref":2}
2592  *
2593  * @param {PropertyMirror} propertyMirror The property to serialize.
2594  * @returns {Object} Protocol object representing the property.
2595  */
2596 JSONProtocolSerializer.prototype.serializeProperty_ = function(propertyMirror) {
2597   var result = {};
2598
2599   result.name = propertyMirror.name();
2600   var propertyValue = propertyMirror.value();
2601   if (this.inlineRefs_() && propertyValue.isValue()) {
2602     result.value = this.serializeReferenceWithDisplayData_(propertyValue);
2603   } else {
2604     if (propertyMirror.attributes() != PropertyAttribute.None) {
2605       result.attributes = propertyMirror.attributes();
2606     }
2607     if (propertyMirror.propertyType() != PropertyType.Normal) {
2608       result.propertyType = propertyMirror.propertyType();
2609     }
2610     result.ref = propertyValue.handle();
2611   }
2612   return result;
2613 };
2614
2615
2616 /**
2617  * Serialize internal property information to the following JSON format for
2618  * building the array of properties.
2619  *
2620  *   {"name":"<property name>",
2621  *    "ref":<number>}
2622  *
2623  *   {"name":"[[BoundThis]]","ref":117}
2624  *
2625  * @param {InternalPropertyMirror} propertyMirror The property to serialize.
2626  * @returns {Object} Protocol object representing the property.
2627  */
2628 JSONProtocolSerializer.prototype.serializeInternalProperty_ =
2629     function(propertyMirror) {
2630   var result = {};
2631
2632   result.name = propertyMirror.name();
2633   var propertyValue = propertyMirror.value();
2634   if (this.inlineRefs_() && propertyValue.isValue()) {
2635     result.value = this.serializeReferenceWithDisplayData_(propertyValue);
2636   } else {
2637     result.ref = propertyValue.handle();
2638   }
2639   return result;
2640 };
2641
2642
2643 JSONProtocolSerializer.prototype.serializeFrame_ = function(mirror, content) {
2644   content.index = mirror.index();
2645   content.receiver = this.serializeReference(mirror.receiver());
2646   var func = mirror.func();
2647   content.func = this.serializeReference(func);
2648   var script = func.script();
2649   if (script) {
2650     content.script = this.serializeReference(script);
2651   }
2652   content.constructCall = mirror.isConstructCall();
2653   content.atReturn = mirror.isAtReturn();
2654   if (mirror.isAtReturn()) {
2655     content.returnValue = this.serializeReference(mirror.returnValue());
2656   }
2657   content.debuggerFrame = mirror.isDebuggerFrame();
2658   var x = new Array(mirror.argumentCount());
2659   for (var i = 0; i < mirror.argumentCount(); i++) {
2660     var arg = {};
2661     var argument_name = mirror.argumentName(i);
2662     if (argument_name) {
2663       arg.name = argument_name;
2664     }
2665     arg.value = this.serializeReference(mirror.argumentValue(i));
2666     x[i] = arg;
2667   }
2668   content.arguments = x;
2669   var x = new Array(mirror.localCount());
2670   for (var i = 0; i < mirror.localCount(); i++) {
2671     var local = {};
2672     local.name = mirror.localName(i);
2673     local.value = this.serializeReference(mirror.localValue(i));
2674     x[i] = local;
2675   }
2676   content.locals = x;
2677   serializeLocationFields(mirror.sourceLocation(), content);
2678   var source_line_text = mirror.sourceLineText();
2679   if (!IS_UNDEFINED(source_line_text)) {
2680     content.sourceLineText = source_line_text;
2681   }
2682
2683   content.scopes = [];
2684   for (var i = 0; i < mirror.scopeCount(); i++) {
2685     var scope = mirror.scope(i);
2686     content.scopes.push({
2687       type: scope.scopeType(),
2688       index: i
2689     });
2690   }
2691 };
2692
2693
2694 JSONProtocolSerializer.prototype.serializeScope_ = function(mirror, content) {
2695   content.index = mirror.scopeIndex();
2696   content.frameIndex = mirror.frameIndex();
2697   content.type = mirror.scopeType();
2698   content.object = this.inlineRefs_() ?
2699                    this.serializeValue(mirror.scopeObject()) :
2700                    this.serializeReference(mirror.scopeObject());
2701 };
2702
2703
2704 /**
2705  * Convert a number to a protocol value. For all finite numbers the number
2706  * itself is returned. For non finite numbers NaN, Infinite and
2707  * -Infinite the string representation "NaN", "Infinite" or "-Infinite"
2708  * (not including the quotes) is returned.
2709  *
2710  * @param {number} value The number value to convert to a protocol value.
2711  * @returns {number|string} Protocol value.
2712  */
2713 function NumberToJSON_(value) {
2714   if (isNaN(value)) {
2715     return 'NaN';
2716   }
2717   if (!NUMBER_IS_FINITE(value)) {
2718     if (value > 0) {
2719       return 'Infinity';
2720     } else {
2721       return '-Infinity';
2722     }
2723   }
2724   return value;
2725 }