no-irregular-whitespace.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**
  2. * @fileoverview Rule to disalow 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 = /[\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;
  15. const 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;
  16. const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mgu;
  17. const LINE_BREAK = astUtils.createGlobalLinebreakMatcher();
  18. //------------------------------------------------------------------------------
  19. // Rule Definition
  20. //------------------------------------------------------------------------------
  21. module.exports = {
  22. meta: {
  23. type: "problem",
  24. docs: {
  25. description: "disallow irregular whitespace",
  26. category: "Possible Errors",
  27. recommended: true,
  28. url: "https://eslint.org/docs/rules/no-irregular-whitespace"
  29. },
  30. schema: [
  31. {
  32. type: "object",
  33. properties: {
  34. skipComments: {
  35. type: "boolean",
  36. default: false
  37. },
  38. skipStrings: {
  39. type: "boolean",
  40. default: true
  41. },
  42. skipTemplates: {
  43. type: "boolean",
  44. default: false
  45. },
  46. skipRegExps: {
  47. type: "boolean",
  48. default: false
  49. }
  50. },
  51. additionalProperties: false
  52. }
  53. ]
  54. },
  55. create(context) {
  56. // Module store of errors that we have found
  57. let errors = [];
  58. // Lookup the `skipComments` option, which defaults to `false`.
  59. const options = context.options[0] || {};
  60. const skipComments = !!options.skipComments;
  61. const skipStrings = options.skipStrings !== false;
  62. const skipRegExps = !!options.skipRegExps;
  63. const skipTemplates = !!options.skipTemplates;
  64. const sourceCode = context.getSourceCode();
  65. const commentNodes = sourceCode.getAllComments();
  66. /**
  67. * Removes errors that occur inside a string node
  68. * @param {ASTNode} node to check for matching errors.
  69. * @returns {void}
  70. * @private
  71. */
  72. function removeWhitespaceError(node) {
  73. const locStart = node.loc.start;
  74. const locEnd = node.loc.end;
  75. errors = errors.filter(({ loc: errorLoc }) => {
  76. if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) {
  77. if (errorLoc.column >= locStart.column && (errorLoc.column <= locEnd.column || errorLoc.line < locEnd.line)) {
  78. return false;
  79. }
  80. }
  81. return true;
  82. });
  83. }
  84. /**
  85. * Checks identifier or literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
  86. * @param {ASTNode} node to check for matching errors.
  87. * @returns {void}
  88. * @private
  89. */
  90. function removeInvalidNodeErrorsInIdentifierOrLiteral(node) {
  91. const shouldCheckStrings = skipStrings && (typeof node.value === "string");
  92. const shouldCheckRegExps = skipRegExps && Boolean(node.regex);
  93. if (shouldCheckStrings || shouldCheckRegExps) {
  94. // If we have irregular characters remove them from the errors list
  95. if (ALL_IRREGULARS.test(node.raw)) {
  96. removeWhitespaceError(node);
  97. }
  98. }
  99. }
  100. /**
  101. * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
  102. * @param {ASTNode} node to check for matching errors.
  103. * @returns {void}
  104. * @private
  105. */
  106. function removeInvalidNodeErrorsInTemplateLiteral(node) {
  107. if (typeof node.value.raw === "string") {
  108. if (ALL_IRREGULARS.test(node.value.raw)) {
  109. removeWhitespaceError(node);
  110. }
  111. }
  112. }
  113. /**
  114. * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
  115. * @param {ASTNode} node to check for matching errors.
  116. * @returns {void}
  117. * @private
  118. */
  119. function removeInvalidNodeErrorsInComment(node) {
  120. if (ALL_IRREGULARS.test(node.value)) {
  121. removeWhitespaceError(node);
  122. }
  123. }
  124. /**
  125. * Checks the program source for irregular whitespace
  126. * @param {ASTNode} node The program node
  127. * @returns {void}
  128. * @private
  129. */
  130. function checkForIrregularWhitespace(node) {
  131. const sourceLines = sourceCode.lines;
  132. sourceLines.forEach((sourceLine, lineIndex) => {
  133. const lineNumber = lineIndex + 1;
  134. let match;
  135. while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) {
  136. const location = {
  137. line: lineNumber,
  138. column: match.index
  139. };
  140. errors.push({ node, message: "Irregular whitespace not allowed.", loc: location });
  141. }
  142. });
  143. }
  144. /**
  145. * Checks the program source for irregular line terminators
  146. * @param {ASTNode} node The program node
  147. * @returns {void}
  148. * @private
  149. */
  150. function checkForIrregularLineTerminators(node) {
  151. const source = sourceCode.getText(),
  152. sourceLines = sourceCode.lines,
  153. linebreaks = source.match(LINE_BREAK);
  154. let lastLineIndex = -1,
  155. match;
  156. while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) {
  157. const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0;
  158. const location = {
  159. line: lineIndex + 1,
  160. column: sourceLines[lineIndex].length
  161. };
  162. errors.push({ node, message: "Irregular whitespace not allowed.", loc: location });
  163. lastLineIndex = lineIndex;
  164. }
  165. }
  166. /**
  167. * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`.
  168. * @returns {void}
  169. * @private
  170. */
  171. function noop() {}
  172. const nodes = {};
  173. if (ALL_IRREGULARS.test(sourceCode.getText())) {
  174. nodes.Program = function(node) {
  175. /*
  176. * As we can easily fire warnings for all white space issues with
  177. * all the source its simpler to fire them here.
  178. * This means we can check all the application code without having
  179. * to worry about issues caused in the parser tokens.
  180. * When writing this code also evaluating per node was missing out
  181. * connecting tokens in some cases.
  182. * We can later filter the errors when they are found to be not an
  183. * issue in nodes we don't care about.
  184. */
  185. checkForIrregularWhitespace(node);
  186. checkForIrregularLineTerminators(node);
  187. };
  188. nodes.Identifier = removeInvalidNodeErrorsInIdentifierOrLiteral;
  189. nodes.Literal = removeInvalidNodeErrorsInIdentifierOrLiteral;
  190. nodes.TemplateElement = skipTemplates ? removeInvalidNodeErrorsInTemplateLiteral : noop;
  191. nodes["Program:exit"] = function() {
  192. if (skipComments) {
  193. // First strip errors occurring in comment nodes.
  194. commentNodes.forEach(removeInvalidNodeErrorsInComment);
  195. }
  196. // If we have any errors remaining report on them
  197. errors.forEach(error => context.report(error));
  198. };
  199. } else {
  200. nodes.Program = noop;
  201. }
  202. return nodes;
  203. }
  204. };