noShadowedVariableRule.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2013 Palantir Technologies, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. var tslib_1 = require("tslib");
  20. var tsutils_1 = require("tsutils");
  21. var ts = require("typescript");
  22. var Lint = require("../index");
  23. var Rule = /** @class */ (function (_super) {
  24. tslib_1.__extends(Rule, _super);
  25. function Rule() {
  26. return _super !== null && _super.apply(this, arguments) || this;
  27. }
  28. /* tslint:enable:object-literal-sort-keys */
  29. Rule.FAILURE_STRING_FACTORY = function (name) {
  30. return "Shadowed name: '" + name + "'";
  31. };
  32. Rule.prototype.apply = function (sourceFile) {
  33. return this.applyWithWalker(new NoShadowedVariableWalker(sourceFile, this.ruleName, parseOptions(this.ruleArguments[0])));
  34. };
  35. /* tslint:disable:object-literal-sort-keys */
  36. Rule.metadata = {
  37. ruleName: "no-shadowed-variable",
  38. description: "Disallows shadowing variable declarations.",
  39. rationale: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Shadowing a variable masks access to it and obscures to what value an identifier actually refers.\n For example, in the following code, it can be confusing why the filter is likely never true:\n\n ```\n const findNeighborsWithin = (instance: MyClass, instances: MyClass[]): MyClass[] => {\n return instances.filter((instance) => instance.neighbors.includes(instance));\n };\n ```\n "], ["\n Shadowing a variable masks access to it and obscures to what value an identifier actually refers.\n For example, in the following code, it can be confusing why the filter is likely never true:\n\n \\`\\`\\`\n const findNeighborsWithin = (instance: MyClass, instances: MyClass[]): MyClass[] => {\n return instances.filter((instance) => instance.neighbors.includes(instance));\n };\n \\`\\`\\`\n "]))),
  40. optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n You can optionally pass an object to disable checking for certain kinds of declarations.\n Possible keys are `\"class\"`, `\"enum\"`, `\"function\"`, `\"import\"`, `\"interface\"`, `\"namespace\"`, `\"typeAlias\"`\n and `\"typeParameter\"`. Just set the value to `false` for the check you want to disable.\n All checks default to `true`, i.e. are enabled by default.\n Note that you cannot disable variables and parameters.\n\n The option `\"temporalDeadZone\"` defaults to `true` which shows errors when shadowing block scoped declarations in their\n temporal dead zone. When set to `false` parameters, classes, enums and variables declared\n with `let` or `const` are not considered shadowed if the shadowing occurs within their\n [temporal dead zone](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified).\n\n The following example shows how the `\"temporalDeadZone\"` option changes the linting result:\n\n ```ts\n function fn(value) {\n if (value) {\n const tmp = value; // no error on this line if \"temporalDeadZone\" is false\n return tmp;\n }\n let tmp = undefined;\n if (!value) {\n const tmp = value; // this line always contains an error\n return tmp;\n }\n }\n ```\n "], ["\n You can optionally pass an object to disable checking for certain kinds of declarations.\n Possible keys are \\`\"class\"\\`, \\`\"enum\"\\`, \\`\"function\"\\`, \\`\"import\"\\`, \\`\"interface\"\\`, \\`\"namespace\"\\`, \\`\"typeAlias\"\\`\n and \\`\"typeParameter\"\\`. Just set the value to \\`false\\` for the check you want to disable.\n All checks default to \\`true\\`, i.e. are enabled by default.\n Note that you cannot disable variables and parameters.\n\n The option \\`\"temporalDeadZone\"\\` defaults to \\`true\\` which shows errors when shadowing block scoped declarations in their\n temporal dead zone. When set to \\`false\\` parameters, classes, enums and variables declared\n with \\`let\\` or \\`const\\` are not considered shadowed if the shadowing occurs within their\n [temporal dead zone](http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified).\n\n The following example shows how the \\`\"temporalDeadZone\"\\` option changes the linting result:\n\n \\`\\`\\`ts\n function fn(value) {\n if (value) {\n const tmp = value; // no error on this line if \"temporalDeadZone\" is false\n return tmp;\n }\n let tmp = undefined;\n if (!value) {\n const tmp = value; // this line always contains an error\n return tmp;\n }\n }\n \\`\\`\\`\n "]))),
  41. options: {
  42. type: "object",
  43. properties: {
  44. class: { type: "boolean" },
  45. enum: { type: "boolean" },
  46. function: { type: "boolean" },
  47. import: { type: "boolean" },
  48. interface: { type: "boolean" },
  49. namespace: { type: "boolean" },
  50. typeAlias: { type: "boolean" },
  51. typeParameter: { type: "boolean" },
  52. temporalDeadZone: { type: "boolean" },
  53. },
  54. },
  55. optionExamples: [
  56. true,
  57. [true, { class: true, enum: true, function: true, interface: false, namespace: true, typeAlias: false, typeParameter: false }],
  58. ],
  59. type: "functionality",
  60. typescriptOnly: false,
  61. };
  62. return Rule;
  63. }(Lint.Rules.AbstractRule));
  64. exports.Rule = Rule;
  65. function parseOptions(option) {
  66. return tslib_1.__assign({ class: true, enum: true, function: true, import: true, interface: true, namespace: true, temporalDeadZone: true, typeAlias: true, typeParameter: true }, option);
  67. }
  68. var Scope = /** @class */ (function () {
  69. function Scope(functionScope) {
  70. this.variables = new Map();
  71. this.variablesSeen = new Map();
  72. this.reassigned = new Set();
  73. // if no functionScope is provided we are in the process of creating a new function scope, which for consistency links to itself
  74. this.functionScope = functionScope !== undefined ? functionScope : this;
  75. }
  76. Scope.prototype.addVariable = function (identifier, blockScoped, tdz) {
  77. if (blockScoped === void 0) { blockScoped = true; }
  78. if (tdz === void 0) { tdz = false; }
  79. // block scoped variables go to the block scope, function scoped variables to the containing function scope
  80. var scope = blockScoped ? this : this.functionScope;
  81. var list = scope.variables.get(identifier.text);
  82. var variableInfo = {
  83. identifier: identifier,
  84. tdz: tdz,
  85. };
  86. if (list === undefined) {
  87. scope.variables.set(identifier.text, [variableInfo]);
  88. }
  89. else {
  90. list.push(variableInfo);
  91. }
  92. };
  93. return Scope;
  94. }());
  95. var NoShadowedVariableWalker = /** @class */ (function (_super) {
  96. tslib_1.__extends(NoShadowedVariableWalker, _super);
  97. function NoShadowedVariableWalker() {
  98. return _super !== null && _super.apply(this, arguments) || this;
  99. }
  100. NoShadowedVariableWalker.prototype.walk = function (sourceFile) {
  101. var _this = this;
  102. if (sourceFile.isDeclarationFile) {
  103. return;
  104. }
  105. this.scope = new Scope();
  106. var cb = function (node) {
  107. var parentScope = _this.scope;
  108. if ((_this.options.function && tsutils_1.isFunctionExpression(node) || _this.options.class && tsutils_1.isClassExpression(node)) &&
  109. node.name !== undefined) {
  110. /* special handling for named function and class expressions:
  111. technically the name of the function is only visible inside of it,
  112. but variables with the same name declared inside don't cause compiler errors.
  113. Therefore we add an additional function scope only for the function name to avoid merging with other declarations */
  114. var functionScope = new Scope();
  115. functionScope.addVariable(node.name, false);
  116. _this.scope = new Scope();
  117. if (tsutils_1.isClassExpression(node)) {
  118. _this.visitClassLikeDeclaration(node, functionScope, cb);
  119. }
  120. else {
  121. ts.forEachChild(node, cb);
  122. }
  123. _this.onScopeEnd(functionScope);
  124. _this.scope = functionScope;
  125. _this.onScopeEnd(parentScope);
  126. _this.scope = parentScope;
  127. return;
  128. }
  129. /* Visit decorators before entering a function scope.
  130. In the AST decorators are children of the declaration they decorate, but we don't want to warn for the following code:
  131. @decorator((param) => param)
  132. function foo(param) {}
  133. */
  134. if (node.decorators !== undefined) {
  135. for (var _i = 0, _a = node.decorators; _i < _a.length; _i++) {
  136. var decorator = _a[_i];
  137. ts.forEachChild(decorator, cb);
  138. }
  139. }
  140. var boundary = tsutils_1.isScopeBoundary(node);
  141. if (boundary === 2 /* Block */) {
  142. _this.scope = new Scope(parentScope.functionScope);
  143. }
  144. else if (boundary === 1 /* Function */) {
  145. _this.scope = new Scope();
  146. }
  147. switch (node.kind) {
  148. case ts.SyntaxKind.Decorator:
  149. return; // handled above
  150. case ts.SyntaxKind.VariableDeclarationList:
  151. _this.handleVariableDeclarationList(node);
  152. break;
  153. case ts.SyntaxKind.TypeParameter:
  154. if (_this.options.typeParameter) {
  155. _this.scope.addVariable(node.name);
  156. }
  157. break;
  158. case ts.SyntaxKind.FunctionDeclaration:
  159. if (_this.options.function && node.name !== undefined) {
  160. parentScope.addVariable(node.name, false);
  161. }
  162. break;
  163. case ts.SyntaxKind.ClassDeclaration:
  164. if (_this.options.class && node.name !== undefined) {
  165. parentScope.addVariable(node.name, true, true);
  166. }
  167. // falls through
  168. case ts.SyntaxKind.ClassExpression:
  169. _this.visitClassLikeDeclaration(node, parentScope, cb);
  170. _this.onScopeEnd(parentScope);
  171. _this.scope = parentScope;
  172. return;
  173. case ts.SyntaxKind.TypeAliasDeclaration:
  174. if (_this.options.typeAlias) {
  175. parentScope.addVariable(node.name);
  176. }
  177. break;
  178. case ts.SyntaxKind.EnumDeclaration:
  179. if (_this.options.enum) {
  180. parentScope.addVariable(node.name, true, true);
  181. }
  182. break;
  183. case ts.SyntaxKind.InterfaceDeclaration:
  184. if (_this.options.interface) {
  185. parentScope.addVariable(node.name);
  186. }
  187. break;
  188. case ts.SyntaxKind.Parameter:
  189. if (node.parent.kind !== ts.SyntaxKind.IndexSignature &&
  190. !tsutils_1.isThisParameter(node) &&
  191. tsutils_1.isFunctionWithBody(node.parent)) {
  192. _this.handleBindingName(node.name, false, true);
  193. }
  194. break;
  195. case ts.SyntaxKind.ModuleDeclaration:
  196. if (_this.options.namespace &&
  197. node.parent.kind !== ts.SyntaxKind.ModuleDeclaration &&
  198. node.name.kind === ts.SyntaxKind.Identifier &&
  199. !tsutils_1.isNodeFlagSet(node, ts.NodeFlags.GlobalAugmentation)) {
  200. parentScope.addVariable(node.name, false);
  201. }
  202. if (tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) {
  203. _this.onScopeEnd(parentScope);
  204. _this.scope = parentScope;
  205. return; // don't check any ambient declaration blocks
  206. }
  207. break;
  208. case ts.SyntaxKind.ImportClause:
  209. if (_this.options.import && node.name !== undefined) {
  210. _this.scope.addVariable(node.name, false);
  211. }
  212. break;
  213. case ts.SyntaxKind.NamespaceImport:
  214. case ts.SyntaxKind.ImportSpecifier:
  215. case ts.SyntaxKind.ImportEqualsDeclaration:
  216. if (_this.options.import) {
  217. _this.scope.addVariable(node.name, false);
  218. }
  219. }
  220. if (boundary !== 0 /* None */) {
  221. ts.forEachChild(node, cb);
  222. _this.onScopeEnd(parentScope);
  223. _this.scope = parentScope;
  224. }
  225. else {
  226. return ts.forEachChild(node, cb);
  227. }
  228. };
  229. ts.forEachChild(sourceFile, cb);
  230. this.onScopeEnd();
  231. };
  232. NoShadowedVariableWalker.prototype.visitClassLikeDeclaration = function (declaration, parentScope, cb) {
  233. var _this = this;
  234. var currentScope = this.scope;
  235. ts.forEachChild(declaration, function (node) {
  236. if (!tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword)) {
  237. return cb(node);
  238. }
  239. /* Don't treat static members as children of the class' scope. That avoid shadowed type parameter warnings on static members.
  240. class C<T> {
  241. static method<T>() {}
  242. }
  243. */
  244. _this.scope = parentScope;
  245. cb(node);
  246. _this.scope = currentScope;
  247. });
  248. };
  249. NoShadowedVariableWalker.prototype.handleVariableDeclarationList = function (node) {
  250. var blockScoped = tsutils_1.isBlockScopedVariableDeclarationList(node);
  251. for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
  252. var variable = _a[_i];
  253. this.handleBindingName(variable.name, blockScoped);
  254. }
  255. };
  256. NoShadowedVariableWalker.prototype.handleBindingName = function (node, blockScoped, tdz) {
  257. if (tdz === void 0) { tdz = blockScoped; }
  258. if (node.kind === ts.SyntaxKind.Identifier) {
  259. this.scope.addVariable(node, blockScoped, tdz);
  260. }
  261. else {
  262. for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
  263. var element = _a[_i];
  264. if (element.kind !== ts.SyntaxKind.OmittedExpression) {
  265. this.handleBindingName(element.name, blockScoped, tdz);
  266. }
  267. }
  268. }
  269. };
  270. NoShadowedVariableWalker.prototype.onScopeEnd = function (parent) {
  271. var _this = this;
  272. var _a = this.scope, variables = _a.variables, variablesSeen = _a.variablesSeen;
  273. variablesSeen.forEach(function (identifiers, name) {
  274. var declarationsInScope = variables.get(name);
  275. var _loop_1 = function (identifier) {
  276. if (declarationsInScope !== undefined &&
  277. (_this.options.temporalDeadZone ||
  278. // check if any of the declaration either has no temporal dead zone or is declared before the identifier
  279. declarationsInScope.some(function (declaration) { return !declaration.tdz || declaration.identifier.pos < identifier.pos; }))) {
  280. _this.addFailureAtNode(identifier, Rule.FAILURE_STRING_FACTORY(name));
  281. }
  282. else if (parent !== undefined) {
  283. addOneToList(parent.variablesSeen, name, identifier);
  284. }
  285. };
  286. for (var _i = 0, identifiers_1 = identifiers; _i < identifiers_1.length; _i++) {
  287. var identifier = identifiers_1[_i];
  288. _loop_1(identifier);
  289. }
  290. });
  291. if (parent !== undefined) {
  292. variables.forEach(function (identifiers, name) {
  293. addToList(parent.variablesSeen, name, identifiers);
  294. });
  295. }
  296. };
  297. return NoShadowedVariableWalker;
  298. }(Lint.AbstractWalker));
  299. function addToList(map, name, variables) {
  300. var list = map.get(name);
  301. if (list === undefined) {
  302. list = [];
  303. map.set(name, list);
  304. }
  305. for (var _i = 0, variables_1 = variables; _i < variables_1.length; _i++) {
  306. var variable = variables_1[_i];
  307. list.push(variable.identifier);
  308. }
  309. }
  310. function addOneToList(map, name, identifier) {
  311. var list = map.get(name);
  312. if (list === undefined) {
  313. map.set(name, [identifier]);
  314. }
  315. else {
  316. list.push(identifier);
  317. }
  318. }
  319. var templateObject_1, templateObject_2;