|
| 1 | +use crate::services::semantic::Semantic; |
| 2 | +use ::serde::{Deserialize, Serialize}; |
| 3 | +use biome_analyze::{ |
| 4 | + Rule, RuleDiagnostic, RuleSource, RuleSourceKind, context::RuleContext, declare_lint_rule, |
| 5 | +}; |
| 6 | +use biome_console::markup; |
| 7 | +use biome_deserialize_macros::Deserializable; |
| 8 | +use biome_js_syntax::{ |
| 9 | + AnyFunctionLike, AnyJsFunction, JsCallExpression, JsParenthesizedExpression, |
| 10 | +}; |
| 11 | +use biome_rowan::AstNode; |
| 12 | +#[cfg(feature = "schemars")] |
| 13 | +use schemars::JsonSchema; |
| 14 | +use std::num::NonZeroU8; |
| 15 | + |
| 16 | +declare_lint_rule! { |
| 17 | + /// Restrict the number of lines of code in a function. |
| 18 | + /// |
| 19 | + /// This rule checks the number of lines in a function body and reports a diagnostic if it exceeds a specified limit. Remember that this rule only counts the lines of code in the function body, not the entire function declaration. |
| 20 | + /// Some people consider large functions a code smell. Large functions tend to do a lot of things and can make it hard following what’s going on. Many coding style guides dictate a limit of the number of lines that a function can comprise of. This rule can help enforce that style. |
| 21 | + /// |
| 22 | + /// ## Examples |
| 23 | + /// |
| 24 | + /// ### Invalid |
| 25 | + /// |
| 26 | + /// The following example will show diagnostic when you set the maxLines limit to 3, however the default value is 50. |
| 27 | + /// |
| 28 | + /// ```js |
| 29 | + /// function foo () { |
| 30 | + /// const x = 0; |
| 31 | + /// const y = 1; |
| 32 | + /// const z = 2; |
| 33 | + /// return x + y + z; |
| 34 | + /// }; |
| 35 | + /// ``` |
| 36 | + /// |
| 37 | + /// ### Valid |
| 38 | + /// |
| 39 | + /// ```js |
| 40 | + /// function foo () { |
| 41 | + /// const x = 0; |
| 42 | + /// const y = 1; |
| 43 | + /// }; |
| 44 | + /// ``` |
| 45 | + /// |
| 46 | + /// ## Options |
| 47 | + /// |
| 48 | + /// The rule supports the following options: |
| 49 | + /// |
| 50 | + /// ```json |
| 51 | + /// { |
| 52 | + /// "options": { |
| 53 | + /// "maxLines": 50, |
| 54 | + /// "skipBlankLines": false, |
| 55 | + /// "skipIifes": false |
| 56 | + /// } |
| 57 | + /// } |
| 58 | + /// ``` |
| 59 | + /// |
| 60 | + /// ### maxLines |
| 61 | + /// |
| 62 | + /// This option sets the maximum number of lines allowed in a function body. |
| 63 | + /// If the function body exceeds this limit, a diagnostic will be reported. |
| 64 | + /// |
| 65 | + /// Default: `50` |
| 66 | + /// |
| 67 | + /// When `maxLines: 2`, the following function will be considered invalid: |
| 68 | + /// ```json,options |
| 69 | + /// { |
| 70 | + /// "options": { |
| 71 | + /// "maxLines": 2 |
| 72 | + /// } |
| 73 | + /// } |
| 74 | + /// ``` |
| 75 | + /// ```js,expect_diagnostic,use_options |
| 76 | + /// function example() { |
| 77 | + /// const a = 1; // 1 |
| 78 | + /// const b = 2; // 2 |
| 79 | + /// const c = 3; // 3 |
| 80 | + /// }; |
| 81 | + /// ``` |
| 82 | + /// |
| 83 | + /// ### skipBlankLines |
| 84 | + /// |
| 85 | + /// When this options is set to `true`, blank lines in the function body are not counted towards the maximum line limit. |
| 86 | + /// This means that only lines with actual code or comments will be counted. |
| 87 | + /// |
| 88 | + /// Default: `false` |
| 89 | + /// |
| 90 | + /// When `maxLines: 2` and `skipBlankLines: true`, the following function will be considered valid: |
| 91 | + /// ```json,options |
| 92 | + /// { |
| 93 | + /// "options": { |
| 94 | + /// "maxLines": 2, |
| 95 | + /// "skipBlankLines": true |
| 96 | + /// } |
| 97 | + /// } |
| 98 | + /// ``` |
| 99 | + /// ```js,use_options |
| 100 | + /// function example() { |
| 101 | + /// const a = 1; // 1 |
| 102 | + /// // not counted |
| 103 | + /// const b = 2; // 2 |
| 104 | + /// // not counted |
| 105 | + /// }; |
| 106 | + /// ``` |
| 107 | + /// |
| 108 | + /// ### skipIifes |
| 109 | + /// |
| 110 | + /// When this option is set to `true`, Immediately Invoked Function Expressions (IIFEs) are not checked for the maximum line limit. |
| 111 | + /// |
| 112 | + /// Default: `false` |
| 113 | + /// |
| 114 | + /// When `maxLines: 2` and `skipIifes: true`, the following IIFE will be considered valid even though its body has 3 lines: |
| 115 | + /// ```json,options |
| 116 | + /// { |
| 117 | + /// "options": { |
| 118 | + /// "maxLines": 2, |
| 119 | + /// "skipIifes": true |
| 120 | + /// } |
| 121 | + /// } |
| 122 | + /// ``` |
| 123 | + /// ```js,use_options |
| 124 | + /// (() => { |
| 125 | + /// const a = 1; // 1 |
| 126 | + /// const b = 2; // 2 |
| 127 | + /// const c = 3; // 3 |
| 128 | + /// })(); |
| 129 | + /// ``` |
| 130 | + /// |
| 131 | + pub NoExcessiveLinesPerFunction { |
| 132 | + version: "2.0.0", |
| 133 | + name: "noExcessiveLinesPerFunction", |
| 134 | + language: "js", |
| 135 | + recommended: false, |
| 136 | + sources: &[RuleSource::Eslint("max-lines-per-function")], |
| 137 | + source_kind: RuleSourceKind::Inspired, |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +impl Rule for NoExcessiveLinesPerFunction { |
| 142 | + type Query = Semantic<AnyFunctionLike>; |
| 143 | + type State = State; |
| 144 | + type Signals = Option<Self::State>; |
| 145 | + type Options = NoExcessiveLinesPerFunctionOptions; |
| 146 | + |
| 147 | + fn run(ctx: &RuleContext<Self>) -> Self::Signals { |
| 148 | + let binding = ctx.query(); |
| 149 | + let options = ctx.options(); |
| 150 | + |
| 151 | + if let AnyFunctionLike::AnyJsFunction(func) = binding { |
| 152 | + if is_iife(func) && options.skip_iifes { |
| 153 | + return None; |
| 154 | + } |
| 155 | + }; |
| 156 | + |
| 157 | + let Ok(func_body) = binding.body() else { |
| 158 | + return None; |
| 159 | + }; |
| 160 | + |
| 161 | + let function_lines_count = func_body |
| 162 | + .syntax() |
| 163 | + .descendants() |
| 164 | + .flat_map(|descendant| descendant.tokens().collect::<Vec<_>>()) |
| 165 | + .filter(|token| { |
| 166 | + !matches!( |
| 167 | + token.kind(), |
| 168 | + biome_js_syntax::JsSyntaxKind::L_CURLY | biome_js_syntax::JsSyntaxKind::R_CURLY |
| 169 | + ) |
| 170 | + }) |
| 171 | + .fold(0, |acc, token| { |
| 172 | + if options.skip_blank_lines { |
| 173 | + return acc + token.has_leading_newline() as usize; |
| 174 | + }; |
| 175 | + |
| 176 | + acc + token |
| 177 | + .trim_trailing_trivia() |
| 178 | + .leading_trivia() |
| 179 | + .pieces() |
| 180 | + .filter(|piece| piece.is_newline()) |
| 181 | + .count() |
| 182 | + }); |
| 183 | + |
| 184 | + if function_lines_count > options.max_lines.get().into() { |
| 185 | + return Some(State { |
| 186 | + function_lines_count, |
| 187 | + }); |
| 188 | + } |
| 189 | + |
| 190 | + None |
| 191 | + } |
| 192 | + |
| 193 | + fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { |
| 194 | + let node = ctx.query(); |
| 195 | + let options = ctx.options(); |
| 196 | + |
| 197 | + Some( |
| 198 | + RuleDiagnostic::new( |
| 199 | + rule_category!(), |
| 200 | + node.range(), |
| 201 | + markup! { |
| 202 | + "This function has too many lines ("{state.function_lines_count}"). Maximum allowed is "{options.max_lines.to_string()}"." |
| 203 | + }, |
| 204 | + ) |
| 205 | + .note(markup! { |
| 206 | + "Consider refactoring this function to split it into smaller functions." |
| 207 | + }), |
| 208 | + ) |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +fn is_iife(func: &AnyJsFunction) -> bool { |
| 213 | + func.parent::<JsParenthesizedExpression>() |
| 214 | + .and_then(|expr| expr.parent::<JsCallExpression>()) |
| 215 | + .is_some() |
| 216 | +} |
| 217 | + |
| 218 | +pub struct State { |
| 219 | + function_lines_count: usize, |
| 220 | +} |
| 221 | + |
| 222 | +#[derive(Clone, Debug, Deserialize, Deserializable, Eq, PartialEq, Serialize)] |
| 223 | +#[cfg_attr(feature = "schema", derive(JsonSchema))] |
| 224 | +#[serde(rename_all = "camelCase", deny_unknown_fields, default)] |
| 225 | +pub struct NoExcessiveLinesPerFunctionOptions { |
| 226 | + /// The maximum number of lines allowed in a function body. |
| 227 | + pub max_lines: NonZeroU8, |
| 228 | + /// When this options is set to `true`, blank lines in the function body are not counted towards the maximum line limit. |
| 229 | + pub skip_blank_lines: bool, |
| 230 | + /// When this option is set to `true`, Immediately Invoked Function Expressions (IIFEs) are not checked for the maximum line limit. |
| 231 | + pub skip_iifes: bool, |
| 232 | +} |
| 233 | + |
| 234 | +impl Default for NoExcessiveLinesPerFunctionOptions { |
| 235 | + fn default() -> Self { |
| 236 | + Self { |
| 237 | + max_lines: NonZeroU8::new(50).unwrap(), |
| 238 | + skip_blank_lines: false, |
| 239 | + skip_iifes: false, |
| 240 | + } |
| 241 | + } |
| 242 | +} |
0 commit comments