| 1 |
import { types as t, template } from "@babel/core"; |
| 2 |
import type { NodePath } from "@babel/traverse"; |
| 3 |
import { |
| 4 |
skipTransparentExprWrapperNodes, |
| 5 |
skipTransparentExprWrappers, |
| 6 |
} from "@babel/helper-skip-transparent-expression-wrappers"; |
| 7 |
import { willPathCastToBoolean, findOutermostTransparentParent } from "./util"; |
| 8 |
|
| 9 |
const { ast } = template.expression; |
| 10 |
|
| 11 |
function isSimpleMemberExpression( |
| 12 |
expression: t.Expression | t.Super, |
| 13 |
): expression is t.Identifier | t.Super | t.MemberExpression { |
| 14 |
expression = skipTransparentExprWrapperNodes(expression); |
| 15 |
return ( |
| 16 |
t.isIdentifier(expression) || |
| 17 |
t.isSuper(expression) || |
| 18 |
(t.isMemberExpression(expression) && |
| 19 |
!expression.computed && |
| 20 |
isSimpleMemberExpression(expression.object)) |
| 21 |
); |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Test if a given optional chain `path` needs to be memoized |
| 26 |
* @param {NodePath} path |
| 27 |
* @returns {boolean} |
| 28 |
*/ |
| 29 |
function needsMemoize( |
| 30 |
path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>, |
| 31 |
) { |
| 32 |
let optionalPath: NodePath = path; |
| 33 |
const { scope } = path; |
| 34 |
while ( |
| 35 |
optionalPath.isOptionalMemberExpression() || |
| 36 |
optionalPath.isOptionalCallExpression() |
| 37 |
) { |
| 38 |
const { node } = optionalPath; |
| 39 |
const childPath = skipTransparentExprWrappers( |
| 40 |
// @ts-expect-error isOptionalMemberExpression does not work with NodePath union |
| 41 |
optionalPath.isOptionalMemberExpression() |
| 42 |
? optionalPath.get("object") |
| 43 |
: optionalPath.get("callee"), |
| 44 |
); |
| 45 |
if (node.optional) { |
| 46 |
return !scope.isStatic(childPath.node); |
| 47 |
} |
| 48 |
|
| 49 |
optionalPath = childPath; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
export function transform( |
| 54 |
path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>, |
| 55 |
{ |
| 56 |
pureGetters, |
| 57 |
noDocumentAll, |
| 58 |
}: { pureGetters: boolean; noDocumentAll: boolean }, |
| 59 |
) { |
| 60 |
const { scope } = path; |
| 61 |
// maybeWrapped points to the outermost transparent expression wrapper |
| 62 |
// or the path itself |
| 63 |
const maybeWrapped = findOutermostTransparentParent(path); |
| 64 |
const { parentPath } = maybeWrapped; |
| 65 |
const willReplacementCastToBoolean = willPathCastToBoolean(maybeWrapped); |
| 66 |
let isDeleteOperation = false; |
| 67 |
const parentIsCall = |
| 68 |
parentPath.isCallExpression({ callee: maybeWrapped.node }) && |
| 69 |
// note that the first condition must implies that `path.optional` is `true`, |
| 70 |
// otherwise the parentPath should be an OptionalCallExpression |
| 71 |
path.isOptionalMemberExpression(); |
| 72 |
|
| 73 |
const optionals = []; |
| 74 |
|
| 75 |
let optionalPath = path; |
| 76 |
// Replace `function (a, x = a.b?.c) {}` to `function (a, x = (() => a.b?.c)() ){}` |
| 77 |
// so the temporary variable can be injected in correct scope |
| 78 |
if (scope.path.isPattern() && needsMemoize(optionalPath)) { |
| 79 |
path.replaceWith(template.ast`(() => ${path.node})()` as t.Statement); |
| 80 |
// The injected optional chain will be queued and eventually transformed when visited |
| 81 |
return; |
| 82 |
} |
| 83 |
while ( |
| 84 |
optionalPath.isOptionalMemberExpression() || |
| 85 |
optionalPath.isOptionalCallExpression() |
| 86 |
) { |
| 87 |
const { node } = optionalPath; |
| 88 |
if (node.optional) { |
| 89 |
optionals.push(node); |
| 90 |
} |
| 91 |
// @ts-expect-error isOptionalMemberExpression does not work with NodePath union |
| 92 |
if (optionalPath.isOptionalMemberExpression()) { |
| 93 |
// @ts-expect-error todo(flow->ts) avoid changing more type |
| 94 |
optionalPath.node.type = "MemberExpression"; |
| 95 |
// @ts-expect-error todo(flow->ts) |
| 96 |
optionalPath = skipTransparentExprWrappers(optionalPath.get("object")); |
| 97 |
} else if (optionalPath.isOptionalCallExpression()) { |
| 98 |
// @ts-expect-error todo(flow->ts) avoid changing more type |
| 99 |
optionalPath.node.type = "CallExpression"; |
| 100 |
// @ts-expect-error todo(flow->ts) |
| 101 |
optionalPath = skipTransparentExprWrappers(optionalPath.get("callee")); |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
// todo: Improve replacementPath typings |
| 106 |
let replacementPath: NodePath<any> = path; |
| 107 |
if (parentPath.isUnaryExpression({ operator: "delete" })) { |
| 108 |
replacementPath = parentPath; |
| 109 |
isDeleteOperation = true; |
| 110 |
} |
| 111 |
for (let i = optionals.length - 1; i >= 0; i--) { |
| 112 |
const node = optionals[i] as unknown as |
| 113 |
| t.MemberExpression |
| 114 |
| t.CallExpression; |
| 115 |
|
| 116 |
const isCall = t.isCallExpression(node); |
| 117 |
|
| 118 |
const chainWithTypes = isCall |
| 119 |
? // V8 intrinsics must not be an optional call |
| 120 |
(node.callee as t.Expression) |
| 121 |
: node.object; |
| 122 |
const chain = skipTransparentExprWrapperNodes(chainWithTypes); |
| 123 |
|
| 124 |
let ref; |
| 125 |
let check; |
| 126 |
if (isCall && t.isIdentifier(chain, { name: "eval" })) { |
| 127 |
check = ref = chain; |
| 128 |
// `eval?.()` is an indirect eval call transformed to `(0,eval)()` |
| 129 |
node.callee = t.sequenceExpression([t.numericLiteral(0), ref]); |
| 130 |
} else if (pureGetters && isCall && isSimpleMemberExpression(chain)) { |
| 131 |
// If we assume getters are pure (avoiding a Function#call) and we are at the call, |
| 132 |
// we can avoid a needless memoize. We only do this if the callee is a simple member |
| 133 |
// expression, to avoid multiple calls to nested call expressions. |
| 134 |
check = ref = node.callee; |
| 135 |
} else { |
| 136 |
ref = scope.maybeGenerateMemoised(chain); |
| 137 |
if (ref) { |
| 138 |
check = t.assignmentExpression( |
| 139 |
"=", |
| 140 |
t.cloneNode(ref), |
| 141 |
// Here `chainWithTypes` MUST NOT be cloned because it could be |
| 142 |
// updated when generating the memoised context of a call |
| 143 |
// expression. It must be an Expression when `ref` is an identifier |
| 144 |
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion |
| 145 |
chainWithTypes as t.Expression, |
| 146 |
); |
| 147 |
|
| 148 |
isCall ? (node.callee = ref) : (node.object = ref); |
| 149 |
} else { |
| 150 |
check = ref = chainWithTypes; |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
// Ensure call expressions have the proper `this` |
| 155 |
// `foo.bar()` has context `foo`. |
| 156 |
if (isCall && t.isMemberExpression(chain)) { |
| 157 |
if (pureGetters && isSimpleMemberExpression(chain)) { |
| 158 |
// To avoid a Function#call, we can instead re-grab the property from the context object. |
| 159 |
// `a.?b.?()` translates roughly to `_a.b != null && _a.b()` |
| 160 |
node.callee = chainWithTypes; |
| 161 |
} else { |
| 162 |
// Otherwise, we need to memoize the context object, and change the call into a Function#call. |
| 163 |
// `a.?b.?()` translates roughly to `(_b = _a.b) != null && _b.call(_a)` |
| 164 |
const { object } = chain; |
| 165 |
let context: t.Expression; |
| 166 |
if (t.isSuper(object)) { |
| 167 |
context = t.thisExpression(); |
| 168 |
} else { |
| 169 |
const memoized = scope.maybeGenerateMemoised(object); |
| 170 |
if (memoized) { |
| 171 |
context = memoized; |
| 172 |
chain.object = t.assignmentExpression("=", memoized, object); |
| 173 |
} else { |
| 174 |
context = object; |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
node.arguments.unshift(t.cloneNode(context)); |
| 179 |
// @ts-expect-error node.callee can not be an V8IntrinsicIdentifier: V8 intrinsic is disallowed in optional chain |
| 180 |
node.callee = t.memberExpression(node.callee, t.identifier("call")); |
| 181 |
} |
| 182 |
} |
| 183 |
let replacement = replacementPath.node; |
| 184 |
// Ensure (a?.b)() has proper `this` |
| 185 |
// The `parentIsCall` is constant within loop, we should check i === 0 |
| 186 |
// to ensure that it is only applied to the first optional chain element |
| 187 |
// i.e. `?.b` in `(a?.b.c)()` |
| 188 |
if (i === 0 && parentIsCall) { |
| 189 |
// `(a?.b)()` to `(a == null ? undefined : a.b.bind(a))()` |
| 190 |
// object must not be Super as super?.foo is invalid |
| 191 |
const object = skipTransparentExprWrapperNodes( |
| 192 |
replacement.object, |
| 193 |
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion |
| 194 |
) as any as t.Expression; |
| 195 |
let baseRef; |
| 196 |
if (!pureGetters || !isSimpleMemberExpression(object)) { |
| 197 |
// memoize the context object when getters are not always pure |
| 198 |
// or the object is not a simple member expression |
| 199 |
// `(a?.b.c)()` to `(a == null ? undefined : (_a$b = a.b).c.bind(_a$b))()` |
| 200 |
baseRef = scope.maybeGenerateMemoised(object); |
| 201 |
if (baseRef) { |
| 202 |
replacement.object = t.assignmentExpression("=", baseRef, object); |
| 203 |
} |
| 204 |
} |
| 205 |
replacement = t.callExpression( |
| 206 |
t.memberExpression(replacement, t.identifier("bind")), |
| 207 |
[t.cloneNode(baseRef ?? object)], |
| 208 |
); |
| 209 |
} |
| 210 |
|
| 211 |
if (willReplacementCastToBoolean) { |
| 212 |
// `if (a?.b) {}` transformed to `if (a != null && a.b) {}` |
| 213 |
// we don't need to return `void 0` because the returned value will |
| 214 |
// eveutally cast to boolean. |
| 215 |
const nonNullishCheck = noDocumentAll |
| 216 |
? ast`${t.cloneNode(check)} != null` |
| 217 |
: ast` |
| 218 |
${t.cloneNode(check)} !== null && ${t.cloneNode(ref)} !== void 0`; |
| 219 |
replacementPath.replaceWith( |
| 220 |
t.logicalExpression("&&", nonNullishCheck, replacement), |
| 221 |
); |
| 222 |
replacementPath = skipTransparentExprWrappers( |
| 223 |
// @ts-expect-error todo(flow->ts) |
| 224 |
replacementPath.get("right"), |
| 225 |
); |
| 226 |
} else { |
| 227 |
const nullishCheck = noDocumentAll |
| 228 |
? ast`${t.cloneNode(check)} == null` |
| 229 |
: ast` |
| 230 |
${t.cloneNode(check)} === null || ${t.cloneNode(ref)} === void 0`; |
| 231 |
|
| 232 |
const returnValue = isDeleteOperation ? ast`true` : ast`void 0`; |
| 233 |
replacementPath.replaceWith( |
| 234 |
t.conditionalExpression(nullishCheck, returnValue, replacement), |
| 235 |
); |
| 236 |
replacementPath = skipTransparentExprWrappers( |
| 237 |
// @ts-expect-error todo(flow->ts) |
| 238 |
replacementPath.get("alternate"), |
| 239 |
); |
| 240 |
} |
| 241 |
} |
| 242 |
} |