Skip to content

Commit

Permalink
fix: fix TemplateElement range and loc
Browse files Browse the repository at this point in the history
  • Loading branch information
3cp committed Oct 16, 2020
1 parent ff71744 commit 2a3632c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 21 deletions.
26 changes: 24 additions & 2 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4581,14 +4581,36 @@ export function parseTemplateElement(
col: number,
tail: boolean
): ESTree.TemplateElement {
return finishNode(parser, context, start, line, col, {
const node = finishNode(parser, context, start, line, col, {
type: 'TemplateElement',
value: {
cooked,
raw
},
tail
});
}) as ESTree.TemplateElement;

const tailSize = tail ? 1 : 2;

// Patch range
if (context & Context.OptionsRanges) {
// skip the front "`" or "}"
(node.start as number) += 1;
(node.range as [number, number])[0] += 1;
// skip the tail "`" or "${"
(node.end as number) -= tailSize;
(node.range as [number, number])[1] -= tailSize;
}

// Patch loc
if (context & Context.OptionsLoc) {
// skip the front "`" or "}"
(node.loc as ESTree.SourceLocation).start.column += 1;
// skip the tail "`" or "${"
(node.loc as ESTree.SourceLocation).end.column -= tailSize;
}

return node;
}

/**
Expand Down
18 changes: 9 additions & 9 deletions test/parser/expressions/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4505,9 +4505,9 @@ describe('Expressions - Object', () => {
quasis: [
{
type: 'TemplateElement',
start: 20,
end: 23,
range: [20, 23],
start: 21,
end: 22,
range: [21, 22],
value: {
raw: 'c',
cooked: 'c'
Expand Down Expand Up @@ -4589,9 +4589,9 @@ describe('Expressions - Object', () => {
quasis: [
{
type: 'TemplateElement',
start: 46,
end: 49,
range: [46, 49],
start: 47,
end: 47,
range: [47, 47],
value: {
raw: '',
cooked: ''
Expand All @@ -4600,9 +4600,9 @@ describe('Expressions - Object', () => {
},
{
type: 'TemplateElement',
start: 50,
end: 53,
range: [50, 53],
start: 51,
end: 52,
range: [51, 52],
value: {
raw: 'e',
cooked: 'e'
Expand Down
20 changes: 10 additions & 10 deletions test/parser/expressions/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3510,17 +3510,17 @@ describe('Expressions - Template', () => {
raw: 'a'
},
tail: true,
start: 4,
end: 7,
range: [4, 7],
start: 5,
end: 6,
range: [5, 6],
loc: {
start: {
line: 1,
column: 4
column: 5
},
end: {
line: 1,
column: 7
column: 6
}
}
}
Expand Down Expand Up @@ -3599,17 +3599,17 @@ describe('Expressions - Template', () => {
raw: 'b'
},
tail: true,
start: 12,
end: 15,
range: [12, 15],
start: 13,
end: 14,
range: [13, 14],
loc: {
start: {
line: 2,
column: 4
column: 5
},
end: {
line: 2,
column: 7
column: 6
}
}
}
Expand Down

0 comments on commit 2a3632c

Please sign in to comment.