From 56723fafa7c6c650bc00b975e3af75d3e70560d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90=20Kevin=20Deng?= Date: Mon, 17 Feb 2025 22:03:05 +0800 Subject: [PATCH] feat(wasm/parser): expose comments --- wasm/parser/src/lib.rs | 45 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/wasm/parser/src/lib.rs b/wasm/parser/src/lib.rs index 5c9f9f69f5db0..b846305d0a96e 100644 --- a/wasm/parser/src/lib.rs +++ b/wasm/parser/src/lib.rs @@ -1,6 +1,6 @@ #![expect(clippy::needless_pass_by_value)] -use oxc::{allocator::Allocator, parser::Parser, span::SourceType}; +use oxc::{allocator::Allocator, ast::CommentKind, parser::Parser, span::SourceType}; use serde::{Deserialize, Serialize}; use tsify::Tsify; use wasm_bindgen::prelude::*; @@ -30,6 +30,10 @@ pub struct ParseResult { #[tsify(type = "Program")] pub program: JsValue, + #[wasm_bindgen(readonly, skip_typescript)] + #[tsify(type = "Comment[]")] + pub comments: Vec, + #[wasm_bindgen(readonly, skip_typescript)] #[tsify(type = "Diagnostic[]")] pub errors: Vec, @@ -43,6 +47,21 @@ pub struct Diagnostic { pub message: String, } +#[derive(Clone, Tsify, Serialize)] +pub struct Comment { + pub r#type: CommentType, + pub value: String, + pub start: u32, + pub end: u32, +} + +#[derive(Clone, Copy, Tsify, Serialize)] +#[tsify(into_wasm_abi)] +pub enum CommentType { + Line, + Block, +} + /// # Errors /// /// * wasm bindgen serialization failed @@ -78,6 +97,28 @@ pub fn parse_sync( let program = ret.program.serialize(&serializer)?; + let comments: Vec = if ret.program.comments.is_empty() { + vec![] + } else { + ret.program + .comments + .iter() + .map(|comment| { + Comment { + r#type: match comment.kind { + CommentKind::Line => CommentType::Line, + CommentKind::Block => CommentType::Block, + }, + value: comment.content_span().source_text(&source_text).to_string(), + start: comment.span.start, + end: comment.span.end, + } + .serialize(&serializer) + .unwrap() + }) + .collect::>() + }; + let errors = if ret.errors.is_empty() { vec![] } else { @@ -102,5 +143,5 @@ pub fn parse_sync( .collect::>() }; - Ok(ParseResult { program, errors }) + Ok(ParseResult { program, comments, errors }) }