Skip to main content

react_auditor/rules/react/
consistent_component_naming.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4use oxc_syntax::scope::ScopeFlags;
5
6use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
7
8pub struct ConsistentComponentNaming;
9
10const RULE_META: RuleMeta = RuleMeta {
11    id: "consistent-component-naming",
12    default_severity: Severity::Warning,
13    category: "react",
14    description: "Component names should be PascalCase, hooks should be camelCase",
15};
16
17impl Rule for ConsistentComponentNaming {
18    fn meta(&self) -> &RuleMeta {
19        &RULE_META
20    }
21
22    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
23        let mut collector = NamingCollector {
24            findings: Vec::new(),
25            source: source_text,
26        };
27        collector.visit_program(program);
28        collector.findings
29    }
30}
31
32struct NamingCollector<'a> {
33    findings: Vec<RuleFinding>,
34    source: &'a str,
35}
36
37impl<'a> Visit<'a> for NamingCollector<'a> {
38    fn visit_function(&mut self, func: &oxc_ast::ast::Function<'a>, _flags: ScopeFlags) {
39        if let Some(id) = &func.id {
40            let name = id.name.as_str();
41
42            if name.starts_with("use") && name.len() > 3 {
43                // Hooks should be camelCase (useFoo), not PascalCase
44                let rest = &name[3..];
45                if !rest.is_empty() && rest.chars().next().is_some_and(|c| c.is_uppercase()) {
46                    // This is a valid hook name like `useState` - skip
47                    return;
48                }
49                return;
50            }
51
52            // Check if function returns JSX (heuristic: check body for JSX)
53            let returns_jsx = func
54                .body
55                .as_ref()
56                .is_some_and(|body| body.statements.iter().any(|stmt| contains_jsx(stmt)));
57
58            if returns_jsx {
59                let first_char = name.chars().next().unwrap_or(' ');
60                if first_char.is_lowercase() {
61                    let start = id.span.start as usize;
62                    let line = self.source[..start].lines().count().max(1);
63                    let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
64
65                    self.findings.push(RuleFinding {
66                        line,
67                        column: col + 1,
68                        message: format!("Component `{name}` should be PascalCase"),
69                    });
70                }
71            }
72        }
73    }
74}
75
76fn contains_jsx(stmt: &oxc_ast::ast::Statement) -> bool {
77    match stmt {
78        oxc_ast::ast::Statement::ReturnStatement(ret) => ret
79            .argument
80            .as_ref()
81            .is_some_and(|arg| is_jsx_expression(arg)),
82        oxc_ast::ast::Statement::ExpressionStatement(expr) => is_jsx_expression(&expr.expression),
83        oxc_ast::ast::Statement::BlockStatement(block) => {
84            block.body.iter().any(|s| contains_jsx(s))
85        }
86        _ => false,
87    }
88}
89
90fn is_jsx_expression(expr: &oxc_ast::ast::Expression) -> bool {
91    matches!(
92        expr,
93        oxc_ast::ast::Expression::JSXElement(_) | oxc_ast::ast::Expression::JSXFragment(_)
94    )
95}