Skip to main content

react_auditor/rules/react/
no_duplicate_props.rs

1use std::collections::HashSet;
2
3use oxc_ast::ast::Program;
4use oxc_ast_visit::Visit;
5use oxc_semantic::Semantic;
6
7use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
8
9pub struct NoDuplicateProps;
10
11const RULE_META: RuleMeta = RuleMeta {
12    id: "jsx-no-duplicate-props",
13    default_severity: Severity::Error,
14    category: "react",
15    description: "Duplicate props are not allowed in JSX",
16};
17
18impl Rule for NoDuplicateProps {
19    fn meta(&self) -> &RuleMeta {
20        &RULE_META
21    }
22
23    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
24        let mut collector = DuplicatePropsCollector {
25            findings: Vec::new(),
26            source: source_text,
27        };
28        collector.visit_program(program);
29        collector.findings
30    }
31}
32
33struct DuplicatePropsCollector<'a> {
34    findings: Vec<RuleFinding>,
35    source: &'a str,
36}
37
38impl<'a> Visit<'a> for DuplicatePropsCollector<'a> {
39    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
40        let mut seen: HashSet<&str> = HashSet::new();
41
42        for attr_item in &el.attributes {
43            if let oxc_ast::ast::JSXAttributeItem::Attribute(attr) = attr_item
44                && let oxc_ast::ast::JSXAttributeName::Identifier(ident) = &attr.name
45            {
46                let name = ident.name.as_str();
47                if !seen.insert(name) {
48                    let start = attr.span.start as usize;
49                    let line = self.source[..start].lines().count().max(1);
50                    let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
51                    self.findings.push(RuleFinding {
52                        line,
53                        column: col + 1,
54                        message: format!("Duplicate prop `{name}`"),
55                    });
56                }
57            }
58        }
59    }
60}