Skip to content

Commit

Permalink
Make NodePath<T | U> distributive (#16439)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo authored Apr 21, 2024
1 parent a8994f8 commit 4d8b2d0
Show file tree
Hide file tree
Showing 35 changed files with 1,113 additions and 1,137 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1876,10 +1876,8 @@ function transformClass(

// update originalClassPath according to the new AST
originalClassPath = (
newPath.get("callee").get("body") as NodePath<t.ClassBody>
)
.get("body")[0]
.get("key");
newPath.get("callee").get("body") as NodePath<t.Class>
).get("body.0.key");
}
}
if (!classInitInjected && classInitCall) {
Expand Down Expand Up @@ -2252,11 +2250,11 @@ function NamedEvaluationVisitoryFactory(
// the object properties under object patterns
ObjectExpression(path, state) {
for (const propertyPath of path.get("properties")) {
if (!propertyPath.isObjectProperty()) continue;
const { node } = propertyPath;
if (node.type !== "ObjectProperty") continue;
const id = node.key;
const initializer = skipTransparentExprWrappers(
propertyPath.get("value"),
propertyPath.get("value") as NodePath<t.Expression>,
);
if (isAnonymous(initializer)) {
if (!node.computed) {
Expand All @@ -2274,7 +2272,7 @@ function NamedEvaluationVisitoryFactory(
}
} else {
const ref = handleComputedProperty(
propertyPath as NodePath<t.ObjectProperty>,
propertyPath,
// The key of a computed object property must not be a private name
id as t.Expression,
state,
Expand Down
14 changes: 1 addition & 13 deletions packages/babel-helper-create-class-features-plugin/src/fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1593,7 +1593,7 @@ export function buildFieldsInitNodes(
// this maybe a bug for ts
switch (true) {
case isStaticBlock: {
const blockBody = (prop.node as t.StaticBlock).body;
const blockBody = prop.node.body;
// We special-case the single expression case to avoid the iife, since
// it's common.
if (blockBody.length === 1 && t.isExpressionStatement(blockBody[0])) {
Expand Down Expand Up @@ -1640,16 +1640,13 @@ export function buildFieldsInitNodes(
// It might still be possible to a computed static fields whose resulting
// key is "name" or "length", but the assumption is telling us that it's
// not going to happen.
// @ts-expect-error checked in switch
if (!isNameOrLength(prop.node)) {
// @ts-expect-error checked in switch
staticNodes.push(buildPublicFieldInitLoose(t.cloneNode(ref), prop));
break;
}
// falls through
case isStatic && isPublic && isField && !setPublicClassFields:
staticNodes.push(
// @ts-expect-error checked in switch
buildPublicFieldInitSpec(t.cloneNode(ref), prop, file),
);
break;
Expand Down Expand Up @@ -1681,15 +1678,13 @@ export function buildFieldsInitNodes(
instanceNodes.unshift(
buildPrivateMethodInitLoose(
t.thisExpression(),
// @ts-expect-error checked in switch
prop,
privateNamesMap,
),
);
pureStaticNodes.push(
buildPrivateMethodDeclaration(
file,
// @ts-expect-error checked in switch
prop,
privateNamesMap,
privateFieldsAsSymbolsOrProperties,
Expand All @@ -1703,7 +1698,6 @@ export function buildFieldsInitNodes(
instanceNodes.unshift(
buildPrivateInstanceMethodInitSpec(
t.thisExpression(),
// @ts-expect-error checked in switch
prop,
privateNamesMap,
file,
Expand All @@ -1712,7 +1706,6 @@ export function buildFieldsInitNodes(
pureStaticNodes.push(
buildPrivateMethodDeclaration(
file,
// @ts-expect-error checked in switch
prop,
privateNamesMap,
privateFieldsAsSymbolsOrProperties,
Expand All @@ -1732,7 +1725,6 @@ export function buildFieldsInitNodes(
pureStaticNodes.push(
buildPrivateMethodDeclaration(
file,
// @ts-expect-error checked in switch
prop,
privateNamesMap,
privateFieldsAsSymbolsOrProperties,
Expand All @@ -1746,7 +1738,6 @@ export function buildFieldsInitNodes(
staticNodes.unshift(
buildPrivateStaticMethodInitLoose(
t.cloneNode(ref),
// @ts-expect-error checked in switch
prop,
file,
privateNamesMap,
Expand All @@ -1755,21 +1746,18 @@ export function buildFieldsInitNodes(
pureStaticNodes.push(
buildPrivateMethodDeclaration(
file,
// @ts-expect-error checked in switch
prop,
privateNamesMap,
privateFieldsAsSymbolsOrProperties,
),
);
break;
case isInstance && isPublic && isField && setPublicClassFields:
// @ts-expect-error checked in switch
instanceNodes.push(buildPublicFieldInitLoose(t.thisExpression(), prop));
break;
case isInstance && isPublic && isField && !setPublicClassFields:
lastInstanceNodeReturnsThis = true;
instanceNodes.push(
// @ts-expect-error checked in switch
buildPublicFieldInitSpec(t.thisExpression(), prop, file),
);
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ export function createClassFeaturePlugin({
const innerBinding = path.node.id;
let ref: t.Identifier | null;
if (!innerBinding || !pathIsClassDeclaration) {
nameFunction(path);
nameFunction(path as NodePath<t.ClassExpression>);
ref = path.scope.generateUidIdentifier(innerBinding?.name || "Class");
}
const classRefForDefine = ref ?? t.cloneNode(innerBinding);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,12 +215,9 @@ const handle = {
);
}

// @ts-expect-error isOptionalMemberExpression does not work with NodePath union
const startingNode = startingOptional.isOptionalMemberExpression()
? // @ts-expect-error isOptionalMemberExpression does not work with NodePath union
startingOptional.node.object
: // @ts-expect-error isOptionalMemberExpression does not work with NodePath union
startingOptional.node.callee;
? startingOptional.node.object
: startingOptional.node.callee;
const baseNeedsMemoised = scope.maybeGenerateMemoised(startingNode);
const baseRef = baseNeedsMemoised ?? startingNode;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,6 @@ function getLocalExportMetadata(
declaration.isFunctionDeclaration() ||
declaration.isClassDeclaration()
) {
// @ts-expect-error todo(flow->ts): improve babel-types
getLocalMetadata(declaration.get("id")).names.push("default");
} else {
// These should have been removed by the nameAnonymousExports() call.
Expand Down Expand Up @@ -594,9 +593,7 @@ function removeImportExportDeclarations(programPath: NodePath<t.Program>) {
) {
// @ts-expect-error todo(flow->ts): avoid mutations
declaration._blockHoist = child.node._blockHoist;
child.replaceWith(
declaration as NodePath<t.FunctionDeclaration | t.ClassDeclaration>,
);
child.replaceWith(declaration);
} else {
// These should have been removed by the nameAnonymousExports() call.
throw declaration.buildCodeFrameError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ const rewriteReferencesVisitor: Visitor<RewriteReferencesVisitorState> = {
}

path.ensureBlock();
const bodyPath = path.get("body");
const bodyPath = path.get("body") as NodePath<t.BlockStatement>;

const newLoopId = scope.generateUidIdentifierBasedOnNode(left);
path
Expand Down
5 changes: 1 addition & 4 deletions packages/babel-helper-split-export-declaration/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,7 @@ export default function splitExportDeclaration(
}

return exportDeclaration;
} else if (
// @ts-expect-error TS can not narrow down to NodePath<t.ExportNamedDeclaration>
exportDeclaration.get("specifiers").length > 0
) {
} else if (exportDeclaration.get("specifiers").length > 0) {
throw new Error("It doesn't make sense to split exported specifiers.");
}

Expand Down
2 changes: 1 addition & 1 deletion packages/babel-helper-wrap-function/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ function plainFunction(
| t.FunctionExpression
| t.CallExpression;
} else {
node = path.node as t.FunctionDeclaration | t.FunctionExpression;
node = path.node;
}

const isDeclaration = isFunctionDeclaration(node);
Expand Down
3 changes: 1 addition & 2 deletions packages/babel-helpers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ function getHelperMetadata(file: File): HelperMetadata {
}
if (
child.get("specifiers").length !== 1 ||
// @ts-expect-error isImportDefaultSpecifier does not work with NodePath union
!child.get("specifiers.0").isImportDefaultSpecifier()
) {
throw child.buildCodeFrameError(
Expand Down Expand Up @@ -223,7 +222,7 @@ function permuteHelperAST(
exp.replaceWith(decl);
} else if (id.type === "MemberExpression") {
exportBindingAssignments.forEach(assignPath => {
const assign: NodePath<t.Expression> = path.get(assignPath);
const assign = path.get(assignPath) as NodePath<t.Expression>;
assign.replaceWith(assignmentExpression("=", id, assign.node));
});
exp.replaceWith(decl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ export default declare(({ types: t, traverse, assertVersion }) => {
elem.node.computed &&
containsClassExpression(elem.get("key"))
) {
wrap(elem.get("key"));
wrap(
// @ts-expect-error .key also includes t.PrivateName
elem.get("key") satisfies NodePath<t.Expression>,
);
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export default declare(api => {
continue;
}

let { node } = stmt;
let node: t.Statement | t.Declaration = stmt.node;
let shouldRemove = true;

if (stmt.isExportDefaultDeclaration()) {
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-plugin-transform-block-scoping/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export default declare((api, opts: Options) => {
if (needsBodyWrap) {
const varPath = wrapLoopBody(path, captured, updatedBindingsUsages);

if (headPath?.isVariableDeclaration<t.Node>()) {
if (headPath?.isVariableDeclaration()) {
// If we wrap the loop body, we transform the var
// declaration in the loop head now, to avoid
// invalid references that break other plugins:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ function disallowConstantViolations(
t.variableDeclarator(violation.scope.generateUidIdentifier(name)),
]),
);
violation.node.body.body.unshift(t.expressionStatement(throwNode));
(violation.node.body as t.BlockStatement).body.unshift(
t.expressionStatement(throwNode),
);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-plugin-transform-destructuring/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export default declare((api, options: Options) => {
]);

path.ensureBlock();
const statementBody = path.node.body.body;
const statementBody = (path.node.body as t.BlockStatement).body;
const nodes = [];
// todo: the completion of a for statement can only be observed from
// a do block (or eval that we don't support),
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-plugin-transform-destructuring/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function unshiftForXStatementBody(
// var a = 0;for (const { #x: x, [a++]: y } of z) { const a = 1; }
node.body = t.blockStatement([...newStatements, node.body]);
} else {
node.body.body.unshift(...newStatements);
(node.body as t.BlockStatement).body.unshift(...newStatements);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,10 @@ export default declare((api, opts: Options) => {
container.push(declar);
} else {
parentPath.ensureBlock();
parentPath.get("body").unshiftContainer("body", declar);
(parentPath.get("body") as NodePath<t.BlockStatement>).unshiftContainer(
"body",
declar,
);
}
paramPath.replaceWith(t.cloneNode(uid));
}
Expand Down Expand Up @@ -575,7 +578,7 @@ export default declare((api, opts: Options) => {
]);

path.ensureBlock();
const body = path.node.body;
const body = path.node.body as t.BlockStatement;

if (body.body.length === 0 && path.isCompletionRecord()) {
body.body.unshift(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ function needsMemoize(
) {
const { node } = optionalPath;
const childPath = skipTransparentExprWrappers(
// @ts-expect-error isOptionalMemberExpression does not work with NodePath union
optionalPath.isOptionalMemberExpression()
? optionalPath.get("object")
: optionalPath.get("callee"),
Expand Down Expand Up @@ -98,7 +97,6 @@ export function transformOptionalChain(
if (node.optional) {
optionals.push(node);
}
// @ts-expect-error isOptionalMemberExpression does not work with NodePath union
if (optionalPath.isOptionalMemberExpression()) {
// @ts-expect-error todo(flow->ts) avoid changing more type
optionalPath.node.type = "MemberExpression";
Expand Down
11 changes: 6 additions & 5 deletions packages/babel-plugin-transform-parameters/src/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,16 +153,17 @@ export default function convertFunctionParams(

// ensure it's a block, useful for arrow functions
path.ensureBlock();
const path2 = path as NodePath<typeof path.node & { body: t.BlockStatement }>;

const { async, generator } = node;
if (generator || state.needsOuterBinding || shadowedParams.size > 0) {
body.push(buildScopeIIFE(shadowedParams, path.node.body));
body.push(buildScopeIIFE(shadowedParams, path2.node.body));

path.set("body", t.blockStatement(body as t.Statement[]));

// We inject an arrow and then transform it to a normal function, to be
// sure that we correctly handle this and arguments.
const bodyPath = path.get("body.body");
const bodyPath = path2.get("body.body");
const arrowPath = bodyPath[bodyPath.length - 1].get(
"argument.callee",
) as NodePath<t.ArrowFunctionExpression>;
Expand All @@ -177,16 +178,16 @@ export default function convertFunctionParams(
node.async = false;
if (async) {
// If the default value of a parameter throws, it must reject asynchronously.
path.node.body = template.statement.ast`{
path2.node.body = template.statement.ast`{
try {
${path.node.body.body}
${path2.node.body.body}
} catch (e) {
return Promise.reject(e);
}
}` as t.BlockStatement;
}
} else {
path.get("body").unshiftContainer("body", body);
path2.get("body").unshiftContainer("body", body);
}

return true;
Expand Down
4 changes: 3 additions & 1 deletion packages/babel-plugin-transform-parameters/src/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,9 @@ export default function convertFunctionRest(path: NodePath<t.Function>) {
path.ensureBlock();
path.set(
"body",
t.blockStatement([buildScopeIIFE(shadowedParams, path.node.body)]),
t.blockStatement([
buildScopeIIFE(shadowedParams, path.node.body as t.BlockStatement),
]),
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export default declare((api, opt: Options) => {
}

function getWeakSetId<Ref extends t.Node>(
weakSets: WeakMap<Ref, t.Identifier>,
weakSets: WeakMap<t.Node, t.Identifier>,
outerClass: NodePath<t.Class>,
reference: NodePath<Ref>,
name = "",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ function getThisFunctionParent(
do {
const { path } = scope;
if (path.isFunctionParent() && !path.isArrowFunctionExpression()) {
// @ts-expect-error TS does not exclude ArrowFunctionExpression from FunctionParent
return path;
}
} while ((scope = scope.parent));
Expand Down
1 change: 0 additions & 1 deletion packages/babel-plugin-transform-typeof-symbol/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export default declare(api => {
let isUnderHelper = path.findParent(path => {
if (path.isFunction()) {
return (
// @ts-expect-error the access is coupled with the shape of typeof helper
path.get("body.directives.0")?.node.value.value ===
"@babel/helpers - typeof"
);
Expand Down
Loading

0 comments on commit 4d8b2d0

Please sign in to comment.