Debian Codegraph @

packages/babel-helper-optimise-call-expression/src/index.ts

raw symbols SCIP
1 import {
2 callExpression,
3 identifier,
4 isIdentifier,
5 isSpreadElement,
6 memberExpression,
7 optionalCallExpression,
8 optionalMemberExpression,
9 } from "@babel/types";
10 import type {
11 CallExpression,
12 Expression,
13 OptionalCallExpression,
14 } from "@babel/types";
15
16 /**
17 * A helper function that generates a new call expression with given thisNode.
18 It will also optimize `(...arguments)` to `.apply(arguments)`
19 *
20 * @export
21 * @param {Expression} callee The callee of call expression
22 * @param {Expression} thisNode The desired this of call expression
23 * @param {Readonly<CallExpression["arguments"]>} args The arguments of call expression
24 * @param {boolean} optional Whether the call expression is optional
25 * @returns {CallExpression | OptionalCallExpression} The generated new call expression
26 */
27 export default function optimiseCallExpression(
28 callee: Expression,
29 thisNode: Expression,
30 args: Readonly<CallExpression["arguments"]>,
31 optional: boolean,
32 ): CallExpression | OptionalCallExpression {
33 if (
34 args.length === 1 &&
35 isSpreadElement(args[0]) &&
36 isIdentifier(args[0].argument, { name: "arguments" })
37 ) {
38 // a.b?.(...arguments);
39 if (optional) {
40 return optionalCallExpression(
41 optionalMemberExpression(callee, identifier("apply"), false, true),
42 [thisNode, args[0].argument],
43 false,
44 );
45 }
46 // a.b(...arguments);
47 return callExpression(memberExpression(callee, identifier("apply")), [
48 thisNode,
49 args[0].argument,
50 ]);
51 } else {
52 // a.b?.(arg1, arg2)
53 if (optional) {
54 return optionalCallExpression(
55 optionalMemberExpression(callee, identifier("call"), false, true),
56 [thisNode, ...args],
57 false,
58 );
59 }
60 // a.b(arg1, arg2)
61 return callExpression(memberExpression(callee, identifier("call")), [
62 thisNode,
63 ...args,
64 ]);
65 }
66 }