react_auditor/rules/react/
prefer_function_components.rs1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct PreferFunctionComponents;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "prefer-function-components",
11 default_severity: Severity::Warning,
12 category: "react",
13 description: "Prefer function components over class components",
14};
15
16impl Rule for PreferFunctionComponents {
17 fn meta(&self) -> &RuleMeta {
18 &RULE_META
19 }
20
21 fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
22 let mut collector = ClassComponentCollector {
23 findings: Vec::new(),
24 source: source_text,
25 };
26 collector.visit_program(program);
27 collector.findings
28 }
29}
30
31struct ClassComponentCollector<'a> {
32 findings: Vec<RuleFinding>,
33 source: &'a str,
34}
35
36impl<'a> Visit<'a> for ClassComponentCollector<'a> {
37 fn visit_class(&mut self, class: &oxc_ast::ast::Class<'a>) {
38 let extends_react = class.super_class.as_ref().is_some_and(|expr| {
39 if let oxc_ast::ast::Expression::Identifier(ident) = expr {
40 let name = ident.name.as_str();
41 name == "Component" || name == "PureComponent"
42 } else if let Some(member) = expr.as_member_expression() {
43 member
44 .static_property_name()
45 .is_some_and(|n| n == "Component" || n == "PureComponent")
46 } else {
47 false
48 }
49 });
50
51 if extends_react && let Some(id) = &class.id {
52 let start = id.span.start as usize;
53 let line = self.source[..start].lines().count().max(1);
54 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
55 self.findings.push(RuleFinding {
56 line,
57 column: col + 1,
58 message: format!(
59 "`{}` extends Component — prefer a function component",
60 id.name
61 ),
62 });
63 }
64 }
65}