You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

261 lines
9.4 KiB

4 years ago
  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 = /[\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. messages: {
  55. noIrregularWhitespace: "Irregular whitespace not allowed."
  56. }
  57. },
  58. create(context) {
  59. // Module store of errors that we have found
  60. let errors = [];
  61. // Lookup the `skipComments` option, which defaults to `false`.
  62. const options = context.options[0] || {};
  63. const skipComments = !!options.skipComments;
  64. const skipStrings = options.skipStrings !== false;
  65. const skipRegExps = !!options.skipRegExps;
  66. const skipTemplates = !!options.skipTemplates;
  67. const sourceCode = context.getSourceCode();
  68. const commentNodes = sourceCode.getAllComments();
  69. /**
  70. * Removes errors that occur inside a string node
  71. * @param {ASTNode} node to check for matching errors.
  72. * @returns {void}
  73. * @private
  74. */
  75. function removeWhitespaceError(node) {
  76. const locStart = node.loc.start;
  77. const locEnd = node.loc.end;
  78. errors = errors.filter(({ loc: { start: errorLoc } }) => {
  79. if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) {
  80. if (errorLoc.column >= locStart.column && (errorLoc.column <= locEnd.column || errorLoc.line < locEnd.line)) {
  81. return false;
  82. }
  83. }
  84. return true;
  85. });
  86. }
  87. /**
  88. * Checks identifier or literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
  89. * @param {ASTNode} node to check for matching errors.
  90. * @returns {void}
  91. * @private
  92. */
  93. function removeInvalidNodeErrorsInIdentifierOrLiteral(node) {
  94. const shouldCheckStrings = skipStrings && (typeof node.value === "string");
  95. const shouldCheckRegExps = skipRegExps && Boolean(node.regex);
  96. if (shouldCheckStrings || shouldCheckRegExps) {
  97. // If we have irregular characters remove them from the errors list
  98. if (ALL_IRREGULARS.test(node.raw)) {
  99. removeWhitespaceError(node);
  100. }
  101. }
  102. }
  103. /**
  104. * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
  105. * @param {ASTNode} node to check for matching errors.
  106. * @returns {void}
  107. * @private
  108. */
  109. function removeInvalidNodeErrorsInTemplateLiteral(node) {
  110. if (typeof node.value.raw === "string") {
  111. if (ALL_IRREGULARS.test(node.value.raw)) {
  112. removeWhitespaceError(node);
  113. }
  114. }
  115. }
  116. /**
  117. * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors
  118. * @param {ASTNode} node to check for matching errors.
  119. * @returns {void}
  120. * @private
  121. */
  122. function removeInvalidNodeErrorsInComment(node) {
  123. if (ALL_IRREGULARS.test(node.value)) {
  124. removeWhitespaceError(node);
  125. }
  126. }
  127. /**
  128. * Checks the program source for irregular whitespace
  129. * @param {ASTNode} node The program node
  130. * @returns {void}
  131. * @private
  132. */
  133. function checkForIrregularWhitespace(node) {
  134. const sourceLines = sourceCode.lines;
  135. sourceLines.forEach((sourceLine, lineIndex) => {
  136. const lineNumber = lineIndex + 1;
  137. let match;
  138. while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) {
  139. errors.push({
  140. node,
  141. messageId: "noIrregularWhitespace",
  142. loc: {
  143. start: {
  144. line: lineNumber,
  145. column: match.index
  146. },
  147. end: {
  148. line: lineNumber,
  149. column: match.index + match[0].length
  150. }
  151. }
  152. });
  153. }
  154. });
  155. }
  156. /**
  157. * Checks the program source for irregular line terminators
  158. * @param {ASTNode} node The program node
  159. * @returns {void}
  160. * @private
  161. */
  162. function checkForIrregularLineTerminators(node) {
  163. const source = sourceCode.getText(),
  164. sourceLines = sourceCode.lines,
  165. linebreaks = source.match(LINE_BREAK);
  166. let lastLineIndex = -1,
  167. match;
  168. while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) {
  169. const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0;
  170. errors.push({
  171. node,
  172. messageId: "noIrregularWhitespace",
  173. loc: {
  174. start: {
  175. line: lineIndex + 1,
  176. column: sourceLines[lineIndex].length
  177. },
  178. end: {
  179. line: lineIndex + 2,
  180. column: 0
  181. }
  182. }
  183. });
  184. lastLineIndex = lineIndex;
  185. }
  186. }
  187. /**
  188. * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`.
  189. * @returns {void}
  190. * @private
  191. */
  192. function noop() {}
  193. const nodes = {};
  194. if (ALL_IRREGULARS.test(sourceCode.getText())) {
  195. nodes.Program = function(node) {
  196. /*
  197. * As we can easily fire warnings for all white space issues with
  198. * all the source its simpler to fire them here.
  199. * This means we can check all the application code without having
  200. * to worry about issues caused in the parser tokens.
  201. * When writing this code also evaluating per node was missing out
  202. * connecting tokens in some cases.
  203. * We can later filter the errors when they are found to be not an
  204. * issue in nodes we don't care about.
  205. */
  206. checkForIrregularWhitespace(node);
  207. checkForIrregularLineTerminators(node);
  208. };
  209. nodes.Identifier = removeInvalidNodeErrorsInIdentifierOrLiteral;
  210. nodes.Literal = removeInvalidNodeErrorsInIdentifierOrLiteral;
  211. nodes.TemplateElement = skipTemplates ? removeInvalidNodeErrorsInTemplateLiteral : noop;
  212. nodes["Program:exit"] = function() {
  213. if (skipComments) {
  214. // First strip errors occurring in comment nodes.
  215. commentNodes.forEach(removeInvalidNodeErrorsInComment);
  216. }
  217. // If we have any errors remaining report on them
  218. errors.forEach(error => context.report(error));
  219. };
  220. } else {
  221. nodes.Program = noop;
  222. }
  223. return nodes;
  224. }
  225. };