space-in-parens.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /**
  2. * @fileoverview Disallows or enforces spaces inside of parentheses.
  3. * @author Jonathan Rajavuori
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "layout",
  13. docs: {
  14. description: "enforce consistent spacing inside parentheses",
  15. category: "Stylistic Issues",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/space-in-parens"
  18. },
  19. fixable: "whitespace",
  20. schema: [
  21. {
  22. enum: ["always", "never"]
  23. },
  24. {
  25. type: "object",
  26. properties: {
  27. exceptions: {
  28. type: "array",
  29. items: {
  30. enum: ["{}", "[]", "()", "empty"]
  31. },
  32. uniqueItems: true
  33. }
  34. },
  35. additionalProperties: false
  36. }
  37. ],
  38. messages: {
  39. missingOpeningSpace: "There must be a space after this paren.",
  40. missingClosingSpace: "There must be a space before this paren.",
  41. rejectedOpeningSpace: "There should be no space after this paren.",
  42. rejectedClosingSpace: "There should be no space before this paren."
  43. }
  44. },
  45. create(context) {
  46. const ALWAYS = context.options[0] === "always",
  47. exceptionsArrayOptions = (context.options[1] && context.options[1].exceptions) || [],
  48. options = {};
  49. let exceptions;
  50. if (exceptionsArrayOptions.length) {
  51. options.braceException = exceptionsArrayOptions.includes("{}");
  52. options.bracketException = exceptionsArrayOptions.includes("[]");
  53. options.parenException = exceptionsArrayOptions.includes("()");
  54. options.empty = exceptionsArrayOptions.includes("empty");
  55. }
  56. /**
  57. * Produces an object with the opener and closer exception values
  58. * @returns {Object} `openers` and `closers` exception values
  59. * @private
  60. */
  61. function getExceptions() {
  62. const openers = [],
  63. closers = [];
  64. if (options.braceException) {
  65. openers.push("{");
  66. closers.push("}");
  67. }
  68. if (options.bracketException) {
  69. openers.push("[");
  70. closers.push("]");
  71. }
  72. if (options.parenException) {
  73. openers.push("(");
  74. closers.push(")");
  75. }
  76. if (options.empty) {
  77. openers.push(")");
  78. closers.push("(");
  79. }
  80. return {
  81. openers,
  82. closers
  83. };
  84. }
  85. //--------------------------------------------------------------------------
  86. // Helpers
  87. //--------------------------------------------------------------------------
  88. const sourceCode = context.getSourceCode();
  89. /**
  90. * Determines if a token is one of the exceptions for the opener paren
  91. * @param {Object} token The token to check
  92. * @returns {boolean} True if the token is one of the exceptions for the opener paren
  93. */
  94. function isOpenerException(token) {
  95. return exceptions.openers.includes(token.value);
  96. }
  97. /**
  98. * Determines if a token is one of the exceptions for the closer paren
  99. * @param {Object} token The token to check
  100. * @returns {boolean} True if the token is one of the exceptions for the closer paren
  101. */
  102. function isCloserException(token) {
  103. return exceptions.closers.includes(token.value);
  104. }
  105. /**
  106. * Determines if an opening paren is immediately followed by a required space
  107. * @param {Object} openingParenToken The paren token
  108. * @param {Object} tokenAfterOpeningParen The token after it
  109. * @returns {boolean} True if the opening paren is missing a required space
  110. */
  111. function openerMissingSpace(openingParenToken, tokenAfterOpeningParen) {
  112. if (sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) {
  113. return false;
  114. }
  115. if (!options.empty && astUtils.isClosingParenToken(tokenAfterOpeningParen)) {
  116. return false;
  117. }
  118. if (ALWAYS) {
  119. return !isOpenerException(tokenAfterOpeningParen);
  120. }
  121. return isOpenerException(tokenAfterOpeningParen);
  122. }
  123. /**
  124. * Determines if an opening paren is immediately followed by a disallowed space
  125. * @param {Object} openingParenToken The paren token
  126. * @param {Object} tokenAfterOpeningParen The token after it
  127. * @returns {boolean} True if the opening paren has a disallowed space
  128. */
  129. function openerRejectsSpace(openingParenToken, tokenAfterOpeningParen) {
  130. if (!astUtils.isTokenOnSameLine(openingParenToken, tokenAfterOpeningParen)) {
  131. return false;
  132. }
  133. if (tokenAfterOpeningParen.type === "Line") {
  134. return false;
  135. }
  136. if (!sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) {
  137. return false;
  138. }
  139. if (ALWAYS) {
  140. return isOpenerException(tokenAfterOpeningParen);
  141. }
  142. return !isOpenerException(tokenAfterOpeningParen);
  143. }
  144. /**
  145. * Determines if a closing paren is immediately preceded by a required space
  146. * @param {Object} tokenBeforeClosingParen The token before the paren
  147. * @param {Object} closingParenToken The paren token
  148. * @returns {boolean} True if the closing paren is missing a required space
  149. */
  150. function closerMissingSpace(tokenBeforeClosingParen, closingParenToken) {
  151. if (sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) {
  152. return false;
  153. }
  154. if (!options.empty && astUtils.isOpeningParenToken(tokenBeforeClosingParen)) {
  155. return false;
  156. }
  157. if (ALWAYS) {
  158. return !isCloserException(tokenBeforeClosingParen);
  159. }
  160. return isCloserException(tokenBeforeClosingParen);
  161. }
  162. /**
  163. * Determines if a closer paren is immediately preceded by a disallowed space
  164. * @param {Object} tokenBeforeClosingParen The token before the paren
  165. * @param {Object} closingParenToken The paren token
  166. * @returns {boolean} True if the closing paren has a disallowed space
  167. */
  168. function closerRejectsSpace(tokenBeforeClosingParen, closingParenToken) {
  169. if (!astUtils.isTokenOnSameLine(tokenBeforeClosingParen, closingParenToken)) {
  170. return false;
  171. }
  172. if (!sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) {
  173. return false;
  174. }
  175. if (ALWAYS) {
  176. return isCloserException(tokenBeforeClosingParen);
  177. }
  178. return !isCloserException(tokenBeforeClosingParen);
  179. }
  180. //--------------------------------------------------------------------------
  181. // Public
  182. //--------------------------------------------------------------------------
  183. return {
  184. Program: function checkParenSpaces(node) {
  185. exceptions = getExceptions();
  186. const tokens = sourceCode.tokensAndComments;
  187. tokens.forEach((token, i) => {
  188. const prevToken = tokens[i - 1];
  189. const nextToken = tokens[i + 1];
  190. // if token is not an opening or closing paren token, do nothing
  191. if (!astUtils.isOpeningParenToken(token) && !astUtils.isClosingParenToken(token)) {
  192. return;
  193. }
  194. // if token is an opening paren and is not followed by a required space
  195. if (token.value === "(" && openerMissingSpace(token, nextToken)) {
  196. context.report({
  197. node,
  198. loc: token.loc,
  199. messageId: "missingOpeningSpace",
  200. fix(fixer) {
  201. return fixer.insertTextAfter(token, " ");
  202. }
  203. });
  204. }
  205. // if token is an opening paren and is followed by a disallowed space
  206. if (token.value === "(" && openerRejectsSpace(token, nextToken)) {
  207. context.report({
  208. node,
  209. loc: { start: token.loc.end, end: nextToken.loc.start },
  210. messageId: "rejectedOpeningSpace",
  211. fix(fixer) {
  212. return fixer.removeRange([token.range[1], nextToken.range[0]]);
  213. }
  214. });
  215. }
  216. // if token is a closing paren and is not preceded by a required space
  217. if (token.value === ")" && closerMissingSpace(prevToken, token)) {
  218. context.report({
  219. node,
  220. loc: token.loc,
  221. messageId: "missingClosingSpace",
  222. fix(fixer) {
  223. return fixer.insertTextBefore(token, " ");
  224. }
  225. });
  226. }
  227. // if token is a closing paren and is preceded by a disallowed space
  228. if (token.value === ")" && closerRejectsSpace(prevToken, token)) {
  229. context.report({
  230. node,
  231. loc: { start: prevToken.loc.end, end: token.loc.start },
  232. messageId: "rejectedClosingSpace",
  233. fix(fixer) {
  234. return fixer.removeRange([prevToken.range[1], token.range[0]]);
  235. }
  236. });
  237. }
  238. });
  239. }
  240. };
  241. }
  242. };