2 * @fileoverview Enforces or disallows inline comments.
7 const astUtils = require("./utils/ast-utils");
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
18 description: "disallow inline comments after code",
19 category: "Stylistic Issues",
21 url: "https://eslint.org/docs/rules/no-inline-comments"
32 additionalProperties: false
37 unexpectedInlineComment: "Unexpected comment inline with code."
42 const sourceCode = context.getSourceCode();
43 const options = context.options[0];
44 let customIgnoreRegExp;
46 if (options && options.ignorePattern) {
47 customIgnoreRegExp = new RegExp(options.ignorePattern, "u");
51 * Will check that comments are not on lines starting with or ending with code
52 * @param {ASTNode} node The comment node to check
56 function testCodeAroundComment(node) {
58 const startLine = String(sourceCode.lines[node.loc.start.line - 1]),
59 endLine = String(sourceCode.lines[node.loc.end.line - 1]),
60 preamble = startLine.slice(0, node.loc.start.column).trim(),
61 postamble = endLine.slice(node.loc.end.column).trim(),
62 isPreambleEmpty = !preamble,
63 isPostambleEmpty = !postamble;
65 // Nothing on both sides
66 if (isPreambleEmpty && isPostambleEmpty) {
70 // Matches the ignore pattern
71 if (customIgnoreRegExp && customIgnoreRegExp.test(node.value)) {
77 (isPreambleEmpty || preamble === "{") &&
78 (isPostambleEmpty || postamble === "}")
80 const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]);
82 if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") {
87 // Don't report ESLint directive comments
88 if (astUtils.isDirectiveComment(node)) {
94 messageId: "unexpectedInlineComment"
98 //--------------------------------------------------------------------------
100 //--------------------------------------------------------------------------
104 sourceCode.getAllComments()
105 .filter(token => token.type !== "Shebang")
106 .forEach(testCodeAroundComment);