UNPKG

2.62 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag use of unnecessary semicolons
3 * @author Nicholas C. Zakas
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = function(context) {
13
14 /**
15 * Reports an unnecessary semicolon error.
16 * @param {Node|Token} nodeOrToken - A node or a token to be reported.
17 * @returns {void}
18 */
19 function report(nodeOrToken) {
20 context.report({
21 node: nodeOrToken,
22 message: "Unnecessary semicolon.",
23 fix: function(fixer) {
24 return fixer.remove(nodeOrToken);
25 }
26 });
27 }
28
29 /**
30 * Checks for a part of a class body.
31 * This checks tokens from a specified token to a next MethodDefinition or the end of class body.
32 *
33 * @param {Token} firstToken - The first token to check.
34 * @returns {void}
35 */
36 function checkForPartOfClassBody(firstToken) {
37 for (var token = firstToken;
38 token.type === "Punctuator" && token.value !== "}";
39 token = context.getTokenAfter(token)
40 ) {
41 if (token.value === ";") {
42 report(token);
43 }
44 }
45 }
46
47 return {
48 /**
49 * Reports this empty statement, except if the parent node is a loop.
50 * @param {Node} node - A EmptyStatement node to be reported.
51 * @returns {void}
52 */
53 "EmptyStatement": function(node) {
54 var parent = node.parent,
55 allowedParentTypes = ["ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement"];
56
57 if (allowedParentTypes.indexOf(parent.type) === -1) {
58 report(node);
59 }
60 },
61
62 /**
63 * Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body.
64 * @param {Node} node - A ClassBody node to check.
65 * @returns {void}
66 */
67 "ClassBody": function(node) {
68 checkForPartOfClassBody(context.getFirstToken(node, 1)); // 0 is `{`.
69 },
70
71 /**
72 * Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body.
73 * @param {Node} node - A MethodDefinition node of the start point.
74 * @returns {void}
75 */
76 "MethodDefinition": function(node) {
77 checkForPartOfClassBody(context.getTokenAfter(node));
78 }
79 };
80
81};
82
83module.exports.schema = [];