Skip to content

Commit 22fca03

Browse files
committed
perf(linter/typescript): avoid searching source text unless required
1 parent c167dfa commit 22fca03

File tree

2 files changed

+16
-17
lines changed

2 files changed

+16
-17
lines changed

crates/oxc_linter/src/rules/typescript/no_namespace.rs

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
use oxc_ast::{
2-
AstKind,
3-
ast::{TSModuleDeclarationKind, TSModuleDeclarationName},
4-
};
1+
use oxc_ast::{AstKind, ast::TSModuleDeclarationName};
52
use oxc_diagnostics::OxcDiagnostic;
63
use oxc_macros::declare_oxc_lint;
74
use oxc_span::Span;
@@ -141,6 +138,8 @@ impl Rule for NoNamespace {
141138
return;
142139
}
143140

141+
// Ignore nested `TSModuleDeclaration`s
142+
// e.g. the 2 inner `TSModuleDeclaration`s in `module A.B.C {}`
144143
if let AstKind::TSModuleDeclaration(_) = ctx.nodes().parent_kind(node.id()) {
145144
return;
146145
}
@@ -151,17 +150,12 @@ impl Rule for NoNamespace {
151150
return;
152151
}
153152

154-
let span = match declaration.kind {
155-
TSModuleDeclarationKind::Module => ctx
156-
.find_next_token_from(declaration.span.start, "module")
157-
.map(|i| Span::sized(declaration.span.start + i, 6)),
158-
TSModuleDeclarationKind::Namespace => ctx
159-
.find_next_token_from(declaration.span.start, "namespace")
160-
.map(|i| Span::sized(declaration.span.start + i, 9)),
161-
};
162-
if let Some(span) = span {
163-
ctx.diagnostic(no_namespace_diagnostic(span));
164-
}
153+
let keyword = declaration.kind.as_str();
154+
let mut span_start = declaration.span.start;
155+
span_start += ctx.find_next_token_from(span_start, keyword).unwrap();
156+
#[expect(clippy::cast_possible_truncation)]
157+
let span = Span::sized(span_start, keyword.len() as u32);
158+
ctx.diagnostic(no_namespace_diagnostic(span));
165159
}
166160

167161
fn should_run(&self, ctx: &ContextHost) -> bool {

crates/oxc_linter/src/rules/typescript/prefer_namespace_keyword.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,15 @@ impl Rule for PreferNamespaceKeyword {
6161
return;
6262
}
6363

64-
let Some(offset) = ctx.find_next_token_from(module.span.start, "module") else { return };
64+
// Ignore nested `TSModuleDeclaration`s
65+
// e.g. the 2 inner `TSModuleDeclaration`s in `module A.B.C {}`
66+
if let AstKind::TSModuleDeclaration(_) = ctx.nodes().parent_kind(node.id()) {
67+
return;
68+
}
6569

6670
ctx.diagnostic_with_fix(prefer_namespace_keyword_diagnostic(module.span), |fixer| {
67-
let span_start = module.span.start + offset;
71+
let mut span_start = module.span.start;
72+
span_start += ctx.find_next_token_from(span_start, "module").unwrap();
6873
fixer.replace(Span::sized(span_start, 6), "namespace")
6974
});
7075
}

0 commit comments

Comments
 (0)