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.

comma-style.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /**
  2. * @fileoverview Comma style - enforces comma styles of two types: last and first
  3. * @author Vignesh Anand aka vegetableman
  4. */
  5. "use strict";
  6. const astUtils = require("../util/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "layout",
  13. docs: {
  14. description: "enforce consistent comma style",
  15. category: "Stylistic Issues",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/comma-style"
  18. },
  19. fixable: "code",
  20. schema: [
  21. {
  22. enum: ["first", "last"]
  23. },
  24. {
  25. type: "object",
  26. properties: {
  27. exceptions: {
  28. type: "object",
  29. additionalProperties: {
  30. type: "boolean"
  31. }
  32. }
  33. },
  34. additionalProperties: false
  35. }
  36. ],
  37. messages: {
  38. unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.",
  39. expectedCommaFirst: "',' should be placed first.",
  40. expectedCommaLast: "',' should be placed last."
  41. }
  42. },
  43. create(context) {
  44. const style = context.options[0] || "last",
  45. sourceCode = context.getSourceCode();
  46. const exceptions = {
  47. ArrayPattern: true,
  48. ArrowFunctionExpression: true,
  49. CallExpression: true,
  50. FunctionDeclaration: true,
  51. FunctionExpression: true,
  52. ImportDeclaration: true,
  53. ObjectPattern: true,
  54. NewExpression: true
  55. };
  56. if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(context.options[1], "exceptions")) {
  57. const keys = Object.keys(context.options[1].exceptions);
  58. for (let i = 0; i < keys.length; i++) {
  59. exceptions[keys[i]] = context.options[1].exceptions[keys[i]];
  60. }
  61. }
  62. //--------------------------------------------------------------------------
  63. // Helpers
  64. //--------------------------------------------------------------------------
  65. /**
  66. * Modified text based on the style
  67. * @param {string} styleType Style type
  68. * @param {string} text Source code text
  69. * @returns {string} modified text
  70. * @private
  71. */
  72. function getReplacedText(styleType, text) {
  73. switch (styleType) {
  74. case "between":
  75. return `,${text.replace("\n", "")}`;
  76. case "first":
  77. return `${text},`;
  78. case "last":
  79. return `,${text}`;
  80. default:
  81. return "";
  82. }
  83. }
  84. /**
  85. * Determines the fixer function for a given style.
  86. * @param {string} styleType comma style
  87. * @param {ASTNode} previousItemToken The token to check.
  88. * @param {ASTNode} commaToken The token to check.
  89. * @param {ASTNode} currentItemToken The token to check.
  90. * @returns {Function} Fixer function
  91. * @private
  92. */
  93. function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
  94. const text =
  95. sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
  96. sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
  97. const range = [previousItemToken.range[1], currentItemToken.range[0]];
  98. return function(fixer) {
  99. return fixer.replaceTextRange(range, getReplacedText(styleType, text));
  100. };
  101. }
  102. /**
  103. * Validates the spacing around single items in lists.
  104. * @param {Token} previousItemToken The last token from the previous item.
  105. * @param {Token} commaToken The token representing the comma.
  106. * @param {Token} currentItemToken The first token of the current item.
  107. * @param {Token} reportItem The item to use when reporting an error.
  108. * @returns {void}
  109. * @private
  110. */
  111. function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
  112. // if single line
  113. if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
  114. astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
  115. // do nothing.
  116. } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
  117. !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
  118. // lone comma
  119. context.report({
  120. node: reportItem,
  121. loc: {
  122. line: commaToken.loc.end.line,
  123. column: commaToken.loc.start.column
  124. },
  125. messageId: "unexpectedLineBeforeAndAfterComma",
  126. fix: getFixerFunction("between", previousItemToken, commaToken, currentItemToken)
  127. });
  128. } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
  129. context.report({
  130. node: reportItem,
  131. messageId: "expectedCommaFirst",
  132. fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
  133. });
  134. } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
  135. context.report({
  136. node: reportItem,
  137. loc: {
  138. line: commaToken.loc.end.line,
  139. column: commaToken.loc.end.column
  140. },
  141. messageId: "expectedCommaLast",
  142. fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
  143. });
  144. }
  145. }
  146. /**
  147. * Checks the comma placement with regards to a declaration/property/element
  148. * @param {ASTNode} node The binary expression node to check
  149. * @param {string} property The property of the node containing child nodes.
  150. * @private
  151. * @returns {void}
  152. */
  153. function validateComma(node, property) {
  154. const items = node[property],
  155. arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern");
  156. if (items.length > 1 || arrayLiteral) {
  157. // seed as opening [
  158. let previousItemToken = sourceCode.getFirstToken(node);
  159. items.forEach(item => {
  160. const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken,
  161. currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken),
  162. reportItem = item || currentItemToken;
  163. /*
  164. * This works by comparing three token locations:
  165. * - previousItemToken is the last token of the previous item
  166. * - commaToken is the location of the comma before the current item
  167. * - currentItemToken is the first token of the current item
  168. *
  169. * These values get switched around if item is undefined.
  170. * previousItemToken will refer to the last token not belonging
  171. * to the current item, which could be a comma or an opening
  172. * square bracket. currentItemToken could be a comma.
  173. *
  174. * All comparisons are done based on these tokens directly, so
  175. * they are always valid regardless of an undefined item.
  176. */
  177. if (astUtils.isCommaToken(commaToken)) {
  178. validateCommaItemSpacing(previousItemToken, commaToken,
  179. currentItemToken, reportItem);
  180. }
  181. if (item) {
  182. const tokenAfterItem = sourceCode.getTokenAfter(item, astUtils.isNotClosingParenToken);
  183. previousItemToken = tokenAfterItem
  184. ? sourceCode.getTokenBefore(tokenAfterItem)
  185. : sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1];
  186. }
  187. });
  188. /*
  189. * Special case for array literals that have empty last items, such
  190. * as [ 1, 2, ]. These arrays only have two items show up in the
  191. * AST, so we need to look at the token to verify that there's no
  192. * dangling comma.
  193. */
  194. if (arrayLiteral) {
  195. const lastToken = sourceCode.getLastToken(node),
  196. nextToLastToken = sourceCode.getTokenBefore(lastToken);
  197. if (astUtils.isCommaToken(nextToLastToken)) {
  198. validateCommaItemSpacing(
  199. sourceCode.getTokenBefore(nextToLastToken),
  200. nextToLastToken,
  201. lastToken,
  202. lastToken
  203. );
  204. }
  205. }
  206. }
  207. }
  208. //--------------------------------------------------------------------------
  209. // Public
  210. //--------------------------------------------------------------------------
  211. const nodes = {};
  212. if (!exceptions.VariableDeclaration) {
  213. nodes.VariableDeclaration = function(node) {
  214. validateComma(node, "declarations");
  215. };
  216. }
  217. if (!exceptions.ObjectExpression) {
  218. nodes.ObjectExpression = function(node) {
  219. validateComma(node, "properties");
  220. };
  221. }
  222. if (!exceptions.ObjectPattern) {
  223. nodes.ObjectPattern = function(node) {
  224. validateComma(node, "properties");
  225. };
  226. }
  227. if (!exceptions.ArrayExpression) {
  228. nodes.ArrayExpression = function(node) {
  229. validateComma(node, "elements");
  230. };
  231. }
  232. if (!exceptions.ArrayPattern) {
  233. nodes.ArrayPattern = function(node) {
  234. validateComma(node, "elements");
  235. };
  236. }
  237. if (!exceptions.FunctionDeclaration) {
  238. nodes.FunctionDeclaration = function(node) {
  239. validateComma(node, "params");
  240. };
  241. }
  242. if (!exceptions.FunctionExpression) {
  243. nodes.FunctionExpression = function(node) {
  244. validateComma(node, "params");
  245. };
  246. }
  247. if (!exceptions.ArrowFunctionExpression) {
  248. nodes.ArrowFunctionExpression = function(node) {
  249. validateComma(node, "params");
  250. };
  251. }
  252. if (!exceptions.CallExpression) {
  253. nodes.CallExpression = function(node) {
  254. validateComma(node, "arguments");
  255. };
  256. }
  257. if (!exceptions.ImportDeclaration) {
  258. nodes.ImportDeclaration = function(node) {
  259. validateComma(node, "specifiers");
  260. };
  261. }
  262. if (!exceptions.NewExpression) {
  263. nodes.NewExpression = function(node) {
  264. validateComma(node, "arguments");
  265. };
  266. }
  267. return nodes;
  268. }
  269. };