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