quotes.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. module.exports = {
  67. meta: {
  68. type: "layout",
  69. docs: {
  70. description: "enforce the consistent use of either backticks, double, or single quotes",
  71. category: "Stylistic Issues",
  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 "MethodDefinition":
  191. return parent.key === node && !parent.computed;
  192. // ModuleSpecifier.
  193. case "ImportDeclaration":
  194. case "ExportNamedDeclaration":
  195. case "ExportAllDeclaration":
  196. return parent.source === node;
  197. // Others don't allow.
  198. default:
  199. return false;
  200. }
  201. }
  202. /**
  203. * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
  204. * @param {ASTNode} node A TemplateLiteral node to check.
  205. * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
  206. * @private
  207. */
  208. function isUsingFeatureOfTemplateLiteral(node) {
  209. const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
  210. if (hasTag) {
  211. return true;
  212. }
  213. const hasStringInterpolation = node.expressions.length > 0;
  214. if (hasStringInterpolation) {
  215. return true;
  216. }
  217. const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
  218. if (isMultilineString) {
  219. return true;
  220. }
  221. return false;
  222. }
  223. return {
  224. Literal(node) {
  225. const val = node.value,
  226. rawVal = node.raw;
  227. if (settings && typeof val === "string") {
  228. let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
  229. isJSXLiteral(node) ||
  230. astUtils.isSurroundedBy(rawVal, settings.quote);
  231. if (!isValid && avoidEscape) {
  232. isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
  233. }
  234. if (!isValid) {
  235. context.report({
  236. node,
  237. messageId: "wrongQuotes",
  238. data: {
  239. description: settings.description
  240. },
  241. fix(fixer) {
  242. if (quoteOption === "backtick" && astUtils.hasOctalEscapeSequence(rawVal)) {
  243. // An octal escape sequence in a template literal would produce syntax error, even in non-strict mode.
  244. return null;
  245. }
  246. return fixer.replaceText(node, settings.convert(node.raw));
  247. }
  248. });
  249. }
  250. }
  251. },
  252. TemplateLiteral(node) {
  253. // Don't throw an error if backticks are expected or a template literal feature is in use.
  254. if (
  255. allowTemplateLiterals ||
  256. quoteOption === "backtick" ||
  257. isUsingFeatureOfTemplateLiteral(node)
  258. ) {
  259. return;
  260. }
  261. context.report({
  262. node,
  263. messageId: "wrongQuotes",
  264. data: {
  265. description: settings.description
  266. },
  267. fix(fixer) {
  268. if (isPartOfDirectivePrologue(node)) {
  269. /*
  270. * TemplateLiterals in a directive prologue aren't actually directives, but if they're
  271. * in the directive prologue, then fixing them might turn them into directives and change
  272. * the behavior of the code.
  273. */
  274. return null;
  275. }
  276. return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));
  277. }
  278. });
  279. }
  280. };
  281. }
  282. };