object-shorthand.js 21 KB

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