source.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. const CovLine = require('./line')
  2. const { sliceRange } = require('./range')
  3. const { originalPositionFor, generatedPositionFor, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND } = require('@jridgewell/trace-mapping')
  4. module.exports = class CovSource {
  5. constructor (sourceRaw, wrapperLength) {
  6. sourceRaw = sourceRaw ? sourceRaw.trimEnd() : ''
  7. this.lines = []
  8. this.eof = sourceRaw.length
  9. this.shebangLength = getShebangLength(sourceRaw)
  10. this.wrapperLength = wrapperLength - this.shebangLength
  11. this._buildLines(sourceRaw)
  12. }
  13. _buildLines (source) {
  14. let position = 0
  15. let ignoreCount = 0
  16. let ignoreAll = false
  17. for (const [i, lineStr] of source.split(/(?<=\r?\n)/u).entries()) {
  18. const line = new CovLine(i + 1, position, lineStr)
  19. if (ignoreCount > 0) {
  20. line.ignore = true
  21. ignoreCount--
  22. } else if (ignoreAll) {
  23. line.ignore = true
  24. }
  25. this.lines.push(line)
  26. position += lineStr.length
  27. const ignoreToken = this._parseIgnore(lineStr)
  28. if (!ignoreToken) continue
  29. line.ignore = true
  30. if (ignoreToken.count !== undefined) {
  31. ignoreCount = ignoreToken.count
  32. }
  33. if (ignoreToken.start || ignoreToken.stop) {
  34. ignoreAll = ignoreToken.start
  35. ignoreCount = 0
  36. }
  37. }
  38. }
  39. /**
  40. * Parses for comments:
  41. * c8 ignore next
  42. * c8 ignore next 3
  43. * c8 ignore start
  44. * c8 ignore stop
  45. * And equivalent ones for v8, e.g. v8 ignore next.
  46. * @param {string} lineStr
  47. * @return {{count?: number, start?: boolean, stop?: boolean}|undefined}
  48. */
  49. _parseIgnore (lineStr) {
  50. const testIgnoreNextLines = lineStr.match(/^\W*\/\* (?:[cv]8|node:coverage) ignore next (?<count>[0-9]+)/)
  51. if (testIgnoreNextLines) {
  52. return { count: Number(testIgnoreNextLines.groups.count) }
  53. }
  54. // Check if comment is on its own line.
  55. if (lineStr.match(/^\W*\/\* (?:[cv]8|node:coverage) ignore next/)) {
  56. return { count: 1 }
  57. }
  58. if (lineStr.match(/\/\* ([cv]8|node:coverage) ignore next/)) {
  59. // Won't ignore successive lines, but the current line will be ignored.
  60. return { count: 0 }
  61. }
  62. const testIgnoreStartStop = lineStr.match(/\/\* [c|v]8 ignore (?<mode>start|stop)/)
  63. if (testIgnoreStartStop) {
  64. if (testIgnoreStartStop.groups.mode === 'start') return { start: true }
  65. if (testIgnoreStartStop.groups.mode === 'stop') return { stop: true }
  66. }
  67. const testNodeIgnoreStartStop = lineStr.match(/\/\* node:coverage (?<mode>enable|disable)/)
  68. if (testNodeIgnoreStartStop) {
  69. if (testNodeIgnoreStartStop.groups.mode === 'disable') return { start: true }
  70. if (testNodeIgnoreStartStop.groups.mode === 'enable') return { stop: true }
  71. }
  72. }
  73. // given a start column and end column in absolute offsets within
  74. // a source file (0 - EOF), returns the relative line column positions.
  75. offsetToOriginalRelative (sourceMap, startCol, endCol) {
  76. const lines = sliceRange(this.lines, startCol, endCol, true)
  77. if (!lines.length) return {}
  78. const start = originalPositionTryBoth(
  79. sourceMap,
  80. lines[0].line,
  81. Math.max(0, startCol - lines[0].startCol)
  82. )
  83. if (!(start && start.source)) {
  84. return {}
  85. }
  86. let end = originalEndPositionFor(
  87. sourceMap,
  88. lines[lines.length - 1].line,
  89. endCol - lines[lines.length - 1].startCol
  90. )
  91. if (!(end && end.source)) {
  92. return {}
  93. }
  94. if (start.source !== end.source) {
  95. return {}
  96. }
  97. if (start.line === end.line && start.column === end.column) {
  98. end = originalPositionFor(sourceMap, {
  99. line: lines[lines.length - 1].line,
  100. column: endCol - lines[lines.length - 1].startCol,
  101. bias: LEAST_UPPER_BOUND
  102. })
  103. end.column -= 1
  104. }
  105. return {
  106. source: start.source,
  107. startLine: start.line,
  108. relStartCol: start.column,
  109. endLine: end.line,
  110. relEndCol: end.column
  111. }
  112. }
  113. relativeToOffset (line, relCol) {
  114. line = Math.max(line, 1)
  115. if (this.lines[line - 1] === undefined) return this.eof
  116. return Math.min(this.lines[line - 1].startCol + relCol, this.lines[line - 1].endCol)
  117. }
  118. }
  119. // this implementation is pulled over from istanbul-lib-sourcemap:
  120. // https://github.com/istanbuljs/istanbuljs/blob/master/packages/istanbul-lib-source-maps/lib/get-mapping.js
  121. //
  122. /**
  123. * AST ranges are inclusive for start positions and exclusive for end positions.
  124. * Source maps are also logically ranges over text, though interacting with
  125. * them is generally achieved by working with explicit positions.
  126. *
  127. * When finding the _end_ location of an AST item, the range behavior is
  128. * important because what we're asking for is the _end_ of whatever range
  129. * corresponds to the end location we seek.
  130. *
  131. * This boils down to the following steps, conceptually, though the source-map
  132. * library doesn't expose primitives to do this nicely:
  133. *
  134. * 1. Find the range on the generated file that ends at, or exclusively
  135. * contains the end position of the AST node.
  136. * 2. Find the range on the original file that corresponds to
  137. * that generated range.
  138. * 3. Find the _end_ location of that original range.
  139. */
  140. function originalEndPositionFor (sourceMap, line, column) {
  141. // Given the generated location, find the original location of the mapping
  142. // that corresponds to a range on the generated file that overlaps the
  143. // generated file end location. Note however that this position on its
  144. // own is not useful because it is the position of the _start_ of the range
  145. // on the original file, and we want the _end_ of the range.
  146. const beforeEndMapping = originalPositionTryBoth(
  147. sourceMap,
  148. line,
  149. Math.max(column - 1, 1)
  150. )
  151. if (beforeEndMapping.source === null) {
  152. return null
  153. }
  154. // Convert that original position back to a generated one, with a bump
  155. // to the right, and a rightward bias. Since 'generatedPositionFor' searches
  156. // for mappings in the original-order sorted list, this will find the
  157. // mapping that corresponds to the one immediately after the
  158. // beforeEndMapping mapping.
  159. const afterEndMapping = generatedPositionFor(sourceMap, {
  160. source: beforeEndMapping.source,
  161. line: beforeEndMapping.line,
  162. column: beforeEndMapping.column + 1,
  163. bias: LEAST_UPPER_BOUND
  164. })
  165. if (
  166. // If this is null, it means that we've hit the end of the file,
  167. // so we can use Infinity as the end column.
  168. afterEndMapping.line === null ||
  169. // If these don't match, it means that the call to
  170. // 'generatedPositionFor' didn't find any other original mappings on
  171. // the line we gave, so consider the binding to extend to infinity.
  172. originalPositionFor(sourceMap, afterEndMapping).line !==
  173. beforeEndMapping.line
  174. ) {
  175. return {
  176. source: beforeEndMapping.source,
  177. line: beforeEndMapping.line,
  178. column: Infinity
  179. }
  180. }
  181. // Convert the end mapping into the real original position.
  182. return originalPositionFor(sourceMap, afterEndMapping)
  183. }
  184. function originalPositionTryBoth (sourceMap, line, column) {
  185. let original = originalPositionFor(sourceMap, {
  186. line,
  187. column,
  188. bias: GREATEST_LOWER_BOUND
  189. })
  190. if (original.line === null) {
  191. original = originalPositionFor(sourceMap, {
  192. line,
  193. column,
  194. bias: LEAST_UPPER_BOUND
  195. })
  196. }
  197. // The source maps generated by https://github.com/istanbuljs/istanbuljs
  198. // (using @babel/core 7.7.5) have behavior, such that a mapping
  199. // mid-way through a line maps to an earlier line than a mapping
  200. // at position 0. Using the line at positon 0 seems to provide better reports:
  201. //
  202. // if (true) {
  203. // cov_y5divc6zu().b[1][0]++;
  204. // cov_y5divc6zu().s[3]++;
  205. // console.info('reachable');
  206. // } else { ... }
  207. // ^ ^
  208. // l5 l3
  209. const min = originalPositionFor(sourceMap, {
  210. line,
  211. column: 0,
  212. bias: GREATEST_LOWER_BOUND
  213. })
  214. if (min.line > original.line) {
  215. original = min
  216. }
  217. return original
  218. }
  219. // Not required since Node 12, see: https://github.com/nodejs/node/pull/27375
  220. const isPreNode12 = /^v1[0-1]\./u.test(process.version)
  221. function getShebangLength (source) {
  222. /* c8 ignore start - platform-specific */
  223. if (isPreNode12 && source.indexOf('#!') === 0) {
  224. const match = source.match(/(?<shebang>#!.*)/)
  225. if (match) {
  226. return match.groups.shebang.length
  227. }
  228. } else {
  229. /* c8 ignore stop - platform-specific */
  230. return 0
  231. }
  232. }