UNPKG

45.1 kBJavaScriptView Raw
1/*
2 Copyright (c) 2012, Yahoo! Inc. All rights reserved.
3 Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
4 */
5
6/*global esprima, escodegen, window */
7(function (isNode) {
8 "use strict";
9 var SYNTAX,
10 nodeType,
11 ESP = isNode ? require('esprima') : esprima,
12 ESPGEN = isNode ? require('escodegen') : escodegen, //TODO - package as dependency
13 crypto = isNode ? require('crypto') : null,
14 LEADER_WRAP = '(function () { ',
15 TRAILER_WRAP = '\n}());',
16 COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/,
17 astgen,
18 preconditions,
19 cond,
20 isArray = Array.isArray;
21
22 /* istanbul ignore if: untestable */
23 if (!isArray) {
24 isArray = function (thing) { return thing && Object.prototype.toString.call(thing) === '[object Array]'; };
25 }
26
27 if (!isNode) {
28 preconditions = {
29 'Could not find esprima': ESP,
30 'Could not find escodegen': ESPGEN,
31 'JSON object not in scope': JSON,
32 'Array does not implement push': [].push,
33 'Array does not implement unshift': [].unshift
34 };
35 /* istanbul ignore next: untestable */
36 for (cond in preconditions) {
37 if (preconditions.hasOwnProperty(cond)) {
38 if (!preconditions[cond]) { throw new Error(cond); }
39 }
40 }
41 }
42
43 function generateTrackerVar(filename, omitSuffix) {
44 var hash, suffix;
45 if (crypto !== null) {
46 hash = crypto.createHash('md5');
47 hash.update(filename);
48 suffix = hash.digest('base64');
49 //trim trailing equal signs, turn identifier unsafe chars to safe ones + => _ and / => $
50 suffix = suffix.replace(new RegExp('=', 'g'), '')
51 .replace(new RegExp('\\+', 'g'), '_')
52 .replace(new RegExp('/', 'g'), '$');
53 } else {
54 window.__cov_seq = window.__cov_seq || 0;
55 window.__cov_seq += 1;
56 suffix = window.__cov_seq;
57 }
58 return '__cov_' + (omitSuffix ? '' : suffix);
59 }
60
61 function pushAll(ary, thing) {
62 if (!isArray(thing)) {
63 thing = [ thing ];
64 }
65 Array.prototype.push.apply(ary, thing);
66 }
67
68 SYNTAX = {
69 // keep in sync with estraverse's VisitorKeys
70 AssignmentExpression: ['left', 'right'],
71 AssignmentPattern: ['left', 'right'],
72 ArrayExpression: ['elements'],
73 ArrayPattern: ['elements'],
74 ArrowFunctionExpression: ['params', 'body'],
75 AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
76 BlockStatement: ['body'],
77 BinaryExpression: ['left', 'right'],
78 BreakStatement: ['label'],
79 CallExpression: ['callee', 'arguments'],
80 CatchClause: ['param', 'body'],
81 ClassBody: ['body'],
82 ClassDeclaration: ['id', 'superClass', 'body'],
83 ClassExpression: ['id', 'superClass', 'body'],
84 ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
85 ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
86 ConditionalExpression: ['test', 'consequent', 'alternate'],
87 ContinueStatement: ['label'],
88 DebuggerStatement: [],
89 DirectiveStatement: [],
90 DoWhileStatement: ['body', 'test'],
91 EmptyStatement: [],
92 ExportAllDeclaration: ['source'],
93 ExportDefaultDeclaration: ['declaration'],
94 ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
95 ExportSpecifier: ['exported', 'local'],
96 ExpressionStatement: ['expression'],
97 ForStatement: ['init', 'test', 'update', 'body'],
98 ForInStatement: ['left', 'right', 'body'],
99 ForOfStatement: ['left', 'right', 'body'],
100 FunctionDeclaration: ['id', 'params', 'body'],
101 FunctionExpression: ['id', 'params', 'body'],
102 GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
103 Identifier: [],
104 IfStatement: ['test', 'consequent', 'alternate'],
105 ImportDeclaration: ['specifiers', 'source'],
106 ImportDefaultSpecifier: ['local'],
107 ImportNamespaceSpecifier: ['local'],
108 ImportSpecifier: ['imported', 'local'],
109 Literal: [],
110 LabeledStatement: ['label', 'body'],
111 LogicalExpression: ['left', 'right'],
112 MetaProperty: ['meta', 'property'],
113 MemberExpression: ['object', 'property'],
114 MethodDefinition: ['key', 'value'],
115 ModuleSpecifier: [],
116 NewExpression: ['callee', 'arguments'],
117 ObjectExpression: ['properties'],
118 ObjectPattern: ['properties'],
119 Program: ['body'],
120 Property: ['key', 'value'],
121 RestElement: [ 'argument' ],
122 ReturnStatement: ['argument'],
123 SequenceExpression: ['expressions'],
124 SpreadElement: ['argument'],
125 Super: [],
126 SwitchStatement: ['discriminant', 'cases'],
127 SwitchCase: ['test', 'consequent'],
128 TaggedTemplateExpression: ['tag', 'quasi'],
129 TemplateElement: [],
130 TemplateLiteral: ['quasis', 'expressions'],
131 ThisExpression: [],
132 ThrowStatement: ['argument'],
133 TryStatement: ['block', 'handler', 'finalizer'],
134 UnaryExpression: ['argument'],
135 UpdateExpression: ['argument'],
136 VariableDeclaration: ['declarations'],
137 VariableDeclarator: ['id', 'init'],
138 WhileStatement: ['test', 'body'],
139 WithStatement: ['object', 'body'],
140 YieldExpression: ['argument']
141 };
142
143 for (nodeType in SYNTAX) {
144 /* istanbul ignore else: has own property */
145 if (SYNTAX.hasOwnProperty(nodeType)) {
146 SYNTAX[nodeType] = { name: nodeType, children: SYNTAX[nodeType] };
147 }
148 }
149
150 astgen = {
151 variable: function (name) { return { type: SYNTAX.Identifier.name, name: name }; },
152 stringLiteral: function (str) { return { type: SYNTAX.Literal.name, value: String(str) }; },
153 numericLiteral: function (num) { return { type: SYNTAX.Literal.name, value: Number(num) }; },
154 statement: function (contents) { return { type: SYNTAX.ExpressionStatement.name, expression: contents }; },
155 dot: function (obj, field) { return { type: SYNTAX.MemberExpression.name, computed: false, object: obj, property: field }; },
156 subscript: function (obj, sub) { return { type: SYNTAX.MemberExpression.name, computed: true, object: obj, property: sub }; },
157 postIncrement: function (obj) { return { type: SYNTAX.UpdateExpression.name, operator: '++', prefix: false, argument: obj }; },
158 sequence: function (one, two) { return { type: SYNTAX.SequenceExpression.name, expressions: [one, two] }; },
159 returnStatement: function (expr) { return { type: SYNTAX.ReturnStatement.name, argument: expr }; }
160 };
161
162 function Walker(walkMap, preprocessor, scope, debug) {
163 this.walkMap = walkMap;
164 this.preprocessor = preprocessor;
165 this.scope = scope;
166 this.debug = debug;
167 if (this.debug) {
168 this.level = 0;
169 this.seq = true;
170 }
171 }
172
173 function defaultWalker(node, walker) {
174
175 var type = node.type,
176 preprocessor,
177 postprocessor,
178 children = SYNTAX[type],
179 // don't run generated nodes thru custom walks otherwise we will attempt to instrument the instrumentation code :)
180 applyCustomWalker = !!node.loc || node.type === SYNTAX.Program.name,
181 walkerFn = applyCustomWalker ? walker.walkMap[type] : null,
182 i,
183 j,
184 walkFnIndex,
185 childType,
186 childNode,
187 ret,
188 childArray,
189 childElement,
190 pathElement,
191 assignNode,
192 isLast;
193
194 if (!SYNTAX[type]) {
195 console.error(node);
196 console.error('Unsupported node type:' + type);
197 return;
198 }
199 children = SYNTAX[type].children;
200 /* istanbul ignore if: guard */
201 if (node.walking) { throw new Error('Infinite regress: Custom walkers may NOT call walker.apply(node)'); }
202 node.walking = true;
203
204 ret = walker.apply(node, walker.preprocessor);
205
206 preprocessor = ret.preprocessor;
207 if (preprocessor) {
208 delete ret.preprocessor;
209 ret = walker.apply(node, preprocessor);
210 }
211
212 if (isArray(walkerFn)) {
213 for (walkFnIndex = 0; walkFnIndex < walkerFn.length; walkFnIndex += 1) {
214 isLast = walkFnIndex === walkerFn.length - 1;
215 ret = walker.apply(ret, walkerFn[walkFnIndex]);
216 /*istanbul ignore next: paranoid check */
217 if (ret.type !== type && !isLast) {
218 throw new Error('Only the last walker is allowed to change the node type: [type was: ' + type + ' ]');
219 }
220 }
221 } else {
222 if (walkerFn) {
223 ret = walker.apply(node, walkerFn);
224 }
225 }
226
227 if (node.skipSelf) {
228 return;
229 }
230
231 for (i = 0; i < children.length; i += 1) {
232 childType = children[i];
233 childNode = node[childType];
234 if (childNode && !childNode.skipWalk) {
235 pathElement = { node: node, property: childType };
236 if (isArray(childNode)) {
237 childArray = [];
238 for (j = 0; j < childNode.length; j += 1) {
239 childElement = childNode[j];
240 pathElement.index = j;
241 if (childElement) {
242 assignNode = walker.apply(childElement, null, pathElement);
243 if (isArray(assignNode.prepend)) {
244 pushAll(childArray, assignNode.prepend);
245 delete assignNode.prepend;
246 }
247 } else {
248 assignNode = undefined;
249 }
250 pushAll(childArray, assignNode);
251 }
252 node[childType] = childArray;
253 } else {
254 assignNode = walker.apply(childNode, null, pathElement);
255 /*istanbul ignore if: paranoid check */
256 if (isArray(assignNode.prepend)) {
257 throw new Error('Internal error: attempt to prepend statements in disallowed (non-array) context');
258 /* if this should be allowed, this is how to solve it
259 tmpNode = { type: 'BlockStatement', body: [] };
260 pushAll(tmpNode.body, assignNode.prepend);
261 pushAll(tmpNode.body, assignNode);
262 node[childType] = tmpNode;
263 delete assignNode.prepend;
264 */
265 } else {
266 node[childType] = assignNode;
267 }
268 }
269 }
270 }
271
272 postprocessor = ret.postprocessor;
273 if (postprocessor) {
274 delete ret.postprocessor;
275 ret = walker.apply(ret, postprocessor);
276 }
277
278 delete node.walking;
279
280 return ret;
281 }
282
283 Walker.prototype = {
284 startWalk: function (node) {
285 this.path = [];
286 this.apply(node);
287 },
288
289 apply: function (node, walkFn, pathElement) {
290 var ret, i, seq, prefix;
291
292 walkFn = walkFn || defaultWalker;
293 if (this.debug) {
294 this.seq += 1;
295 this.level += 1;
296 seq = this.seq;
297 prefix = '';
298 for (i = 0; i < this.level; i += 1) { prefix += ' '; }
299 console.log(prefix + 'Enter (' + seq + '):' + node.type);
300 }
301 if (pathElement) { this.path.push(pathElement); }
302 ret = walkFn.call(this.scope, node, this);
303 if (pathElement) { this.path.pop(); }
304 if (this.debug) {
305 this.level -= 1;
306 console.log(prefix + 'Return (' + seq + '):' + node.type);
307 }
308 return ret || node;
309 },
310
311 startLineForNode: function (node) {
312 return node && node.loc && node.loc.start ? node.loc.start.line : /* istanbul ignore next: guard */ null;
313 },
314
315 ancestor: function (n) {
316 return this.path.length > n - 1 ? this.path[this.path.length - n] : /* istanbul ignore next: guard */ null;
317 },
318
319 parent: function () {
320 return this.ancestor(1);
321 },
322
323 isLabeled: function () {
324 var el = this.parent();
325 return el && el.node.type === SYNTAX.LabeledStatement.name;
326 }
327 };
328
329 /**
330 * mechanism to instrument code for coverage. It uses the `esprima` and
331 * `escodegen` libraries for JS parsing and code generation respectively.
332 *
333 * Works on `node` as well as the browser.
334 *
335 * Usage on nodejs
336 * ---------------
337 *
338 * var instrumenter = new require('istanbul').Instrumenter(),
339 * changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
340 *
341 * Usage in a browser
342 * ------------------
343 *
344 * Load `esprima.js`, `escodegen.js` and `instrumenter.js` (this file) using `script` tags or other means.
345 *
346 * Create an instrumenter object as:
347 *
348 * var instrumenter = new Instrumenter(),
349 * changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
350 *
351 * Aside from demonstration purposes, it is unclear why you would want to instrument code in a browser.
352 *
353 * @class Instrumenter
354 * @constructor
355 * @param {Object} options Optional. Configuration options.
356 * @param {String} [options.coverageVariable] the global variable name to use for
357 * tracking coverage. Defaults to `__coverage__`
358 * @param {Boolean} [options.embedSource] whether to embed the source code of every
359 * file as an array in the file coverage object for that file. Defaults to `false`
360 * @param {Boolean} [options.preserveComments] whether comments should be preserved in the output. Defaults to `false`
361 * @param {Boolean} [options.noCompact] emit readable code when set. Defaults to `false`
362 * @param {Boolean} [options.esModules] whether the code to instrument contains uses es
363 * imports or exports.
364 * @param {Boolean} [options.noAutoWrap] do not automatically wrap the source in
365 * an anonymous function before covering it. By default, code is wrapped in
366 * an anonymous function before it is parsed. This is done because
367 * some nodejs libraries have `return` statements outside of
368 * a function which is technically invalid Javascript and causes the parser to fail.
369 * This construct, however, works correctly in node since module loading
370 * is done in the context of an anonymous function.
371 *
372 * Note that the semantics of the code *returned* by the instrumenter does not change in any way.
373 * The function wrapper is "unwrapped" before the instrumented code is generated.
374 * @param {Object} [options.codeGenerationOptions] an object that is directly passed to the `escodegen`
375 * library as configuration for code generation. The `noCompact` setting is not honored when this
376 * option is specified
377 * @param {Boolean} [options.debug] assist in debugging. Currently, the only effect of
378 * setting this option is a pretty-print of the coverage variable. Defaults to `false`
379 * @param {Boolean} [options.walkDebug] assist in debugging of the AST walker used by this class.
380 *
381 */
382 function Instrumenter(options) {
383 this.opts = options || {
384 debug: false,
385 walkDebug: false,
386 coverageVariable: '__coverage__',
387 codeGenerationOptions: undefined,
388 noAutoWrap: false,
389 noCompact: false,
390 embedSource: false,
391 preserveComments: false,
392 esModules: false
393 };
394
395 if (this.opts.esModules && !this.opts.noAutoWrap) {
396 this.opts.noAutoWrap = true;
397 if (this.opts.debug) {
398 console.log('Setting noAutoWrap to true as required by esModules');
399 }
400 }
401
402 this.walker = new Walker({
403 ArrowFunctionExpression: [ this.arrowBlockConverter ],
404 ExpressionStatement: this.coverStatement,
405 ExportNamedDeclaration: this.coverExport,
406 BreakStatement: this.coverStatement,
407 ContinueStatement: this.coverStatement,
408 DebuggerStatement: this.coverStatement,
409 ReturnStatement: this.coverStatement,
410 ThrowStatement: this.coverStatement,
411 TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
412 VariableDeclaration: this.coverStatement,
413 IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
414 ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
415 ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
416 ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
417 WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
418 DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
419 SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
420 SwitchCase: [ this.switchCaseInjector ],
421 WithStatement: [ this.withBlockConverter, this.coverStatement ],
422 FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
423 FunctionExpression: this.coverFunction,
424 LabeledStatement: this.coverStatement,
425 ConditionalExpression: this.conditionalBranchInjector,
426 LogicalExpression: this.logicalExpressionBranchInjector,
427 ObjectExpression: this.maybeAddType,
428 MetaProperty: this.coverMetaProperty,
429 }, this.extractCurrentHint, this, this.opts.walkDebug);
430
431 //unit testing purposes only
432 if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
433 this.omitTrackerSuffix = true;
434 }
435 }
436
437 Instrumenter.prototype = {
438 /**
439 * synchronous instrumentation method. Throws when illegal code is passed to it
440 * @method instrumentSync
441 * @param {String} code the code to be instrumented as a String
442 * @param {String} filename Optional. The name of the file from which
443 * the code was read. A temporary filename is generated when not specified.
444 * Not specifying a filename is only useful for unit tests and demonstrations
445 * of this library.
446 */
447 instrumentSync: function (code, filename) {
448 var program;
449
450 //protect from users accidentally passing in a Buffer object instead
451 if (typeof code !== 'string') { throw new Error('Code must be string'); }
452 if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't affect syntax tree locations for things we care about
453 code = '//' + code;
454 }
455 if (!this.opts.noAutoWrap) {
456 code = LEADER_WRAP + code + TRAILER_WRAP;
457 }
458 try {
459 program = ESP.parse(code, {
460 loc: true,
461 range: true,
462 tokens: this.opts.preserveComments,
463 comment: true,
464 sourceType: this.opts.esModules ? 'module' : 'script'
465 });
466 } catch (e) {
467 console.log('Failed to parse file: ' + filename);
468 throw e;
469 }
470 if (this.opts.preserveComments) {
471 program = ESPGEN.attachComments(program, program.comments, program.tokens);
472 }
473 if (!this.opts.noAutoWrap) {
474 program = {
475 type: SYNTAX.Program.name,
476 body: program.body[0].expression.callee.body.body,
477 comments: program.comments
478 };
479 }
480 return this.instrumentASTSync(program, filename, code);
481 },
482 filterHints: function (comments) {
483 var ret = [],
484 i,
485 comment,
486 groups;
487 if (!(comments && isArray(comments))) {
488 return ret;
489 }
490 for (i = 0; i < comments.length; i += 1) {
491 comment = comments[i];
492 /* istanbul ignore else: paranoid check */
493 if (comment && comment.value && comment.range && isArray(comment.range)) {
494 groups = String(comment.value).match(COMMENT_RE);
495 if (groups) {
496 ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] });
497 }
498 }
499 }
500 return ret;
501 },
502 extractCurrentHint: function (node) {
503 if (!node.range) { return; }
504 var i = this.currentState.lastHintPosition + 1,
505 hints = this.currentState.hints,
506 nodeStart = node.range[0],
507 hint;
508 this.currentState.currentHint = null;
509 while (i < hints.length) {
510 hint = hints[i];
511 if (hint.end < nodeStart) {
512 this.currentState.currentHint = hint;
513 this.currentState.lastHintPosition = i;
514 i += 1;
515 } else {
516 break;
517 }
518 }
519 },
520 /**
521 * synchronous instrumentation method that instruments an AST instead.
522 * @method instrumentASTSync
523 * @param {String} program the AST to be instrumented
524 * @param {String} filename Optional. The name of the file from which
525 * the code was read. A temporary filename is generated when not specified.
526 * Not specifying a filename is only useful for unit tests and demonstrations
527 * of this library.
528 * @param {String} originalCode the original code corresponding to the AST,
529 * used for embedding the source into the coverage object
530 */
531 instrumentASTSync: function (program, filename, originalCode) {
532 var usingStrict = false,
533 codegenOptions,
534 generated,
535 preamble,
536 lineCount,
537 i;
538 filename = filename || String(new Date().getTime()) + '.js';
539 this.sourceMap = null;
540 this.coverState = {
541 path: filename,
542 s: {},
543 b: {},
544 f: {},
545 fnMap: {},
546 statementMap: {},
547 branchMap: {}
548 };
549 this.currentState = {
550 trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix),
551 func: 0,
552 branch: 0,
553 variable: 0,
554 statement: 0,
555 hints: this.filterHints(program.comments),
556 currentHint: null,
557 lastHintPosition: -1,
558 ignoring: 0
559 };
560 if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) {
561 //nuke it
562 program.body.shift();
563 //and add it back at code generation time
564 usingStrict = true;
565 }
566 this.walker.startWalk(program);
567 codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }};
568 codegenOptions.comment = this.opts.preserveComments;
569 //console.log(JSON.stringify(program, undefined, 2));
570
571 generated = ESPGEN.generate(program, codegenOptions);
572 preamble = this.getPreamble(originalCode || '', usingStrict);
573
574 if (generated.map && generated.code) {
575 lineCount = preamble.split(/\r\n|\r|\n/).length;
576 // offset all the generated line numbers by the number of lines in the preamble
577 for (i = 0; i < generated.map._mappings._array.length; i += 1) {
578 generated.map._mappings._array[i].generatedLine += lineCount;
579 }
580 this.sourceMap = generated.map;
581 generated = generated.code;
582 }
583
584 return preamble + '\n' + generated + '\n';
585 },
586 /**
587 * Callback based instrumentation. Note that this still executes synchronously in the same process tick
588 * and calls back immediately. It only provides the options for callback style error handling as
589 * opposed to a `try-catch` style and nothing more. Implemented as a wrapper over `instrumentSync`
590 *
591 * @method instrument
592 * @param {String} code the code to be instrumented as a String
593 * @param {String} filename Optional. The name of the file from which
594 * the code was read. A temporary filename is generated when not specified.
595 * Not specifying a filename is only useful for unit tests and demonstrations
596 * of this library.
597 * @param {Function(err, instrumentedCode)} callback - the callback function
598 */
599 instrument: function (code, filename, callback) {
600
601 if (!callback && typeof filename === 'function') {
602 callback = filename;
603 filename = null;
604 }
605 try {
606 callback(null, this.instrumentSync(code, filename));
607 } catch (ex) {
608 callback(ex);
609 }
610 },
611 /**
612 * returns the file coverage object for the code that was instrumented
613 * just before calling this method. Note that this represents a
614 * "zero-coverage" object which is not even representative of the code
615 * being loaded in node or a browser (which would increase the statement
616 * counts for mainline code).
617 * @method lastFileCoverage
618 * @return {Object} a "zero-coverage" file coverage object for the code last instrumented
619 * by this instrumenter
620 */
621 lastFileCoverage: function () {
622 return this.coverState;
623 },
624 /**
625 * returns the source map object for the code that was instrumented
626 * just before calling this method.
627 * @method lastSourceMap
628 * @return {Object} a source map object for the code last instrumented
629 * by this instrumenter
630 */
631 lastSourceMap: function () {
632 return this.sourceMap;
633 },
634 fixColumnPositions: function (coverState) {
635 var offset = LEADER_WRAP.length,
636 fixer = function (loc) {
637 if (loc.start.line === 1) {
638 loc.start.column -= offset;
639 }
640 if (loc.end.line === 1) {
641 loc.end.column -= offset;
642 }
643 },
644 k,
645 obj,
646 i,
647 locations;
648
649 obj = coverState.statementMap;
650 for (k in obj) {
651 /* istanbul ignore else: has own property */
652 if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
653 }
654 obj = coverState.fnMap;
655 for (k in obj) {
656 /* istanbul ignore else: has own property */
657 if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
658 }
659 obj = coverState.branchMap;
660 for (k in obj) {
661 /* istanbul ignore else: has own property */
662 if (obj.hasOwnProperty(k)) {
663 locations = obj[k].locations;
664 for (i = 0; i < locations.length; i += 1) {
665 fixer(locations[i]);
666 }
667 }
668 }
669 },
670
671 getPreamble: function (sourceCode, emitUseStrict) {
672 var varName = this.opts.coverageVariable || '__coverage__',
673 file = this.coverState.path.replace(/\\/g, '\\\\'),
674 tracker = this.currentState.trackerVar,
675 coverState,
676 strictLine = emitUseStrict ? '"use strict";' : '',
677 // return replacements using the function to ensure that the replacement is
678 // treated like a dumb string and not as a string with RE replacement patterns
679 replacer = function (s) {
680 return function () { return s; };
681 },
682 code;
683 if (!this.opts.noAutoWrap) {
684 this.fixColumnPositions(this.coverState);
685 }
686 if (this.opts.embedSource) {
687 this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
688 }
689 coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState);
690 code = [
691 "%STRICT%",
692 "var %VAR% = (Function('return this'))();",
693 "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
694 "%VAR% = %VAR%.%GLOBAL%;",
695 "if (!(%VAR%['%FILE%'])) {",
696 " %VAR%['%FILE%'] = %OBJECT%;",
697 "}",
698 "%VAR% = %VAR%['%FILE%'];"
699 ].join("\n")
700 .replace(/%STRICT%/g, replacer(strictLine))
701 .replace(/%VAR%/g, replacer(tracker))
702 .replace(/%GLOBAL%/g, replacer(varName))
703 .replace(/%FILE%/g, replacer(file))
704 .replace(/%OBJECT%/g, replacer(coverState));
705 return code;
706 },
707
708 startIgnore: function () {
709 this.currentState.ignoring += 1;
710 },
711
712 endIgnore: function () {
713 this.currentState.ignoring -= 1;
714 },
715
716 convertToBlock: function (node) {
717 if (!node) {
718 return { type: 'BlockStatement', body: [] };
719 } else if (node.type === 'BlockStatement') {
720 return node;
721 } else {
722 return { type: 'BlockStatement', body: [ node ] };
723 }
724 },
725
726 arrowBlockConverter: function (node) {
727 var retStatement;
728 if (node.expression) { // turn expression nodes into a block with a return statement
729 retStatement = astgen.returnStatement(node.body);
730 // ensure the generated return statement is covered
731 retStatement.loc = node.body.loc;
732 node.body = this.convertToBlock(retStatement);
733 node.expression = false;
734 }
735 },
736
737 paranoidHandlerCheck: function (node) {
738 // if someone is using an older esprima on the browser
739 // convert handlers array to single handler attribute
740 // containing its first element
741 /* istanbul ignore next */
742 if (!node.handler && node.handlers) {
743 node.handler = node.handlers[0];
744 }
745 },
746
747 ifBlockConverter: function (node) {
748 node.consequent = this.convertToBlock(node.consequent);
749 node.alternate = this.convertToBlock(node.alternate);
750 },
751
752 loopBlockConverter: function (node) {
753 node.body = this.convertToBlock(node.body);
754 },
755
756 withBlockConverter: function (node) {
757 node.body = this.convertToBlock(node.body);
758 },
759
760 statementName: function (location, initValue) {
761 var sName,
762 ignoring = !!this.currentState.ignoring;
763
764 location.skip = ignoring || undefined;
765 initValue = initValue || 0;
766 this.currentState.statement += 1;
767 sName = this.currentState.statement;
768 this.coverState.statementMap[sName] = location;
769 this.coverState.s[sName] = initValue;
770 return sName;
771 },
772
773 skipInit: function (node /*, walker */) {
774 if (node.init) {
775 node.init.skipWalk = true;
776 }
777 },
778
779 skipLeft: function (node /*, walker */) {
780 node.left.skipWalk = true;
781 },
782
783 isUseStrictExpression: function (node) {
784 return node && node.type === SYNTAX.ExpressionStatement.name &&
785 node.expression && node.expression.type === SYNTAX.Literal.name &&
786 node.expression.value === 'use strict';
787 },
788
789 maybeSkipNode: function (node, type) {
790 var alreadyIgnoring = !!this.currentState.ignoring,
791 hint = this.currentState.currentHint,
792 ignoreThis = !alreadyIgnoring && hint && hint.type === type;
793
794 if (ignoreThis) {
795 this.startIgnore();
796 node.postprocessor = this.endIgnore;
797 return true;
798 }
799 return false;
800 },
801
802 coverMetaProperty: function(node /* , walker */) {
803 node.skipSelf = true;
804 },
805
806 coverStatement: function (node, walker) {
807 var sName,
808 incrStatementCount,
809 parent,
810 grandParent;
811
812 this.maybeSkipNode(node, 'next');
813
814 if (this.isUseStrictExpression(node)) {
815 grandParent = walker.ancestor(2);
816 /* istanbul ignore else: difficult to test */
817 if (grandParent) {
818 if ((grandParent.node.type === SYNTAX.FunctionExpression.name ||
819 grandParent.node.type === SYNTAX.FunctionDeclaration.name) &&
820 walker.parent().node.body[0] === node) {
821 return;
822 }
823 }
824 }
825
826 if (node.type === SYNTAX.FunctionDeclaration.name) {
827 // Called for the side-effect of setting the function's statement count to 1.
828 this.statementName(node.loc, 1);
829 } else {
830 // We let `coverExport` handle ExportNamedDeclarations.
831 parent = walker.parent();
832 if (parent && parent.node.type === SYNTAX.ExportNamedDeclaration.name) {
833 return;
834 }
835
836 sName = this.statementName(node.loc);
837
838 incrStatementCount = astgen.statement(
839 astgen.postIncrement(
840 astgen.subscript(
841 astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
842 astgen.stringLiteral(sName)
843 )
844 )
845 );
846
847 this.splice(incrStatementCount, node, walker);
848 }
849 },
850
851 coverExport: function (node, walker) {
852 var sName, incrStatementCount;
853
854 if ( !node.declaration || !node.declaration.declarations ) { return; }
855
856 this.maybeSkipNode(node, 'next');
857
858 sName = this.statementName(node.declaration.loc);
859 incrStatementCount = astgen.statement(
860 astgen.postIncrement(
861 astgen.subscript(
862 astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
863 astgen.stringLiteral(sName)
864 )
865 )
866 );
867
868 this.splice(incrStatementCount, node, walker);
869 },
870
871 splice: function (statements, node, walker) {
872 var targetNode = walker.isLabeled() ? walker.parent().node : node;
873 targetNode.prepend = targetNode.prepend || [];
874 pushAll(targetNode.prepend, statements);
875 },
876
877 functionName: function (node, line, location) {
878 this.currentState.func += 1;
879 var id = this.currentState.func,
880 ignoring = !!this.currentState.ignoring,
881 name = node.id ? node.id.name : '(anonymous_' + id + ')',
882 clone = function (attr) {
883 var obj = location[attr] || /* istanbul ignore next */ {};
884 return { line: obj.line, column: obj.column };
885 };
886 this.coverState.fnMap[id] = {
887 name: name, line: line,
888 loc: {
889 start: clone('start'),
890 end: clone('end')
891 },
892 skip: ignoring || undefined
893 };
894 this.coverState.f[id] = 0;
895 return id;
896 },
897
898 coverFunction: function (node, walker) {
899 var id,
900 body = node.body,
901 blockBody = body.body,
902 popped;
903
904 this.maybeSkipNode(node, 'next');
905
906 id = this.functionName(node, walker.startLineForNode(node), {
907 start: node.loc.start,
908 end: { line: node.body.loc.start.line, column: node.body.loc.start.column }
909 });
910
911 if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) {
912 popped = blockBody.shift();
913 }
914 blockBody.unshift(
915 astgen.statement(
916 astgen.postIncrement(
917 astgen.subscript(
918 astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
919 astgen.stringLiteral(id)
920 )
921 )
922 )
923 );
924 if (popped) {
925 blockBody.unshift(popped);
926 }
927 },
928
929 branchName: function (type, startLine, pathLocations) {
930 var bName,
931 paths = [],
932 locations = [],
933 i,
934 ignoring = !!this.currentState.ignoring;
935 this.currentState.branch += 1;
936 bName = this.currentState.branch;
937 for (i = 0; i < pathLocations.length; i += 1) {
938 pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined;
939 locations.push(pathLocations[i]);
940 paths.push(0);
941 }
942 this.coverState.b[bName] = paths;
943 this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations };
944 return bName;
945 },
946
947 branchIncrementExprAst: function (varName, branchIndex, down) {
948 var ret = astgen.postIncrement(
949 astgen.subscript(
950 astgen.subscript(
951 astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
952 astgen.stringLiteral(varName)
953 ),
954 astgen.numericLiteral(branchIndex)
955 ),
956 down
957 );
958 return ret;
959 },
960
961 locationsForNodes: function (nodes) {
962 var ret = [],
963 i;
964 for (i = 0; i < nodes.length; i += 1) {
965 ret.push(nodes[i].loc);
966 }
967 return ret;
968 },
969
970 ifBranchInjector: function (node, walker) {
971 var alreadyIgnoring = !!this.currentState.ignoring,
972 hint = this.currentState.currentHint,
973 ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
974 ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
975 line = node.loc.start.line,
976 col = node.loc.start.column,
977 makeLoc = function () { return { line: line, column: col }; },
978 bName = this.branchName('if', walker.startLineForNode(node), [
979 { start: makeLoc(), end: makeLoc(), skip: ignoreThen || undefined },
980 { start: makeLoc(), end: makeLoc(), skip: ignoreElse || undefined }
981 ]),
982 thenBody = node.consequent.body,
983 elseBody = node.alternate.body,
984 child;
985 thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
986 elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
987 if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
988 if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
989 },
990
991 branchLocationFor: function (name, index) {
992 return this.coverState.branchMap[name].locations[index];
993 },
994
995 switchBranchInjector: function (node, walker) {
996 var cases = node.cases,
997 bName,
998 i;
999
1000 if (!(cases && cases.length > 0)) {
1001 return;
1002 }
1003 bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases));
1004 for (i = 0; i < cases.length; i += 1) {
1005 cases[i].branchLocation = this.branchLocationFor(bName, i);
1006 cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i)));
1007 }
1008 },
1009
1010 switchCaseInjector: function (node) {
1011 var location = node.branchLocation;
1012 delete node.branchLocation;
1013 if (this.maybeSkipNode(node, 'next')) {
1014 location.skip = true;
1015 }
1016 },
1017
1018 conditionalBranchInjector: function (node, walker) {
1019 var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate ])),
1020 ast1 = this.branchIncrementExprAst(bName, 0),
1021 ast2 = this.branchIncrementExprAst(bName, 1);
1022
1023 node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0));
1024 node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1));
1025 node.consequent = astgen.sequence(ast1, node.consequent);
1026 node.alternate = astgen.sequence(ast2, node.alternate);
1027 },
1028
1029 maybeAddSkip: function (branchLocation) {
1030 return function (node) {
1031 var alreadyIgnoring = !!this.currentState.ignoring,
1032 hint = this.currentState.currentHint,
1033 ignoreThis = !alreadyIgnoring && hint && hint.type === 'next';
1034 if (ignoreThis) {
1035 this.startIgnore();
1036 node.postprocessor = this.endIgnore;
1037 }
1038 if (ignoreThis || alreadyIgnoring) {
1039 branchLocation.skip = true;
1040 }
1041 };
1042 },
1043
1044 logicalExpressionBranchInjector: function (node, walker) {
1045 var parent = walker.parent(),
1046 leaves = [],
1047 bName,
1048 tuple,
1049 i;
1050
1051 this.maybeSkipNode(node, 'next');
1052
1053 if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
1054 //already covered
1055 return;
1056 }
1057
1058 this.findLeaves(node, leaves);
1059 bName = this.branchName('binary-expr',
1060 walker.startLineForNode(node),
1061 this.locationsForNodes(leaves.map(function (item) { return item.node; }))
1062 );
1063 for (i = 0; i < leaves.length; i += 1) {
1064 tuple = leaves[i];
1065 tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
1066 tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i));
1067 }
1068 },
1069
1070 findLeaves: function (node, accumulator, parent, property) {
1071 if (node.type === SYNTAX.LogicalExpression.name) {
1072 this.findLeaves(node.left, accumulator, node, 'left');
1073 this.findLeaves(node.right, accumulator, node, 'right');
1074 } else {
1075 accumulator.push({ node: node, parent: parent, property: property });
1076 }
1077 },
1078 maybeAddType: function (node /*, walker */) {
1079 var props = node.properties,
1080 i,
1081 child;
1082 for (i = 0; i < props.length; i += 1) {
1083 child = props[i];
1084 if (!child.type) {
1085 child.type = SYNTAX.Property.name;
1086 }
1087 }
1088 },
1089 };
1090
1091 if (isNode) {
1092 module.exports = Instrumenter;
1093 } else {
1094 window.Instrumenter = Instrumenter;
1095 }
1096
1097}(typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof exports !== 'undefined'));