key-spacing.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. * Starting from the given node (a property.key node here) looks forward
  322. * until it finds the colon punctuator and returns it.
  323. * @param {ASTNode} node The node to start looking from.
  324. * @returns {ASTNode} The colon punctuator.
  325. */
  326. function getNextColon(node) {
  327. return sourceCode.getTokenAfter(node, astUtils.isColonToken);
  328. }
  329. /**
  330. * Starting from the given node (a property.key node here) looks forward
  331. * until it finds the last token before a colon punctuator and returns it.
  332. * @param {ASTNode} node The node to start looking from.
  333. * @returns {ASTNode} The last token before a colon punctuator.
  334. */
  335. function getLastTokenBeforeColon(node) {
  336. const colonToken = getNextColon(node);
  337. return sourceCode.getTokenBefore(colonToken);
  338. }
  339. /**
  340. * Starting from the given node (a property.key node here) looks forward
  341. * until it finds the first token after a colon punctuator and returns it.
  342. * @param {ASTNode} node The node to start looking from.
  343. * @returns {ASTNode} The first token after a colon punctuator.
  344. */
  345. function getFirstTokenAfterColon(node) {
  346. const colonToken = getNextColon(node);
  347. return sourceCode.getTokenAfter(colonToken);
  348. }
  349. /**
  350. * Checks whether a property is a member of the property group it follows.
  351. * @param {ASTNode} lastMember The last Property known to be in the group.
  352. * @param {ASTNode} candidate The next Property that might be in the group.
  353. * @returns {boolean} True if the candidate property is part of the group.
  354. */
  355. function continuesPropertyGroup(lastMember, candidate) {
  356. const groupEndLine = lastMember.loc.start.line,
  357. candidateValueStartLine = (isKeyValueProperty(candidate) ? getFirstTokenAfterColon(candidate.key) : candidate).loc.start.line;
  358. if (candidateValueStartLine - groupEndLine <= 1) {
  359. return true;
  360. }
  361. /*
  362. * Check that the first comment is adjacent to the end of the group, the
  363. * last comment is adjacent to the candidate property, and that successive
  364. * comments are adjacent to each other.
  365. */
  366. const leadingComments = sourceCode.getCommentsBefore(candidate);
  367. if (
  368. leadingComments.length &&
  369. leadingComments[0].loc.start.line - groupEndLine <= 1 &&
  370. candidateValueStartLine - last(leadingComments).loc.end.line <= 1
  371. ) {
  372. for (let i = 1; i < leadingComments.length; i++) {
  373. if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) {
  374. return false;
  375. }
  376. }
  377. return true;
  378. }
  379. return false;
  380. }
  381. /**
  382. * Gets an object literal property's key as the identifier name or string value.
  383. * @param {ASTNode} property Property node whose key to retrieve.
  384. * @returns {string} The property's key.
  385. */
  386. function getKey(property) {
  387. const key = property.key;
  388. if (property.computed) {
  389. return sourceCode.getText().slice(key.range[0], key.range[1]);
  390. }
  391. return astUtils.getStaticPropertyName(property);
  392. }
  393. /**
  394. * Reports an appropriately-formatted error if spacing is incorrect on one
  395. * side of the colon.
  396. * @param {ASTNode} property Key-value pair in an object literal.
  397. * @param {string} side Side being verified - either "key" or "value".
  398. * @param {string} whitespace Actual whitespace string.
  399. * @param {int} expected Expected whitespace length.
  400. * @param {string} mode Value of the mode as "strict" or "minimum"
  401. * @returns {void}
  402. */
  403. function report(property, side, whitespace, expected, mode) {
  404. const diff = whitespace.length - expected;
  405. if ((
  406. diff && mode === "strict" ||
  407. diff < 0 && mode === "minimum" ||
  408. diff > 0 && !expected && mode === "minimum") &&
  409. !(expected && containsLineTerminator(whitespace))
  410. ) {
  411. const nextColon = getNextColon(property.key),
  412. tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }),
  413. tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }),
  414. isKeySide = side === "key",
  415. isExtra = diff > 0,
  416. diffAbs = Math.abs(diff),
  417. spaces = Array(diffAbs + 1).join(" ");
  418. const locStart = isKeySide ? tokenBeforeColon.loc.end : nextColon.loc.start;
  419. const locEnd = isKeySide ? nextColon.loc.start : tokenAfterColon.loc.start;
  420. const missingLoc = isKeySide ? tokenBeforeColon.loc : tokenAfterColon.loc;
  421. const loc = isExtra ? { start: locStart, end: locEnd } : missingLoc;
  422. let fix;
  423. if (isExtra) {
  424. let range;
  425. // Remove whitespace
  426. if (isKeySide) {
  427. range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs];
  428. } else {
  429. range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]];
  430. }
  431. fix = function(fixer) {
  432. return fixer.removeRange(range);
  433. };
  434. } else {
  435. // Add whitespace
  436. if (isKeySide) {
  437. fix = function(fixer) {
  438. return fixer.insertTextAfter(tokenBeforeColon, spaces);
  439. };
  440. } else {
  441. fix = function(fixer) {
  442. return fixer.insertTextBefore(tokenAfterColon, spaces);
  443. };
  444. }
  445. }
  446. let messageId = "";
  447. if (isExtra) {
  448. messageId = side === "key" ? "extraKey" : "extraValue";
  449. } else {
  450. messageId = side === "key" ? "missingKey" : "missingValue";
  451. }
  452. context.report({
  453. node: property[side],
  454. loc,
  455. messageId,
  456. data: {
  457. computed: property.computed ? "computed " : "",
  458. key: getKey(property)
  459. },
  460. fix
  461. });
  462. }
  463. }
  464. /**
  465. * Gets the number of characters in a key, including quotes around string
  466. * keys and braces around computed property keys.
  467. * @param {ASTNode} property Property of on object literal.
  468. * @returns {int} Width of the key.
  469. */
  470. function getKeyWidth(property) {
  471. const startToken = sourceCode.getFirstToken(property);
  472. const endToken = getLastTokenBeforeColon(property.key);
  473. return splitter.countGraphemes(sourceCode.getText().slice(startToken.range[0], endToken.range[1]));
  474. }
  475. /**
  476. * Gets the whitespace around the colon in an object literal property.
  477. * @param {ASTNode} property Property node from an object literal.
  478. * @returns {Object} Whitespace before and after the property's colon.
  479. */
  480. function getPropertyWhitespace(property) {
  481. const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice(
  482. property.key.range[1], property.value.range[0]
  483. ));
  484. if (whitespace) {
  485. return {
  486. beforeColon: whitespace[1],
  487. afterColon: whitespace[2]
  488. };
  489. }
  490. return null;
  491. }
  492. /**
  493. * Creates groups of properties.
  494. * @param {ASTNode} node ObjectExpression node being evaluated.
  495. * @returns {Array<ASTNode[]>} Groups of property AST node lists.
  496. */
  497. function createGroups(node) {
  498. if (node.properties.length === 1) {
  499. return [node.properties];
  500. }
  501. return node.properties.reduce((groups, property) => {
  502. const currentGroup = last(groups),
  503. prev = last(currentGroup);
  504. if (!prev || continuesPropertyGroup(prev, property)) {
  505. currentGroup.push(property);
  506. } else {
  507. groups.push([property]);
  508. }
  509. return groups;
  510. }, [
  511. []
  512. ]);
  513. }
  514. /**
  515. * Verifies correct vertical alignment of a group of properties.
  516. * @param {ASTNode[]} properties List of Property AST nodes.
  517. * @returns {void}
  518. */
  519. function verifyGroupAlignment(properties) {
  520. const length = properties.length,
  521. widths = properties.map(getKeyWidth), // Width of keys, including quotes
  522. align = alignmentOptions.on; // "value" or "colon"
  523. let targetWidth = Math.max(...widths),
  524. beforeColon, afterColon, mode;
  525. if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration.
  526. beforeColon = alignmentOptions.beforeColon;
  527. afterColon = alignmentOptions.afterColon;
  528. mode = alignmentOptions.mode;
  529. } else {
  530. beforeColon = multiLineOptions.beforeColon;
  531. afterColon = multiLineOptions.afterColon;
  532. mode = alignmentOptions.mode;
  533. }
  534. // Conditionally include one space before or after colon
  535. targetWidth += (align === "colon" ? beforeColon : afterColon);
  536. for (let i = 0; i < length; i++) {
  537. const property = properties[i];
  538. const whitespace = getPropertyWhitespace(property);
  539. if (whitespace) { // Object literal getters/setters lack a colon
  540. const width = widths[i];
  541. if (align === "value") {
  542. report(property, "key", whitespace.beforeColon, beforeColon, mode);
  543. report(property, "value", whitespace.afterColon, targetWidth - width, mode);
  544. } else { // align = "colon"
  545. report(property, "key", whitespace.beforeColon, targetWidth - width, mode);
  546. report(property, "value", whitespace.afterColon, afterColon, mode);
  547. }
  548. }
  549. }
  550. }
  551. /**
  552. * Verifies spacing of property conforms to specified options.
  553. * @param {ASTNode} node Property node being evaluated.
  554. * @param {Object} lineOptions Configured singleLine or multiLine options
  555. * @returns {void}
  556. */
  557. function verifySpacing(node, lineOptions) {
  558. const actual = getPropertyWhitespace(node);
  559. if (actual) { // Object literal getters/setters lack colons
  560. report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode);
  561. report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode);
  562. }
  563. }
  564. /**
  565. * Verifies spacing of each property in a list.
  566. * @param {ASTNode[]} properties List of Property AST nodes.
  567. * @param {Object} lineOptions Configured singleLine or multiLine options
  568. * @returns {void}
  569. */
  570. function verifyListSpacing(properties, lineOptions) {
  571. const length = properties.length;
  572. for (let i = 0; i < length; i++) {
  573. verifySpacing(properties[i], lineOptions);
  574. }
  575. }
  576. /**
  577. * Verifies vertical alignment, taking into account groups of properties.
  578. * @param {ASTNode} node ObjectExpression node being evaluated.
  579. * @returns {void}
  580. */
  581. function verifyAlignment(node) {
  582. createGroups(node).forEach(group => {
  583. const properties = group.filter(isKeyValueProperty);
  584. if (properties.length > 0 && isSingleLineProperties(properties)) {
  585. verifyListSpacing(properties, multiLineOptions);
  586. } else {
  587. verifyGroupAlignment(properties);
  588. }
  589. });
  590. }
  591. //--------------------------------------------------------------------------
  592. // Public API
  593. //--------------------------------------------------------------------------
  594. if (alignmentOptions) { // Verify vertical alignment
  595. return {
  596. ObjectExpression(node) {
  597. if (isSingleLine(node)) {
  598. verifyListSpacing(node.properties.filter(isKeyValueProperty), singleLineOptions);
  599. } else {
  600. verifyAlignment(node);
  601. }
  602. }
  603. };
  604. }
  605. // Obey beforeColon and afterColon in each property as configured
  606. return {
  607. Property(node) {
  608. verifySpacing(node, isSingleLine(node.parent) ? singleLineOptions : multiLineOptions);
  609. }
  610. };
  611. }
  612. };