UNPKG

9.57 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow whitespace that is not a tab or space, whitespace inside strings and comments are allowed
3 * @author Jonathan Kingston
4 * @author Christophe Porteneuve
5 */
6
7"use strict";
8
9//------------------------------------------------------------------------------
10// Requirements
11//------------------------------------------------------------------------------
12
13const astUtils = require("./utils/ast-utils");
14
15//------------------------------------------------------------------------------
16// Constants
17//------------------------------------------------------------------------------
18
19const ALL_IRREGULARS = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/u;
20const IRREGULAR_WHITESPACE = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mgu;
21const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mgu;
22const LINE_BREAK = astUtils.createGlobalLinebreakMatcher();
23
24//------------------------------------------------------------------------------
25// Rule Definition
26//------------------------------------------------------------------------------
27
28module.exports = {
29 meta: {
30 type: "problem",
31
32 docs: {
33 description: "disallow irregular whitespace",
34 category: "Possible Errors",
35 recommended: true,
36 url: "https://eslint.org/docs/rules/no-irregular-whitespace"
37 },
38
39 schema: [
40 {
41 type: "object",
42 properties: {
43 skipComments: {
44 type: "boolean",
45 default: false
46 },
47 skipStrings: {
48 type: "boolean",
49 default: true
50 },
51 skipTemplates: {
52 type: "boolean",
53 default: false
54 },
55 skipRegExps: {
56 type: "boolean",
57 default: false
58 }
59 },
60 additionalProperties: false
61 }
62 ],
63
64 messages: {
65 noIrregularWhitespace: "Irregular whitespace not allowed."
66 }
67 },
68
69 create(context) {
70
71 // Module store of errors that we have found
72 let errors = [];
73
74 // Lookup the `skipComments` option, which defaults to `false`.
75 const options = context.options[0] || {};
76 const skipComments = !!options.skipComments;
77 const skipStrings = options.skipStrings !== false;
78 const skipRegExps = !!options.skipRegExps;
79 const skipTemplates = !!options.skipTemplates;
80
81 const sourceCode = context.getSourceCode();
82 const commentNodes = sourceCode.getAllComments();
83
84 /**
85 * Removes errors that occur inside the given node
86 * @param {ASTNode} node to check for matching errors.
87 * @returns {void}
88 * @private
89 */
90 function removeWhitespaceError(node) {
91 const locStart = node.loc.start;
92 const locEnd = node.loc.end;
93
94 errors = errors.filter(({ loc: { start: errorLocStart } }) => (
95 errorLocStart.line < locStart.line ||
96 errorLocStart.line === locStart.line && errorLocStart.column < locStart.column ||
97 errorLocStart.line === locEnd.line && errorLocStart.column >= locEnd.column ||
98 errorLocStart.line > locEnd.line
99 ));
100 }
101
102 /**
103 * Checks identifier or literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
104 * @param {ASTNode} node to check for matching errors.
105 * @returns {void}
106 * @private
107 */
108 function removeInvalidNodeErrorsInIdentifierOrLiteral(node) {
109 const shouldCheckStrings = skipStrings && (typeof node.value === "string");
110 const shouldCheckRegExps = skipRegExps && Boolean(node.regex);
111
112 if (shouldCheckStrings || shouldCheckRegExps) {
113
114 // If we have irregular characters remove them from the errors list
115 if (ALL_IRREGULARS.test(node.raw)) {
116 removeWhitespaceError(node);
117 }
118 }
119 }
120
121 /**
122 * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
123 * @param {ASTNode} node to check for matching errors.
124 * @returns {void}
125 * @private
126 */
127 function removeInvalidNodeErrorsInTemplateLiteral(node) {
128 if (typeof node.value.raw === "string") {
129 if (ALL_IRREGULARS.test(node.value.raw)) {
130 removeWhitespaceError(node);
131 }
132 }
133 }
134
135 /**
136 * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
137 * @param {ASTNode} node to check for matching errors.
138 * @returns {void}
139 * @private
140 */
141 function removeInvalidNodeErrorsInComment(node) {
142 if (ALL_IRREGULARS.test(node.value)) {
143 removeWhitespaceError(node);
144 }
145 }
146
147 /**
148 * Checks the program source for irregular whitespace
149 * @param {ASTNode} node The program node
150 * @returns {void}
151 * @private
152 */
153 function checkForIrregularWhitespace(node) {
154 const sourceLines = sourceCode.lines;
155
156 sourceLines.forEach((sourceLine, lineIndex) => {
157 const lineNumber = lineIndex + 1;
158 let match;
159
160 while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) {
161 errors.push({
162 node,
163 messageId: "noIrregularWhitespace",
164 loc: {
165 start: {
166 line: lineNumber,
167 column: match.index
168 },
169 end: {
170 line: lineNumber,
171 column: match.index + match[0].length
172 }
173 }
174 });
175 }
176 });
177 }
178
179 /**
180 * Checks the program source for irregular line terminators
181 * @param {ASTNode} node The program node
182 * @returns {void}
183 * @private
184 */
185 function checkForIrregularLineTerminators(node) {
186 const source = sourceCode.getText(),
187 sourceLines = sourceCode.lines,
188 linebreaks = source.match(LINE_BREAK);
189 let lastLineIndex = -1,
190 match;
191
192 while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) {
193 const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0;
194
195 errors.push({
196 node,
197 messageId: "noIrregularWhitespace",
198 loc: {
199 start: {
200 line: lineIndex + 1,
201 column: sourceLines[lineIndex].length
202 },
203 end: {
204 line: lineIndex + 2,
205 column: 0
206 }
207 }
208 });
209
210 lastLineIndex = lineIndex;
211 }
212 }
213
214 /**
215 * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`.
216 * @returns {void}
217 * @private
218 */
219 function noop() {}
220
221 const nodes = {};
222
223 if (ALL_IRREGULARS.test(sourceCode.getText())) {
224 nodes.Program = function(node) {
225
226 /*
227 * As we can easily fire warnings for all white space issues with
228 * all the source its simpler to fire them here.
229 * This means we can check all the application code without having
230 * to worry about issues caused in the parser tokens.
231 * When writing this code also evaluating per node was missing out
232 * connecting tokens in some cases.
233 * We can later filter the errors when they are found to be not an
234 * issue in nodes we don't care about.
235 */
236 checkForIrregularWhitespace(node);
237 checkForIrregularLineTerminators(node);
238 };
239
240 nodes.Identifier = removeInvalidNodeErrorsInIdentifierOrLiteral;
241 nodes.Literal = removeInvalidNodeErrorsInIdentifierOrLiteral;
242 nodes.TemplateElement = skipTemplates ? removeInvalidNodeErrorsInTemplateLiteral : noop;
243 nodes["Program:exit"] = function() {
244 if (skipComments) {
245
246 // First strip errors occurring in comment nodes.
247 commentNodes.forEach(removeInvalidNodeErrorsInComment);
248 }
249
250 // If we have any errors remaining report on them
251 errors.forEach(error => context.report(error));
252 };
253 } else {
254 nodes.Program = noop;
255 }
256
257 return nodes;
258 }
259};