visitor.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6. var _sourceCoverage = require('./source-coverage');
  7. var _constants = require('./constants');
  8. var _crypto = require('crypto');
  9. var _babelTemplate = require('babel-template');
  10. var _babelTemplate2 = _interopRequireDefault(_babelTemplate);
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13. // istanbul ignore comment pattern
  14. var COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/;
  15. // istanbul ignore file pattern
  16. var COMMENT_FILE_RE = /^\s*istanbul\s+ignore\s+(file)(?=\W|$)/;
  17. // source map URL pattern
  18. var SOURCE_MAP_RE = /[#@]\s*sourceMappingURL=(.*)\s*$/m;
  19. // generate a variable name from hashing the supplied file path
  20. function genVar(filename) {
  21. var hash = (0, _crypto.createHash)(_constants.SHA);
  22. hash.update(filename);
  23. return 'cov_' + parseInt(hash.digest('hex').substr(0, 12), 16).toString(36);
  24. }
  25. // VisitState holds the state of the visitor, provides helper functions
  26. // and is the `this` for the individual coverage visitors.
  27. var VisitState = function () {
  28. function VisitState(types, sourceFilePath, inputSourceMap) {
  29. _classCallCheck(this, VisitState);
  30. this.varName = genVar(sourceFilePath);
  31. this.attrs = {};
  32. this.nextIgnore = null;
  33. this.cov = new _sourceCoverage.SourceCoverage(sourceFilePath);
  34. if (typeof inputSourceMap !== "undefined") {
  35. this.cov.inputSourceMap(inputSourceMap);
  36. }
  37. this.types = types;
  38. this.sourceMappingURL = null;
  39. }
  40. // should we ignore the node? Yes, if specifically ignoring
  41. // or if the node is generated.
  42. _createClass(VisitState, [{
  43. key: 'shouldIgnore',
  44. value: function shouldIgnore(path) {
  45. return this.nextIgnore || !path.node.loc;
  46. }
  47. // extract the ignore comment hint (next|if|else) or null
  48. }, {
  49. key: 'hintFor',
  50. value: function hintFor(node) {
  51. var hint = null;
  52. if (node.leadingComments) {
  53. node.leadingComments.forEach(function (c) {
  54. var v = (c.value || /* istanbul ignore next: paranoid check */"").trim();
  55. var groups = v.match(COMMENT_RE);
  56. if (groups) {
  57. hint = groups[1];
  58. }
  59. });
  60. }
  61. return hint;
  62. }
  63. // extract a source map URL from comments and keep track of it
  64. }, {
  65. key: 'maybeAssignSourceMapURL',
  66. value: function maybeAssignSourceMapURL(node) {
  67. var that = this;
  68. var extractURL = function extractURL(comments) {
  69. if (!comments) {
  70. return;
  71. }
  72. comments.forEach(function (c) {
  73. var v = (c.value || /* istanbul ignore next: paranoid check */"").trim();
  74. var groups = v.match(SOURCE_MAP_RE);
  75. if (groups) {
  76. that.sourceMappingURL = groups[1];
  77. }
  78. });
  79. };
  80. extractURL(node.leadingComments);
  81. extractURL(node.trailingComments);
  82. }
  83. // for these expressions the statement counter needs to be hoisted, so
  84. // function name inference can be preserved
  85. }, {
  86. key: 'counterNeedsHoisting',
  87. value: function counterNeedsHoisting(path) {
  88. return path.isFunctionExpression() || path.isArrowFunctionExpression() || path.isClassExpression();
  89. }
  90. // all the generic stuff that needs to be done on enter for every node
  91. }, {
  92. key: 'onEnter',
  93. value: function onEnter(path) {
  94. var n = path.node;
  95. this.maybeAssignSourceMapURL(n);
  96. // if already ignoring, nothing more to do
  97. if (this.nextIgnore !== null) {
  98. return;
  99. }
  100. // check hint to see if ignore should be turned on
  101. var hint = this.hintFor(n);
  102. if (hint === 'next') {
  103. this.nextIgnore = n;
  104. return;
  105. }
  106. // else check custom node attribute set by a prior visitor
  107. if (this.getAttr(path.node, 'skip-all') !== null) {
  108. this.nextIgnore = n;
  109. }
  110. }
  111. // all the generic stuff on exit of a node,
  112. // including reseting ignores and custom node attrs
  113. }, {
  114. key: 'onExit',
  115. value: function onExit(path) {
  116. // restore ignore status, if needed
  117. if (path.node === this.nextIgnore) {
  118. this.nextIgnore = null;
  119. }
  120. // nuke all attributes for the node
  121. delete path.node.__cov__;
  122. }
  123. // set a node attribute for the supplied node
  124. }, {
  125. key: 'setAttr',
  126. value: function setAttr(node, name, value) {
  127. node.__cov__ = node.__cov__ || {};
  128. node.__cov__[name] = value;
  129. }
  130. // retrieve a node attribute for the supplied node or null
  131. }, {
  132. key: 'getAttr',
  133. value: function getAttr(node, name) {
  134. var c = node.__cov__;
  135. if (!c) {
  136. return null;
  137. }
  138. return c[name];
  139. }
  140. //
  141. }, {
  142. key: 'increase',
  143. value: function increase(type, id, index) {
  144. var T = this.types;
  145. var wrap = index !== null
  146. // If `index` present, turn `x` into `x[index]`.
  147. ? function (x) {
  148. return T.memberExpression(x, T.numericLiteral(index), true);
  149. } : function (x) {
  150. return x;
  151. };
  152. return T.updateExpression('++', wrap(T.memberExpression(T.memberExpression(T.identifier(this.varName), T.identifier(type)), T.numericLiteral(id), true)));
  153. }
  154. }, {
  155. key: 'insertCounter',
  156. value: function insertCounter(path, increment) {
  157. var T = this.types;
  158. if (path.isBlockStatement()) {
  159. path.node.body.unshift(T.expressionStatement(increment));
  160. } else if (path.isStatement()) {
  161. path.insertBefore(T.expressionStatement(increment));
  162. } else if (this.counterNeedsHoisting(path) && T.isVariableDeclarator(path.parentPath)) {
  163. // make an attempt to hoist the statement counter, so that
  164. // function names are maintained.
  165. var parent = path.parentPath.parentPath;
  166. if (parent && T.isExportNamedDeclaration(parent.parentPath)) {
  167. parent.parentPath.insertBefore(T.expressionStatement(increment));
  168. } else if (parent && (T.isProgram(parent.parentPath) || T.isBlockStatement(parent.parentPath))) {
  169. parent.insertBefore(T.expressionStatement(increment));
  170. } else {
  171. path.replaceWith(T.sequenceExpression([increment, path.node]));
  172. }
  173. } else /* istanbul ignore else: not expected */if (path.isExpression()) {
  174. path.replaceWith(T.sequenceExpression([increment, path.node]));
  175. } else {
  176. console.error('Unable to insert counter for node type:', path.node.type);
  177. }
  178. }
  179. }, {
  180. key: 'insertStatementCounter',
  181. value: function insertStatementCounter(path) {
  182. /* istanbul ignore if: paranoid check */
  183. if (!(path.node && path.node.loc)) {
  184. return;
  185. }
  186. var index = this.cov.newStatement(path.node.loc);
  187. var increment = this.increase('s', index, null);
  188. this.insertCounter(path, increment);
  189. }
  190. }, {
  191. key: 'insertFunctionCounter',
  192. value: function insertFunctionCounter(path) {
  193. var T = this.types;
  194. /* istanbul ignore if: paranoid check */
  195. if (!(path.node && path.node.loc)) {
  196. return;
  197. }
  198. var n = path.node;
  199. var dloc = null;
  200. // get location for declaration
  201. switch (n.type) {
  202. case "FunctionDeclaration":
  203. /* istanbul ignore else: paranoid check */
  204. if (n.id) {
  205. dloc = n.id.loc;
  206. }
  207. break;
  208. case "FunctionExpression":
  209. if (n.id) {
  210. dloc = n.id.loc;
  211. }
  212. break;
  213. }
  214. if (!dloc) {
  215. dloc = {
  216. start: n.loc.start,
  217. end: { line: n.loc.start.line, column: n.loc.start.column + 1 }
  218. };
  219. }
  220. var name = path.node.id ? path.node.id.name : path.node.name;
  221. var index = this.cov.newFunction(name, dloc, path.node.body.loc);
  222. var increment = this.increase('f', index, null);
  223. var body = path.get('body');
  224. /* istanbul ignore else: not expected */
  225. if (body.isBlockStatement()) {
  226. body.node.body.unshift(T.expressionStatement(increment));
  227. } else {
  228. console.error('Unable to process function body node type:', path.node.type);
  229. }
  230. }
  231. }, {
  232. key: 'getBranchIncrement',
  233. value: function getBranchIncrement(branchName, loc) {
  234. var index = this.cov.addBranchPath(branchName, loc);
  235. return this.increase('b', branchName, index);
  236. }
  237. }, {
  238. key: 'insertBranchCounter',
  239. value: function insertBranchCounter(path, branchName, loc) {
  240. var increment = this.getBranchIncrement(branchName, loc || path.node.loc);
  241. this.insertCounter(path, increment);
  242. }
  243. }, {
  244. key: 'findLeaves',
  245. value: function findLeaves(node, accumulator, parent, property) {
  246. if (!node) {
  247. return;
  248. }
  249. if (node.type === "LogicalExpression") {
  250. var hint = this.hintFor(node);
  251. if (hint !== 'next') {
  252. this.findLeaves(node.left, accumulator, node, 'left');
  253. this.findLeaves(node.right, accumulator, node, 'right');
  254. }
  255. } else {
  256. accumulator.push({
  257. node: node,
  258. parent: parent,
  259. property: property
  260. });
  261. }
  262. }
  263. }]);
  264. return VisitState;
  265. }();
  266. // generic function that takes a set of visitor methods and
  267. // returns a visitor object with `enter` and `exit` properties,
  268. // such that:
  269. //
  270. // * standard entry processing is done
  271. // * the supplied visitors are called only when ignore is not in effect
  272. // This relieves them from worrying about ignore states and generated nodes.
  273. // * standard exit processing is done
  274. //
  275. function entries() {
  276. var enter = Array.prototype.slice.call(arguments);
  277. // the enter function
  278. var wrappedEntry = function wrappedEntry(path, node) {
  279. this.onEnter(path);
  280. if (this.shouldIgnore(path)) {
  281. return;
  282. }
  283. var that = this;
  284. enter.forEach(function (e) {
  285. e.call(that, path, node);
  286. });
  287. };
  288. var exit = function exit(path, node) {
  289. this.onExit(path, node);
  290. };
  291. return {
  292. enter: wrappedEntry,
  293. exit: exit
  294. };
  295. }
  296. function coverStatement(path) {
  297. this.insertStatementCounter(path);
  298. }
  299. /* istanbul ignore next: no node.js support */
  300. function coverAssignmentPattern(path) {
  301. var n = path.node;
  302. var b = this.cov.newBranch('default-arg', n.loc);
  303. this.insertBranchCounter(path.get('right'), b);
  304. }
  305. function coverFunction(path) {
  306. this.insertFunctionCounter(path);
  307. }
  308. function coverVariableDeclarator(path) {
  309. this.insertStatementCounter(path.get('init'));
  310. }
  311. function skipInit(path) {
  312. if (path.node.init) {
  313. this.setAttr(path.node.init, 'skip-all', true);
  314. }
  315. }
  316. function makeBlock(path) {
  317. var T = this.types;
  318. if (!path.node) {
  319. path.replaceWith(T.blockStatement([]));
  320. }
  321. if (!path.isBlockStatement()) {
  322. path.replaceWith(T.blockStatement([path.node]));
  323. path.node.loc = path.node.body[0].loc;
  324. }
  325. }
  326. function blockProp(prop) {
  327. return function (path) {
  328. makeBlock.call(this, path.get(prop));
  329. };
  330. }
  331. function makeParenthesizedExpression(path) {
  332. var T = this.types;
  333. if (path.node) {
  334. path.replaceWith(T.parenthesizedExpression(path.node));
  335. }
  336. }
  337. function parenthesizedExpressionProp(prop) {
  338. return function (path) {
  339. makeParenthesizedExpression.call(this, path.get(prop));
  340. };
  341. }
  342. function convertArrowExpression(path) {
  343. var n = path.node;
  344. var T = this.types;
  345. if (!T.isBlockStatement(n.body)) {
  346. var bloc = n.body.loc;
  347. if (n.expression === true) {
  348. n.expression = false;
  349. }
  350. n.body = T.blockStatement([T.returnStatement(n.body)]);
  351. // restore body location
  352. n.body.loc = bloc;
  353. // set up the location for the return statement so it gets
  354. // instrumented
  355. n.body.body[0].loc = bloc;
  356. }
  357. }
  358. function coverIfBranches(path) {
  359. var n = path.node,
  360. hint = this.hintFor(n),
  361. ignoreIf = hint === 'if',
  362. ignoreElse = hint === 'else',
  363. branch = this.cov.newBranch('if', n.loc);
  364. if (ignoreIf) {
  365. this.setAttr(n.consequent, 'skip-all', true);
  366. } else {
  367. this.insertBranchCounter(path.get('consequent'), branch, n.loc);
  368. }
  369. if (ignoreElse) {
  370. this.setAttr(n.alternate, 'skip-all', true);
  371. } else {
  372. this.insertBranchCounter(path.get('alternate'), branch, n.loc);
  373. }
  374. }
  375. function createSwitchBranch(path) {
  376. var b = this.cov.newBranch('switch', path.node.loc);
  377. this.setAttr(path.node, 'branchName', b);
  378. }
  379. function coverSwitchCase(path) {
  380. var T = this.types;
  381. var b = this.getAttr(path.parentPath.node, 'branchName');
  382. /* istanbul ignore if: paranoid check */
  383. if (b === null) {
  384. throw new Error('Unable to get switch branch name');
  385. }
  386. var increment = this.getBranchIncrement(b, path.node.loc);
  387. path.node.consequent.unshift(T.expressionStatement(increment));
  388. }
  389. function coverTernary(path) {
  390. var n = path.node,
  391. branch = this.cov.newBranch('cond-expr', path.node.loc),
  392. cHint = this.hintFor(n.consequent),
  393. aHint = this.hintFor(n.alternate);
  394. if (cHint !== 'next') {
  395. this.insertBranchCounter(path.get('consequent'), branch);
  396. }
  397. if (aHint !== 'next') {
  398. this.insertBranchCounter(path.get('alternate'), branch);
  399. }
  400. }
  401. function coverLogicalExpression(path) {
  402. var T = this.types;
  403. if (path.parentPath.node.type === "LogicalExpression") {
  404. return; // already processed
  405. }
  406. var leaves = [];
  407. this.findLeaves(path.node, leaves);
  408. var b = this.cov.newBranch("binary-expr", path.node.loc);
  409. for (var i = 0; i < leaves.length; i += 1) {
  410. var leaf = leaves[i];
  411. var hint = this.hintFor(leaf.node);
  412. if (hint === 'next') {
  413. continue;
  414. }
  415. var increment = this.getBranchIncrement(b, leaf.node.loc);
  416. if (!increment) {
  417. continue;
  418. }
  419. leaf.parent[leaf.property] = T.sequenceExpression([increment, leaf.node]);
  420. }
  421. }
  422. var codeVisitor = {
  423. ArrowFunctionExpression: entries(convertArrowExpression, coverFunction),
  424. AssignmentPattern: entries(coverAssignmentPattern),
  425. BlockStatement: entries(), // ignore processing only
  426. ClassMethod: entries(coverFunction),
  427. ClassDeclaration: entries(parenthesizedExpressionProp('superClass')),
  428. ExpressionStatement: entries(coverStatement),
  429. BreakStatement: entries(coverStatement),
  430. ContinueStatement: entries(coverStatement),
  431. DebuggerStatement: entries(coverStatement),
  432. ReturnStatement: entries(coverStatement),
  433. ThrowStatement: entries(coverStatement),
  434. TryStatement: entries(coverStatement),
  435. VariableDeclaration: entries(), // ignore processing only
  436. VariableDeclarator: entries(coverVariableDeclarator),
  437. IfStatement: entries(blockProp('consequent'), blockProp('alternate'), coverStatement, coverIfBranches),
  438. ForStatement: entries(blockProp('body'), skipInit, coverStatement),
  439. ForInStatement: entries(blockProp('body'), skipInit, coverStatement),
  440. ForOfStatement: entries(blockProp('body'), skipInit, coverStatement),
  441. WhileStatement: entries(blockProp('body'), coverStatement),
  442. DoWhileStatement: entries(blockProp('body'), coverStatement),
  443. SwitchStatement: entries(createSwitchBranch, coverStatement),
  444. SwitchCase: entries(coverSwitchCase),
  445. WithStatement: entries(blockProp('body'), coverStatement),
  446. FunctionDeclaration: entries(coverFunction),
  447. FunctionExpression: entries(coverFunction),
  448. LabeledStatement: entries(coverStatement),
  449. ConditionalExpression: entries(coverTernary),
  450. LogicalExpression: entries(coverLogicalExpression)
  451. };
  452. // the template to insert at the top of the program.
  453. var coverageTemplate = (0, _babelTemplate2.default)('\n var COVERAGE_VAR = (function () {\n var path = PATH,\n hash = HASH,\n Function = (function(){}).constructor,\n global = (new Function(\'return this\'))(),\n gcv = GLOBAL_COVERAGE_VAR,\n coverageData = INITIAL,\n coverage = global[gcv] || (global[gcv] = {});\n if (coverage[path] && coverage[path].hash === hash) {\n return coverage[path];\n }\n coverageData.hash = hash;\n return coverage[path] = coverageData;\n })();\n');
  454. // the rewire plugin (and potentially other babel middleware)
  455. // may cause files to be instrumented twice, see:
  456. // https://github.com/istanbuljs/babel-plugin-istanbul/issues/94
  457. // we should only instrument code for coverage the first time
  458. // it's run through istanbul-lib-instrument.
  459. function alreadyInstrumented(path, visitState) {
  460. return path.scope.hasBinding(visitState.varName);
  461. }
  462. function shouldIgnoreFile(programNode) {
  463. return programNode.parent && programNode.parent.comments.some(function (c) {
  464. return COMMENT_FILE_RE.test(c.value);
  465. });
  466. }
  467. /**
  468. * programVisitor is a `babel` adaptor for instrumentation.
  469. * It returns an object with two methods `enter` and `exit`.
  470. * These should be assigned to or called from `Program` entry and exit functions
  471. * in a babel visitor.
  472. * These functions do not make assumptions about the state set by Babel and thus
  473. * can be used in a context other than a Babel plugin.
  474. *
  475. * The exit function returns an object that currently has the following keys:
  476. *
  477. * `fileCoverage` - the file coverage object created for the source file.
  478. * `sourceMappingURL` - any source mapping URL found when processing the file.
  479. *
  480. * @param {Object} types - an instance of babel-types
  481. * @param {string} sourceFilePath - the path to source file
  482. * @param {Object} opts - additional options
  483. * @param {string} [opts.coverageVariable=__coverage__] the global coverage variable name.
  484. * @param {object} [opts.inputSourceMap=undefined] the input source map, that maps the uninstrumented code back to the
  485. * original code.
  486. */
  487. function programVisitor(types) {
  488. var sourceFilePath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'unknown.js';
  489. var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { coverageVariable: '__coverage__', inputSourceMap: undefined };
  490. var T = types;
  491. var visitState = new VisitState(types, sourceFilePath, opts.inputSourceMap);
  492. return {
  493. enter: function enter(path) {
  494. if (shouldIgnoreFile(path.find(function (p) {
  495. return p.isProgram();
  496. }))) {
  497. return;
  498. }
  499. if (alreadyInstrumented(path, visitState)) {
  500. return;
  501. }
  502. path.traverse(codeVisitor, visitState);
  503. },
  504. exit: function exit(path) {
  505. if (alreadyInstrumented(path, visitState)) {
  506. return;
  507. }
  508. visitState.cov.freeze();
  509. var coverageData = visitState.cov.toJSON();
  510. if (shouldIgnoreFile(path.find(function (p) {
  511. return p.isProgram();
  512. }))) {
  513. return { fileCoverage: coverageData, sourceMappingURL: visitState.sourceMappingURL };
  514. }
  515. coverageData[_constants.MAGIC_KEY] = _constants.MAGIC_VALUE;
  516. var hash = (0, _crypto.createHash)(_constants.SHA).update(JSON.stringify(coverageData)).digest('hex');
  517. var coverageNode = T.valueToNode(coverageData);
  518. delete coverageData[_constants.MAGIC_KEY];
  519. var cv = coverageTemplate({
  520. GLOBAL_COVERAGE_VAR: T.stringLiteral(opts.coverageVariable),
  521. COVERAGE_VAR: T.identifier(visitState.varName),
  522. PATH: T.stringLiteral(sourceFilePath),
  523. INITIAL: coverageNode,
  524. HASH: T.stringLiteral(hash)
  525. });
  526. cv._blockHoist = 5;
  527. path.node.body.unshift(cv);
  528. return {
  529. fileCoverage: coverageData,
  530. sourceMappingURL: visitState.sourceMappingURL
  531. };
  532. }
  533. };
  534. }
  535. exports.default = programVisitor;