blob: 27207928cad403112a540b185283d01f667ff805 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28
29// -------------------------------------------------------------------
30
31// Lazily initialized.
32var kVowelSounds = 0;
33var kCapitalVowelSounds = 0;
34
35// If this object gets passed to an error constructor the error will
36// get an accessor for .message that constructs a descriptive error
37// message on access.
38var kAddMessageAccessorsMarker = { };
39
40
41function GetInstanceName(cons) {
42 if (cons.length == 0) {
43 return "";
44 }
45 var first = %StringToLowerCase(StringCharAt.call(cons, 0));
46 if (kVowelSounds === 0) {
47 kVowelSounds = {a: true, e: true, i: true, o: true, u: true, y: true};
48 kCapitalVowelSounds = {a: true, e: true, i: true, o: true, u: true, h: true,
49 f: true, l: true, m: true, n: true, r: true, s: true, x: true, y: true};
50 }
51 var vowel_mapping = kVowelSounds;
52 if (cons.length > 1 && (StringCharAt.call(cons, 0) != first)) {
53 // First char is upper case
54 var second = %StringToLowerCase(StringCharAt.call(cons, 1));
55 // Second char is upper case
56 if (StringCharAt.call(cons, 1) != second) {
57 vowel_mapping = kCapitalVowelSounds;
58 }
59 }
60 var s = vowel_mapping[first] ? "an " : "a ";
61 return s + cons;
62}
63
64
65var kMessages = 0;
66
67
68function FormatString(format, args) {
69 var result = format;
70 for (var i = 0; i < args.length; i++) {
71 var str;
72 try { str = ToDetailString(args[i]); }
73 catch (e) { str = "#<error>"; }
74 result = ArrayJoin.call(StringSplit.call(result, "%" + i), str);
75 }
76 return result;
77}
78
79
80function ToDetailString(obj) {
81 if (obj != null && IS_OBJECT(obj) && obj.toString === $Object.prototype.toString) {
82 var constructor = obj.constructor;
83 if (!constructor) return ToString(obj);
84 var constructorName = constructor.name;
85 if (!constructorName) return ToString(obj);
86 return "#<" + GetInstanceName(constructorName) + ">";
87 } else {
88 return ToString(obj);
89 }
90}
91
92
93function MakeGenericError(constructor, type, args) {
94 if (IS_UNDEFINED(args)) {
95 args = [];
96 }
97 var e = new constructor(kAddMessageAccessorsMarker);
98 e.type = type;
99 e.arguments = args;
100 return e;
101}
102
103
104/**
105 * Setup the Script function and constructor.
106 */
107%FunctionSetInstanceClassName(Script, 'Script');
108%SetProperty(Script.prototype, 'constructor', Script, DONT_ENUM);
109%SetCode(Script, function(x) {
110 // Script objects can only be created by the VM.
111 throw new $Error("Not supported");
112});
113
114
115// Helper functions; called from the runtime system.
116function FormatMessage(message) {
117 if (kMessages === 0) {
118 kMessages = {
119 // Error
120 cyclic_proto: "Cyclic __proto__ value",
121 // TypeError
122 unexpected_token: "Unexpected token %0",
123 unexpected_token_number: "Unexpected number",
124 unexpected_token_string: "Unexpected string",
125 unexpected_token_identifier: "Unexpected identifier",
126 unexpected_eos: "Unexpected end of input",
127 malformed_regexp: "Invalid regular expression: /%0/: %1",
128 unterminated_regexp: "Invalid regular expression: missing /",
129 regexp_flags: "Cannot supply flags when constructing one RegExp from another",
130 invalid_lhs_in_assignment: "Invalid left-hand side in assignment",
131 invalid_lhs_in_for_in: "Invalid left-hand side in for-in",
132 invalid_lhs_in_postfix_op: "Invalid left-hand side expression in postfix operation",
133 invalid_lhs_in_prefix_op: "Invalid left-hand side expression in prefix operation",
134 multiple_defaults_in_switch: "More than one default clause in switch statement",
135 newline_after_throw: "Illegal newline after throw",
136 redeclaration: "%0 '%1' has already been declared",
137 no_catch_or_finally: "Missing catch or finally after try",
138 unknown_label: "Undefined label '%0'",
139 uncaught_exception: "Uncaught %0",
140 stack_trace: "Stack Trace:\n%0",
141 called_non_callable: "%0 is not a function",
142 undefined_method: "Object %1 has no method '%0'",
143 property_not_function: "Property '%0' of object %1 is not a function",
144 cannot_convert_to_primitive: "Cannot convert object to primitive value",
145 not_constructor: "%0 is not a constructor",
146 not_defined: "%0 is not defined",
147 non_object_property_load: "Cannot read property '%0' of %1",
148 non_object_property_store: "Cannot set property '%0' of %1",
149 non_object_property_call: "Cannot call method '%0' of %1",
150 with_expression: "%0 has no properties",
151 illegal_invocation: "Illegal invocation",
152 no_setter_in_callback: "Cannot set property %0 of %1 which has only a getter",
153 apply_non_function: "Function.prototype.apply was called on %0, which is a %1 and not a function",
154 apply_wrong_args: "Function.prototype.apply: Arguments list has wrong type",
155 invalid_in_operator_use: "Cannot use 'in' operator to search for '%0' in %1",
156 instanceof_function_expected: "Expecting a function in instanceof check, but got %0",
157 instanceof_nonobject_proto: "Function has non-object prototype '%0' in instanceof check",
158 null_to_object: "Cannot convert null to object",
159 reduce_no_initial: "Reduce of empty array with no initial value",
160 // RangeError
161 invalid_array_length: "Invalid array length",
162 stack_overflow: "Maximum call stack size exceeded",
163 apply_overflow: "Function.prototype.apply cannot support %0 arguments",
164 // SyntaxError
165 unable_to_parse: "Parse error",
166 duplicate_regexp_flag: "Duplicate RegExp flag %0",
167 invalid_regexp: "Invalid RegExp pattern /%0/",
168 illegal_break: "Illegal break statement",
169 illegal_continue: "Illegal continue statement",
170 illegal_return: "Illegal return statement",
171 error_loading_debugger: "Error loading debugger",
172 no_input_to_regexp: "No input to %0",
173 result_not_primitive: "Result of %0 must be a primitive, was %1",
174 invalid_json: "String '%0' is not valid JSON",
175 circular_structure: "Converting circular structure to JSON",
176 object_keys_non_object: "Object.keys called on non-object"
177 };
178 }
179 var format = kMessages[message.type];
180 if (!format) return "<unknown message " + message.type + ">";
181 return FormatString(format, message.args);
182}
183
184
185function GetLineNumber(message) {
186 if (message.startPos == -1) return -1;
187 var location = message.script.locationFromPosition(message.startPos, true);
188 if (location == null) return -1;
189 return location.line + 1;
190}
191
192
193// Returns the source code line containing the given source
194// position, or the empty string if the position is invalid.
195function GetSourceLine(message) {
196 var location = message.script.locationFromPosition(message.startPos, true);
197 if (location == null) return "";
198 location.restrict();
199 return location.sourceText();
200}
201
202
203function MakeTypeError(type, args) {
204 return MakeGenericError($TypeError, type, args);
205}
206
207
208function MakeRangeError(type, args) {
209 return MakeGenericError($RangeError, type, args);
210}
211
212
213function MakeSyntaxError(type, args) {
214 return MakeGenericError($SyntaxError, type, args);
215}
216
217
218function MakeReferenceError(type, args) {
219 return MakeGenericError($ReferenceError, type, args);
220}
221
222
223function MakeEvalError(type, args) {
224 return MakeGenericError($EvalError, type, args);
225}
226
227
228function MakeError(type, args) {
229 return MakeGenericError($Error, type, args);
230}
231
232/**
233 * Find a line number given a specific source position.
234 * @param {number} position The source position.
235 * @return {number} 0 if input too small, -1 if input too large,
236 else the line number.
237 */
238Script.prototype.lineFromPosition = function(position) {
239 var lower = 0;
240 var upper = this.lineCount() - 1;
241
242 // We'll never find invalid positions so bail right away.
243 if (position > this.line_ends[upper]) {
244 return -1;
245 }
246
247 // This means we don't have to safe-guard indexing line_ends[i - 1].
248 if (position <= this.line_ends[0]) {
249 return 0;
250 }
251
252 // Binary search to find line # from position range.
253 while (upper >= 1) {
254 var i = (lower + upper) >> 1;
255
256 if (position > this.line_ends[i]) {
257 lower = i + 1;
258 } else if (position <= this.line_ends[i - 1]) {
259 upper = i - 1;
260 } else {
261 return i;
262 }
263 }
264 return -1;
265}
266
267/**
268 * Get information on a specific source position.
269 * @param {number} position The source position
270 * @param {boolean} include_resource_offset Set to true to have the resource
271 * offset added to the location
272 * @return {SourceLocation}
273 * If line is negative or not in the source null is returned.
274 */
275Script.prototype.locationFromPosition = function (position,
276 include_resource_offset) {
277 var line = this.lineFromPosition(position);
278 if (line == -1) return null;
279
280 // Determine start, end and column.
281 var start = line == 0 ? 0 : this.line_ends[line - 1] + 1;
282 var end = this.line_ends[line];
283 if (end > 0 && StringCharAt.call(this.source, end - 1) == '\r') end--;
284 var column = position - start;
285
286 // Adjust according to the offset within the resource.
287 if (include_resource_offset) {
288 line += this.line_offset;
289 if (line == this.line_offset) {
290 column += this.column_offset;
291 }
292 }
293
294 return new SourceLocation(this, position, line, column, start, end);
295};
296
297
298/**
299 * Get information on a specific source line and column possibly offset by a
300 * fixed source position. This function is used to find a source position from
301 * a line and column position. The fixed source position offset is typically
302 * used to find a source position in a function based on a line and column in
303 * the source for the function alone. The offset passed will then be the
304 * start position of the source for the function within the full script source.
305 * @param {number} opt_line The line within the source. Default value is 0
306 * @param {number} opt_column The column in within the line. Default value is 0
307 * @param {number} opt_offset_position The offset from the begining of the
308 * source from where the line and column calculation starts. Default value is 0
309 * @return {SourceLocation}
310 * If line is negative or not in the source null is returned.
311 */
312Script.prototype.locationFromLine = function (opt_line, opt_column, opt_offset_position) {
313 // Default is the first line in the script. Lines in the script is relative
314 // to the offset within the resource.
315 var line = 0;
316 if (!IS_UNDEFINED(opt_line)) {
317 line = opt_line - this.line_offset;
318 }
319
320 // Default is first column. If on the first line add the offset within the
321 // resource.
322 var column = opt_column || 0;
323 if (line == 0) {
324 column -= this.column_offset
325 }
326
327 var offset_position = opt_offset_position || 0;
328 if (line < 0 || column < 0 || offset_position < 0) return null;
329 if (line == 0) {
330 return this.locationFromPosition(offset_position + column, false);
331 } else {
332 // Find the line where the offset position is located.
333 var offset_line = this.lineFromPosition(offset_position);
334
335 if (offset_line == -1 || offset_line + line >= this.lineCount()) {
336 return null;
337 }
338
339 return this.locationFromPosition(this.line_ends[offset_line + line - 1] + 1 + column); // line > 0 here.
340 }
341}
342
343
344/**
345 * Get a slice of source code from the script. The boundaries for the slice is
346 * specified in lines.
347 * @param {number} opt_from_line The first line (zero bound) in the slice.
348 * Default is 0
349 * @param {number} opt_to_column The last line (zero bound) in the slice (non
350 * inclusive). Default is the number of lines in the script
351 * @return {SourceSlice} The source slice or null of the parameters where
352 * invalid
353 */
354Script.prototype.sourceSlice = function (opt_from_line, opt_to_line) {
355 var from_line = IS_UNDEFINED(opt_from_line) ? this.line_offset : opt_from_line;
356 var to_line = IS_UNDEFINED(opt_to_line) ? this.line_offset + this.lineCount() : opt_to_line
357
358 // Adjust according to the offset within the resource.
359 from_line -= this.line_offset;
360 to_line -= this.line_offset;
361 if (from_line < 0) from_line = 0;
362 if (to_line > this.lineCount()) to_line = this.lineCount();
363
364 // Check parameters.
365 if (from_line >= this.lineCount() ||
366 to_line < 0 ||
367 from_line > to_line) {
368 return null;
369 }
370
371 var from_position = from_line == 0 ? 0 : this.line_ends[from_line - 1] + 1;
372 var to_position = to_line == 0 ? 0 : this.line_ends[to_line - 1] + 1;
373
374 // Return a source slice with line numbers re-adjusted to the resource.
375 return new SourceSlice(this, from_line + this.line_offset, to_line + this.line_offset,
376 from_position, to_position);
377}
378
379
380Script.prototype.sourceLine = function (opt_line) {
381 // Default is the first line in the script. Lines in the script are relative
382 // to the offset within the resource.
383 var line = 0;
384 if (!IS_UNDEFINED(opt_line)) {
385 line = opt_line - this.line_offset;
386 }
387
388 // Check parameter.
389 if (line < 0 || this.lineCount() <= line) {
390 return null;
391 }
392
393 // Return the source line.
394 var start = line == 0 ? 0 : this.line_ends[line - 1] + 1;
395 var end = this.line_ends[line];
396 return StringSubstring.call(this.source, start, end);
397}
398
399
400/**
401 * Returns the number of source lines.
402 * @return {number}
403 * Number of source lines.
404 */
405Script.prototype.lineCount = function() {
406 // Return number of source lines.
407 return this.line_ends.length;
408};
409
410
411/**
412 * Class for source location. A source location is a position within some
413 * source with the following properties:
414 * script : script object for the source
415 * line : source line number
416 * column : source column within the line
417 * position : position within the source
418 * start : position of start of source context (inclusive)
419 * end : position of end of source context (not inclusive)
420 * Source text for the source context is the character interval [start, end[. In
421 * most cases end will point to a newline character. It might point just past
422 * the final position of the source if the last source line does not end with a
423 * newline character.
424 * @param {Script} script The Script object for which this is a location
425 * @param {number} position Source position for the location
426 * @param {number} line The line number for the location
427 * @param {number} column The column within the line for the location
428 * @param {number} start Source position for start of source context
429 * @param {number} end Source position for end of source context
430 * @constructor
431 */
432function SourceLocation(script, position, line, column, start, end) {
433 this.script = script;
434 this.position = position;
435 this.line = line;
436 this.column = column;
437 this.start = start;
438 this.end = end;
439}
440
441
442const kLineLengthLimit = 78;
443
444/**
445 * Restrict source location start and end positions to make the source slice
446 * no more that a certain number of characters wide.
447 * @param {number} opt_limit The with limit of the source text with a default
448 * of 78
449 * @param {number} opt_before The number of characters to prefer before the
450 * position with a default value of 10 less that the limit
451 */
452SourceLocation.prototype.restrict = function (opt_limit, opt_before) {
453 // Find the actual limit to use.
454 var limit;
455 var before;
456 if (!IS_UNDEFINED(opt_limit)) {
457 limit = opt_limit;
458 } else {
459 limit = kLineLengthLimit;
460 }
461 if (!IS_UNDEFINED(opt_before)) {
462 before = opt_before;
463 } else {
464 // If no before is specified center for small limits and perfer more source
465 // before the the position that after for longer limits.
466 if (limit <= 20) {
467 before = $floor(limit / 2);
468 } else {
469 before = limit - 10;
470 }
471 }
472 if (before >= limit) {
473 before = limit - 1;
474 }
475
476 // If the [start, end[ interval is too big we restrict
477 // it in one or both ends. We make sure to always produce
478 // restricted intervals of maximum allowed size.
479 if (this.end - this.start > limit) {
480 var start_limit = this.position - before;
481 var end_limit = this.position + limit - before;
482 if (this.start < start_limit && end_limit < this.end) {
483 this.start = start_limit;
484 this.end = end_limit;
485 } else if (this.start < start_limit) {
486 this.start = this.end - limit;
487 } else {
488 this.end = this.start + limit;
489 }
490 }
491};
492
493
494/**
495 * Get the source text for a SourceLocation
496 * @return {String}
497 * Source text for this location.
498 */
499SourceLocation.prototype.sourceText = function () {
500 return StringSubstring.call(this.script.source, this.start, this.end);
501};
502
503
504/**
505 * Class for a source slice. A source slice is a part of a script source with
506 * the following properties:
507 * script : script object for the source
508 * from_line : line number for the first line in the slice
509 * to_line : source line number for the last line in the slice
510 * from_position : position of the first character in the slice
511 * to_position : position of the last character in the slice
512 * The to_line and to_position are not included in the slice, that is the lines
513 * in the slice are [from_line, to_line[. Likewise the characters in the slice
514 * are [from_position, to_position[.
515 * @param {Script} script The Script object for the source slice
516 * @param {number} from_line
517 * @param {number} to_line
518 * @param {number} from_position
519 * @param {number} to_position
520 * @constructor
521 */
522function SourceSlice(script, from_line, to_line, from_position, to_position) {
523 this.script = script;
524 this.from_line = from_line;
525 this.to_line = to_line;
526 this.from_position = from_position;
527 this.to_position = to_position;
528}
529
530
531/**
532 * Get the source text for a SourceSlice
533 * @return {String} Source text for this slice. The last line will include
534 * the line terminating characters (if any)
535 */
536SourceSlice.prototype.sourceText = function () {
537 return StringSubstring.call(this.script.source, this.from_position, this.to_position);
538};
539
540
541// Returns the offset of the given position within the containing
542// line.
543function GetPositionInLine(message) {
544 var location = message.script.locationFromPosition(message.startPos, false);
545 if (location == null) return -1;
546 location.restrict();
547 return message.startPos - location.start;
548}
549
550
551function ErrorMessage(type, args, startPos, endPos, script, stackTrace) {
552 this.startPos = startPos;
553 this.endPos = endPos;
554 this.type = type;
555 this.args = args;
556 this.script = script;
557 this.stackTrace = stackTrace;
558}
559
560
561function MakeMessage(type, args, startPos, endPos, script, stackTrace) {
562 return new ErrorMessage(type, args, startPos, endPos, script, stackTrace);
563}
564
565
566function GetStackTraceLine(recv, fun, pos, isGlobal) {
567 return FormatSourcePosition(new CallSite(recv, fun, pos));
568}
569
570// ----------------------------------------------------------------------------
571// Error implementation
572
573// Defines accessors for a property that is calculated the first time
574// the property is read.
575function DefineOneShotAccessor(obj, name, fun) {
576 // Note that the accessors consistently operate on 'obj', not 'this'.
577 // Since the object may occur in someone else's prototype chain we
578 // can't rely on 'this' being the same as 'obj'.
579 var hasBeenSet = false;
580 var value;
581 obj.__defineGetter__(name, function () {
582 if (hasBeenSet) {
583 return value;
584 }
585 hasBeenSet = true;
586 value = fun(obj);
587 return value;
588 });
589 obj.__defineSetter__(name, function (v) {
590 hasBeenSet = true;
591 value = v;
592 });
593}
594
595function CallSite(receiver, fun, pos) {
596 this.receiver = receiver;
597 this.fun = fun;
598 this.pos = pos;
599}
600
601CallSite.prototype.getThis = function () {
602 return this.receiver;
603};
604
605CallSite.prototype.getTypeName = function () {
606 var constructor = this.receiver.constructor;
607 if (!constructor)
608 return $Object.prototype.toString.call(this.receiver);
609 var constructorName = constructor.name;
610 if (!constructorName)
611 return $Object.prototype.toString.call(this.receiver);
612 return constructorName;
613};
614
615CallSite.prototype.isToplevel = function () {
616 if (this.receiver == null)
617 return true;
618 return IS_GLOBAL(this.receiver);
619};
620
621CallSite.prototype.isEval = function () {
622 var script = %FunctionGetScript(this.fun);
623 return script && script.compilation_type == 1;
624};
625
626CallSite.prototype.getEvalOrigin = function () {
627 var script = %FunctionGetScript(this.fun);
628 if (!script || script.compilation_type != 1)
629 return null;
630 return new CallSite(null, script.eval_from_function,
631 script.eval_from_position);
632};
633
634CallSite.prototype.getFunction = function () {
635 return this.fun;
636};
637
638CallSite.prototype.getFunctionName = function () {
639 // See if the function knows its own name
640 var name = this.fun.name;
641 if (name) {
642 return name;
643 } else {
644 return %FunctionGetInferredName(this.fun);
645 }
646 // Maybe this is an evaluation?
647 var script = %FunctionGetScript(this.fun);
648 if (script && script.compilation_type == 1)
649 return "eval";
650 return null;
651};
652
653CallSite.prototype.getMethodName = function () {
654 // See if we can find a unique property on the receiver that holds
655 // this function.
656 var ownName = this.fun.name;
657 if (ownName && this.receiver && this.receiver[ownName] === this.fun)
658 // To handle DontEnum properties we guess that the method has
659 // the same name as the function.
660 return ownName;
661 var name = null;
662 for (var prop in this.receiver) {
663 if (this.receiver[prop] === this.fun) {
664 // If we find more than one match bail out to avoid confusion
665 if (name)
666 return null;
667 name = prop;
668 }
669 }
670 if (name)
671 return name;
672 return null;
673};
674
675CallSite.prototype.getFileName = function () {
676 var script = %FunctionGetScript(this.fun);
677 return script ? script.name : null;
678};
679
680CallSite.prototype.getLineNumber = function () {
681 if (this.pos == -1)
682 return null;
683 var script = %FunctionGetScript(this.fun);
684 var location = null;
685 if (script) {
686 location = script.locationFromPosition(this.pos, true);
687 }
688 return location ? location.line + 1 : null;
689};
690
691CallSite.prototype.getColumnNumber = function () {
692 if (this.pos == -1)
693 return null;
694 var script = %FunctionGetScript(this.fun);
695 var location = null;
696 if (script) {
697 location = script.locationFromPosition(this.pos, true);
698 }
699 return location ? location.column : null;
700};
701
702CallSite.prototype.isNative = function () {
703 var script = %FunctionGetScript(this.fun);
704 return script ? (script.type == 0) : false;
705};
706
707CallSite.prototype.getPosition = function () {
708 return this.pos;
709};
710
711CallSite.prototype.isConstructor = function () {
712 var constructor = this.receiver ? this.receiver.constructor : null;
713 if (!constructor)
714 return false;
715 return this.fun === constructor;
716};
717
718function FormatSourcePosition(frame) {
719 var fileLocation = "";
720 if (frame.isNative()) {
721 fileLocation = "native";
722 } else if (frame.isEval()) {
723 fileLocation = "eval at " + FormatSourcePosition(frame.getEvalOrigin());
724 } else {
725 var fileName = frame.getFileName();
726 if (fileName) {
727 fileLocation += fileName;
728 var lineNumber = frame.getLineNumber();
729 if (lineNumber != null) {
730 fileLocation += ":" + lineNumber;
731 var columnNumber = frame.getColumnNumber();
732 if (columnNumber) {
733 fileLocation += ":" + columnNumber;
734 }
735 }
736 }
737 }
738 if (!fileLocation) {
739 fileLocation = "unknown source";
740 }
741 var line = "";
742 var functionName = frame.getFunction().name;
743 var methodName = frame.getMethodName();
744 var addPrefix = true;
745 var isConstructor = frame.isConstructor();
746 var isMethodCall = !(frame.isToplevel() || isConstructor);
747 if (isMethodCall) {
748 line += frame.getTypeName() + ".";
749 if (functionName) {
750 line += functionName;
751 if (methodName && (methodName != functionName)) {
752 line += " [as " + methodName + "]";
753 }
754 } else {
755 line += methodName || "<anonymous>";
756 }
757 } else if (isConstructor) {
758 line += "new " + (functionName || "<anonymous>");
759 } else if (functionName) {
760 line += functionName;
761 } else {
762 line += fileLocation;
763 addPrefix = false;
764 }
765 if (addPrefix) {
766 line += " (" + fileLocation + ")";
767 }
768 return line;
769}
770
771function FormatStackTrace(error, frames) {
772 var lines = [];
773 try {
774 lines.push(error.toString());
775 } catch (e) {
776 try {
777 lines.push("<error: " + e + ">");
778 } catch (ee) {
779 lines.push("<error>");
780 }
781 }
782 for (var i = 0; i < frames.length; i++) {
783 var frame = frames[i];
784 var line;
785 try {
786 line = FormatSourcePosition(frame);
787 } catch (e) {
788 try {
789 line = "<error: " + e + ">";
790 } catch (ee) {
791 // Any code that reaches this point is seriously nasty!
792 line = "<error>";
793 }
794 }
795 lines.push(" at " + line);
796 }
797 return lines.join("\n");
798}
799
800function FormatRawStackTrace(error, raw_stack) {
801 var frames = [ ];
802 for (var i = 0; i < raw_stack.length; i += 3) {
803 var recv = raw_stack[i];
804 var fun = raw_stack[i+1];
805 var pc = raw_stack[i+2];
806 var pos = %FunctionGetPositionForOffset(fun, pc);
807 frames.push(new CallSite(recv, fun, pos));
808 }
809 if (IS_FUNCTION($Error.prepareStackTrace)) {
810 return $Error.prepareStackTrace(error, frames);
811 } else {
812 return FormatStackTrace(error, frames);
813 }
814}
815
816function DefineError(f) {
817 // Store the error function in both the global object
818 // and the runtime object. The function is fetched
819 // from the runtime object when throwing errors from
820 // within the runtime system to avoid strange side
821 // effects when overwriting the error functions from
822 // user code.
823 var name = f.name;
824 %SetProperty(global, name, f, DONT_ENUM);
825 this['$' + name] = f;
826 // Configure the error function.
827 if (name == 'Error') {
828 // The prototype of the Error object must itself be an error.
829 // However, it can't be an instance of the Error object because
830 // it hasn't been properly configured yet. Instead we create a
831 // special not-a-true-error-but-close-enough object.
832 function ErrorPrototype() {}
833 %FunctionSetPrototype(ErrorPrototype, $Object.prototype);
834 %FunctionSetInstanceClassName(ErrorPrototype, 'Error');
835 %FunctionSetPrototype(f, new ErrorPrototype());
836 } else {
837 %FunctionSetPrototype(f, new $Error());
838 }
839 %FunctionSetInstanceClassName(f, 'Error');
840 %SetProperty(f.prototype, 'constructor', f, DONT_ENUM);
841 f.prototype.name = name;
842 %SetCode(f, function(m) {
843 if (%_IsConstructCall()) {
844 if (m === kAddMessageAccessorsMarker) {
845 DefineOneShotAccessor(this, 'message', function (obj) {
846 return FormatMessage({type: obj.type, args: obj.arguments});
847 });
848 } else if (!IS_UNDEFINED(m)) {
849 this.message = ToString(m);
850 }
851 captureStackTrace(this, f);
852 } else {
853 return new f(m);
854 }
855 });
856}
857
858function captureStackTrace(obj, cons_opt) {
859 var stackTraceLimit = $Error.stackTraceLimit;
860 if (!stackTraceLimit) return;
861 if (stackTraceLimit < 0 || stackTraceLimit > 10000)
862 stackTraceLimit = 10000;
863 var raw_stack = %CollectStackTrace(cons_opt ? cons_opt : captureStackTrace,
864 stackTraceLimit);
865 DefineOneShotAccessor(obj, 'stack', function (obj) {
866 return FormatRawStackTrace(obj, raw_stack);
867 });
868};
869
870$Math.__proto__ = global.Object.prototype;
871
872DefineError(function Error() { });
873DefineError(function TypeError() { });
874DefineError(function RangeError() { });
875DefineError(function SyntaxError() { });
876DefineError(function ReferenceError() { });
877DefineError(function EvalError() { });
878DefineError(function URIError() { });
879
880$Error.captureStackTrace = captureStackTrace;
881
882// Setup extra properties of the Error.prototype object.
883$Error.prototype.message = '';
884
885%SetProperty($Error.prototype, 'toString', function toString() {
886 var type = this.type;
887 if (type && !this.hasOwnProperty("message")) {
888 return this.name + ": " + FormatMessage({ type: type, args: this.arguments });
889 }
890 var message = this.message;
891 return this.name + (message ? (": " + message) : "");
892}, DONT_ENUM);
893
894
895// Boilerplate for exceptions for stack overflows. Used from
896// Top::StackOverflow().
897const kStackOverflowBoilerplate = MakeRangeError('stack_overflow', []);