blob: 99ba45464fe61c9b0e9ea9d68c87146eabcecb5c [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// -------------------------------------------------------------------
Andrei Popescu31002712010-02-23 13:46:05 +000030//
31// Matches Script::Type from objects.h
32var TYPE_NATIVE = 0;
33var TYPE_EXTENSION = 1;
34var TYPE_NORMAL = 2;
35
36// Matches Script::CompilationType from objects.h
37var COMPILATION_TYPE_HOST = 0;
38var COMPILATION_TYPE_EVAL = 1;
39var COMPILATION_TYPE_JSON = 2;
Steve Blocka7e24c12009-10-30 11:49:00 +000040
41// Lazily initialized.
42var kVowelSounds = 0;
43var kCapitalVowelSounds = 0;
44
Kristian Monsen25f61362010-05-21 11:50:48 +010045// Matches Messages::kNoLineNumberInfo from v8.h
46var kNoLineNumberInfo = 0;
47
Steve Blocka7e24c12009-10-30 11:49:00 +000048// If this object gets passed to an error constructor the error will
49// get an accessor for .message that constructs a descriptive error
50// message on access.
51var kAddMessageAccessorsMarker = { };
52
53
54function GetInstanceName(cons) {
55 if (cons.length == 0) {
56 return "";
57 }
58 var first = %StringToLowerCase(StringCharAt.call(cons, 0));
59 if (kVowelSounds === 0) {
60 kVowelSounds = {a: true, e: true, i: true, o: true, u: true, y: true};
61 kCapitalVowelSounds = {a: true, e: true, i: true, o: true, u: true, h: true,
62 f: true, l: true, m: true, n: true, r: true, s: true, x: true, y: true};
63 }
64 var vowel_mapping = kVowelSounds;
65 if (cons.length > 1 && (StringCharAt.call(cons, 0) != first)) {
66 // First char is upper case
67 var second = %StringToLowerCase(StringCharAt.call(cons, 1));
68 // Second char is upper case
69 if (StringCharAt.call(cons, 1) != second) {
70 vowel_mapping = kCapitalVowelSounds;
71 }
72 }
73 var s = vowel_mapping[first] ? "an " : "a ";
74 return s + cons;
75}
76
77
78var kMessages = 0;
79
80
81function FormatString(format, args) {
82 var result = format;
83 for (var i = 0; i < args.length; i++) {
84 var str;
85 try { str = ToDetailString(args[i]); }
86 catch (e) { str = "#<error>"; }
87 result = ArrayJoin.call(StringSplit.call(result, "%" + i), str);
88 }
89 return result;
90}
91
92
93function ToDetailString(obj) {
94 if (obj != null && IS_OBJECT(obj) && obj.toString === $Object.prototype.toString) {
95 var constructor = obj.constructor;
96 if (!constructor) return ToString(obj);
97 var constructorName = constructor.name;
98 if (!constructorName) return ToString(obj);
99 return "#<" + GetInstanceName(constructorName) + ">";
100 } else {
101 return ToString(obj);
102 }
103}
104
105
106function MakeGenericError(constructor, type, args) {
107 if (IS_UNDEFINED(args)) {
108 args = [];
109 }
110 var e = new constructor(kAddMessageAccessorsMarker);
111 e.type = type;
112 e.arguments = args;
113 return e;
114}
115
116
117/**
118 * Setup the Script function and constructor.
119 */
120%FunctionSetInstanceClassName(Script, 'Script');
121%SetProperty(Script.prototype, 'constructor', Script, DONT_ENUM);
122%SetCode(Script, function(x) {
123 // Script objects can only be created by the VM.
124 throw new $Error("Not supported");
125});
126
127
128// Helper functions; called from the runtime system.
129function FormatMessage(message) {
130 if (kMessages === 0) {
131 kMessages = {
132 // Error
133 cyclic_proto: "Cyclic __proto__ value",
134 // TypeError
135 unexpected_token: "Unexpected token %0",
136 unexpected_token_number: "Unexpected number",
137 unexpected_token_string: "Unexpected string",
138 unexpected_token_identifier: "Unexpected identifier",
139 unexpected_eos: "Unexpected end of input",
140 malformed_regexp: "Invalid regular expression: /%0/: %1",
141 unterminated_regexp: "Invalid regular expression: missing /",
142 regexp_flags: "Cannot supply flags when constructing one RegExp from another",
Steve Block6ded16b2010-05-10 14:33:55 +0100143 incompatible_method_receiver: "Method %0 called on incompatible receiver %1",
Steve Blocka7e24c12009-10-30 11:49:00 +0000144 invalid_lhs_in_assignment: "Invalid left-hand side in assignment",
145 invalid_lhs_in_for_in: "Invalid left-hand side in for-in",
146 invalid_lhs_in_postfix_op: "Invalid left-hand side expression in postfix operation",
147 invalid_lhs_in_prefix_op: "Invalid left-hand side expression in prefix operation",
148 multiple_defaults_in_switch: "More than one default clause in switch statement",
149 newline_after_throw: "Illegal newline after throw",
150 redeclaration: "%0 '%1' has already been declared",
151 no_catch_or_finally: "Missing catch or finally after try",
152 unknown_label: "Undefined label '%0'",
153 uncaught_exception: "Uncaught %0",
154 stack_trace: "Stack Trace:\n%0",
155 called_non_callable: "%0 is not a function",
156 undefined_method: "Object %1 has no method '%0'",
157 property_not_function: "Property '%0' of object %1 is not a function",
158 cannot_convert_to_primitive: "Cannot convert object to primitive value",
159 not_constructor: "%0 is not a constructor",
160 not_defined: "%0 is not defined",
161 non_object_property_load: "Cannot read property '%0' of %1",
162 non_object_property_store: "Cannot set property '%0' of %1",
163 non_object_property_call: "Cannot call method '%0' of %1",
164 with_expression: "%0 has no properties",
165 illegal_invocation: "Illegal invocation",
166 no_setter_in_callback: "Cannot set property %0 of %1 which has only a getter",
167 apply_non_function: "Function.prototype.apply was called on %0, which is a %1 and not a function",
168 apply_wrong_args: "Function.prototype.apply: Arguments list has wrong type",
169 invalid_in_operator_use: "Cannot use 'in' operator to search for '%0' in %1",
170 instanceof_function_expected: "Expecting a function in instanceof check, but got %0",
171 instanceof_nonobject_proto: "Function has non-object prototype '%0' in instanceof check",
172 null_to_object: "Cannot convert null to object",
173 reduce_no_initial: "Reduce of empty array with no initial value",
Leon Clarkee46be812010-01-19 14:06:41 +0000174 getter_must_be_callable: "Getter must be a function: %0",
175 setter_must_be_callable: "Setter must be a function: %0",
176 value_and_accessor: "Invalid property. A property cannot both have accessors and be writable or have a value: %0",
177 proto_object_or_null: "Object prototype may only be an Object or null",
178 property_desc_object: "Property description must be an object: %0",
Andrei Popescu31002712010-02-23 13:46:05 +0000179 redefine_disallowed: "Cannot redefine property: %0",
180 define_disallowed: "Cannot define property, object is not extensible: %0",
Steve Blocka7e24c12009-10-30 11:49:00 +0000181 // RangeError
182 invalid_array_length: "Invalid array length",
183 stack_overflow: "Maximum call stack size exceeded",
184 apply_overflow: "Function.prototype.apply cannot support %0 arguments",
185 // SyntaxError
186 unable_to_parse: "Parse error",
187 duplicate_regexp_flag: "Duplicate RegExp flag %0",
188 invalid_regexp: "Invalid RegExp pattern /%0/",
189 illegal_break: "Illegal break statement",
190 illegal_continue: "Illegal continue statement",
191 illegal_return: "Illegal return statement",
192 error_loading_debugger: "Error loading debugger",
193 no_input_to_regexp: "No input to %0",
194 result_not_primitive: "Result of %0 must be a primitive, was %1",
195 invalid_json: "String '%0' is not valid JSON",
196 circular_structure: "Converting circular structure to JSON",
Leon Clarkee46be812010-01-19 14:06:41 +0000197 obj_ctor_property_non_object: "Object.%0 called on non-object",
Steve Block6ded16b2010-05-10 14:33:55 +0100198 array_indexof_not_defined: "Array.getIndexOf: Argument undefined",
Steve Block8defd9f2010-07-08 12:39:36 +0100199 object_not_extensible: "Can't add property %0, object is not extensible",
Leon Clarkeac952652010-07-15 11:15:24 +0100200 illegal_access: "Illegal access",
201 invalid_preparser_data: "Invalid preparser data for function %0"
Steve Blocka7e24c12009-10-30 11:49:00 +0000202 };
203 }
204 var format = kMessages[message.type];
205 if (!format) return "<unknown message " + message.type + ">";
206 return FormatString(format, message.args);
207}
208
209
210function GetLineNumber(message) {
Kristian Monsen25f61362010-05-21 11:50:48 +0100211 if (message.startPos == -1) return kNoLineNumberInfo;
Steve Blocka7e24c12009-10-30 11:49:00 +0000212 var location = message.script.locationFromPosition(message.startPos, true);
Kristian Monsen25f61362010-05-21 11:50:48 +0100213 if (location == null) return kNoLineNumberInfo;
Steve Blocka7e24c12009-10-30 11:49:00 +0000214 return location.line + 1;
215}
216
217
218// Returns the source code line containing the given source
219// position, or the empty string if the position is invalid.
220function GetSourceLine(message) {
221 var location = message.script.locationFromPosition(message.startPos, true);
222 if (location == null) return "";
223 location.restrict();
224 return location.sourceText();
225}
226
227
228function MakeTypeError(type, args) {
229 return MakeGenericError($TypeError, type, args);
230}
231
232
233function MakeRangeError(type, args) {
234 return MakeGenericError($RangeError, type, args);
235}
236
237
238function MakeSyntaxError(type, args) {
239 return MakeGenericError($SyntaxError, type, args);
240}
241
242
243function MakeReferenceError(type, args) {
244 return MakeGenericError($ReferenceError, type, args);
245}
246
247
248function MakeEvalError(type, args) {
249 return MakeGenericError($EvalError, type, args);
250}
251
252
253function MakeError(type, args) {
254 return MakeGenericError($Error, type, args);
255}
256
257/**
258 * Find a line number given a specific source position.
259 * @param {number} position The source position.
260 * @return {number} 0 if input too small, -1 if input too large,
261 else the line number.
262 */
263Script.prototype.lineFromPosition = function(position) {
264 var lower = 0;
265 var upper = this.lineCount() - 1;
Steve Blockd0582a62009-12-15 09:54:21 +0000266 var line_ends = this.line_ends;
Steve Blocka7e24c12009-10-30 11:49:00 +0000267
268 // We'll never find invalid positions so bail right away.
Steve Blockd0582a62009-12-15 09:54:21 +0000269 if (position > line_ends[upper]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000270 return -1;
271 }
272
273 // This means we don't have to safe-guard indexing line_ends[i - 1].
Steve Blockd0582a62009-12-15 09:54:21 +0000274 if (position <= line_ends[0]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000275 return 0;
276 }
277
278 // Binary search to find line # from position range.
279 while (upper >= 1) {
280 var i = (lower + upper) >> 1;
281
Steve Blockd0582a62009-12-15 09:54:21 +0000282 if (position > line_ends[i]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000283 lower = i + 1;
Steve Blockd0582a62009-12-15 09:54:21 +0000284 } else if (position <= line_ends[i - 1]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000285 upper = i - 1;
286 } else {
287 return i;
288 }
289 }
290 return -1;
291}
292
293/**
294 * Get information on a specific source position.
295 * @param {number} position The source position
296 * @param {boolean} include_resource_offset Set to true to have the resource
297 * offset added to the location
298 * @return {SourceLocation}
299 * If line is negative or not in the source null is returned.
300 */
301Script.prototype.locationFromPosition = function (position,
302 include_resource_offset) {
303 var line = this.lineFromPosition(position);
304 if (line == -1) return null;
305
306 // Determine start, end and column.
Steve Blockd0582a62009-12-15 09:54:21 +0000307 var line_ends = this.line_ends;
308 var start = line == 0 ? 0 : line_ends[line - 1] + 1;
309 var end = line_ends[line];
Steve Blocka7e24c12009-10-30 11:49:00 +0000310 if (end > 0 && StringCharAt.call(this.source, end - 1) == '\r') end--;
311 var column = position - start;
312
313 // Adjust according to the offset within the resource.
314 if (include_resource_offset) {
315 line += this.line_offset;
316 if (line == this.line_offset) {
317 column += this.column_offset;
318 }
319 }
320
321 return new SourceLocation(this, position, line, column, start, end);
322};
323
324
325/**
326 * Get information on a specific source line and column possibly offset by a
327 * fixed source position. This function is used to find a source position from
328 * a line and column position. The fixed source position offset is typically
329 * used to find a source position in a function based on a line and column in
330 * the source for the function alone. The offset passed will then be the
331 * start position of the source for the function within the full script source.
332 * @param {number} opt_line The line within the source. Default value is 0
333 * @param {number} opt_column The column in within the line. Default value is 0
334 * @param {number} opt_offset_position The offset from the begining of the
335 * source from where the line and column calculation starts. Default value is 0
336 * @return {SourceLocation}
337 * If line is negative or not in the source null is returned.
338 */
339Script.prototype.locationFromLine = function (opt_line, opt_column, opt_offset_position) {
340 // Default is the first line in the script. Lines in the script is relative
341 // to the offset within the resource.
342 var line = 0;
343 if (!IS_UNDEFINED(opt_line)) {
344 line = opt_line - this.line_offset;
345 }
346
347 // Default is first column. If on the first line add the offset within the
348 // resource.
349 var column = opt_column || 0;
350 if (line == 0) {
351 column -= this.column_offset
352 }
353
354 var offset_position = opt_offset_position || 0;
355 if (line < 0 || column < 0 || offset_position < 0) return null;
356 if (line == 0) {
357 return this.locationFromPosition(offset_position + column, false);
358 } else {
359 // Find the line where the offset position is located.
360 var offset_line = this.lineFromPosition(offset_position);
361
362 if (offset_line == -1 || offset_line + line >= this.lineCount()) {
363 return null;
364 }
365
366 return this.locationFromPosition(this.line_ends[offset_line + line - 1] + 1 + column); // line > 0 here.
367 }
368}
369
370
371/**
372 * Get a slice of source code from the script. The boundaries for the slice is
373 * specified in lines.
374 * @param {number} opt_from_line The first line (zero bound) in the slice.
375 * Default is 0
376 * @param {number} opt_to_column The last line (zero bound) in the slice (non
377 * inclusive). Default is the number of lines in the script
378 * @return {SourceSlice} The source slice or null of the parameters where
379 * invalid
380 */
381Script.prototype.sourceSlice = function (opt_from_line, opt_to_line) {
382 var from_line = IS_UNDEFINED(opt_from_line) ? this.line_offset : opt_from_line;
383 var to_line = IS_UNDEFINED(opt_to_line) ? this.line_offset + this.lineCount() : opt_to_line
384
385 // Adjust according to the offset within the resource.
386 from_line -= this.line_offset;
387 to_line -= this.line_offset;
388 if (from_line < 0) from_line = 0;
389 if (to_line > this.lineCount()) to_line = this.lineCount();
390
391 // Check parameters.
392 if (from_line >= this.lineCount() ||
393 to_line < 0 ||
394 from_line > to_line) {
395 return null;
396 }
397
Steve Blockd0582a62009-12-15 09:54:21 +0000398 var line_ends = this.line_ends;
399 var from_position = from_line == 0 ? 0 : line_ends[from_line - 1] + 1;
400 var to_position = to_line == 0 ? 0 : line_ends[to_line - 1] + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +0000401
402 // Return a source slice with line numbers re-adjusted to the resource.
403 return new SourceSlice(this, from_line + this.line_offset, to_line + this.line_offset,
404 from_position, to_position);
405}
406
407
408Script.prototype.sourceLine = function (opt_line) {
409 // Default is the first line in the script. Lines in the script are relative
410 // to the offset within the resource.
411 var line = 0;
412 if (!IS_UNDEFINED(opt_line)) {
413 line = opt_line - this.line_offset;
414 }
415
416 // Check parameter.
417 if (line < 0 || this.lineCount() <= line) {
418 return null;
419 }
420
421 // Return the source line.
Steve Blockd0582a62009-12-15 09:54:21 +0000422 var line_ends = this.line_ends;
423 var start = line == 0 ? 0 : line_ends[line - 1] + 1;
424 var end = line_ends[line];
Steve Blocka7e24c12009-10-30 11:49:00 +0000425 return StringSubstring.call(this.source, start, end);
426}
427
428
429/**
430 * Returns the number of source lines.
431 * @return {number}
432 * Number of source lines.
433 */
434Script.prototype.lineCount = function() {
435 // Return number of source lines.
436 return this.line_ends.length;
437};
438
439
440/**
Steve Block6ded16b2010-05-10 14:33:55 +0100441 * Returns the name of script if available, contents of sourceURL comment
442 * otherwise. See
443 * http://fbug.googlecode.com/svn/branches/firebug1.1/docs/ReleaseNotes_1.1.txt
444 * for details on using //@ sourceURL comment to identify scritps that don't
445 * have name.
446 *
447 * @return {?string} script name if present, value for //@ sourceURL comment
448 * otherwise.
449 */
450Script.prototype.nameOrSourceURL = function() {
451 if (this.name)
452 return this.name;
453 // TODO(608): the spaces in a regexp below had to be escaped as \040
454 // because this file is being processed by js2c whose handling of spaces
455 // in regexps is broken. Also, ['"] are excluded from allowed URLs to
456 // avoid matches against sources that invoke evals with sourceURL.
457 var sourceUrlPattern =
458 /\/\/@[\040\t]sourceURL=[\040\t]*([^\s'"]*)[\040\t]*$/m;
459 var match = sourceUrlPattern.exec(this.source);
460 return match ? match[1] : this.name;
461}
462
463
464/**
Steve Blocka7e24c12009-10-30 11:49:00 +0000465 * Class for source location. A source location is a position within some
466 * source with the following properties:
467 * script : script object for the source
468 * line : source line number
469 * column : source column within the line
470 * position : position within the source
471 * start : position of start of source context (inclusive)
472 * end : position of end of source context (not inclusive)
473 * Source text for the source context is the character interval [start, end[. In
474 * most cases end will point to a newline character. It might point just past
475 * the final position of the source if the last source line does not end with a
476 * newline character.
477 * @param {Script} script The Script object for which this is a location
478 * @param {number} position Source position for the location
479 * @param {number} line The line number for the location
480 * @param {number} column The column within the line for the location
481 * @param {number} start Source position for start of source context
482 * @param {number} end Source position for end of source context
483 * @constructor
484 */
485function SourceLocation(script, position, line, column, start, end) {
486 this.script = script;
487 this.position = position;
488 this.line = line;
489 this.column = column;
490 this.start = start;
491 this.end = end;
492}
493
494
495const kLineLengthLimit = 78;
496
497/**
498 * Restrict source location start and end positions to make the source slice
499 * no more that a certain number of characters wide.
500 * @param {number} opt_limit The with limit of the source text with a default
501 * of 78
502 * @param {number} opt_before The number of characters to prefer before the
503 * position with a default value of 10 less that the limit
504 */
505SourceLocation.prototype.restrict = function (opt_limit, opt_before) {
506 // Find the actual limit to use.
507 var limit;
508 var before;
509 if (!IS_UNDEFINED(opt_limit)) {
510 limit = opt_limit;
511 } else {
512 limit = kLineLengthLimit;
513 }
514 if (!IS_UNDEFINED(opt_before)) {
515 before = opt_before;
516 } else {
517 // If no before is specified center for small limits and perfer more source
518 // before the the position that after for longer limits.
519 if (limit <= 20) {
520 before = $floor(limit / 2);
521 } else {
522 before = limit - 10;
523 }
524 }
525 if (before >= limit) {
526 before = limit - 1;
527 }
528
529 // If the [start, end[ interval is too big we restrict
530 // it in one or both ends. We make sure to always produce
531 // restricted intervals of maximum allowed size.
532 if (this.end - this.start > limit) {
533 var start_limit = this.position - before;
534 var end_limit = this.position + limit - before;
535 if (this.start < start_limit && end_limit < this.end) {
536 this.start = start_limit;
537 this.end = end_limit;
538 } else if (this.start < start_limit) {
539 this.start = this.end - limit;
540 } else {
541 this.end = this.start + limit;
542 }
543 }
544};
545
546
547/**
548 * Get the source text for a SourceLocation
549 * @return {String}
550 * Source text for this location.
551 */
552SourceLocation.prototype.sourceText = function () {
553 return StringSubstring.call(this.script.source, this.start, this.end);
554};
555
556
557/**
558 * Class for a source slice. A source slice is a part of a script source with
559 * the following properties:
560 * script : script object for the source
561 * from_line : line number for the first line in the slice
562 * to_line : source line number for the last line in the slice
563 * from_position : position of the first character in the slice
564 * to_position : position of the last character in the slice
565 * The to_line and to_position are not included in the slice, that is the lines
566 * in the slice are [from_line, to_line[. Likewise the characters in the slice
567 * are [from_position, to_position[.
568 * @param {Script} script The Script object for the source slice
569 * @param {number} from_line
570 * @param {number} to_line
571 * @param {number} from_position
572 * @param {number} to_position
573 * @constructor
574 */
575function SourceSlice(script, from_line, to_line, from_position, to_position) {
576 this.script = script;
577 this.from_line = from_line;
578 this.to_line = to_line;
579 this.from_position = from_position;
580 this.to_position = to_position;
581}
582
583
584/**
585 * Get the source text for a SourceSlice
586 * @return {String} Source text for this slice. The last line will include
587 * the line terminating characters (if any)
588 */
589SourceSlice.prototype.sourceText = function () {
590 return StringSubstring.call(this.script.source, this.from_position, this.to_position);
591};
592
593
594// Returns the offset of the given position within the containing
595// line.
596function GetPositionInLine(message) {
597 var location = message.script.locationFromPosition(message.startPos, false);
598 if (location == null) return -1;
599 location.restrict();
600 return message.startPos - location.start;
601}
602
603
604function ErrorMessage(type, args, startPos, endPos, script, stackTrace) {
605 this.startPos = startPos;
606 this.endPos = endPos;
607 this.type = type;
608 this.args = args;
609 this.script = script;
610 this.stackTrace = stackTrace;
611}
612
613
614function MakeMessage(type, args, startPos, endPos, script, stackTrace) {
615 return new ErrorMessage(type, args, startPos, endPos, script, stackTrace);
616}
617
618
619function GetStackTraceLine(recv, fun, pos, isGlobal) {
620 return FormatSourcePosition(new CallSite(recv, fun, pos));
621}
622
623// ----------------------------------------------------------------------------
624// Error implementation
625
626// Defines accessors for a property that is calculated the first time
627// the property is read.
628function DefineOneShotAccessor(obj, name, fun) {
629 // Note that the accessors consistently operate on 'obj', not 'this'.
630 // Since the object may occur in someone else's prototype chain we
631 // can't rely on 'this' being the same as 'obj'.
632 var hasBeenSet = false;
633 var value;
634 obj.__defineGetter__(name, function () {
635 if (hasBeenSet) {
636 return value;
637 }
638 hasBeenSet = true;
639 value = fun(obj);
640 return value;
641 });
642 obj.__defineSetter__(name, function (v) {
643 hasBeenSet = true;
644 value = v;
645 });
646}
647
648function CallSite(receiver, fun, pos) {
649 this.receiver = receiver;
650 this.fun = fun;
651 this.pos = pos;
652}
653
654CallSite.prototype.getThis = function () {
655 return this.receiver;
656};
657
658CallSite.prototype.getTypeName = function () {
659 var constructor = this.receiver.constructor;
660 if (!constructor)
661 return $Object.prototype.toString.call(this.receiver);
662 var constructorName = constructor.name;
663 if (!constructorName)
664 return $Object.prototype.toString.call(this.receiver);
665 return constructorName;
666};
667
668CallSite.prototype.isToplevel = function () {
669 if (this.receiver == null)
670 return true;
671 return IS_GLOBAL(this.receiver);
672};
673
674CallSite.prototype.isEval = function () {
675 var script = %FunctionGetScript(this.fun);
Andrei Popescu31002712010-02-23 13:46:05 +0000676 return script && script.compilation_type == COMPILATION_TYPE_EVAL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000677};
678
679CallSite.prototype.getEvalOrigin = function () {
680 var script = %FunctionGetScript(this.fun);
Steve Blockd0582a62009-12-15 09:54:21 +0000681 return FormatEvalOrigin(script);
Steve Blocka7e24c12009-10-30 11:49:00 +0000682};
683
684CallSite.prototype.getFunction = function () {
685 return this.fun;
686};
687
688CallSite.prototype.getFunctionName = function () {
689 // See if the function knows its own name
690 var name = this.fun.name;
691 if (name) {
692 return name;
693 } else {
694 return %FunctionGetInferredName(this.fun);
695 }
696 // Maybe this is an evaluation?
697 var script = %FunctionGetScript(this.fun);
Andrei Popescu31002712010-02-23 13:46:05 +0000698 if (script && script.compilation_type == COMPILATION_TYPE_EVAL)
Steve Blocka7e24c12009-10-30 11:49:00 +0000699 return "eval";
700 return null;
701};
702
703CallSite.prototype.getMethodName = function () {
704 // See if we can find a unique property on the receiver that holds
705 // this function.
706 var ownName = this.fun.name;
707 if (ownName && this.receiver && this.receiver[ownName] === this.fun)
708 // To handle DontEnum properties we guess that the method has
709 // the same name as the function.
710 return ownName;
711 var name = null;
712 for (var prop in this.receiver) {
713 if (this.receiver[prop] === this.fun) {
714 // If we find more than one match bail out to avoid confusion
715 if (name)
716 return null;
717 name = prop;
718 }
719 }
720 if (name)
721 return name;
722 return null;
723};
724
725CallSite.prototype.getFileName = function () {
726 var script = %FunctionGetScript(this.fun);
727 return script ? script.name : null;
728};
729
730CallSite.prototype.getLineNumber = function () {
731 if (this.pos == -1)
732 return null;
733 var script = %FunctionGetScript(this.fun);
734 var location = null;
735 if (script) {
736 location = script.locationFromPosition(this.pos, true);
737 }
738 return location ? location.line + 1 : null;
739};
740
741CallSite.prototype.getColumnNumber = function () {
742 if (this.pos == -1)
743 return null;
744 var script = %FunctionGetScript(this.fun);
745 var location = null;
746 if (script) {
747 location = script.locationFromPosition(this.pos, true);
748 }
Steve Blockd0582a62009-12-15 09:54:21 +0000749 return location ? location.column + 1: null;
Steve Blocka7e24c12009-10-30 11:49:00 +0000750};
751
752CallSite.prototype.isNative = function () {
753 var script = %FunctionGetScript(this.fun);
Andrei Popescu31002712010-02-23 13:46:05 +0000754 return script ? (script.type == TYPE_NATIVE) : false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000755};
756
757CallSite.prototype.getPosition = function () {
758 return this.pos;
759};
760
761CallSite.prototype.isConstructor = function () {
762 var constructor = this.receiver ? this.receiver.constructor : null;
763 if (!constructor)
764 return false;
765 return this.fun === constructor;
766};
767
Steve Blockd0582a62009-12-15 09:54:21 +0000768function FormatEvalOrigin(script) {
769 var eval_origin = "";
770 if (script.eval_from_function_name) {
771 eval_origin += script.eval_from_function_name;
772 } else {
773 eval_origin += "<anonymous>";
774 }
Steve Block6ded16b2010-05-10 14:33:55 +0100775
Steve Blockd0582a62009-12-15 09:54:21 +0000776 var eval_from_script = script.eval_from_script;
777 if (eval_from_script) {
Andrei Popescu31002712010-02-23 13:46:05 +0000778 if (eval_from_script.compilation_type == COMPILATION_TYPE_EVAL) {
Steve Blockd0582a62009-12-15 09:54:21 +0000779 // eval script originated from another eval.
780 eval_origin += " (eval at " + FormatEvalOrigin(eval_from_script) + ")";
781 } else {
782 // eval script originated from "real" scource.
783 if (eval_from_script.name) {
784 eval_origin += " (" + eval_from_script.name;
785 var location = eval_from_script.locationFromPosition(script.eval_from_script_position, true);
786 if (location) {
787 eval_origin += ":" + (location.line + 1);
788 eval_origin += ":" + (location.column + 1);
789 }
790 eval_origin += ")"
791 } else {
792 eval_origin += " (unknown source)";
793 }
794 }
795 }
Steve Block6ded16b2010-05-10 14:33:55 +0100796
Steve Blockd0582a62009-12-15 09:54:21 +0000797 return eval_origin;
798};
799
Steve Blocka7e24c12009-10-30 11:49:00 +0000800function FormatSourcePosition(frame) {
801 var fileLocation = "";
802 if (frame.isNative()) {
803 fileLocation = "native";
804 } else if (frame.isEval()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000805 fileLocation = "eval at " + frame.getEvalOrigin();
Steve Blocka7e24c12009-10-30 11:49:00 +0000806 } else {
807 var fileName = frame.getFileName();
808 if (fileName) {
809 fileLocation += fileName;
810 var lineNumber = frame.getLineNumber();
811 if (lineNumber != null) {
812 fileLocation += ":" + lineNumber;
813 var columnNumber = frame.getColumnNumber();
814 if (columnNumber) {
815 fileLocation += ":" + columnNumber;
816 }
817 }
818 }
819 }
820 if (!fileLocation) {
821 fileLocation = "unknown source";
822 }
823 var line = "";
824 var functionName = frame.getFunction().name;
825 var methodName = frame.getMethodName();
826 var addPrefix = true;
827 var isConstructor = frame.isConstructor();
828 var isMethodCall = !(frame.isToplevel() || isConstructor);
829 if (isMethodCall) {
830 line += frame.getTypeName() + ".";
831 if (functionName) {
832 line += functionName;
833 if (methodName && (methodName != functionName)) {
834 line += " [as " + methodName + "]";
835 }
836 } else {
837 line += methodName || "<anonymous>";
838 }
839 } else if (isConstructor) {
840 line += "new " + (functionName || "<anonymous>");
841 } else if (functionName) {
842 line += functionName;
843 } else {
844 line += fileLocation;
845 addPrefix = false;
846 }
847 if (addPrefix) {
848 line += " (" + fileLocation + ")";
849 }
850 return line;
851}
852
853function FormatStackTrace(error, frames) {
854 var lines = [];
855 try {
856 lines.push(error.toString());
857 } catch (e) {
858 try {
859 lines.push("<error: " + e + ">");
860 } catch (ee) {
861 lines.push("<error>");
862 }
863 }
864 for (var i = 0; i < frames.length; i++) {
865 var frame = frames[i];
866 var line;
867 try {
868 line = FormatSourcePosition(frame);
869 } catch (e) {
870 try {
871 line = "<error: " + e + ">";
872 } catch (ee) {
873 // Any code that reaches this point is seriously nasty!
874 line = "<error>";
875 }
876 }
877 lines.push(" at " + line);
878 }
879 return lines.join("\n");
880}
881
882function FormatRawStackTrace(error, raw_stack) {
883 var frames = [ ];
884 for (var i = 0; i < raw_stack.length; i += 3) {
885 var recv = raw_stack[i];
886 var fun = raw_stack[i+1];
887 var pc = raw_stack[i+2];
888 var pos = %FunctionGetPositionForOffset(fun, pc);
889 frames.push(new CallSite(recv, fun, pos));
890 }
891 if (IS_FUNCTION($Error.prepareStackTrace)) {
892 return $Error.prepareStackTrace(error, frames);
893 } else {
894 return FormatStackTrace(error, frames);
895 }
896}
897
898function DefineError(f) {
899 // Store the error function in both the global object
900 // and the runtime object. The function is fetched
901 // from the runtime object when throwing errors from
902 // within the runtime system to avoid strange side
903 // effects when overwriting the error functions from
904 // user code.
905 var name = f.name;
906 %SetProperty(global, name, f, DONT_ENUM);
907 this['$' + name] = f;
908 // Configure the error function.
909 if (name == 'Error') {
910 // The prototype of the Error object must itself be an error.
911 // However, it can't be an instance of the Error object because
912 // it hasn't been properly configured yet. Instead we create a
913 // special not-a-true-error-but-close-enough object.
914 function ErrorPrototype() {}
915 %FunctionSetPrototype(ErrorPrototype, $Object.prototype);
916 %FunctionSetInstanceClassName(ErrorPrototype, 'Error');
917 %FunctionSetPrototype(f, new ErrorPrototype());
918 } else {
919 %FunctionSetPrototype(f, new $Error());
920 }
921 %FunctionSetInstanceClassName(f, 'Error');
922 %SetProperty(f.prototype, 'constructor', f, DONT_ENUM);
923 f.prototype.name = name;
924 %SetCode(f, function(m) {
925 if (%_IsConstructCall()) {
926 if (m === kAddMessageAccessorsMarker) {
927 DefineOneShotAccessor(this, 'message', function (obj) {
928 return FormatMessage({type: obj.type, args: obj.arguments});
929 });
930 } else if (!IS_UNDEFINED(m)) {
931 this.message = ToString(m);
932 }
933 captureStackTrace(this, f);
934 } else {
935 return new f(m);
936 }
937 });
938}
939
940function captureStackTrace(obj, cons_opt) {
941 var stackTraceLimit = $Error.stackTraceLimit;
942 if (!stackTraceLimit) return;
943 if (stackTraceLimit < 0 || stackTraceLimit > 10000)
944 stackTraceLimit = 10000;
945 var raw_stack = %CollectStackTrace(cons_opt ? cons_opt : captureStackTrace,
946 stackTraceLimit);
947 DefineOneShotAccessor(obj, 'stack', function (obj) {
948 return FormatRawStackTrace(obj, raw_stack);
949 });
950};
951
952$Math.__proto__ = global.Object.prototype;
953
954DefineError(function Error() { });
955DefineError(function TypeError() { });
956DefineError(function RangeError() { });
957DefineError(function SyntaxError() { });
958DefineError(function ReferenceError() { });
959DefineError(function EvalError() { });
960DefineError(function URIError() { });
961
962$Error.captureStackTrace = captureStackTrace;
963
964// Setup extra properties of the Error.prototype object.
965$Error.prototype.message = '';
966
967%SetProperty($Error.prototype, 'toString', function toString() {
968 var type = this.type;
969 if (type && !this.hasOwnProperty("message")) {
970 return this.name + ": " + FormatMessage({ type: type, args: this.arguments });
971 }
972 var message = this.message;
973 return this.name + (message ? (": " + message) : "");
974}, DONT_ENUM);
975
976
977// Boilerplate for exceptions for stack overflows. Used from
978// Top::StackOverflow().
979const kStackOverflowBoilerplate = MakeRangeError('stack_overflow', []);