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

refactor: inline collectReferences utility into scopeHasLocalReference #1276

Merged
merged 3 commits into from Nov 4, 2022
Merged
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
72 changes: 25 additions & 47 deletions src/rules/utils/parseJestFnCall.ts
Expand Up @@ -514,42 +514,6 @@ const describePossibleImportDef = (def: TSESLint.Scope.Definition) => {
return null;
};

const collectReferences = (scope: TSESLint.Scope.Scope) => {
const locals = new Set();
const imports = new Map<string, ImportDetails>();
const unresolved = new Set();

let currentScope: TSESLint.Scope.Scope | null = scope;

while (currentScope !== null) {
for (const ref of currentScope.variables) {
if (ref.defs.length === 0) {
continue;
}

const def = ref.defs[ref.defs.length - 1];

const importDetails = describePossibleImportDef(def);

if (importDetails) {
imports.set(importDetails.local, importDetails);

continue;
}

locals.add(ref.name);
}

for (const ref of currentScope.through) {
unresolved.add(ref.identifier.name);
}

currentScope = currentScope.upper;
}

return { locals, imports, unresolved };
};

const resolveScope = (scope: TSESLint.Scope.Scope, identifier: string) => {
let currentScope: TSESLint.Scope.Scope | null = scope;

Expand Down Expand Up @@ -621,15 +585,29 @@ export const scopeHasLocalReference = (
scope: TSESLint.Scope.Scope,
referenceName: string,
) => {
const references = collectReferences(scope);

return (
// referenceName was found as a local variable or function declaration.
references.locals.has(referenceName) ||
// referenceName was found as an imported identifier
references.imports.has(referenceName) ||
// referenceName was not found as an unresolved reference,
// meaning it is likely not an implicit global reference.
!references.unresolved.has(referenceName)
);
let currentScope: TSESLint.Scope.Scope | null = scope;

while (currentScope !== null) {
for (const ref of currentScope.variables) {
if (ref.defs.length === 0) {
continue;
}

const def = ref.defs[ref.defs.length - 1];

const importDetails = describePossibleImportDef(def);

// referenceName was found as an imported identifier
if (importDetails?.local === referenceName) {
return true;
}

// referenceName was found as a local variable or function declaration.
return ref.name === referenceName;
}

currentScope = currentScope.upper;
}

return false;
};