This commit is contained in:
2022-07-18 02:50:52 +00:00
parent befd344ab0
commit 06181b34d6
8569 changed files with 818704 additions and 352705 deletions
+13 -15
View File
@@ -3,26 +3,24 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findParent = findParent;
exports.find = find;
exports.findParent = findParent;
exports.getAncestry = getAncestry;
exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom;
exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom;
exports.getFunctionParent = getFunctionParent;
exports.getStatementParent = getStatementParent;
exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom;
exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom;
exports.getAncestry = getAncestry;
exports.inType = inType;
exports.isAncestor = isAncestor;
exports.isDescendant = isDescendant;
exports.inType = inType;
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
var _index = _interopRequireDefault(require("./index"));
var _index = require("./index");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const {
VISITOR_KEYS
} = _t;
function findParent(callback) {
let path = this;
@@ -69,7 +67,7 @@ function getStatementParent() {
function getEarliestCommonAncestorFrom(paths) {
return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) {
let earliest;
const keys = t.VISITOR_KEYS[deepest.type];
const keys = VISITOR_KEYS[deepest.type];
for (const ancestry of ancestries) {
const path = ancestry[i + 1];
@@ -167,11 +165,11 @@ function isDescendant(maybeAncestor) {
return !!this.findParent(parent => parent === maybeAncestor);
}
function inType() {
function inType(...candidateTypes) {
let path = this;
while (path) {
for (const type of arguments) {
for (const type of candidateTypes) {
if (path.node.type === type) return true;
}
+8 -7
View File
@@ -3,15 +3,16 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.shareCommentsWithSiblings = shareCommentsWithSiblings;
exports.addComment = addComment;
exports.addComments = addComments;
exports.shareCommentsWithSiblings = shareCommentsWithSiblings;
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const {
addComment: _addComment,
addComments: _addComments
} = _t;
function shareCommentsWithSiblings() {
if (typeof this.key === "string") return;
@@ -33,9 +34,9 @@ function shareCommentsWithSiblings() {
}
function addComment(type, content, line) {
t.addComment(this.node, type, content, line);
_addComment(this.node, type, content, line);
}
function addComments(type, comments) {
t.addComments(this.node, type, comments);
_addComments(this.node, type, comments);
}
+49 -30
View File
@@ -3,32 +3,30 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.call = call;
exports._call = _call;
exports.isBlacklisted = isBlacklisted;
exports.visit = visit;
exports._getQueueContexts = _getQueueContexts;
exports._resyncKey = _resyncKey;
exports._resyncList = _resyncList;
exports._resyncParent = _resyncParent;
exports._resyncRemoved = _resyncRemoved;
exports.call = call;
exports.isBlacklisted = exports.isDenylisted = isDenylisted;
exports.popContext = popContext;
exports.pushContext = pushContext;
exports.requeue = requeue;
exports.resync = resync;
exports.setContext = setContext;
exports.setKey = setKey;
exports.setScope = setScope;
exports.setup = setup;
exports.skip = skip;
exports.skipKey = skipKey;
exports.stop = stop;
exports.setScope = setScope;
exports.setContext = setContext;
exports.resync = resync;
exports._resyncParent = _resyncParent;
exports._resyncKey = _resyncKey;
exports._resyncList = _resyncList;
exports._resyncRemoved = _resyncRemoved;
exports.popContext = popContext;
exports.pushContext = pushContext;
exports.setup = setup;
exports.setKey = setKey;
exports.requeue = requeue;
exports._getQueueContexts = _getQueueContexts;
exports.visit = visit;
var _index = _interopRequireDefault(require("../index"));
var _traverseNode = require("../traverse-node");
var _index2 = require("./index");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _index = require("./index");
function call(key) {
const opts = this.opts;
@@ -69,9 +67,19 @@ function _call(fns) {
return false;
}
function isBlacklisted() {
const blacklist = this.opts.blacklist;
return blacklist && blacklist.indexOf(this.node.type) > -1;
function isDenylisted() {
var _this$opts$denylist;
const denylist = (_this$opts$denylist = this.opts.denylist) != null ? _this$opts$denylist : this.opts.blacklist;
return denylist && denylist.indexOf(this.node.type) > -1;
}
function restoreContext(path, context) {
if (path.context !== context) {
path.context = context;
path.state = context.state;
path.opts = context.opts;
}
}
function visit() {
@@ -79,7 +87,7 @@ function visit() {
return false;
}
if (this.isBlacklisted()) {
if (this.isDenylisted()) {
return false;
}
@@ -87,15 +95,17 @@ function visit() {
return false;
}
if (this.shouldSkip || this.call("enter") || this.shouldSkip) {
const currentContext = this.context;
if (this.shouldSkip || this.call("enter")) {
this.debug("Skip...");
return this.shouldStop;
}
restoreContext(this, currentContext);
this.debug("Recursing into...");
_index.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys);
this.shouldStop = (0, _traverseNode.traverseNode)(this.node, this.opts, this.scope, this.state, this, this.skipKeys);
restoreContext(this, currentContext);
this.call("exit");
return this.shouldStop;
}
@@ -113,12 +123,17 @@ function skipKey(key) {
}
function stop() {
this._traverseFlags |= _index2.SHOULD_SKIP | _index2.SHOULD_STOP;
this._traverseFlags |= _index.SHOULD_SKIP | _index.SHOULD_STOP;
}
function setScope() {
if (this.opts && this.opts.noScope) return;
let path = this.parentPath;
if ((this.key === "key" || this.listKey === "decorators") && path.isMethod()) {
path = path.parentPath;
}
let target;
while (path && !target) {
@@ -166,7 +181,10 @@ function _resyncParent() {
function _resyncKey() {
if (!this.container) return;
if (this.node === this.container[this.key]) return;
if (this.node === this.container[this.key]) {
return;
}
if (Array.isArray(this.container)) {
for (let i = 0; i < this.container.length; i++) {
@@ -230,6 +248,7 @@ function setKey(key) {
function requeue(pathToQueue = this) {
if (pathToQueue.removed) return;
;
const contexts = this.contexts;
for (const context of contexts) {
+253 -149
View File
@@ -3,36 +3,61 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.toComputedKey = toComputedKey;
exports.ensureBlock = ensureBlock;
exports.arrowFunctionToShadowed = arrowFunctionToShadowed;
exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment;
exports.arrowFunctionToExpression = arrowFunctionToExpression;
exports.arrowFunctionToShadowed = arrowFunctionToShadowed;
exports.ensureBlock = ensureBlock;
exports.toComputedKey = toComputedKey;
exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment;
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name"));
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _helperFunctionName = require("@babel/helper-function-name");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
var _visitors = require("../visitors");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const {
arrowFunctionExpression,
assignmentExpression,
binaryExpression,
blockStatement,
callExpression,
conditionalExpression,
expressionStatement,
identifier,
isIdentifier,
jsxIdentifier,
logicalExpression,
LOGICAL_OPERATORS,
memberExpression,
metaProperty,
numericLiteral,
objectExpression,
restElement,
returnStatement,
sequenceExpression,
spreadElement,
stringLiteral,
super: _super,
thisExpression,
toExpression,
unaryExpression
} = _t;
function toComputedKey() {
const node = this.node;
let key;
if (this.isMemberExpression()) {
key = node.property;
key = this.node.property;
} else if (this.isProperty() || this.isMethod()) {
key = node.key;
key = this.node.key;
} else {
throw new ReferenceError("todo");
}
if (!node.computed) {
if (t.isIdentifier(key)) key = t.stringLiteral(key.name);
if (!this.node.computed) {
if (isIdentifier(key)) key = stringLiteral(key.name);
}
return key;
@@ -68,14 +93,14 @@ function ensureBlock() {
if (this.isFunction()) {
key = "argument";
statements.push(t.returnStatement(body.node));
statements.push(returnStatement(body.node));
} else {
key = "expression";
statements.push(t.expressionStatement(body.node));
statements.push(expressionStatement(body.node));
}
}
this.node.body = t.blockStatement(statements);
this.node.body = blockStatement(statements);
const parentPath = this.get(stringPath);
body.setup(parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
return this.node;
@@ -96,41 +121,75 @@ function unwrapFunctionEnvironment() {
function arrowFunctionToExpression({
allowInsertArrow = true,
specCompliant = false
specCompliant = false,
noNewArrows = !specCompliant
} = {}) {
if (!this.isArrowFunctionExpression()) {
throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
}
const thisBinding = hoistFunctionEnvironment(this, specCompliant, allowInsertArrow);
this.ensureBlock();
this.node.type = "FunctionExpression";
const {
thisBinding,
fnPath: fn
} = hoistFunctionEnvironment(this, noNewArrows, allowInsertArrow);
fn.ensureBlock();
fn.node.type = "FunctionExpression";
if (specCompliant) {
const checkBinding = thisBinding ? null : this.parentPath.scope.generateUidIdentifier("arrowCheckId");
if (!noNewArrows) {
const checkBinding = thisBinding ? null : fn.scope.generateUidIdentifier("arrowCheckId");
if (checkBinding) {
this.parentPath.scope.push({
fn.parentPath.scope.push({
id: checkBinding,
init: t.objectExpression([])
init: objectExpression([])
});
}
this.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(this.hub.addHelper("newArrowCheck"), [t.thisExpression(), checkBinding ? t.identifier(checkBinding.name) : t.identifier(thisBinding)])));
this.replaceWith(t.callExpression(t.memberExpression((0, _helperFunctionName.default)(this, true) || this.node, t.identifier("bind")), [checkBinding ? t.identifier(checkBinding.name) : t.thisExpression()]));
fn.get("body").unshiftContainer("body", expressionStatement(callExpression(this.hub.addHelper("newArrowCheck"), [thisExpression(), checkBinding ? identifier(checkBinding.name) : identifier(thisBinding)])));
fn.replaceWith(callExpression(memberExpression((0, _helperFunctionName.default)(this, true) || fn.node, identifier("bind")), [checkBinding ? identifier(checkBinding.name) : thisExpression()]));
}
}
function hoistFunctionEnvironment(fnPath, specCompliant = false, allowInsertArrow = true) {
const thisEnvFn = fnPath.findParent(p => {
return p.isFunction() && !p.isArrowFunctionExpression() || p.isProgram() || p.isClassProperty({
const getSuperCallsVisitor = (0, _visitors.merge)([{
CallExpression(child, {
allSuperCalls
}) {
if (!child.get("callee").isSuper()) return;
allSuperCalls.push(child);
}
}, _helperEnvironmentVisitor.default]);
function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true) {
let arrowParent;
let thisEnvFn = fnPath.findParent(p => {
if (p.isArrowFunctionExpression()) {
var _arrowParent;
(_arrowParent = arrowParent) != null ? _arrowParent : arrowParent = p;
return false;
}
return p.isFunction() || p.isProgram() || p.isClassProperty({
static: false
}) || p.isClassPrivateProperty({
static: false
});
});
const inConstructor = (thisEnvFn == null ? void 0 : thisEnvFn.node.kind) === "constructor";
const inConstructor = thisEnvFn.isClassMethod({
kind: "constructor"
});
if (thisEnvFn.isClassProperty()) {
throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) {
if (arrowParent) {
thisEnvFn = arrowParent;
} else if (allowInsertArrow) {
fnPath.replaceWith(callExpression(arrowFunctionExpression([], toExpression(fnPath.node)), []));
thisEnvFn = fnPath.get("callee");
fnPath = thisEnvFn.get("body");
} else {
throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
}
}
const {
@@ -147,43 +206,38 @@ function hoistFunctionEnvironment(fnPath, specCompliant = false, allowInsertArro
}
const allSuperCalls = [];
thisEnvFn.traverse({
Function(child) {
if (child.isArrowFunctionExpression()) return;
child.skip();
},
ClassProperty(child) {
child.skip();
},
CallExpression(child) {
if (!child.get("callee").isSuper()) return;
allSuperCalls.push(child);
}
thisEnvFn.traverse(getSuperCallsVisitor, {
allSuperCalls
});
const superBinding = getSuperBinding(thisEnvFn);
allSuperCalls.forEach(superCall => {
const callee = t.identifier(superBinding);
const callee = identifier(superBinding);
callee.loc = superCall.node.callee.loc;
superCall.get("callee").replaceWith(callee);
});
}
if (argumentsPaths.length > 0) {
const argumentsBinding = getBinding(thisEnvFn, "arguments", () => t.identifier("arguments"));
const argumentsBinding = getBinding(thisEnvFn, "arguments", () => {
const args = () => identifier("arguments");
if (thisEnvFn.scope.path.isProgram()) {
return conditionalExpression(binaryExpression("===", unaryExpression("typeof", args()), stringLiteral("undefined")), thisEnvFn.scope.buildUndefinedNode(), args());
} else {
return args();
}
});
argumentsPaths.forEach(argumentsChild => {
const argsRef = t.identifier(argumentsBinding);
const argsRef = identifier(argumentsBinding);
argsRef.loc = argumentsChild.node.loc;
argumentsChild.replaceWith(argsRef);
});
}
if (newTargetPaths.length > 0) {
const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => t.metaProperty(t.identifier("new"), t.identifier("target")));
const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => metaProperty(identifier("new"), identifier("target")));
newTargetPaths.forEach(targetChild => {
const targetRef = t.identifier(newTargetBinding);
const targetRef = identifier(newTargetBinding);
targetRef.loc = targetChild.node.loc;
targetChild.replaceWith(targetRef);
});
@@ -197,10 +251,11 @@ function hoistFunctionEnvironment(fnPath, specCompliant = false, allowInsertArro
const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []);
flatSuperProps.forEach(superProp => {
const key = superProp.node.computed ? "" : superProp.get("property").node.name;
const isAssignment = superProp.parentPath.isAssignmentExpression({
const superParentPath = superProp.parentPath;
const isAssignment = superParentPath.isAssignmentExpression({
left: superProp.node
});
const isCall = superProp.parentPath.isCallExpression({
const isCall = superParentPath.isCallExpression({
callee: superProp.node
});
const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
@@ -211,18 +266,18 @@ function hoistFunctionEnvironment(fnPath, specCompliant = false, allowInsertArro
}
if (isAssignment) {
const value = superProp.parentPath.node.right;
const value = superParentPath.node.right;
args.push(value);
}
const call = t.callExpression(t.identifier(superBinding), args);
const call = callExpression(identifier(superBinding), args);
if (isCall) {
superProp.parentPath.unshiftContainer("arguments", t.thisExpression());
superProp.replaceWith(t.memberExpression(call, t.identifier("call")));
thisPaths.push(superProp.parentPath.get("arguments.0"));
superParentPath.unshiftContainer("arguments", thisExpression());
superProp.replaceWith(memberExpression(call, identifier("call")));
thisPaths.push(superParentPath.get("arguments.0"));
} else if (isAssignment) {
superProp.parentPath.replaceWith(call);
superParentPath.replaceWith(call);
} else {
superProp.replaceWith(call);
}
@@ -231,20 +286,27 @@ function hoistFunctionEnvironment(fnPath, specCompliant = false, allowInsertArro
let thisBinding;
if (thisPaths.length > 0 || specCompliant) {
if (thisPaths.length > 0 || !noNewArrows) {
thisBinding = getThisBinding(thisEnvFn, inConstructor);
if (!specCompliant || inConstructor && hasSuperClass(thisEnvFn)) {
if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
thisPaths.forEach(thisChild => {
const thisRef = thisChild.isJSX() ? t.jsxIdentifier(thisBinding) : t.identifier(thisBinding);
const thisRef = thisChild.isJSX() ? jsxIdentifier(thisBinding) : identifier(thisBinding);
thisRef.loc = thisChild.node.loc;
thisChild.replaceWith(thisRef);
});
if (specCompliant) thisBinding = null;
if (!noNewArrows) thisBinding = null;
}
}
return thisBinding;
return {
thisBinding,
fnPath
};
}
function isLogicalOp(op) {
return LOGICAL_OPERATORS.includes(op);
}
function standardizeSuperProperty(superProp) {
@@ -252,15 +314,25 @@ function standardizeSuperProperty(superProp) {
const assignmentPath = superProp.parentPath;
const op = assignmentPath.node.operator.slice(0, -1);
const value = assignmentPath.node.right;
assignmentPath.node.operator = "=";
const isLogicalAssignment = isLogicalOp(op);
if (superProp.node.computed) {
const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
assignmentPath.get("left").replaceWith(t.memberExpression(superProp.node.object, t.assignmentExpression("=", tmp, superProp.node.property), true));
assignmentPath.get("right").replaceWith(t.binaryExpression(op, t.memberExpression(superProp.node.object, t.identifier(tmp.name), true), value));
const object = superProp.node.object;
const property = superProp.node.property;
assignmentPath.get("left").replaceWith(memberExpression(object, assignmentExpression("=", tmp, property), true));
assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(tmp.name), true), value));
} else {
assignmentPath.get("left").replaceWith(t.memberExpression(superProp.node.object, superProp.node.property));
assignmentPath.get("right").replaceWith(t.binaryExpression(op, t.memberExpression(superProp.node.object, t.identifier(superProp.node.property.name)), value));
const object = superProp.node.object;
const property = superProp.node.property;
assignmentPath.get("left").replaceWith(memberExpression(object, property));
assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(property.name)), value));
}
if (isLogicalAssignment) {
assignmentPath.replaceWith(logicalExpression(op, assignmentPath.node.left, assignmentPath.node.right));
} else {
assignmentPath.node.operator = "=";
}
return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
@@ -268,46 +340,52 @@ function standardizeSuperProperty(superProp) {
const updateExpr = superProp.parentPath;
const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
const parts = [t.assignmentExpression("=", tmp, t.memberExpression(superProp.node.object, computedKey ? t.assignmentExpression("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), t.assignmentExpression("=", t.memberExpression(superProp.node.object, computedKey ? t.identifier(computedKey.name) : superProp.node.property, superProp.node.computed), t.binaryExpression("+", t.identifier(tmp.name), t.numericLiteral(1)))];
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)))];
if (!superProp.parentPath.node.prefix) {
parts.push(t.identifier(tmp.name));
parts.push(identifier(tmp.name));
}
updateExpr.replaceWith(t.sequenceExpression(parts));
updateExpr.replaceWith(sequenceExpression(parts));
const left = updateExpr.get("expressions.0.right");
const right = updateExpr.get("expressions.1.left");
return [left, right];
}
return [superProp];
function rightExpression(op, left, right) {
if (op === "=") {
return assignmentExpression("=", left, right);
} else {
return binaryExpression(op, left, right);
}
}
}
function hasSuperClass(thisEnvFn) {
return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
}
const assignSuperThisVisitor = (0, _visitors.merge)([{
CallExpression(child, {
supers,
thisBinding
}) {
if (!child.get("callee").isSuper()) return;
if (supers.has(child.node)) return;
supers.add(child.node);
child.replaceWithMultiple([child.node, assignmentExpression("=", identifier(thisBinding), identifier("this"))]);
}
}, _helperEnvironmentVisitor.default]);
function getThisBinding(thisEnvFn, inConstructor) {
return getBinding(thisEnvFn, "this", thisBinding => {
if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression();
const supers = new WeakSet();
thisEnvFn.traverse({
Function(child) {
if (child.isArrowFunctionExpression()) return;
child.skip();
},
ClassProperty(child) {
child.skip();
},
CallExpression(child) {
if (!child.get("callee").isSuper()) return;
if (supers.has(child.node)) return;
supers.add(child.node);
child.replaceWithMultiple([child.node, t.assignmentExpression("=", t.identifier(thisBinding), t.identifier("this"))]);
}
if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression();
thisEnvFn.traverse(assignSuperThisVisitor, {
supers: new WeakSet(),
thisBinding
});
});
}
@@ -315,7 +393,7 @@ function getThisBinding(thisEnvFn, inConstructor) {
function getSuperBinding(thisEnvFn) {
return getBinding(thisEnvFn, "supercall", () => {
const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
return t.arrowFunctionExpression([t.restElement(argsBinding)], t.callExpression(t.super(), [t.spreadElement(t.identifier(argsBinding.name))]));
return arrowFunctionExpression([restElement(argsBinding)], callExpression(_super(), [spreadElement(identifier(argsBinding.name))]));
});
}
@@ -326,20 +404,20 @@ function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
let fnBody;
if (propName) {
fnBody = t.memberExpression(t.super(), t.identifier(propName));
fnBody = memberExpression(_super(), identifier(propName));
} else {
const method = thisEnvFn.scope.generateUidIdentifier("prop");
argsList.unshift(method);
fnBody = t.memberExpression(t.super(), t.identifier(method.name), true);
fnBody = memberExpression(_super(), identifier(method.name), true);
}
if (isAssignment) {
const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
argsList.push(valueIdent);
fnBody = t.assignmentExpression("=", fnBody, t.identifier(valueIdent.name));
fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name));
}
return t.arrowFunctionExpression(argsList, fnBody);
return arrowFunctionExpression(argsList, fnBody);
});
}
@@ -360,63 +438,89 @@ function getBinding(thisEnvFn, key, init) {
return data;
}
const getScopeInformationVisitor = (0, _visitors.merge)([{
ThisExpression(child, {
thisPaths
}) {
thisPaths.push(child);
},
JSXIdentifier(child, {
thisPaths
}) {
if (child.node.name !== "this") return;
if (!child.parentPath.isJSXMemberExpression({
object: child.node
}) && !child.parentPath.isJSXOpeningElement({
name: child.node
})) {
return;
}
thisPaths.push(child);
},
CallExpression(child, {
superCalls
}) {
if (child.get("callee").isSuper()) superCalls.push(child);
},
MemberExpression(child, {
superProps
}) {
if (child.get("object").isSuper()) superProps.push(child);
},
Identifier(child, {
argumentsPaths
}) {
if (!child.isReferencedIdentifier({
name: "arguments"
})) return;
let curr = child.scope;
do {
if (curr.hasOwnBinding("arguments")) {
curr.rename("arguments");
return;
}
if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
break;
}
} while (curr = curr.parent);
argumentsPaths.push(child);
},
MetaProperty(child, {
newTargetPaths
}) {
if (!child.get("meta").isIdentifier({
name: "new"
})) return;
if (!child.get("property").isIdentifier({
name: "target"
})) return;
newTargetPaths.push(child);
}
}, _helperEnvironmentVisitor.default]);
function getScopeInformation(fnPath) {
const thisPaths = [];
const argumentsPaths = [];
const newTargetPaths = [];
const superProps = [];
const superCalls = [];
fnPath.traverse({
ClassProperty(child) {
child.skip();
},
Function(child) {
if (child.isArrowFunctionExpression()) return;
child.skip();
},
ThisExpression(child) {
thisPaths.push(child);
},
JSXIdentifier(child) {
if (child.node.name !== "this") return;
if (!child.parentPath.isJSXMemberExpression({
object: child.node
}) && !child.parentPath.isJSXOpeningElement({
name: child.node
})) {
return;
}
thisPaths.push(child);
},
CallExpression(child) {
if (child.get("callee").isSuper()) superCalls.push(child);
},
MemberExpression(child) {
if (child.get("object").isSuper()) superProps.push(child);
},
ReferencedIdentifier(child) {
if (child.node.name !== "arguments") return;
argumentsPaths.push(child);
},
MetaProperty(child) {
if (!child.get("meta").isIdentifier({
name: "new"
})) return;
if (!child.get("property").isIdentifier({
name: "target"
})) return;
newTargetPaths.push(child);
}
fnPath.traverse(getScopeInformationVisitor, {
thisPaths,
argumentsPaths,
newTargetPaths,
superProps,
superCalls
});
return {
thisPaths,
+30 -25
View File
@@ -3,11 +3,19 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.evaluateTruthy = evaluateTruthy;
exports.evaluate = evaluate;
exports.evaluateTruthy = evaluateTruthy;
const VALID_CALLEES = ["String", "Number", "Math"];
const INVALID_METHODS = ["random"];
function isValidCallee(val) {
return VALID_CALLEES.includes(val);
}
function isInvalidMethod(val) {
return INVALID_METHODS.includes(val);
}
function evaluateTruthy() {
const res = this.evaluate();
if (res.confident) return !!res.value;
@@ -55,9 +63,6 @@ function evaluateCached(path, state) {
function _evaluate(path, state) {
if (!state.confident) return;
const {
node
} = path;
if (path.isSequenceExpression()) {
const exprs = path.get("expressions");
@@ -65,7 +70,7 @@ function _evaluate(path, state) {
}
if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) {
return node.value;
return path.node.value;
}
if (path.isNullLiteral()) {
@@ -73,7 +78,7 @@ function _evaluate(path, state) {
}
if (path.isTemplateLiteral()) {
return evaluateQuasis(path, node.quasis, state);
return evaluateQuasis(path, path.node.quasis, state);
}
if (path.isTaggedTemplateExpression() && path.get("tag").isMemberExpression()) {
@@ -85,8 +90,8 @@ function _evaluate(path, state) {
} = object;
const property = path.get("tag.property");
if (object.isIdentifier() && name === "String" && !path.scope.getBinding(name, true) && property.isIdentifier && property.node.name === "raw") {
return evaluateQuasis(path, node.quasi.quasis, state, true);
if (object.isIdentifier() && name === "String" && !path.scope.getBinding(name) && property.isIdentifier() && property.node.name === "raw") {
return evaluateQuasis(path, path.node.quasi.quasis, state, true);
}
}
@@ -106,7 +111,7 @@ function _evaluate(path, state) {
}
if (path.isMemberExpression() && !path.parentPath.isCallExpression({
callee: node
callee: path.node
})) {
const property = path.get("property");
const object = path.get("object");
@@ -122,7 +127,7 @@ function _evaluate(path, state) {
}
if (path.isReferencedIdentifier()) {
const binding = path.scope.getBinding(node.name);
const binding = path.scope.getBinding(path.node.name);
if (binding && binding.constantViolations.length > 0) {
return deopt(binding.path, state);
@@ -132,14 +137,14 @@ function _evaluate(path, state) {
return deopt(binding.path, state);
}
if (binding == null ? void 0 : binding.hasValue) {
if (binding != null && binding.hasValue) {
return binding.value;
} else {
if (node.name === "undefined") {
if (path.node.name === "undefined") {
return binding ? deopt(binding.path, state) : undefined;
} else if (node.name === "Infinity") {
} else if (path.node.name === "Infinity") {
return binding ? deopt(binding.path, state) : Infinity;
} else if (node.name === "NaN") {
} else if (path.node.name === "NaN") {
return binding ? deopt(binding.path, state) : NaN;
}
@@ -156,20 +161,20 @@ function _evaluate(path, state) {
if (path.isUnaryExpression({
prefix: true
})) {
if (node.operator === "void") {
if (path.node.operator === "void") {
return undefined;
}
const argument = path.get("argument");
if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) {
if (path.node.operator === "typeof" && (argument.isFunction() || argument.isClass())) {
return "function";
}
const arg = evaluateCached(argument, state);
if (!state.confident) return;
switch (node.operator) {
switch (path.node.operator) {
case "!":
return !arg;
@@ -197,7 +202,7 @@ function _evaluate(path, state) {
if (elemValue.confident) {
arr.push(elemValue.value);
} else {
return deopt(elem, state);
return deopt(elemValue.deopt, state);
}
}
@@ -220,7 +225,7 @@ function _evaluate(path, state) {
key = key.evaluate();
if (!key.confident) {
return deopt(keyPath, state);
return deopt(key.deopt, state);
}
key = key.value;
@@ -234,7 +239,7 @@ function _evaluate(path, state) {
let value = valuePath.evaluate();
if (!value.confident) {
return deopt(valuePath, state);
return deopt(value.deopt, state);
}
value = value.value;
@@ -252,7 +257,7 @@ function _evaluate(path, state) {
const right = evaluateCached(path.get("right"), state);
const rightConfident = state.confident;
switch (node.operator) {
switch (path.node.operator) {
case "||":
state.confident = leftConfident && (!!left || rightConfident);
if (!state.confident) return;
@@ -271,7 +276,7 @@ function _evaluate(path, state) {
const right = evaluateCached(path.get("right"), state);
if (!state.confident) return;
switch (node.operator) {
switch (path.node.operator) {
case "-":
return left - right;
@@ -339,15 +344,15 @@ function _evaluate(path, state) {
let context;
let func;
if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) {
func = global[node.callee.name];
if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name) && isValidCallee(callee.node.name)) {
func = global[callee.node.name];
}
if (callee.isMemberExpression()) {
const object = callee.get("object");
const property = callee.get("property");
if (object.isIdentifier() && property.isIdentifier() && VALID_CALLEES.indexOf(object.node.name) >= 0 && INVALID_METHODS.indexOf(property.node.name) < 0) {
if (object.isIdentifier() && property.isIdentifier() && isValidCallee(object.node.name) && !isInvalidMethod(property.node.name)) {
context = global[object.node.name];
func = context[property.node.name];
}
+209 -89
View File
@@ -3,30 +3,48 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getOpposite = getOpposite;
exports.getCompletionRecords = getCompletionRecords;
exports.getSibling = getSibling;
exports.getPrevSibling = getPrevSibling;
exports.getNextSibling = getNextSibling;
exports.getAllNextSiblings = getAllNextSiblings;
exports.getAllPrevSiblings = getAllPrevSiblings;
exports.get = get;
exports._getKey = _getKey;
exports._getPattern = _getPattern;
exports.getBindingIdentifiers = getBindingIdentifiers;
exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers;
exports.get = get;
exports.getAllNextSiblings = getAllNextSiblings;
exports.getAllPrevSiblings = getAllPrevSiblings;
exports.getBindingIdentifierPaths = getBindingIdentifierPaths;
exports.getBindingIdentifiers = getBindingIdentifiers;
exports.getCompletionRecords = getCompletionRecords;
exports.getNextSibling = getNextSibling;
exports.getOpposite = getOpposite;
exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths;
exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers;
exports.getPrevSibling = getPrevSibling;
exports.getSibling = getSibling;
var _index = _interopRequireDefault(require("./index"));
var _index = require("./index");
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
const {
getBindingIdentifiers: _getBindingIdentifiers,
getOuterBindingIdentifiers: _getOuterBindingIdentifiers,
isDeclaration,
numericLiteral,
unaryExpression
} = _t;
const NORMAL_COMPLETION = 0;
const BREAK_COMPLETION = 1;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function NormalCompletion(path) {
return {
type: NORMAL_COMPLETION,
path
};
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function BreakCompletion(path) {
return {
type: BREAK_COMPLETION,
path
};
}
function getOpposite() {
if (this.key === "left") {
@@ -34,88 +52,188 @@ function getOpposite() {
} else if (this.key === "right") {
return this.getSibling("left");
}
return null;
}
function addCompletionRecords(path, paths) {
if (path) return paths.concat(path.getCompletionRecords());
return paths;
function addCompletionRecords(path, records, context) {
if (path) {
records.push(..._getCompletionRecords(path, context));
}
return records;
}
function completionRecordForSwitch(cases, paths) {
let isLastCaseWithConsequent = true;
function completionRecordForSwitch(cases, records, context) {
let lastNormalCompletions = [];
for (let i = cases.length - 1; i >= 0; i--) {
const switchCase = cases[i];
const consequent = switchCase.get("consequent");
let breakStatement;
for (let i = 0; i < cases.length; i++) {
const casePath = cases[i];
findBreak: for (const statement of consequent) {
if (statement.isBlockStatement()) {
for (const statementInBlock of statement.get("body")) {
if (statementInBlock.isBreakStatement()) {
breakStatement = statementInBlock;
break findBreak;
const caseCompletions = _getCompletionRecords(casePath, context);
const normalCompletions = [];
const breakCompletions = [];
for (const c of caseCompletions) {
if (c.type === NORMAL_COMPLETION) {
normalCompletions.push(c);
}
if (c.type === BREAK_COMPLETION) {
breakCompletions.push(c);
}
}
if (normalCompletions.length) {
lastNormalCompletions = normalCompletions;
}
records.push(...breakCompletions);
}
records.push(...lastNormalCompletions);
return records;
}
function normalCompletionToBreak(completions) {
completions.forEach(c => {
c.type = BREAK_COMPLETION;
});
}
function replaceBreakStatementInBreakCompletion(completions, reachable) {
completions.forEach(c => {
if (c.path.isBreakStatement({
label: null
})) {
if (reachable) {
c.path.replaceWith(unaryExpression("void", numericLiteral(0)));
} else {
c.path.remove();
}
}
});
}
function getStatementListCompletion(paths, context) {
const completions = [];
if (context.canHaveBreak) {
let lastNormalCompletions = [];
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const newContext = Object.assign({}, context, {
inCaseClause: false
});
if (path.isBlockStatement() && (context.inCaseClause || context.shouldPopulateBreak)) {
newContext.shouldPopulateBreak = true;
} else {
newContext.shouldPopulateBreak = false;
}
const statementCompletions = _getCompletionRecords(path, newContext);
if (statementCompletions.length > 0 && statementCompletions.every(c => c.type === BREAK_COMPLETION)) {
if (lastNormalCompletions.length > 0 && statementCompletions.every(c => c.path.isBreakStatement({
label: null
}))) {
normalCompletionToBreak(lastNormalCompletions);
completions.push(...lastNormalCompletions);
if (lastNormalCompletions.some(c => c.path.isDeclaration())) {
completions.push(...statementCompletions);
replaceBreakStatementInBreakCompletion(statementCompletions, true);
}
replaceBreakStatementInBreakCompletion(statementCompletions, false);
} else {
completions.push(...statementCompletions);
if (!context.shouldPopulateBreak) {
replaceBreakStatementInBreakCompletion(statementCompletions, true);
}
}
} else if (statement.isBreakStatement()) {
breakStatement = statement;
break;
}
if (i === paths.length - 1) {
completions.push(...statementCompletions);
} else {
lastNormalCompletions = [];
for (let i = 0; i < statementCompletions.length; i++) {
const c = statementCompletions[i];
if (c.type === BREAK_COMPLETION) {
completions.push(c);
}
if (c.type === NORMAL_COMPLETION) {
lastNormalCompletions.push(c);
}
}
}
}
} else if (paths.length) {
for (let i = paths.length - 1; i >= 0; i--) {
const pathCompletions = _getCompletionRecords(paths[i], context);
if (pathCompletions.length > 1 || pathCompletions.length === 1 && !pathCompletions[0].path.isVariableDeclaration()) {
completions.push(...pathCompletions);
break;
}
}
if (breakStatement) {
while (breakStatement.key === 0 && breakStatement.parentPath.isBlockStatement()) {
breakStatement = breakStatement.parentPath;
}
const prevSibling = breakStatement.getPrevSibling();
if (breakStatement.key > 0 && (prevSibling.isExpressionStatement() || prevSibling.isBlockStatement())) {
paths = addCompletionRecords(prevSibling, paths);
breakStatement.remove();
} else {
breakStatement.replaceWith(breakStatement.scope.buildUndefinedNode());
paths = addCompletionRecords(breakStatement, paths);
}
} else if (isLastCaseWithConsequent) {
const statementFinder = statement => !statement.isBlockStatement() || statement.get("body").some(statementFinder);
const hasConsequent = consequent.some(statementFinder);
if (hasConsequent) {
paths = addCompletionRecords(consequent[consequent.length - 1], paths);
isLastCaseWithConsequent = false;
}
}
}
return paths;
return completions;
}
function _getCompletionRecords(path, context) {
let records = [];
if (path.isIfStatement()) {
records = addCompletionRecords(path.get("consequent"), records, context);
records = addCompletionRecords(path.get("alternate"), records, context);
} else if (path.isDoExpression() || path.isFor() || path.isWhile() || path.isLabeledStatement()) {
return addCompletionRecords(path.get("body"), records, context);
} else if (path.isProgram() || path.isBlockStatement()) {
return getStatementListCompletion(path.get("body"), context);
} else if (path.isFunction()) {
return _getCompletionRecords(path.get("body"), context);
} else if (path.isTryStatement()) {
records = addCompletionRecords(path.get("block"), records, context);
records = addCompletionRecords(path.get("handler"), records, context);
} else if (path.isCatchClause()) {
return addCompletionRecords(path.get("body"), records, context);
} else if (path.isSwitchStatement()) {
return completionRecordForSwitch(path.get("cases"), records, context);
} else if (path.isSwitchCase()) {
return getStatementListCompletion(path.get("consequent"), {
canHaveBreak: true,
shouldPopulateBreak: false,
inCaseClause: true
});
} else if (path.isBreakStatement()) {
records.push(BreakCompletion(path));
} else {
records.push(NormalCompletion(path));
}
return records;
}
function getCompletionRecords() {
let paths = [];
const records = _getCompletionRecords(this, {
canHaveBreak: false,
shouldPopulateBreak: false,
inCaseClause: false
});
if (this.isIfStatement()) {
paths = addCompletionRecords(this.get("consequent"), paths);
paths = addCompletionRecords(this.get("alternate"), paths);
} else if (this.isDoExpression() || this.isFor() || this.isWhile()) {
paths = addCompletionRecords(this.get("body"), paths);
} else if (this.isProgram() || this.isBlockStatement()) {
paths = addCompletionRecords(this.get("body").pop(), paths);
} else if (this.isFunction()) {
return this.get("body").getCompletionRecords();
} else if (this.isTryStatement()) {
paths = addCompletionRecords(this.get("block"), paths);
paths = addCompletionRecords(this.get("handler"), paths);
} else if (this.isCatchClause()) {
paths = addCompletionRecords(this.get("body"), paths);
} else if (this.isSwitchStatement()) {
paths = completionRecordForSwitch(this.get("cases"), paths);
} else {
paths.push(this);
}
return paths;
return records.map(r => r.path);
}
function getSibling(key) {
@@ -125,7 +243,7 @@ function getSibling(key) {
container: this.container,
listKey: this.listKey,
key: key
});
}).setContext(this.context);
}
function getPrevSibling() {
@@ -162,7 +280,7 @@ function getAllPrevSiblings() {
return siblings;
}
function get(key, context) {
function get(key, context = true) {
if (context === true) context = this.context;
const parts = key.split(".");
@@ -216,23 +334,23 @@ function _getPattern(parts, context) {
}
function getBindingIdentifiers(duplicates) {
return t.getBindingIdentifiers(this.node, duplicates);
return _getBindingIdentifiers(this.node, duplicates);
}
function getOuterBindingIdentifiers(duplicates) {
return t.getOuterBindingIdentifiers(this.node, duplicates);
return _getOuterBindingIdentifiers(this.node, duplicates);
}
function getBindingIdentifierPaths(duplicates = false, outerOnly = false) {
const path = this;
let search = [].concat(path);
const search = [path];
const ids = Object.create(null);
while (search.length) {
const id = search.shift();
if (!id) continue;
if (!id.node) continue;
const keys = t.getBindingIdentifiers.keys[id.node.type];
const keys = _getBindingIdentifiers.keys[id.node.type];
if (id.isIdentifier()) {
if (duplicates) {
@@ -249,7 +367,7 @@ function getBindingIdentifierPaths(duplicates = false, outerOnly = false) {
if (id.isExportDeclaration()) {
const declaration = id.get("declaration");
if (declaration.isDeclaration()) {
if (isDeclaration(declaration)) {
search.push(declaration);
}
@@ -272,8 +390,10 @@ function getBindingIdentifierPaths(duplicates = false, outerOnly = false) {
const key = keys[i];
const child = id.get(key);
if (Array.isArray(child) || child.node) {
search = search.concat(child);
if (Array.isArray(child)) {
search.push(...child);
} else if (child.node) {
search.push(child);
}
}
}
+5
View File
@@ -0,0 +1,5 @@
"use strict";
var t = require("@babel/types");
var _index = require("../index");
+5
View File
@@ -0,0 +1,5 @@
"use strict";
var t = require("@babel/types");
var _index = require("../index");
+3
View File
@@ -0,0 +1,3 @@
"use strict";
var t = require("@babel/types");
+49 -45
View File
@@ -3,51 +3,52 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.SHOULD_SKIP = exports.SHOULD_STOP = exports.REMOVED = void 0;
exports.default = exports.SHOULD_STOP = exports.SHOULD_SKIP = exports.REMOVED = void 0;
var virtualTypes = _interopRequireWildcard(require("./lib/virtual-types"));
var virtualTypes = require("./lib/virtual-types");
var _debug = _interopRequireDefault(require("debug"));
var _debug = require("debug");
var _index = _interopRequireDefault(require("../index"));
var _index = require("../index");
var _scope = _interopRequireDefault(require("../scope"));
var _scope = require("../scope");
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
var t = _t;
var _cache = require("../cache");
var _generator = _interopRequireDefault(require("@babel/generator"));
var _generator = require("@babel/generator");
var NodePath_ancestry = _interopRequireWildcard(require("./ancestry"));
var NodePath_ancestry = require("./ancestry");
var NodePath_inference = _interopRequireWildcard(require("./inference"));
var NodePath_inference = require("./inference");
var NodePath_replacement = _interopRequireWildcard(require("./replacement"));
var NodePath_replacement = require("./replacement");
var NodePath_evaluation = _interopRequireWildcard(require("./evaluation"));
var NodePath_evaluation = require("./evaluation");
var NodePath_conversion = _interopRequireWildcard(require("./conversion"));
var NodePath_conversion = require("./conversion");
var NodePath_introspection = _interopRequireWildcard(require("./introspection"));
var NodePath_introspection = require("./introspection");
var NodePath_context = _interopRequireWildcard(require("./context"));
var NodePath_context = require("./context");
var NodePath_removal = _interopRequireWildcard(require("./removal"));
var NodePath_removal = require("./removal");
var NodePath_modification = _interopRequireWildcard(require("./modification"));
var NodePath_modification = require("./modification");
var NodePath_family = _interopRequireWildcard(require("./family"));
var NodePath_family = require("./family");
var NodePath_comments = _interopRequireWildcard(require("./comments"));
var NodePath_comments = require("./comments");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const {
validate
} = _t;
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
const debug = _debug("babel");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const debug = (0, _debug.default)("babel");
const REMOVED = 1 << 0;
exports.REMOVED = REMOVED;
const SHOULD_STOP = 1 << 1;
@@ -57,22 +58,22 @@ exports.SHOULD_SKIP = SHOULD_SKIP;
class NodePath {
constructor(hub, parent) {
this.parent = parent;
this.hub = hub;
this.contexts = [];
this.data = null;
this._traverseFlags = 0;
this.state = null;
this.opts = null;
this._traverseFlags = 0;
this.skipKeys = null;
this.parentPath = null;
this.context = null;
this.container = null;
this.listKey = null;
this.key = null;
this.node = null;
this.scope = null;
this.type = null;
this.parent = parent;
this.hub = hub;
this.data = null;
this.context = null;
this.scope = null;
}
static get({
@@ -92,26 +93,20 @@ class NodePath {
}
const targetNode = container[key];
const paths = _cache.path.get(parent) || [];
if (!_cache.path.has(parent)) {
let paths = _cache.path.get(parent);
if (!paths) {
paths = new Map();
_cache.path.set(parent, paths);
}
let path;
for (let i = 0; i < paths.length; i++) {
const pathCheck = paths[i];
if (pathCheck.node === targetNode) {
path = pathCheck;
break;
}
}
let path = paths.get(targetNode);
if (!path) {
path = new NodePath(hub, parent);
paths.push(path);
if (targetNode) paths.set(targetNode, path);
}
path.setup(parentPath, container, listKey, key);
@@ -140,6 +135,10 @@ class NodePath {
return val;
}
hasNode() {
return this.node != null;
}
buildCodeFrameError(msg, Error = SyntaxError) {
return this.hub.buildError(this.node, msg, Error);
}
@@ -149,7 +148,7 @@ class NodePath {
}
set(key, node) {
t.validate(this.node, key, node);
validate(this.node, key, node);
this.node[key] = node;
}
@@ -227,8 +226,10 @@ class NodePath {
}
exports.default = NodePath;
Object.assign(NodePath.prototype, NodePath_ancestry, NodePath_inference, NodePath_replacement, NodePath_evaluation, NodePath_conversion, NodePath_introspection, NodePath_context, NodePath_removal, NodePath_modification, NodePath_family, NodePath_comments);
{
NodePath.prototype._guessExecutionStatusRelativeToDifferentFunctions = NodePath_introspection._guessExecutionStatusRelativeTo;
}
for (const type of t.TYPES) {
const typeKey = `is${type}`;
@@ -253,4 +254,7 @@ for (const type of Object.keys(virtualTypes)) {
NodePath.prototype[`is${type}`] = function (opts) {
return virtualType.checkPath(this, opts);
};
}
}
var _default = NodePath;
exports.default = _default;
+90 -38
View File
@@ -3,31 +3,60 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getTypeAnnotation = getTypeAnnotation;
exports._getTypeAnnotation = _getTypeAnnotation;
exports.isBaseType = isBaseType;
exports.couldBeBaseType = couldBeBaseType;
exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches;
exports.couldBeBaseType = couldBeBaseType;
exports.getTypeAnnotation = getTypeAnnotation;
exports.isBaseType = isBaseType;
exports.isGenericType = isGenericType;
var inferers = _interopRequireWildcard(require("./inferers"));
var inferers = require("./inferers");
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const {
anyTypeAnnotation,
isAnyTypeAnnotation,
isArrayTypeAnnotation,
isBooleanTypeAnnotation,
isEmptyTypeAnnotation,
isFlowBaseAnnotation,
isGenericTypeAnnotation,
isIdentifier,
isMixedTypeAnnotation,
isNumberTypeAnnotation,
isStringTypeAnnotation,
isTSArrayType,
isTSTypeAnnotation,
isTSTypeReference,
isTupleTypeAnnotation,
isTypeAnnotation,
isUnionTypeAnnotation,
isVoidTypeAnnotation,
stringTypeAnnotation,
voidTypeAnnotation
} = _t;
function getTypeAnnotation() {
if (this.typeAnnotation) return this.typeAnnotation;
let type = this._getTypeAnnotation() || t.anyTypeAnnotation();
if (t.isTypeAnnotation(type)) type = type.typeAnnotation;
return this.typeAnnotation = type;
let type = this.getData("typeAnnotation");
if (type != null) {
return type;
}
type = this._getTypeAnnotation() || anyTypeAnnotation();
if (isTypeAnnotation(type) || isTSTypeAnnotation(type)) {
type = type.typeAnnotation;
}
this.setData("typeAnnotation", type);
return type;
}
function _getTypeAnnotation() {
var _inferer;
const typeAnnotationInferringNodes = new WeakSet();
function _getTypeAnnotation() {
const node = this.node;
if (!node) {
@@ -36,14 +65,14 @@ function _getTypeAnnotation() {
const declarParent = declar.parentPath;
if (declar.key === "left" && declarParent.isForInStatement()) {
return t.stringTypeAnnotation();
return stringTypeAnnotation();
}
if (declar.key === "left" && declarParent.isForOfStatement()) {
return t.anyTypeAnnotation();
return anyTypeAnnotation();
}
return t.voidTypeAnnotation();
return voidTypeAnnotation();
} else {
return;
}
@@ -53,16 +82,28 @@ function _getTypeAnnotation() {
return node.typeAnnotation;
}
let inferer = inferers[node.type];
if (inferer) {
return inferer.call(this, node);
if (typeAnnotationInferringNodes.has(node)) {
return;
}
inferer = inferers[this.parentPath.type];
typeAnnotationInferringNodes.add(node);
if ((_inferer = inferer) == null ? void 0 : _inferer.validParent) {
return this.parentPath.getTypeAnnotation();
try {
var _inferer;
let inferer = inferers[node.type];
if (inferer) {
return inferer.call(this, node);
}
inferer = inferers[this.parentPath.type];
if ((_inferer = inferer) != null && _inferer.validParent) {
return this.parentPath.getTypeAnnotation();
}
} finally {
typeAnnotationInferringNodes.delete(node);
}
}
@@ -72,19 +113,19 @@ function isBaseType(baseName, soft) {
function _isBaseType(baseName, type, soft) {
if (baseName === "string") {
return t.isStringTypeAnnotation(type);
return isStringTypeAnnotation(type);
} else if (baseName === "number") {
return t.isNumberTypeAnnotation(type);
return isNumberTypeAnnotation(type);
} else if (baseName === "boolean") {
return t.isBooleanTypeAnnotation(type);
return isBooleanTypeAnnotation(type);
} else if (baseName === "any") {
return t.isAnyTypeAnnotation(type);
return isAnyTypeAnnotation(type);
} else if (baseName === "mixed") {
return t.isMixedTypeAnnotation(type);
return isMixedTypeAnnotation(type);
} else if (baseName === "empty") {
return t.isEmptyTypeAnnotation(type);
return isEmptyTypeAnnotation(type);
} else if (baseName === "void") {
return t.isVoidTypeAnnotation(type);
return isVoidTypeAnnotation(type);
} else {
if (soft) {
return false;
@@ -96,11 +137,11 @@ function _isBaseType(baseName, type, soft) {
function couldBeBaseType(name) {
const type = this.getTypeAnnotation();
if (t.isAnyTypeAnnotation(type)) return true;
if (isAnyTypeAnnotation(type)) return true;
if (t.isUnionTypeAnnotation(type)) {
if (isUnionTypeAnnotation(type)) {
for (const type2 of type.types) {
if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) {
if (isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) {
return true;
}
}
@@ -111,18 +152,29 @@ function couldBeBaseType(name) {
}
}
function baseTypeStrictlyMatches(right) {
function baseTypeStrictlyMatches(rightArg) {
const left = this.getTypeAnnotation();
right = right.getTypeAnnotation();
const right = rightArg.getTypeAnnotation();
if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) {
if (!isAnyTypeAnnotation(left) && isFlowBaseAnnotation(left)) {
return right.type === left.type;
}
return false;
}
function isGenericType(genericName) {
const type = this.getTypeAnnotation();
return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, {
if (genericName === "Array") {
if (isTSArrayType(type) || isArrayTypeAnnotation(type) || isTupleTypeAnnotation(type)) {
return true;
}
}
return isGenericTypeAnnotation(type) && isIdentifier(type.id, {
name: genericName
}) || isTSTypeReference(type) && isIdentifier(type.typeName, {
name: genericName
});
}
+17 -34
View File
@@ -5,11 +5,16 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = _default;
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
var _util = require("./util");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const {
BOOLEAN_NUMBER_BINARY_OPERATORS,
createTypeAnnotationBasedOnTypeof,
numberTypeAnnotation,
voidTypeAnnotation
} = _t;
function _default(node) {
if (!this.isReferenced()) return;
@@ -24,9 +29,9 @@ function _default(node) {
}
if (node.name === "undefined") {
return t.voidTypeAnnotation();
return voidTypeAnnotation();
} else if (node.name === "NaN" || node.name === "Infinity") {
return t.numberTypeAnnotation();
return numberTypeAnnotation();
} else if (node.name === "arguments") {}
}
@@ -43,7 +48,7 @@ function getTypeAnnotationBindingConstantViolations(binding, path, name) {
}
if (constantViolations.length) {
constantViolations = constantViolations.concat(functionConstantViolations);
constantViolations.push(...functionConstantViolations);
for (const violation of constantViolations) {
types.push(violation.getTypeAnnotation());
@@ -54,15 +59,7 @@ function getTypeAnnotationBindingConstantViolations(binding, path, name) {
return;
}
if (t.isTSTypeAnnotation(types[0]) && t.createTSUnionType) {
return t.createTSUnionType(types);
}
if (t.createFlowUnionType) {
return t.createFlowUnionType(types);
}
return t.createUnionTypeAnnotation(types);
return (0, _util.createUnionType)(types);
}
function getConstantViolationsBefore(binding, path, functions) {
@@ -99,8 +96,8 @@ function inferAnnotationFromBinaryExpression(name, path) {
return target.getTypeAnnotation();
}
if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
if (BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return numberTypeAnnotation();
}
return;
@@ -130,7 +127,7 @@ function inferAnnotationFromBinaryExpression(name, path) {
if (!typePath.isLiteral()) return;
const typeValue = typePath.node.value;
if (typeof typeValue !== "string") return;
return t.createTypeAnnotationBasedOnTypeof(typeValue);
return createTypeAnnotationBasedOnTypeof(typeValue);
}
function getParentConditionalPath(binding, path, name) {
@@ -175,25 +172,11 @@ function getConditionalAnnotation(binding, path, name) {
}
if (types.length) {
if (t.isTSTypeAnnotation(types[0]) && t.createTSUnionType) {
return {
typeAnnotation: t.createTSUnionType(types),
ifStatement
};
}
if (t.createFlowUnionType) {
return {
typeAnnotation: t.createFlowUnionType(types),
ifStatement
};
}
return {
typeAnnotation: t.createUnionTypeAnnotation(types),
typeAnnotation: (0, _util.createUnionType)(types),
ifStatement
};
}
return getConditionalAnnotation(ifStatement, name);
return getConditionalAnnotation(binding, ifStatement, name);
}
+107 -102
View File
@@ -3,63 +3,68 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.VariableDeclarator = VariableDeclarator;
exports.TypeCastExpression = TypeCastExpression;
exports.NewExpression = NewExpression;
exports.TemplateLiteral = TemplateLiteral;
exports.UnaryExpression = UnaryExpression;
exports.BinaryExpression = BinaryExpression;
exports.LogicalExpression = LogicalExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.SequenceExpression = SequenceExpression;
exports.ParenthesizedExpression = ParenthesizedExpression;
exports.AssignmentExpression = AssignmentExpression;
exports.UpdateExpression = UpdateExpression;
exports.StringLiteral = StringLiteral;
exports.NumericLiteral = NumericLiteral;
exports.BooleanLiteral = BooleanLiteral;
exports.NullLiteral = NullLiteral;
exports.RegExpLiteral = RegExpLiteral;
exports.ObjectExpression = ObjectExpression;
exports.ArrayExpression = ArrayExpression;
exports.RestElement = RestElement;
exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = Func;
exports.AssignmentExpression = AssignmentExpression;
exports.BinaryExpression = BinaryExpression;
exports.BooleanLiteral = BooleanLiteral;
exports.CallExpression = CallExpression;
exports.TaggedTemplateExpression = TaggedTemplateExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = Func;
Object.defineProperty(exports, "Identifier", {
enumerable: true,
get: function () {
return _infererReference.default;
}
});
exports.LogicalExpression = LogicalExpression;
exports.NewExpression = NewExpression;
exports.NullLiteral = NullLiteral;
exports.NumericLiteral = NumericLiteral;
exports.ObjectExpression = ObjectExpression;
exports.ParenthesizedExpression = ParenthesizedExpression;
exports.RegExpLiteral = RegExpLiteral;
exports.RestElement = RestElement;
exports.SequenceExpression = SequenceExpression;
exports.StringLiteral = StringLiteral;
exports.TSAsExpression = TSAsExpression;
exports.TSNonNullExpression = TSNonNullExpression;
exports.TaggedTemplateExpression = TaggedTemplateExpression;
exports.TemplateLiteral = TemplateLiteral;
exports.TypeCastExpression = TypeCastExpression;
exports.UnaryExpression = UnaryExpression;
exports.UpdateExpression = UpdateExpression;
exports.VariableDeclarator = VariableDeclarator;
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
var _infererReference = _interopRequireDefault(require("./inferer-reference"));
var _infererReference = require("./inferer-reference");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _util = require("./util");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const {
BOOLEAN_BINARY_OPERATORS,
BOOLEAN_UNARY_OPERATORS,
NUMBER_BINARY_OPERATORS,
NUMBER_UNARY_OPERATORS,
STRING_UNARY_OPERATORS,
anyTypeAnnotation,
arrayTypeAnnotation,
booleanTypeAnnotation,
buildMatchMemberExpression,
genericTypeAnnotation,
identifier,
nullLiteralTypeAnnotation,
numberTypeAnnotation,
stringTypeAnnotation,
tupleTypeAnnotation,
unionTypeAnnotation,
voidTypeAnnotation,
isIdentifier
} = _t;
function VariableDeclarator() {
var _type;
const id = this.get("id");
if (!id.isIdentifier()) return;
const init = this.get("init");
let type = init.getTypeAnnotation();
if (((_type = type) == null ? void 0 : _type.type) === "AnyTypeAnnotation") {
if (init.isCallExpression() && init.get("callee").isIdentifier({
name: "Array"
}) && !init.scope.hasBinding("Array", true)) {
type = ArrayExpression();
}
}
return type;
if (!this.get("id").isIdentifier()) return;
return this.get("init").getTypeAnnotation();
}
function TypeCastExpression(node) {
@@ -68,77 +73,69 @@ function TypeCastExpression(node) {
TypeCastExpression.validParent = true;
function TSAsExpression(node) {
return node.typeAnnotation;
}
TSAsExpression.validParent = true;
function TSNonNullExpression() {
return this.get("expression").getTypeAnnotation();
}
function NewExpression(node) {
if (this.get("callee").isIdentifier()) {
return t.genericTypeAnnotation(node.callee);
if (node.callee.type === "Identifier") {
return genericTypeAnnotation(node.callee);
}
}
function TemplateLiteral() {
return t.stringTypeAnnotation();
return stringTypeAnnotation();
}
function UnaryExpression(node) {
const operator = node.operator;
if (operator === "void") {
return t.voidTypeAnnotation();
} else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
} else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.stringTypeAnnotation();
} else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.booleanTypeAnnotation();
return voidTypeAnnotation();
} else if (NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) {
return numberTypeAnnotation();
} else if (STRING_UNARY_OPERATORS.indexOf(operator) >= 0) {
return stringTypeAnnotation();
} else if (BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) {
return booleanTypeAnnotation();
}
}
function BinaryExpression(node) {
const operator = node.operator;
if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
} else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.booleanTypeAnnotation();
if (NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return numberTypeAnnotation();
} else if (BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) {
return booleanTypeAnnotation();
} else if (operator === "+") {
const right = this.get("right");
const left = this.get("left");
if (left.isBaseType("number") && right.isBaseType("number")) {
return t.numberTypeAnnotation();
return numberTypeAnnotation();
} else if (left.isBaseType("string") || right.isBaseType("string")) {
return t.stringTypeAnnotation();
return stringTypeAnnotation();
}
return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]);
return unionTypeAnnotation([stringTypeAnnotation(), numberTypeAnnotation()]);
}
}
function LogicalExpression() {
const argumentTypes = [this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()];
if (t.isTSTypeAnnotation(argumentTypes[0]) && t.createTSUnionType) {
return t.createTSUnionType(argumentTypes);
}
if (t.createFlowUnionType) {
return t.createFlowUnionType(argumentTypes);
}
return t.createUnionTypeAnnotation(argumentTypes);
return (0, _util.createUnionType)(argumentTypes);
}
function ConditionalExpression() {
const argumentTypes = [this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()];
if (t.isTSTypeAnnotation(argumentTypes[0]) && t.createTSUnionType) {
return t.createTSUnionType(argumentTypes);
}
if (t.createFlowUnionType) {
return t.createFlowUnionType(argumentTypes);
}
return t.createUnionTypeAnnotation(argumentTypes);
return (0, _util.createUnionType)(argumentTypes);
}
function SequenceExpression() {
@@ -157,36 +154,36 @@ function UpdateExpression(node) {
const operator = node.operator;
if (operator === "++" || operator === "--") {
return t.numberTypeAnnotation();
return numberTypeAnnotation();
}
}
function StringLiteral() {
return t.stringTypeAnnotation();
return stringTypeAnnotation();
}
function NumericLiteral() {
return t.numberTypeAnnotation();
return numberTypeAnnotation();
}
function BooleanLiteral() {
return t.booleanTypeAnnotation();
return booleanTypeAnnotation();
}
function NullLiteral() {
return t.nullLiteralTypeAnnotation();
return nullLiteralTypeAnnotation();
}
function RegExpLiteral() {
return t.genericTypeAnnotation(t.identifier("RegExp"));
return genericTypeAnnotation(identifier("RegExp"));
}
function ObjectExpression() {
return t.genericTypeAnnotation(t.identifier("Object"));
return genericTypeAnnotation(identifier("Object"));
}
function ArrayExpression() {
return t.genericTypeAnnotation(t.identifier("Array"));
return genericTypeAnnotation(identifier("Array"));
}
function RestElement() {
@@ -196,13 +193,13 @@ function RestElement() {
RestElement.validParent = true;
function Func() {
return t.genericTypeAnnotation(t.identifier("Function"));
return genericTypeAnnotation(identifier("Function"));
}
const isArrayFrom = t.buildMatchMemberExpression("Array.from");
const isObjectKeys = t.buildMatchMemberExpression("Object.keys");
const isObjectValues = t.buildMatchMemberExpression("Object.values");
const isObjectEntries = t.buildMatchMemberExpression("Object.entries");
const isArrayFrom = buildMatchMemberExpression("Array.from");
const isObjectKeys = buildMatchMemberExpression("Object.keys");
const isObjectValues = buildMatchMemberExpression("Object.values");
const isObjectEntries = buildMatchMemberExpression("Object.entries");
function CallExpression() {
const {
@@ -210,11 +207,13 @@ function CallExpression() {
} = this.node;
if (isObjectKeys(callee)) {
return t.arrayTypeAnnotation(t.stringTypeAnnotation());
} else if (isArrayFrom(callee) || isObjectValues(callee)) {
return t.arrayTypeAnnotation(t.anyTypeAnnotation());
return arrayTypeAnnotation(stringTypeAnnotation());
} else if (isArrayFrom(callee) || isObjectValues(callee) || isIdentifier(callee, {
name: "Array"
})) {
return arrayTypeAnnotation(anyTypeAnnotation());
} else if (isObjectEntries(callee)) {
return t.arrayTypeAnnotation(t.tupleTypeAnnotation([t.stringTypeAnnotation(), t.anyTypeAnnotation()]));
return arrayTypeAnnotation(tupleTypeAnnotation([stringTypeAnnotation(), anyTypeAnnotation()]));
}
return resolveCall(this.get("callee"));
@@ -228,14 +227,20 @@ function resolveCall(callee) {
callee = callee.resolve();
if (callee.isFunction()) {
if (callee.is("async")) {
if (callee.is("generator")) {
return t.genericTypeAnnotation(t.identifier("AsyncIterator"));
const {
node
} = callee;
if (node.async) {
if (node.generator) {
return genericTypeAnnotation(identifier("AsyncIterator"));
} else {
return t.genericTypeAnnotation(t.identifier("Promise"));
return genericTypeAnnotation(identifier("Promise"));
}
} else {
if (callee.node.returnType) {
if (node.generator) {
return genericTypeAnnotation(identifier("Iterator"));
} else if (callee.node.returnType) {
return callee.node.returnType;
} else {}
}
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createUnionType = createUnionType;
var _t = require("@babel/types");
const {
createFlowUnionType,
createTSUnionType,
createUnionTypeAnnotation,
isFlowType,
isTSType
} = _t;
function createUnionType(types) {
{
if (isFlowType(types[0])) {
if (createFlowUnionType) {
return createFlowUnionType(types);
}
return createUnionTypeAnnotation(types);
} else {
if (createTSUnionType) {
return createTSUnionType(types);
}
}
}
}
+91 -55
View File
@@ -3,39 +3,42 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.matchesPattern = matchesPattern;
exports.has = has;
exports.isStatic = isStatic;
exports.isnt = isnt;
exports.equals = equals;
exports.isNodeType = isNodeType;
exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo;
exports._resolve = _resolve;
exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression;
exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement;
exports.isCompletionRecord = isCompletionRecord;
exports.isStatementOrBlock = isStatementOrBlock;
exports.referencesImport = referencesImport;
exports.equals = equals;
exports.getSource = getSource;
exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore;
exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo;
exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions;
exports.resolve = resolve;
exports._resolve = _resolve;
exports.has = has;
exports.is = void 0;
exports.isCompletionRecord = isCompletionRecord;
exports.isConstantExpression = isConstantExpression;
exports.isInStrictMode = isInStrictMode;
exports.is = void 0;
exports.isNodeType = isNodeType;
exports.isStatementOrBlock = isStatementOrBlock;
exports.isStatic = isStatic;
exports.isnt = isnt;
exports.matchesPattern = matchesPattern;
exports.referencesImport = referencesImport;
exports.resolve = resolve;
exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore;
var _includes = _interopRequireDefault(require("lodash/includes"));
var _t = require("@babel/types");
var t = _interopRequireWildcard(require("@babel/types"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const {
STATEMENT_OR_BLOCK_KEYS,
VISITOR_KEYS,
isBlockStatement,
isExpression,
isIdentifier,
isLiteral,
isStringLiteral,
isType,
matchesPattern: _matchesPattern
} = _t;
function matchesPattern(pattern, allowPartial) {
return t.matchesPattern(this.node, pattern, allowPartial);
return _matchesPattern(this.node, pattern, allowPartial);
}
function has(key) {
@@ -64,7 +67,7 @@ function equals(key, value) {
}
function isNodeType(type) {
return t.isType(this.type, type);
return isType(this.type, type);
}
function canHaveVariableDeclarationOrExpression() {
@@ -77,9 +80,9 @@ function canSwapBetweenExpressionAndStatement(replacement) {
}
if (this.isExpression()) {
return t.isBlockStatement(replacement);
return isBlockStatement(replacement);
} else if (this.isBlockStatement()) {
return t.isExpression(replacement);
return isExpression(replacement);
}
return false;
@@ -90,9 +93,12 @@ function isCompletionRecord(allowInsideFunction) {
let first = true;
do {
const container = path.container;
const {
type,
container
} = path;
if (path.isFunction() && !first) {
if (!first && (path.isFunction() || type === "StaticBlock")) {
return !!allowInsideFunction;
}
@@ -101,21 +107,31 @@ function isCompletionRecord(allowInsideFunction) {
if (Array.isArray(container) && path.key !== container.length - 1) {
return false;
}
} while ((path = path.parentPath) && !path.isProgram());
} while ((path = path.parentPath) && !path.isProgram() && !path.isDoExpression());
return true;
}
function isStatementOrBlock() {
if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) {
if (this.parentPath.isLabeledStatement() || isBlockStatement(this.container)) {
return false;
} else {
return (0, _includes.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key);
return STATEMENT_OR_BLOCK_KEYS.includes(this.key);
}
}
function referencesImport(moduleSource, importName) {
if (!this.isReferencedIdentifier()) return false;
if (!this.isReferencedIdentifier()) {
if (this.isJSXMemberExpression() && this.node.property.name === importName || (this.isMemberExpression() || this.isOptionalMemberExpression()) && (this.node.computed ? isStringLiteral(this.node.property, {
value: importName
}) : this.node.property.name === importName)) {
const object = this.get("object");
return object.isReferencedIdentifier() && object.referencesImport(moduleSource, "*");
}
return false;
}
const binding = this.scope.getBinding(this.node.name);
if (!binding || binding.kind !== "module") return false;
const path = binding.path;
@@ -136,7 +152,9 @@ function referencesImport(moduleSource, importName) {
return true;
}
if (path.isImportSpecifier() && path.node.imported.name === importName) {
if (path.isImportSpecifier() && isIdentifier(path.node.imported, {
name: importName
})) {
return true;
}
@@ -213,20 +231,24 @@ function isExecutionUncertainInList(paths, maxIndex) {
}
function _guessExecutionStatusRelativeTo(target) {
return _guessExecutionStatusRelativeToCached(this, target, new Map());
}
function _guessExecutionStatusRelativeToCached(base, target, cache) {
const funcParent = {
this: getOuterFunction(this),
this: getOuterFunction(base),
target: getOuterFunction(target)
};
if (funcParent.target.node !== funcParent.this.node) {
return this._guessExecutionStatusRelativeToDifferentFunctions(funcParent.target);
return _guessExecutionStatusRelativeToDifferentFunctionsCached(base, funcParent.target, cache);
}
const paths = {
target: target.getAncestry(),
this: this.getAncestry()
this: base.getAncestry()
};
if (paths.target.indexOf(this) >= 0) return "after";
if (paths.target.indexOf(base) >= 0) return "after";
if (paths.this.indexOf(target) >= 0) return "before";
let commonPath;
const commonIndex = {
@@ -262,7 +284,7 @@ function _guessExecutionStatusRelativeTo(target) {
return divergence.target.key > divergence.this.key ? "before" : "after";
}
const keys = t.VISITOR_KEYS[commonPath.type];
const keys = VISITOR_KEYS[commonPath.type];
const keyPosition = {
this: keys.indexOf(divergence.this.parentKey),
target: keys.indexOf(divergence.target.parentKey)
@@ -270,9 +292,9 @@ function _guessExecutionStatusRelativeTo(target) {
return keyPosition.target > keyPosition.this ? "before" : "after";
}
const executionOrderCheckedNodes = new WeakSet();
const executionOrderCheckedNodes = new Set();
function _guessExecutionStatusRelativeToDifferentFunctions(target) {
function _guessExecutionStatusRelativeToDifferentFunctionsInternal(base, target, cache) {
if (!target.isFunctionDeclaration() || target.parentPath.isExportDeclaration()) {
return "unknown";
}
@@ -293,20 +315,37 @@ function _guessExecutionStatusRelativeToDifferentFunctions(target) {
if (executionOrderCheckedNodes.has(path.node)) continue;
executionOrderCheckedNodes.add(path.node);
const status = this._guessExecutionStatusRelativeTo(path);
try {
const status = _guessExecutionStatusRelativeToCached(base, path, cache);
executionOrderCheckedNodes.delete(path.node);
if (allStatus && allStatus !== status) {
return "unknown";
} else {
allStatus = status;
if (allStatus && allStatus !== status) {
return "unknown";
} else {
allStatus = status;
}
} finally {
executionOrderCheckedNodes.delete(path.node);
}
}
return allStatus;
}
function _guessExecutionStatusRelativeToDifferentFunctionsCached(base, target, cache) {
let nodeMap = cache.get(base.node);
if (!nodeMap) {
cache.set(base.node, nodeMap = new Map());
} else if (nodeMap.has(target.node)) {
return nodeMap.get(target.node);
}
const result = _guessExecutionStatusRelativeToDifferentFunctionsInternal(base, target, cache);
nodeMap.set(target.node, result);
return result;
}
function resolve(dangerous, resolved) {
return this._resolve(dangerous, resolved) || this;
}
@@ -335,7 +374,7 @@ function _resolve(dangerous, resolved) {
return this.get("expression").resolve(dangerous, resolved);
} else if (dangerous && this.isMemberExpression()) {
const targetKey = this.toComputedKey();
if (!t.isLiteral(targetKey)) return;
if (!isLiteral(targetKey)) return;
const targetName = targetKey.value;
const target = this.get("object").resolve(dangerous, resolved);
@@ -381,7 +420,7 @@ function isConstantExpression() {
}
if (this.isUnaryExpression()) {
if (this.get("operator").node !== "void") {
if (this.node.operator !== "void") {
return false;
}
@@ -408,12 +447,9 @@ function isInStrictMode() {
return false;
}
let {
node
} = path;
if (path.isFunction()) node = node.body;
const body = path.isFunction() ? path.node.body : path.node;
for (const directive of node.directives) {
for (const directive of body.directives) {
if (directive.value.value === "use strict") {
return true;
}
+23 -10
View File
@@ -5,15 +5,21 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _t = require("@babel/types");
var _t2 = _t;
const {
react
} = _t;
const {
cloneNode,
jsxExpressionContainer,
variableDeclaration,
variableDeclarator
} = _t2;
const referenceVisitor = {
ReferencedIdentifier(path, state) {
if (path.isJSXIdentifier() && t.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) {
if (path.isJSXIdentifier() && react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) {
return;
}
@@ -48,6 +54,13 @@ const referenceVisitor = {
class PathHoister {
constructor(path, scope) {
this.breakOnScopePaths = void 0;
this.bindings = void 0;
this.mutableBinding = void 0;
this.scopes = void 0;
this.scope = void 0;
this.path = void 0;
this.attachAfter = void 0;
this.breakOnScopePaths = [];
this.bindings = {};
this.mutableBinding = false;
@@ -175,16 +188,16 @@ class PathHoister {
if (!attachTo) return;
if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return;
let uid = attachTo.scope.generateUidIdentifier("ref");
const declarator = t.variableDeclarator(uid, this.path.node);
const declarator = variableDeclarator(uid, this.path.node);
const insertFn = this.attachAfter ? "insertAfter" : "insertBefore";
const [attached] = attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]);
const [attached] = attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : variableDeclaration("var", [declarator])]);
const parent = this.path.parentPath;
if (parent.isJSXElement() && this.path.container === parent.node.children) {
uid = t.JSXExpressionContainer(uid);
uid = jsxExpressionContainer(uid);
}
this.path.replaceWith(t.cloneNode(uid));
this.path.replaceWith(cloneNode(uid));
return attachTo.isVariableDeclarator() ? attached.get("init") : attached.get("declarations.0.init");
}
+3
View File
@@ -4,6 +4,9 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hooks = void 0;
var _ = require("..");
const hooks = [function (self, parent) {
const removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement();
+47 -27
View File
@@ -3,14 +3,34 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ForAwaitStatement = exports.NumericLiteralTypeAnnotation = exports.ExistentialTypeParam = exports.SpreadProperty = exports.RestProperty = exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = void 0;
exports.Var = exports.User = exports.Statement = exports.SpreadProperty = exports.Scope = exports.RestProperty = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = exports.Referenced = exports.Pure = exports.NumericLiteralTypeAnnotation = exports.Generated = exports.ForAwaitStatement = exports.Flow = exports.Expression = exports.ExistentialTypeParam = exports.BlockScoped = exports.BindingIdentifier = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _t = require("@babel/types");
const {
isBinding,
isBlockScoped,
isExportDeclaration,
isExpression,
isFlow,
isForStatement,
isForXStatement,
isIdentifier,
isImportDeclaration,
isImportSpecifier,
isJSXIdentifier,
isJSXMemberExpression,
isMemberExpression,
isReferenced,
isScope,
isStatement,
isVar,
isVariableDeclaration,
react
} = _t;
const {
isCompatTag
} = react;
const ReferencedIdentifier = {
types: ["Identifier", "JSXIdentifier"],
@@ -20,15 +40,15 @@ const ReferencedIdentifier = {
parent
} = path;
if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) {
if (t.isJSXIdentifier(node, opts)) {
if (t.react.isCompatTag(node.name)) return false;
if (!isIdentifier(node, opts) && !isJSXMemberExpression(parent, opts)) {
if (isJSXIdentifier(node, opts)) {
if (isCompatTag(node.name)) return false;
} else {
return false;
}
}
return t.isReferenced(node, parent, path.parentPath.parent);
return isReferenced(node, parent, path.parentPath.parent);
}
};
@@ -40,7 +60,7 @@ const ReferencedMemberExpression = {
node,
parent
}) {
return t.isMemberExpression(node) && t.isReferenced(node, parent);
return isMemberExpression(node) && isReferenced(node, parent);
}
};
@@ -54,7 +74,7 @@ const BindingIdentifier = {
parent
} = path;
const grandparent = path.parentPath.parent;
return t.isIdentifier(node) && t.isBinding(node, parent, grandparent);
return isIdentifier(node) && isBinding(node, parent, grandparent);
}
};
@@ -66,12 +86,12 @@ const Statement = {
node,
parent
}) {
if (t.isStatement(node)) {
if (t.isVariableDeclaration(node)) {
if (t.isForXStatement(parent, {
if (isStatement(node)) {
if (isVariableDeclaration(node)) {
if (isForXStatement(parent, {
left: node
})) return false;
if (t.isForStatement(parent, {
if (isForStatement(parent, {
init: node
})) return false;
}
@@ -91,7 +111,7 @@ const Expression = {
if (path.isIdentifier()) {
return path.isReferencedIdentifier();
} else {
return t.isExpression(path.node);
return isExpression(path.node);
}
}
@@ -101,21 +121,21 @@ const Scope = {
types: ["Scopable", "Pattern"],
checkPath(path) {
return t.isScope(path.node, path.parent);
return isScope(path.node, path.parent);
}
};
exports.Scope = Scope;
const Referenced = {
checkPath(path) {
return t.isReferenced(path.node, path.parent);
return isReferenced(path.node, path.parent);
}
};
exports.Referenced = Referenced;
const BlockScoped = {
checkPath(path) {
return t.isBlockScoped(path.node);
return isBlockScoped(path.node);
}
};
@@ -124,7 +144,7 @@ const Var = {
types: ["VariableDeclaration"],
checkPath(path) {
return t.isVar(path.node);
return isVar(path.node);
}
};
@@ -144,8 +164,8 @@ const Generated = {
};
exports.Generated = Generated;
const Pure = {
checkPath(path, opts) {
return path.scope.isPure(path.node, opts);
checkPath(path, constantsOnly) {
return path.scope.isPure(path.node, constantsOnly);
}
};
@@ -156,13 +176,13 @@ const Flow = {
checkPath({
node
}) {
if (t.isFlow(node)) {
if (isFlow(node)) {
return true;
} else if (t.isImportDeclaration(node)) {
} else if (isImportDeclaration(node)) {
return node.importKind === "type" || node.importKind === "typeof";
} else if (t.isExportDeclaration(node)) {
} else if (isExportDeclaration(node)) {
return node.exportKind === "type";
} else if (t.isImportSpecifier(node)) {
} else if (isImportSpecifier(node)) {
return node.importKind === "type" || node.importKind === "typeof";
} else {
return false;
+92 -39
View File
@@ -3,35 +3,47 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.insertBefore = insertBefore;
exports._containerInsert = _containerInsert;
exports._containerInsertBefore = _containerInsertBefore;
exports._containerInsertAfter = _containerInsertAfter;
exports.insertAfter = insertAfter;
exports.updateSiblingKeys = updateSiblingKeys;
exports._containerInsertBefore = _containerInsertBefore;
exports._verifyNodeList = _verifyNodeList;
exports.unshiftContainer = unshiftContainer;
exports.pushContainer = pushContainer;
exports.hoist = hoist;
exports.insertAfter = insertAfter;
exports.insertBefore = insertBefore;
exports.pushContainer = pushContainer;
exports.unshiftContainer = unshiftContainer;
exports.updateSiblingKeys = updateSiblingKeys;
var _cache = require("../cache");
var _hoister = _interopRequireDefault(require("./lib/hoister"));
var _hoister = require("./lib/hoister");
var _index = _interopRequireDefault(require("./index"));
var _index = require("./index");
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
const {
arrowFunctionExpression,
assertExpression,
assignmentExpression,
blockStatement,
callExpression,
cloneNode,
expressionStatement,
isAssignmentExpression,
isCallExpression,
isExpression,
isIdentifier,
isSequenceExpression,
isSuper,
thisExpression
} = _t;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function insertBefore(nodes) {
function insertBefore(nodes_) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
const nodes = this._verifyNodeList(nodes_);
const {
parentPath
} = this;
@@ -44,8 +56,9 @@ function insertBefore(nodes) {
} else if (Array.isArray(this.container)) {
return this._containerInsertBefore(nodes);
} else if (this.isStatementOrBlock()) {
const shouldInsertCurrentNode = this.node && (!this.isExpressionStatement() || this.node.expression != null);
this.replaceWith(t.blockStatement(shouldInsertCurrentNode ? [this.node] : []));
const node = this.node;
const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));
return this.unshiftContainer("body", nodes);
} else {
throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?");
@@ -89,42 +102,83 @@ function _containerInsertAfter(nodes) {
return this._containerInsert(this.key + 1, nodes);
}
function insertAfter(nodes) {
const last = arr => arr[arr.length - 1];
function isHiddenInSequenceExpression(path) {
return isSequenceExpression(path.parent) && (last(path.parent.expressions) !== path.node || isHiddenInSequenceExpression(path.parentPath));
}
function isAlmostConstantAssignment(node, scope) {
if (!isAssignmentExpression(node) || !isIdentifier(node.left)) {
return false;
}
const blockScope = scope.getBlockParent();
return blockScope.hasOwnBinding(node.left.name) && blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1;
}
function insertAfter(nodes_) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
if (this.isSequenceExpression()) {
return last(this.get("expressions")).insertAfter(nodes_);
}
const nodes = this._verifyNodeList(nodes_);
const {
parentPath
} = this;
if (parentPath.isExpressionStatement() || parentPath.isLabeledStatement() || parentPath.isExportNamedDeclaration() || parentPath.isExportDefaultDeclaration() && this.isDeclaration()) {
return parentPath.insertAfter(nodes.map(node => {
return t.isExpression(node) ? t.expressionStatement(node) : node;
return isExpression(node) ? expressionStatement(node) : node;
}));
} else if (this.isNodeType("Expression") && !this.isJSXElement() && !parentPath.isJSXElement() || parentPath.isForStatement() && this.key === "init") {
if (this.node) {
const node = this.node;
let {
scope
} = this;
if (parentPath.isMethod({
computed: true,
key: this.node
})) {
scope = scope.parent;
if (scope.path.isPattern()) {
assertExpression(node);
this.replaceWith(callExpression(arrowFunctionExpression([], node), []));
this.get("callee.body").insertAfter(nodes);
return [this];
}
const temp = scope.generateDeclaredUidIdentifier();
nodes.unshift(t.expressionStatement(t.assignmentExpression("=", t.cloneNode(temp), this.node)));
nodes.push(t.expressionStatement(t.cloneNode(temp)));
if (isHiddenInSequenceExpression(this)) {
nodes.unshift(node);
} else if (isCallExpression(node) && isSuper(node.callee)) {
nodes.unshift(node);
nodes.push(thisExpression());
} else if (isAlmostConstantAssignment(node, scope)) {
nodes.unshift(node);
nodes.push(cloneNode(node.left));
} else if (scope.isPure(node, true)) {
nodes.push(node);
} else {
if (parentPath.isMethod({
computed: true,
key: node
})) {
scope = scope.parent;
}
const temp = scope.generateDeclaredUidIdentifier();
nodes.unshift(expressionStatement(assignmentExpression("=", cloneNode(temp), node)));
nodes.push(expressionStatement(cloneNode(temp)));
}
}
return this.replaceExpressionWithStatements(nodes);
} else if (Array.isArray(this.container)) {
return this._containerInsertAfter(nodes);
} else if (this.isStatementOrBlock()) {
const shouldInsertCurrentNode = this.node && (!this.isExpressionStatement() || this.node.expression != null);
this.replaceWith(t.blockStatement(shouldInsertCurrentNode ? [this.node] : []));
const node = this.node;
const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));
return this.pushContainer("body", nodes);
} else {
throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?");
@@ -136,9 +190,7 @@ function updateSiblingKeys(fromIndex, incrementBy) {
const paths = _cache.path.get(this.parent);
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
for (const [, path] of paths) {
if (path.key >= fromIndex) {
path.key += incrementBy;
}
@@ -150,7 +202,7 @@ function _verifyNodeList(nodes) {
return [];
}
if (nodes.constructor !== Array) {
if (!Array.isArray(nodes)) {
nodes = [nodes];
}
@@ -188,7 +240,7 @@ function unshiftContainer(listKey, nodes) {
container: this.node[listKey],
listKey,
key: 0
});
}).setContext(this.context);
return path._containerInsertBefore(nodes);
}
@@ -196,7 +248,8 @@ function unshiftContainer(listKey, nodes) {
function pushContainer(listKey, nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
const verifiedNodes = this._verifyNodeList(nodes);
const container = this.node[listKey];
const path = _index.default.get({
@@ -205,9 +258,9 @@ function pushContainer(listKey, nodes) {
container: container,
listKey,
key: container.length
});
}).setContext(this.context);
return path.replaceWithMultiple(nodes);
return path.replaceWithMultiple(verifiedNodes);
}
function hoist(scope = this.scope) {
+9 -6
View File
@@ -3,15 +3,17 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.remove = remove;
exports._removeFromScope = _removeFromScope;
exports._callRemovalHooks = _callRemovalHooks;
exports._remove = _remove;
exports._markRemoved = _markRemoved;
exports._assertUnremoved = _assertUnremoved;
exports._callRemovalHooks = _callRemovalHooks;
exports._markRemoved = _markRemoved;
exports._remove = _remove;
exports._removeFromScope = _removeFromScope;
exports.remove = remove;
var _removalHooks = require("./lib/removal-hooks");
var _cache = require("../cache");
var _index = require("./index");
function remove() {
@@ -21,7 +23,7 @@ function remove() {
this.resync();
if (!((_this$opts = this.opts) == null ? void 0 : _this$opts.noScope)) {
if (!((_this$opts = this.opts) != null && _this$opts.noScope)) {
this._removeFromScope();
}
@@ -60,6 +62,7 @@ function _remove() {
function _markRemoved() {
this._traverseFlags |= _index.SHOULD_SKIP | _index.REMOVED;
if (this.parent) _cache.path.get(this.parent).delete(this.node);
this.node = null;
}
+87 -72
View File
@@ -3,62 +3,58 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.replaceWithMultiple = replaceWithMultiple;
exports.replaceWithSourceString = replaceWithSourceString;
exports.replaceWith = replaceWith;
exports._replaceWith = _replaceWith;
exports.replaceExpressionWithStatements = replaceExpressionWithStatements;
exports.replaceInline = replaceInline;
exports.replaceWith = replaceWith;
exports.replaceWithMultiple = replaceWithMultiple;
exports.replaceWithSourceString = replaceWithSourceString;
var _codeFrame = require("@babel/code-frame");
var _index = _interopRequireDefault(require("../index"));
var _index = require("../index");
var _index2 = _interopRequireDefault(require("./index"));
var _index2 = require("./index");
var _cache = require("../cache");
var _parser = require("@babel/parser");
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
var _helperHoistVariables = require("@babel/helper-hoist-variables");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const hoistVariablesVisitor = {
Function(path) {
path.skip();
},
VariableDeclaration(path) {
if (path.node.kind !== "var") return;
const bindings = path.getBindingIdentifiers();
for (const key of Object.keys(bindings)) {
path.scope.push({
id: bindings[key]
});
}
const exprs = [];
for (const declar of path.node.declarations) {
if (declar.init) {
exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init)));
}
}
path.replaceWithMultiple(exprs);
}
};
const {
FUNCTION_TYPES,
arrowFunctionExpression,
assignmentExpression,
awaitExpression,
blockStatement,
callExpression,
cloneNode,
expressionStatement,
identifier,
inheritLeadingComments,
inheritTrailingComments,
inheritsComments,
isExpression,
isProgram,
isStatement,
removeComments,
returnStatement,
toSequenceExpression,
validate,
yieldExpression
} = _t;
function replaceWithMultiple(nodes) {
var _pathCache$get;
this.resync();
nodes = this._verifyNodeList(nodes);
t.inheritLeadingComments(nodes[0], this.node);
t.inheritTrailingComments(nodes[nodes.length - 1], this.node);
inheritLeadingComments(nodes[0], this.node);
inheritTrailingComments(nodes[nodes.length - 1], this.node);
(_pathCache$get = _cache.path.get(this.parent)) == null ? void 0 : _pathCache$get.delete(this.node);
this.node = this.container[this.key] = null;
const paths = this.insertAfter(nodes);
@@ -73,10 +69,11 @@ function replaceWithMultiple(nodes) {
function replaceWithSourceString(replacement) {
this.resync();
let ast;
try {
replacement = `(${replacement})`;
replacement = (0, _parser.parse)(replacement);
ast = (0, _parser.parse)(replacement);
} catch (err) {
const loc = err.loc;
@@ -93,23 +90,21 @@ function replaceWithSourceString(replacement) {
throw err;
}
replacement = replacement.program.body[0].expression;
const expressionAST = ast.program.body[0].expression;
_index.default.removeProperties(replacement);
_index.default.removeProperties(expressionAST);
return this.replaceWith(replacement);
return this.replaceWith(expressionAST);
}
function replaceWith(replacement) {
function replaceWith(replacementPath) {
this.resync();
if (this.removed) {
throw new Error("You can't replace this node, we've already removed it");
}
if (replacement instanceof _index2.default) {
replacement = replacement.node;
}
let replacement = replacementPath instanceof _index2.default ? replacementPath.node : replacementPath;
if (!replacement) {
throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");
@@ -119,7 +114,7 @@ function replaceWith(replacement) {
return [this];
}
if (this.isProgram() && !t.isProgram(replacement)) {
if (this.isProgram() && !isProgram(replacement)) {
throw new Error("You can only replace a Program root node with another Program node");
}
@@ -133,14 +128,14 @@ function replaceWith(replacement) {
let nodePath = "";
if (this.isNodeType("Statement") && t.isExpression(replacement)) {
if (this.isNodeType("Statement") && isExpression(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) {
replacement = t.expressionStatement(replacement);
replacement = expressionStatement(replacement);
nodePath = "expression";
}
}
if (this.isNodeType("Expression") && t.isStatement(replacement)) {
if (this.isNodeType("Expression") && isStatement(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) {
return this.replaceExpressionWithStatements([replacement]);
}
@@ -149,8 +144,8 @@ function replaceWith(replacement) {
const oldNode = this.node;
if (oldNode) {
t.inheritsComments(replacement, oldNode);
t.removeComments(oldNode);
inheritsComments(replacement, oldNode);
removeComments(oldNode);
}
this._replaceWith(replacement);
@@ -162,33 +157,42 @@ function replaceWith(replacement) {
}
function _replaceWith(node) {
var _pathCache$get2;
if (!this.container) {
throw new ReferenceError("Container is falsy");
}
if (this.inList) {
t.validate(this.parent, this.key, [node]);
validate(this.parent, this.key, [node]);
} else {
t.validate(this.parent, this.key, node);
validate(this.parent, this.key, node);
}
this.debug(`Replace with ${node == null ? void 0 : node.type}`);
(_pathCache$get2 = _cache.path.get(this.parent)) == null ? void 0 : _pathCache$get2.set(node, this).delete(this.node);
this.node = this.container[this.key] = node;
}
function replaceExpressionWithStatements(nodes) {
this.resync();
const toSequenceExpression = t.toSequenceExpression(nodes, this.scope);
const nodesAsSequenceExpression = toSequenceExpression(nodes, this.scope);
if (toSequenceExpression) {
return this.replaceWith(toSequenceExpression)[0].get("expressions");
if (nodesAsSequenceExpression) {
return this.replaceWith(nodesAsSequenceExpression)[0].get("expressions");
}
const functionParent = this.getFunctionParent();
const isParentAsync = functionParent == null ? void 0 : functionParent.is("async");
const container = t.arrowFunctionExpression([], t.blockStatement(nodes));
this.replaceWith(t.callExpression(container, []));
this.traverse(hoistVariablesVisitor);
const isParentGenerator = functionParent == null ? void 0 : functionParent.is("generator");
const container = arrowFunctionExpression([], blockStatement(nodes));
this.replaceWith(callExpression(container, []));
const callee = this.get("callee");
(0, _helperHoistVariables.default)(callee.get("body"), id => {
this.scope.push({
id
});
}, "var");
const completionRecords = this.get("callee").getCompletionRecords();
for (const path of completionRecords) {
@@ -199,29 +203,40 @@ function replaceExpressionWithStatements(nodes) {
let uid = loop.getData("expressionReplacementReturnUid");
if (!uid) {
const callee = this.get("callee");
uid = callee.scope.generateDeclaredUidIdentifier("ret");
callee.get("body").pushContainer("body", t.returnStatement(t.cloneNode(uid)));
callee.get("body").pushContainer("body", returnStatement(cloneNode(uid)));
loop.setData("expressionReplacementReturnUid", uid);
} else {
uid = t.identifier(uid.name);
uid = identifier(uid.name);
}
path.get("expression").replaceWith(t.assignmentExpression("=", t.cloneNode(uid), path.node.expression));
path.get("expression").replaceWith(assignmentExpression("=", cloneNode(uid), path.node.expression));
} else {
path.replaceWith(t.returnStatement(path.node.expression));
path.replaceWith(returnStatement(path.node.expression));
}
}
const callee = this.get("callee");
callee.arrowFunctionToExpression();
const newCallee = callee;
if (isParentAsync && _index.default.hasType(this.get("callee.body").node, "AwaitExpression", t.FUNCTION_TYPES)) {
callee.set("async", true);
this.replaceWith(t.awaitExpression(this.node));
const needToAwaitFunction = isParentAsync && _index.default.hasType(this.get("callee.body").node, "AwaitExpression", FUNCTION_TYPES);
const needToYieldFunction = isParentGenerator && _index.default.hasType(this.get("callee.body").node, "YieldExpression", FUNCTION_TYPES);
if (needToAwaitFunction) {
newCallee.set("async", true);
if (!needToYieldFunction) {
this.replaceWith(awaitExpression(this.node));
}
}
return callee.get("body.body");
if (needToYieldFunction) {
newCallee.set("generator", true);
this.replaceWith(yieldExpression(this.node, true));
}
return newCallee.get("body.body");
}
function replaceInline(nodes) {