no-irregular-whitespace.js 7.7 KB

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