object-shorthand.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /**
  2. * @fileoverview Rule to enforce concise object methods and properties.
  3. * @author Jamund Ferguson
  4. */
  5. "use strict";
  6. const OPTIONS = {
  7. always: "always",
  8. never: "never",
  9. methods: "methods",
  10. properties: "properties",
  11. consistent: "consistent",
  12. consistentAsNeeded: "consistent-as-needed"
  13. };
  14. //------------------------------------------------------------------------------
  15. // Requirements
  16. //------------------------------------------------------------------------------
  17. const astUtils = require("./utils/ast-utils");
  18. //------------------------------------------------------------------------------
  19. // Rule Definition
  20. //------------------------------------------------------------------------------
  21. /** @type {import('../shared/types').Rule} */
  22. module.exports = {
  23. meta: {
  24. type: "suggestion",
  25. docs: {
  26. description: "Require or disallow method and property shorthand syntax for object literals",
  27. recommended: false,
  28. url: "https://eslint.org/docs/latest/rules/object-shorthand"
  29. },
  30. fixable: "code",
  31. schema: {
  32. anyOf: [
  33. {
  34. type: "array",
  35. items: [
  36. {
  37. enum: ["always", "methods", "properties", "never", "consistent", "consistent-as-needed"]
  38. }
  39. ],
  40. minItems: 0,
  41. maxItems: 1
  42. },
  43. {
  44. type: "array",
  45. items: [
  46. {
  47. enum: ["always", "methods", "properties"]
  48. },
  49. {
  50. type: "object",
  51. properties: {
  52. avoidQuotes: {
  53. type: "boolean"
  54. }
  55. },
  56. additionalProperties: false
  57. }
  58. ],
  59. minItems: 0,
  60. maxItems: 2
  61. },
  62. {
  63. type: "array",
  64. items: [
  65. {
  66. enum: ["always", "methods"]
  67. },
  68. {
  69. type: "object",
  70. properties: {
  71. ignoreConstructors: {
  72. type: "boolean"
  73. },
  74. methodsIgnorePattern: {
  75. type: "string"
  76. },
  77. avoidQuotes: {
  78. type: "boolean"
  79. },
  80. avoidExplicitReturnArrows: {
  81. type: "boolean"
  82. }
  83. },
  84. additionalProperties: false
  85. }
  86. ],
  87. minItems: 0,
  88. maxItems: 2
  89. }
  90. ]
  91. },
  92. messages: {
  93. expectedAllPropertiesShorthanded: "Expected shorthand for all properties.",
  94. expectedLiteralMethodLongform: "Expected longform method syntax for string literal keys.",
  95. expectedPropertyShorthand: "Expected property shorthand.",
  96. expectedPropertyLongform: "Expected longform property syntax.",
  97. expectedMethodShorthand: "Expected method shorthand.",
  98. expectedMethodLongform: "Expected longform method syntax.",
  99. unexpectedMix: "Unexpected mix of shorthand and non-shorthand properties."
  100. }
  101. },
  102. create(context) {
  103. const APPLY = context.options[0] || OPTIONS.always;
  104. const APPLY_TO_METHODS = APPLY === OPTIONS.methods || APPLY === OPTIONS.always;
  105. const APPLY_TO_PROPS = APPLY === OPTIONS.properties || APPLY === OPTIONS.always;
  106. const APPLY_NEVER = APPLY === OPTIONS.never;
  107. const APPLY_CONSISTENT = APPLY === OPTIONS.consistent;
  108. const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded;
  109. const PARAMS = context.options[1] || {};
  110. const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors;
  111. const METHODS_IGNORE_PATTERN = PARAMS.methodsIgnorePattern
  112. ? new RegExp(PARAMS.methodsIgnorePattern, "u")
  113. : null;
  114. const AVOID_QUOTES = PARAMS.avoidQuotes;
  115. const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows;
  116. const sourceCode = context.sourceCode;
  117. //--------------------------------------------------------------------------
  118. // Helpers
  119. //--------------------------------------------------------------------------
  120. const CTOR_PREFIX_REGEX = /[^_$0-9]/u;
  121. /**
  122. * Determines if the first character of the name is a capital letter.
  123. * @param {string} name The name of the node to evaluate.
  124. * @returns {boolean} True if the first character of the property name is a capital letter, false if not.
  125. * @private
  126. */
  127. function isConstructor(name) {
  128. const match = CTOR_PREFIX_REGEX.exec(name);
  129. // Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8'
  130. if (!match) {
  131. return false;
  132. }
  133. const firstChar = name.charAt(match.index);
  134. return firstChar === firstChar.toUpperCase();
  135. }
  136. /**
  137. * Determines if the property can have a shorthand form.
  138. * @param {ASTNode} property Property AST node
  139. * @returns {boolean} True if the property can have a shorthand form
  140. * @private
  141. */
  142. function canHaveShorthand(property) {
  143. return (property.kind !== "set" && property.kind !== "get" && property.type !== "SpreadElement" && property.type !== "SpreadProperty" && property.type !== "ExperimentalSpreadProperty");
  144. }
  145. /**
  146. * Checks whether a node is a string literal.
  147. * @param {ASTNode} node Any AST node.
  148. * @returns {boolean} `true` if it is a string literal.
  149. */
  150. function isStringLiteral(node) {
  151. return node.type === "Literal" && typeof node.value === "string";
  152. }
  153. /**
  154. * Determines if the property is a shorthand or not.
  155. * @param {ASTNode} property Property AST node
  156. * @returns {boolean} True if the property is considered shorthand, false if not.
  157. * @private
  158. */
  159. function isShorthand(property) {
  160. // property.method is true when `{a(){}}`.
  161. return (property.shorthand || property.method);
  162. }
  163. /**
  164. * Determines if the property's key and method or value are named equally.
  165. * @param {ASTNode} property Property AST node
  166. * @returns {boolean} True if the key and value are named equally, false if not.
  167. * @private
  168. */
  169. function isRedundant(property) {
  170. const value = property.value;
  171. if (value.type === "FunctionExpression") {
  172. return !value.id; // Only anonymous should be shorthand method.
  173. }
  174. if (value.type === "Identifier") {
  175. return astUtils.getStaticPropertyName(property) === value.name;
  176. }
  177. return false;
  178. }
  179. /**
  180. * Ensures that an object's properties are consistently shorthand, or not shorthand at all.
  181. * @param {ASTNode} node Property AST node
  182. * @param {boolean} checkRedundancy Whether to check longform redundancy
  183. * @returns {void}
  184. */
  185. function checkConsistency(node, checkRedundancy) {
  186. // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand.
  187. const properties = node.properties.filter(canHaveShorthand);
  188. // Do we still have properties left after filtering the getters and setters?
  189. if (properties.length > 0) {
  190. const shorthandProperties = properties.filter(isShorthand);
  191. /*
  192. * If we do not have an equal number of longform properties as
  193. * shorthand properties, we are using the annotations inconsistently
  194. */
  195. if (shorthandProperties.length !== properties.length) {
  196. // We have at least 1 shorthand property
  197. if (shorthandProperties.length > 0) {
  198. context.report({ node, messageId: "unexpectedMix" });
  199. } else if (checkRedundancy) {
  200. /*
  201. * If all properties of the object contain a method or value with a name matching it's key,
  202. * all the keys are redundant.
  203. */
  204. const canAlwaysUseShorthand = properties.every(isRedundant);
  205. if (canAlwaysUseShorthand) {
  206. context.report({ node, messageId: "expectedAllPropertiesShorthanded" });
  207. }
  208. }
  209. }
  210. }
  211. }
  212. /**
  213. * Fixes a FunctionExpression node by making it into a shorthand property.
  214. * @param {SourceCodeFixer} fixer The fixer object
  215. * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value
  216. * @returns {Object} A fix for this node
  217. */
  218. function makeFunctionShorthand(fixer, node) {
  219. const firstKeyToken = node.computed
  220. ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken)
  221. : sourceCode.getFirstToken(node.key);
  222. const lastKeyToken = node.computed
  223. ? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken)
  224. : sourceCode.getLastToken(node.key);
  225. const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
  226. let keyPrefix = "";
  227. // key: /* */ () => {}
  228. if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) {
  229. return null;
  230. }
  231. if (node.value.async) {
  232. keyPrefix += "async ";
  233. }
  234. if (node.value.generator) {
  235. keyPrefix += "*";
  236. }
  237. const fixRange = [firstKeyToken.range[0], node.range[1]];
  238. const methodPrefix = keyPrefix + keyText;
  239. if (node.value.type === "FunctionExpression") {
  240. const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function");
  241. const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken;
  242. return fixer.replaceTextRange(
  243. fixRange,
  244. methodPrefix + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1])
  245. );
  246. }
  247. const arrowToken = sourceCode.getTokenBefore(node.value.body, astUtils.isArrowToken);
  248. const fnBody = sourceCode.text.slice(arrowToken.range[1], node.value.range[1]);
  249. // First token should not be `async`
  250. const firstValueToken = sourceCode.getFirstToken(node.value, {
  251. skip: node.value.async ? 1 : 0
  252. });
  253. const sliceStart = firstValueToken.range[0];
  254. const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1];
  255. const shouldAddParens = node.value.params.length === 1 && node.value.params[0].range[0] === sliceStart;
  256. const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd);
  257. const newParamText = shouldAddParens ? `(${oldParamText})` : oldParamText;
  258. return fixer.replaceTextRange(
  259. fixRange,
  260. methodPrefix + newParamText + fnBody
  261. );
  262. }
  263. /**
  264. * Fixes a FunctionExpression node by making it into a longform property.
  265. * @param {SourceCodeFixer} fixer The fixer object
  266. * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value
  267. * @returns {Object} A fix for this node
  268. */
  269. function makeFunctionLongform(fixer, node) {
  270. const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key);
  271. const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key);
  272. const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
  273. let functionHeader = "function";
  274. if (node.value.async) {
  275. functionHeader = `async ${functionHeader}`;
  276. }
  277. if (node.value.generator) {
  278. functionHeader = `${functionHeader}*`;
  279. }
  280. return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`);
  281. }
  282. /*
  283. * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`),
  284. * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is
  285. * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical
  286. * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered,
  287. * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited.
  288. * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them
  289. * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule,
  290. * because converting it into a method would change the value of one of the lexical identifiers.
  291. */
  292. const lexicalScopeStack = [];
  293. const arrowsWithLexicalIdentifiers = new WeakSet();
  294. const argumentsIdentifiers = new WeakSet();
  295. /**
  296. * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack.
  297. * Also, this marks all `arguments` identifiers so that they can be detected later.
  298. * @param {ASTNode} node The node representing the function.
  299. * @returns {void}
  300. */
  301. function enterFunction(node) {
  302. lexicalScopeStack.unshift(new Set());
  303. sourceCode.getScope(node).variables.filter(variable => variable.name === "arguments").forEach(variable => {
  304. variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier));
  305. });
  306. }
  307. /**
  308. * Exits a function. This pops the current set of arrow functions off the lexical scope stack.
  309. * @returns {void}
  310. */
  311. function exitFunction() {
  312. lexicalScopeStack.shift();
  313. }
  314. /**
  315. * Marks the current function as having a lexical keyword. This implies that all arrow functions
  316. * in the current lexical scope contain a reference to this lexical keyword.
  317. * @returns {void}
  318. */
  319. function reportLexicalIdentifier() {
  320. lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction));
  321. }
  322. //--------------------------------------------------------------------------
  323. // Public
  324. //--------------------------------------------------------------------------
  325. return {
  326. Program: enterFunction,
  327. FunctionDeclaration: enterFunction,
  328. FunctionExpression: enterFunction,
  329. "Program:exit": exitFunction,
  330. "FunctionDeclaration:exit": exitFunction,
  331. "FunctionExpression:exit": exitFunction,
  332. ArrowFunctionExpression(node) {
  333. lexicalScopeStack[0].add(node);
  334. },
  335. "ArrowFunctionExpression:exit"(node) {
  336. lexicalScopeStack[0].delete(node);
  337. },
  338. ThisExpression: reportLexicalIdentifier,
  339. Super: reportLexicalIdentifier,
  340. MetaProperty(node) {
  341. if (node.meta.name === "new" && node.property.name === "target") {
  342. reportLexicalIdentifier();
  343. }
  344. },
  345. Identifier(node) {
  346. if (argumentsIdentifiers.has(node)) {
  347. reportLexicalIdentifier();
  348. }
  349. },
  350. ObjectExpression(node) {
  351. if (APPLY_CONSISTENT) {
  352. checkConsistency(node, false);
  353. } else if (APPLY_CONSISTENT_AS_NEEDED) {
  354. checkConsistency(node, true);
  355. }
  356. },
  357. "Property:exit"(node) {
  358. const isConciseProperty = node.method || node.shorthand;
  359. // Ignore destructuring assignment
  360. if (node.parent.type === "ObjectPattern") {
  361. return;
  362. }
  363. // getters and setters are ignored
  364. if (node.kind === "get" || node.kind === "set") {
  365. return;
  366. }
  367. // only computed methods can fail the following checks
  368. if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") {
  369. return;
  370. }
  371. //--------------------------------------------------------------
  372. // Checks for property/method shorthand.
  373. if (isConciseProperty) {
  374. if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) {
  375. const messageId = APPLY_NEVER ? "expectedMethodLongform" : "expectedLiteralMethodLongform";
  376. // { x() {} } should be written as { x: function() {} }
  377. context.report({
  378. node,
  379. messageId,
  380. fix: fixer => makeFunctionLongform(fixer, node)
  381. });
  382. } else if (APPLY_NEVER) {
  383. // { x } should be written as { x: x }
  384. context.report({
  385. node,
  386. messageId: "expectedPropertyLongform",
  387. fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`)
  388. });
  389. }
  390. } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) {
  391. if (IGNORE_CONSTRUCTORS && node.key.type === "Identifier" && isConstructor(node.key.name)) {
  392. return;
  393. }
  394. if (METHODS_IGNORE_PATTERN) {
  395. const propertyName = astUtils.getStaticPropertyName(node);
  396. if (propertyName !== null && METHODS_IGNORE_PATTERN.test(propertyName)) {
  397. return;
  398. }
  399. }
  400. if (AVOID_QUOTES && isStringLiteral(node.key)) {
  401. return;
  402. }
  403. // {[x]: function(){}} should be written as {[x]() {}}
  404. if (node.value.type === "FunctionExpression" ||
  405. node.value.type === "ArrowFunctionExpression" &&
  406. node.value.body.type === "BlockStatement" &&
  407. AVOID_EXPLICIT_RETURN_ARROWS &&
  408. !arrowsWithLexicalIdentifiers.has(node.value)
  409. ) {
  410. context.report({
  411. node,
  412. messageId: "expectedMethodShorthand",
  413. fix: fixer => makeFunctionShorthand(fixer, node)
  414. });
  415. }
  416. } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) {
  417. // {x: x} should be written as {x}
  418. context.report({
  419. node,
  420. messageId: "expectedPropertyShorthand",
  421. fix(fixer) {
  422. // x: /* */ x
  423. // x: (/* */ x)
  424. if (sourceCode.getCommentsInside(node).length > 0) {
  425. return null;
  426. }
  427. return fixer.replaceText(node, node.value.name);
  428. }
  429. });
  430. } else if (node.value.type === "Identifier" && node.key.type === "Literal" && node.key.value === node.value.name && APPLY_TO_PROPS) {
  431. if (AVOID_QUOTES) {
  432. return;
  433. }
  434. // {"x": x} should be written as {x}
  435. context.report({
  436. node,
  437. messageId: "expectedPropertyShorthand",
  438. fix(fixer) {
  439. // "x": /* */ x
  440. // "x": (/* */ x)
  441. if (sourceCode.getCommentsInside(node).length > 0) {
  442. return null;
  443. }
  444. return fixer.replaceText(node, node.value.name);
  445. }
  446. });
  447. }
  448. }
  449. };
  450. }
  451. };