key-spacing.js 25 KB

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