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 all 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
173 changes: 122 additions & 51 deletions packages/eslint-plugin/src/rules/unbound-method.ts
Original file line number Diff line number Diff line change
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,145 @@ 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 != null && isNotImported(objectSymbol, currentSourceFile);

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.

Copy link
Member

Choose a reason for hiding this comment

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

Hmm. I'm not sure I have enough knowledge to know what to do here. Maybe someone from @typescript-eslint/triage-team will have a suggestion?

Copy link
Member

Choose a reason for hiding this comment

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

Just to make sure I understand: we're saying that:

  1. console's log is a known exception defined in lib.dom.d.ts
  2. A log override is defined in @types/node'
  3. We'd like to still allow the exception for console's log, even though type info thinks it's a @types/node thing

...is that right?

) {
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;
}
kirkwaiblinger marked this conversation as resolved.
Show resolved Hide resolved

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 intersectionPart of tsutils
.unionTypeParts(services.getTypeAtLocation(node))
.flatMap(unionPart => tsutils.intersectionTypeParts(unionPart))) {
const reported = checkIfMethodAndReport(
property.key,
intersectionPart.getProperty(property.key.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