debug: Add verbose stacktrace function.

Zev and I found this useful for debugging what's happening inside
casperjs today.

(imported from commit 6fb42165c4ff138ba3417ac2ee0db92040e49fa4)
This commit is contained in:
Tim Abbott 2013-03-05 15:31:09 -05:00
parent 27d91eb9ea
commit 618183d065
1 changed files with 45 additions and 0 deletions

View File

@ -25,3 +25,48 @@ function print_elapsed_time(name, fun) {
console.log(name + ': ' + (t1 - t0) + ' ms');
return out;
}
// Javascript stack trac functionality, adapted from:
// https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js
// The first function is just a helper.
function stringifyArguments(args) {
var i, result = [];
var slice = Array.prototype.slice;
for (i = 0; i < args.length; ++i) {
var arg = args[i];
if (arg === undefined) {
result[i] = 'undefined';
} else if (arg === null) {
result[i] = 'null';
} else if (arg.constructor) {
if (arg.constructor === Array) {
if (arg.length < 3) {
result[i] = '[' + stringifyArguments(arg) + ']';
} else {
result[i] = '[' + stringifyArguments(slice.call(arg, 0, 1)) + '...' + stringifyArguments(slice.call(arg, -1)) + ']';
}
} else if (arg.constructor === Object) {
result[i] = '#object';
} else if (arg.constructor === Function) {
result[i] = '#function';
} else if (arg.constructor === String) {
result[i] = '"' + arg + '"';
} else if (arg.constructor === Number) {
result[i] = arg;
}
}
}
return result.join(',');
}
// Usage: console.log(verbose_stacktrace(arguments.callee));
function verbose_stacktrace(curr) {
var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], fn, args, maxStackSize = 50;
while (curr && curr['arguments'] && stack.length < maxStackSize) {
fn = curr.toString();
args = Array.prototype.slice.call(curr['arguments'] || []);
stack[stack.length] = fn + '(' + stringifyArguments(args) + ')';
curr = curr.caller;
}
return stack;
}