quote-props.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /**
  2. * @fileoverview Rule to flag non-quoted property names in object literals.
  3. * @author Mathias Bynens <http://mathiasbynens.be/>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const espree = require("espree"),
  10. keywords = require("../util/keywords");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. docs: {
  17. description: "require quotes around object literal property names",
  18. category: "Stylistic Issues",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/quote-props"
  21. },
  22. schema: {
  23. anyOf: [
  24. {
  25. type: "array",
  26. items: [
  27. {
  28. enum: ["always", "as-needed", "consistent", "consistent-as-needed"]
  29. }
  30. ],
  31. minItems: 0,
  32. maxItems: 1
  33. },
  34. {
  35. type: "array",
  36. items: [
  37. {
  38. enum: ["always", "as-needed", "consistent", "consistent-as-needed"]
  39. },
  40. {
  41. type: "object",
  42. properties: {
  43. keywords: {
  44. type: "boolean"
  45. },
  46. unnecessary: {
  47. type: "boolean"
  48. },
  49. numbers: {
  50. type: "boolean"
  51. }
  52. },
  53. additionalProperties: false
  54. }
  55. ],
  56. minItems: 0,
  57. maxItems: 2
  58. }
  59. ]
  60. },
  61. fixable: "code"
  62. },
  63. create(context) {
  64. const MODE = context.options[0],
  65. KEYWORDS = context.options[1] && context.options[1].keywords,
  66. CHECK_UNNECESSARY = !context.options[1] || context.options[1].unnecessary !== false,
  67. NUMBERS = context.options[1] && context.options[1].numbers,
  68. MESSAGE_UNNECESSARY = "Unnecessarily quoted property '{{property}}' found.",
  69. MESSAGE_UNQUOTED = "Unquoted property '{{property}}' found.",
  70. MESSAGE_NUMERIC = "Unquoted number literal '{{property}}' used as key.",
  71. MESSAGE_RESERVED = "Unquoted reserved word '{{property}}' used as key.",
  72. sourceCode = context.getSourceCode();
  73. /**
  74. * Checks whether a certain string constitutes an ES3 token
  75. * @param {string} tokenStr - The string to be checked.
  76. * @returns {boolean} `true` if it is an ES3 token.
  77. */
  78. function isKeyword(tokenStr) {
  79. return keywords.indexOf(tokenStr) >= 0;
  80. }
  81. /**
  82. * Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary)
  83. * @param {string} rawKey The raw key value from the source
  84. * @param {espreeTokens} tokens The espree-tokenized node key
  85. * @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked
  86. * @returns {boolean} Whether or not a key has redundant quotes.
  87. * @private
  88. */
  89. function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) {
  90. return tokens.length === 1 && tokens[0].start === 0 && tokens[0].end === rawKey.length &&
  91. (["Identifier", "Keyword", "Null", "Boolean"].indexOf(tokens[0].type) >= 0 ||
  92. (tokens[0].type === "Numeric" && !skipNumberLiterals && String(+tokens[0].value) === tokens[0].value));
  93. }
  94. /**
  95. * Returns a string representation of a property node with quotes removed
  96. * @param {ASTNode} key Key AST Node, which may or may not be quoted
  97. * @returns {string} A replacement string for this property
  98. */
  99. function getUnquotedKey(key) {
  100. return key.type === "Identifier" ? key.name : key.value;
  101. }
  102. /**
  103. * Returns a string representation of a property node with quotes added
  104. * @param {ASTNode} key Key AST Node, which may or may not be quoted
  105. * @returns {string} A replacement string for this property
  106. */
  107. function getQuotedKey(key) {
  108. if (key.type === "Literal" && typeof key.value === "string") {
  109. // If the key is already a string literal, don't replace the quotes with double quotes.
  110. return sourceCode.getText(key);
  111. }
  112. // Otherwise, the key is either an identifier or a number literal.
  113. return `"${key.type === "Identifier" ? key.name : key.value}"`;
  114. }
  115. /**
  116. * Ensures that a property's key is quoted only when necessary
  117. * @param {ASTNode} node Property AST node
  118. * @returns {void}
  119. */
  120. function checkUnnecessaryQuotes(node) {
  121. const key = node.key;
  122. if (node.method || node.computed || node.shorthand) {
  123. return;
  124. }
  125. if (key.type === "Literal" && typeof key.value === "string") {
  126. let tokens;
  127. try {
  128. tokens = espree.tokenize(key.value);
  129. } catch (e) {
  130. return;
  131. }
  132. if (tokens.length !== 1) {
  133. return;
  134. }
  135. const isKeywordToken = isKeyword(tokens[0].value);
  136. if (isKeywordToken && KEYWORDS) {
  137. return;
  138. }
  139. if (CHECK_UNNECESSARY && areQuotesRedundant(key.value, tokens, NUMBERS)) {
  140. context.report({
  141. node,
  142. message: MESSAGE_UNNECESSARY,
  143. data: { property: key.value },
  144. fix: fixer => fixer.replaceText(key, getUnquotedKey(key))
  145. });
  146. }
  147. } else if (KEYWORDS && key.type === "Identifier" && isKeyword(key.name)) {
  148. context.report({
  149. node,
  150. message: MESSAGE_RESERVED,
  151. data: { property: key.name },
  152. fix: fixer => fixer.replaceText(key, getQuotedKey(key))
  153. });
  154. } else if (NUMBERS && key.type === "Literal" && typeof key.value === "number") {
  155. context.report({
  156. node,
  157. message: MESSAGE_NUMERIC,
  158. data: { property: key.value },
  159. fix: fixer => fixer.replaceText(key, getQuotedKey(key))
  160. });
  161. }
  162. }
  163. /**
  164. * Ensures that a property's key is quoted
  165. * @param {ASTNode} node Property AST node
  166. * @returns {void}
  167. */
  168. function checkOmittedQuotes(node) {
  169. const key = node.key;
  170. if (!node.method && !node.computed && !node.shorthand && !(key.type === "Literal" && typeof key.value === "string")) {
  171. context.report({
  172. node,
  173. message: MESSAGE_UNQUOTED,
  174. data: { property: key.name || key.value },
  175. fix: fixer => fixer.replaceText(key, getQuotedKey(key))
  176. });
  177. }
  178. }
  179. /**
  180. * Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes
  181. * @param {ASTNode} node Property AST node
  182. * @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy
  183. * @returns {void}
  184. */
  185. function checkConsistency(node, checkQuotesRedundancy) {
  186. const quotedProps = [],
  187. unquotedProps = [];
  188. let keywordKeyName = null,
  189. necessaryQuotes = false;
  190. node.properties.forEach(property => {
  191. const key = property.key;
  192. if (!key || property.method || property.computed || property.shorthand) {
  193. return;
  194. }
  195. if (key.type === "Literal" && typeof key.value === "string") {
  196. quotedProps.push(property);
  197. if (checkQuotesRedundancy) {
  198. let tokens;
  199. try {
  200. tokens = espree.tokenize(key.value);
  201. } catch (e) {
  202. necessaryQuotes = true;
  203. return;
  204. }
  205. necessaryQuotes = necessaryQuotes || !areQuotesRedundant(key.value, tokens) || KEYWORDS && isKeyword(tokens[0].value);
  206. }
  207. } else if (KEYWORDS && checkQuotesRedundancy && key.type === "Identifier" && isKeyword(key.name)) {
  208. unquotedProps.push(property);
  209. necessaryQuotes = true;
  210. keywordKeyName = key.name;
  211. } else {
  212. unquotedProps.push(property);
  213. }
  214. });
  215. if (checkQuotesRedundancy && quotedProps.length && !necessaryQuotes) {
  216. quotedProps.forEach(property => {
  217. context.report({
  218. node: property,
  219. message: "Properties shouldn't be quoted as all quotes are redundant.",
  220. fix: fixer => fixer.replaceText(property.key, getUnquotedKey(property.key))
  221. });
  222. });
  223. } else if (unquotedProps.length && keywordKeyName) {
  224. unquotedProps.forEach(property => {
  225. context.report({
  226. node: property,
  227. message: "Properties should be quoted as '{{property}}' is a reserved word.",
  228. data: { property: keywordKeyName },
  229. fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key))
  230. });
  231. });
  232. } else if (quotedProps.length && unquotedProps.length) {
  233. unquotedProps.forEach(property => {
  234. context.report({
  235. node: property,
  236. message: "Inconsistently quoted property '{{key}}' found.",
  237. data: { key: property.key.name || property.key.value },
  238. fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key))
  239. });
  240. });
  241. }
  242. }
  243. return {
  244. Property(node) {
  245. if (MODE === "always" || !MODE) {
  246. checkOmittedQuotes(node);
  247. }
  248. if (MODE === "as-needed") {
  249. checkUnnecessaryQuotes(node);
  250. }
  251. },
  252. ObjectExpression(node) {
  253. if (MODE === "consistent") {
  254. checkConsistency(node, false);
  255. }
  256. if (MODE === "consistent-as-needed") {
  257. checkConsistency(node, true);
  258. }
  259. }
  260. };
  261. }
  262. };