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