@@ -4,7 +4,7 @@ use oxc_ast::{
4
4
} ;
5
5
use oxc_diagnostics:: OxcDiagnostic ;
6
6
use oxc_macros:: declare_oxc_lint;
7
- use oxc_span:: Span ;
7
+ use oxc_span:: { GetSpan , Span } ;
8
8
9
9
use crate :: {
10
10
context:: { ContextHost , LintContext } ,
@@ -38,38 +38,27 @@ declare_oxc_lint!(
38
38
fix
39
39
) ;
40
40
41
- fn is_nest_module ( node : & AstNode , ctx : & LintContext < ' _ > ) -> bool {
42
- ctx. nodes ( )
43
- . parent_node ( node. id ( ) )
44
- . map_or ( false , |parent_node| is_valid_module_node ( parent_node) )
45
- }
46
-
47
- fn is_valid_module_node ( node : & AstNode ) -> bool {
48
- matches ! ( node. kind( ) , AstKind :: TSModuleDeclaration ( module) if is_valid_module( module) )
49
- }
50
-
51
41
fn is_valid_module ( module : & TSModuleDeclaration ) -> bool {
52
- !module. id . is_string_literal ( )
53
- && matches ! ( module. id, TSModuleDeclarationName :: Identifier ( _) )
42
+ matches ! ( module. id, TSModuleDeclarationName :: Identifier ( _) )
54
43
&& module. kind == TSModuleDeclarationKind :: Module
55
44
}
56
45
57
46
impl Rule for PreferNamespaceKeyword {
58
47
fn run < ' a > ( & self , node : & AstNode < ' a > , ctx : & LintContext < ' a > ) {
59
48
let AstKind :: TSModuleDeclaration ( module) = node. kind ( ) else { return } ;
60
49
61
- if !is_valid_module ( module) || is_nest_module ( node , ctx ) {
50
+ if !is_valid_module ( module) {
62
51
return ;
63
52
}
64
53
54
+ let token = ctx. source_range ( Span :: new ( module. span . start , module. id . span ( ) . start ) ) ;
55
+ let Some ( offset) = token. find ( "module" ) else {
56
+ return ;
57
+ } ;
58
+
65
59
ctx. diagnostic_with_fix ( prefer_namespace_keyword_diagnostic ( module. span ) , |fixer| {
66
- let span_size = u32:: try_from ( "module" . len ( ) ) . unwrap_or ( 6 ) ;
67
- let span_start = if module. declare {
68
- module. span . start + u32:: try_from ( "declare " . len ( ) ) . unwrap_or ( 8 )
69
- } else {
70
- module. span . start
71
- } ;
72
- fixer. replace ( Span :: sized ( span_start, span_size) , "namespace" )
60
+ let span_start = module. span . start + u32:: try_from ( offset) . unwrap ( ) ;
61
+ fixer. replace ( Span :: sized ( span_start, 6 ) , "namespace" )
73
62
} ) ;
74
63
}
75
64
@@ -88,6 +77,7 @@ fn test() {
88
77
"namespace foo {}" ,
89
78
"declare namespace foo {}" ,
90
79
"declare global {}" ,
80
+ "module''.s" ,
91
81
] ;
92
82
93
83
let fail = vec ! [
@@ -104,6 +94,7 @@ fn test() {
104
94
module foo {}
105
95
}
106
96
" ,
97
+ "module foo.'a'" ,
107
98
] ;
108
99
109
100
let fix = vec ! [
@@ -136,6 +127,8 @@ fn test() {
136
127
" ,
137
128
None ,
138
129
) ,
130
+ ( "module foo.'a'" , "namespace foo.'a'" , None ) ,
139
131
] ;
132
+
140
133
Tester :: new ( PreferNamespaceKeyword :: NAME , pass, fail) . expect_fix ( fix) . test_and_snapshot ( ) ;
141
134
}
0 commit comments