Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [unbound-method] report on destructuring in function parameters #8952

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
190 changes: 139 additions & 51 deletions packages/eslint-plugin/src/rules/unbound-method.ts
Expand Up @@ -7,7 +7,8 @@ import {
createRule,
getModifiers,
getParserServices,
isIdentifier,
isBuiltinSymbolLike,
isSymbolFromDefaultLibrary,
} from '../util';

//------------------------------------------------------------------------------
Expand Down Expand Up @@ -83,12 +84,6 @@ const isNotImported = (
);
};

const getNodeName = (node: TSESTree.Node): string | null =>
node.type === AST_NODE_TYPES.Identifier ? node.name : null;

const getMemberFullName = (node: TSESTree.MemberExpression): string =>
`${getNodeName(node.object)}.${getNodeName(node.property)}`;

const BASE_MESSAGE =
'Avoid referencing unbound methods which may cause unintentional scoping of `this`.';

Expand Down Expand Up @@ -135,9 +130,9 @@ export default createRule<Options, MessageIds>({
function checkIfMethodAndReport(
node: TSESTree.Node,
symbol: ts.Symbol | undefined,
): void {
): boolean {
if (!symbol) {
return;
return false;
}

const { dangerous, firstParamIsThis } = checkIfMethod(
Expand All @@ -152,69 +147,162 @@ export default createRule<Options, MessageIds>({
: 'unbound',
node,
});
return true;
}
return false;
}

return {
MemberExpression(node: TSESTree.MemberExpression): void {
if (isSafeUse(node)) {
return;
}

const objectSymbol = services.getSymbolAtLocation(node.object);
function isNativelyBound(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not super obvious how this function works. I cloned it down to play around with the tests, and I'm still not 100% sure, but my rough understanding is that the first part checks by identity whether something is a natively bound member, and the second part checks via the type system, in order to catch a more general set of cases where the builtin namespace objects are potentially renamed.

Could you add some comments to help the reader 🙏 ?

object: TSESTree.Node,
property: TSESTree.Node,
): boolean {
if (
object.type === AST_NODE_TYPES.Identifier &&
property.type === AST_NODE_TYPES.Identifier
) {
const objectSymbol = services.getSymbolAtLocation(object);
const notImported =
objectSymbol && isNotImported(objectSymbol, currentSourceFile);
auvred marked this conversation as resolved.
Show resolved Hide resolved

if (
objectSymbol &&
nativelyBoundMembers.has(getMemberFullName(node)) &&
isNotImported(objectSymbol, currentSourceFile)
notImported &&
nativelyBoundMembers.has(`${object.name}.${property.name}`)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const { log } = console;

In our current configuration, the console.log declarations are under @types/node. So if we remove this check, the rule will report on this case. Not sure what's the best solution there..

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you saying, you'd like to get rid of the first half of this function and only have the part after the return statement, but that that would cause bugs to do so? I'm not 100% following.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you'd like to get rid of the first half of this function and only have the part after the return statement, but that that would cause bugs to do so?

Yup, exactly!

I'd prefer to use only type checking here for obvious reasons, as it is more flexible and robust than just checking identifier names.

But this type checking-based approach works by checking whether a method is defined in the default library. This can be a problem for us, especially in the case of console methods.

Imagine the following situation:

// tsconfig.json
{
  "compilerOptions": {
    "lib": ["ESNext"],
    "types": ["node"]
  }
}
// index.ts
const { log } = console

The log method of the Console interface is defined in the node_modules/@types/node/console.d.ts, not in the default TypeScript library. Therefore, the rule will false-positively report on this destructuring because it knows that this method is defined outside the default lib.

) {
return true;
}
}

return (
isBuiltinSymbolLike(
services.program,
services.getTypeAtLocation(object),
[
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the difference between this array literal and the SUPPORTED_GLOBALS array? Do we need both? Perhaps giving it a good name will make it clear?

Thoughts?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need both?

I really don't know 🙁

For more reasoning on this, see #8952 (comment)

Perhaps giving it a good name will make it clear?

+1 👍 Will rename it

'NumberConstructor',
'Number',
'ObjectConstructor',
'Object',
'StringConstructor',
'String', // eslint-disable-line @typescript-eslint/internal/prefer-ast-types-enum
'SymbolConstructor',
'ArrayConstructor',
'Array',
'ProxyConstructor',
'DateConstructor',
'Date',
'Atomics',
'Math',
'JSON',
],
) &&
isSymbolFromDefaultLibrary(
services.program,
services.getTypeAtLocation(property).getSymbol(),
)
);
}

return {
MemberExpression(node: TSESTree.MemberExpression): void {
if (isSafeUse(node) || isNativelyBound(node.object, node.property)) {
return;
}

checkIfMethodAndReport(node, services.getSymbolAtLocation(node));
},
'VariableDeclarator, AssignmentExpression'(
node: TSESTree.AssignmentExpression | TSESTree.VariableDeclarator,
): void {
const [idNode, initNode] =
node.type === AST_NODE_TYPES.VariableDeclarator
? [node.id, node.init]
: [node.left, node.right];

if (initNode && idNode.type === AST_NODE_TYPES.ObjectPattern) {
const rightSymbol = services.getSymbolAtLocation(initNode);
const initTypes = services.getTypeAtLocation(initNode);

const notImported =
rightSymbol && isNotImported(rightSymbol, currentSourceFile);

idNode.properties.forEach(property => {
if (
property.type === AST_NODE_TYPES.Property &&
property.key.type === AST_NODE_TYPES.Identifier
) {
if (
notImported &&
isIdentifier(initNode) &&
nativelyBoundMembers.has(
`${initNode.name}.${property.key.name}`,
)
) {
return;
}
ObjectPattern(node): void {
if (isNodeInsideTypeDeclaration(node)) {
return;
}
let initNode: TSESTree.Node | null = null;
if (node.parent.type === AST_NODE_TYPES.VariableDeclarator) {
initNode = node.parent.init;
} else if (
node.parent.type === AST_NODE_TYPES.AssignmentPattern ||
node.parent.type === AST_NODE_TYPES.AssignmentExpression
) {
initNode = node.parent.right;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should there be some kind of assertion here to ensure that every way that ObjectPattern could occur is handled (especially in light of the bug that this PR fixes)? Relates to #6225

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interestingly, the introduction of the type checking actually supports unaccounted-for parents pretty well.

Check this out 😆

// should be invalid, passes (didn't in previous implementation)
function f({ evil: { nesting } } = { evil: { nesting: function () { } } }) {
}

// should also be invalid, fails (since it's _only_ looking at the type)
function g({ evil: { nesting } }: any = { evil: { nesting: function () { } } }) {
}

To be clear, I don't think you need to account for these crazy scenarios (or, even more heinous things like const [{ a }, { b }] = [{ a() {} }, { b: 'b' }]; in this PR. I am just pointing out that it's cool that you've incidentally added partial support for them!

There is one false positive regression introduced that I can think of, though....

// the possible assignments _are_ provably bound.
//  but the presence of the annotation causes `b` to flag as possibly unbound.
const { a: { b } = { b: () => { } } }: { a: { b(): void } } = { a: undefined }

but I really don't think it's a blocker granted how absurd it is.


checkIfMethodAndReport(
for (const property of node.properties) {
if (
property.type !== AST_NODE_TYPES.Property ||
property.key.type !== AST_NODE_TYPES.Identifier
) {
continue;
}

if (initNode) {
if (!isNativelyBound(initNode, property.key)) {
const reported = checkIfMethodAndReport(
property.key,
initTypes.getProperty(property.key.name),
services
.getTypeAtLocation(initNode)
.getProperty(property.key.name),
);
if (reported) {
continue;
}
// In assignment patterns, we should also check the type of
// Foo's nativelyBound method because initNode might be used as
// default value:
// function ({ nativelyBound }: Foo = NativeObject) {}
} else if (node.parent.type !== AST_NODE_TYPES.AssignmentPattern) {
continue;
}
}

for (const unionPart of tsutils.unionTypeParts(
services.getTypeAtLocation(node),
)) {
const propertyKey = property.key;
const reported = checkIfMethodAndReport(
propertyKey,
unionPart.getProperty(propertyKey.name),
);
if (reported) {
break;
}

if (!tsutils.isIntersectionType(unionPart)) {
continue;
}

for (const intersectionPart of tsutils.intersectionTypeParts(
unionPart,
)) {
const reported = checkIfMethodAndReport(
propertyKey,
intersectionPart.getProperty(propertyKey.name),
);
if (reported) {
break;
}
}
});
}
}
},
};
},
});

function isNodeInsideTypeDeclaration(node: TSESTree.Node): boolean {
let parent: TSESTree.Node | undefined = node;
while ((parent = parent.parent)) {
if (
(parent.type === AST_NODE_TYPES.ClassDeclaration && parent.declare) ||
parent.type === AST_NODE_TYPES.TSAbstractMethodDefinition ||
parent.type === AST_NODE_TYPES.TSDeclareFunction ||
parent.type === AST_NODE_TYPES.TSFunctionType ||
parent.type === AST_NODE_TYPES.TSInterfaceDeclaration ||
parent.type === AST_NODE_TYPES.TSTypeAliasDeclaration ||
(parent.type === AST_NODE_TYPES.VariableDeclaration && parent.declare)
) {
return true;
}
}
return false;
}

interface CheckMethodResult {
dangerous: boolean;
firstParamIsThis?: boolean;
Expand Down