blob: 1e5053d7eb28f046392a9772d5ff112ed4a3fba3 [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;
Steve Blockd0582a62009-12-15 09:54:21 +0000241 var line_ends = this.line_ends;
Steve Blocka7e24c12009-10-30 11:49:00 +0000242
243 // We'll never find invalid positions so bail right away.
Steve Blockd0582a62009-12-15 09:54:21 +0000244 if (position > line_ends[upper]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000245 return -1;
246 }
247
248 // This means we don't have to safe-guard indexing line_ends[i - 1].
Steve Blockd0582a62009-12-15 09:54:21 +0000249 if (position <= line_ends[0]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000250 return 0;
251 }
252
253 // Binary search to find line # from position range.
254 while (upper >= 1) {
255 var i = (lower + upper) >> 1;
256
Steve Blockd0582a62009-12-15 09:54:21 +0000257 if (position > line_ends[i]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000258 lower = i + 1;
Steve Blockd0582a62009-12-15 09:54:21 +0000259 } else if (position <= line_ends[i - 1]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000260 upper = i - 1;
261 } else {
262 return i;
263 }
264 }
265 return -1;
266}
267
268/**
269 * Get information on a specific source position.
270 * @param {number} position The source position
271 * @param {boolean} include_resource_offset Set to true to have the resource
272 * offset added to the location
273 * @return {SourceLocation}
274 * If line is negative or not in the source null is returned.
275 */
276Script.prototype.locationFromPosition = function (position,
277 include_resource_offset) {
278 var line = this.lineFromPosition(position);
279 if (line == -1) return null;
280
281 // Determine start, end and column.
Steve Blockd0582a62009-12-15 09:54:21 +0000282 var line_ends = this.line_ends;
283 var start = line == 0 ? 0 : line_ends[line - 1] + 1;
284 var end = line_ends[line];
Steve Blocka7e24c12009-10-30 11:49:00 +0000285 if (end > 0 && StringCharAt.call(this.source, end - 1) == '\r') end--;
286 var column = position - start;
287
288 // Adjust according to the offset within the resource.
289 if (include_resource_offset) {
290 line += this.line_offset;
291 if (line == this.line_offset) {
292 column += this.column_offset;
293 }
294 }
295
296 return new SourceLocation(this, position, line, column, start, end);
297};
298
299
300/**
301 * Get information on a specific source line and column possibly offset by a
302 * fixed source position. This function is used to find a source position from
303 * a line and column position. The fixed source position offset is typically
304 * used to find a source position in a function based on a line and column in
305 * the source for the function alone. The offset passed will then be the
306 * start position of the source for the function within the full script source.
307 * @param {number} opt_line The line within the source. Default value is 0
308 * @param {number} opt_column The column in within the line. Default value is 0
309 * @param {number} opt_offset_position The offset from the begining of the
310 * source from where the line and column calculation starts. Default value is 0
311 * @return {SourceLocation}
312 * If line is negative or not in the source null is returned.
313 */
314Script.prototype.locationFromLine = function (opt_line, opt_column, opt_offset_position) {
315 // Default is the first line in the script. Lines in the script is relative
316 // to the offset within the resource.
317 var line = 0;
318 if (!IS_UNDEFINED(opt_line)) {
319 line = opt_line - this.line_offset;
320 }
321
322 // Default is first column. If on the first line add the offset within the
323 // resource.
324 var column = opt_column || 0;
325 if (line == 0) {
326 column -= this.column_offset
327 }
328
329 var offset_position = opt_offset_position || 0;
330 if (line < 0 || column < 0 || offset_position < 0) return null;
331 if (line == 0) {
332 return this.locationFromPosition(offset_position + column, false);
333 } else {
334 // Find the line where the offset position is located.
335 var offset_line = this.lineFromPosition(offset_position);
336
337 if (offset_line == -1 || offset_line + line >= this.lineCount()) {
338 return null;
339 }
340
341 return this.locationFromPosition(this.line_ends[offset_line + line - 1] + 1 + column); // line > 0 here.
342 }
343}
344
345
346/**
347 * Get a slice of source code from the script. The boundaries for the slice is
348 * specified in lines.
349 * @param {number} opt_from_line The first line (zero bound) in the slice.
350 * Default is 0
351 * @param {number} opt_to_column The last line (zero bound) in the slice (non
352 * inclusive). Default is the number of lines in the script
353 * @return {SourceSlice} The source slice or null of the parameters where
354 * invalid
355 */
356Script.prototype.sourceSlice = function (opt_from_line, opt_to_line) {
357 var from_line = IS_UNDEFINED(opt_from_line) ? this.line_offset : opt_from_line;
358 var to_line = IS_UNDEFINED(opt_to_line) ? this.line_offset + this.lineCount() : opt_to_line
359
360 // Adjust according to the offset within the resource.
361 from_line -= this.line_offset;
362 to_line -= this.line_offset;
363 if (from_line < 0) from_line = 0;
364 if (to_line > this.lineCount()) to_line = this.lineCount();
365
366 // Check parameters.
367 if (from_line >= this.lineCount() ||
368 to_line < 0 ||
369 from_line > to_line) {
370 return null;
371 }
372
Steve Blockd0582a62009-12-15 09:54:21 +0000373 var line_ends = this.line_ends;
374 var from_position = from_line == 0 ? 0 : line_ends[from_line - 1] + 1;
375 var to_position = to_line == 0 ? 0 : line_ends[to_line - 1] + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +0000376
377 // Return a source slice with line numbers re-adjusted to the resource.
378 return new SourceSlice(this, from_line + this.line_offset, to_line + this.line_offset,
379 from_position, to_position);
380}
381
382
383Script.prototype.sourceLine = function (opt_line) {
384 // Default is the first line in the script. Lines in the script are relative
385 // to the offset within the resource.
386 var line = 0;
387 if (!IS_UNDEFINED(opt_line)) {
388 line = opt_line - this.line_offset;
389 }
390
391 // Check parameter.
392 if (line < 0 || this.lineCount() <= line) {
393 return null;
394 }
395
396 // Return the source line.
Steve Blockd0582a62009-12-15 09:54:21 +0000397 var line_ends = this.line_ends;
398 var start = line == 0 ? 0 : line_ends[line - 1] + 1;
399 var end = line_ends[line];
Steve Blocka7e24c12009-10-30 11:49:00 +0000400 return StringSubstring.call(this.source, start, end);
401}
402
403
404/**
405 * Returns the number of source lines.
406 * @return {number}
407 * Number of source lines.
408 */
409Script.prototype.lineCount = function() {
410 // Return number of source lines.
411 return this.line_ends.length;
412};
413
414
415/**
416 * Class for source location. A source location is a position within some
417 * source with the following properties:
418 * script : script object for the source
419 * line : source line number
420 * column : source column within the line
421 * position : position within the source
422 * start : position of start of source context (inclusive)
423 * end : position of end of source context (not inclusive)
424 * Source text for the source context is the character interval [start, end[. In
425 * most cases end will point to a newline character. It might point just past
426 * the final position of the source if the last source line does not end with a
427 * newline character.
428 * @param {Script} script The Script object for which this is a location
429 * @param {number} position Source position for the location
430 * @param {number} line The line number for the location
431 * @param {number} column The column within the line for the location
432 * @param {number} start Source position for start of source context
433 * @param {number} end Source position for end of source context
434 * @constructor
435 */
436function SourceLocation(script, position, line, column, start, end) {
437 this.script = script;
438 this.position = position;
439 this.line = line;
440 this.column = column;
441 this.start = start;
442 this.end = end;
443}
444
445
446const kLineLengthLimit = 78;
447
448/**
449 * Restrict source location start and end positions to make the source slice
450 * no more that a certain number of characters wide.
451 * @param {number} opt_limit The with limit of the source text with a default
452 * of 78
453 * @param {number} opt_before The number of characters to prefer before the
454 * position with a default value of 10 less that the limit
455 */
456SourceLocation.prototype.restrict = function (opt_limit, opt_before) {
457 // Find the actual limit to use.
458 var limit;
459 var before;
460 if (!IS_UNDEFINED(opt_limit)) {
461 limit = opt_limit;
462 } else {
463 limit = kLineLengthLimit;
464 }
465 if (!IS_UNDEFINED(opt_before)) {
466 before = opt_before;
467 } else {
468 // If no before is specified center for small limits and perfer more source
469 // before the the position that after for longer limits.
470 if (limit <= 20) {
471 before = $floor(limit / 2);
472 } else {
473 before = limit - 10;
474 }
475 }
476 if (before >= limit) {
477 before = limit - 1;
478 }
479
480 // If the [start, end[ interval is too big we restrict
481 // it in one or both ends. We make sure to always produce
482 // restricted intervals of maximum allowed size.
483 if (this.end - this.start > limit) {
484 var start_limit = this.position - before;
485 var end_limit = this.position + limit - before;
486 if (this.start < start_limit && end_limit < this.end) {
487 this.start = start_limit;
488 this.end = end_limit;
489 } else if (this.start < start_limit) {
490 this.start = this.end - limit;
491 } else {
492 this.end = this.start + limit;
493 }
494 }
495};
496
497
498/**
499 * Get the source text for a SourceLocation
500 * @return {String}
501 * Source text for this location.
502 */
503SourceLocation.prototype.sourceText = function () {
504 return StringSubstring.call(this.script.source, this.start, this.end);
505};
506
507
508/**
509 * Class for a source slice. A source slice is a part of a script source with
510 * the following properties:
511 * script : script object for the source
512 * from_line : line number for the first line in the slice
513 * to_line : source line number for the last line in the slice
514 * from_position : position of the first character in the slice
515 * to_position : position of the last character in the slice
516 * The to_line and to_position are not included in the slice, that is the lines
517 * in the slice are [from_line, to_line[. Likewise the characters in the slice
518 * are [from_position, to_position[.
519 * @param {Script} script The Script object for the source slice
520 * @param {number} from_line
521 * @param {number} to_line
522 * @param {number} from_position
523 * @param {number} to_position
524 * @constructor
525 */
526function SourceSlice(script, from_line, to_line, from_position, to_position) {
527 this.script = script;
528 this.from_line = from_line;
529 this.to_line = to_line;
530 this.from_position = from_position;
531 this.to_position = to_position;
532}
533
534
535/**
536 * Get the source text for a SourceSlice
537 * @return {String} Source text for this slice. The last line will include
538 * the line terminating characters (if any)
539 */
540SourceSlice.prototype.sourceText = function () {
541 return StringSubstring.call(this.script.source, this.from_position, this.to_position);
542};
543
544
545// Returns the offset of the given position within the containing
546// line.
547function GetPositionInLine(message) {
548 var location = message.script.locationFromPosition(message.startPos, false);
549 if (location == null) return -1;
550 location.restrict();
551 return message.startPos - location.start;
552}
553
554
555function ErrorMessage(type, args, startPos, endPos, script, stackTrace) {
556 this.startPos = startPos;
557 this.endPos = endPos;
558 this.type = type;
559 this.args = args;
560 this.script = script;
561 this.stackTrace = stackTrace;
562}
563
564
565function MakeMessage(type, args, startPos, endPos, script, stackTrace) {
566 return new ErrorMessage(type, args, startPos, endPos, script, stackTrace);
567}
568
569
570function GetStackTraceLine(recv, fun, pos, isGlobal) {
571 return FormatSourcePosition(new CallSite(recv, fun, pos));
572}
573
574// ----------------------------------------------------------------------------
575// Error implementation
576
577// Defines accessors for a property that is calculated the first time
578// the property is read.
579function DefineOneShotAccessor(obj, name, fun) {
580 // Note that the accessors consistently operate on 'obj', not 'this'.
581 // Since the object may occur in someone else's prototype chain we
582 // can't rely on 'this' being the same as 'obj'.
583 var hasBeenSet = false;
584 var value;
585 obj.__defineGetter__(name, function () {
586 if (hasBeenSet) {
587 return value;
588 }
589 hasBeenSet = true;
590 value = fun(obj);
591 return value;
592 });
593 obj.__defineSetter__(name, function (v) {
594 hasBeenSet = true;
595 value = v;
596 });
597}
598
599function CallSite(receiver, fun, pos) {
600 this.receiver = receiver;
601 this.fun = fun;
602 this.pos = pos;
603}
604
605CallSite.prototype.getThis = function () {
606 return this.receiver;
607};
608
609CallSite.prototype.getTypeName = function () {
610 var constructor = this.receiver.constructor;
611 if (!constructor)
612 return $Object.prototype.toString.call(this.receiver);
613 var constructorName = constructor.name;
614 if (!constructorName)
615 return $Object.prototype.toString.call(this.receiver);
616 return constructorName;
617};
618
619CallSite.prototype.isToplevel = function () {
620 if (this.receiver == null)
621 return true;
622 return IS_GLOBAL(this.receiver);
623};
624
625CallSite.prototype.isEval = function () {
626 var script = %FunctionGetScript(this.fun);
627 return script && script.compilation_type == 1;
628};
629
630CallSite.prototype.getEvalOrigin = function () {
631 var script = %FunctionGetScript(this.fun);
Steve Blockd0582a62009-12-15 09:54:21 +0000632 return FormatEvalOrigin(script);
Steve Blocka7e24c12009-10-30 11:49:00 +0000633};
634
635CallSite.prototype.getFunction = function () {
636 return this.fun;
637};
638
639CallSite.prototype.getFunctionName = function () {
640 // See if the function knows its own name
641 var name = this.fun.name;
642 if (name) {
643 return name;
644 } else {
645 return %FunctionGetInferredName(this.fun);
646 }
647 // Maybe this is an evaluation?
648 var script = %FunctionGetScript(this.fun);
649 if (script && script.compilation_type == 1)
650 return "eval";
651 return null;
652};
653
654CallSite.prototype.getMethodName = function () {
655 // See if we can find a unique property on the receiver that holds
656 // this function.
657 var ownName = this.fun.name;
658 if (ownName && this.receiver && this.receiver[ownName] === this.fun)
659 // To handle DontEnum properties we guess that the method has
660 // the same name as the function.
661 return ownName;
662 var name = null;
663 for (var prop in this.receiver) {
664 if (this.receiver[prop] === this.fun) {
665 // If we find more than one match bail out to avoid confusion
666 if (name)
667 return null;
668 name = prop;
669 }
670 }
671 if (name)
672 return name;
673 return null;
674};
675
676CallSite.prototype.getFileName = function () {
677 var script = %FunctionGetScript(this.fun);
678 return script ? script.name : null;
679};
680
681CallSite.prototype.getLineNumber = function () {
682 if (this.pos == -1)
683 return null;
684 var script = %FunctionGetScript(this.fun);
685 var location = null;
686 if (script) {
687 location = script.locationFromPosition(this.pos, true);
688 }
689 return location ? location.line + 1 : null;
690};
691
692CallSite.prototype.getColumnNumber = function () {
693 if (this.pos == -1)
694 return null;
695 var script = %FunctionGetScript(this.fun);
696 var location = null;
697 if (script) {
698 location = script.locationFromPosition(this.pos, true);
699 }
Steve Blockd0582a62009-12-15 09:54:21 +0000700 return location ? location.column + 1: null;
Steve Blocka7e24c12009-10-30 11:49:00 +0000701};
702
703CallSite.prototype.isNative = function () {
704 var script = %FunctionGetScript(this.fun);
705 return script ? (script.type == 0) : false;
706};
707
708CallSite.prototype.getPosition = function () {
709 return this.pos;
710};
711
712CallSite.prototype.isConstructor = function () {
713 var constructor = this.receiver ? this.receiver.constructor : null;
714 if (!constructor)
715 return false;
716 return this.fun === constructor;
717};
718
Steve Blockd0582a62009-12-15 09:54:21 +0000719function FormatEvalOrigin(script) {
720 var eval_origin = "";
721 if (script.eval_from_function_name) {
722 eval_origin += script.eval_from_function_name;
723 } else {
724 eval_origin += "<anonymous>";
725 }
726
727 var eval_from_script = script.eval_from_script;
728 if (eval_from_script) {
729 if (eval_from_script.compilation_type == 1) {
730 // eval script originated from another eval.
731 eval_origin += " (eval at " + FormatEvalOrigin(eval_from_script) + ")";
732 } else {
733 // eval script originated from "real" scource.
734 if (eval_from_script.name) {
735 eval_origin += " (" + eval_from_script.name;
736 var location = eval_from_script.locationFromPosition(script.eval_from_script_position, true);
737 if (location) {
738 eval_origin += ":" + (location.line + 1);
739 eval_origin += ":" + (location.column + 1);
740 }
741 eval_origin += ")"
742 } else {
743 eval_origin += " (unknown source)";
744 }
745 }
746 }
747
748 return eval_origin;
749};
750
Steve Blocka7e24c12009-10-30 11:49:00 +0000751function FormatSourcePosition(frame) {
752 var fileLocation = "";
753 if (frame.isNative()) {
754 fileLocation = "native";
755 } else if (frame.isEval()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000756 fileLocation = "eval at " + frame.getEvalOrigin();
Steve Blocka7e24c12009-10-30 11:49:00 +0000757 } else {
758 var fileName = frame.getFileName();
759 if (fileName) {
760 fileLocation += fileName;
761 var lineNumber = frame.getLineNumber();
762 if (lineNumber != null) {
763 fileLocation += ":" + lineNumber;
764 var columnNumber = frame.getColumnNumber();
765 if (columnNumber) {
766 fileLocation += ":" + columnNumber;
767 }
768 }
769 }
770 }
771 if (!fileLocation) {
772 fileLocation = "unknown source";
773 }
774 var line = "";
775 var functionName = frame.getFunction().name;
776 var methodName = frame.getMethodName();
777 var addPrefix = true;
778 var isConstructor = frame.isConstructor();
779 var isMethodCall = !(frame.isToplevel() || isConstructor);
780 if (isMethodCall) {
781 line += frame.getTypeName() + ".";
782 if (functionName) {
783 line += functionName;
784 if (methodName && (methodName != functionName)) {
785 line += " [as " + methodName + "]";
786 }
787 } else {
788 line += methodName || "<anonymous>";
789 }
790 } else if (isConstructor) {
791 line += "new " + (functionName || "<anonymous>");
792 } else if (functionName) {
793 line += functionName;
794 } else {
795 line += fileLocation;
796 addPrefix = false;
797 }
798 if (addPrefix) {
799 line += " (" + fileLocation + ")";
800 }
801 return line;
802}
803
804function FormatStackTrace(error, frames) {
805 var lines = [];
806 try {
807 lines.push(error.toString());
808 } catch (e) {
809 try {
810 lines.push("<error: " + e + ">");
811 } catch (ee) {
812 lines.push("<error>");
813 }
814 }
815 for (var i = 0; i < frames.length; i++) {
816 var frame = frames[i];
817 var line;
818 try {
819 line = FormatSourcePosition(frame);
820 } catch (e) {
821 try {
822 line = "<error: " + e + ">";
823 } catch (ee) {
824 // Any code that reaches this point is seriously nasty!
825 line = "<error>";
826 }
827 }
828 lines.push(" at " + line);
829 }
830 return lines.join("\n");
831}
832
833function FormatRawStackTrace(error, raw_stack) {
834 var frames = [ ];
835 for (var i = 0; i < raw_stack.length; i += 3) {
836 var recv = raw_stack[i];
837 var fun = raw_stack[i+1];
838 var pc = raw_stack[i+2];
839 var pos = %FunctionGetPositionForOffset(fun, pc);
840 frames.push(new CallSite(recv, fun, pos));
841 }
842 if (IS_FUNCTION($Error.prepareStackTrace)) {
843 return $Error.prepareStackTrace(error, frames);
844 } else {
845 return FormatStackTrace(error, frames);
846 }
847}
848
849function DefineError(f) {
850 // Store the error function in both the global object
851 // and the runtime object. The function is fetched
852 // from the runtime object when throwing errors from
853 // within the runtime system to avoid strange side
854 // effects when overwriting the error functions from
855 // user code.
856 var name = f.name;
857 %SetProperty(global, name, f, DONT_ENUM);
858 this['$' + name] = f;
859 // Configure the error function.
860 if (name == 'Error') {
861 // The prototype of the Error object must itself be an error.
862 // However, it can't be an instance of the Error object because
863 // it hasn't been properly configured yet. Instead we create a
864 // special not-a-true-error-but-close-enough object.
865 function ErrorPrototype() {}
866 %FunctionSetPrototype(ErrorPrototype, $Object.prototype);
867 %FunctionSetInstanceClassName(ErrorPrototype, 'Error');
868 %FunctionSetPrototype(f, new ErrorPrototype());
869 } else {
870 %FunctionSetPrototype(f, new $Error());
871 }
872 %FunctionSetInstanceClassName(f, 'Error');
873 %SetProperty(f.prototype, 'constructor', f, DONT_ENUM);
874 f.prototype.name = name;
875 %SetCode(f, function(m) {
876 if (%_IsConstructCall()) {
877 if (m === kAddMessageAccessorsMarker) {
878 DefineOneShotAccessor(this, 'message', function (obj) {
879 return FormatMessage({type: obj.type, args: obj.arguments});
880 });
881 } else if (!IS_UNDEFINED(m)) {
882 this.message = ToString(m);
883 }
884 captureStackTrace(this, f);
885 } else {
886 return new f(m);
887 }
888 });
889}
890
891function captureStackTrace(obj, cons_opt) {
892 var stackTraceLimit = $Error.stackTraceLimit;
893 if (!stackTraceLimit) return;
894 if (stackTraceLimit < 0 || stackTraceLimit > 10000)
895 stackTraceLimit = 10000;
896 var raw_stack = %CollectStackTrace(cons_opt ? cons_opt : captureStackTrace,
897 stackTraceLimit);
898 DefineOneShotAccessor(obj, 'stack', function (obj) {
899 return FormatRawStackTrace(obj, raw_stack);
900 });
901};
902
903$Math.__proto__ = global.Object.prototype;
904
905DefineError(function Error() { });
906DefineError(function TypeError() { });
907DefineError(function RangeError() { });
908DefineError(function SyntaxError() { });
909DefineError(function ReferenceError() { });
910DefineError(function EvalError() { });
911DefineError(function URIError() { });
912
913$Error.captureStackTrace = captureStackTrace;
914
915// Setup extra properties of the Error.prototype object.
916$Error.prototype.message = '';
917
918%SetProperty($Error.prototype, 'toString', function toString() {
919 var type = this.type;
920 if (type && !this.hasOwnProperty("message")) {
921 return this.name + ": " + FormatMessage({ type: type, args: this.arguments });
922 }
923 var message = this.message;
924 return this.name + (message ? (": " + message) : "");
925}, DONT_ENUM);
926
927
928// Boilerplate for exceptions for stack overflows. Used from
929// Top::StackOverflow().
930const kStackOverflowBoilerplate = MakeRangeError('stack_overflow', []);