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.

89 lines
2.7 KiB

4 years ago
  1. /**
  2. * @fileoverview Enforces or disallows inline comments.
  3. * @author Greg Cochard
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "disallow inline comments after code",
  15. category: "Stylistic Issues",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/no-inline-comments"
  18. },
  19. schema: [],
  20. messages: {
  21. unexpectedInlineComment: "Unexpected comment inline with code."
  22. }
  23. },
  24. create(context) {
  25. const sourceCode = context.getSourceCode();
  26. /**
  27. * Will check that comments are not on lines starting with or ending with code
  28. * @param {ASTNode} node The comment node to check
  29. * @private
  30. * @returns {void}
  31. */
  32. function testCodeAroundComment(node) {
  33. const startLine = String(sourceCode.lines[node.loc.start.line - 1]),
  34. endLine = String(sourceCode.lines[node.loc.end.line - 1]),
  35. preamble = startLine.slice(0, node.loc.start.column).trim(),
  36. postamble = endLine.slice(node.loc.end.column).trim(),
  37. isPreambleEmpty = !preamble,
  38. isPostambleEmpty = !postamble;
  39. // Nothing on both sides
  40. if (isPreambleEmpty && isPostambleEmpty) {
  41. return;
  42. }
  43. // JSX Exception
  44. if (
  45. (isPreambleEmpty || preamble === "{") &&
  46. (isPostambleEmpty || postamble === "}")
  47. ) {
  48. const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]);
  49. if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") {
  50. return;
  51. }
  52. }
  53. // Don't report ESLint directive comments
  54. if (astUtils.isDirectiveComment(node)) {
  55. return;
  56. }
  57. context.report({
  58. node,
  59. messageId: "unexpectedInlineComment"
  60. });
  61. }
  62. //--------------------------------------------------------------------------
  63. // Public
  64. //--------------------------------------------------------------------------
  65. return {
  66. Program() {
  67. const comments = sourceCode.getAllComments();
  68. comments.filter(token => token.type !== "Shebang").forEach(testCodeAroundComment);
  69. }
  70. };
  71. }
  72. };