fix(parser): fix span start for TSModuleDeclaration (#2593)

[playground](https://oxc-project.github.io/oxc/playground/?code=3YCAAICZgICAgICAgICymcgR7351T2PErukD7UXVyom%2F90VSbC7jSaCgoj9%2BqCyA)

---------

Co-authored-by: Boshen <boshenc@gmail.com>
This commit is contained in:
Arnaud Barré 2024-03-04 05:29:32 +01:00 committed by GitHub
parent f66059e91b
commit 24d46bccb5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 17 additions and 13 deletions

View file

@ -1,5 +1,5 @@
use oxc_ast::{
ast::{ModifierKind, TSModuleDeclarationName},
ast::{ModifierKind, TSModuleDeclarationKind, TSModuleDeclarationName},
AstKind,
};
use oxc_diagnostics::{
@ -61,6 +61,7 @@ impl Rule for NoNamespace {
}
}
#[allow(clippy::cast_possible_truncation)]
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
let AstKind::TSModuleDeclaration(declaration) = node.kind() else { return };
let TSModuleDeclarationName::Identifier(ident) = &declaration.id else { return };
@ -83,15 +84,20 @@ impl Rule for NoNamespace {
return;
}
let start = declaration.span.start;
let span = Span::new(start, declaration.span.start + 6); // "module".len()
let modifier = span.source_text(ctx.source_text());
let span = if modifier == "module" {
span
} else {
Span::new(start, declaration.span.start + 9) // "namespace".len()
let declaration_code = declaration.span.source_text(ctx.source_text());
let span = match declaration.kind {
TSModuleDeclarationKind::Global => None, // handled above
TSModuleDeclarationKind::Module => declaration_code.find("module").map(|i| {
Span::new(declaration.span.start + i as u32, declaration.span.start + i as u32 + 6)
}),
TSModuleDeclarationKind::Namespace => declaration_code.find("namespace").map(|i| {
Span::new(declaration.span.start + i as u32, declaration.span.start + i as u32 + 9)
}),
};
ctx.diagnostic(NoNamespaceDiagnostic(span));
if let Some(span) = span {
ctx.diagnostic(NoNamespaceDiagnostic(span));
}
}
}

View file

@ -295,16 +295,14 @@ impl<'a> ParserImpl<'a> {
match self.cur_kind() {
Kind::Namespace => {
let kind = TSModuleDeclarationKind::Namespace;
let span = self.start_span();
self.bump_any();
self.parse_ts_namespace_or_module_declaration_body(span, kind, modifiers)
self.parse_ts_namespace_or_module_declaration_body(start_span, kind, modifiers)
.map(Declaration::TSModuleDeclaration)
}
Kind::Module => {
let kind = TSModuleDeclarationKind::Module;
let span = self.start_span();
self.bump_any();
self.parse_ts_namespace_or_module_declaration_body(span, kind, modifiers)
self.parse_ts_namespace_or_module_declaration_body(start_span, kind, modifiers)
.map(Declaration::TSModuleDeclaration)
}
Kind::Global => {