Skip to content

Commit

Permalink
fix(source-maps): map nameless nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbonnet committed Jan 3, 2021
1 parent 967363d commit 102e569
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 12 deletions.
16 changes: 6 additions & 10 deletions src/astring.js
Original file line number Diff line number Diff line change
Expand Up @@ -1052,16 +1052,18 @@ class State {
this.line++
return
}
if (node.loc != null) {
const { mapping } = this
mapping.original = node.loc.start
mapping.name = node.name
this.sourceMap.addMapping(mapping)
}
if (
(type[0] === 'T' && type[8] === 'E') ||
(type[0] === 'L' && type[1] === 'i' && typeof node.value === 'string')
) {
// TemplateElement or Literal string node
const { length } = code
if (length === 0 || (length === 2 && type[0] === 'L')) {
// Empty TemplateElement or Literal string with begin and end quotes
return
}
let { column, line } = this
for (let i = 0; i < length; i++) {
if (code[i] === '\n') {
Expand All @@ -1075,12 +1077,6 @@ class State {
this.line = line
return
}
if (node.name != null) {
const { mapping } = this
mapping.original = node.loc.start
mapping.name = node.name
this.sourceMap.addMapping(mapping)
}
}
const { length } = code
const { lineEnd } = this
Expand Down
42 changes: 40 additions & 2 deletions src/tests/astring.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,12 @@ test('Source map generation', (assert) => {
const code = readFile(path.join(dirname, filename))
const sourceMap = {
mappings: [],
_file: 'script.js',
_file: filename,
addMapping({ original, generated, name, source }) {
assert.deepEqual(
pick(generated, ['line', 'column']),
pick(original, ['line', 'column']),
`${filename}:${name}`,
`${source}:${name}`,
)
assert.is(source, this._file)
this.mappings.push({
Expand All @@ -156,3 +156,41 @@ test('Source map generation', (assert) => {
})
})
})

test('Source map generation with comments', (assert) => {
const dirname = path.join(FIXTURES_FOLDER, 'comment')
const files = fs.readdirSync(dirname).sort()
files.forEach((filename) => {
const code = readFile(path.join(dirname, filename))
const sourceMap = {
mappings: [],
_file: filename,
addMapping({ original, generated, name, source }) {
assert.deepEqual(
pick(generated, ['line', 'column']),
pick(original, ['line', 'column']),
`${source}:${name}`,
)
assert.is(source, this._file)
this.mappings.push({
original,
generated,
name,
source,
})
},
}
const comments = []
const ast = parse(code, {
ecmaVersion,
comments: true,
locations: true,
onComment: comments,
})
astravel.attachComments(ast, comments)
generate(ast, {
sourceMap,
comments: true,
})
})
})

0 comments on commit 102e569

Please sign in to comment.