Debian Codegraph @

packages/babel-plugin-transform-template-literals/src/index.ts

raw symbols SCIP
1 import { declare } from "@babel/helper-plugin-utils";
2 import { template, types as t } from "@babel/core";
3 import type { NodePath } from "@babel/traverse";
4
5 export interface Options {
6 loose?: boolean;
7 }
8
9 export default declare((api, options: Options) => {
10 api.assertVersion(7);
11
12 const ignoreToPrimitiveHint =
13 api.assumption("ignoreToPrimitiveHint") ?? options.loose;
14 const mutableTemplateObject =
15 api.assumption("mutableTemplateObject") ?? options.loose;
16
17 let helperName = "taggedTemplateLiteral";
18 if (mutableTemplateObject) helperName += "Loose";
19
20 /**
21 * This function groups the objects into multiple calls to `.concat()` in
22 * order to preserve execution order of the primitive conversion, e.g.
23 *
24 * "".concat(obj.foo, "foo", obj2.foo, "foo2")
25 *
26 * would evaluate both member expressions _first_ then, `concat` will
27 * convert each one to a primitive, whereas
28 *
29 * "".concat(obj.foo, "foo").concat(obj2.foo, "foo2")
30 *
31 * would evaluate the member, then convert it to a primitive, then evaluate
32 * the second member and convert that one, which reflects the spec behavior
33 * of template literals.
34 */
35 function buildConcatCallExpressions(items: t.Expression[]): t.CallExpression {
36 let avail = true;
37 // @ts-expect-error items must not be empty
38 return items.reduce(function (left, right) {
39 let canBeInserted = t.isLiteral(right);
40
41 if (!canBeInserted && avail) {
42 canBeInserted = true;
43 avail = false;
44 }
45 if (canBeInserted && t.isCallExpression(left)) {
46 left.arguments.push(right);
47 return left;
48 }
49 return t.callExpression(
50 t.memberExpression(left, t.identifier("concat")),
51 [right],
52 );
53 });
54 }
55
56 return {
57 name: "transform-template-literals",
58
59 visitor: {
60 TaggedTemplateExpression(path) {
61 const { node } = path;
62 const { quasi } = node;
63
64 const strings = [];
65 const raws = [];
66
67 // Flag variable to check if contents of strings and raw are equal
68 let isStringsRawEqual = true;
69
70 for (const elem of quasi.quasis) {
71 const { raw, cooked } = elem.value;
72 const value =
73 cooked == null
74 ? path.scope.buildUndefinedNode()
75 : t.stringLiteral(cooked);
76
77 strings.push(value);
78 raws.push(t.stringLiteral(raw));
79
80 if (raw !== cooked) {
81 // false even if one of raw and cooked are not equal
82 isStringsRawEqual = false;
83 }
84 }
85
86 const helperArgs = [t.arrayExpression(strings)];
87 // only add raw arrayExpression if there is any difference between raws and strings
88 if (!isStringsRawEqual) {
89 helperArgs.push(t.arrayExpression(raws));
90 }
91
92 const tmp = path.scope.generateUidIdentifier("templateObject");
93 path.scope.getProgramParent().push({ id: t.cloneNode(tmp) });
94
95 path.replaceWith(
96 t.callExpression(node.tag, [
97 template.expression.ast`
98 ${t.cloneNode(tmp)} || (
99 ${tmp} = ${this.addHelper(helperName)}(${helperArgs})
100 )
101 `,
102 // @ts-expect-error Fixme: quasi.expressions may contain TSAnyKeyword
103 ...quasi.expressions,
104 ]),
105 );
106 },
107
108 TemplateLiteral(path) {
109 // Skip TemplateLiteral in TSLiteralType
110 if (path.parent.type === "TSLiteralType") {
111 return;
112 }
113 const nodes: t.Expression[] = [];
114 const expressions = path.get("expressions") as NodePath<t.Expression>[];
115
116 let index = 0;
117 for (const elem of path.node.quasis) {
118 if (elem.value.cooked) {
119 nodes.push(t.stringLiteral(elem.value.cooked));
120 }
121
122 if (index < expressions.length) {
123 const expr = expressions[index++];
124 const node = expr.node;
125 if (!t.isStringLiteral(node, { value: "" })) {
126 nodes.push(node);
127 }
128 }
129 }
130
131 // since `+` is left-to-right associative
132 // ensure the first node is a string if first/second isn't
133 if (
134 !t.isStringLiteral(nodes[0]) &&
135 !(ignoreToPrimitiveHint && t.isStringLiteral(nodes[1]))
136 ) {
137 nodes.unshift(t.stringLiteral(""));
138 }
139 let root = nodes[0];
140
141 if (ignoreToPrimitiveHint) {
142 for (let i = 1; i < nodes.length; i++) {
143 root = t.binaryExpression("+", root, nodes[i]);
144 }
145 } else if (nodes.length > 1) {
146 root = buildConcatCallExpressions(nodes);
147 }
148
149 path.replaceWith(root);
150 },
151 },
152 };
153 });