Skip to content

chore(eslint-plugin): make utility for static member access #9836

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 15 additions & 15 deletions packages/eslint-plugin/src/rules/class-literal-property-style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { AST_NODE_TYPES } from '@typescript-eslint/utils';

import {
createRule,
getStaticMemberAccessValue,
getStaticStringValue,
isAssignee,
isFunction,
isStaticMemberAccessOfValue,
nullThrows,
} from '../util';

Expand Down Expand Up @@ -79,10 +81,6 @@ export default createRule<Options, MessageIds>({
create(context, [style]) {
const propertiesInfoStack: PropertiesInfo[] = [];

function getStringValue(node: TSESTree.Node): string {
return getStaticStringValue(node) ?? context.sourceCode.getText(node);
}

function enterClassBody(): void {
propertiesInfoStack.push({
properties: [],
Expand All @@ -102,8 +100,8 @@ export default createRule<Options, MessageIds>({
return;
}

const name = getStringValue(node.key);
if (excludeSet.has(name)) {
const name = getStaticMemberAccessValue(node, context);
if (name && excludeSet.has(name)) {
return;
}

Expand Down Expand Up @@ -167,15 +165,17 @@ export default createRule<Options, MessageIds>({
return;
}

const name = getStringValue(node.key);

const hasDuplicateKeySetter = node.parent.body.some(element => {
return (
element.type === AST_NODE_TYPES.MethodDefinition &&
element.kind === 'set' &&
getStringValue(element.key) === name
);
});
const name = getStaticMemberAccessValue(node, context);

const hasDuplicateKeySetter =
name &&
node.parent.body.some(element => {
return (
element.type === AST_NODE_TYPES.MethodDefinition &&
element.kind === 'set' &&
isStaticMemberAccessOfValue(element, context, name)
);
});
if (hasDuplicateKeySetter) {
return;
}
Expand Down
7 changes: 2 additions & 5 deletions packages/eslint-plugin/src/rules/class-methods-use-this.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
createRule,
getFunctionHeadLoc,
getFunctionNameWithKind,
getStaticStringValue,
getStaticMemberAccessValue,
} from '../util';

type Options = [
Expand Down Expand Up @@ -182,10 +182,7 @@ export default createRule<Options, MessageIds>({

const hashIfNeeded =
node.key.type === AST_NODE_TYPES.PrivateIdentifier ? '#' : '';
const name =
node.key.type === AST_NODE_TYPES.Literal
? getStaticStringValue(node.key)
: node.key.name || '';
const name = getStaticMemberAccessValue(node, context);

return !exceptMethods.has(hashIfNeeded + (name ?? ''));
}
Expand Down
22 changes: 6 additions & 16 deletions packages/eslint-plugin/src/rules/explicit-module-boundary-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { DefinitionType } from '@typescript-eslint/scope-manager';
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';

import { createRule, isFunction } from '../util';
import { createRule, isFunction, isStaticMemberAccessOfValue } from '../util';
import type {
FunctionExpression,
FunctionInfo,
Expand Down Expand Up @@ -268,21 +268,11 @@ export default createRule<Options, MessageIds>({
(node.type === AST_NODE_TYPES.Property && node.method) ||
node.type === AST_NODE_TYPES.PropertyDefinition
) {
if (
node.key.type === AST_NODE_TYPES.Literal &&
typeof node.key.value === 'string'
) {
return options.allowedNames.includes(node.key.value);
}
if (
node.key.type === AST_NODE_TYPES.TemplateLiteral &&
node.key.expressions.length === 0
) {
return options.allowedNames.includes(node.key.quasis[0].value.raw);
}
if (!node.computed && node.key.type === AST_NODE_TYPES.Identifier) {
return options.allowedNames.includes(node.key.name);
}
return isStaticMemberAccessOfValue(
node,
context,
...options.allowedNames,
);
}

return false;
Expand Down
84 changes: 29 additions & 55 deletions packages/eslint-plugin/src/rules/no-floating-promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
createRule,
getOperatorPrecedence,
getParserServices,
getStaticMemberAccessValue,
isBuiltinSymbolLike,
OperatorPrecedence,
readonlynessOptionsDefaults,
Expand Down Expand Up @@ -334,27 +335,38 @@ export default createRule<Options, MessageId>({
// If the outer expression is a call, a `.catch()` or `.then()` with
// rejection handler handles the promise.

const catchRejectionHandler = getRejectionHandlerFromCatchCall(node);
if (catchRejectionHandler) {
if (isValidRejectionHandler(catchRejectionHandler)) {
return { isUnhandled: false };
const { callee } = node;
if (callee.type === AST_NODE_TYPES.MemberExpression) {
const methodName = getStaticMemberAccessValue(callee, context);
const catchRejectionHandler =
methodName === 'catch' && node.arguments.length >= 1
? node.arguments[0]
: undefined;
if (catchRejectionHandler) {
if (isValidRejectionHandler(catchRejectionHandler)) {
return { isUnhandled: false };
}
return { isUnhandled: true, nonFunctionHandler: true };
}
return { isUnhandled: true, nonFunctionHandler: true };
}

const thenRejectionHandler = getRejectionHandlerFromThenCall(node);
if (thenRejectionHandler) {
if (isValidRejectionHandler(thenRejectionHandler)) {
return { isUnhandled: false };
const thenRejectionHandler =
methodName === 'then' && node.arguments.length >= 2
? node.arguments[1]
: undefined;
if (thenRejectionHandler) {
if (isValidRejectionHandler(thenRejectionHandler)) {
return { isUnhandled: false };
}
return { isUnhandled: true, nonFunctionHandler: true };
}
return { isUnhandled: true, nonFunctionHandler: true };
}

// `x.finally()` is transparent to resolution of the promise, so check `x`.
// ("object" in this context is the `x` in `x.finally()`)
const promiseFinallyObject = getObjectFromFinallyCall(node);
if (promiseFinallyObject) {
return isUnhandledPromise(checker, promiseFinallyObject);
// `x.finally()` is transparent to resolution of the promise, so check `x`.
// ("object" in this context is the `x` in `x.finally()`)
const promiseFinallyObject =
methodName === 'finally' ? callee.object : undefined;
if (promiseFinallyObject) {
return isUnhandledPromise(checker, promiseFinallyObject);
}
}

// All other cases are unhandled.
Expand Down Expand Up @@ -485,41 +497,3 @@ function isFunctionParam(
}
return false;
}

function getRejectionHandlerFromCatchCall(
expression: TSESTree.CallExpression,
): TSESTree.CallExpressionArgument | undefined {
if (
expression.callee.type === AST_NODE_TYPES.MemberExpression &&
expression.callee.property.type === AST_NODE_TYPES.Identifier &&
expression.callee.property.name === 'catch' &&
expression.arguments.length >= 1
) {
return expression.arguments[0];
}
return undefined;
}

function getRejectionHandlerFromThenCall(
expression: TSESTree.CallExpression,
): TSESTree.CallExpressionArgument | undefined {
if (
expression.callee.type === AST_NODE_TYPES.MemberExpression &&
expression.callee.property.type === AST_NODE_TYPES.Identifier &&
expression.callee.property.name === 'then' &&
expression.arguments.length >= 2
) {
return expression.arguments[1];
}
return undefined;
}

function getObjectFromFinallyCall(
expression: TSESTree.CallExpression,
): TSESTree.Expression | undefined {
return expression.callee.type === AST_NODE_TYPES.MemberExpression &&
expression.callee.property.type === AST_NODE_TYPES.Identifier &&
expression.callee.property.name === 'finally'
? expression.callee.object
: undefined;
}
29 changes: 4 additions & 25 deletions packages/eslint-plugin/src/rules/prefer-find.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type { RuleFix, Scope } from '@typescript-eslint/utils/ts-eslint';
import type { RuleFix } from '@typescript-eslint/utils/ts-eslint';
import * as tsutils from 'ts-api-utils';
import type { Type } from 'typescript';

Expand All @@ -9,6 +9,7 @@ import {
getConstrainedTypeAtLocation,
getParserServices,
getStaticValue,
isStaticMemberAccessOfValue,
nullThrows,
} from '../util';

Expand Down Expand Up @@ -89,7 +90,7 @@ export default createRule({
// or the optional chaining variants.
if (callee.type === AST_NODE_TYPES.MemberExpression) {
const isBracketSyntaxForFilter = callee.computed;
if (isStaticMemberAccessOfValue(callee, 'filter', globalScope)) {
if (isStaticMemberAccessOfValue(callee, context, 'filter')) {
const filterNode = callee.property;

const filteredObjectType = getConstrainedTypeAtLocation(
Expand Down Expand Up @@ -162,7 +163,7 @@ export default createRule({
if (
callee.type === AST_NODE_TYPES.MemberExpression &&
!callee.optional &&
isStaticMemberAccessOfValue(callee, 'at', globalScope)
isStaticMemberAccessOfValue(callee, context, 'at')
) {
const atArgument = getStaticValue(node.arguments[0], globalScope);
if (atArgument != null && isTreatedAsZeroByArrayAt(atArgument.value)) {
Expand Down Expand Up @@ -321,25 +322,3 @@ export default createRule({
};
},
});

/**
* Answers whether the member expression looks like
* `x.memberName`, `x['memberName']`,
* or even `const mn = 'memberName'; x[mn]` (or optional variants thereof).
*/
function isStaticMemberAccessOfValue(
memberExpression:
| TSESTree.MemberExpressionComputedName
| TSESTree.MemberExpressionNonComputedName,
value: string,
scope?: Scope.Scope,
): boolean {
if (!memberExpression.computed) {
// x.memberName case.
return memberExpression.property.name === value;
}

// x['memberName'] cases.
const staticValueResult = getStaticValue(memberExpression.property, scope);
return staticValueResult != null && value === staticValueResult.value;
}
8 changes: 6 additions & 2 deletions packages/eslint-plugin/src/rules/prefer-includes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
getConstrainedTypeAtLocation,
getParserServices,
getStaticValue,
isStaticMemberAccessOfValue,
} from '../util';

export default createRule({
Expand Down Expand Up @@ -146,6 +147,9 @@
node: TSESTree.MemberExpression,
allowFixing: boolean,
): void {
if (!isStaticMemberAccessOfValue(node, context, 'indexOf')) {
return;

Check warning on line 151 in packages/eslint-plugin/src/rules/prefer-includes.ts

View check run for this annotation

Codecov / codecov/patch

packages/eslint-plugin/src/rules/prefer-includes.ts#L151

Added line #L151 was not covered by tests
}
// Check if the comparison is equivalent to `includes()`.
const callNode = node.parent as TSESTree.CallExpression;
const compareNode = (
Expand Down Expand Up @@ -204,14 +208,14 @@

return {
// a.indexOf(b) !== 1
"BinaryExpression > CallExpression.left > MemberExpression.callee[property.name='indexOf'][computed=false]"(
'BinaryExpression > CallExpression.left > MemberExpression'(
node: TSESTree.MemberExpression,
): void {
checkArrayIndexOf(node, /* allowFixing */ true);
},

// a?.indexOf(b) !== 1
"BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name='indexOf'][computed=false]"(
'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression'(
node: TSESTree.MemberExpression,
): void {
checkArrayIndexOf(node, /* allowFixing */ false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
isPromiseConstructorLike,
isPromiseLike,
isReadonlyErrorLike,
isStaticMemberAccessOfValue,
} from '../util';

export type MessageIds = 'rejectAnError';
Expand Down Expand Up @@ -99,13 +100,8 @@ export default createRule<Options, MessageIds>({
return;
}

const rejectMethodCalled = callee.computed
? callee.property.type === AST_NODE_TYPES.Literal &&
callee.property.value === 'reject'
: callee.property.name === 'reject';

if (
!rejectMethodCalled ||
!isStaticMemberAccessOfValue(callee, context, 'reject') ||
!typeAtLocationIsLikePromise(callee.object)
) {
return;
Expand Down
21 changes: 2 additions & 19 deletions packages/eslint-plugin/src/rules/prefer-reduce-type-parameter.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,19 @@
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as tsutils from 'ts-api-utils';
import type * as ts from 'typescript';

import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
isStaticMemberAccessOfValue,
isTypeAssertion,
} from '../util';

type MemberExpressionWithCallExpressionParent = TSESTree.MemberExpression & {
parent: TSESTree.CallExpression;
};

const getMemberExpressionName = (
member: TSESTree.MemberExpression,
): string | null => {
if (!member.computed) {
return member.property.name;
}

if (
member.property.type === AST_NODE_TYPES.Literal &&
typeof member.property.value === 'string'
) {
return member.property.value;
}

return null;
};

export default createRule({
name: 'prefer-reduce-type-parameter',
meta: {
Expand Down Expand Up @@ -67,7 +50,7 @@ export default createRule({
'CallExpression > MemberExpression.callee'(
callee: MemberExpressionWithCallExpressionParent,
): void {
if (getMemberExpressionName(callee) !== 'reduce') {
if (!isStaticMemberAccessOfValue(callee, context, 'reduce')) {
return;
}

Expand Down
Loading
Loading