-
Notifications
You must be signed in to change notification settings - Fork 109
/
template-literals.js
195 lines (163 loc) · 5.78 KB
/
template-literals.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/**
* Replaces string concatenation with template literals.
* Adapted from https://vramana.github.io/blog/2015/12/21/codemod-tutorial/
*
* Areas of improvement:
*
* - Comments in the middle of string concatenation are currently added before
* the string but after the assignment. Perhaps in these situations, the
* string concatenation should be preserved as-is.
*
* - Nested concatenation inside template literals is not currently simplified.
* Currently, a + `b${'c' + d}` becomes `${a}b${'c' + d}` but it would ideally
* become `${a}b${`c${d}`}`.
*
* - Unnecessary escaping of quotes from the resulting template literals is
* currently not removed. This is possibly the domain of a different
* transform.
*
* - Unicode escape sequences are converted to unicode characters when
* the simplified concatenation results in a string literal instead of a
* template literal. It would be nice to preserve the original--whether it be
* a unicode escape sequence or a unicode character.
*/
module.exports = function templateLiterals(file, api, options) {
const j = api.jscodeshift;
const printOptions = options.printOptions || {quote: 'single'};
function extractNodes(node, comments, topLevel = false) {
if (comments) {
node.comments = node.comments || [];
node.comments.push(...comments);
}
if (node.type !== 'BinaryExpression') {
return [node];
}
if (node.operator !== '+') {
return [node];
}
if (!topLevel && node.parenthesizedExpression) {
return [node];
}
// We need to be careful about not having a stringish node on the left to
// prevent things like 1 + 2 + 'foo', which should evaluate to '3foo' from
// becoming '12foo'.
return [
...(hasStringish(node.left) ? extractNodes(node.left) : [node.left]),
...extractNodes(node.right, node.comments),
];
}
function isStringNode(node) {
return node.type === 'Literal' && (typeof node.value === 'string');
}
function isCastToStringNode(node) {
// foo.toString()
if (
node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'toString'
) {
return true;
}
// String(foo) and new String(foo)
if (
['CallExpression', 'NewExpression'].indexOf(node.type) !== -1 &&
node.callee.type === 'Identifier' &&
node.callee.name === 'String'
) {
return true;
}
return false;
}
function isTemplateLiteralNode(node) {
return node.type === 'TemplateLiteral';
}
function isBinaryExpressionNode(node) {
return node.type === 'BinaryExpression';
}
function isStringishNode(node) {
return (
isStringNode(node) ||
isTemplateLiteralNode(node) ||
isCastToStringNode(node)
);
}
function hasStringish(node) {
if (isBinaryExpressionNode(node)) {
return hasStringish(node.left) || hasStringish(node.right);
}
return isStringishNode(node);
}
function joinQuasis(leftQuasis, rightQuasis) {
const lastQuasi = leftQuasis.pop();
if (lastQuasi) {
rightQuasis[0] = j.templateElement({
cooked: lastQuasi.value.cooked + rightQuasis[0].value.cooked,
raw: lastQuasi.value.raw + rightQuasis[0].value.raw,
}, false);
}
return leftQuasis.concat(rightQuasis);
}
function buildTL(nodes, quasis = [], expressions = [], comments = []) {
if (nodes.length === 0) {
return { quasis, expressions, comments };
}
const [node, ...rest] = nodes;
const newComments = comments.concat(node.comments || []);
if (node.type === 'Literal') {
const cooked = node.value.toString();
let raw = node.raw.toString();
if (typeof node.value === 'string') {
// We need to remove the opening and trailing quote from the raw value
// of the string.
raw = raw.slice(1, -1);
// We need to escape ${ to prevent new interpolation.
raw = raw.replace(/\$\{/g, '\\${');
}
const newQuasi = j.templateElement({ cooked, raw }, false);
const newQuasis = joinQuasis(quasis, [newQuasi]);
return buildTL(rest, newQuasis, expressions, newComments);
}
if (node.type === 'TemplateLiteral') {
const nodeQuasis = node.quasis.map((q) => (
j.templateElement({
cooked: q.value.cooked,
raw: q.value.raw,
}, false)
));
// We need to join the last quasi and the next quasi to prevent
// expressions from shifting.
const newQuasis = joinQuasis(quasis, nodeQuasis);
const newExpressions = expressions.concat(node.expressions);
return buildTL(rest, newQuasis, newExpressions, newComments);
}
const newQuasis = joinQuasis(quasis, [
j.templateElement({ cooked: '', raw: '' }, false),
j.templateElement({ cooked: '', raw: '' }, false),
]);
const newExpressions = expressions.concat(node);
return buildTL(rest, newQuasis, newExpressions, newComments);
}
function convertToTemplateString(p) {
const tempNodes = extractNodes(p.node, null, true);
if (!tempNodes.some(isStringishNode)) {
return p.node;
}
const tlOptions = buildTL(tempNodes);
const tl = j.templateLiteral(tlOptions.quasis, tlOptions.expressions);
if (tl.expressions.length > 0) {
tl.comments = tlOptions.comments;
return tl;
}
// There are no expressions, so let's use a regular string instead of a
// template literal.
const str = tl.quasis.map(q => q.value.cooked).join('');
const strLiteral = j.literal(str);
strLiteral.comments = tlOptions.comments;
return strLiteral;
}
return j(file.source)
.find(j.BinaryExpression, { operator: '+' })
.replaceWith(convertToTemplateString)
.toSource(printOptions);
};