source: trip-planner-front/node_modules/@babel/plugin-transform-classes/lib/transformClass.js@ 6a80231

Last change on this file since 6a80231 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 17.8 KB
Line 
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = transformClass;
7
8var _helperFunctionName = require("@babel/helper-function-name");
9
10var _helperReplaceSupers = require("@babel/helper-replace-supers");
11
12var _helperOptimiseCallExpression = require("@babel/helper-optimise-call-expression");
13
14var _core = require("@babel/core");
15
16var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
17
18var _inlineCreateSuperHelpers = require("./inline-createSuper-helpers");
19
20function buildConstructor(classRef, constructorBody, node) {
21 const func = _core.types.functionDeclaration(_core.types.cloneNode(classRef), [], constructorBody);
22
23 _core.types.inherits(func, node);
24
25 return func;
26}
27
28function transformClass(path, file, builtinClasses, isLoose, assumptions) {
29 const classState = {
30 parent: undefined,
31 scope: undefined,
32 node: undefined,
33 path: undefined,
34 file: undefined,
35 classId: undefined,
36 classRef: undefined,
37 superFnId: undefined,
38 superName: undefined,
39 superReturns: [],
40 isDerived: false,
41 extendsNative: false,
42 construct: undefined,
43 constructorBody: undefined,
44 userConstructor: undefined,
45 userConstructorPath: undefined,
46 hasConstructor: false,
47 staticPropBody: [],
48 body: [],
49 superThises: [],
50 pushedConstructor: false,
51 pushedInherits: false,
52 protoAlias: null,
53 isLoose: false,
54 dynamicKeys: new Map(),
55 methods: {
56 instance: {
57 hasComputed: false,
58 list: [],
59 map: new Map()
60 },
61 static: {
62 hasComputed: false,
63 list: [],
64 map: new Map()
65 }
66 }
67 };
68
69 const setState = newState => {
70 Object.assign(classState, newState);
71 };
72
73 const findThisesVisitor = _core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
74 ThisExpression(path) {
75 classState.superThises.push(path);
76 }
77
78 }]);
79
80 function maybeCreateConstructor() {
81 let hasConstructor = false;
82 const paths = classState.path.get("body.body");
83
84 for (const path of paths) {
85 hasConstructor = path.equals("kind", "constructor");
86 if (hasConstructor) break;
87 }
88
89 if (hasConstructor) return;
90 let params, body;
91
92 if (classState.isDerived) {
93 const constructor = _core.template.expression.ast`
94 (function () {
95 super(...arguments);
96 })
97 `;
98 params = constructor.params;
99 body = constructor.body;
100 } else {
101 params = [];
102 body = _core.types.blockStatement([]);
103 }
104
105 classState.path.get("body").unshiftContainer("body", _core.types.classMethod("constructor", _core.types.identifier("constructor"), params, body));
106 }
107
108 function buildBody() {
109 maybeCreateConstructor();
110 pushBody();
111 verifyConstructor();
112
113 if (classState.userConstructor) {
114 const {
115 constructorBody,
116 userConstructor,
117 construct
118 } = classState;
119 constructorBody.body.push(...userConstructor.body.body);
120
121 _core.types.inherits(construct, userConstructor);
122
123 _core.types.inherits(constructorBody, userConstructor.body);
124 }
125
126 pushDescriptors();
127 }
128
129 function pushBody() {
130 const classBodyPaths = classState.path.get("body.body");
131
132 for (const path of classBodyPaths) {
133 const node = path.node;
134
135 if (path.isClassProperty()) {
136 throw path.buildCodeFrameError("Missing class properties transform.");
137 }
138
139 if (node.decorators) {
140 throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
141 }
142
143 if (_core.types.isClassMethod(node)) {
144 const isConstructor = node.kind === "constructor";
145 const replaceSupers = new _helperReplaceSupers.default({
146 methodPath: path,
147 objectRef: classState.classRef,
148 superRef: classState.superName,
149 constantSuper: assumptions.constantSuper,
150 file: classState.file,
151 refToPreserve: classState.classRef
152 });
153 replaceSupers.replace();
154 const superReturns = [];
155 path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
156 ReturnStatement(path) {
157 if (!path.getFunctionParent().isArrowFunctionExpression()) {
158 superReturns.push(path);
159 }
160 }
161
162 }]));
163
164 if (isConstructor) {
165 pushConstructor(superReturns, node, path);
166 } else {
167 pushMethod(node, path);
168 }
169 }
170 }
171 }
172
173 function pushDescriptors() {
174 pushInheritsToBody();
175 const {
176 body
177 } = classState;
178 const props = {
179 instance: null,
180 static: null
181 };
182
183 for (const placement of ["static", "instance"]) {
184 if (classState.methods[placement].list.length) {
185 props[placement] = classState.methods[placement].list.map(desc => {
186 const obj = _core.types.objectExpression([_core.types.objectProperty(_core.types.identifier("key"), desc.key)]);
187
188 for (const kind of ["get", "set", "value"]) {
189 if (desc[kind] != null) {
190 obj.properties.push(_core.types.objectProperty(_core.types.identifier(kind), desc[kind]));
191 }
192 }
193
194 return obj;
195 });
196 }
197 }
198
199 if (props.instance || props.static) {
200 let args = [_core.types.cloneNode(classState.classRef), props.instance ? _core.types.arrayExpression(props.instance) : _core.types.nullLiteral(), props.static ? _core.types.arrayExpression(props.static) : _core.types.nullLiteral()];
201 let lastNonNullIndex = 0;
202
203 for (let i = 0; i < args.length; i++) {
204 if (!_core.types.isNullLiteral(args[i])) lastNonNullIndex = i;
205 }
206
207 args = args.slice(0, lastNonNullIndex + 1);
208 body.push(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("createClass"), args)));
209 }
210 }
211
212 function wrapSuperCall(bareSuper, superRef, thisRef, body) {
213 const bareSuperNode = bareSuper.node;
214 let call;
215
216 if (assumptions.superIsCallableConstructor) {
217 bareSuperNode.arguments.unshift(_core.types.thisExpression());
218
219 if (bareSuperNode.arguments.length === 2 && _core.types.isSpreadElement(bareSuperNode.arguments[1]) && _core.types.isIdentifier(bareSuperNode.arguments[1].argument, {
220 name: "arguments"
221 })) {
222 bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
223 bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("apply"));
224 } else {
225 bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("call"));
226 }
227
228 call = _core.types.logicalExpression("||", bareSuperNode, _core.types.thisExpression());
229 } else {
230 call = (0, _helperOptimiseCallExpression.default)(_core.types.cloneNode(classState.superFnId), _core.types.thisExpression(), bareSuperNode.arguments, false);
231 }
232
233 if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
234 if (classState.superThises.length) {
235 call = _core.types.assignmentExpression("=", thisRef(), call);
236 }
237
238 bareSuper.parentPath.replaceWith(_core.types.returnStatement(call));
239 } else {
240 bareSuper.replaceWith(_core.types.assignmentExpression("=", thisRef(), call));
241 }
242 }
243
244 function verifyConstructor() {
245 if (!classState.isDerived) return;
246 const path = classState.userConstructorPath;
247 const body = path.get("body");
248 path.traverse(findThisesVisitor);
249
250 let thisRef = function () {
251 const ref = path.scope.generateDeclaredUidIdentifier("this");
252
253 thisRef = () => _core.types.cloneNode(ref);
254
255 return ref;
256 };
257
258 for (const thisPath of classState.superThises) {
259 const {
260 node,
261 parentPath
262 } = thisPath;
263
264 if (parentPath.isMemberExpression({
265 object: node
266 })) {
267 thisPath.replaceWith(thisRef());
268 continue;
269 }
270
271 thisPath.replaceWith(_core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
272 }
273
274 const bareSupers = new Set();
275 path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
276 Super(path) {
277 const {
278 node,
279 parentPath
280 } = path;
281
282 if (parentPath.isCallExpression({
283 callee: node
284 })) {
285 bareSupers.add(parentPath);
286 }
287 }
288
289 }]));
290 let guaranteedSuperBeforeFinish = !!bareSupers.size;
291
292 for (const bareSuper of bareSupers) {
293 wrapSuperCall(bareSuper, classState.superName, thisRef, body);
294
295 if (guaranteedSuperBeforeFinish) {
296 bareSuper.find(function (parentPath) {
297 if (parentPath === path) {
298 return true;
299 }
300
301 if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
302 guaranteedSuperBeforeFinish = false;
303 return true;
304 }
305 });
306 }
307 }
308
309 let wrapReturn;
310
311 if (classState.isLoose) {
312 wrapReturn = returnArg => {
313 const thisExpr = _core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
314
315 return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
316 };
317 } else {
318 wrapReturn = returnArg => _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [thisRef()].concat(returnArg || []));
319 }
320
321 const bodyPaths = body.get("body");
322
323 if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
324 body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
325 }
326
327 for (const returnPath of classState.superReturns) {
328 returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
329 }
330 }
331
332 function pushMethod(node, path) {
333 const scope = path ? path.scope : classState.scope;
334
335 if (node.kind === "method") {
336 if (processMethod(node, scope)) return;
337 }
338
339 const placement = node.static ? "static" : "instance";
340 const methods = classState.methods[placement];
341 const descKey = node.kind === "method" ? "value" : node.kind;
342 const key = _core.types.isNumericLiteral(node.key) || _core.types.isBigIntLiteral(node.key) ? _core.types.stringLiteral(String(node.key.value)) : _core.types.toComputedKey(node);
343
344 let fn = _core.types.toExpression(node);
345
346 if (_core.types.isStringLiteral(key)) {
347 if (node.kind === "method") {
348 fn = (0, _helperFunctionName.default)({
349 id: key,
350 node: node,
351 scope
352 });
353 }
354 } else {
355 methods.hasComputed = true;
356 }
357
358 let descriptor;
359
360 if (!methods.hasComputed && methods.map.has(key.value)) {
361 descriptor = methods.map.get(key.value);
362 descriptor[descKey] = fn;
363
364 if (descKey === "value") {
365 descriptor.get = null;
366 descriptor.set = null;
367 } else {
368 descriptor.value = null;
369 }
370 } else {
371 descriptor = {
372 key: key,
373 [descKey]: fn
374 };
375 methods.list.push(descriptor);
376
377 if (!methods.hasComputed) {
378 methods.map.set(key.value, descriptor);
379 }
380 }
381 }
382
383 function processMethod(node, scope) {
384 if (assumptions.setClassMethods && !node.decorators) {
385 let {
386 classRef
387 } = classState;
388
389 if (!node.static) {
390 insertProtoAliasOnce();
391 classRef = classState.protoAlias;
392 }
393
394 const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
395
396 let func = _core.types.functionExpression(null, node.params, node.body, node.generator, node.async);
397
398 _core.types.inherits(func, node);
399
400 const key = _core.types.toComputedKey(node, node.key);
401
402 if (_core.types.isStringLiteral(key)) {
403 func = (0, _helperFunctionName.default)({
404 node: func,
405 id: key,
406 scope
407 });
408 }
409
410 const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
411
412 _core.types.inheritsComments(expr, node);
413
414 classState.body.push(expr);
415 return true;
416 }
417
418 return false;
419 }
420
421 function insertProtoAliasOnce() {
422 if (classState.protoAlias === null) {
423 setState({
424 protoAlias: classState.scope.generateUidIdentifier("proto")
425 });
426
427 const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
428
429 const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
430
431 classState.body.push(protoDeclaration);
432 }
433 }
434
435 function pushConstructor(superReturns, method, path) {
436 setState({
437 userConstructorPath: path,
438 userConstructor: method,
439 hasConstructor: true,
440 superReturns
441 });
442 const {
443 construct
444 } = classState;
445
446 _core.types.inheritsComments(construct, method);
447
448 construct.params = method.params;
449
450 _core.types.inherits(construct.body, method.body);
451
452 construct.body.directives = method.body.directives;
453 pushConstructorToBody();
454 }
455
456 function pushConstructorToBody() {
457 if (classState.pushedConstructor) return;
458 classState.pushedConstructor = true;
459
460 if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
461 pushDescriptors();
462 }
463
464 classState.body.push(classState.construct);
465 pushInheritsToBody();
466 }
467
468 function pushInheritsToBody() {
469 if (!classState.isDerived || classState.pushedInherits) return;
470 const superFnId = path.scope.generateUidIdentifier("super");
471 setState({
472 pushedInherits: true,
473 superFnId
474 });
475
476 if (!assumptions.superIsCallableConstructor) {
477 classState.body.unshift(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(superFnId, _core.types.callExpression((0, _inlineCreateSuperHelpers.default)(classState.file), [_core.types.cloneNode(classState.classRef)]))]));
478 }
479
480 classState.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper(classState.isLoose ? "inheritsLoose" : "inherits"), [_core.types.cloneNode(classState.classRef), _core.types.cloneNode(classState.superName)])));
481 }
482
483 function extractDynamicKeys() {
484 const {
485 dynamicKeys,
486 node,
487 scope
488 } = classState;
489
490 for (const elem of node.body.body) {
491 if (!_core.types.isClassMethod(elem) || !elem.computed) continue;
492 if (scope.isPure(elem.key, true)) continue;
493 const id = scope.generateUidIdentifierBasedOnNode(elem.key);
494 dynamicKeys.set(id.name, elem.key);
495 elem.key = id;
496 }
497 }
498
499 function setupClosureParamsArgs() {
500 const {
501 superName,
502 dynamicKeys
503 } = classState;
504 const closureParams = [];
505 const closureArgs = [];
506
507 if (classState.isDerived) {
508 let arg = _core.types.cloneNode(superName);
509
510 if (classState.extendsNative) {
511 arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
512 (0, _helperAnnotateAsPure.default)(arg);
513 }
514
515 const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
516 closureParams.push(param);
517 closureArgs.push(arg);
518 setState({
519 superName: _core.types.cloneNode(param)
520 });
521 }
522
523 for (const [name, value] of dynamicKeys) {
524 closureParams.push(_core.types.identifier(name));
525 closureArgs.push(value);
526 }
527
528 return {
529 closureParams,
530 closureArgs
531 };
532 }
533
534 function classTransformer(path, file, builtinClasses, isLoose) {
535 setState({
536 parent: path.parent,
537 scope: path.scope,
538 node: path.node,
539 path,
540 file,
541 isLoose
542 });
543 setState({
544 classId: classState.node.id,
545 classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
546 superName: classState.node.superClass,
547 isDerived: !!classState.node.superClass,
548 constructorBody: _core.types.blockStatement([])
549 });
550 setState({
551 extendsNative: classState.isDerived && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
552 });
553 const {
554 classRef,
555 node,
556 constructorBody
557 } = classState;
558 setState({
559 construct: buildConstructor(classRef, constructorBody, node)
560 });
561 extractDynamicKeys();
562 const {
563 body
564 } = classState;
565 const {
566 closureParams,
567 closureArgs
568 } = setupClosureParamsArgs();
569 buildBody();
570
571 if (!assumptions.noClassCalls) {
572 constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
573 }
574
575 body.push(...classState.staticPropBody.map(fn => fn(_core.types.cloneNode(classState.classRef))));
576 const isStrict = path.isInStrictMode();
577 let constructorOnly = classState.classId && body.length === 1;
578
579 if (constructorOnly && !isStrict) {
580 for (const param of classState.construct.params) {
581 if (!_core.types.isIdentifier(param)) {
582 constructorOnly = false;
583 break;
584 }
585 }
586 }
587
588 const directives = constructorOnly ? body[0].body.directives : [];
589
590 if (!isStrict) {
591 directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
592 }
593
594 if (constructorOnly) {
595 return _core.types.toExpression(body[0]);
596 }
597
598 body.push(_core.types.returnStatement(_core.types.cloneNode(classState.classRef)));
599
600 const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
601
602 return _core.types.callExpression(container, closureArgs);
603 }
604
605 return classTransformer(path, file, builtinClasses, isLoose);
606}
Note: See TracBrowser for help on using the repository browser.