UNPKG

2.66 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag missing semicolons.
3 * @author Nicholas C. Zakas
4 */
5
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10module.exports = function(context) {
11
12 "use strict";
13
14 var always = context.options[0] !== "never";
15
16 //--------------------------------------------------------------------------
17 // Helpers
18 //--------------------------------------------------------------------------
19
20 /**
21 * Checks a node to see if it's followed by a semicolon.
22 * @param {ASTNode} node The node to check.
23 * @returns {void}
24 */
25 function checkForSemicolon(node) {
26
27 var tokens = context.getTokens(node),
28 token = tokens.pop();
29
30 if (always) {
31 if (token.type !== "Punctuator" || token.value !== ";") {
32 context.report(node, node.loc.end, "Missing semicolon.");
33 }
34 } else {
35 if (token.type === "Punctuator" && token.value === ";") {
36 context.report(node, node.loc.end, "Extra semicolon.");
37 }
38 }
39 }
40
41 /**
42 * Checks to see if there's a semicolon after a variable declaration.
43 * @param {ASTNode} node The node to check.
44 * @returns {void}
45 */
46 function checkForSemicolonForVariableDeclaration(node) {
47
48 var ancestors = context.getAncestors(),
49 parentIndex = ancestors.length - 1,
50 parent = ancestors[parentIndex];
51
52 if ((parent.type !== "ForStatement" || parent.init !== node) &&
53 (parent.type !== "ForInStatement" || parent.left !== node)
54 ) {
55 checkForSemicolon(node);
56 }
57 }
58
59 //--------------------------------------------------------------------------
60 // Public API
61 //--------------------------------------------------------------------------
62
63 return {
64
65 "VariableDeclaration": checkForSemicolonForVariableDeclaration,
66 "ExpressionStatement": checkForSemicolon,
67 "ReturnStatement": checkForSemicolon,
68 "DebuggerStatement": checkForSemicolon,
69 "BreakStatement": checkForSemicolon,
70 "ContinueStatement": checkForSemicolon,
71 "EmptyStatement": function (node) {
72 var tokens,
73 token;
74
75 if (!always) {
76 tokens = context.getTokens(node, 0, 1);
77 token = tokens.pop();
78
79 if (!(/[\[\(\/\+\-]/.test(token.value))) {
80 context.report(node, "Extra semicolon.");
81 }
82 }
83
84
85 }
86 };
87
88};