2 * @fileoverview A rule to ensure whitespace before blocks.
3 * @author Mathias Schreck <https://github.com/lo1tuma>
4 * @copyright 2014 Mathias Schreck. All rights reserved.
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
13 module.exports = function (context) {
14 var requireSpace = context.options[0] !== "never";
17 * Determines whether two adjacent tokens are have whitespace between them.
18 * @param {Object} left - The left token object.
19 * @param {Object} right - The right token object.
20 * @returns {boolean} Whether or not there is space between the tokens.
22 function isSpaced(left, right) {
23 return left.range[1] < right.range[0];
27 * Determines whether two adjacent tokens are on the same line.
28 * @param {Object} left - The left token object.
29 * @param {Object} right - The right token object.
30 * @returns {boolean} Whether or not the tokens are on the same line.
32 function isSameLine(left, right) {
33 return left.loc.start.line === right.loc.start.line;
37 * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line.
38 * @param {ASTNode|Token} node The AST node of a BlockStatement.
39 * @returns {void} undefined.
41 function checkPrecedingSpace(node) {
42 var precedingToken = context.getTokenBefore(node),
45 if (precedingToken && isSameLine(precedingToken, node)) {
46 hasSpace = isSpaced(precedingToken, node);
50 context.report(node, "Missing space before opening brace.");
54 context.report(node, "Unexpected space before opening brace.");
61 * Checks if the CaseBlock of an given SwitchStatement node has a preceding space.
62 * @param {ASTNode} node The node of a SwitchStatement.
63 * @returns {void} undefined.
65 function checkSpaceBeforeCaseBlock(node) {
66 var cases = node.cases,
70 if (cases.length > 0) {
72 openingBrace = context.getTokenBefore(firstCase);
74 openingBrace = context.getLastToken(node, 1);
77 checkPrecedingSpace(openingBrace);
81 "BlockStatement": checkPrecedingSpace,
82 "SwitchStatement": checkSpaceBeforeCaseBlock