Debian Codegraph @

packages/babel-helper-function-name/src/index.ts

raw
1 import template from "@babel/template";
2 import {
3 NOT_LOCAL_BINDING,
4 cloneNode,
5 identifier,
6 isAssignmentExpression,
7 isAssignmentPattern,
8 isFunction,
9 isIdentifier,
10 isLiteral,
11 isNullLiteral,
12 isObjectMethod,
13 isObjectProperty,
14 isRegExpLiteral,
15 isRestElement,
16 isTemplateLiteral,
17 isVariableDeclarator,
18 toBindingIdentifierName,
19 } from "@babel/types";
20 import type * as t from "@babel/types";
21 import type { NodePath, Scope, Visitor } from "@babel/traverse";
22
23 function getFunctionArity(node: t.Function): number {
24 const count = node.params.findIndex(
25 param => isAssignmentPattern(param) || isRestElement(param),
26 );
27 return count === -1 ? node.params.length : count;
28 }
29
30 const buildPropertyMethodAssignmentWrapper = template.statement(`
31 (function (FUNCTION_KEY) {
32 function FUNCTION_ID() {
33 return FUNCTION_KEY.apply(this, arguments);
34 }
35
36 FUNCTION_ID.toString = function () {
37 return FUNCTION_KEY.toString();
38 }
39
40 return FUNCTION_ID;
41 })(FUNCTION)
42 `);
43
44 const buildGeneratorPropertyMethodAssignmentWrapper = template.statement(`
45 (function (FUNCTION_KEY) {
46 function* FUNCTION_ID() {
47 return yield* FUNCTION_KEY.apply(this, arguments);
48 }
49
50 FUNCTION_ID.toString = function () {
51 return FUNCTION_KEY.toString();
52 };
53
54 return FUNCTION_ID;
55 })(FUNCTION)
56 `);
57
58 type State = {
59 name: string;
60 outerDeclar: t.Identifier;
61 selfAssignment: boolean;
62 selfReference: boolean;
63 };
64
65 const visitor: Visitor<State> = {
66 "ReferencedIdentifier|BindingIdentifier"(
67 path: NodePath<t.Identifier>,
68 state,
69 ) {
70 // check if this node matches our function id
71 if (path.node.name !== state.name) return;
72
73 // check that we don't have a local variable declared as that removes the need
74 // for the wrapper
75 const localDeclar = path.scope.getBindingIdentifier(state.name);
76 if (localDeclar !== state.outerDeclar) return;
77
78 state.selfReference = true;
79 path.stop();
80 },
81 };
82
83 function getNameFromLiteralId(id: t.Literal) {
84 if (isNullLiteral(id)) {
85 return "null";
86 }
87
88 if (isRegExpLiteral(id)) {
89 return `_${id.pattern}_${id.flags}`;
90 }
91
92 if (isTemplateLiteral(id)) {
93 return id.quasis.map(quasi => quasi.value.raw).join("");
94 }
95
96 if (id.value !== undefined) {
97 return id.value + "";
98 }
99
100 return "";
101 }
102
103 function wrap(
104 state: State,
105 method: t.FunctionExpression | t.Class,
106 id: t.Identifier,
107 scope: Scope,
108 ) {
109 if (state.selfReference) {
110 if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
111 // we can just munge the local binding
112 scope.rename(id.name);
113 } else {
114 // we don't currently support wrapping class expressions
115 if (!isFunction(method)) return;
116
117 // need to add a wrapper since we can't change the references
118 let build = buildPropertyMethodAssignmentWrapper;
119 if (method.generator) {
120 build = buildGeneratorPropertyMethodAssignmentWrapper;
121 }
122
123 const template = (
124 build({
125 FUNCTION: method,
126 FUNCTION_ID: id,
127 FUNCTION_KEY: scope.generateUidIdentifier(id.name),
128 }) as t.ExpressionStatement
129 ).expression as t.CallExpression;
130
131 // shim in dummy params to retain function arity, if you try to read the
132 // source then you'll get the original since it's proxied so it's all good
133 const params = (
134 (template.callee as t.FunctionExpression).body
135 .body[0] as any as t.FunctionExpression
136 ).params;
137
138 for (let i = 0, len = getFunctionArity(method); i < len; i++) {
139 params.push(scope.generateUidIdentifier("x"));
140 }
141
142 return template;
143 }
144 }
145
146 method.id = id;
147 scope.getProgramParent().references[id.name] = true;
148 }
149
150 function visit(
151 node: t.FunctionExpression | t.Class,
152 name: string,
153 scope: Scope,
154 ) {
155 const state: State = {
156 selfAssignment: false,
157 selfReference: false,
158 outerDeclar: scope.getBindingIdentifier(name),
159 name: name,
160 };
161
162 // check to see if we have a local binding of the id we're setting inside of
163 // the function, this is important as there are caveats associated
164
165 const binding = scope.getOwnBinding(name);
166
167 if (binding) {
168 if (binding.kind === "param") {
169 // safari will blow up in strict mode with code like:
170 //
171 // let t = function t(t) {};
172 //
173 // with the error:
174 //
175 // Cannot declare a parameter named 't' as it shadows the name of a
176 // strict mode function.
177 //
178 // this isn't to the spec and they've invented this behaviour which is
179 // **extremely** annoying so we avoid setting the name if it has a param
180 // with the same id
181 state.selfReference = true;
182 } else {
183 // otherwise it's defined somewhere in scope like:
184 //
185 // let t = function () {
186 // let t = 2;
187 // };
188 //
189 // so we can safely just set the id and move along as it shadows the
190 // bound function id
191 }
192 } else if (state.outerDeclar || scope.hasGlobal(name)) {
193 scope.traverse(node, visitor, state);
194 }
195
196 return state;
197 }
198
199 /**
200 * Add id to function/class expression inferred from the AST
201 *
202 * @export
203 * @template N The unamed expression type
204 * @param {Object} nodePathLike The NodePath-like input
205 * @param {N} nodePathLike.node an AST node
206 * @param {NodePath<N>["parent"]} [nodePathLike.parent] The parent of the AST node
207 * @param {Scope} nodePathLike.scope The scope associated to the AST node
208 * @param {t.LVal | t.StringLiteral | t.NumericLiteral | t.BigIntLiteral} [nodePathLike.id] the fallback naming source when the helper
209 * can not infer the function name from the AST
210 * @param {boolean} [localBinding=false] whether a name could shadow a self-reference (e.g. converting arrow function)
211 * @param {boolean} [supportUnicodeId=false] whether the compilation target supports unicodeId (non-BMP characters) or not
212 * @returns {(N | t.CallExpression | void)}
213 * - modified node when name can be inferred,
214 * - an IIFE when `node` contains a binding shadowing the inferred function name (e.g. `let f = function (f) {}`),
215 * - `void` when `node` has `id` property or the helper can not inferred the name or the inferred name contains non-BMP characters that is not supported by current target
216 */
217 export default function <N extends t.FunctionExpression | t.Class>(
218 {
219 node,
220 parent,
221 scope,
222 id,
223 }: {
224 node: N;
225 parent?: NodePath<N>["parent"];
226 scope: Scope;
227 id?: t.LVal | t.StringLiteral | t.NumericLiteral | t.BigIntLiteral;
228 },
229 localBinding = false,
230 supportUnicodeId = false,
231 ): N | t.CallExpression | void {
232 // has an `id` so we don't need to infer one
233 if (node.id) return;
234
235 if (
236 (isObjectProperty(parent) || isObjectMethod(parent, { kind: "method" })) &&
237 (!parent.computed || isLiteral(parent.key))
238 ) {
239 // { foo() {} };
240 id = parent.key as
241 | t.Identifier
242 | t.StringLiteral
243 | t.NumericLiteral
244 | t.BigIntLiteral;
245 } else if (isVariableDeclarator(parent)) {
246 // let foo = function () {};
247 id = parent.id;
248
249 // but not "let foo = () => {};" being converted to function expression
250 if (isIdentifier(id) && !localBinding) {
251 const binding = scope.parent.getBinding(id.name);
252 if (
253 binding &&
254 binding.constant &&
255 scope.getBinding(id.name) === binding
256 ) {
257 // always going to reference this method
258 node.id = cloneNode(id);
259 // @ts-expect-error Fixme: avoid mutating AST nodes
260 node.id[NOT_LOCAL_BINDING] = true;
261 return;
262 }
263 }
264 } else if (isAssignmentExpression(parent, { operator: "=" })) {
265 // foo = function () {};
266 id = parent.left;
267 } else if (!id) {
268 return;
269 }
270
271 let name;
272 if (id && isLiteral(id)) {
273 name = getNameFromLiteralId(id);
274 } else if (id && isIdentifier(id)) {
275 name = id.name;
276 }
277
278 if (name === undefined) {
279 return;
280 }
281
282 if (!supportUnicodeId && isFunction(node) && /[\uD800-\uDFFF]/.test(name)) {
283 return;
284 }
285
286 name = toBindingIdentifierName(name);
287 const newId = identifier(name);
288
289 // The id shouldn't be considered a local binding to the function because
290 // we are simply trying to set the function name and not actually create
291 // a local binding.
292 // @ts-expect-error Fixme: avoid mutating AST nodes
293 newId[NOT_LOCAL_BINDING] = true;
294
295 const state = visit(node, name, scope);
296 return wrap(state, node, newId, scope) || node;
297 }