Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

object-shorthand.js 20KB

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