new-cap.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /**
  2. * @fileoverview Rule to flag use of constructors without capital letters
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. //------------------------------------------------------------------------------
  10. // Helpers
  11. //------------------------------------------------------------------------------
  12. const CAPS_ALLOWED = [
  13. "Array",
  14. "Boolean",
  15. "Date",
  16. "Error",
  17. "Function",
  18. "Number",
  19. "Object",
  20. "RegExp",
  21. "String",
  22. "Symbol"
  23. ];
  24. /**
  25. * Ensure that if the key is provided, it must be an array.
  26. * @param {Object} obj Object to check with `key`.
  27. * @param {string} key Object key to check on `obj`.
  28. * @param {*} fallback If obj[key] is not present, this will be returned.
  29. * @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback`
  30. */
  31. function checkArray(obj, key, fallback) {
  32. /* istanbul ignore if */
  33. if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) {
  34. throw new TypeError(`${key}, if provided, must be an Array`);
  35. }
  36. return obj[key] || fallback;
  37. }
  38. /**
  39. * A reducer function to invert an array to an Object mapping the string form of the key, to `true`.
  40. * @param {Object} map Accumulator object for the reduce.
  41. * @param {string} key Object key to set to `true`.
  42. * @returns {Object} Returns the updated Object for further reduction.
  43. */
  44. function invert(map, key) {
  45. map[key] = true;
  46. return map;
  47. }
  48. /**
  49. * Creates an object with the cap is new exceptions as its keys and true as their values.
  50. * @param {Object} config Rule configuration
  51. * @returns {Object} Object with cap is new exceptions.
  52. */
  53. function calculateCapIsNewExceptions(config) {
  54. let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
  55. if (capIsNewExceptions !== CAPS_ALLOWED) {
  56. capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED);
  57. }
  58. return capIsNewExceptions.reduce(invert, {});
  59. }
  60. //------------------------------------------------------------------------------
  61. // Rule Definition
  62. //------------------------------------------------------------------------------
  63. module.exports = {
  64. meta: {
  65. type: "suggestion",
  66. docs: {
  67. description: "require constructor names to begin with a capital letter",
  68. category: "Stylistic Issues",
  69. recommended: false,
  70. url: "https://eslint.org/docs/rules/new-cap"
  71. },
  72. schema: [
  73. {
  74. type: "object",
  75. properties: {
  76. newIsCap: {
  77. type: "boolean",
  78. default: true
  79. },
  80. capIsNew: {
  81. type: "boolean",
  82. default: true
  83. },
  84. newIsCapExceptions: {
  85. type: "array",
  86. items: {
  87. type: "string"
  88. }
  89. },
  90. newIsCapExceptionPattern: {
  91. type: "string"
  92. },
  93. capIsNewExceptions: {
  94. type: "array",
  95. items: {
  96. type: "string"
  97. }
  98. },
  99. capIsNewExceptionPattern: {
  100. type: "string"
  101. },
  102. properties: {
  103. type: "boolean",
  104. default: true
  105. }
  106. },
  107. additionalProperties: false
  108. }
  109. ],
  110. messages: {
  111. upper: "A function with a name starting with an uppercase letter should only be used as a constructor.",
  112. lower: "A constructor name should not start with a lowercase letter."
  113. }
  114. },
  115. create(context) {
  116. const config = Object.assign({}, context.options[0]);
  117. config.newIsCap = config.newIsCap !== false;
  118. config.capIsNew = config.capIsNew !== false;
  119. const skipProperties = config.properties === false;
  120. const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {});
  121. const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern) : null; // eslint-disable-line require-unicode-regexp
  122. const capIsNewExceptions = calculateCapIsNewExceptions(config);
  123. const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern) : null; // eslint-disable-line require-unicode-regexp
  124. const listeners = {};
  125. const sourceCode = context.getSourceCode();
  126. //--------------------------------------------------------------------------
  127. // Helpers
  128. //--------------------------------------------------------------------------
  129. /**
  130. * Get exact callee name from expression
  131. * @param {ASTNode} node CallExpression or NewExpression node
  132. * @returns {string} name
  133. */
  134. function extractNameFromExpression(node) {
  135. let name = "";
  136. if (node.callee.type === "MemberExpression") {
  137. const property = node.callee.property;
  138. if (property.type === "Literal" && (typeof property.value === "string")) {
  139. name = property.value;
  140. } else if (property.type === "Identifier" && !node.callee.computed) {
  141. name = property.name;
  142. }
  143. } else {
  144. name = node.callee.name;
  145. }
  146. return name;
  147. }
  148. /**
  149. * Returns the capitalization state of the string -
  150. * Whether the first character is uppercase, lowercase, or non-alphabetic
  151. * @param {string} str String
  152. * @returns {string} capitalization state: "non-alpha", "lower", or "upper"
  153. */
  154. function getCap(str) {
  155. const firstChar = str.charAt(0);
  156. const firstCharLower = firstChar.toLowerCase();
  157. const firstCharUpper = firstChar.toUpperCase();
  158. if (firstCharLower === firstCharUpper) {
  159. // char has no uppercase variant, so it's non-alphabetic
  160. return "non-alpha";
  161. }
  162. if (firstChar === firstCharLower) {
  163. return "lower";
  164. }
  165. return "upper";
  166. }
  167. /**
  168. * Check if capitalization is allowed for a CallExpression
  169. * @param {Object} allowedMap Object mapping calleeName to a Boolean
  170. * @param {ASTNode} node CallExpression node
  171. * @param {string} calleeName Capitalized callee name from a CallExpression
  172. * @param {Object} pattern RegExp object from options pattern
  173. * @returns {boolean} Returns true if the callee may be capitalized
  174. */
  175. function isCapAllowed(allowedMap, node, calleeName, pattern) {
  176. const sourceText = sourceCode.getText(node.callee);
  177. if (allowedMap[calleeName] || allowedMap[sourceText]) {
  178. return true;
  179. }
  180. if (pattern && pattern.test(sourceText)) {
  181. return true;
  182. }
  183. if (calleeName === "UTC" && node.callee.type === "MemberExpression") {
  184. // allow if callee is Date.UTC
  185. return node.callee.object.type === "Identifier" &&
  186. node.callee.object.name === "Date";
  187. }
  188. return skipProperties && node.callee.type === "MemberExpression";
  189. }
  190. /**
  191. * Reports the given messageId for the given node. The location will be the start of the property or the callee.
  192. * @param {ASTNode} node CallExpression or NewExpression node.
  193. * @param {string} messageId The messageId to report.
  194. * @returns {void}
  195. */
  196. function report(node, messageId) {
  197. let callee = node.callee;
  198. if (callee.type === "MemberExpression") {
  199. callee = callee.property;
  200. }
  201. context.report({ node, loc: callee.loc.start, messageId });
  202. }
  203. //--------------------------------------------------------------------------
  204. // Public
  205. //--------------------------------------------------------------------------
  206. if (config.newIsCap) {
  207. listeners.NewExpression = function(node) {
  208. const constructorName = extractNameFromExpression(node);
  209. if (constructorName) {
  210. const capitalization = getCap(constructorName);
  211. const isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName, newIsCapExceptionPattern);
  212. if (!isAllowed) {
  213. report(node, "lower");
  214. }
  215. }
  216. };
  217. }
  218. if (config.capIsNew) {
  219. listeners.CallExpression = function(node) {
  220. const calleeName = extractNameFromExpression(node);
  221. if (calleeName) {
  222. const capitalization = getCap(calleeName);
  223. const isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName, capIsNewExceptionPattern);
  224. if (!isAllowed) {
  225. report(node, "upper");
  226. }
  227. }
  228. };
  229. }
  230. return listeners;
  231. }
  232. };