Skip to content

Commit

Permalink
Fix TaggedTemplateLiteral evaluation (#15224)
Browse files Browse the repository at this point in the history
* Fix TaggedTemplate evaluation bug

This line of code causes a type error since `TaggedTemplateLiteral`s do not have a property called "expressions".

This change does what is probably expected. However, to maintain the existing behaviour, the line should instead be:

```js
const exprs: Array<undefined | NodePath<t.Node>> = path.isTemplateLiteral()
    ? path.get('expressions')
    : []
```

* Add test

* Review by liuxingbaoyu

Co-authored-by: Nicol貌 Ribaudo <nicolo.ribaudo@gmail.com>
  • Loading branch information
nmn and nicolo-ribaudo committed Jan 3, 2023
1 parent 8e03800 commit d3bce24
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
4 changes: 3 additions & 1 deletion packages/babel-traverse/src/path/evaluation.ts
Expand Up @@ -442,7 +442,9 @@ function evaluateQuasis(
let str = "";

let i = 0;
const exprs = path.get("expressions");
const exprs: Array<NodePath<t.Node>> = path.isTemplateLiteral()
? path.get("expressions")
: path.get("quasi.expressions");

for (const elem of quasis) {
// not confident, evaluated an expression we don't like
Expand Down
27 changes: 21 additions & 6 deletions packages/babel-traverse/test/evaluation.js
Expand Up @@ -100,12 +100,27 @@ describe("evaluation", function () {
).toBe(false);
});

it("should evaluate template literals", function () {
expect(
getPath("var x = 8; var y = 1; var z = `value is ${x >>> y}`")
.get("body.2.declarations.0.init")
.evaluate().value,
).toBe("value is 4");
describe("template literals", function () {
it("should evaluate template literals", function () {
expect(
getPath("var x = 8; var y = 1; var z = `value is ${x >>> y}`")
.get("body.2.declarations.0.init")
.evaluate().value,
).toBe("value is 4");
});

it("shold evaluate String.raw tags", function () {
expect(
getPath("String.raw`a\\n${1}\\u`;").get("body.0.expression").evaluate()
.value,
).toBe("a\\n1\\u");
});

addDeoptTest(
"a`x${b}y`",
"TaggedTemplateExpression",
"TaggedTemplateExpression",
);
});

it("should evaluate member expressions", function () {
Expand Down

0 comments on commit d3bce24

Please sign in to comment.