react_auditor/rules/quality/
no_long_functions.rs1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_ast_visit::walk;
4use oxc_semantic::Semantic;
5use oxc_syntax::scope::ScopeFlags;
6
7use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
8
9pub struct NoLongFunctions;
10
11const RULE_META: RuleMeta = RuleMeta {
12 id: "no-long-functions",
13 default_severity: Severity::Warning,
14 category: "quality",
15 description: "Functions should not exceed 40 lines",
16};
17
18const MAX_LINES: usize = 40;
19
20impl Rule for NoLongFunctions {
21 fn meta(&self) -> &RuleMeta {
22 &RULE_META
23 }
24
25 fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
26 let mut collector = LongFnCollector {
27 findings: Vec::new(),
28 source: source_text,
29 };
30 collector.visit_program(program);
31 collector.findings
32 }
33}
34
35struct LongFnCollector<'a> {
36 findings: Vec<RuleFinding>,
37 source: &'a str,
38}
39
40impl<'a> Visit<'a> for LongFnCollector<'a> {
41 fn visit_function(&mut self, func: &oxc_ast::ast::Function<'a>, _flags: ScopeFlags) {
42 if let Some(body) = &func.body {
43 let start_line = self.source[..body.span.start as usize].lines().count();
44 let end_line = self.source[..body.span.end as usize].lines().count();
45 let line_count = end_line - start_line;
46
47 if line_count > MAX_LINES {
48 let name = func
49 .id
50 .as_ref()
51 .map(|id| id.name.as_str())
52 .unwrap_or("anonymous");
53
54 self.findings.push(RuleFinding {
55 line: start_line + 1,
56 column: 1,
57 message: format!(
58 "Function `{name}` is {line_count} lines long (max {MAX_LINES})"
59 ),
60 });
61 }
62 }
63 walk::walk_function(self, func, _flags);
64 }
65
66 fn visit_arrow_function_expression(
67 &mut self,
68 func: &oxc_ast::ast::ArrowFunctionExpression<'a>,
69 ) {
70 let start_line = self.source[..func.body.span.start as usize].lines().count();
71 let end_line = self.source[..func.body.span.end as usize].lines().count();
72 let line_count = end_line - start_line;
73
74 if line_count > MAX_LINES {
75 self.findings.push(RuleFinding {
76 line: start_line + 1,
77 column: 1,
78 message: format!("Arrow function is {line_count} lines long (max {MAX_LINES})"),
79 });
80 }
81 walk::walk_arrow_function_expression(self, func);
82 }
83}