UNPKG

10.6 kBJavaScriptView Raw
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"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("../ast-utils");
13
14//------------------------------------------------------------------------------
15// Constants
16//------------------------------------------------------------------------------
17
18const 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.
37const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`);
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 */
48QUOTE_SETTINGS.double.convert =
49QUOTE_SETTINGS.single.convert =
50QUOTE_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)/g, (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
71const AVOID_ESCAPE = "avoid-escape";
72
73//------------------------------------------------------------------------------
74// Rule Definition
75//------------------------------------------------------------------------------
76
77module.exports = {
78 meta: {
79 docs: {
80 description: "enforce the consistent use of either backticks, double, or single quotes",
81 category: "Stylistic Issues",
82 recommended: false,
83 url: "https://eslint.org/docs/rules/quotes"
84 },
85
86 fixable: "code",
87
88 schema: [
89 {
90 enum: ["single", "double", "backtick"]
91 },
92 {
93 anyOf: [
94 {
95 enum: ["avoid-escape"]
96 },
97 {
98 type: "object",
99 properties: {
100 avoidEscape: {
101 type: "boolean"
102 },
103 allowTemplateLiterals: {
104 type: "boolean"
105 }
106 },
107 additionalProperties: false
108 }
109 ]
110 }
111 ]
112 },
113
114 create(context) {
115
116 const quoteOption = context.options[0],
117 settings = QUOTE_SETTINGS[quoteOption || "double"],
118 options = context.options[1],
119 allowTemplateLiterals = options && options.allowTemplateLiterals === true,
120 sourceCode = context.getSourceCode();
121 let avoidEscape = options && options.avoidEscape === true;
122
123 // deprecated
124 if (options === AVOID_ESCAPE) {
125 avoidEscape = true;
126 }
127
128 /**
129 * Determines if a given node is part of JSX syntax.
130 *
131 * This function returns `true` in the following cases:
132 *
133 * - `<div className="foo"></div>` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`.
134 * - `<div>foo</div>` ... If the literal is a text content, the parent of the literal is `JSXElement`.
135 *
136 * In particular, this function returns `false` in the following cases:
137 *
138 * - `<div className={"foo"}></div>`
139 * - `<div>{"foo"}</div>`
140 *
141 * In both cases, inside of the braces is handled as normal JavaScript.
142 * The braces are `JSXExpressionContainer` nodes.
143 *
144 * @param {ASTNode} node The Literal node to check.
145 * @returns {boolean} True if the node is a part of JSX, false if not.
146 * @private
147 */
148 function isJSXLiteral(node) {
149 return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement";
150 }
151
152 /**
153 * Checks whether or not a given node is a directive.
154 * The directive is a `ExpressionStatement` which has only a string literal.
155 * @param {ASTNode} node - A node to check.
156 * @returns {boolean} Whether or not the node is a directive.
157 * @private
158 */
159 function isDirective(node) {
160 return (
161 node.type === "ExpressionStatement" &&
162 node.expression.type === "Literal" &&
163 typeof node.expression.value === "string"
164 );
165 }
166
167 /**
168 * Checks whether or not a given node is a part of directive prologues.
169 * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive
170 * @param {ASTNode} node - A node to check.
171 * @returns {boolean} Whether or not the node is a part of directive prologues.
172 * @private
173 */
174 function isPartOfDirectivePrologue(node) {
175 const block = node.parent.parent;
176
177 if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) {
178 return false;
179 }
180
181 // Check the node is at a prologue.
182 for (let i = 0; i < block.body.length; ++i) {
183 const statement = block.body[i];
184
185 if (statement === node.parent) {
186 return true;
187 }
188 if (!isDirective(statement)) {
189 break;
190 }
191 }
192
193 return false;
194 }
195
196 /**
197 * Checks whether or not a given node is allowed as non backtick.
198 * @param {ASTNode} node - A node to check.
199 * @returns {boolean} Whether or not the node is allowed as non backtick.
200 * @private
201 */
202 function isAllowedAsNonBacktick(node) {
203 const parent = node.parent;
204
205 switch (parent.type) {
206
207 // Directive Prologues.
208 case "ExpressionStatement":
209 return isPartOfDirectivePrologue(node);
210
211 // LiteralPropertyName.
212 case "Property":
213 case "MethodDefinition":
214 return parent.key === node && !parent.computed;
215
216 // ModuleSpecifier.
217 case "ImportDeclaration":
218 case "ExportNamedDeclaration":
219 case "ExportAllDeclaration":
220 return parent.source === node;
221
222 // Others don't allow.
223 default:
224 return false;
225 }
226 }
227
228 return {
229
230 Literal(node) {
231 const val = node.value,
232 rawVal = node.raw;
233
234 if (settings && typeof val === "string") {
235 let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
236 isJSXLiteral(node) ||
237 astUtils.isSurroundedBy(rawVal, settings.quote);
238
239 if (!isValid && avoidEscape) {
240 isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
241 }
242
243 if (!isValid) {
244 context.report({
245 node,
246 message: "Strings must use {{description}}.",
247 data: {
248 description: settings.description
249 },
250 fix(fixer) {
251 return fixer.replaceText(node, settings.convert(node.raw));
252 }
253 });
254 }
255 }
256 },
257
258 TemplateLiteral(node) {
259
260 // If backticks are expected or it's a tagged template, then this shouldn't throw an errors
261 if (
262 allowTemplateLiterals ||
263 quoteOption === "backtick" ||
264 node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi
265 ) {
266 return;
267 }
268
269 // A warning should be produced if the template literal only has one TemplateElement, and has no unescaped newlines.
270 const shouldWarn = node.quasis.length === 1 && !UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
271
272 if (shouldWarn) {
273 context.report({
274 node,
275 message: "Strings must use {{description}}.",
276 data: {
277 description: settings.description
278 },
279 fix(fixer) {
280 if (isPartOfDirectivePrologue(node)) {
281
282 /*
283 * TemplateLiterals in a directive prologue aren't actually directives, but if they're
284 * in the directive prologue, then fixing them might turn them into directives and change
285 * the behavior of the code.
286 */
287 return null;
288 }
289 return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));
290 }
291 });
292 }
293 }
294 };
295
296 }
297};