2 * @fileoverview A rule to choose between single and double quote marks
3 * @author Matt DuVall <http://www.mattduvall.com/>, Brandon Payton
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
18 const QUOTE_SETTINGS = {
22 description: "doublequote"
27 description: "singlequote"
32 description: "backtick"
36 // An unescaped newline is a newline preceded by an even number of backslashes.
37 const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`, "u");
40 * Switches quoting of javascript string between ' " and `
41 * escaping and unescaping as necessary.
42 * Only escaping of the minimal set of characters is changed.
43 * Note: escaping of newlines when switching from backtick to other quotes is not handled.
44 * @param {string} str A string to convert.
45 * @returns {string} The string with changed quotes.
48 QUOTE_SETTINGS.double.convert =
49 QUOTE_SETTINGS.single.convert =
50 QUOTE_SETTINGS.backtick.convert = function(str) {
51 const newQuote = this.quote;
52 const oldQuote = str[0];
54 if (newQuote === oldQuote) {
57 return newQuote + str.slice(1, -1).replace(/\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, (match, escaped, newline) => {
58 if (escaped === oldQuote || oldQuote === "`" && escaped === "${") {
59 return escaped; // unescape
61 if (match === newQuote || newQuote === "`" && match === "${") {
62 return `\\${match}`; // escape
64 if (newline && oldQuote === "`") {
65 return "\\n"; // escape newlines
71 const AVOID_ESCAPE = "avoid-escape";
73 //------------------------------------------------------------------------------
75 //------------------------------------------------------------------------------
82 description: "enforce the consistent use of either backticks, double, or single quotes",
83 category: "Stylistic Issues",
85 url: "https://eslint.org/docs/rules/quotes"
92 enum: ["single", "double", "backtick"]
97 enum: ["avoid-escape"]
105 allowTemplateLiterals: {
109 additionalProperties: false
118 const quoteOption = context.options[0],
119 settings = QUOTE_SETTINGS[quoteOption || "double"],
120 options = context.options[1],
121 allowTemplateLiterals = options && options.allowTemplateLiterals === true,
122 sourceCode = context.getSourceCode();
123 let avoidEscape = options && options.avoidEscape === true;
126 if (options === AVOID_ESCAPE) {
131 * Determines if a given node is part of JSX syntax.
133 * This function returns `true` in the following cases:
135 * - `<div className="foo"></div>` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`.
136 * - `<div>foo</div>` ... If the literal is a text content, the parent of the literal is `JSXElement`.
137 * - `<>foo</>` ... If the literal is a text content, the parent of the literal is `JSXFragment`.
139 * In particular, this function returns `false` in the following cases:
141 * - `<div className={"foo"}></div>`
142 * - `<div>{"foo"}</div>`
144 * In both cases, inside of the braces is handled as normal JavaScript.
145 * The braces are `JSXExpressionContainer` nodes.
146 * @param {ASTNode} node The Literal node to check.
147 * @returns {boolean} True if the node is a part of JSX, false if not.
150 function isJSXLiteral(node) {
151 return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
155 * Checks whether or not a given node is a directive.
156 * The directive is a `ExpressionStatement` which has only a string literal.
157 * @param {ASTNode} node A node to check.
158 * @returns {boolean} Whether or not the node is a directive.
161 function isDirective(node) {
163 node.type === "ExpressionStatement" &&
164 node.expression.type === "Literal" &&
165 typeof node.expression.value === "string"
170 * Checks whether or not a given node is a part of directive prologues.
171 * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive
172 * @param {ASTNode} node A node to check.
173 * @returns {boolean} Whether or not the node is a part of directive prologues.
176 function isPartOfDirectivePrologue(node) {
177 const block = node.parent.parent;
179 if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) {
183 // Check the node is at a prologue.
184 for (let i = 0; i < block.body.length; ++i) {
185 const statement = block.body[i];
187 if (statement === node.parent) {
190 if (!isDirective(statement)) {
199 * Checks whether or not a given node is allowed as non backtick.
200 * @param {ASTNode} node A node to check.
201 * @returns {boolean} Whether or not the node is allowed as non backtick.
204 function isAllowedAsNonBacktick(node) {
205 const parent = node.parent;
207 switch (parent.type) {
209 // Directive Prologues.
210 case "ExpressionStatement":
211 return isPartOfDirectivePrologue(node);
213 // LiteralPropertyName.
215 case "MethodDefinition":
216 return parent.key === node && !parent.computed;
219 case "ImportDeclaration":
220 case "ExportNamedDeclaration":
221 case "ExportAllDeclaration":
222 return parent.source === node;
224 // Others don't allow.
231 * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
232 * @param {ASTNode} node A TemplateLiteral node to check.
233 * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
236 function isUsingFeatureOfTemplateLiteral(node) {
237 const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
243 const hasStringInterpolation = node.expressions.length > 0;
245 if (hasStringInterpolation) {
249 const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
251 if (isMultilineString) {
261 const val = node.value,
264 if (settings && typeof val === "string") {
265 let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
266 isJSXLiteral(node) ||
267 astUtils.isSurroundedBy(rawVal, settings.quote);
269 if (!isValid && avoidEscape) {
270 isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
276 message: "Strings must use {{description}}.",
278 description: settings.description
281 if (quoteOption === "backtick" && astUtils.hasOctalEscapeSequence(rawVal)) {
283 // An octal escape sequence in a template literal would produce syntax error, even in non-strict mode.
287 return fixer.replaceText(node, settings.convert(node.raw));
294 TemplateLiteral(node) {
296 // Don't throw an error if backticks are expected or a template literal feature is in use.
298 allowTemplateLiterals ||
299 quoteOption === "backtick" ||
300 isUsingFeatureOfTemplateLiteral(node)
307 message: "Strings must use {{description}}.",
309 description: settings.description
312 if (isPartOfDirectivePrologue(node)) {
315 * TemplateLiterals in a directive prologue aren't actually directives, but if they're
316 * in the directive prologue, then fixing them might turn them into directives and change
317 * the behavior of the code.
321 return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));