UNPKG

2.59 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag statements without curly braces
3 * @author Nicholas C. Zakas
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = function(context) {
12
13 var multiOnly = (context.options[0] === "multi");
14
15 //--------------------------------------------------------------------------
16 // Helpers
17 //--------------------------------------------------------------------------
18
19 /**
20 * Checks the body of a node to see if it's a block statement. Depending on
21 * the rule options, reports the appropriate problems.
22 * @param {ASTNode} node The node to report if there's a problem.
23 * @param {ASTNode} body The body node to check for blocks.
24 * @param {string} name The name to report if there's a problem.
25 * @param {string} suffix Additional string to add to the end of a report.
26 * @returns {void}
27 */
28 function checkBody(node, body, name, suffix) {
29 var hasBlock = (body.type === "BlockStatement");
30
31 if (multiOnly) {
32 if (hasBlock && body.body.length === 1) {
33 context.report(node, "Unnecessary { after '{{name}}'{{suffix}}.",
34 {
35 name: name,
36 suffix: (suffix ? " " + suffix : "")
37 }
38 );
39 }
40 } else {
41 if (!hasBlock) {
42 context.report(node, "Expected { after '{{name}}'{{suffix}}.",
43 {
44 name: name,
45 suffix: (suffix ? " " + suffix : "")
46 }
47 );
48 }
49 }
50 }
51
52 //--------------------------------------------------------------------------
53 // Public
54 //--------------------------------------------------------------------------
55
56 return {
57
58 "IfStatement": function(node) {
59
60 checkBody(node, node.consequent, "if", "condition");
61
62 if (node.alternate && node.alternate.type !== "IfStatement") {
63 checkBody(node, node.alternate, "else");
64 }
65
66 },
67
68 "WhileStatement": function(node) {
69 checkBody(node, node.body, "while", "condition");
70 },
71
72 "DoWhileStatement": function (node) {
73 checkBody(node, node.body, "do");
74 },
75
76 "ForStatement": function(node) {
77 checkBody(node, node.body, "for", "condition");
78 }
79 };
80
81};