object-shorthand.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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/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.getSourceCode();
  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. let shouldAddParensAroundParameters = false;
  250. let tokenBeforeParams;
  251. if (node.value.params.length === 0) {
  252. tokenBeforeParams = sourceCode.getFirstToken(node.value, astUtils.isOpeningParenToken);
  253. } else {
  254. tokenBeforeParams = sourceCode.getTokenBefore(node.value.params[0]);
  255. }
  256. if (node.value.params.length === 1) {
  257. const hasParen = astUtils.isOpeningParenToken(tokenBeforeParams);
  258. const isTokenOutsideNode = tokenBeforeParams.range[0] < node.range[0];
  259. shouldAddParensAroundParameters = !hasParen || isTokenOutsideNode;
  260. }
  261. const sliceStart = shouldAddParensAroundParameters
  262. ? node.value.params[0].range[0]
  263. : tokenBeforeParams.range[0];
  264. const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1];
  265. const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd);
  266. const newParamText = shouldAddParensAroundParameters ? `(${oldParamText})` : oldParamText;
  267. return fixer.replaceTextRange(
  268. fixRange,
  269. methodPrefix + newParamText + fnBody
  270. );
  271. }
  272. /**
  273. * Fixes a FunctionExpression node by making it into a longform property.
  274. * @param {SourceCodeFixer} fixer The fixer object
  275. * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value
  276. * @returns {Object} A fix for this node
  277. */
  278. function makeFunctionLongform(fixer, node) {
  279. const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key);
  280. const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key);
  281. const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
  282. let functionHeader = "function";
  283. if (node.value.async) {
  284. functionHeader = `async ${functionHeader}`;
  285. }
  286. if (node.value.generator) {
  287. functionHeader = `${functionHeader}*`;
  288. }
  289. return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`);
  290. }
  291. /*
  292. * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`),
  293. * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is
  294. * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical
  295. * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered,
  296. * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited.
  297. * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them
  298. * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule,
  299. * because converting it into a method would change the value of one of the lexical identifiers.
  300. */
  301. const lexicalScopeStack = [];
  302. const arrowsWithLexicalIdentifiers = new WeakSet();
  303. const argumentsIdentifiers = new WeakSet();
  304. /**
  305. * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack.
  306. * Also, this marks all `arguments` identifiers so that they can be detected later.
  307. * @returns {void}
  308. */
  309. function enterFunction() {
  310. lexicalScopeStack.unshift(new Set());
  311. context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => {
  312. variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier));
  313. });
  314. }
  315. /**
  316. * Exits a function. This pops the current set of arrow functions off the lexical scope stack.
  317. * @returns {void}
  318. */
  319. function exitFunction() {
  320. lexicalScopeStack.shift();
  321. }
  322. /**
  323. * Marks the current function as having a lexical keyword. This implies that all arrow functions
  324. * in the current lexical scope contain a reference to this lexical keyword.
  325. * @returns {void}
  326. */
  327. function reportLexicalIdentifier() {
  328. lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction));
  329. }
  330. //--------------------------------------------------------------------------
  331. // Public
  332. //--------------------------------------------------------------------------
  333. return {
  334. Program: enterFunction,
  335. FunctionDeclaration: enterFunction,
  336. FunctionExpression: enterFunction,
  337. "Program:exit": exitFunction,
  338. "FunctionDeclaration:exit": exitFunction,
  339. "FunctionExpression:exit": exitFunction,
  340. ArrowFunctionExpression(node) {
  341. lexicalScopeStack[0].add(node);
  342. },
  343. "ArrowFunctionExpression:exit"(node) {
  344. lexicalScopeStack[0].delete(node);
  345. },
  346. ThisExpression: reportLexicalIdentifier,
  347. Super: reportLexicalIdentifier,
  348. MetaProperty(node) {
  349. if (node.meta.name === "new" && node.property.name === "target") {
  350. reportLexicalIdentifier();
  351. }
  352. },
  353. Identifier(node) {
  354. if (argumentsIdentifiers.has(node)) {
  355. reportLexicalIdentifier();
  356. }
  357. },
  358. ObjectExpression(node) {
  359. if (APPLY_CONSISTENT) {
  360. checkConsistency(node, false);
  361. } else if (APPLY_CONSISTENT_AS_NEEDED) {
  362. checkConsistency(node, true);
  363. }
  364. },
  365. "Property:exit"(node) {
  366. const isConciseProperty = node.method || node.shorthand;
  367. // Ignore destructuring assignment
  368. if (node.parent.type === "ObjectPattern") {
  369. return;
  370. }
  371. // getters and setters are ignored
  372. if (node.kind === "get" || node.kind === "set") {
  373. return;
  374. }
  375. // only computed methods can fail the following checks
  376. if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") {
  377. return;
  378. }
  379. //--------------------------------------------------------------
  380. // Checks for property/method shorthand.
  381. if (isConciseProperty) {
  382. if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) {
  383. const messageId = APPLY_NEVER ? "expectedMethodLongform" : "expectedLiteralMethodLongform";
  384. // { x() {} } should be written as { x: function() {} }
  385. context.report({
  386. node,
  387. messageId,
  388. fix: fixer => makeFunctionLongform(fixer, node)
  389. });
  390. } else if (APPLY_NEVER) {
  391. // { x } should be written as { x: x }
  392. context.report({
  393. node,
  394. messageId: "expectedPropertyLongform",
  395. fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`)
  396. });
  397. }
  398. } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) {
  399. if (IGNORE_CONSTRUCTORS && node.key.type === "Identifier" && isConstructor(node.key.name)) {
  400. return;
  401. }
  402. if (METHODS_IGNORE_PATTERN) {
  403. const propertyName = astUtils.getStaticPropertyName(node);
  404. if (propertyName !== null && METHODS_IGNORE_PATTERN.test(propertyName)) {
  405. return;
  406. }
  407. }
  408. if (AVOID_QUOTES && isStringLiteral(node.key)) {
  409. return;
  410. }
  411. // {[x]: function(){}} should be written as {[x]() {}}
  412. if (node.value.type === "FunctionExpression" ||
  413. node.value.type === "ArrowFunctionExpression" &&
  414. node.value.body.type === "BlockStatement" &&
  415. AVOID_EXPLICIT_RETURN_ARROWS &&
  416. !arrowsWithLexicalIdentifiers.has(node.value)
  417. ) {
  418. context.report({
  419. node,
  420. messageId: "expectedMethodShorthand",
  421. fix: fixer => makeFunctionShorthand(fixer, node)
  422. });
  423. }
  424. } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) {
  425. // {x: x} should be written as {x}
  426. context.report({
  427. node,
  428. messageId: "expectedPropertyShorthand",
  429. fix(fixer) {
  430. return fixer.replaceText(node, node.value.name);
  431. }
  432. });
  433. } else if (node.value.type === "Identifier" && node.key.type === "Literal" && node.key.value === node.value.name && APPLY_TO_PROPS) {
  434. if (AVOID_QUOTES) {
  435. return;
  436. }
  437. // {"x": x} should be written as {x}
  438. context.report({
  439. node,
  440. messageId: "expectedPropertyShorthand",
  441. fix(fixer) {
  442. return fixer.replaceText(node, node.value.name);
  443. }
  444. });
  445. }
  446. }
  447. };
  448. }
  449. };