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 //------------------------------------------------------------------------------
77 /** @type {import('../shared/types').Rule} */
83 description
: "Enforce the consistent use of either backticks, double, or single quotes",
85 url
: "https://eslint.org/docs/latest/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
.sourceCode
;
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 "PropertyDefinition":
220 case "MethodDefinition":
221 return parent
.key
=== node
&& !parent
.computed
;
224 case "ImportDeclaration":
225 case "ExportNamedDeclaration":
226 return parent
.source
=== node
;
228 // ModuleExportName or ModuleSpecifier.
229 case "ExportAllDeclaration":
230 return parent
.exported
=== node
|| parent
.source
=== node
;
233 case "ImportSpecifier":
234 return parent
.imported
=== node
;
237 case "ExportSpecifier":
238 return parent
.local
=== node
|| parent
.exported
=== node
;
240 // Others don't allow.
247 * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
248 * @param {ASTNode} node A TemplateLiteral node to check.
249 * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
252 function isUsingFeatureOfTemplateLiteral(node
) {
253 const hasTag
= node
.parent
.type
=== "TaggedTemplateExpression" && node
=== node
.parent
.quasi
;
259 const hasStringInterpolation
= node
.expressions
.length
> 0;
261 if (hasStringInterpolation
) {
265 const isMultilineString
= node
.quasis
.length
>= 1 && UNESCAPED_LINEBREAK_PATTERN
.test(node
.quasis
[0].value
.raw
);
267 if (isMultilineString
) {
277 const val
= node
.value
,
280 if (settings
&& typeof val
=== "string") {
281 let isValid
= (quoteOption
=== "backtick" && isAllowedAsNonBacktick(node
)) ||
282 isJSXLiteral(node
) ||
283 astUtils
.isSurroundedBy(rawVal
, settings
.quote
);
285 if (!isValid
&& avoidEscape
) {
286 isValid
= astUtils
.isSurroundedBy(rawVal
, settings
.alternateQuote
) && rawVal
.includes(settings
.quote
);
292 messageId
: "wrongQuotes",
294 description
: settings
.description
297 if (quoteOption
=== "backtick" && astUtils
.hasOctalOrNonOctalDecimalEscapeSequence(rawVal
)) {
300 * An octal or non-octal decimal escape sequence in a template literal would
301 * produce syntax error, even in non-strict mode.
306 return fixer
.replaceText(node
, settings
.convert(node
.raw
));
313 TemplateLiteral(node
) {
315 // Don't throw an error if backticks are expected or a template literal feature is in use.
317 allowTemplateLiterals
||
318 quoteOption
=== "backtick" ||
319 isUsingFeatureOfTemplateLiteral(node
)
326 messageId
: "wrongQuotes",
328 description
: settings
.description
331 if (isPartOfDirectivePrologue(node
)) {
334 * TemplateLiterals in a directive prologue aren't actually directives, but if they're
335 * in the directive prologue, then fixing them might turn them into directives and change
336 * the behavior of the code.
340 return fixer
.replaceText(node
, settings
.convert(sourceCode
.getText(node
)));