MCPcopy Create free account
hub / github.com/babel/babel / transform

Function transform

packages/babel-plugin-transform-optional-chaining/src/transform.ts:239–300  ·  view source on GitHub ↗
(
  path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,
  assumptions: OptionalChainAssumptions,
)

Source from the content-addressed store, hash-verified

237}
238
239export function transform(
240 path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,
241 assumptions: OptionalChainAssumptions,
242) {
243 const { scope } = path;
244
245 // maybeWrapped points to the outermost transparent expression wrapper
246 // or the path itself
247 const maybeWrapped = findOutermostTransparentParent(path);
248 const { parentPath } = maybeWrapped;
249
250 if (parentPath.isUnaryExpression({ operator: "delete" })) {
251 transformOptionalChain(
252 path,
253 assumptions,
254 parentPath,
255 t.booleanLiteral(true),
256 );
257 } else {
258 let wrapLast: ((value: t.Expression) => t.Expression) | undefined;
259 if (
260 parentPath.isCallExpression({ callee: maybeWrapped.node }) &&
261 // note that the first condition must implies that `path.optional` is `true`,
262 // otherwise the parentPath should be an OptionalCallExpression
263 path.isOptionalMemberExpression()
264 ) {
265 // Ensure (a?.b)() has proper `this`
266 wrapLast = ((replacement: t.MemberExpression) => {
267 // `(a?.b)()` to `(a == null ? undefined : a.b.bind(a))()`
268 // object must not be Super as super?.foo is invalid
269
270 const object = skipTransparentExprWrapperNodes(
271 replacement.object,
272 ) as t.Expression;
273 let baseRef: t.Expression | undefined;
274 if (!assumptions.pureGetters || !isSimpleMemberExpression(object)) {
275 // memoize the context object when getters are not always pure
276 // or the object is not a simple member expression
277 // `(a?.b.c)()` to `(a == null ? undefined : (_a$b = a.b).c.bind(_a$b))()`
278 baseRef = scope.maybeGenerateMemoised(object)!;
279 if (baseRef) {
280 replacement.object = t.assignmentExpression("=", baseRef, object);
281 }
282 }
283 return t.callExpression(
284 t.memberExpression(replacement, t.identifier("bind")),
285 [t.cloneNode(baseRef ?? object)],
286 );
287 }) as (value: t.Expression) => t.Expression;
288 }
289
290 transformOptionalChain(
291 path,
292 assumptions,
293 path,
294 willPathCastToBoolean(maybeWrapped)
295 ? t.booleanLiteral(false)
296 : t.buildUndefinedNode(),

Calls 9

willPathCastToBooleanFunction · 0.90
transformOptionalChainFunction · 0.85
isSimpleMemberExpressionFunction · 0.85
isUnaryExpressionMethod · 0.80
isCallExpressionMethod · 0.80
maybeGenerateMemoisedMethod · 0.80

Tested by

no test coverage detected