2 * @fileoverview enforce the location of single-line statements
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const POSITION_SCHEMA = { enum: ["beside", "below", "any"] };
18 description: "enforce the location of single-line statements",
19 category: "Stylistic Issues",
21 url: "https://eslint.org/docs/rules/nonblock-statement-body-position"
24 fixable: "whitespace",
33 else: POSITION_SCHEMA,
34 while: POSITION_SCHEMA,
38 additionalProperties: false
41 additionalProperties: false
47 const sourceCode = context.getSourceCode();
49 //----------------------------------------------------------------------
51 //----------------------------------------------------------------------
54 * Gets the applicable preference for a particular keyword
55 * @param {string} keywordName The name of a keyword, e.g. 'if'
56 * @returns {string} The applicable option for the keyword, e.g. 'beside'
58 function getOption(keywordName) {
59 return context.options[1] && context.options[1].overrides && context.options[1].overrides[keywordName] ||
65 * Validates the location of a single-line statement
66 * @param {ASTNode} node The single-line statement
67 * @param {string} keywordName The applicable keyword name for the single-line statement
70 function validateStatement(node, keywordName) {
71 const option = getOption(keywordName);
73 if (node.type === "BlockStatement" || option === "any") {
77 const tokenBefore = sourceCode.getTokenBefore(node);
79 if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") {
82 message: "Expected a linebreak before this statement.",
83 fix: fixer => fixer.insertTextBefore(node, "\n")
85 } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") {
88 message: "Expected no linebreak before this statement.",
90 if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) {
93 return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " ");
99 //----------------------------------------------------------------------
101 //----------------------------------------------------------------------
105 validateStatement(node.consequent, "if");
107 // Check the `else` node, but don't check 'else if' statements.
108 if (node.alternate && node.alternate.type !== "IfStatement") {
109 validateStatement(node.alternate, "else");
112 WhileStatement: node => validateStatement(node.body, "while"),
113 DoWhileStatement: node => validateStatement(node.body, "do"),
114 ForStatement: node => validateStatement(node.body, "for"),
115 ForInStatement: node => validateStatement(node.body, "for"),
116 ForOfStatement: node => validateStatement(node.body, "for")