|
| 1 | +use oxc_ast::AstKind; |
1 | 2 | use oxc_diagnostics::OxcDiagnostic; |
2 | 3 | use oxc_macros::declare_oxc_lint; |
3 | | -use oxc_semantic::SymbolId; |
| 4 | +use oxc_semantic::{AstNode, SymbolId}; |
4 | 5 | use oxc_span::Span; |
5 | 6 |
|
6 | 7 | use crate::{context::LintContext, rule::Rule}; |
@@ -50,18 +51,53 @@ declare_oxc_lint!( |
50 | 51 | ); |
51 | 52 |
|
52 | 53 | impl Rule for NoConstAssign { |
53 | | - fn run_on_symbol(&self, symbol_id: SymbolId, ctx: &LintContext<'_>) { |
54 | | - let symbol_table = ctx.scoping(); |
55 | | - if symbol_table.symbol_flags(symbol_id).is_const_variable() { |
56 | | - for reference in symbol_table.get_resolved_references(symbol_id) { |
57 | | - if reference.is_write() { |
58 | | - ctx.diagnostic(no_const_assign_diagnostic( |
59 | | - symbol_table.symbol_name(symbol_id), |
60 | | - symbol_table.symbol_span(symbol_id), |
61 | | - ctx.semantic().reference_span(reference), |
62 | | - )); |
| 54 | + fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { |
| 55 | + match node.kind() { |
| 56 | + AstKind::VariableDeclaration(var_decl) if var_decl.kind.is_const() => { |
| 57 | + for decl in &var_decl.declarations { |
| 58 | + for ident in decl.id.get_binding_identifiers() { |
| 59 | + check_symbol(ident.symbol_id(), ctx); |
| 60 | + } |
63 | 61 | } |
64 | 62 | } |
| 63 | + AstKind::ArrayPattern(pat) => { |
| 64 | + let Some(idents) = &pat.rest else { |
| 65 | + return; |
| 66 | + }; |
| 67 | + for ident in idents.argument.get_binding_identifiers() { |
| 68 | + let symbol_id = ident.symbol_id(); |
| 69 | + let symbol_table = ctx.scoping(); |
| 70 | + if symbol_table.symbol_flags(symbol_id).is_const_variable() { |
| 71 | + check_symbol(symbol_id, ctx); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + AstKind::AssignmentPattern(pat) => { |
| 76 | + for ident in pat.left.get_binding_identifiers() { |
| 77 | + let symbol_id = ident.symbol_id(); |
| 78 | + let symbol_table = ctx.scoping(); |
| 79 | + if symbol_table.symbol_flags(symbol_id).is_const_variable() { |
| 80 | + check_symbol(symbol_id, ctx); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + _ => {} |
| 85 | + } |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +fn check_symbol(symbol_id: SymbolId, ctx: &LintContext<'_>) { |
| 90 | + let symbol_table = ctx.scoping(); |
| 91 | + // This symbol _should_ always be considered a const variable (since we got it from a const declaration), |
| 92 | + // but we check in debug mode just to be sure. |
| 93 | + debug_assert!(symbol_table.symbol_flags(symbol_id).is_const_variable()); |
| 94 | + for reference in symbol_table.get_resolved_references(symbol_id) { |
| 95 | + if reference.is_write() { |
| 96 | + ctx.diagnostic(no_const_assign_diagnostic( |
| 97 | + symbol_table.symbol_name(symbol_id), |
| 98 | + symbol_table.symbol_span(symbol_id), |
| 99 | + ctx.semantic().reference_span(reference), |
| 100 | + )); |
65 | 101 | } |
66 | 102 | } |
67 | 103 | } |
|
0 commit comments