object-curly-spacing.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /**
  2. * @fileoverview Disallows or enforces spaces inside of object literals.
  3. * @author Jamund Ferguson
  4. * @deprecated in ESLint v8.53.0
  5. */
  6. "use strict";
  7. const astUtils = require("./utils/ast-utils");
  8. //------------------------------------------------------------------------------
  9. // Rule Definition
  10. //------------------------------------------------------------------------------
  11. /** @type {import('../types').Rule.RuleModule} */
  12. module.exports = {
  13. meta: {
  14. deprecated: {
  15. message: "Formatting rules are being moved out of ESLint core.",
  16. url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
  17. deprecatedSince: "8.53.0",
  18. availableUntil: "11.0.0",
  19. replacedBy: [
  20. {
  21. message:
  22. "ESLint Stylistic now maintains deprecated stylistic core rules.",
  23. url: "https://eslint.style/guide/migration",
  24. plugin: {
  25. name: "@stylistic/eslint-plugin",
  26. url: "https://eslint.style",
  27. },
  28. rule: {
  29. name: "object-curly-spacing",
  30. url: "https://eslint.style/rules/object-curly-spacing",
  31. },
  32. },
  33. ],
  34. },
  35. type: "layout",
  36. docs: {
  37. description: "Enforce consistent spacing inside braces",
  38. recommended: false,
  39. url: "https://eslint.org/docs/latest/rules/object-curly-spacing",
  40. },
  41. fixable: "whitespace",
  42. schema: [
  43. {
  44. enum: ["always", "never"],
  45. },
  46. {
  47. type: "object",
  48. properties: {
  49. arraysInObjects: {
  50. type: "boolean",
  51. },
  52. objectsInObjects: {
  53. type: "boolean",
  54. },
  55. },
  56. additionalProperties: false,
  57. },
  58. ],
  59. messages: {
  60. requireSpaceBefore: "A space is required before '{{token}}'.",
  61. requireSpaceAfter: "A space is required after '{{token}}'.",
  62. unexpectedSpaceBefore:
  63. "There should be no space before '{{token}}'.",
  64. unexpectedSpaceAfter: "There should be no space after '{{token}}'.",
  65. },
  66. },
  67. create(context) {
  68. const spaced = context.options[0] === "always",
  69. sourceCode = context.sourceCode;
  70. /**
  71. * Determines whether an option is set, relative to the spacing option.
  72. * If spaced is "always", then check whether option is set to false.
  73. * If spaced is "never", then check whether option is set to true.
  74. * @param {Object} option The option to exclude.
  75. * @returns {boolean} Whether or not the property is excluded.
  76. */
  77. function isOptionSet(option) {
  78. return context.options[1]
  79. ? context.options[1][option] === !spaced
  80. : false;
  81. }
  82. const options = {
  83. spaced,
  84. arraysInObjectsException: isOptionSet("arraysInObjects"),
  85. objectsInObjectsException: isOptionSet("objectsInObjects"),
  86. };
  87. //--------------------------------------------------------------------------
  88. // Helpers
  89. //--------------------------------------------------------------------------
  90. /**
  91. * Reports that there shouldn't be a space after the first token
  92. * @param {ASTNode} node The node to report in the event of an error.
  93. * @param {Token} token The token to use for the report.
  94. * @returns {void}
  95. */
  96. function reportNoBeginningSpace(node, token) {
  97. const nextToken = context.sourceCode.getTokenAfter(token, {
  98. includeComments: true,
  99. });
  100. context.report({
  101. node,
  102. loc: { start: token.loc.end, end: nextToken.loc.start },
  103. messageId: "unexpectedSpaceAfter",
  104. data: {
  105. token: token.value,
  106. },
  107. fix(fixer) {
  108. return fixer.removeRange([
  109. token.range[1],
  110. nextToken.range[0],
  111. ]);
  112. },
  113. });
  114. }
  115. /**
  116. * Reports that there shouldn't be a space before the last token
  117. * @param {ASTNode} node The node to report in the event of an error.
  118. * @param {Token} token The token to use for the report.
  119. * @returns {void}
  120. */
  121. function reportNoEndingSpace(node, token) {
  122. const previousToken = context.sourceCode.getTokenBefore(token, {
  123. includeComments: true,
  124. });
  125. context.report({
  126. node,
  127. loc: { start: previousToken.loc.end, end: token.loc.start },
  128. messageId: "unexpectedSpaceBefore",
  129. data: {
  130. token: token.value,
  131. },
  132. fix(fixer) {
  133. return fixer.removeRange([
  134. previousToken.range[1],
  135. token.range[0],
  136. ]);
  137. },
  138. });
  139. }
  140. /**
  141. * Reports that there should be a space after the first token
  142. * @param {ASTNode} node The node to report in the event of an error.
  143. * @param {Token} token The token to use for the report.
  144. * @returns {void}
  145. */
  146. function reportRequiredBeginningSpace(node, token) {
  147. context.report({
  148. node,
  149. loc: token.loc,
  150. messageId: "requireSpaceAfter",
  151. data: {
  152. token: token.value,
  153. },
  154. fix(fixer) {
  155. return fixer.insertTextAfter(token, " ");
  156. },
  157. });
  158. }
  159. /**
  160. * Reports that there should be a space before the last token
  161. * @param {ASTNode} node The node to report in the event of an error.
  162. * @param {Token} token The token to use for the report.
  163. * @returns {void}
  164. */
  165. function reportRequiredEndingSpace(node, token) {
  166. context.report({
  167. node,
  168. loc: token.loc,
  169. messageId: "requireSpaceBefore",
  170. data: {
  171. token: token.value,
  172. },
  173. fix(fixer) {
  174. return fixer.insertTextBefore(token, " ");
  175. },
  176. });
  177. }
  178. /**
  179. * Determines if spacing in curly braces is valid.
  180. * @param {ASTNode} node The AST node to check.
  181. * @param {Token} first The first token to check (should be the opening brace)
  182. * @param {Token} second The second token to check (should be first after the opening brace)
  183. * @param {Token} penultimate The penultimate token to check (should be last before closing brace)
  184. * @param {Token} last The last token to check (should be closing brace)
  185. * @returns {void}
  186. */
  187. function validateBraceSpacing(node, first, second, penultimate, last) {
  188. if (astUtils.isTokenOnSameLine(first, second)) {
  189. const firstSpaced = sourceCode.isSpaceBetweenTokens(
  190. first,
  191. second,
  192. );
  193. if (options.spaced && !firstSpaced) {
  194. reportRequiredBeginningSpace(node, first);
  195. }
  196. if (!options.spaced && firstSpaced && second.type !== "Line") {
  197. reportNoBeginningSpace(node, first);
  198. }
  199. }
  200. if (astUtils.isTokenOnSameLine(penultimate, last)) {
  201. const shouldCheckPenultimate =
  202. (options.arraysInObjectsException &&
  203. astUtils.isClosingBracketToken(penultimate)) ||
  204. (options.objectsInObjectsException &&
  205. astUtils.isClosingBraceToken(penultimate));
  206. const penultimateType =
  207. shouldCheckPenultimate &&
  208. sourceCode.getNodeByRangeIndex(penultimate.range[0]).type;
  209. const closingCurlyBraceMustBeSpaced =
  210. (options.arraysInObjectsException &&
  211. penultimateType === "ArrayExpression") ||
  212. (options.objectsInObjectsException &&
  213. (penultimateType === "ObjectExpression" ||
  214. penultimateType === "ObjectPattern"))
  215. ? !options.spaced
  216. : options.spaced;
  217. const lastSpaced = sourceCode.isSpaceBetweenTokens(
  218. penultimate,
  219. last,
  220. );
  221. if (closingCurlyBraceMustBeSpaced && !lastSpaced) {
  222. reportRequiredEndingSpace(node, last);
  223. }
  224. if (!closingCurlyBraceMustBeSpaced && lastSpaced) {
  225. reportNoEndingSpace(node, last);
  226. }
  227. }
  228. }
  229. /**
  230. * Gets '}' token of an object node.
  231. *
  232. * Because the last token of object patterns might be a type annotation,
  233. * this traverses tokens preceded by the last property, then returns the
  234. * first '}' token.
  235. * @param {ASTNode} node The node to get. This node is an
  236. * ObjectExpression or an ObjectPattern. And this node has one or
  237. * more properties.
  238. * @returns {Token} '}' token.
  239. */
  240. function getClosingBraceOfObject(node) {
  241. const lastProperty = node.properties.at(-1);
  242. return sourceCode.getTokenAfter(
  243. lastProperty,
  244. astUtils.isClosingBraceToken,
  245. );
  246. }
  247. /**
  248. * Reports a given object node if spacing in curly braces is invalid.
  249. * @param {ASTNode} node An ObjectExpression or ObjectPattern node to check.
  250. * @returns {void}
  251. */
  252. function checkForObject(node) {
  253. if (node.properties.length === 0) {
  254. return;
  255. }
  256. const first = sourceCode.getFirstToken(node),
  257. last = getClosingBraceOfObject(node),
  258. second = sourceCode.getTokenAfter(first, {
  259. includeComments: true,
  260. }),
  261. penultimate = sourceCode.getTokenBefore(last, {
  262. includeComments: true,
  263. });
  264. validateBraceSpacing(node, first, second, penultimate, last);
  265. }
  266. /**
  267. * Reports a given import node if spacing in curly braces is invalid.
  268. * @param {ASTNode} node An ImportDeclaration node to check.
  269. * @returns {void}
  270. */
  271. function checkForImport(node) {
  272. if (node.specifiers.length === 0) {
  273. return;
  274. }
  275. let firstSpecifier = node.specifiers[0];
  276. const lastSpecifier = node.specifiers.at(-1);
  277. if (lastSpecifier.type !== "ImportSpecifier") {
  278. return;
  279. }
  280. if (firstSpecifier.type !== "ImportSpecifier") {
  281. firstSpecifier = node.specifiers[1];
  282. }
  283. const first = sourceCode.getTokenBefore(firstSpecifier),
  284. last = sourceCode.getTokenAfter(
  285. lastSpecifier,
  286. astUtils.isNotCommaToken,
  287. ),
  288. second = sourceCode.getTokenAfter(first, {
  289. includeComments: true,
  290. }),
  291. penultimate = sourceCode.getTokenBefore(last, {
  292. includeComments: true,
  293. });
  294. validateBraceSpacing(node, first, second, penultimate, last);
  295. }
  296. /**
  297. * Reports a given export node if spacing in curly braces is invalid.
  298. * @param {ASTNode} node An ExportNamedDeclaration node to check.
  299. * @returns {void}
  300. */
  301. function checkForExport(node) {
  302. if (node.specifiers.length === 0) {
  303. return;
  304. }
  305. const firstSpecifier = node.specifiers[0],
  306. lastSpecifier = node.specifiers.at(-1),
  307. first = sourceCode.getTokenBefore(firstSpecifier),
  308. last = sourceCode.getTokenAfter(
  309. lastSpecifier,
  310. astUtils.isNotCommaToken,
  311. ),
  312. second = sourceCode.getTokenAfter(first, {
  313. includeComments: true,
  314. }),
  315. penultimate = sourceCode.getTokenBefore(last, {
  316. includeComments: true,
  317. });
  318. validateBraceSpacing(node, first, second, penultimate, last);
  319. }
  320. //--------------------------------------------------------------------------
  321. // Public
  322. //--------------------------------------------------------------------------
  323. return {
  324. // var {x} = y;
  325. ObjectPattern: checkForObject,
  326. // var y = {x: 'y'}
  327. ObjectExpression: checkForObject,
  328. // import {y} from 'x';
  329. ImportDeclaration: checkForImport,
  330. // export {name} from 'yo';
  331. ExportNamedDeclaration: checkForExport,
  332. };
  333. },
  334. };