visitor.js 20 KB

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