summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/lines-around-comment.js
blob: e2416fc59ead42b043ee8bffc3029da5421bcc24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**
 * @fileoverview Enforces empty lines around comments.
 * @author Jamund Ferguson
 * @copyright 2015 Mathieu M-Gosselin. All rights reserved.
 * @copyright 2015 Jamund Ferguson. All rights reserved.
 * @copyright 2015 Gyandeep Singh. All rights reserved.
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var assign = require("object-assign");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Return an array with with any line numbers that are empty.
 * @param {Array} lines An array of each line of the file.
 * @returns {Array} An array of line numbers.
 */
function getEmptyLineNums(lines) {
    var emptyLines = lines.map(function(line, i) {
        return {
            code: line.trim(),
            num: i + 1
        };
    }).filter(function(line) {
        return !line.code;
    }).map(function(line) {
        return line.num;
    });
    return emptyLines;
}

/**
 * Return an array with with any line numbers that contain comments.
 * @param {Array} comments An array of comment nodes.
 * @returns {Array} An array of line numbers.
 */
function getCommentLineNums(comments) {
    var lines = [];
    comments.forEach(function(token) {
        var start = token.loc.start.line;
        var end = token.loc.end.line;
        lines.push(start, end);
    });
    return lines;
}

/**
 * Determines if a value is an array.
 * @param {number} val The value we wish to check for in the array..
 * @param {Array} array An array.
 * @returns {boolean} True if the value is in the array..
 */
