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
116 wrongQuotes: "Strings must use {{description}}."
122 const quoteOption = context.options[0],
123 settings = QUOTE_SETTINGS[quoteOption || "double"],
124 options = context.options[1],
125 allowTemplateLiterals = options && options.allowTemplateLiterals === true,
126 sourceCode = context.getSourceCode();
127 let avoidEscape = options && options.avoidEscape === true;
130 if (options === AVOID_ESCAPE) {
135 * Determines if a given node is part of JSX syntax.
137 * This function returns `true` in the following cases:
139 * - `<div className="foo"></div>` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`.
140 * - `<div>foo</div>` ... If the literal is a text content, the parent of the literal is `JSXElement`.
141 * - `<>foo</>` ... If the literal is a text content, the parent of the literal is `JSXFragment`.
143 * In particular, this function returns `false` in the following cases:
145 * - `<div className={"foo"}></div>`
146 * - `<div>{"foo"}</div>`
148 * In both cases, inside of the braces is handled as normal JavaScript.
149 * The braces are `JSXExpressionContainer` nodes.
150 * @param {ASTNode} node The Literal node to check.
151 * @returns {boolean} True if the node is a part of JSX, false if not.
154 function isJSXLiteral(node) {
155 return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
159 * Checks whether or not a given node is a directive.
160 * The directive is a `ExpressionStatement` which has only a string literal.
161 * @param {ASTNode} node A node to check.
162 * @returns {boolean} Whether or not the node is a directive.
165 function isDirective(node) {
167 node.type === "ExpressionStatement" &&
168 node.expression.type === "Literal" &&
169 typeof node.expression.value === "string"
174 * Checks whether or not a given node is a part of directive prologues.
175 * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive
176 * @param {ASTNode} node A node to check.
177 * @returns {boolean} Whether or not the node is a part of directive prologues.
180 function isPartOfDirectivePrologue(node) {
181 const block = node.parent.parent;
183 if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) {
187 // Check the node is at a prologue.
188 for (let i = 0; i < block.body.length; ++i) {
189 const statement = block.body[i];
191 if (statement === node.parent) {
194 if (!isDirective(statement)) {
203 * Checks whether or not a given node is allowed as non backtick.
204 * @param {ASTNode} node A node to check.
205 * @returns {boolean} Whether or not the node is allowed as non backtick.
208 function isAllowedAsNonBacktick(node) {
209 const parent = node.parent;
211 switch (parent.type) {
213 // Directive Prologues.
214 case "ExpressionStatement":
215 return isPartOfDirectivePrologue(node);
217 // LiteralPropertyName.
219 case "MethodDefinition":
220 return parent.key === node && !parent.computed;
223 case "ImportDeclaration":
224 case "ExportNamedDeclaration":
225 case "ExportAllDeclaration":
226 return parent.source === node;
228 // Others don't allow.
235 * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
236 * @param {ASTNode} node A TemplateLiteral node to check.
237 * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
240 function isUsingFeatureOfTemplateLiteral(node) {
241 const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
247 const hasStringInterpolation = node.expressions.length > 0;
249 if (hasStringInterpolation) {
253 const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
255 if (isMultilineString) {
265 const val = node.value,
268 if (settings && typeof val === "string") {
269 let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
270 isJSXLiteral(node) ||
271 astUtils.isSurroundedBy(rawVal, settings.quote);
273 if (!isValid && avoidEscape) {
274 isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
280 messageId: "wrongQuotes",
282 description: settings.description
285 if (quoteOption === "backtick" && astUtils.hasOctalOrNonOctalDecimalEscapeSequence(rawVal)) {
288 * An octal or non-octal decimal escape sequence in a template literal would
289 * produce syntax error, even in non-strict mode.
294 return fixer.replaceText(node, settings.convert(node.raw));
301 TemplateLiteral(node) {
303 // Don't throw an error if backticks are expected or a template literal feature is in use.
305 allowTemplateLiterals ||
306 quoteOption === "backtick" ||
307 isUsingFeatureOfTemplateLiteral(node)
314 messageId: "wrongQuotes",
316 description: settings.description
319 if (isPartOfDirectivePrologue(node)) {
322 * TemplateLiterals in a directive prologue aren't actually directives, but if they're
323 * in the directive prologue, then fixing them might turn them into directives and change
324 * the behavior of the code.
328 return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));