key-spacing.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /**
  2. * @fileoverview Rule to specify spacing of object literal keys and values
  3. * @author Brandon Mills
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. const GraphemeSplitter = require("grapheme-splitter");
  11. const splitter = new GraphemeSplitter();
  12. //------------------------------------------------------------------------------
  13. // Helpers
  14. //------------------------------------------------------------------------------
  15. /**
  16. * Checks whether a string contains a line terminator as defined in
  17. * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3
  18. * @param {string} str String to test.
  19. * @returns {boolean} True if str contains a line terminator.
  20. */
  21. function containsLineTerminator(str) {
  22. return astUtils.LINEBREAK_MATCHER.test(str);
  23. }
  24. /**
  25. * Gets the last element of an array.
  26. * @param {Array} arr An array.
  27. * @returns {any} Last element of arr.
  28. */
  29. function last(arr) {
  30. return arr[arr.length - 1];
  31. }
  32. /**
  33. * Checks whether a node is contained on a single line.
  34. * @param {ASTNode} node AST Node being evaluated.
  35. * @returns {boolean} True if the node is a single line.
  36. */
  37. function isSingleLine(node) {
  38. return (node.loc.end.line === node.loc.start.line);
  39. }
  40. /**
  41. * Checks whether the properties on a single line.
  42. * @param {ASTNode[]} properties List of Property AST nodes.
  43. * @returns {boolean} True if all properties is on a single line.
  44. */
  45. function isSingleLineProperties(properties) {
  46. const [firstProp] = properties,
  47. lastProp = last(properties);
  48. return firstProp.loc.start.line === lastProp.loc.end.line;
  49. }
  50. /**
  51. * Initializes a single option property from the configuration with defaults for undefined values
  52. * @param {Object} toOptions Object to be initialized
  53. * @param {Object} fromOptions Object to be initialized from
  54. * @returns {Object} The object with correctly initialized options and values
  55. */
  56. function initOptionProperty(toOptions, fromOptions) {
  57. toOptions.mode = fromOptions.mode || "strict";
  58. // Set value of beforeColon
  59. if (typeof fromOptions.beforeColon !== "undefined") {
  60. toOptions.beforeColon = +fromOptions.beforeColon;
  61. } else {
  62. toOptions.beforeColon = 0;
  63. }
  64. // Set value of afterColon
  65. if (typeof fromOptions.afterColon !== "undefined") {
  66. toOptions.afterColon = +fromOptions.afterColon;
  67. } else {
  68. toOptions.afterColon = 1;
  69. }
  70. // Set align if exists
  71. if (typeof fromOptions.align !== "undefined") {
  72. if (typeof fromOptions.align === "object") {
  73. toOptions.align = fromOptions.align;
  74. } else { // "string"
  75. toOptions.align = {
  76. on: fromOptions.align,
  77. mode: toOptions.mode,
  78. beforeColon: toOptions.beforeColon,
  79. afterColon: toOptions.afterColon
  80. };
  81. }
  82. }
  83. return toOptions;
  84. }
  85. /**
  86. * Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values
  87. * @param {Object} toOptions Object to be initialized
  88. * @param {Object} fromOptions Object to be initialized from
  89. * @returns {Object} The object with correctly initialized options and values
  90. */
  91. function initOptions(toOptions, fromOptions) {
  92. if (typeof fromOptions.align === "object") {
  93. // Initialize the alignment configuration
  94. toOptions.align = initOptionProperty({}, fromOptions.align);
  95. toOptions.align.on = fromOptions.align.on || "colon";
  96. toOptions.align.mode = fromOptions.align.mode || "strict";
  97. toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions));
  98. toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions));
  99. } else { // string or undefined
  100. toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions));
  101. toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions));
  102. // If alignment options are defined in multiLine, pull them out into the general align configuration
  103. if (toOptions.multiLine.align) {
  104. toOptions.align = {
  105. on: toOptions.multiLine.align.on,
  106. mode: toOptions.multiLine.align.mode || toOptions.multiLine.mode,
  107. beforeColon: toOptions.multiLine.align.beforeColon,
  108. afterColon: toOptions.multiLine.align.afterColon
  109. };
  110. }
  111. }
  112. return toOptions;
  113. }
  114. //------------------------------------------------------------------------------
  115. // Rule Definition
  116. //------------------------------------------------------------------------------
  117. /** @type {import('../shared/types').Rule} */
  118. module.exports = {
  119. meta: {
  120. type: "layout",
  121. docs: {
  122. description: "Enforce consistent spacing between keys and values in object literal properties",
  123. recommended: false,
  124. url: "https://eslint.org/docs/rules/key-spacing"
  125. },
  126. fixable: "whitespace",
  127. schema: [{
  128. anyOf: [
  129. {
  130. type: "object",
  131. properties: {
  132. align: {
  133. anyOf: [
  134. {
  135. enum: ["colon", "value"]
  136. },
  137. {
  138. type: "object",
  139. properties: {
  140. mode: {
  141. enum: ["strict", "minimum"]
  142. },
  143. on: {
  144. enum: ["colon", "value"]
  145. },
  146. beforeColon: {
  147. type: "boolean"
  148. },
  149. afterColon: {
  150. type: "boolean"
  151. }
  152. },
  153. additionalProperties: false
  154. }
  155. ]
  156. },
  157. mode: {
  158. enum: ["strict", "minimum"]
  159. },
  160. beforeColon: {
  161. type: "boolean"
  162. },
  163. afterColon: {
  164. type: "boolean"
  165. }
  166. },
  167. additionalProperties: false
  168. },
  169. {
  170. type: "object",
  171. properties: {
  172. singleLine: {
  173. type: "object",
  174. properties: {
  175. mode: {
  176. enum: ["strict", "minimum"]
  177. },
  178. beforeColon: {
  179. type: "boolean"
  180. },
  181. afterColon: {
  182. type: "boolean"
  183. }
  184. },
  185. additionalProperties: false
  186. },
  187. multiLine: {
  188. type: "object",
  189. properties: {
  190. align: {
  191. anyOf: [
  192. {
  193. enum: ["colon", "value"]
  194. },
  195. {
  196. type: "object",
  197. properties: {
  198. mode: {
  199. enum: ["strict", "minimum"]
  200. },
  201. on: {
  202. enum: ["colon", "value"]
  203. },
  204. beforeColon: {
  205. type: "boolean"
  206. },
  207. afterColon: {
  208. type: "boolean"
  209. }
  210. },
  211. additionalProperties: false
  212. }
  213. ]
  214. },
  215. mode: {
  216. enum: ["strict", "minimum"]
  217. },
  218. beforeColon: {
  219. type: "boolean"
  220. },
  221. afterColon: {
  222. type: "boolean"
  223. }
  224. },
  225. additionalProperties: false
  226. }
  227. },
  228. additionalProperties: false
  229. },
  230. {
  231. type: "object",
  232. properties: {
  233. singleLine: {
  234. type: "object",
  235. properties: {
  236. mode: {
  237. enum: ["strict", "minimum"]
  238. },
  239. beforeColon: {
  240. type: "boolean"
  241. },
  242. afterColon: {
  243. type: "boolean"
  244. }
  245. },
  246. additionalProperties: false
  247. },
  248. multiLine: {
  249. type: "object",
  250. properties: {
  251. mode: {
  252. enum: ["strict", "minimum"]
  253. },
  254. beforeColon: {
  255. type: "boolean"
  256. },
  257. afterColon: {
  258. type: "boolean"
  259. }
  260. },
  261. additionalProperties: false
  262. },
  263. align: {
  264. type: "object",
  265. properties: {
  266. mode: {
  267. enum: ["strict", "minimum"]
  268. },
  269. on: {
  270. enum: ["colon", "value"]
  271. },
  272. beforeColon: {
  273. type: "boolean"
  274. },
  275. afterColon: {
  276. type: "boolean"
  277. }
  278. },
  279. additionalProperties: false
  280. }
  281. },
  282. additionalProperties: false
  283. }
  284. ]
  285. }],
  286. messages: {
  287. extraKey: "Extra space after {{computed}}key '{{key}}'.",
  288. extraValue: "Extra space before value for {{computed}}key '{{key}}'.",
  289. missingKey: "Missing space after {{computed}}key '{{key}}'.",
  290. missingValue: "Missing space before value for {{computed}}key '{{key}}'."
  291. }
  292. },
  293. create(context) {
  294. /**
  295. * OPTIONS
  296. * "key-spacing": [2, {
  297. * beforeColon: false,
  298. * afterColon: true,
  299. * align: "colon" // Optional, or "value"
  300. * }
  301. */
  302. const options = context.options[0] || {},
  303. ruleOptions = initOptions({}, options),
  304. multiLineOptions = ruleOptions.multiLine,
  305. singleLineOptions = ruleOptions.singleLine,
  306. alignmentOptions = ruleOptions.align || null;
  307. const sourceCode = context.getSourceCode();
  308. /**
  309. * Determines if the given property is key-value property.
  310. * @param {ASTNode} property Property node to check.
  311. * @returns {boolean} Whether the property is a key-value property.
  312. */
  313. function isKeyValueProperty(property) {
  314. return !(
  315. (property.method ||
  316. property.shorthand ||
  317. property.kind !== "init" || property.type !== "Property") // Could be "ExperimentalSpreadProperty" or "SpreadElement"
  318. );
  319. }
  320. /**
  321. * Checks whether a property is a member of the property group it follows.
  322. * @param {ASTNode} lastMember The last Property known to be in the group.
  323. * @param {ASTNode} candidate The next Property that might be in the group.
  324. * @returns {boolean} True if the candidate property is part of the group.
  325. */
  326. function continuesPropertyGroup(lastMember, candidate) {
  327. const groupEndLine = lastMember.loc.start.line,
  328. candidateValueStartLine = (isKeyValueProperty(candidate) ? candidate.value : candidate).loc.start.line;
  329. if (candidateValueStartLine - groupEndLine <= 1) {
  330. return true;
  331. }
  332. /*
  333. * Check that the first comment is adjacent to the end of the group, the
  334. * last comment is adjacent to the candidate property, and that successive
  335. * comments are adjacent to each other.
  336. */
  337. const leadingComments = sourceCode.getCommentsBefore(candidate);
  338. if (
  339. leadingComments.length &&
  340. leadingComments[0].loc.start.line - groupEndLine <= 1 &&
  341. candidateValueStartLine - last(leadingComments).loc.end.line <= 1
  342. ) {
  343. for (let i = 1; i < leadingComments.length; i++) {
  344. if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) {
  345. return false;
  346. }
  347. }
  348. return true;
  349. }
  350. return false;
  351. }
  352. /**
  353. * Starting from the given a node (a property.key node here) looks forward
  354. * until it finds the last token before a colon punctuator and returns it.
  355. * @param {ASTNode} node The node to start looking from.
  356. * @returns {ASTNode} The last token before a colon punctuator.
  357. */
  358. function getLastTokenBeforeColon(node) {
  359. const colonToken = sourceCode.getTokenAfter(node, astUtils.isColonToken);
  360. return sourceCode.getTokenBefore(colonToken);
  361. }
  362. /**
  363. * Starting from the given a node (a property.key node here) looks forward
  364. * until it finds the colon punctuator and returns it.
  365. * @param {ASTNode} node The node to start looking from.
  366. * @returns {ASTNode} The colon punctuator.
  367. */
  368. function getNextColon(node) {
  369. return sourceCode.getTokenAfter(node, astUtils.isColonToken);
  370. }
  371. /**
  372. * Gets an object literal property's key as the identifier name or string value.
  373. * @param {ASTNode} property Property node whose key to retrieve.
  374. * @returns {string} The property's key.
  375. */
  376. function getKey(property) {
  377. const key = property.key;
  378. if (property.computed) {
  379. return sourceCode.getText().slice(key.range[0], key.range[1]);
  380. }
  381. return astUtils.getStaticPropertyName(property);
  382. }
  383. /**
  384. * Reports an appropriately-formatted error if spacing is incorrect on one
  385. * side of the colon.
  386. * @param {ASTNode} property Key-value pair in an object literal.
  387. * @param {string} side Side being verified - either "key" or "value".
  388. * @param {string} whitespace Actual whitespace string.
  389. * @param {int} expected Expected whitespace length.
  390. * @param {string} mode Value of the mode as "strict" or "minimum"
  391. * @returns {void}
  392. */
  393. function report(property, side, whitespace, expected, mode) {
  394. const diff = whitespace.length - expected;
  395. if ((
  396. diff && mode === "strict" ||
  397. diff < 0 && mode === "minimum" ||
  398. diff > 0 && !expected && mode === "minimum") &&
  399. !(expected && containsLineTerminator(whitespace))
  400. ) {
  401. const nextColon = getNextColon(property.key),
  402. tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }),
  403. tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }),
  404. isKeySide = side === "key",
  405. isExtra = diff > 0,
  406. diffAbs = Math.abs(diff),
  407. spaces = Array(diffAbs + 1).join(" ");
  408. const locStart = isKeySide ? tokenBeforeColon.loc.end : nextColon.loc.start;
  409. const locEnd = isKeySide ? nextColon.loc.start : tokenAfterColon.loc.start;
  410. const missingLoc = isKeySide ? tokenBeforeColon.loc : tokenAfterColon.loc;
  411. const loc = isExtra ? { start: locStart, end: locEnd } : missingLoc;
  412. let fix;
  413. if (isExtra) {
  414. let range;
  415. // Remove whitespace
  416. if (isKeySide) {
  417. range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs];
  418. } else {
  419. range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]];
  420. }
  421. fix = function(fixer) {
  422. return fixer.removeRange(range);
  423. };
  424. } else {
  425. // Add whitespace
  426. if (isKeySide) {
  427. fix = function(fixer) {
  428. return fixer.insertTextAfter(tokenBeforeColon, spaces);
  429. };
  430. } else {
  431. fix = function(fixer) {
  432. return fixer.insertTextBefore(tokenAfterColon, spaces);
  433. };
  434. }
  435. }
  436. let messageId = "";
  437. if (isExtra) {
  438. messageId = side === "key" ? "extraKey" : "extraValue";
  439. } else {
  440. messageId = side === "key" ? "missingKey" : "missingValue";
  441. }
  442. context.report({
  443. node: property[side],
  444. loc,
  445. messageId,
  446. data: {
  447. computed: property.computed ? "computed " : "",
  448. key: getKey(property)
  449. },
  450. fix
  451. });
  452. }
  453. }
  454. /**
  455. * Gets the number of characters in a key, including quotes around string
  456. * keys and braces around computed property keys.
  457. * @param {ASTNode} property Property of on object literal.
  458. * @returns {int} Width of the key.
  459. */
  460. function getKeyWidth(property) {
  461. const startToken = sourceCode.getFirstToken(property);
  462. const endToken = getLastTokenBeforeColon(property.key);
  463. return splitter.countGraphemes(sourceCode.getText().slice(startToken.range[0], endToken.range[1]));
  464. }
  465. /**
  466. * Gets the whitespace around the colon in an object literal property.
  467. * @param {ASTNode} property Property node from an object literal.
  468. * @returns {Object} Whitespace before and after the property's colon.
  469. */
  470. function getPropertyWhitespace(property) {
  471. const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice(
  472. property.key.range[1], property.value.range[0]
  473. ));
  474. if (whitespace) {
  475. return {
  476. beforeColon: whitespace[1],
  477. afterColon: whitespace[2]
  478. };
  479. }
  480. return null;
  481. }
  482. /**
  483. * Creates groups of properties.
  484. * @param {ASTNode} node ObjectExpression node being evaluated.
  485. * @returns {Array<ASTNode[]>} Groups of property AST node lists.
  486. */
  487. function createGroups(node) {
  488. if (node.properties.length === 1) {
  489. return [node.properties];
  490. }
  491. return node.properties.reduce((groups, property) => {
  492. const currentGroup = last(groups),
  493. prev = last(currentGroup);
  494. if (!prev || continuesPropertyGroup(prev, property)) {
  495. currentGroup.push(property);
  496. } else {
  497. groups.push([property]);
  498. }
  499. return groups;
  500. }, [
  501. []
  502. ]);
  503. }
  504. /**
  505. * Verifies correct vertical alignment of a group of properties.
  506. * @param {ASTNode[]} properties List of Property AST nodes.
  507. * @returns {void}
  508. */
  509. function verifyGroupAlignment(properties) {
  510. const length = properties.length,
  511. widths = properties.map(getKeyWidth), // Width of keys, including quotes
  512. align = alignmentOptions.on; // "value" or "colon"
  513. let targetWidth = Math.max(...widths),
  514. beforeColon, afterColon, mode;
  515. if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration.
  516. beforeColon = alignmentOptions.beforeColon;
  517. afterColon = alignmentOptions.afterColon;
  518. mode = alignmentOptions.mode;
  519. } else {
  520. beforeColon = multiLineOptions.beforeColon;
  521. afterColon = multiLineOptions.afterColon;
  522. mode = alignmentOptions.mode;
  523. }
  524. // Conditionally include one space before or after colon
  525. targetWidth += (align === "colon" ? beforeColon : afterColon);
  526. for (let i = 0; i < length; i++) {
  527. const property = properties[i];
  528. const whitespace = getPropertyWhitespace(property);
  529. if (whitespace) { // Object literal getters/setters lack a colon
  530. const width = widths[i];
  531. if (align === "value") {
  532. report(property, "key", whitespace.beforeColon, beforeColon, mode);
  533. report(property, "value", whitespace.afterColon, targetWidth - width, mode);
  534. } else { // align = "colon"
  535. report(property, "key", whitespace.beforeColon, targetWidth - width, mode);
  536. report(property, "value", whitespace.afterColon, afterColon, mode);
  537. }
  538. }
  539. }
  540. }
  541. /**
  542. * Verifies spacing of property conforms to specified options.
  543. * @param {ASTNode} node Property node being evaluated.
  544. * @param {Object} lineOptions Configured singleLine or multiLine options
  545. * @returns {void}
  546. */
  547. function verifySpacing(node, lineOptions) {
  548. const actual = getPropertyWhitespace(node);
  549. if (actual) { // Object literal getters/setters lack colons
  550. report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode);
  551. report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode);
  552. }
  553. }
  554. /**
  555. * Verifies spacing of each property in a list.
  556. * @param {ASTNode[]} properties List of Property AST nodes.
  557. * @param {Object} lineOptions Configured singleLine or multiLine options
  558. * @returns {void}
  559. */
  560. function verifyListSpacing(properties, lineOptions) {
  561. const length = properties.length;
  562. for (let i = 0; i < length; i++) {
  563. verifySpacing(properties[i], lineOptions);
  564. }
  565. }
  566. /**
  567. * Verifies vertical alignment, taking into account groups of properties.
  568. * @param {ASTNode} node ObjectExpression node being evaluated.
  569. * @returns {void}
  570. */
  571. function verifyAlignment(node) {
  572. createGroups(node).forEach(group => {
  573. const properties = group.filter(isKeyValueProperty);
  574. if (properties.length > 0 && isSingleLineProperties(properties)) {
  575. verifyListSpacing(properties, multiLineOptions);
  576. } else {
  577. verifyGroupAlignment(properties);
  578. }
  579. });
  580. }
  581. //--------------------------------------------------------------------------
  582. // Public API
  583. //--------------------------------------------------------------------------
  584. if (alignmentOptions) { // Verify vertical alignment
  585. return {
  586. ObjectExpression(node) {
  587. if (isSingleLine(node)) {
  588. verifyListSpacing(node.properties.filter(isKeyValueProperty), singleLineOptions);
  589. } else {
  590. verifyAlignment(node);
  591. }
  592. }
  593. };
  594. }
  595. // Obey beforeColon and afterColon in each property as configured
  596. return {
  597. Property(node) {
  598. verifySpacing(node, isSingleLine(node.parent) ? singleLineOptions : multiLineOptions);
  599. }
  600. };
  601. }
  602. };