forked from babel/babel
/
index.ts
247 lines (207 loc) · 7.92 KB
/
index.ts
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { declare } from "@babel/helper-plugin-utils";
import { types as t, template } from "@babel/core";
import type { Visitor, Scope } from "@babel/traverse";
export interface Options {
allowMutablePropsOnTags?: null | string[];
}
interface VisitorState {
isImmutable: boolean;
mutablePropsAllowed: boolean;
jsxScope: Scope;
targetScope: Scope;
}
export default declare((api, options: Options) => {
api.assertVersion(7);
const { allowMutablePropsOnTags } = options;
if (
allowMutablePropsOnTags != null &&
!Array.isArray(allowMutablePropsOnTags)
) {
throw new Error(
".allowMutablePropsOnTags must be an array, null, or undefined.",
);
}
// Element -> Target scope
const HOISTED = new WeakMap();
function declares(node: t.Identifier | t.JSXIdentifier, scope) {
if (
t.isJSXIdentifier(node, { name: "this" }) ||
t.isJSXIdentifier(node, { name: "arguments" }) ||
t.isJSXIdentifier(node, { name: "super" }) ||
t.isJSXIdentifier(node, { name: "new" })
) {
const { path } = scope;
return path.isFunctionParent() && !path.isArrowFunctionExpression();
}
return scope.hasOwnBinding(node.name);
}
function isHoistingScope({ path }) {
return path.isFunctionParent() || path.isLoop() || path.isProgram();
}
function getHoistingScope(scope) {
while (!isHoistingScope(scope)) scope = scope.parent;
return scope;
}
const immutabilityVisitor: Visitor<VisitorState> = {
enter(path, state) {
const stop = () => {
state.isImmutable = false;
path.stop();
};
const skip = () => {
path.skip();
};
if (path.isJSXClosingElement()) return skip();
// Elements with refs are not safe to hoist.
if (
path.isJSXIdentifier({ name: "ref" }) &&
path.parentPath.isJSXAttribute({ name: path.node })
) {
return stop();
}
// Ignore JSX expressions and immutable values.
if (
path.isJSXIdentifier() ||
path.isJSXMemberExpression() ||
path.isJSXNamespacedName() ||
path.isImmutable()
) {
return;
}
// Ignore constant bindings.
if (path.isIdentifier()) {
const binding = path.scope.getBinding(path.node.name);
if (binding && binding.constant) return;
}
// If we allow mutable props, tags with function expressions can be
// safely hoisted.
const { mutablePropsAllowed } = state;
if (mutablePropsAllowed && path.isFunction()) {
path.traverse(targetScopeVisitor, state);
return skip();
}
if (!path.isPure()) return stop();
// If it's not immutable, it may still be a pure expression, such as string concatenation.
// It is still safe to hoist that, so long as its result is immutable.
// If not, it is not safe to replace as mutable values (like objects) could be mutated after render.
// https://github.com/facebook/react/issues/3226
const expressionResult = path.evaluate();
if (expressionResult.confident) {
// We know the result; check its mutability.
const { value } = expressionResult;
if (
mutablePropsAllowed ||
value === null ||
(typeof value !== "object" && typeof value !== "function")
) {
// It evaluated to an immutable value, so we can hoist it.
return skip();
}
} else if (t.isIdentifier(expressionResult.deopt)) {
// It's safe to hoist here if the deopt reason is an identifier (e.g. func param).
// The hoister will take care of how high up it can be hoisted.
return;
}
stop();
},
};
const targetScopeVisitor: Visitor<VisitorState> = {
ReferencedIdentifier(path, state) {
const { node } = path;
let { scope } = path;
while (scope !== state.jsxScope) {
// If a binding is declared in an inner function, it doesn't affect hoisting.
if (declares(node, scope)) return;
scope = scope.parent;
}
while (scope) {
// We cannot hoist outside of the previous hoisting target
// scope, so we return early and we don't update it.
if (scope === state.targetScope) return;
// If the scope declares this identifier (or we're at the function
// providing the lexical env binding), we can't hoist the var any
// higher.
if (declares(node, scope)) break;
scope = scope.parent;
}
state.targetScope = getHoistingScope(scope);
},
};
// We cannot use traverse.visitors.merge because it doesn't support
// immutabilityVisitor's bare `enter` visitor.
// It's safe to just use ... because the two visitors don't share any key.
const hoistingVisitor = { ...immutabilityVisitor, ...targetScopeVisitor };
return {
name: "transform-react-constant-elements",
visitor: {
JSXElement(path) {
if (HOISTED.has(path.node)) return;
HOISTED.set(path.node, path.scope);
const name = path.node.openingElement.name;
// This transform takes the option `allowMutablePropsOnTags`, which is an array
// of JSX tags to allow mutable props (such as objects, functions) on. Use sparingly
// and only on tags you know will never modify their own props.
let mutablePropsAllowed = false;
if (allowMutablePropsOnTags != null) {
// Get the element's name. If it's a member expression, we use the last part of the path.
// So the option ["FormattedMessage"] would match "Intl.FormattedMessage".
let lastSegment = name;
while (t.isJSXMemberExpression(lastSegment)) {
lastSegment = lastSegment.property;
}
const elementName = lastSegment.name;
// @ts-expect-error Fixme: allowMutablePropsOnTags should handle JSXNamespacedName
mutablePropsAllowed = allowMutablePropsOnTags.includes(elementName);
}
// In order to avoid hoisting unnecessarily, we need to know which is
// the scope containing the current JSX element. If a parent of the
// current element has already been hoisted, we can consider its target
// scope as the base scope for the current element.
let jsxScope;
let current = path;
while (!jsxScope && current.parentPath.isJSX()) {
// @ts-ignore current is a search pointer
current = current.parentPath;
jsxScope = HOISTED.get(current.node);
}
jsxScope ??= path.scope;
const visitorState: VisitorState = {
isImmutable: true,
mutablePropsAllowed,
jsxScope,
targetScope: path.scope.getProgramParent(),
};
path.traverse(hoistingVisitor, visitorState);
if (!visitorState.isImmutable) return;
const { targetScope } = visitorState;
HOISTED.set(path.node, targetScope);
// Only hoist if it would give us an advantage.
for (let currentScope = jsxScope; ; ) {
if (targetScope === currentScope) return;
if (isHoistingScope(currentScope)) break;
currentScope = currentScope.parent;
if (!currentScope) {
throw new Error(
"Internal @babel/plugin-transform-react-constant-elements error: " +
"targetScope must be an ancestor of jsxScope. " +
"This is a Babel bug, please report it.",
);
}
}
const id = path.scope.generateUidBasedOnNode(name);
targetScope.push({ id: t.identifier(id) });
let replacement: t.Expression | t.JSXExpressionContainer = template
.expression.ast`
${t.identifier(id)} || (${t.identifier(id)} = ${path.node})
`;
if (
path.parentPath.isJSXElement() ||
path.parentPath.isJSXAttribute()
) {
replacement = t.jsxExpressionContainer(replacement);
}
path.replaceWith(replacement);
},
},
};
});