source: imaps-frontend/node_modules/@babel/traverse/lib/path/conversion.js@ 0c6b92a

main
Last change on this file since 0c6b92a was 0c6b92a, checked in by stefan toskovski <stefantoska84@…>, 5 weeks ago

Pred finalna verzija

  • Property mode set to 100644
File size: 21.1 KB
Line 
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.arrowFunctionToExpression = arrowFunctionToExpression;
7exports.ensureBlock = ensureBlock;
8exports.ensureFunctionName = ensureFunctionName;
9exports.splitExportDeclaration = splitExportDeclaration;
10exports.toComputedKey = toComputedKey;
11exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment;
12var _t = require("@babel/types");
13var _template = require("@babel/template");
14var _visitors = require("../visitors.js");
15var _context = require("./context.js");
16const {
17 arrowFunctionExpression,
18 assignmentExpression,
19 binaryExpression,
20 blockStatement,
21 callExpression,
22 conditionalExpression,
23 expressionStatement,
24 identifier,
25 isIdentifier,
26 jsxIdentifier,
27 logicalExpression,
28 LOGICAL_OPERATORS,
29 memberExpression,
30 metaProperty,
31 numericLiteral,
32 objectExpression,
33 restElement,
34 returnStatement,
35 sequenceExpression,
36 spreadElement,
37 stringLiteral,
38 super: _super,
39 thisExpression,
40 toExpression,
41 unaryExpression,
42 toBindingIdentifierName,
43 isFunction,
44 isAssignmentPattern,
45 isRestElement,
46 getFunctionName,
47 cloneNode,
48 variableDeclaration,
49 variableDeclarator,
50 exportNamedDeclaration,
51 exportSpecifier,
52 inherits
53} = _t;
54function toComputedKey() {
55 let key;
56 if (this.isMemberExpression()) {
57 key = this.node.property;
58 } else if (this.isProperty() || this.isMethod()) {
59 key = this.node.key;
60 } else {
61 throw new ReferenceError("todo");
62 }
63 if (!this.node.computed) {
64 if (isIdentifier(key)) key = stringLiteral(key.name);
65 }
66 return key;
67}
68function ensureBlock() {
69 const body = this.get("body");
70 const bodyNode = body.node;
71 if (Array.isArray(body)) {
72 throw new Error("Can't convert array path to a block statement");
73 }
74 if (!bodyNode) {
75 throw new Error("Can't convert node without a body");
76 }
77 if (body.isBlockStatement()) {
78 return bodyNode;
79 }
80 const statements = [];
81 let stringPath = "body";
82 let key;
83 let listKey;
84 if (body.isStatement()) {
85 listKey = "body";
86 key = 0;
87 statements.push(body.node);
88 } else {
89 stringPath += ".body.0";
90 if (this.isFunction()) {
91 key = "argument";
92 statements.push(returnStatement(body.node));
93 } else {
94 key = "expression";
95 statements.push(expressionStatement(body.node));
96 }
97 }
98 this.node.body = blockStatement(statements);
99 const parentPath = this.get(stringPath);
100 _context.setup.call(body, parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
101 return this.node;
102}
103{
104 exports.arrowFunctionToShadowed = function () {
105 if (!this.isArrowFunctionExpression()) return;
106 this.arrowFunctionToExpression();
107 };
108}
109function unwrapFunctionEnvironment() {
110 if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
111 throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
112 }
113 hoistFunctionEnvironment(this);
114}
115function setType(path, type) {
116 path.node.type = type;
117}
118function arrowFunctionToExpression({
119 allowInsertArrow = true,
120 allowInsertArrowWithRest = allowInsertArrow,
121 noNewArrows = !(_arguments$ => (_arguments$ = arguments[0]) == null ? void 0 : _arguments$.specCompliant)()
122} = {}) {
123 if (!this.isArrowFunctionExpression()) {
124 throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
125 }
126 let self = this;
127 if (!noNewArrows) {
128 var _self$ensureFunctionN;
129 self = (_self$ensureFunctionN = self.ensureFunctionName(false)) != null ? _self$ensureFunctionN : self;
130 }
131 const {
132 thisBinding,
133 fnPath: fn
134 } = hoistFunctionEnvironment(self, noNewArrows, allowInsertArrow, allowInsertArrowWithRest);
135 fn.ensureBlock();
136 setType(fn, "FunctionExpression");
137 if (!noNewArrows) {
138 const checkBinding = thisBinding ? null : fn.scope.generateUidIdentifier("arrowCheckId");
139 if (checkBinding) {
140 fn.parentPath.scope.push({
141 id: checkBinding,
142 init: objectExpression([])
143 });
144 }
145 fn.get("body").unshiftContainer("body", expressionStatement(callExpression(this.hub.addHelper("newArrowCheck"), [thisExpression(), checkBinding ? identifier(checkBinding.name) : identifier(thisBinding)])));
146 fn.replaceWith(callExpression(memberExpression(fn.node, identifier("bind")), [checkBinding ? identifier(checkBinding.name) : thisExpression()]));
147 return fn.get("callee.object");
148 }
149 return fn;
150}
151const getSuperCallsVisitor = (0, _visitors.environmentVisitor)({
152 CallExpression(child, {
153 allSuperCalls
154 }) {
155 if (!child.get("callee").isSuper()) return;
156 allSuperCalls.push(child);
157 }
158});
159function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true, allowInsertArrowWithRest = true) {
160 let arrowParent;
161 let thisEnvFn = fnPath.findParent(p => {
162 if (p.isArrowFunctionExpression()) {
163 var _arrowParent;
164 (_arrowParent = arrowParent) != null ? _arrowParent : arrowParent = p;
165 return false;
166 }
167 return p.isFunction() || p.isProgram() || p.isClassProperty({
168 static: false
169 }) || p.isClassPrivateProperty({
170 static: false
171 });
172 });
173 const inConstructor = thisEnvFn.isClassMethod({
174 kind: "constructor"
175 });
176 if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) {
177 if (arrowParent) {
178 thisEnvFn = arrowParent;
179 } else if (allowInsertArrow) {
180 fnPath.replaceWith(callExpression(arrowFunctionExpression([], toExpression(fnPath.node)), []));
181 thisEnvFn = fnPath.get("callee");
182 fnPath = thisEnvFn.get("body");
183 } else {
184 throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
185 }
186 }
187 const {
188 thisPaths,
189 argumentsPaths,
190 newTargetPaths,
191 superProps,
192 superCalls
193 } = getScopeInformation(fnPath);
194 if (inConstructor && superCalls.length > 0) {
195 if (!allowInsertArrow) {
196 throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super()` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
197 }
198 if (!allowInsertArrowWithRest) {
199 throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-parameters', " + "it's not possible to compile `super()` in an arrow function with default or rest parameters without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
200 }
201 const allSuperCalls = [];
202 thisEnvFn.traverse(getSuperCallsVisitor, {
203 allSuperCalls
204 });
205 const superBinding = getSuperBinding(thisEnvFn);
206 allSuperCalls.forEach(superCall => {
207 const callee = identifier(superBinding);
208 callee.loc = superCall.node.callee.loc;
209 superCall.get("callee").replaceWith(callee);
210 });
211 }
212 if (argumentsPaths.length > 0) {
213 const argumentsBinding = getBinding(thisEnvFn, "arguments", () => {
214 const args = () => identifier("arguments");
215 if (thisEnvFn.scope.path.isProgram()) {
216 return conditionalExpression(binaryExpression("===", unaryExpression("typeof", args()), stringLiteral("undefined")), thisEnvFn.scope.buildUndefinedNode(), args());
217 } else {
218 return args();
219 }
220 });
221 argumentsPaths.forEach(argumentsChild => {
222 const argsRef = identifier(argumentsBinding);
223 argsRef.loc = argumentsChild.node.loc;
224 argumentsChild.replaceWith(argsRef);
225 });
226 }
227 if (newTargetPaths.length > 0) {
228 const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => metaProperty(identifier("new"), identifier("target")));
229 newTargetPaths.forEach(targetChild => {
230 const targetRef = identifier(newTargetBinding);
231 targetRef.loc = targetChild.node.loc;
232 targetChild.replaceWith(targetRef);
233 });
234 }
235 if (superProps.length > 0) {
236 if (!allowInsertArrow) {
237 throw superProps[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super.prop` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
238 }
239 const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []);
240 flatSuperProps.forEach(superProp => {
241 const key = superProp.node.computed ? "" : superProp.get("property").node.name;
242 const superParentPath = superProp.parentPath;
243 const isAssignment = superParentPath.isAssignmentExpression({
244 left: superProp.node
245 });
246 const isCall = superParentPath.isCallExpression({
247 callee: superProp.node
248 });
249 const isTaggedTemplate = superParentPath.isTaggedTemplateExpression({
250 tag: superProp.node
251 });
252 const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
253 const args = [];
254 if (superProp.node.computed) {
255 args.push(superProp.get("property").node);
256 }
257 if (isAssignment) {
258 const value = superParentPath.node.right;
259 args.push(value);
260 }
261 const call = callExpression(identifier(superBinding), args);
262 if (isCall) {
263 superParentPath.unshiftContainer("arguments", thisExpression());
264 superProp.replaceWith(memberExpression(call, identifier("call")));
265 thisPaths.push(superParentPath.get("arguments.0"));
266 } else if (isAssignment) {
267 superParentPath.replaceWith(call);
268 } else if (isTaggedTemplate) {
269 superProp.replaceWith(callExpression(memberExpression(call, identifier("bind"), false), [thisExpression()]));
270 thisPaths.push(superProp.get("arguments.0"));
271 } else {
272 superProp.replaceWith(call);
273 }
274 });
275 }
276 let thisBinding;
277 if (thisPaths.length > 0 || !noNewArrows) {
278 thisBinding = getThisBinding(thisEnvFn, inConstructor);
279 if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
280 thisPaths.forEach(thisChild => {
281 const thisRef = thisChild.isJSX() ? jsxIdentifier(thisBinding) : identifier(thisBinding);
282 thisRef.loc = thisChild.node.loc;
283 thisChild.replaceWith(thisRef);
284 });
285 if (!noNewArrows) thisBinding = null;
286 }
287 }
288 return {
289 thisBinding,
290 fnPath
291 };
292}
293function isLogicalOp(op) {
294 return LOGICAL_OPERATORS.includes(op);
295}
296function standardizeSuperProperty(superProp) {
297 if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
298 const assignmentPath = superProp.parentPath;
299 const op = assignmentPath.node.operator.slice(0, -1);
300 const value = assignmentPath.node.right;
301 const isLogicalAssignment = isLogicalOp(op);
302 if (superProp.node.computed) {
303 const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
304 const object = superProp.node.object;
305 const property = superProp.node.property;
306 assignmentPath.get("left").replaceWith(memberExpression(object, assignmentExpression("=", tmp, property), true));
307 assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(tmp.name), true), value));
308 } else {
309 const object = superProp.node.object;
310 const property = superProp.node.property;
311 assignmentPath.get("left").replaceWith(memberExpression(object, property));
312 assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(property.name)), value));
313 }
314 if (isLogicalAssignment) {
315 assignmentPath.replaceWith(logicalExpression(op, assignmentPath.node.left, assignmentPath.node.right));
316 } else {
317 assignmentPath.node.operator = "=";
318 }
319 return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
320 } else if (superProp.parentPath.isUpdateExpression()) {
321 const updateExpr = superProp.parentPath;
322 const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
323 const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
324 const parts = [assignmentExpression("=", tmp, memberExpression(superProp.node.object, computedKey ? assignmentExpression("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), assignmentExpression("=", memberExpression(superProp.node.object, computedKey ? identifier(computedKey.name) : superProp.node.property, superProp.node.computed), binaryExpression(superProp.parentPath.node.operator[0], identifier(tmp.name), numericLiteral(1)))];
325 if (!superProp.parentPath.node.prefix) {
326 parts.push(identifier(tmp.name));
327 }
328 updateExpr.replaceWith(sequenceExpression(parts));
329 const left = updateExpr.get("expressions.0.right");
330 const right = updateExpr.get("expressions.1.left");
331 return [left, right];
332 }
333 return [superProp];
334 function rightExpression(op, left, right) {
335 if (op === "=") {
336 return assignmentExpression("=", left, right);
337 } else {
338 return binaryExpression(op, left, right);
339 }
340 }
341}
342function hasSuperClass(thisEnvFn) {
343 return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
344}
345const assignSuperThisVisitor = (0, _visitors.environmentVisitor)({
346 CallExpression(child, {
347 supers,
348 thisBinding
349 }) {
350 if (!child.get("callee").isSuper()) return;
351 if (supers.has(child.node)) return;
352 supers.add(child.node);
353 child.replaceWithMultiple([child.node, assignmentExpression("=", identifier(thisBinding), identifier("this"))]);
354 }
355});
356function getThisBinding(thisEnvFn, inConstructor) {
357 return getBinding(thisEnvFn, "this", thisBinding => {
358 if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression();
359 thisEnvFn.traverse(assignSuperThisVisitor, {
360 supers: new WeakSet(),
361 thisBinding
362 });
363 });
364}
365function getSuperBinding(thisEnvFn) {
366 return getBinding(thisEnvFn, "supercall", () => {
367 const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
368 return arrowFunctionExpression([restElement(argsBinding)], callExpression(_super(), [spreadElement(identifier(argsBinding.name))]));
369 });
370}
371function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
372 const op = isAssignment ? "set" : "get";
373 return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
374 const argsList = [];
375 let fnBody;
376 if (propName) {
377 fnBody = memberExpression(_super(), identifier(propName));
378 } else {
379 const method = thisEnvFn.scope.generateUidIdentifier("prop");
380 argsList.unshift(method);
381 fnBody = memberExpression(_super(), identifier(method.name), true);
382 }
383 if (isAssignment) {
384 const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
385 argsList.push(valueIdent);
386 fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name));
387 }
388 return arrowFunctionExpression(argsList, fnBody);
389 });
390}
391function getBinding(thisEnvFn, key, init) {
392 const cacheKey = "binding:" + key;
393 let data = thisEnvFn.getData(cacheKey);
394 if (!data) {
395 const id = thisEnvFn.scope.generateUidIdentifier(key);
396 data = id.name;
397 thisEnvFn.setData(cacheKey, data);
398 thisEnvFn.scope.push({
399 id: id,
400 init: init(data)
401 });
402 }
403 return data;
404}
405const getScopeInformationVisitor = (0, _visitors.environmentVisitor)({
406 ThisExpression(child, {
407 thisPaths
408 }) {
409 thisPaths.push(child);
410 },
411 JSXIdentifier(child, {
412 thisPaths
413 }) {
414 if (child.node.name !== "this") return;
415 if (!child.parentPath.isJSXMemberExpression({
416 object: child.node
417 }) && !child.parentPath.isJSXOpeningElement({
418 name: child.node
419 })) {
420 return;
421 }
422 thisPaths.push(child);
423 },
424 CallExpression(child, {
425 superCalls
426 }) {
427 if (child.get("callee").isSuper()) superCalls.push(child);
428 },
429 MemberExpression(child, {
430 superProps
431 }) {
432 if (child.get("object").isSuper()) superProps.push(child);
433 },
434 Identifier(child, {
435 argumentsPaths
436 }) {
437 if (!child.isReferencedIdentifier({
438 name: "arguments"
439 })) return;
440 let curr = child.scope;
441 do {
442 if (curr.hasOwnBinding("arguments")) {
443 curr.rename("arguments");
444 return;
445 }
446 if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
447 break;
448 }
449 } while (curr = curr.parent);
450 argumentsPaths.push(child);
451 },
452 MetaProperty(child, {
453 newTargetPaths
454 }) {
455 if (!child.get("meta").isIdentifier({
456 name: "new"
457 })) return;
458 if (!child.get("property").isIdentifier({
459 name: "target"
460 })) return;
461 newTargetPaths.push(child);
462 }
463});
464function getScopeInformation(fnPath) {
465 const thisPaths = [];
466 const argumentsPaths = [];
467 const newTargetPaths = [];
468 const superProps = [];
469 const superCalls = [];
470 fnPath.traverse(getScopeInformationVisitor, {
471 thisPaths,
472 argumentsPaths,
473 newTargetPaths,
474 superProps,
475 superCalls
476 });
477 return {
478 thisPaths,
479 argumentsPaths,
480 newTargetPaths,
481 superProps,
482 superCalls
483 };
484}
485function splitExportDeclaration() {
486 if (!this.isExportDeclaration() || this.isExportAllDeclaration()) {
487 throw new Error("Only default and named export declarations can be split.");
488 }
489 if (this.isExportNamedDeclaration() && this.get("specifiers").length > 0) {
490 throw new Error("It doesn't make sense to split exported specifiers.");
491 }
492 const declaration = this.get("declaration");
493 if (this.isExportDefaultDeclaration()) {
494 const standaloneDeclaration = declaration.isFunctionDeclaration() || declaration.isClassDeclaration();
495 const exportExpr = declaration.isFunctionExpression() || declaration.isClassExpression();
496 const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
497 let id = declaration.node.id;
498 let needBindingRegistration = false;
499 if (!id) {
500 needBindingRegistration = true;
501 id = scope.generateUidIdentifier("default");
502 if (standaloneDeclaration || exportExpr) {
503 declaration.node.id = cloneNode(id);
504 }
505 } else if (exportExpr && scope.hasBinding(id.name)) {
506 needBindingRegistration = true;
507 id = scope.generateUidIdentifier(id.name);
508 }
509 const updatedDeclaration = standaloneDeclaration ? declaration.node : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]);
510 const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]);
511 this.insertAfter(updatedExportDeclaration);
512 this.replaceWith(updatedDeclaration);
513 if (needBindingRegistration) {
514 scope.registerDeclaration(this);
515 }
516 return this;
517 } else if (this.get("specifiers").length > 0) {
518 throw new Error("It doesn't make sense to split exported specifiers.");
519 }
520 const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
521 const specifiers = Object.keys(bindingIdentifiers).map(name => {
522 return exportSpecifier(identifier(name), identifier(name));
523 });
524 const aliasDeclar = exportNamedDeclaration(null, specifiers);
525 this.insertAfter(aliasDeclar);
526 this.replaceWith(declaration.node);
527 return this;
528}
529const refersOuterBindingVisitor = {
530 "ReferencedIdentifier|BindingIdentifier"(path, state) {
531 if (path.node.name !== state.name) return;
532 state.needsRename = true;
533 path.stop();
534 },
535 Scope(path, state) {
536 if (path.scope.hasOwnBinding(state.name)) {
537 path.skip();
538 }
539 }
540};
541function ensureFunctionName(supportUnicodeId) {
542 if (this.node.id) return this;
543 const res = getFunctionName(this.node, this.parent);
544 if (res == null) return this;
545 let {
546 name
547 } = res;
548 if (!supportUnicodeId && /[\uD800-\uDFFF]/.test(name)) {
549 return null;
550 }
551 if (name.startsWith("get ") || name.startsWith("set ")) {
552 return null;
553 }
554 name = toBindingIdentifierName(name.replace(/[/ ]/g, "_"));
555 const id = identifier(name);
556 inherits(id, res.originalNode);
557 const state = {
558 needsRename: false,
559 name
560 };
561 const {
562 scope
563 } = this;
564 const binding = scope.getOwnBinding(name);
565 if (binding) {
566 if (binding.kind === "param") {
567 state.needsRename = true;
568 } else {}
569 } else if (scope.parent.hasBinding(name) || scope.hasGlobal(name)) {
570 this.traverse(refersOuterBindingVisitor, state);
571 }
572 if (!state.needsRename) {
573 this.node.id = id;
574 scope.getProgramParent().references[id.name] = true;
575 return this;
576 }
577 if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
578 scope.rename(id.name);
579 this.node.id = id;
580 scope.getProgramParent().references[id.name] = true;
581 return this;
582 }
583 if (!isFunction(this.node)) return null;
584 const key = scope.generateUidIdentifier(id.name);
585 const params = [];
586 for (let i = 0, len = getFunctionArity(this.node); i < len; i++) {
587 params.push(scope.generateUidIdentifier("x"));
588 }
589 const call = _template.default.expression.ast`
590 (function (${key}) {
591 function ${id}(${params}) {
592 return ${cloneNode(key)}.apply(this, arguments);
593 }
594
595 ${cloneNode(id)}.toString = function () {
596 return ${cloneNode(key)}.toString();
597 }
598
599 return ${cloneNode(id)};
600 })(${toExpression(this.node)})
601 `;
602 return this.replaceWith(call)[0].get("arguments.0");
603}
604function getFunctionArity(node) {
605 const count = node.params.findIndex(param => isAssignmentPattern(param) || isRestElement(param));
606 return count === -1 ? node.params.length : count;
607}
608
609//# sourceMappingURL=conversion.js.map
Note: See TracBrowser for help on using the repository browser.