项目原始demo,不改动
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
Це архівний репозитарій. Ви можете переглядати і клонувати файли, але не можете робити пуш або відкривати питання/запити.

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