All files / src/utils scope-tracker.ts

55.71% Statements 39/70
63.15% Branches 24/38
58.82% Functions 20/34
62.26% Lines 33/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222                                                    56x     56x             56x 56x             1036x               1036x 1036x 1036x             1034x 1033x                                   946x                     946x             8116x 8116x 2917x               8118x   8118x 26770x 26770x 2918x   23852x     5200x                           45x   45x 1071x     45x                           57x 57x     54x 54x 114x     54x                                           522x                                                                            
import { TSESTree } from '@typescript-eslint/typescript-estree';
 
export type ScopeType = 'global' | 'function' | 'block' | 'loop' | 'class';
 
export interface VariableInfo {
  name: string;
  node: TSESTree.Node;
  declarationLine: number;
  references: TSESTree.Node[];
  type?: TSESTree.TypeNode | null;
  isParameter: boolean;
  isDestructured: boolean;
  isLoopVariable: boolean;
}
 
export interface Scope {
  type: ScopeType;
  node: TSESTree.Node;
  parent: Scope | null;
  children: Scope[];
  variables: Map<string, VariableInfo>;
}
 
export class ScopeTracker {
  private currentScope: Scope;
  private readonly rootScope: Scope;
  private readonly allScopes: Scope[] = [];
 
  constructor(rootNode: TSESTree.Program) {
    this.rootScope = {
      type: 'global',
      node: rootNode,
      parent: null,
      children: [],
      variables: new Map(),
    };
    this.currentScope = this.rootScope;
    this.allScopes.push(this.rootScope);
  }
 
  /**
   * Enter a new scope
   */
  enterScope(type: ScopeType, node: TSESTree.Node): void {
    const newScope: Scope = {
      type,
      node,
      parent: this.currentScope,
      children: [],
      variables: new Map(),
    };
 
    this.currentScope.children.push(newScope);
    this.currentScope = newScope;
    this.allScopes.push(newScope);
  }
 
  /**
   * Exit current scope and return to parent
   */
  exitScope(): void {
    if (this.currentScope.parent) {
      this.currentScope = this.currentScope.parent;
    }
  }
 
  /**
   * Declare a variable in the current scope
   */
  declareVariable(
    name: string,
    node: TSESTree.Node,
    line: number,
    options: {
      type?: TSESTree.TypeNode | null;
      isParameter?: boolean;
      isDestructured?: boolean;
      isLoopVariable?: boolean;
    } = {}
  ): void {
    const varInfo: VariableInfo = {
      name,
      node,
      declarationLine: line,
      references: [],
      type: options.type,
      isParameter: options.isParameter ?? false,
      isDestructured: options.isDestructured ?? false,
      isLoopVariable: options.isLoopVariable ?? false,
    };
 
    this.currentScope.variables.set(name, varInfo);
  }
 
  /**
   * Add a reference to a variable
   */
  addReference(name: string, node: TSESTree.Node): void {
    const varInfo = this.findVariable(name);
    if (varInfo) {
      varInfo.references.push(node);
    }
  }
 
  /**
   * Find a variable in current or parent scopes
   */
  findVariable(name: string): VariableInfo | null {
    let scope: Scope | null = this.currentScope;
 
    while (scope) {
      const varInfo = scope.variables.get(name);
      if (varInfo) {
        return varInfo;
      }
      scope = scope.parent;
    }
 
    return null;
  }
 
  /**
   * Get all variables in current scope (not including parent scopes)
   */
  getCurrentScopeVariables(): VariableInfo[] {
    return Array.from(this.currentScope.variables.values());
  }
 
  /**
   * Get all variables across all scopes
   */
  getAllVariables(): VariableInfo[] {
    const allVars: VariableInfo[] = [];
 
    for (const scope of this.allScopes) {
      allVars.push(...Array.from(scope.variables.values()));
    }
 
    return allVars;
  }
 
  /**
   * Calculate actual usage count (references minus declaration)
   */
  getUsageCount(varInfo: VariableInfo): number {
    return varInfo.references.length;
  }
 
  /**
   * Check if a variable is short-lived (used within N lines)
   */
  isShortLived(varInfo: VariableInfo, maxLines: number = 5): boolean {
    if (varInfo.references.length === 0) {
      return false; // Unused variable
    }
 
    const declarationLine = varInfo.declarationLine;
    const maxUsageLine = Math.max(
      ...varInfo.references.map((ref) => ref.loc?.start.line ?? declarationLine)
    );
 
    return maxUsageLine - declarationLine <= maxLines;
  }
 
  /**
   * Check if a variable is used in a limited scope (e.g., only in one callback)
   */
  isLocallyScoped(varInfo: VariableInfo): boolean {
    // If all references are within a small scope (e.g., arrow function), it's locally scoped
    if (varInfo.references.length === 0) return false;
 
    // Check if usage span is small
    const lines = varInfo.references.map((ref) => ref.loc?.start.line ?? 0);
    const minLine = Math.min(...lines);
    const maxLine = Math.max(...lines);
 
    return maxLine - minLine <= 3;
  }
 
  /**
   * Get current scope type
   */
  getCurrentScopeType(): ScopeType {
    return this.currentScope.type;
  }
 
  /**
   * Check if currently in a loop scope
   */
  isInLoop(): boolean {
    let scope: Scope | null = this.currentScope;
    while (scope) {
      if (scope.type === 'loop') {
        return true;
      }
      scope = scope.parent;
    }
    return false;
  }
 
  /**
   * Check if currently in a function scope
   */
  isInFunction(): boolean {
    let scope: Scope | null = this.currentScope;
    while (scope) {
      if (scope.type === 'function') {
        return true;
      }
      scope = scope.parent;
    }
    return false;
  }
 
  /**
   * Get the root scope
   */
  getRootScope(): Scope {
    return this.rootScope;
  }
}