blob: 7bac3b24bb93fb7b96f6d96ad8795d68388cb27d [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",
Steve Block6ded16b2010-05-10 14:33:55 +0100200 illegal_access: "illegal access"
Steve Blocka7e24c12009-10-30 11:49:00 +0000201 };
202 }
203 var format = kMessages[message.type];
204 if (!format) return "<unknown message " + message.type + ">";
205 return FormatString(format, message.args);
206}
207
208
209function GetLineNumber(message) {
Kristian Monsen25f61362010-05-21 11:50:48 +0100210 if (message.startPos == -1) return kNoLineNumberInfo;
Steve Blocka7e24c12009-10-30 11:49:00 +0000211 var location = message.script.locationFromPosition(message.startPos, true);
Kristian Monsen25f61362010-05-21 11:50:48 +0100212 if (location == null) return kNoLineNumberInfo;
Steve Blocka7e24c12009-10-30 11:49:00 +0000213 return location.line + 1;
214}
215
216
217// Returns the source code line containing the given source
218// position, or the empty string if the position is invalid.
219function GetSourceLine(message) {
220 var location = message.script.locationFromPosition(message.startPos, true);
221 if (location == null) return "";
222 location.restrict();
223 return location.sourceText();
224}
225
226
227function MakeTypeError(type, args) {
228 return MakeGenericError($TypeError, type, args);
229}
230
231
232function MakeRangeError(type, args) {
233 return MakeGenericError($RangeError, type, args);
234}
235
236
237function MakeSyntaxError(type, args) {
238 return MakeGenericError($SyntaxError, type, args);
239}
240
241
242function MakeReferenceError(type, args) {
243 return MakeGenericError($ReferenceError, type, args);
244}
245
246
247function MakeEvalError(type, args) {
248 return MakeGenericError($EvalError, type, args);
249}
250
251
252function MakeError(type, args) {
253 return MakeGenericError($Error, type, args);
254}
255
256/**
257 * Find a line number given a specific source position.
258 * @param {number} position The source position.
259 * @return {number} 0 if input too small, -1 if input too large,
260 else the line number.
261 */
262Script.prototype.lineFromPosition = function(position) {
263 var lower = 0;
264 var upper = this.lineCount() - 1;
Steve Blockd0582a62009-12-15 09:54:21 +0000265 var line_ends = this.line_ends;
Steve Blocka7e24c12009-10-30 11:49:00 +0000266
267 // We'll never find invalid positions so bail right away.
Steve Blockd0582a62009-12-15 09:54:21 +0000268 if (position > line_ends[upper]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000269 return -1;
270 }
271
272 // This means we don't have to safe-guard indexing line_ends[i - 1].
Steve Blockd0582a62009-12-15 09:54:21 +0000273 if (position <= line_ends[0]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000274 return 0;
275 }
276
277 // Binary search to find line # from position range.
278 while (upper >= 1) {
279 var i = (lower + upper) >> 1;
280
Steve Blockd0582a62009-12-15 09:54:21 +0000281 if (position > line_ends[i]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000282 lower = i + 1;
Steve Blockd0582a62009-12-15 09:54:21 +0000283 } else if (position <= line_ends[i - 1]) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000284 upper = i - 1;
285 } else {
286 return i;
287 }
288 }
289 return -1;
290}
291
292/**
293 * Get information on a specific source position.
294 * @param {number} position The source position
295 * @param {boolean} include_resource_offset Set to true to have the resource
296 * offset added to the location
297 * @return {SourceLocation}
298 * If line is negative or not in the source null is returned.
299 */
300Script.prototype.locationFromPosition = function (position,
301 include_resource_offset) {
302 var line = this.lineFromPosition(position);
303 if (line == -1) return null;
304
305 // Determine start, end and column.
Steve Blockd0582a62009-12-15 09:54:21 +0000306 var line_ends = this.line_ends;
307 var start = line == 0 ? 0 : line_ends[line - 1] + 1;
308 var end = line_ends[line];
Steve Blocka7e24c12009-10-30 11:49:00 +0000309 if (end > 0 && StringCharAt.call(this.source, end - 1) == '\r') end--;
310 var column = position - start;
311
312 // Adjust according to the offset within the resource.
313 if (include_resource_offset) {
314 line += this.line_offset;
315 if (line == this.line_offset) {
316 column += this.column_offset;
317 }
318 }
319
320 return new SourceLocation(this, position, line, column, start, end);
321};
322
323
324/**
325 * Get information on a specific source line and column possibly offset by a
326 * fixed source position. This function is used to find a source position from
327 * a line and column position. The fixed source position offset is typically
328 * used to find a source position in a function based on a line and column in
329 * the source for the function alone. The offset passed will then be the
330 * start position of the source for the function within the full script source.
331 * @param {number} opt_line The line within the source. Default value is 0
332 * @param {number} opt_column The column in within the line. Default value is 0
333 * @param {number} opt_offset_position The offset from the begining of the
334 * source from where the line and column calculation starts. Default value is 0
335 * @return {SourceLocation}
336 * If line is negative or not in the source null is returned.
337 */
338Script.prototype.locationFromLine = function (opt_line, opt_column, opt_offset_position) {
339 // Default is the first line in the script. Lines in the script is relative
340 // to the offset within the resource.
341 var line = 0;
342 if (!IS_UNDEFINED(opt_line)) {
343 line = opt_line - this.line_offset;
344 }
345
346 // Default is first column. If on the first line add the offset within the
347 // resource.
348 var column = opt_column || 0;
349 if (line == 0) {
350 column -= this.column_offset
351 }
352
353 var offset_position = opt_offset_position || 0;
354 if (line < 0 || column < 0 || offset_position < 0) return null;
355 if (line == 0) {
356 return this.locationFromPosition(offset_position + column, false);
357 } else {
358 // Find the line where the offset position is located.
359 var offset_line = this.lineFromPosition(offset_position);
360
361 if (offset_line == -1 || offset_line + line >= this.lineCount()) {
362 return null;
363 }
364
365 return this.locationFromPosition(this.line_ends[offset_line + line - 1] + 1 + column); // line > 0 here.
366 }
367}
368
369
370/**
371 * Get a slice of source code from the script. The boundaries for the slice is
372 * specified in lines.
373 * @param {number} opt_from_line The first line (zero bound) in the slice.
374 * Default is 0
375 * @param {number} opt_to_column The last line (zero bound) in the slice (non
376 * inclusive). Default is the number of lines in the script
377 * @return {SourceSlice} The source slice or null of the parameters where
378 * invalid
379 */
380Script.prototype.sourceSlice = function (opt_from_line, opt_to_line) {
381 var from_line = IS_UNDEFINED(opt_from_line) ? this.line_offset : opt_from_line;
382 var to_line = IS_UNDEFINED(opt_to_line) ? this.line_offset + this.lineCount() : opt_to_line
383
384 // Adjust according to the offset within the resource.
385 from_line -= this.line_offset;
386 to_line -= this.line_offset;
387 if (from_line < 0) from_line = 0;
388 if (to_line > this.lineCount()) to_line = this.lineCount();
389
390 // Check parameters.
391 if (from_line >= this.lineCount() ||
392 to_line < 0 ||
393 from_line > to_line) {
394 return null;
395 }
396
Steve Blockd0582a62009-12-15 09:54:21 +0000397 var line_ends = this.line_ends;
398 var from_position = from_line == 0 ? 0 : line_ends[from_line - 1] + 1;
399 var to_position = to_line == 0 ? 0 : line_ends[to_line - 1] + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +0000400
401 // Return a source slice with line numbers re-adjusted to the resource.
402 return new SourceSlice(this, from_line + this.line_offset, to_line + this.line_offset,
403 from_position, to_position);
404}
405
406
407Script.prototype.sourceLine = function (opt_line) {
408 // Default is the first line in the script. Lines in the script are relative
409 // to the offset within the resource.
410 var line = 0;
411 if (!IS_UNDEFINED(opt_line)) {
412 line = opt_line - this.line_offset;
413 }
414
415 // Check parameter.
416 if (line < 0 || this.lineCount() <= line) {
417 return null;
418 }
419
420 // Return the source line.
Steve Blockd0582a62009-12-15 09:54:21 +0000421 var line_ends = this.line_ends;
422 var start = line == 0 ? 0 : line_ends[line - 1] + 1;
423 var end = line_ends[line];
Steve Blocka7e24c12009-10-30 11:49:00 +0000424 return StringSubstring.call(this.source, start, end);
425}
426
427
428/**
429 * Returns the number of source lines.
430 * @return {number}
431 * Number of source lines.
432 */
433Script.prototype.lineCount = function() {
434 // Return number of source lines.
435 return this.line_ends.length;
436};
437
438
439/**
Steve Block6ded16b2010-05-10 14:33:55 +0100440 * Returns the name of script if available, contents of sourceURL comment
441 * otherwise. See
442 * http://fbug.googlecode.com/svn/branches/firebug1.1/docs/ReleaseNotes_1.1.txt
443 * for details on using //@ sourceURL comment to identify scritps that don't
444 * have name.
445 *
446 * @return {?string} script name if present, value for //@ sourceURL comment
447 * otherwise.
448 */
449Script.prototype.nameOrSourceURL = function() {
450 if (this.name)
451 return this.name;
452 // TODO(608): the spaces in a regexp below had to be escaped as \040
453 // because this file is being processed by js2c whose handling of spaces
454 // in regexps is broken. Also, ['"] are excluded from allowed URLs to
455 // avoid matches against sources that invoke evals with sourceURL.
456 var sourceUrlPattern =
457 /\/\/@[\040\t]sourceURL=[\040\t]*([^\s'"]*)[\040\t]*$/m;
458 var match = sourceUrlPattern.exec(this.source);
459 return match ? match[1] : this.name;
460}
461
462
463/**
Steve Blocka7e24c12009-10-30 11:49:00 +0000464 * Class for source location. A source location is a position within some
465 * source with the following properties:
466 * script : script object for the source
467 * line : source line number
468 * column : source column within the line
469 * position : position within the source
470 * start : position of start of source context (inclusive)
471 * end : position of end of source context (not inclusive)
472 * Source text for the source context is the character interval [start, end[. In
473 * most cases end will point to a newline character. It might point just past
474 * the final position of the source if the last source line does not end with a
475 * newline character.
476 * @param {Script} script The Script object for which this is a location
477 * @param {number} position Source position for the location
478 * @param {number} line The line number for the location
479 * @param {number} column The column within the line for the location
480 * @param {number} start Source position for start of source context
481 * @param {number} end Source position for end of source context
482 * @constructor
483 */
484function SourceLocation(script, position, line, column, start, end) {
485 this.script = script;
486 this.position = position;
487 this.line = line;
488 this.column = column;
489 this.start = start;
490 this.end = end;
491}
492
493
494const kLineLengthLimit = 78;
495
496/**
497 * Restrict source location start and end positions to make the source slice
498 * no more that a certain number of characters wide.
499 * @param {number} opt_limit The with limit of the source text with a default
500 * of 78
501 * @param {number} opt_before The number of characters to prefer before the
502 * position with a default value of 10 less that the limit
503 */
504SourceLocation.prototype.restrict = function (opt_limit, opt_before) {
505 // Find the actual limit to use.
506 var limit;
507 var before;
508 if (!IS_UNDEFINED(opt_limit)) {
509 limit = opt_limit;
510 } else {
511 limit = kLineLengthLimit;
512 }
513 if (!IS_UNDEFINED(opt_before)) {
514 before = opt_before;
515 } else {
516 // If no before is specified center for small limits and perfer more source
517 // before the the position that after for longer limits.
518 if (limit <= 20) {
519 before = $floor(limit / 2);
520 } else {
521 before = limit - 10;
522 }
523 }
524 if (before >= limit) {
525 before = limit - 1;
526 }
527
528 // If the [start, end[ interval is too big we restrict
529 // it in one or both ends. We make sure to always produce
530 // restricted intervals of maximum allowed size.
531 if (this.end - this.start > limit) {
532 var start_limit = this.position - before;
533 var end_limit = this.position + limit - before;
534 if (this.start < start_limit && end_limit < this.end) {
535 this.start = start_limit;
536 this.end = end_limit;
537 } else if (this.start < start_limit) {
538 this.start = this.end - limit;
539 } else {
540 this.end = this.start + limit;
541 }
542 }
543};
544
545
546/**
547 * Get the source text for a SourceLocation
548 * @return {String}
549 * Source text for this location.
550 */
551SourceLocation.prototype.sourceText = function () {
552 return StringSubstring.call(this.script.source, this.start, this.end);
553};
554
555
556/**
557 * Class for a source slice. A source slice is a part of a script source with
558 * the following properties:
559 * script : script object for the source
560 * from_line : line number for the first line in the slice
561 * to_line : source line number for the last line in the slice
562 * from_position : position of the first character in the slice
563 * to_position : position of the last character in the slice
564 * The to_line and to_position are not included in the slice, that is the lines
565 * in the slice are [from_line, to_line[. Likewise the characters in the slice
566 * are [from_position, to_position[.
567 * @param {Script} script The Script object for the source slice
568 * @param {number} from_line
569 * @param {number} to_line
570 * @param {number} from_position
571 * @param {number} to_position
572 * @constructor
573 */
574function SourceSlice(script, from_line, to_line, from_position, to_position) {
575 this.script = script;
576 this.from_line = from_line;
577 this.to_line = to_line;
578 this.from_position = from_position;
579 this.to_position = to_position;
580}
581
582
583/**
584 * Get the source text for a SourceSlice
585 * @return {String} Source text for this slice. The last line will include
586 * the line terminating characters (if any)
587 */
588SourceSlice.prototype.sourceText = function () {
589 return StringSubstring.call(this.script.source, this.from_position, this.to_position);
590};
591
592
593// Returns the offset of the given position within the containing
594// line.
595function GetPositionInLine(message) {
596 var location = message.script.locationFromPosition(message.startPos, false);
597 if (location == null) return -1;
598 location.restrict();
599 return message.startPos - location.start;
600}
601
602
603function ErrorMessage(type, args, startPos, endPos, script, stackTrace) {
604 this.startPos = startPos;
605 this.endPos = endPos;
606 this.type = type;
607 this.args = args;
608 this.script = script;
609 this.stackTrace = stackTrace;
610}
611
612
613function MakeMessage(type, args, startPos, endPos, script, stackTrace) {
614 return new ErrorMessage(type, args, startPos, endPos, script, stackTrace);
615}
616
617
618function GetStackTraceLine(recv, fun, pos, isGlobal) {
619 return FormatSourcePosition(new CallSite(recv, fun, pos));
620}
621
622// ----------------------------------------------------------------------------
623// Error implementation
624
625// Defines accessors for a property that is calculated the first time
626// the property is read.
627function DefineOneShotAccessor(obj, name, fun) {
628 // Note that the accessors consistently operate on 'obj', not 'this'.
629 // Since the object may occur in someone else's prototype chain we
630 // can't rely on 'this' being the same as 'obj'.
631 var hasBeenSet = false;
632 var value;
633 obj.__defineGetter__(name, function () {
634 if (hasBeenSet) {
635 return value;
636 }
637 hasBeenSet = true;
638 value = fun(obj);
639 return value;
640 });
641 obj.__defineSetter__(name, function (v) {
642 hasBeenSet = true;
643 value = v;
644 });
645}
646
647function CallSite(receiver, fun, pos) {
648 this.receiver = receiver;
649 this.fun = fun;
650 this.pos = pos;
651}
652
653CallSite.prototype.getThis = function () {
654 return this.receiver;
655};
656
657CallSite.prototype.getTypeName = function () {
658 var constructor = this.receiver.constructor;
659 if (!constructor)
660 return $Object.prototype.toString.call(this.receiver);
661 var constructorName = constructor.name;
662 if (!constructorName)
663 return $Object.prototype.toString.call(this.receiver);
664 return constructorName;
665};
666
667CallSite.prototype.isToplevel = function () {
668 if (this.receiver == null)
669 return true;
670 return IS_GLOBAL(this.receiver);
671};
672
673CallSite.prototype.isEval = function () {
674 var script = %FunctionGetScript(this.fun);
Andrei Popescu31002712010-02-23 13:46:05 +0000675 return script && script.compilation_type == COMPILATION_TYPE_EVAL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000676};
677
678CallSite.prototype.getEvalOrigin = function () {
679 var script = %FunctionGetScript(this.fun);
Steve Blockd0582a62009-12-15 09:54:21 +0000680 return FormatEvalOrigin(script);
Steve Blocka7e24c12009-10-30 11:49:00 +0000681};
682
683CallSite.prototype.getFunction = function () {
684 return this.fun;
685};
686
687CallSite.prototype.getFunctionName = function () {
688 // See if the function knows its own name
689 var name = this.fun.name;
690 if (name) {
691 return name;
692 } else {
693 return %FunctionGetInferredName(this.fun);
694 }
695 // Maybe this is an evaluation?
696 var script = %FunctionGetScript(this.fun);
Andrei Popescu31002712010-02-23 13:46:05 +0000697 if (script && script.compilation_type == COMPILATION_TYPE_EVAL)
Steve Blocka7e24c12009-10-30 11:49:00 +0000698 return "eval";
699 return null;
700};
701
702CallSite.prototype.getMethodName = function () {
703 // See if we can find a unique property on the receiver that holds
704 // this function.
705 var ownName = this.fun.name;
706 if (ownName && this.receiver && this.receiver[ownName] === this.fun)
707 // To handle DontEnum properties we guess that the method has
708 // the same name as the function.
709 return ownName;
710 var name = null;
711 for (var prop in this.receiver) {
712 if (this.receiver[prop] === this.fun) {
713 // If we find more than one match bail out to avoid confusion
714 if (name)
715 return null;
716 name = prop;
717 }
718 }
719 if (name)
720 return name;
721 return null;
722};
723
724CallSite.prototype.getFileName = function () {
725 var script = %FunctionGetScript(this.fun);
726 return script ? script.name : null;
727};
728
729CallSite.prototype.getLineNumber = function () {
730 if (this.pos == -1)
731 return null;
732 var script = %FunctionGetScript(this.fun);
733 var location = null;
734 if (script) {
735 location = script.locationFromPosition(this.pos, true);
736 }
737 return location ? location.line + 1 : null;
738};
739
740CallSite.prototype.getColumnNumber = function () {
741 if (this.pos == -1)
742 return null;
743 var script = %FunctionGetScript(this.fun);
744 var location = null;
745 if (script) {
746 location = script.locationFromPosition(this.pos, true);
747 }
Steve Blockd0582a62009-12-15 09:54:21 +0000748 return location ? location.column + 1: null;
Steve Blocka7e24c12009-10-30 11:49:00 +0000749};
750
751CallSite.prototype.isNative = function () {
752 var script = %FunctionGetScript(this.fun);
Andrei Popescu31002712010-02-23 13:46:05 +0000753 return script ? (script.type == TYPE_NATIVE) : false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000754};
755
756CallSite.prototype.getPosition = function () {
757 return this.pos;
758};
759
760CallSite.prototype.isConstructor = function () {
761 var constructor = this.receiver ? this.receiver.constructor : null;
762 if (!constructor)
763 return false;
764 return this.fun === constructor;
765};
766
Steve Blockd0582a62009-12-15 09:54:21 +0000767function FormatEvalOrigin(script) {
768 var eval_origin = "";
769 if (script.eval_from_function_name) {
770 eval_origin += script.eval_from_function_name;
771 } else {
772 eval_origin += "<anonymous>";
773 }
Steve Block6ded16b2010-05-10 14:33:55 +0100774
Steve Blockd0582a62009-12-15 09:54:21 +0000775 var eval_from_script = script.eval_from_script;
776 if (eval_from_script) {
Andrei Popescu31002712010-02-23 13:46:05 +0000777 if (eval_from_script.compilation_type == COMPILATION_TYPE_EVAL) {
Steve Blockd0582a62009-12-15 09:54:21 +0000778 // eval script originated from another eval.
779 eval_origin += " (eval at " + FormatEvalOrigin(eval_from_script) + ")";
780 } else {
781 // eval script originated from "real" scource.
782 if (eval_from_script.name) {
783 eval_origin += " (" + eval_from_script.name;
784 var location = eval_from_script.locationFromPosition(script.eval_from_script_position, true);
785 if (location) {
786 eval_origin += ":" + (location.line + 1);
787 eval_origin += ":" + (location.column + 1);
788 }
789 eval_origin += ")"
790 } else {
791 eval_origin += " (unknown source)";
792 }
793 }
794 }
Steve Block6ded16b2010-05-10 14:33:55 +0100795
Steve Blockd0582a62009-12-15 09:54:21 +0000796 return eval_origin;
797};
798
Steve Blocka7e24c12009-10-30 11:49:00 +0000799function FormatSourcePosition(frame) {
800 var fileLocation = "";
801 if (frame.isNative()) {
802 fileLocation = "native";
803 } else if (frame.isEval()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000804 fileLocation = "eval at " + frame.getEvalOrigin();
Steve Blocka7e24c12009-10-30 11:49:00 +0000805 } else {
806 var fileName = frame.getFileName();
807 if (fileName) {
808 fileLocation += fileName;
809 var lineNumber = frame.getLineNumber();
810 if (lineNumber != null) {
811 fileLocation += ":" + lineNumber;
812 var columnNumber = frame.getColumnNumber();
813 if (columnNumber) {
814 fileLocation += ":" + columnNumber;
815 }
816 }
817 }
818 }
819 if (!fileLocation) {
820 fileLocation = "unknown source";
821 }
822 var line = "";
823 var functionName = frame.getFunction().name;
824 var methodName = frame.getMethodName();
825 var addPrefix = true;
826 var isConstructor = frame.isConstructor();
827 var isMethodCall = !(frame.isToplevel() || isConstructor);
828 if (isMethodCall) {
829 line += frame.getTypeName() + ".";
830 if (functionName) {
831 line += functionName;
832 if (methodName && (methodName != functionName)) {
833 line += " [as " + methodName + "]";
834 }
835 } else {
836 line += methodName || "<anonymous>";
837 }
838 } else if (isConstructor) {
839 line += "new " + (functionName || "<anonymous>");
840 } else if (functionName) {
841 line += functionName;
842 } else {
843 line += fileLocation;
844 addPrefix = false;
845 }
846 if (addPrefix) {
847 line += " (" + fileLocation + ")";
848 }
849 return line;
850}
851
852function FormatStackTrace(error, frames) {
853 var lines = [];
854 try {
855 lines.push(error.toString());
856 } catch (e) {
857 try {
858 lines.push("<error: " + e + ">");
859 } catch (ee) {
860 lines.push("<error>");
861 }
862 }
863 for (var i = 0; i < frames.length; i++) {
864 var frame = frames[i];
865 var line;
866 try {
867 line = FormatSourcePosition(frame);
868 } catch (e) {
869 try {
870 line = "<error: " + e + ">";
871 } catch (ee) {
872 // Any code that reaches this point is seriously nasty!
873 line = "<error>";
874 }
875 }
876 lines.push(" at " + line);
877 }
878 return lines.join("\n");
879}
880
881function FormatRawStackTrace(error, raw_stack) {
882 var frames = [ ];
883 for (var i = 0; i < raw_stack.length; i += 3) {
884 var recv = raw_stack[i];
885 var fun = raw_stack[i+1];
886 var pc = raw_stack[i+2];
887 var pos = %FunctionGetPositionForOffset(fun, pc);
888 frames.push(new CallSite(recv, fun, pos));
889 }
890 if (IS_FUNCTION($Error.prepareStackTrace)) {
891 return $Error.prepareStackTrace(error, frames);
892 } else {
893 return FormatStackTrace(error, frames);
894 }
895}
896
897function DefineError(f) {
898 // Store the error function in both the global object
899 // and the runtime object. The function is fetched
900 // from the runtime object when throwing errors from
901 // within the runtime system to avoid strange side
902 // effects when overwriting the error functions from
903 // user code.
904 var name = f.name;
905 %SetProperty(global, name, f, DONT_ENUM);
906 this['$' + name] = f;
907 // Configure the error function.
908 if (name == 'Error') {
909 // The prototype of the Error object must itself be an error.
910 // However, it can't be an instance of the Error object because
911 // it hasn't been properly configured yet. Instead we create a
912 // special not-a-true-error-but-close-enough object.
913 function ErrorPrototype() {}
914 %FunctionSetPrototype(ErrorPrototype, $Object.prototype);
915 %FunctionSetInstanceClassName(ErrorPrototype, 'Error');
916 %FunctionSetPrototype(f, new ErrorPrototype());
917 } else {
918 %FunctionSetPrototype(f, new $Error());
919 }
920 %FunctionSetInstanceClassName(f, 'Error');
921 %SetProperty(f.prototype, 'constructor', f, DONT_ENUM);
922 f.prototype.name = name;
923 %SetCode(f, function(m) {
924 if (%_IsConstructCall()) {
925 if (m === kAddMessageAccessorsMarker) {
926 DefineOneShotAccessor(this, 'message', function (obj) {
927 return FormatMessage({type: obj.type, args: obj.arguments});
928 });
929 } else if (!IS_UNDEFINED(m)) {
930 this.message = ToString(m);
931 }
932 captureStackTrace(this, f);
933 } else {
934 return new f(m);
935 }
936 });
937}
938
939function captureStackTrace(obj, cons_opt) {
940 var stackTraceLimit = $Error.stackTraceLimit;
941 if (!stackTraceLimit) return;
942 if (stackTraceLimit < 0 || stackTraceLimit > 10000)
943 stackTraceLimit = 10000;
944 var raw_stack = %CollectStackTrace(cons_opt ? cons_opt : captureStackTrace,
945 stackTraceLimit);
946 DefineOneShotAccessor(obj, 'stack', function (obj) {
947 return FormatRawStackTrace(obj, raw_stack);
948 });
949};
950
951$Math.__proto__ = global.Object.prototype;
952
953DefineError(function Error() { });
954DefineError(function TypeError() { });
955DefineError(function RangeError() { });
956DefineError(function SyntaxError() { });
957DefineError(function ReferenceError() { });
958DefineError(function EvalError() { });
959DefineError(function URIError() { });
960
961$Error.captureStackTrace = captureStackTrace;
962
963// Setup extra properties of the Error.prototype object.
964$Error.prototype.message = '';
965
966%SetProperty($Error.prototype, 'toString', function toString() {
967 var type = this.type;
968 if (type && !this.hasOwnProperty("message")) {
969 return this.name + ": " + FormatMessage({ type: type, args: this.arguments });
970 }
971 var message = this.message;
972 return this.name + (message ? (": " + message) : "");
973}, DONT_ENUM);
974
975
976// Boilerplate for exceptions for stack overflows. Used from
977// Top::StackOverflow().
978const kStackOverflowBoilerplate = MakeRangeError('stack_overflow', []);