2 * @fileoverview Rule to check for "block scoped" variables by binding context
3 * @author Matt DuVall <http://www.mattduvall.com>
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
16 description: "enforce the use of variables within the scope they are defined",
17 category: "Best Practices",
19 url: "https://eslint.org/docs/rules/block-scoped-var"
25 outOfScope: "'{{name}}' used outside of binding context."
33 * Makes a block scope.
34 * @param {ASTNode} node A node of a scope.
37 function enterScope(node) {
38 stack.push(node.range);
42 * Pops the last block scope.
45 function exitScope() {
50 * Reports a given reference.
51 * @param {eslint-scope.Reference} reference A reference to report.
54 function report(reference) {
55 const identifier = reference.identifier;
57 context.report({ node: identifier, messageId: "outOfScope", data: { name: identifier.name } });
61 * Finds and reports references which are outside of valid scopes.
62 * @param {ASTNode} node A node to get variables.
65 function checkForVariables(node) {
66 if (node.kind !== "var") {
70 // Defines a predicate to check whether or not a given reference is outside of valid scope.
71 const scopeRange = stack[stack.length - 1];
74 * Check if a reference is out of scope
75 * @param {ASTNode} reference node to examine
76 * @returns {boolean} True is its outside the scope
79 function isOutsideOfScope(reference) {
80 const idRange = reference.identifier.range;
82 return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1];
85 // Gets declared variables, and checks its references.
86 const variables = context.getDeclaredVariables(node);
88 for (let i = 0; i < variables.length; ++i) {
93 .filter(isOutsideOfScope)
100 stack = [node.range];
104 BlockStatement: enterScope,
105 "BlockStatement:exit": exitScope,
106 ForStatement: enterScope,
107 "ForStatement:exit": exitScope,
108 ForInStatement: enterScope,
109 "ForInStatement:exit": exitScope,
110 ForOfStatement: enterScope,
111 "ForOfStatement:exit": exitScope,
112 SwitchStatement: enterScope,
113 "SwitchStatement:exit": exitScope,
114 CatchClause: enterScope,
115 "CatchClause:exit": exitScope,
117 // Finds and reports references which are outside of valid scope.
118 VariableDeclaration: checkForVariables