Skip to content

Commit

Permalink
refactor: inline collectReferences utility into `scopeHasLocalRefer…
Browse files Browse the repository at this point in the history
…ence` (#1276)

* refactor: inline `collectReferences` utility into `scopeHasLocalReference`

* refactor: optimize a little further

* refactor: remove unneeded checks
  • Loading branch information
G-Rath committed Nov 4, 2022
1 parent 49e6f2f commit 6f85b64
Showing 1 changed file with 25 additions and 47 deletions.
72 changes: 25 additions & 47 deletions src/rules/utils/parseJestFnCall.ts
Original file line number Diff line number Diff line change
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;
};

0 comments on commit 6f85b64

Please sign in to comment.