quotes.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /**
  2. * @fileoverview A rule to choose between single and double quote marks
  3. * @author Matt DuVall <http://www.mattduvall.com/>, Brandon Payton
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Constants
  12. //------------------------------------------------------------------------------
  13. const QUOTE_SETTINGS = {
  14. double: {
  15. quote: "\"",
  16. alternateQuote: "'",
  17. description: "doublequote"
  18. },
  19. single: {
  20. quote: "'",
  21. alternateQuote: "\"",
  22. description: "singlequote"
  23. },
  24. backtick: {
  25. quote: "`",
  26. alternateQuote: "\"",
  27. description: "backtick"
  28. }
  29. };
  30. // An unescaped newline is a newline preceded by an even number of backslashes.
  31. const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`, "u");
  32. /**
  33. * Switches quoting of javascript string between ' " and `
  34. * escaping and unescaping as necessary.
  35. * Only escaping of the minimal set of characters is changed.
  36. * Note: escaping of newlines when switching from backtick to other quotes is not handled.
  37. * @param {string} str A string to convert.
  38. * @returns {string} The string with changed quotes.
  39. * @private
  40. */
  41. QUOTE_SETTINGS.double.convert =
  42. QUOTE_SETTINGS.single.convert =
  43. QUOTE_SETTINGS.backtick.convert = function(str) {
  44. const newQuote = this.quote;
  45. const oldQuote = str[0];
  46. if (newQuote === oldQuote) {
  47. return str;
  48. }
  49. return newQuote + str.slice(1, -1).replace(/\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, (match, escaped, newline) => {
  50. if (escaped === oldQuote || oldQuote === "`" && escaped === "${") {
  51. return escaped; // unescape
  52. }
  53. if (match === newQuote || newQuote === "`" && match === "${") {
  54. return `\\${match}`; // escape
  55. }
  56. if (newline && oldQuote === "`") {
  57. return "\\n"; // escape newlines
  58. }
  59. return match;
  60. }) + newQuote;
  61. };
  62. const AVOID_ESCAPE = "avoid-escape";
  63. //------------------------------------------------------------------------------
  64. // Rule Definition
  65. //------------------------------------------------------------------------------
  66. /** @type {import('../shared/types').Rule} */
  67. module.exports = {
  68. meta: {
  69. type: "layout",
  70. docs: {
  71. description: "Enforce the consistent use of either backticks, double, or single quotes",
  72. recommended: false,
  73. url: "https://eslint.org/docs/latest/rules/quotes"
  74. },
  75. fixable: "code",
  76. schema: [
  77. {
  78. enum: ["single", "double", "backtick"]
  79. },
  80. {
  81. anyOf: [
  82. {
  83. enum: ["avoid-escape"]
  84. },
  85. {
  86. type: "object",
  87. properties: {
  88. avoidEscape: {
  89. type: "boolean"
  90. },
  91. allowTemplateLiterals: {
  92. type: "boolean"
  93. }
  94. },
  95. additionalProperties: false
  96. }
  97. ]
  98. }
  99. ],
  100. messages: {
  101. wrongQuotes: "Strings must use {{description}}."
  102. }
  103. },
  104. create(context) {
  105. const quoteOption = context.options[0],
  106. settings = QUOTE_SETTINGS[quoteOption || "double"],
  107. options = context.options[1],
  108. allowTemplateLiterals = options && options.allowTemplateLiterals === true,
  109. sourceCode = context.sourceCode;
  110. let avoidEscape = options && options.avoidEscape === true;
  111. // deprecated
  112. if (options === AVOID_ESCAPE) {
  113. avoidEscape = true;
  114. }
  115. /**
  116. * Determines if a given node is part of JSX syntax.
  117. *
  118. * This function returns `true` in the following cases:
  119. *
  120. * - `<div className="foo"></div>` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`.
  121. * - `<div>foo</div>` ... If the literal is a text content, the parent of the literal is `JSXElement`.
  122. * - `<>foo</>` ... If the literal is a text content, the parent of the literal is `JSXFragment`.
  123. *
  124. * In particular, this function returns `false` in the following cases:
  125. *
  126. * - `<div className={"foo"}></div>`
  127. * - `<div>{"foo"}</div>`
  128. *
  129. * In both cases, inside of the braces is handled as normal JavaScript.
  130. * The braces are `JSXExpressionContainer` nodes.
  131. * @param {ASTNode} node The Literal node to check.
  132. * @returns {boolean} True if the node is a part of JSX, false if not.
  133. * @private
  134. */
  135. function isJSXLiteral(node) {
  136. return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
  137. }
  138. /**
  139. * Checks whether or not a given node is a directive.
  140. * The directive is a `ExpressionStatement` which has only a string literal not surrounded by
  141. * parentheses.
  142. * @param {ASTNode} node A node to check.
  143. * @returns {boolean} Whether or not the node is a directive.
  144. * @private
  145. */
  146. function isDirective(node) {
  147. return (
  148. node.type === "ExpressionStatement" &&
  149. node.expression.type === "Literal" &&
  150. typeof node.expression.value === "string" &&
  151. !astUtils.isParenthesised(sourceCode, node.expression)
  152. );
  153. }
  154. /**
  155. * Checks whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue.
  156. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive}
  157. * @param {ASTNode} node A node to check.
  158. * @returns {boolean} Whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue.
  159. * @private
  160. */
  161. function isExpressionInOrJustAfterDirectivePrologue(node) {
  162. if (!astUtils.isTopLevelExpressionStatement(node.parent)) {
  163. return false;
  164. }
  165. const block = node.parent.parent;
  166. // Check the node is at a prologue.
  167. for (let i = 0; i < block.body.length; ++i) {
  168. const statement = block.body[i];
  169. if (statement === node.parent) {
  170. return true;
  171. }
  172. if (!isDirective(statement)) {
  173. break;
  174. }
  175. }
  176. return false;
  177. }
  178. /**
  179. * Checks whether or not a given node is allowed as non backtick.
  180. * @param {ASTNode} node A node to check.
  181. * @returns {boolean} Whether or not the node is allowed as non backtick.
  182. * @private
  183. */
  184. function isAllowedAsNonBacktick(node) {
  185. const parent = node.parent;
  186. switch (parent.type) {
  187. // Directive Prologues.
  188. case "ExpressionStatement":
  189. return !astUtils.isParenthesised(sourceCode, node) && isExpressionInOrJustAfterDirectivePrologue(node);
  190. // LiteralPropertyName.
  191. case "Property":
  192. case "PropertyDefinition":
  193. case "MethodDefinition":
  194. return parent.key === node && !parent.computed;
  195. // ModuleSpecifier.
  196. case "ImportDeclaration":
  197. case "ExportNamedDeclaration":
  198. return parent.source === node;
  199. // ModuleExportName or ModuleSpecifier.
  200. case "ExportAllDeclaration":
  201. return parent.exported === node || parent.source === node;
  202. // ModuleExportName.
  203. case "ImportSpecifier":
  204. return parent.imported === node;
  205. // ModuleExportName.
  206. case "ExportSpecifier":
  207. return parent.local === node || parent.exported === node;
  208. // Others don't allow.
  209. default:
  210. return false;
  211. }
  212. }
  213. /**
  214. * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
  215. * @param {ASTNode} node A TemplateLiteral node to check.
  216. * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
  217. * @private
  218. */
  219. function isUsingFeatureOfTemplateLiteral(node) {
  220. const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
  221. if (hasTag) {
  222. return true;
  223. }
  224. const hasStringInterpolation = node.expressions.length > 0;
  225. if (hasStringInterpolation) {
  226. return true;
  227. }
  228. const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
  229. if (isMultilineString) {
  230. return true;
  231. }
  232. return false;
  233. }
  234. return {
  235. Literal(node) {
  236. const val = node.value,
  237. rawVal = node.raw;
  238. if (settings && typeof val === "string") {
  239. let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
  240. isJSXLiteral(node) ||
  241. astUtils.isSurroundedBy(rawVal, settings.quote);
  242. if (!isValid && avoidEscape) {
  243. isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.includes(settings.quote);
  244. }
  245. if (!isValid) {
  246. context.report({
  247. node,
  248. messageId: "wrongQuotes",
  249. data: {
  250. description: settings.description
  251. },
  252. fix(fixer) {
  253. if (quoteOption === "backtick" && astUtils.hasOctalOrNonOctalDecimalEscapeSequence(rawVal)) {
  254. /*
  255. * An octal or non-octal decimal escape sequence in a template literal would
  256. * produce syntax error, even in non-strict mode.
  257. */
  258. return null;
  259. }
  260. return fixer.replaceText(node, settings.convert(node.raw));
  261. }
  262. });
  263. }
  264. }
  265. },
  266. TemplateLiteral(node) {
  267. // Don't throw an error if backticks are expected or a template literal feature is in use.
  268. if (
  269. allowTemplateLiterals ||
  270. quoteOption === "backtick" ||
  271. isUsingFeatureOfTemplateLiteral(node)
  272. ) {
  273. return;
  274. }
  275. context.report({
  276. node,
  277. messageId: "wrongQuotes",
  278. data: {
  279. description: settings.description
  280. },
  281. fix(fixer) {
  282. if (astUtils.isTopLevelExpressionStatement(node.parent) && !astUtils.isParenthesised(sourceCode, node)) {
  283. /*
  284. * TemplateLiterals aren't actually directives, but fixing them might turn
  285. * them into directives and change the behavior of the code.
  286. */
  287. return null;
  288. }
  289. return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));
  290. }
  291. });
  292. }
  293. };
  294. }
  295. };