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
46 expectNoLinebreak: "Expected no linebreak before this statement.",
47 expectLinebreak: "Expected a linebreak before this statement."
52 const sourceCode = context.getSourceCode();
54 //----------------------------------------------------------------------
56 //----------------------------------------------------------------------
59 * Gets the applicable preference for a particular keyword
60 * @param {string} keywordName The name of a keyword, e.g. 'if'
61 * @returns {string} The applicable option for the keyword, e.g. 'beside'
63 function getOption(keywordName) {
64 return context.options[1] && context.options[1].overrides && context.options[1].overrides[keywordName] ||
70 * Validates the location of a single-line statement
71 * @param {ASTNode} node The single-line statement
72 * @param {string} keywordName The applicable keyword name for the single-line statement
75 function validateStatement(node, keywordName) {
76 const option = getOption(keywordName);
78 if (node.type === "BlockStatement" || option === "any") {
82 const tokenBefore = sourceCode.getTokenBefore(node);
84 if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") {
87 messageId: "expectLinebreak",
88 fix: fixer => fixer.insertTextBefore(node, "\n")
90 } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") {
93 messageId: "expectNoLinebreak",
95 if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) {
98 return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " ");
104 //----------------------------------------------------------------------
106 //----------------------------------------------------------------------
110 validateStatement(node.consequent, "if");
112 // Check the `else` node, but don't check 'else if' statements.
113 if (node.alternate && node.alternate.type !== "IfStatement") {
114 validateStatement(node.alternate, "else");
117 WhileStatement: node => validateStatement(node.body, "while"),
118 DoWhileStatement: node => validateStatement(node.body, "do"),
119 ForStatement: node => validateStatement(node.body, "for"),
120 ForInStatement: node => validateStatement(node.body, "for"),
121 ForOfStatement: node => validateStatement(node.body, "for")