2 Copyright (c) 2012, Yahoo! Inc. All rights reserved.
3 Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
6 /*global esprima, escodegen, window */
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|$)/,
20 isArray = Array.isArray;
22 /* istanbul ignore if: untestable */
24 isArray = function (thing) { return thing && Object.prototype.toString.call(thing) === '[object Array]'; };
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
35 /* istanbul ignore next: untestable */
36 for (cond in preconditions) {
37 if (preconditions.hasOwnProperty(cond)) {
38 if (!preconditions[cond]) { throw new Error(cond); }
43 function generateTrackerVar(filename, omitSuffix) {
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'), '$');
54 window.__cov_seq = window.__cov_seq || 0;
55 window.__cov_seq += 1;
56 suffix = window.__cov_seq;
58 return '__cov_' + (omitSuffix ? '' : suffix);
61 function pushAll(ary, thing) {
62 if (!isArray(thing)) {
65 Array.prototype.push.apply(ary, thing);
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'],
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'],
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.
104 IfStatement: ['test', 'consequent', 'alternate'],
105 ImportDeclaration: ['specifiers', 'source'],
106 ImportDefaultSpecifier: ['local'],
107 ImportNamespaceSpecifier: ['local'],
108 ImportSpecifier: ['imported', 'local'],
110 LabeledStatement: ['label', 'body'],
111 LogicalExpression: ['left', 'right'],
112 MemberExpression: ['object', 'property'],
113 MethodDefinition: ['key', 'value'],
115 NewExpression: ['callee', 'arguments'],
116 ObjectExpression: ['properties'],
117 ObjectPattern: ['properties'],
119 Property: ['key', 'value'],
120 RestElement: [ 'argument' ],
121 ReturnStatement: ['argument'],
122 SequenceExpression: ['expressions'],
123 SpreadElement: ['argument'],
125 SwitchStatement: ['discriminant', 'cases'],
126 SwitchCase: ['test', 'consequent'],
127 TaggedTemplateExpression: ['tag', 'quasi'],
129 TemplateLiteral: ['quasis', 'expressions'],
131 ThrowStatement: ['argument'],
132 TryStatement: ['block', 'handler', 'finalizer'],
133 UnaryExpression: ['argument'],
134 UpdateExpression: ['argument'],
135 VariableDeclaration: ['declarations'],
136 VariableDeclarator: ['id', 'init'],
137 WhileStatement: ['test', 'body'],
138 WithStatement: ['object', 'body'],
139 YieldExpression: ['argument']
142 for (nodeType in SYNTAX) {
143 /* istanbul ignore else: has own property */
144 if (SYNTAX.hasOwnProperty(nodeType)) {
145 SYNTAX[nodeType] = { name: nodeType, children: SYNTAX[nodeType] };
150 variable: function (name) { return { type: SYNTAX.Identifier.name, name: name }; },
151 stringLiteral: function (str) { return { type: SYNTAX.Literal.name, value: String(str) }; },
152 numericLiteral: function (num) { return { type: SYNTAX.Literal.name, value: Number(num) }; },
153 statement: function (contents) { return { type: SYNTAX.ExpressionStatement.name, expression: contents }; },
154 dot: function (obj, field) { return { type: SYNTAX.MemberExpression.name, computed: false, object: obj, property: field }; },
155 subscript: function (obj, sub) { return { type: SYNTAX.MemberExpression.name, computed: true, object: obj, property: sub }; },
156 postIncrement: function (obj) { return { type: SYNTAX.UpdateExpression.name, operator: '++', prefix: false, argument: obj }; },
157 sequence: function (one, two) { return { type: SYNTAX.SequenceExpression.name, expressions: [one, two] }; },
158 returnStatement: function (expr) { return { type: SYNTAX.ReturnStatement.name, argument: expr }; }
161 function Walker(walkMap, preprocessor, scope, debug) {
162 this.walkMap = walkMap;
163 this.preprocessor = preprocessor;
172 function defaultWalker(node, walker) {
174 var type = node.type,
177 children = SYNTAX[type],
178 // don't run generated nodes thru custom walks otherwise we will attempt to instrument the instrumentation code :)
179 applyCustomWalker = !!node.loc || node.type === SYNTAX.Program.name,
180 walkerFn = applyCustomWalker ? walker.walkMap[type] : null,
195 console.error('Unsupported node type:' + type);
198 children = SYNTAX[type].children;
199 /* istanbul ignore if: guard */
200 if (node.walking) { throw new Error('Infinite regress: Custom walkers may NOT call walker.apply(node)'); }
203 ret = walker.apply(node, walker.preprocessor);
205 preprocessor = ret.preprocessor;
207 delete ret.preprocessor;
208 ret = walker.apply(node, preprocessor);
211 if (isArray(walkerFn)) {
212 for (walkFnIndex = 0; walkFnIndex < walkerFn.length; walkFnIndex += 1) {
213 isLast = walkFnIndex === walkerFn.length - 1;
214 ret = walker.apply(ret, walkerFn[walkFnIndex]);
215 /*istanbul ignore next: paranoid check */
216 if (ret.type !== type && !isLast) {
217 throw new Error('Only the last walker is allowed to change the node type: [type was: ' + type + ' ]');
222 ret = walker.apply(node, walkerFn);
226 for (i = 0; i < children.length; i += 1) {
227 childType = children[i];
228 childNode = node[childType];
229 if (childNode && !childNode.skipWalk) {
230 pathElement = { node: node, property: childType };
231 if (isArray(childNode)) {
233 for (j = 0; j < childNode.length; j += 1) {
234 childElement = childNode[j];
235 pathElement.index = j;
237 assignNode = walker.apply(childElement, null, pathElement);
238 if (isArray(assignNode.prepend)) {
239 pushAll(childArray, assignNode.prepend);
240 delete assignNode.prepend;
243 assignNode = undefined;
245 pushAll(childArray, assignNode);
247 node[childType] = childArray;
249 assignNode = walker.apply(childNode, null, pathElement);
250 /*istanbul ignore if: paranoid check */
251 if (isArray(assignNode.prepend)) {
252 throw new Error('Internal error: attempt to prepend statements in disallowed (non-array) context');
253 /* if this should be allowed, this is how to solve it
254 tmpNode = { type: 'BlockStatement', body: [] };
255 pushAll(tmpNode.body, assignNode.prepend);
256 pushAll(tmpNode.body, assignNode);
257 node[childType] = tmpNode;
258 delete assignNode.prepend;
261 node[childType] = assignNode;
267 postprocessor = ret.postprocessor;
269 delete ret.postprocessor;
270 ret = walker.apply(ret, postprocessor);
279 startWalk: function (node) {
284 apply: function (node, walkFn, pathElement) {
285 var ret, i, seq, prefix;
287 walkFn = walkFn || defaultWalker;
293 for (i = 0; i < this.level; i += 1) { prefix += ' '; }
294 console.log(prefix + 'Enter (' + seq + '):' + node.type);
296 if (pathElement) { this.path.push(pathElement); }
297 ret = walkFn.call(this.scope, node, this);
298 if (pathElement) { this.path.pop(); }
301 console.log(prefix + 'Return (' + seq + '):' + node.type);
306 startLineForNode: function (node) {
307 return node && node.loc && node.loc.start ? node.loc.start.line : /* istanbul ignore next: guard */ null;
310 ancestor: function (n) {
311 return this.path.length > n - 1 ? this.path[this.path.length - n] : /* istanbul ignore next: guard */ null;
314 parent: function () {
315 return this.ancestor(1);
318 isLabeled: function () {
319 var el = this.parent();
320 return el && el.node.type === SYNTAX.LabeledStatement.name;
325 * mechanism to instrument code for coverage. It uses the `esprima` and
326 * `escodegen` libraries for JS parsing and code generation respectively.
328 * Works on `node` as well as the browser.
333 * var instrumenter = new require('istanbul').Instrumenter(),
334 * changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
339 * Load `esprima.js`, `escodegen.js` and `instrumenter.js` (this file) using `script` tags or other means.
341 * Create an instrumenter object as:
343 * var instrumenter = new Instrumenter(),
344 * changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
346 * Aside from demonstration purposes, it is unclear why you would want to instrument code in a browser.
348 * @class Instrumenter
350 * @param {Object} options Optional. Configuration options.
351 * @param {String} [options.coverageVariable] the global variable name to use for
352 * tracking coverage. Defaults to `__coverage__`
353 * @param {Boolean} [options.embedSource] whether to embed the source code of every
354 * file as an array in the file coverage object for that file. Defaults to `false`
355 * @param {Boolean} [options.preserveComments] whether comments should be preserved in the output. Defaults to `false`
356 * @param {Boolean} [options.noCompact] emit readable code when set. Defaults to `false`
357 * @param {Boolean} [options.noAutoWrap] do not automatically wrap the source in
358 * an anonymous function before covering it. By default, code is wrapped in
359 * an anonymous function before it is parsed. This is done because
360 * some nodejs libraries have `return` statements outside of
361 * a function which is technically invalid Javascript and causes the parser to fail.
362 * This construct, however, works correctly in node since module loading
363 * is done in the context of an anonymous function.
365 * Note that the semantics of the code *returned* by the instrumenter does not change in any way.
366 * The function wrapper is "unwrapped" before the instrumented code is generated.
367 * @param {Object} [options.codeGenerationOptions] an object that is directly passed to the `escodegen`
368 * library as configuration for code generation. The `noCompact` setting is not honored when this
369 * option is specified
370 * @param {Boolean} [options.debug] assist in debugging. Currently, the only effect of
371 * setting this option is a pretty-print of the coverage variable. Defaults to `false`
372 * @param {Boolean} [options.walkDebug] assist in debugging of the AST walker used by this class.
375 function Instrumenter(options) {
376 this.opts = options || {
379 coverageVariable: '__coverage__',
380 codeGenerationOptions: undefined,
384 preserveComments: false
387 this.walker = new Walker({
388 ArrowFunctionExpression: [ this.arrowBlockConverter ],
389 ExpressionStatement: this.coverStatement,
390 BreakStatement: this.coverStatement,
391 ContinueStatement: this.coverStatement,
392 DebuggerStatement: this.coverStatement,
393 ReturnStatement: this.coverStatement,
394 ThrowStatement: this.coverStatement,
395 TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
396 VariableDeclaration: this.coverStatement,
397 IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
398 ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
399 ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
400 ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
401 WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
402 DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
403 SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
404 SwitchCase: [ this.switchCaseInjector ],
405 WithStatement: [ this.withBlockConverter, this.coverStatement ],
406 FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
407 FunctionExpression: this.coverFunction,
408 LabeledStatement: this.coverStatement,
409 ConditionalExpression: this.conditionalBranchInjector,
410 LogicalExpression: this.logicalExpressionBranchInjector,
411 ObjectExpression: this.maybeAddType
412 }, this.extractCurrentHint, this, this.opts.walkDebug);
414 //unit testing purposes only
415 if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
416 this.omitTrackerSuffix = true;
420 Instrumenter.prototype = {
422 * synchronous instrumentation method. Throws when illegal code is passed to it
423 * @method instrumentSync
424 * @param {String} code the code to be instrumented as a String
425 * @param {String} filename Optional. The name of the file from which
426 * the code was read. A temporary filename is generated when not specified.
427 * Not specifying a filename is only useful for unit tests and demonstrations
430 instrumentSync: function (code, filename) {
433 //protect from users accidentally passing in a Buffer object instead
434 if (typeof code !== 'string') { throw new Error('Code must be string'); }
435 if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't affect syntax tree locations for things we care about
438 if (!this.opts.noAutoWrap) {
439 code = LEADER_WRAP + code + TRAILER_WRAP;
441 program = ESP.parse(code, {
444 tokens: this.opts.preserveComments,
447 if (this.opts.preserveComments) {
448 program = ESPGEN.attachComments(program, program.comments, program.tokens);
450 if (!this.opts.noAutoWrap) {
452 type: SYNTAX.Program.name,
453 body: program.body[0].expression.callee.body.body,
454 comments: program.comments
457 return this.instrumentASTSync(program, filename, code);
459 filterHints: function (comments) {
464 if (!(comments && isArray(comments))) {
467 for (i = 0; i < comments.length; i += 1) {
468 comment = comments[i];
469 /* istanbul ignore else: paranoid check */
470 if (comment && comment.value && comment.range && isArray(comment.range)) {
471 groups = String(comment.value).match(COMMENT_RE);
473 ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] });
479 extractCurrentHint: function (node) {
480 if (!node.range) { return; }
481 var i = this.currentState.lastHintPosition + 1,
482 hints = this.currentState.hints,
483 nodeStart = node.range[0],
485 this.currentState.currentHint = null;
486 while (i < hints.length) {
488 if (hint.end < nodeStart) {
489 this.currentState.currentHint = hint;
490 this.currentState.lastHintPosition = i;
498 * synchronous instrumentation method that instruments an AST instead.
499 * @method instrumentASTSync
500 * @param {String} program the AST to be instrumented
501 * @param {String} filename Optional. The name of the file from which
502 * the code was read. A temporary filename is generated when not specified.
503 * Not specifying a filename is only useful for unit tests and demonstrations
505 * @param {String} originalCode the original code corresponding to the AST,
506 * used for embedding the source into the coverage object
508 instrumentASTSync: function (program, filename, originalCode) {
509 var usingStrict = false,
515 filename = filename || String(new Date().getTime()) + '.js';
516 this.sourceMap = null;
526 this.currentState = {
527 trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix),
532 hints: this.filterHints(program.comments),
534 lastHintPosition: -1,
537 if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) {
539 program.body.shift();
540 //and add it back at code generation time
543 this.walker.startWalk(program);
544 codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }};
545 codegenOptions.comment = this.opts.preserveComments;
546 //console.log(JSON.stringify(program, undefined, 2));
548 generated = ESPGEN.generate(program, codegenOptions);
549 preamble = this.getPreamble(originalCode || '', usingStrict);
551 if (generated.map && generated.code) {
552 lineCount = preamble.split(/\r\n|\r|\n/).length;
553 // offset all the generated line numbers by the number of lines in the preamble
554 for (i = 0; i < generated.map._mappings._array.length; i += 1) {
555 generated.map._mappings._array[i].generatedLine += lineCount;
557 this.sourceMap = generated.map;
558 generated = generated.code;
561 return preamble + '\n' + generated + '\n';
564 * Callback based instrumentation. Note that this still executes synchronously in the same process tick
565 * and calls back immediately. It only provides the options for callback style error handling as
566 * opposed to a `try-catch` style and nothing more. Implemented as a wrapper over `instrumentSync`
569 * @param {String} code the code to be instrumented as a String
570 * @param {String} filename Optional. The name of the file from which
571 * the code was read. A temporary filename is generated when not specified.
572 * Not specifying a filename is only useful for unit tests and demonstrations
574 * @param {Function(err, instrumentedCode)} callback - the callback function
576 instrument: function (code, filename, callback) {
578 if (!callback && typeof filename === 'function') {
583 callback(null, this.instrumentSync(code, filename));
589 * returns the file coverage object for the code that was instrumented
590 * just before calling this method. Note that this represents a
591 * "zero-coverage" object which is not even representative of the code
592 * being loaded in node or a browser (which would increase the statement
593 * counts for mainline code).
594 * @method lastFileCoverage
595 * @return {Object} a "zero-coverage" file coverage object for the code last instrumented
596 * by this instrumenter
598 lastFileCoverage: function () {
599 return this.coverState;
602 * returns the source map object for the code that was instrumented
603 * just before calling this method.
604 * @method lastSourceMap
605 * @return {Object} a source map object for the code last instrumented
606 * by this instrumenter
608 lastSourceMap: function () {
609 return this.sourceMap;
611 fixColumnPositions: function (coverState) {
612 var offset = LEADER_WRAP.length,
613 fixer = function (loc) {
614 if (loc.start.line === 1) {
615 loc.start.column -= offset;
617 if (loc.end.line === 1) {
618 loc.end.column -= offset;
626 obj = coverState.statementMap;
628 /* istanbul ignore else: has own property */
629 if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
631 obj = coverState.fnMap;
633 /* istanbul ignore else: has own property */
634 if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
636 obj = coverState.branchMap;
638 /* istanbul ignore else: has own property */
639 if (obj.hasOwnProperty(k)) {
640 locations = obj[k].locations;
641 for (i = 0; i < locations.length; i += 1) {
648 getPreamble: function (sourceCode, emitUseStrict) {
649 var varName = this.opts.coverageVariable || '__coverage__',
650 file = this.coverState.path.replace(/\\/g, '\\\\'),
651 tracker = this.currentState.trackerVar,
653 strictLine = emitUseStrict ? '"use strict";' : '',
654 // return replacements using the function to ensure that the replacement is
655 // treated like a dumb string and not as a string with RE replacement patterns
656 replacer = function (s) {
657 return function () { return s; };
660 if (!this.opts.noAutoWrap) {
661 this.fixColumnPositions(this.coverState);
663 if (this.opts.embedSource) {
664 this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
666 coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState);
669 "var %VAR% = (Function('return this'))();",
670 "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
671 "%VAR% = %VAR%.%GLOBAL%;",
672 "if (!(%VAR%['%FILE%'])) {",
673 " %VAR%['%FILE%'] = %OBJECT%;",
675 "%VAR% = %VAR%['%FILE%'];"
677 .replace(/%STRICT%/g, replacer(strictLine))
678 .replace(/%VAR%/g, replacer(tracker))
679 .replace(/%GLOBAL%/g, replacer(varName))
680 .replace(/%FILE%/g, replacer(file))
681 .replace(/%OBJECT%/g, replacer(coverState));
685 startIgnore: function () {
686 this.currentState.ignoring += 1;
689 endIgnore: function () {
690 this.currentState.ignoring -= 1;
693 convertToBlock: function (node) {
695 return { type: 'BlockStatement', body: [] };
696 } else if (node.type === 'BlockStatement') {
699 return { type: 'BlockStatement', body: [ node ] };
703 arrowBlockConverter: function (node) {
705 if (node.expression) { // turn expression nodes into a block with a return statement
706 retStatement = astgen.returnStatement(node.body);
707 // ensure the generated return statement is covered
708 retStatement.loc = node.body.loc;
709 node.body = this.convertToBlock(retStatement);
710 node.expression = false;
714 paranoidHandlerCheck: function (node) {
715 // if someone is using an older esprima on the browser
716 // convert handlers array to single handler attribute
717 // containing its first element
718 /* istanbul ignore next */
719 if (!node.handler && node.handlers) {
720 node.handler = node.handlers[0];
724 ifBlockConverter: function (node) {
725 node.consequent = this.convertToBlock(node.consequent);
726 node.alternate = this.convertToBlock(node.alternate);
729 loopBlockConverter: function (node) {
730 node.body = this.convertToBlock(node.body);
733 withBlockConverter: function (node) {
734 node.body = this.convertToBlock(node.body);
737 statementName: function (location, initValue) {
739 ignoring = !!this.currentState.ignoring;
741 location.skip = ignoring || undefined;
742 initValue = initValue || 0;
743 this.currentState.statement += 1;
744 sName = this.currentState.statement;
745 this.coverState.statementMap[sName] = location;
746 this.coverState.s[sName] = initValue;
750 skipInit: function (node /*, walker */) {
752 node.init.skipWalk = true;
756 skipLeft: function (node /*, walker */) {
757 node.left.skipWalk = true;
760 isUseStrictExpression: function (node) {
761 return node && node.type === SYNTAX.ExpressionStatement.name &&
762 node.expression && node.expression.type === SYNTAX.Literal.name &&
763 node.expression.value === 'use strict';
766 maybeSkipNode: function (node, type) {
767 var alreadyIgnoring = !!this.currentState.ignoring,
768 hint = this.currentState.currentHint,
769 ignoreThis = !alreadyIgnoring && hint && hint.type === type;
773 node.postprocessor = this.endIgnore;
779 coverStatement: function (node, walker) {
784 this.maybeSkipNode(node, 'next');
786 if (this.isUseStrictExpression(node)) {
787 grandParent = walker.ancestor(2);
788 /* istanbul ignore else: difficult to test */
790 if ((grandParent.node.type === SYNTAX.FunctionExpression.name ||
791 grandParent.node.type === SYNTAX.FunctionDeclaration.name) &&
792 walker.parent().node.body[0] === node) {
797 if (node.type === SYNTAX.FunctionDeclaration.name) {
798 sName = this.statementName(node.loc, 1);
800 sName = this.statementName(node.loc);
801 incrStatementCount = astgen.statement(
802 astgen.postIncrement(
804 astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
805 astgen.stringLiteral(sName)
809 this.splice(incrStatementCount, node, walker);
813 splice: function (statements, node, walker) {
814 var targetNode = walker.isLabeled() ? walker.parent().node : node;
815 targetNode.prepend = targetNode.prepend || [];
816 pushAll(targetNode.prepend, statements);
819 functionName: function (node, line, location) {
820 this.currentState.func += 1;
821 var id = this.currentState.func,
822 ignoring = !!this.currentState.ignoring,
823 name = node.id ? node.id.name : '(anonymous_' + id + ')',
824 clone = function (attr) {
825 var obj = location[attr] || /* istanbul ignore next */ {};
826 return { line: obj.line, column: obj.column };
828 this.coverState.fnMap[id] = {
829 name: name, line: line,
831 start: clone('start'),
834 skip: ignoring || undefined
836 this.coverState.f[id] = 0;
840 coverFunction: function (node, walker) {
843 blockBody = body.body,
846 this.maybeSkipNode(node, 'next');
848 id = this.functionName(node, walker.startLineForNode(node), {
849 start: node.loc.start,
850 end: { line: node.body.loc.start.line, column: node.body.loc.start.column }
853 if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) {
854 popped = blockBody.shift();
858 astgen.postIncrement(
860 astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
861 astgen.stringLiteral(id)
867 blockBody.unshift(popped);
871 branchName: function (type, startLine, pathLocations) {
876 ignoring = !!this.currentState.ignoring;
877 this.currentState.branch += 1;
878 bName = this.currentState.branch;
879 for (i = 0; i < pathLocations.length; i += 1) {
880 pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined;
881 locations.push(pathLocations[i]);
884 this.coverState.b[bName] = paths;
885 this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations };
889 branchIncrementExprAst: function (varName, branchIndex, down) {
890 var ret = astgen.postIncrement(
893 astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
894 astgen.stringLiteral(varName)
896 astgen.numericLiteral(branchIndex)
903 locationsForNodes: function (nodes) {
906 for (i = 0; i < nodes.length; i += 1) {
907 ret.push(nodes[i].loc);
912 ifBranchInjector: function (node, walker) {
913 var alreadyIgnoring = !!this.currentState.ignoring,
914 hint = this.currentState.currentHint,
915 ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
916 ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
917 line = node.loc.start.line,
918 col = node.loc.start.column,
919 makeLoc = function () { return { line: line, column: col }; },
920 bName = this.branchName('if', walker.startLineForNode(node), [
921 { start: makeLoc(), end: makeLoc(), skip: ignoreThen || undefined },
922 { start: makeLoc(), end: makeLoc(), skip: ignoreElse || undefined }
924 thenBody = node.consequent.body,
925 elseBody = node.alternate.body,
927 thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
928 elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
929 if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
930 if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
933 branchLocationFor: function (name, index) {
934 return this.coverState.branchMap[name].locations[index];
937 switchBranchInjector: function (node, walker) {
938 var cases = node.cases,
942 if (!(cases && cases.length > 0)) {
945 bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases));
946 for (i = 0; i < cases.length; i += 1) {
947 cases[i].branchLocation = this.branchLocationFor(bName, i);
948 cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i)));
952 switchCaseInjector: function (node) {
953 var location = node.branchLocation;
954 delete node.branchLocation;
955 if (this.maybeSkipNode(node, 'next')) {
956 location.skip = true;
960 conditionalBranchInjector: function (node, walker) {
961 var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate ])),
962 ast1 = this.branchIncrementExprAst(bName, 0),
963 ast2 = this.branchIncrementExprAst(bName, 1);
965 node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0));
966 node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1));
967 node.consequent = astgen.sequence(ast1, node.consequent);
968 node.alternate = astgen.sequence(ast2, node.alternate);
971 maybeAddSkip: function (branchLocation) {
972 return function (node) {
973 var alreadyIgnoring = !!this.currentState.ignoring,
974 hint = this.currentState.currentHint,
975 ignoreThis = !alreadyIgnoring && hint && hint.type === 'next';
978 node.postprocessor = this.endIgnore;
980 if (ignoreThis || alreadyIgnoring) {
981 branchLocation.skip = true;
986 logicalExpressionBranchInjector: function (node, walker) {
987 var parent = walker.parent(),
993 this.maybeSkipNode(node, 'next');
995 if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
1000 this.findLeaves(node, leaves);
1001 bName = this.branchName('binary-expr',
1002 walker.startLineForNode(node),
1003 this.locationsForNodes(leaves.map(function (item) { return item.node; }))
1005 for (i = 0; i < leaves.length; i += 1) {
1007 tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
1008 tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i));
1012 findLeaves: function (node, accumulator, parent, property) {
1013 if (node.type === SYNTAX.LogicalExpression.name) {
1014 this.findLeaves(node.left, accumulator, node, 'left');
1015 this.findLeaves(node.right, accumulator, node, 'right');
1017 accumulator.push({ node: node, parent: parent, property: property });
1020 maybeAddType: function (node /*, walker */) {
1021 var props = node.properties,
1024 for (i = 0; i < props.length; i += 1) {
1027 child.type = SYNTAX.Property.name;
1034 module.exports = Instrumenter;
1036 window.Instrumenter = Instrumenter;
1039 }(typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof exports !== 'undefined'));