Skip to main content

react_auditor/rules/react/
hook_rules.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_ast_visit::walk;
4use oxc_semantic::Semantic;
5
6use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
7
8pub struct HookRules;
9
10const RULE_META: RuleMeta = RuleMeta {
11    id: "hook-rules",
12    default_severity: Severity::Error,
13    category: "react",
14    description: "Hooks must follow the Rules of Hooks",
15};
16
17const HOOK_PREFIXES: &[&str] = &["use"];
18
19fn is_hook_call(name: &str) -> bool {
20    HOOK_PREFIXES.iter().any(|p| name.starts_with(p))
21        && name.len() > 3
22        && name.as_bytes()[3].is_ascii_uppercase()
23}
24
25struct HookRuleCollector<'a> {
26    findings: Vec<RuleFinding>,
27    source: &'a str,
28    inside_loop: Vec<bool>,
29    inside_condition: Vec<bool>,
30    inside_nested_fn: Vec<bool>,
31}
32
33impl<'a> HookRuleCollector<'a> {
34    fn add_finding(&mut self, start: usize, msg: String) {
35        let line = self.source[..start].lines().count().max(1);
36        let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
37        self.findings.push(RuleFinding {
38            line,
39            column: col + 1,
40            message: msg,
41        });
42    }
43}
44
45impl<'a> Visit<'a> for HookRuleCollector<'a> {
46    fn visit_call_expression(&mut self, expr: &oxc_ast::ast::CallExpression<'a>) {
47        if let oxc_ast::ast::Expression::Identifier(ident) = &expr.callee {
48            let name = ident.name.as_str();
49            if is_hook_call(name) {
50                let in_loop = self.inside_loop.iter().any(|&v| v);
51                let in_condition = self.inside_condition.iter().any(|&v| v);
52                let in_nested_func = self.inside_nested_fn.len() > 1;
53
54                if in_condition {
55                    self.add_finding(
56                        expr.span.start as usize,
57                        format!("React hook `{name}` is called conditionally — move to top level"),
58                    );
59                }
60                if in_loop {
61                    self.add_finding(
62                        expr.span.start as usize,
63                        format!("React hook `{name}` is called inside a loop — move to top level"),
64                    );
65                }
66                if in_nested_func {
67                    self.add_finding(
68                        expr.span.start as usize,
69                        format!("React hook `{name}` is called inside a nested function"),
70                    );
71                }
72            }
73        }
74    }
75
76    fn visit_function(
77        &mut self,
78        func: &oxc_ast::ast::Function<'a>,
79        _flags: oxc_syntax::scope::ScopeFlags,
80    ) {
81        self.inside_nested_fn.push(true);
82        walk::walk_function(self, func, _flags);
83        self.inside_nested_fn.pop();
84    }
85
86    fn visit_arrow_function_expression(
87        &mut self,
88        func: &oxc_ast::ast::ArrowFunctionExpression<'a>,
89    ) {
90        self.inside_nested_fn.push(true);
91        walk::walk_arrow_function_expression(self, func);
92        self.inside_nested_fn.pop();
93    }
94
95    fn visit_if_statement(&mut self, stmt: &oxc_ast::ast::IfStatement<'a>) {
96        self.inside_condition.push(true);
97        walk::walk_if_statement(self, stmt);
98        self.inside_condition.pop();
99    }
100
101    fn visit_conditional_expression(&mut self, expr: &oxc_ast::ast::ConditionalExpression<'a>) {
102        self.inside_condition.push(true);
103        walk::walk_conditional_expression(self, expr);
104        self.inside_condition.pop();
105    }
106
107    fn visit_logical_expression(&mut self, expr: &oxc_ast::ast::LogicalExpression<'a>) {
108        if matches!(
109            expr.operator,
110            oxc_ast::ast::LogicalOperator::And | oxc_ast::ast::LogicalOperator::Or
111        ) {
112            // Walk the left side (unconditional) first, then the right side (conditional)
113            walk::walk_expression(self, &expr.left);
114            self.inside_condition.push(true);
115            walk::walk_expression(self, &expr.right);
116            self.inside_condition.pop();
117        } else {
118            walk::walk_logical_expression(self, expr);
119        }
120    }
121
122    fn visit_for_statement(&mut self, stmt: &oxc_ast::ast::ForStatement<'a>) {
123        self.inside_loop.push(true);
124        walk::walk_for_statement(self, stmt);
125        self.inside_loop.pop();
126    }
127
128    fn visit_for_in_statement(&mut self, stmt: &oxc_ast::ast::ForInStatement<'a>) {
129        self.inside_loop.push(true);
130        walk::walk_for_in_statement(self, stmt);
131        self.inside_loop.pop();
132    }
133
134    fn visit_for_of_statement(&mut self, stmt: &oxc_ast::ast::ForOfStatement<'a>) {
135        self.inside_loop.push(true);
136        walk::walk_for_of_statement(self, stmt);
137        self.inside_loop.pop();
138    }
139
140    fn visit_while_statement(&mut self, stmt: &oxc_ast::ast::WhileStatement<'a>) {
141        self.inside_loop.push(true);
142        walk::walk_while_statement(self, stmt);
143        self.inside_loop.pop();
144    }
145
146    fn visit_do_while_statement(&mut self, stmt: &oxc_ast::ast::DoWhileStatement<'a>) {
147        self.inside_loop.push(true);
148        walk::walk_do_while_statement(self, stmt);
149        self.inside_loop.pop();
150    }
151
152    fn visit_switch_statement(&mut self, stmt: &oxc_ast::ast::SwitchStatement<'a>) {
153        // The discriminant expression is unconditional — walk it first
154        walk::walk_expression(self, &stmt.discriminant);
155        self.inside_condition.push(true);
156        for case in &stmt.cases {
157            walk::walk_switch_case(self, case);
158        }
159        self.inside_condition.pop();
160    }
161}
162
163impl Rule for HookRules {
164    fn meta(&self) -> &RuleMeta {
165        &RULE_META
166    }
167
168    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
169        let mut collector = HookRuleCollector {
170            findings: Vec::new(),
171            source: source_text,
172            inside_loop: Vec::new(),
173            inside_condition: Vec::new(),
174            inside_nested_fn: Vec::new(),
175        };
176        collector.visit_program(program);
177        collector.findings
178    }
179}