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/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.getSourceCode();
  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.
  141. * @param {ASTNode} node A node to check.
  142. * @returns {boolean} Whether or not the node is a directive.
  143. * @private
  144. */
  145. function isDirective(node) {
  146. return (
  147. node.type === "ExpressionStatement" &&
  148. node.expression.type === "Literal" &&
  149. typeof node.expression.value === "string"
  150. );
  151. }
  152. /**
  153. * Checks whether or not a given node is a part of directive prologues.
  154. * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive
  155. * @param {ASTNode} node A node to check.
  156. * @returns {boolean} Whether or not the node is a part of directive prologues.
  157. * @private
  158. */
  159. function isPartOfDirectivePrologue(node) {
  160. const block = node.parent.parent;
  161. if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) {
  162. return false;
  163. }
  164. // Check the node is at a prologue.
  165. for (let i = 0; i < block.body.length; ++i) {
  166. const statement = block.body[i];
  167. if (statement === node.parent) {
  168. return true;
  169. }
  170. if (!isDirective(statement)) {
  171. break;
  172. }
  173. }
  174. return false;
  175. }
  176. /**
  177. * Checks whether or not a given node is allowed as non backtick.
  178. * @param {ASTNode} node A node to check.
  179. * @returns {boolean} Whether or not the node is allowed as non backtick.
  180. * @private
  181. */
  182. function isAllowedAsNonBacktick(node) {
  183. const parent = node.parent;
  184. switch (parent.type) {
  185. // Directive Prologues.
  186. case "ExpressionStatement":
  187. return isPartOfDirectivePrologue(node);
  188. // LiteralPropertyName.
  189. case "Property":
  190. case "PropertyDefinition":
  191. case "MethodDefinition":
  192. return parent.key === node && !parent.computed;
  193. // ModuleSpecifier.
  194. case "ImportDeclaration":
  195. case "ExportNamedDeclaration":
  196. return parent.source === node;
  197. // ModuleExportName or ModuleSpecifier.
  198. case "ExportAllDeclaration":
  199. return parent.exported === node || parent.source === node;
  200. // ModuleExportName.
  201. case "ImportSpecifier":
  202. return parent.imported === node;
  203. // ModuleExportName.
  204. case "ExportSpecifier":
  205. return parent.local === node || parent.exported === node;
  206. // Others don't allow.
  207. default:
  208. return false;
  209. }
  210. }
  211. /**
  212. * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
  213. * @param {ASTNode} node A TemplateLiteral node to check.
  214. * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
  215. * @private
  216. */
  217. function isUsingFeatureOfTemplateLiteral(node) {
  218. const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
  219. if (hasTag) {
  220. return true;
  221. }
  222. const hasStringInterpolation = node.expressions.length > 0;
  223. if (hasStringInterpolation) {
  224. return true;
  225. }
  226. const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
  227. if (isMultilineString) {
  228. return true;
  229. }
  230. return false;
  231. }
  232. return {
  233. Literal(node) {
  234. const val = node.value,
  235. rawVal = node.raw;
  236. if (settings && typeof val === "string") {
  237. let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
  238. isJSXLiteral(node) ||
  239. astUtils.isSurroundedBy(rawVal, settings.quote);
  240. if (!isValid && avoidEscape) {
  241. isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.includes(settings.quote);
  242. }
  243. if (!isValid) {
  244. context.report({
  245. node,
  246. messageId: "wrongQuotes",
  247. data: {
  248. description: settings.description
  249. },
  250. fix(fixer) {
  251. if (quoteOption === "backtick" && astUtils.hasOctalOrNonOctalDecimalEscapeSequence(rawVal)) {
  252. /*
  253. * An octal or non-octal decimal escape sequence in a template literal would
  254. * produce syntax error, even in non-strict mode.
  255. */
  256. return null;
  257. }
  258. return fixer.replaceText(node, settings.convert(node.raw));
  259. }
  260. });
  261. }
  262. }
  263. },
  264. TemplateLiteral(node) {
  265. // Don't throw an error if backticks are expected or a template literal feature is in use.
  266. if (
  267. allowTemplateLiterals ||
  268. quoteOption === "backtick" ||
  269. isUsingFeatureOfTemplateLiteral(node)
  270. ) {
  271. return;
  272. }
  273. context.report({
  274. node,
  275. messageId: "wrongQuotes",
  276. data: {
  277. description: settings.description
  278. },
  279. fix(fixer) {
  280. if (isPartOfDirectivePrologue(node)) {
  281. /*
  282. * TemplateLiterals in a directive prologue aren't actually directives, but if they're
  283. * in the directive prologue, then fixing them might turn them into directives and change
  284. * the behavior of the code.
  285. */
  286. return null;
  287. }
  288. return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));
  289. }
  290. });
  291. }
  292. };
  293. }
  294. };