source.js 7.7 KB

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