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 |
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Requirements
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | const astUtils = require("./utils/ast-utils");
|
13 |
|
14 | //------------------------------------------------------------------------------
|
15 | // Constants
|
16 | //------------------------------------------------------------------------------
|
17 |
|
18 | const QUOTE_SETTINGS = {
|
19 | double: {
|
20 | quote: "\"",
|
21 | alternateQuote: "'",
|
22 | description: "doublequote"
|
23 | },
|
24 | single: {
|
25 | quote: "'",
|
26 | alternateQuote: "\"",
|
27 | description: "singlequote"
|
28 | },
|
29 | backtick: {
|
30 | quote: "`",
|
31 | alternateQuote: "\"",
|
32 | description: "backtick"
|
33 | }
|
34 | };
|
35 |
|
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");
|
38 |
|
39 | /**
|
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.
|
46 | * @private
|
47 | */
|
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];
|
53 |
|
54 | if (newQuote === oldQuote) {
|
55 | return str;
|
56 | }
|
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
|
60 | }
|
61 | if (match === newQuote || newQuote === "`" && match === "${") {
|
62 | return `\\${match}`; // escape
|
63 | }
|
64 | if (newline && oldQuote === "`") {
|
65 | return "\\n"; // escape newlines
|
66 | }
|
67 | return match;
|
68 | }) + newQuote;
|
69 | };
|
70 |
|
71 | const AVOID_ESCAPE = "avoid-escape";
|
72 |
|
73 | //------------------------------------------------------------------------------
|
74 | // Rule Definition
|
75 | //------------------------------------------------------------------------------
|
76 |
|
77 | module.exports = {
|
78 | meta: {
|
79 | type: "layout",
|
80 |
|
81 | docs: {
|
82 | description: "enforce the consistent use of either backticks, double, or single quotes",
|
83 | category: "Stylistic Issues",
|
84 | recommended: false,
|
85 | url: "https://eslint.org/docs/rules/quotes"
|
86 | },
|
87 |
|
88 | fixable: "code",
|
89 |
|
90 | schema: [
|
91 | {
|
92 | enum: ["single", "double", "backtick"]
|
93 | },
|
94 | {
|
95 | anyOf: [
|
96 | {
|
97 | enum: ["avoid-escape"]
|
98 | },
|
99 | {
|
100 | type: "object",
|
101 | properties: {
|
102 | avoidEscape: {
|
103 | type: "boolean"
|
104 | },
|
105 | allowTemplateLiterals: {
|
106 | type: "boolean"
|
107 | }
|
108 | },
|
109 | additionalProperties: false
|
110 | }
|
111 | ]
|
112 | }
|
113 | ]
|
114 | },
|
115 |
|
116 | create(context) {
|
117 |
|
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;
|
124 |
|
125 | // deprecated
|
126 | if (options === AVOID_ESCAPE) {
|
127 | avoidEscape = true;
|
128 | }
|
129 |
|
130 | /**
|
131 | * Determines if a given node is part of JSX syntax.
|
132 | *
|
133 | * This function returns `true` in the following cases:
|
134 | *
|
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`.
|
138 | *
|
139 | * In particular, this function returns `false` in the following cases:
|
140 | *
|
141 | * - `<div className={"foo"}></div>`
|
142 | * - `<div>{"foo"}</div>`
|
143 | *
|
144 | * In both cases, inside of the braces is handled as normal JavaScript.
|
145 | * The braces are `JSXExpressionContainer` nodes.
|
146 | *
|
147 | * @param {ASTNode} node The Literal node to check.
|
148 | * @returns {boolean} True if the node is a part of JSX, false if not.
|
149 | * @private
|
150 | */
|
151 | function isJSXLiteral(node) {
|
152 | return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
|
153 | }
|
154 |
|
155 | /**
|
156 | * Checks whether or not a given node is a directive.
|
157 | * The directive is a `ExpressionStatement` which has only a string literal.
|
158 | * @param {ASTNode} node - A node to check.
|
159 | * @returns {boolean} Whether or not the node is a directive.
|
160 | * @private
|
161 | */
|
162 | function isDirective(node) {
|
163 | return (
|
164 | node.type === "ExpressionStatement" &&
|
165 | node.expression.type === "Literal" &&
|
166 | typeof node.expression.value === "string"
|
167 | );
|
168 | }
|
169 |
|
170 | /**
|
171 | * Checks whether or not a given node is a part of directive prologues.
|
172 | * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive
|
173 | * @param {ASTNode} node - A node to check.
|
174 | * @returns {boolean} Whether or not the node is a part of directive prologues.
|
175 | * @private
|
176 | */
|
177 | function isPartOfDirectivePrologue(node) {
|
178 | const block = node.parent.parent;
|
179 |
|
180 | if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) {
|
181 | return false;
|
182 | }
|
183 |
|
184 | // Check the node is at a prologue.
|
185 | for (let i = 0; i < block.body.length; ++i) {
|
186 | const statement = block.body[i];
|
187 |
|
188 | if (statement === node.parent) {
|
189 | return true;
|
190 | }
|
191 | if (!isDirective(statement)) {
|
192 | break;
|
193 | }
|
194 | }
|
195 |
|
196 | return false;
|
197 | }
|
198 |
|
199 | /**
|
200 | * Checks whether or not a given node is allowed as non backtick.
|
201 | * @param {ASTNode} node - A node to check.
|
202 | * @returns {boolean} Whether or not the node is allowed as non backtick.
|
203 | * @private
|
204 | */
|
205 | function isAllowedAsNonBacktick(node) {
|
206 | const parent = node.parent;
|
207 |
|
208 | switch (parent.type) {
|
209 |
|
210 | // Directive Prologues.
|
211 | case "ExpressionStatement":
|
212 | return isPartOfDirectivePrologue(node);
|
213 |
|
214 | // LiteralPropertyName.
|
215 | case "Property":
|
216 | case "MethodDefinition":
|
217 | return parent.key === node && !parent.computed;
|
218 |
|
219 | // ModuleSpecifier.
|
220 | case "ImportDeclaration":
|
221 | case "ExportNamedDeclaration":
|
222 | case "ExportAllDeclaration":
|
223 | return parent.source === node;
|
224 |
|
225 | // Others don't allow.
|
226 | default:
|
227 | return false;
|
228 | }
|
229 | }
|
230 |
|
231 | /**
|
232 | * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
|
233 | * @param {ASTNode} node - A TemplateLiteral node to check.
|
234 | * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
|
235 | * @private
|
236 | */
|
237 | function isUsingFeatureOfTemplateLiteral(node) {
|
238 | const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
|
239 |
|
240 | if (hasTag) {
|
241 | return true;
|
242 | }
|
243 |
|
244 | const hasStringInterpolation = node.expressions.length > 0;
|
245 |
|
246 | if (hasStringInterpolation) {
|
247 | return true;
|
248 | }
|
249 |
|
250 | const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
|
251 |
|
252 | if (isMultilineString) {
|
253 | return true;
|
254 | }
|
255 |
|
256 | return false;
|
257 | }
|
258 |
|
259 | return {
|
260 |
|
261 | Literal(node) {
|
262 | const val = node.value,
|
263 | rawVal = node.raw;
|
264 |
|
265 | if (settings && typeof val === "string") {
|
266 | let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
|
267 | isJSXLiteral(node) ||
|
268 | astUtils.isSurroundedBy(rawVal, settings.quote);
|
269 |
|
270 | if (!isValid && avoidEscape) {
|
271 | isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
|
272 | }
|
273 |
|
274 | if (!isValid) {
|
275 | context.report({
|
276 | node,
|
277 | message: "Strings must use {{description}}.",
|
278 | data: {
|
279 | description: settings.description
|
280 | },
|
281 | fix(fixer) {
|
282 | return fixer.replaceText(node, settings.convert(node.raw));
|
283 | }
|
284 | });
|
285 | }
|
286 | }
|
287 | },
|
288 |
|
289 | TemplateLiteral(node) {
|
290 |
|
291 | // Don't throw an error if backticks are expected or a template literal feature is in use.
|
292 | if (
|
293 | allowTemplateLiterals ||
|
294 | quoteOption === "backtick" ||
|
295 | isUsingFeatureOfTemplateLiteral(node)
|
296 | ) {
|
297 | return;
|
298 | }
|
299 |
|
300 | context.report({
|
301 | node,
|
302 | message: "Strings must use {{description}}.",
|
303 | data: {
|
304 | description: settings.description
|
305 | },
|
306 | fix(fixer) {
|
307 | if (isPartOfDirectivePrologue(node)) {
|
308 |
|
309 | /*
|
310 | * TemplateLiterals in a directive prologue aren't actually directives, but if they're
|
311 | * in the directive prologue, then fixing them might turn them into directives and change
|
312 | * the behavior of the code.
|
313 | */
|
314 | return null;
|
315 | }
|
316 | return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));
|
317 | }
|
318 | });
|
319 | }
|
320 | };
|
321 |
|
322 | }
|
323 | };
|