function contains(val, array) {
    return array.indexOf(val) > -1;
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    var options = context.options[0] ? assign({}, context.options[0]) : {};
    options.beforeLineComment = options.beforeLineComment || false;
    options.afterLineComment = options.afterLineComment || false;
    options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true;
    options.afterBlockComment = options.afterBlockComment || false;
    options.allowBlockStart = options.allowBlockStart || false;
    options.allowBlockEnd = options.allowBlockEnd || false;

    var sourceCode = context.getSourceCode();
    /**
     * Returns whether or not comments are on lines starting with or ending with code
     * @param {ASTNode} node The comment node to check.
     * @returns {boolean} True if the comment is not alone.
     */
    function codeAroundComment(node) {
        var token;

        token = node;
        do {
            token = sourceCode.getTokenOrCommentBefore(token);
        } while (token && (token.type === "Block" || token.type === "Line"));

        if (token && token.loc.end.line === node.loc.start.line) {
            return true;
        }

        token = node;
        do {
            token = sourceCode.getTokenOrCommentAfter(token);
        } while (token && (token.type === "Block" || token.type === "Line"));

        if (token && token.loc.start.line === node.loc.end.line) {
            return true;
        }

        return false;
    }

    /**
     * Returns whether or not comments are inside a node type or not.
     * @param {ASTNode} node The Comment node.
     * @param {ASTNode} parent The Comment parent node.
     * @param {string} nodeType The parent type to check against.
     * @returns {boolean} True if the comment is inside nodeType.
     */
    function isCommentInsideNodeType(node, parent, nodeType) {
        return parent.type === nodeType ||
            (parent.body && parent.body.type === nodeType) ||
            (parent.consequent && parent.consequent.type === nodeType);
    }

    /**
     * Returns whether or not comments are at the parent start or not.
     * @param {ASTNode} node The Comment node.
     * @param {string} nodeType The parent type to check against.
     * @returns {boolean} True if the comment is at parent start.
     */
    function isCommentAtParentStart(node, nodeType) {
        var ancestors = context.getAncestors();
        var parent;

        if (ancestors.length) {
            parent = ancestors.pop();
        }

        return parent && isCommentInsideNodeType(node, parent, nodeType) &&
                node.loc.start.line - parent.loc.start.line === 1;
    }

    /**
     * Returns whether or not comments are at the parent end or not.
     * @param {ASTNode} node The Comment node.
     * @param {string} nodeType The parent type to check against.
     * @returns {boolean} True if the comment is at parent end.
     */
    function isCommentAtParentEnd(node, nodeType) {
        var ancestors = context.getAncestors();
        var parent;

        if (ancestors.length) {
            parent = ancestors.pop();
        }

        return parent && isCommentInsideNodeType(node, parent, nodeType) &&
                parent.loc.end.line - node.loc.end.line === 1;
    }

    /**
     * Returns whether or not comments are at the block start or not.
     * @param {ASTNode} node The Comment node.
     * @returns {boolean} True if the comment is at block start.
     */
    function isCommentAtBlockStart(node) {
        return isCommentAtParentStart(node, "ClassBody") || isCommentAtParentStart(node, "BlockStatement");
    }

    /**
     * Returns whether or not comments are at the block end or not.
     * @param {ASTNode} node The Comment node.
     * @returns {boolean} True if the comment is at block end.
     */
    function isCommentAtBlockEnd(node) {
        return isCommentAtParentEnd(node, "ClassBody") || isCommentAtParentEnd(node, "BlockStatement");
    }

    /**
     * Returns whether or not comments are at the object start or not.
     * @param {ASTNode} node The Comment node.
     * @returns {boolean} True if the comment is at object start.
     */
    function isCommentAtObjectStart(node) {
        return isCommentAtParentStart(node, "ObjectExpression") || isCommentAtParentStart(node, "ObjectPattern");
    }

    /**
     * Returns whether or not comments are at the object end or not.
     * @param {ASTNode} node The Comment node.
     * @returns {boolean} True if the comment is at object end.
     */
    function isCommentAtObjectEnd(node) {
        return isCommentAtParentEnd(node, "ObjectExpression") || isCommentAtParentEnd(node, "ObjectPattern");
    }

    /**
     * Returns whether or not comments are at the array start or not.
     * @param {ASTNode} node The Comment node.
     * @returns {boolean} True if the comment is at array start.
     */
    function isCommentAtArrayStart(node) {
        return isCommentAtParentStart(node, "ArrayExpression") || isCommentAtParentStart(node, "ArrayPattern");
    }

    /**
     * Returns whether or not comments are at the array end or not.
     * @param {ASTNode} node The Comment node.
     * @returns {boolean} True if the comment is at array end.
     */
    function isCommentAtArrayEnd(node) {
        return isCommentAtParentEnd(node, "ArrayExpression") || isCommentAtParentEnd(node, "ArrayPattern");
    }

    /**
     * Checks if a comment node has lines around it (ignores inline comments)
     * @param {ASTNode} node The Comment node.
     * @param {Object} opts Options to determine the newline.
     * @param {Boolean} opts.after Should have a newline after this line.
     * @param {Boolean} opts.before Should have a newline before this line.
     * @returns {void}
     */
    function checkForEmptyLine(node, opts) {

        var lines = context.getSourceLines(),
            numLines = lines.length + 1,
            comments = context.getAllComments(),
            commentLines = getCommentLineNums(comments),
            emptyLines = getEmptyLineNums(lines),
            commentAndEmptyLines = commentLines.concat(emptyLines);

        var after = opts.after,
            before = opts.before;

        var prevLineNum = node.loc.start.line - 1,
            nextLineNum = node.loc.end.line + 1,
            commentIsNotAlone = codeAroundComment(node);

        var blockStartAllowed = options.allowBlockStart && isCommentAtBlockStart(node),
            blockEndAllowed = options.allowBlockEnd && isCommentAtBlockEnd(node),
            objectStartAllowed = options.allowObjectStart && isCommentAtObjectStart(node),
            objectEndAllowed = options.allowObjectEnd && isCommentAtObjectEnd(node),
            arrayStartAllowed = options.allowArrayStart && isCommentAtArrayStart(node),
            arrayEndAllowed = options.allowArrayEnd && isCommentAtArrayEnd(node);

        var exceptionStartAllowed = blockStartAllowed || objectStartAllowed || arrayStartAllowed;
        var exceptionEndAllowed = blockEndAllowed || objectEndAllowed || arrayEndAllowed;

        // ignore top of the file and bottom of the file
        if (prevLineNum < 1) {
            before = false;
        }
        if (nextLineNum >= numLines) {
            after = false;
        }

        // we ignore all inline comments
        if (commentIsNotAlone) {
            return;
        }

        // check for newline before
        if (!exceptionStartAllowed && before && !contains(prevLineNum, commentAndEmptyLines)) {
            context.report(node, "Expected line before comment.");
        }

        // check for newline after
        if (!exceptionEndAllowed && after && !contains(nextLineNum, commentAndEmptyLines)) {
            context.report(node, "Expected line after comment.");
        }

    }

    //--------------------------------------------------------------------------
    // Public
    //--------------------------------------------------------------------------

    return {

        "LineComment": function(node) {
            if (options.beforeLineComment || options.afterLineComment) {
                checkForEmptyLine(node, {
                    after: options.afterLineComment,
                    before: options.beforeLineComment
                });
            }
        },

        "BlockComment": function(node) {
            if (options.beforeBlockComment || options.afterBlockComment) {
                checkForEmptyLine(node, {
                    after: options.afterBlockComment,
                    before: options.beforeBlockComment
                });
            }
        }

    };
};

module.exports.schema = [
    {
        "type": "object",
        "properties": {
            "beforeBlockComment": {
                "type": "boolean"
            },
            "afterBlockComment": {
                "type": "boolean"
            },
            "beforeLineComment": {
                "type": "boolean"
            },
            "afterLineComment": {
                "type": "boolean"
            },
            "allowBlockStart": {
                "type": "boolean"
            },
            "allowBlockEnd": {
                "type": "boolean"
            },
            "allowObjectStart": {
                "type": "boolean"
            },
            "allowObjectEnd": {
                "type": "boolean"
            },
            "allowArrayStart": {
                "type": "boolean"
            },
            "allowArrayEnd": {
                "type": "boolean"
            }
        },
        "additionalProperties": false
    }
];