forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
97 lines (80 loc) · 2.73 KB
/
index.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
export default function ({ types: t }) {
function buildConcatCallExressions(items) {
return items.reduce(function(left, right) {
const isString = t.isStringLiteral(right);
const canBeInserted = !left._withIdentifier || isString;
if (t.isCallExpression(left) && canBeInserted) {
left._withIdentifier = left._withIdentifier || !isString;
left.arguments.push(right);
return left;
}
const nextCall = t.callExpression(
t.memberExpression(left, t.identifier("concat")),
[right]
);
nextCall._withIdentifier = !isString;
return nextCall;
});
}
return {
visitor: {
TaggedTemplateExpression(path, state) {
const { node } = path;
const { quasi } = node;
const strings = [];
const raws = [];
for (const elem of (quasi.quasis: Array)) {
const { raw, cooked } = elem.value;
const value = cooked == null
? path.scope.buildUndefinedNode()
: t.stringLiteral(cooked);
strings.push(value);
raws.push(t.stringLiteral(raw));
}
let templateName = "taggedTemplateLiteral";
if (state.opts.loose) templateName += "Loose";
const templateObject = state.file.addTemplateObject(
templateName,
t.arrayExpression(strings),
t.arrayExpression(raws)
);
const args = [templateObject].concat(quasi.expressions);
path.replaceWith(t.callExpression(node.tag, args));
},
TemplateLiteral(path, state) {
const nodes = [];
const expressions = path.get("expressions");
let index = 0;
for (const elem of (path.node.quasis: Array)) {
if (elem.value.cooked) {
nodes.push(t.stringLiteral(elem.value.cooked));
}
if (index < expressions.length) {
const expr = expressions[index++];
const node = expr.node;
if (!t.isStringLiteral(node, { value: "" })) {
nodes.push(node);
}
}
}
// since `+` is left-to-right associative
// ensure the first node is a string if first/second isn't
const considerSecondNode = state.opts.spec || !t.isStringLiteral(nodes[1]);
if (!t.isStringLiteral(nodes[0]) && considerSecondNode) {
nodes.unshift(t.stringLiteral(""));
}
let root = nodes[0];
if (state.opts.spec) {
if (nodes.length > 1) {
root = buildConcatCallExressions(nodes);
}
} else {
for (let i = 1; i < nodes.length; i++) {
root = t.binaryExpression("+", root, nodes[i]);
}
}
path.replaceWith(root);
},
},
};
}