1 // sample on how to use the parser and walker API to instrument some code
3 var jsp = require("uglify-js").parser;
4 var pro = require("uglify-js").uglify;
6 function instrument(code) {
7 var ast = jsp.parse(code, false, true); // true for the third arg specifies that we want
8 // to have start/end tokens embedded in the
10 var w = pro.ast_walker();
12 // we're gonna need this to push elements that we're currently looking at, to avoid
17 if (this[0].start && analyzing.indexOf(this) < 0) {
18 // without the `analyzing' hack, w.walk(this) would re-enter here leading
19 // to infinite recursion
21 ret = [ "splice", // XXX: "block" is safer
23 [ "call", [ "name", "trace" ],
24 [ [ "string", this[0].toString() ],
25 [ "num", this[0].start.line ],
26 [ "num", this[0].start.col ],
27 [ "num", this[0].end.line ],
28 [ "num", this[0].end.col ]]]],
34 var new_ast = w.with_walkers({
56 return pro.gen_code(new_ast, { beautify: true });
62 ////// test code follows.
64 var code = instrument(test.toString());
75 const bar = 6, baz = 7;
77 // switch block. note we can't track case lines the same way.
86 for (var i = 0; i < 5; ++i) {
87 console.log("Hello " + i);
89 for (var i in [ 1, 2, 3]) {
93 // note however that the following is broken. I guess we
94 // should add the block brackets in this case...
95 for (var i = 0; i < 5; ++i)