camelcase.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /**
  2. * @fileoverview Rule to flag non-camelcased identifiers
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "enforce camelcase naming convention",
  14. category: "Stylistic Issues",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/camelcase"
  17. },
  18. schema: [
  19. {
  20. type: "object",
  21. properties: {
  22. ignoreDestructuring: {
  23. type: "boolean",
  24. default: false
  25. },
  26. ignoreImports: {
  27. type: "boolean",
  28. default: false
  29. },
  30. ignoreGlobals: {
  31. type: "boolean",
  32. default: false
  33. },
  34. properties: {
  35. enum: ["always", "never"]
  36. },
  37. allow: {
  38. type: "array",
  39. items: [
  40. {
  41. type: "string"
  42. }
  43. ],
  44. minItems: 0,
  45. uniqueItems: true
  46. }
  47. },
  48. additionalProperties: false
  49. }
  50. ],
  51. messages: {
  52. notCamelCase: "Identifier '{{name}}' is not in camel case."
  53. }
  54. },
  55. create(context) {
  56. const options = context.options[0] || {};
  57. let properties = options.properties || "";
  58. const ignoreDestructuring = options.ignoreDestructuring;
  59. const ignoreImports = options.ignoreImports;
  60. const ignoreGlobals = options.ignoreGlobals;
  61. const allow = options.allow || [];
  62. let globalScope;
  63. if (properties !== "always" && properties !== "never") {
  64. properties = "always";
  65. }
  66. //--------------------------------------------------------------------------
  67. // Helpers
  68. //--------------------------------------------------------------------------
  69. // contains reported nodes to avoid reporting twice on destructuring with shorthand notation
  70. const reported = [];
  71. const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]);
  72. /**
  73. * Checks if a string contains an underscore and isn't all upper-case
  74. * @param {string} name The string to check.
  75. * @returns {boolean} if the string is underscored
  76. * @private
  77. */
  78. function isUnderscored(name) {
  79. // if there's an underscore, it might be A_CONSTANT, which is okay
  80. return name.includes("_") && name !== name.toUpperCase();
  81. }
  82. /**
  83. * Checks if a string match the ignore list
  84. * @param {string} name The string to check.
  85. * @returns {boolean} if the string is ignored
  86. * @private
  87. */
  88. function isAllowed(name) {
  89. return allow.some(
  90. entry => name === entry || name.match(new RegExp(entry, "u"))
  91. );
  92. }
  93. /**
  94. * Checks if a parent of a node is an ObjectPattern.
  95. * @param {ASTNode} node The node to check.
  96. * @returns {boolean} if the node is inside an ObjectPattern
  97. * @private
  98. */
  99. function isInsideObjectPattern(node) {
  100. let current = node;
  101. while (current) {
  102. const parent = current.parent;
  103. if (parent && parent.type === "Property" && parent.computed && parent.key === current) {
  104. return false;
  105. }
  106. if (current.type === "ObjectPattern") {
  107. return true;
  108. }
  109. current = parent;
  110. }
  111. return false;
  112. }
  113. /**
  114. * Checks whether the given node represents assignment target property in destructuring.
  115. *
  116. * For examples:
  117. * ({a: b.foo} = c); // => true for `foo`
  118. * ([a.foo] = b); // => true for `foo`
  119. * ([a.foo = 1] = b); // => true for `foo`
  120. * ({...a.foo} = b); // => true for `foo`
  121. * @param {ASTNode} node An Identifier node to check
  122. * @returns {boolean} True if the node is an assignment target property in destructuring.
  123. */
  124. function isAssignmentTargetPropertyInDestructuring(node) {
  125. if (
  126. node.parent.type === "MemberExpression" &&
  127. node.parent.property === node &&
  128. !node.parent.computed
  129. ) {
  130. const effectiveParent = node.parent.parent;
  131. return (
  132. effectiveParent.type === "Property" &&
  133. effectiveParent.value === node.parent &&
  134. effectiveParent.parent.type === "ObjectPattern" ||
  135. effectiveParent.type === "ArrayPattern" ||
  136. effectiveParent.type === "RestElement" ||
  137. (
  138. effectiveParent.type === "AssignmentPattern" &&
  139. effectiveParent.left === node.parent
  140. )
  141. );
  142. }
  143. return false;
  144. }
  145. /**
  146. * Checks whether the given node represents a reference to a global variable that is not declared in the source code.
  147. * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables.
  148. * @param {ASTNode} node `Identifier` node to check.
  149. * @returns {boolean} `true` if the node is a reference to a global variable.
  150. */
  151. function isReferenceToGlobalVariable(node) {
  152. const variable = globalScope.set.get(node.name);
  153. return variable && variable.defs.length === 0 &&
  154. variable.references.some(ref => ref.identifier === node);
  155. }
  156. /**
  157. * Checks whether the given node represents a reference to a property of an object in an object literal expression.
  158. * This allows to differentiate between a global variable that is allowed to be used as a reference, and the key
  159. * of the expressed object (which shouldn't be allowed).
  160. * @param {ASTNode} node `Identifier` node to check.
  161. * @returns {boolean} `true` if the node is a property name of an object literal expression
  162. */
  163. function isPropertyNameInObjectLiteral(node) {
  164. const parent = node.parent;
  165. return (
  166. parent.type === "Property" &&
  167. parent.parent.type === "ObjectExpression" &&
  168. !parent.computed &&
  169. parent.key === node
  170. );
  171. }
  172. /**
  173. * Reports an AST node as a rule violation.
  174. * @param {ASTNode} node The node to report.
  175. * @returns {void}
  176. * @private
  177. */
  178. function report(node) {
  179. if (!reported.includes(node)) {
  180. reported.push(node);
  181. context.report({ node, messageId: "notCamelCase", data: { name: node.name } });
  182. }
  183. }
  184. return {
  185. Program() {
  186. globalScope = context.getScope();
  187. },
  188. Identifier(node) {
  189. /*
  190. * Leading and trailing underscores are commonly used to flag
  191. * private/protected identifiers, strip them before checking if underscored
  192. */
  193. const name = node.name,
  194. nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/gu, "")),
  195. effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
  196. // First, we ignore the node if it match the ignore list
  197. if (isAllowed(name)) {
  198. return;
  199. }
  200. // Check if it's a global variable
  201. if (ignoreGlobals && isReferenceToGlobalVariable(node) && !isPropertyNameInObjectLiteral(node)) {
  202. return;
  203. }
  204. // MemberExpressions get special rules
  205. if (node.parent.type === "MemberExpression") {
  206. // "never" check properties
  207. if (properties === "never") {
  208. return;
  209. }
  210. // Always report underscored object names
  211. if (node.parent.object.type === "Identifier" && node.parent.object.name === node.name && nameIsUnderscored) {
  212. report(node);
  213. // Report AssignmentExpressions only if they are the left side of the assignment
  214. } else if (effectiveParent.type === "AssignmentExpression" && nameIsUnderscored && (effectiveParent.right.type !== "MemberExpression" || effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name)) {
  215. report(node);
  216. } else if (isAssignmentTargetPropertyInDestructuring(node) && nameIsUnderscored) {
  217. report(node);
  218. }
  219. /*
  220. * Properties have their own rules, and
  221. * AssignmentPattern nodes can be treated like Properties:
  222. * e.g.: const { no_camelcased = false } = bar;
  223. */
  224. } else if (node.parent.type === "Property" || node.parent.type === "AssignmentPattern") {
  225. if (node.parent.parent && node.parent.parent.type === "ObjectPattern") {
  226. if (node.parent.shorthand && node.parent.value.left && nameIsUnderscored) {
  227. report(node);
  228. }
  229. const assignmentKeyEqualsValue = node.parent.key.name === node.parent.value.name;
  230. if (nameIsUnderscored && node.parent.computed) {
  231. report(node);
  232. }
  233. // prevent checking righthand side of destructured object
  234. if (node.parent.key === node && node.parent.value !== node) {
  235. return;
  236. }
  237. const valueIsUnderscored = node.parent.value.name && nameIsUnderscored;
  238. // ignore destructuring if the option is set, unless a new identifier is created
  239. if (valueIsUnderscored && !(assignmentKeyEqualsValue && ignoreDestructuring)) {
  240. report(node);
  241. }
  242. }
  243. // "never" check properties or always ignore destructuring
  244. if (properties === "never" || (ignoreDestructuring && isInsideObjectPattern(node))) {
  245. return;
  246. }
  247. // don't check right hand side of AssignmentExpression to prevent duplicate warnings
  248. if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && !(node.parent.right === node)) {
  249. report(node);
  250. }
  251. // Check if it's an import specifier
  252. } else if (["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"].includes(node.parent.type)) {
  253. if (node.parent.type === "ImportSpecifier" && ignoreImports) {
  254. return;
  255. }
  256. // Report only if the local imported identifier is underscored
  257. if (
  258. node.parent.local &&
  259. node.parent.local.name === node.name &&
  260. nameIsUnderscored
  261. ) {
  262. report(node);
  263. }
  264. // Report anything that is underscored that isn't a CallExpression
  265. } else if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) {
  266. report(node);
  267. }
  268. }
  269. };
  270. }
  271. };