source: imaps-frontend/node_modules/@babel/plugin-transform-classes/lib/transformClass.js

main
Last change on this file was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 4 days ago

F4 Finalna Verzija

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