From bd36325845845b170ad20967771f0bbabd3c51d4 Mon Sep 17 00:00:00 2001 From: Boshen Date: Tue, 10 Dec 2024 18:23:27 +0800 Subject: [PATCH] feat(napi/parer): add `get_line_column_number` API --- Cargo.lock | 1 + napi/parser/Cargo.toml | 1 + napi/parser/src/magic_string.rs | 16 ++++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 5357028946330a..6f9be2bf0e1f4e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1834,6 +1834,7 @@ dependencies = [ "napi-derive", "oxc", "oxc_ast", + "oxc_data_structures", "oxc_napi", "rustc-hash", "self_cell", diff --git a/napi/parser/Cargo.toml b/napi/parser/Cargo.toml index a4d767d43642da..5187e4b078a64a 100644 --- a/napi/parser/Cargo.toml +++ b/napi/parser/Cargo.toml @@ -23,6 +23,7 @@ doctest = false [dependencies] oxc = { workspace = true } oxc_ast = { workspace = true, features = ["serialize"] } # enable feature only +oxc_data_structures = { workspace = true } oxc_napi = { workspace = true } rustc-hash = { workspace = true } diff --git a/napi/parser/src/magic_string.rs b/napi/parser/src/magic_string.rs index dd650d41d013fb..883aecd82a0070 100644 --- a/napi/parser/src/magic_string.rs +++ b/napi/parser/src/magic_string.rs @@ -2,6 +2,7 @@ // use std::sync::Arc; use napi_derive::napi; +use oxc_data_structures::rope::{get_line_column, Rope}; // use oxc_sourcemap::napi::SourceMap; use self_cell::self_cell; @@ -10,6 +11,7 @@ use string_wizard::MagicString as MS; #[napi] pub struct MagicString { cell: MagicStringImpl, + rope: Option, } self_cell!( @@ -26,6 +28,12 @@ impl MagicString { } } +#[napi(object)] +pub struct LineColumn { + pub line: u32, + pub column: u32, +} + #[napi(object)] pub struct OverwriteOptions { pub content_only: bool, @@ -45,6 +53,14 @@ impl MagicString { &self.cell.borrow_owner()[start as usize..end as usize] } + #[napi] + pub fn get_line_column(&self, offest: u32) -> LineColumn { + let source_text = self.cell.borrow_owner(); + let rope = self.rope.get_or_insert_with(|| Rope::from_str(source_text)); + let (line, column) = get_line_column(rope, offset, source_text); + LineColumn { line, column } + } + #[napi] pub fn length(&self) -> u32 { self.cell.borrow_dependent().len() as u32