mapped.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. Copyright 2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. 'use strict';
  6. const { FileCoverage } = require('istanbul-lib-coverage').classes;
  7. function locString(loc) {
  8. return [
  9. loc.start.line,
  10. loc.start.column,
  11. loc.end.line,
  12. loc.end.column
  13. ].join(':');
  14. }
  15. class MappedCoverage extends FileCoverage {
  16. constructor(pathOrObj) {
  17. super(pathOrObj);
  18. this.meta = {
  19. last: {
  20. s: 0,
  21. f: 0,
  22. b: 0
  23. },
  24. seen: {}
  25. };
  26. }
  27. addStatement(loc, hits) {
  28. const key = 's:' + locString(loc);
  29. const { meta } = this;
  30. let index = meta.seen[key];
  31. if (index === undefined) {
  32. index = meta.last.s;
  33. meta.last.s += 1;
  34. meta.seen[key] = index;
  35. this.statementMap[index] = this.cloneLocation(loc);
  36. }
  37. this.s[index] = this.s[index] || 0;
  38. this.s[index] += hits;
  39. return index;
  40. }
  41. addFunction(name, decl, loc, hits) {
  42. const key = 'f:' + locString(decl);
  43. const { meta } = this;
  44. let index = meta.seen[key];
  45. if (index === undefined) {
  46. index = meta.last.f;
  47. meta.last.f += 1;
  48. meta.seen[key] = index;
  49. name = name || `(unknown_${index})`;
  50. this.fnMap[index] = {
  51. name,
  52. decl: this.cloneLocation(decl),
  53. loc: this.cloneLocation(loc)
  54. };
  55. }
  56. this.f[index] = this.f[index] || 0;
  57. this.f[index] += hits;
  58. return index;
  59. }
  60. addBranch(type, loc, branchLocations, hits) {
  61. const key = ['b', ...branchLocations.map(l => locString(l))].join(':');
  62. const { meta } = this;
  63. let index = meta.seen[key];
  64. if (index === undefined) {
  65. index = meta.last.b;
  66. meta.last.b += 1;
  67. meta.seen[key] = index;
  68. this.branchMap[index] = {
  69. loc,
  70. type,
  71. locations: branchLocations.map(l => this.cloneLocation(l))
  72. };
  73. }
  74. if (!this.b[index]) {
  75. this.b[index] = branchLocations.map(() => 0);
  76. }
  77. hits.forEach((hit, i) => {
  78. this.b[index][i] += hit;
  79. });
  80. return index;
  81. }
  82. /* Returns a clone of the location object with only the attributes of interest */
  83. cloneLocation(loc) {
  84. return {
  85. start: {
  86. line: loc.start.line,
  87. column: loc.start.column
  88. },
  89. end: {
  90. line: loc.end.line,
  91. column: loc.end.column
  92. }
  93. };
  94. }
  95. }
  96. module.exports = {
  97. MappedCoverage
  98. };