Skip to main content

react_auditor/rules/quality/
no_magic_numbers.rs

1use oxc_ast::ast::{NumericLiteral, Program, VariableDeclarationKind};
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoMagicNumbers;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-magic-numbers",
11    default_severity: Severity::Warning,
12    category: "quality",
13    description: "Prefer named constants over magic numbers",
14};
15
16const ALLOWED: &[f64] = &[-1.0, 0.0, 1.0, 2.0, 100.0];
17
18impl Rule for NoMagicNumbers {
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 = MagicCollector {
25            findings: Vec::new(),
26            source: source_text,
27            in_const_decl: false,
28        };
29        collector.visit_program(program);
30        collector.findings
31    }
32}
33
34struct MagicCollector<'a> {
35    findings: Vec<RuleFinding>,
36    source: &'a str,
37    in_const_decl: bool,
38}
39
40impl<'a> Visit<'a> for MagicCollector<'a> {
41    fn visit_variable_declarator(&mut self, decl: &oxc_ast::ast::VariableDeclarator<'a>) {
42        let was_in_const = self.in_const_decl;
43        self.in_const_decl = decl.kind == VariableDeclarationKind::Const;
44        oxc_ast_visit::walk::walk_variable_declarator(self, decl);
45        self.in_const_decl = was_in_const;
46    }
47
48    fn visit_numeric_literal(&mut self, lit: &NumericLiteral) {
49        if !self.in_const_decl && !ALLOWED.contains(&lit.value) {
50            let start = lit.span.start as usize;
51            let line = self.source[..start].lines().count().max(1);
52            let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
53            self.findings.push(RuleFinding {
54                line,
55                column: col + 1,
56                message: format!(
57                    "Magic number `{}` — use a named constant instead",
58                    lit.value
59                ),
60            });
61        }
62    }
63}