react_auditor/rules/react/
no_state_in_default_props.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 NoStateInDefaultProps;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "no-state-in-default-props",
11 default_severity: Severity::Warning,
12 category: "react",
13 description: "Don't derive default props from state",
14};
15
16impl Rule for NoStateInDefaultProps {
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 = StateInDefaultPropsCollector {
23 findings: Vec::new(),
24 source: source_text,
25 in_default_props: false,
26 };
27 collector.visit_program(program);
28 collector.findings
29 }
30}
31
32struct StateInDefaultPropsCollector<'a> {
33 findings: Vec<RuleFinding>,
34 source: &'a str,
35 in_default_props: bool,
36}
37
38impl<'a> StateInDefaultPropsCollector<'a> {
39 fn push_finding(&mut self, start: usize) {
40 let line = self.source[..start].lines().count().max(1);
41 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
42 self.findings.push(RuleFinding {
43 line,
44 column: col + 1,
45 message: "Default props should not reference component state".to_string(),
46 });
47 }
48}
49
50impl<'a> Visit<'a> for StateInDefaultPropsCollector<'a> {
51 fn visit_assignment_expression(&mut self, expr: &oxc_ast::ast::AssignmentExpression<'a>) {
52 let is_default_props = matches!(
53 &expr.left,
54 oxc_ast::ast::AssignmentTarget::StaticMemberExpression(member)
55 if member.property.name.as_str() == "defaultProps"
56 );
57 if is_default_props {
58 self.in_default_props = true;
59 oxc_ast_visit::walk::walk_assignment_expression(self, expr);
60 self.in_default_props = false;
61 return;
62 }
63 if !self.in_default_props {
64 oxc_ast_visit::walk::walk_assignment_expression(self, expr);
65 }
66 }
67
68 fn visit_this_expression(&mut self, expr: &oxc_ast::ast::ThisExpression) {
69 if self.in_default_props {
70 self.push_finding(expr.span.start as usize);
71 }
72 }
73}