Skip to main content

react_auditor/rules/react/
no_ref_in_component_name.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoRefInComponentName;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-ref-in-component-name",
11    default_severity: Severity::Warning,
12    category: "react",
13    description: "Component names should not contain 'Ref'",
14};
15
16impl Rule for NoRefInComponentName {
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 = RefNameCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct RefNameCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for RefNameCollector<'a> {
37    fn visit_variable_declarator(&mut self, decl: &oxc_ast::ast::VariableDeclarator<'a>) {
38        if let oxc_ast::ast::BindingPattern::BindingIdentifier(ident) = &decl.id {
39            let name = ident.name.as_str();
40            if is_pascal_case(name) && (name.contains("Ref") || name.contains("ref")) {
41                let start = ident.span.start as usize;
42                let line = self.source[..start].lines().count().max(1);
43                let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
44                self.findings.push(RuleFinding {
45                    line,
46                    column: col + 1,
47                    message: format!("Component name `{name}` contains 'Ref' — consider renaming"),
48                });
49            }
50        }
51    }
52
53    fn visit_function(
54        &mut self,
55        func: &oxc_ast::ast::Function<'a>,
56        _flags: oxc_syntax::scope::ScopeFlags,
57    ) {
58        if let Some(ident) = &func.id {
59            let name = ident.name.as_str();
60            if is_pascal_case(name) && (name.contains("Ref") || name.contains("ref")) {
61                let start = ident.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                self.findings.push(RuleFinding {
65                    line,
66                    column: col + 1,
67                    message: format!("Component name `{name}` contains 'Ref' — consider renaming"),
68                });
69            }
70        }
71    }
72}
73
74fn is_pascal_case(s: &str) -> bool {
75    let first = s.chars().next();
76    matches!(first, Some(c) if c.is_ascii_uppercase())
77}