variableNameRule.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. // tslint:disable object-literal-sort-keys
  21. var tsutils_1 = require("tsutils");
  22. var ts = require("typescript");
  23. var Lint = require("../index");
  24. var utils_1 = require("../utils");
  25. var BANNED_KEYWORDS = ["any", "Number", "number", "String", "string", "Boolean", "boolean", "Undefined", "undefined"];
  26. var bannedKeywordsSet = new Set(BANNED_KEYWORDS);
  27. var bannedKeywordsStr = BANNED_KEYWORDS.map(function (kw) { return "`" + kw + "`"; }).join(", ");
  28. var OPTION_LEADING_UNDERSCORE = "allow-leading-underscore";
  29. var OPTION_TRAILING_UNDERSCORE = "allow-trailing-underscore";
  30. var OPTION_BAN_KEYWORDS = "ban-keywords";
  31. var OPTION_CHECK_FORMAT = "check-format";
  32. var OPTION_ALLOW_PASCAL_CASE = "allow-pascal-case";
  33. var OPTION_ALLOW_SNAKE_CASE = "allow-snake-case";
  34. var Rule = /** @class */ (function (_super) {
  35. tslib_1.__extends(Rule, _super);
  36. function Rule() {
  37. return _super !== null && _super.apply(this, arguments) || this;
  38. }
  39. Rule.prototype.apply = function (sourceFile) {
  40. return this.applyWithFunction(sourceFile, walk, parseOptions(this.ruleArguments));
  41. };
  42. Rule.metadata = {
  43. ruleName: "variable-name",
  44. description: "Checks variable names for various errors.",
  45. optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Five arguments may be optionally provided:\n\n * `\"", "\"`: allows only lowerCamelCased or UPPER_CASED variable names\n * `\"", "\"` allows underscores at the beginning (only has an effect if \"check-format\" specified)\n * `\"", "\"` allows underscores at the end. (only has an effect if \"check-format\" specified)\n * `\"", "\"` allows PascalCase in addition to lowerCamelCase.\n * `\"", "\"` allows snake_case in addition to lowerCamelCase.\n * `\"", "\"`: disallows the use of certain TypeScript keywords as variable or parameter names.\n * These are: ", ""], ["\n Five arguments may be optionally provided:\n\n * \\`\"", "\"\\`: allows only lowerCamelCased or UPPER_CASED variable names\n * \\`\"", "\"\\` allows underscores at the beginning (only has an effect if \"check-format\" specified)\n * \\`\"", "\"\\` allows underscores at the end. (only has an effect if \"check-format\" specified)\n * \\`\"", "\"\\` allows PascalCase in addition to lowerCamelCase.\n * \\`\"", "\"\\` allows snake_case in addition to lowerCamelCase.\n * \\`\"", "\"\\`: disallows the use of certain TypeScript keywords as variable or parameter names.\n * These are: ", ""])), OPTION_CHECK_FORMAT, OPTION_LEADING_UNDERSCORE, OPTION_TRAILING_UNDERSCORE, OPTION_ALLOW_PASCAL_CASE, OPTION_ALLOW_SNAKE_CASE, OPTION_BAN_KEYWORDS, bannedKeywordsStr),
  46. options: {
  47. type: "array",
  48. items: {
  49. type: "string",
  50. enum: [
  51. OPTION_CHECK_FORMAT,
  52. OPTION_LEADING_UNDERSCORE,
  53. OPTION_TRAILING_UNDERSCORE,
  54. OPTION_ALLOW_PASCAL_CASE,
  55. OPTION_ALLOW_SNAKE_CASE,
  56. OPTION_BAN_KEYWORDS,
  57. ],
  58. },
  59. minLength: 0,
  60. maxLength: 5,
  61. },
  62. optionExamples: [[true, "ban-keywords", "check-format", "allow-leading-underscore"]],
  63. type: "style",
  64. typescriptOnly: false,
  65. };
  66. Rule.KEYWORD_FAILURE = "variable name clashes with keyword/type";
  67. return Rule;
  68. }(Lint.Rules.AbstractRule));
  69. exports.Rule = Rule;
  70. function parseOptions(ruleArguments) {
  71. var banKeywords = hasOption(OPTION_BAN_KEYWORDS);
  72. return {
  73. banKeywords: banKeywords,
  74. // check variable name formatting by default if no options are specified
  75. checkFormat: !banKeywords || hasOption(OPTION_CHECK_FORMAT),
  76. leadingUnderscore: hasOption(OPTION_LEADING_UNDERSCORE),
  77. trailingUnderscore: hasOption(OPTION_TRAILING_UNDERSCORE),
  78. allowPascalCase: hasOption(OPTION_ALLOW_PASCAL_CASE),
  79. allowSnakeCase: hasOption(OPTION_ALLOW_SNAKE_CASE),
  80. };
  81. function hasOption(name) {
  82. return ruleArguments.indexOf(name) !== -1;
  83. }
  84. }
  85. function walk(ctx) {
  86. var options = ctx.options, sourceFile = ctx.sourceFile;
  87. return ts.forEachChild(sourceFile, function cb(node) {
  88. switch (node.kind) {
  89. case ts.SyntaxKind.BindingElement: {
  90. var _a = node, initializer = _a.initializer, name = _a.name, propertyName = _a.propertyName;
  91. if (name.kind === ts.SyntaxKind.Identifier) {
  92. handleVariableNameKeyword(name);
  93. // A destructuring pattern that does not rebind an expression is always an alias, e.g. `var {Foo} = ...;`.
  94. // Only check if the name is rebound (`var {Foo: bar} = ...;`).
  95. if (node.parent.kind !== ts.SyntaxKind.ObjectBindingPattern || propertyName !== undefined) {
  96. handleVariableNameFormat(name, initializer);
  97. }
  98. }
  99. break;
  100. }
  101. case ts.SyntaxKind.VariableStatement:
  102. // skip 'declare' keywords
  103. if (tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) {
  104. return;
  105. }
  106. break;
  107. case ts.SyntaxKind.Parameter:
  108. case ts.SyntaxKind.PropertyDeclaration:
  109. case ts.SyntaxKind.VariableDeclaration: {
  110. var _b = node, name = _b.name, initializer = _b.initializer;
  111. if (name.kind === ts.SyntaxKind.Identifier) {
  112. handleVariableNameFormat(name, initializer);
  113. // do not check property declarations for keywords, they are allowed to be keywords
  114. if (node.kind !== ts.SyntaxKind.PropertyDeclaration) {
  115. handleVariableNameKeyword(name);
  116. }
  117. }
  118. }
  119. }
  120. return ts.forEachChild(node, cb);
  121. });
  122. function handleVariableNameFormat(name, initializer) {
  123. if (!options.checkFormat) {
  124. return;
  125. }
  126. var text = name.text;
  127. if (initializer !== undefined && isAlias(text, initializer)) {
  128. return;
  129. }
  130. if (text.length !== 0 && !isCamelCase(text, options) && !utils_1.isUpperCase(text)) {
  131. ctx.addFailureAtNode(name, formatFailure());
  132. }
  133. }
  134. function handleVariableNameKeyword(name) {
  135. if (options.banKeywords && bannedKeywordsSet.has(name.text)) {
  136. ctx.addFailureAtNode(name, Rule.KEYWORD_FAILURE);
  137. }
  138. }
  139. function formatFailure() {
  140. var failureMessage = "variable name must be in lowerCamelCase";
  141. if (options.allowPascalCase) {
  142. failureMessage += ", PascalCase";
  143. }
  144. if (options.allowSnakeCase) {
  145. failureMessage += ", snake_case";
  146. }
  147. return failureMessage + " or UPPER_CASE";
  148. }
  149. }
  150. function isAlias(name, initializer) {
  151. switch (initializer.kind) {
  152. case ts.SyntaxKind.PropertyAccessExpression:
  153. return initializer.name.text === name;
  154. case ts.SyntaxKind.Identifier:
  155. return initializer.text === name;
  156. default:
  157. return false;
  158. }
  159. }
  160. function isCamelCase(name, options) {
  161. var firstCharacter = name[0];
  162. var lastCharacter = name[name.length - 1];
  163. var middle = name.slice(1, -1);
  164. if (!options.leadingUnderscore && firstCharacter === "_") {
  165. return false;
  166. }
  167. if (!options.trailingUnderscore && lastCharacter === "_") {
  168. return false;
  169. }
  170. if (!options.allowPascalCase && !utils_1.isLowerCase(firstCharacter)) {
  171. return false;
  172. }
  173. if (!options.allowSnakeCase && middle.indexOf("_") !== -1) {
  174. return false;
  175. }
  176. return true;
  177. }
  178. var templateObject_1;