Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions crates/oxc_ast/src/serialize.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use cow_utils::CowUtils;

use crate::ast::*;
use oxc_ast_macros::ast_meta;
use oxc_estree::{
CompactJSSerializer, CompactTSSerializer, ESTree, JsonSafeString, LoneSurrogatesString,
PrettyJSSerializer, PrettyTSSerializer, SequenceSerializer, Serializer, StructSerializer,
};

use crate::ast::*;
use oxc_span::GetSpan;

/// Main serialization methods for `Program`.
///
Expand Down Expand Up @@ -37,7 +37,16 @@ const JSON_CAPACITY_RATIO_PRETTY: usize = 80;

impl Program<'_> {
/// Serialize AST to ESTree JSON, including TypeScript fields.
pub fn to_estree_ts_json(&self) -> String {
pub fn to_estree_ts_json(&mut self) -> String {
// Set start span to first token of first directive or statement. This is required because
// unlike Acorn, TS-ESLint excludes whitespace and comments from the `Program` start span.
// See https://github.com/oxc-project/oxc/pull/10134 for more info.
if let Some(first_directive) = self.directives.first() {
self.span.start = first_directive.span.start;
} else if let Some(first_stmt) = self.body.first() {
self.span.start = first_stmt.span().start;
}

let capacity = self.source_text.len() * JSON_CAPACITY_RATIO_COMPACT;
let mut serializer = CompactTSSerializer::with_capacity(capacity);
self.serialize(&mut serializer);
Expand All @@ -53,7 +62,16 @@ impl Program<'_> {
}

/// Serialize AST to pretty-printed ESTree JSON, including TypeScript fields.
pub fn to_pretty_estree_ts_json(&self) -> String {
pub fn to_pretty_estree_ts_json(&mut self) -> String {
// Set start span to first token of first directive or statement. This is required because
// unlike Acorn, TS-ESLint excludes whitespace and comments from the `Program` start span.
// See https://github.com/oxc-project/oxc/pull/10134 for more info.
if let Some(first_directive) = self.directives.first() {
self.span.start = first_directive.span.start;
} else if let Some(first_stmt) = self.body.first() {
self.span.start = first_stmt.span().start;
}

let capacity = self.source_text.len() * JSON_CAPACITY_RATIO_PRETTY;
let mut serializer = PrettyTSSerializer::with_capacity(capacity);
self.serialize(&mut serializer);
Expand Down
Loading
Loading