Skip to content
Draft
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
16 changes: 4 additions & 12 deletions crates/swc_formatter/src/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,8 @@ pub fn format(
) -> Result<String, FormatError> {
let session = FormatSession::new(options.into());
let producer = EcmaDocumentProducer::new(parser_options);
let document = session.produce(&producer, source, &options.into())?;
Ok(print_source_document(
source,
document,
session.print_options(),
))
let writer = producer.write(session.context(), source, options.into())?;
Ok(writer.with_doc(|doc| print_source_document(source, doc, session.print_options())))
}

/// Format an already parsed program AST.
Expand All @@ -57,12 +53,8 @@ pub fn format(
/// Panics if the AST has no root or its root is not a program.
pub fn format_ast(ast: &AstCtx<'_>, options: FormatOptions) -> Result<String, FormatError> {
let session = FormatSession::new(options.into());
let document = formatter::ast_to_doc(ast, session.context(), options.into())?;
Ok(print_source_document(
ast.source(),
document,
session.print_options(),
))
let writer = formatter::ast_to_writer(ast, session.context(), options.into())?;
Ok(writer.with_doc(|doc| print_source_document(ast.source(), doc, session.print_options())))
}

/// JavaScript and TypeScript formatting options.
Expand Down
2 changes: 1 addition & 1 deletion crates/swc_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn printed_edit(source: &str, doc: RangeDocument<'_>, options: PrintOptions) ->
}

fn print_source_document(source: &str, document: Doc<'_>, options: PrintOptions) -> String {
let mut output = document.print(options);
let mut output = document.print_with_capacity(options, source.len());
if source.starts_with('\u{feff}') {
output.insert(0, '\u{feff}');
}
Expand Down
16 changes: 11 additions & 5 deletions crates/swc_formatter_core/src/document.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Flat instruction streams with borrowed text and explicit layout scopes.
//!
//! Construction owns a growable instruction buffer in the formatting arena.
//! Finishing seals an immutable slice; source text remains borrowed from its owner.
//! Construction grows a temporary instruction buffer.
//! Finishing stores an immutable slice in the formatting arena; source text
//! remains borrowed from its owner.
//! Compact instructions retain immutable borrows with checked lengths.
//! Line suffixes retain complete Docs and their insertion mode and indentation.
//! Syntax-specific whitespace and break requests belong to the caller's Doc.
Expand Down Expand Up @@ -613,7 +614,12 @@ impl<'a> Doc<'a> {
}

pub fn print(self, options: PrintOptions) -> String {
printer::print(self, options, false)
self.print_with_capacity(options, 0)
}

/// Prints with a best-effort initial capacity for the output string.
pub fn print_with_capacity(self, options: PrintOptions, capacity: usize) -> String {
printer::print(self, options, false, capacity)
.expect("cursor collection is disabled")
.text
}
Expand All @@ -632,7 +638,7 @@ impl<'a> Doc<'a> {
writer.cursor();
writer.align_text(indent, |writer| writer.write_doc(&self));
writer.line_suffix(|writer| writer.cursor());
let mut printed = writer.finish().print_with_cursor(options)?;
let mut printed = writer.with_doc(|doc| doc.print_with_cursor(options))?;
let range = printed.cursor_range.ok_or(CursorError)?;
printed.text.truncate(range.end);
printed.text.drain(..range.start);
Expand All @@ -642,6 +648,6 @@ impl<'a> Doc<'a> {
/// Prints the Doc and returns the UTF-8 byte range between two emitted cursors.
/// Zero or one cursor produces no range. More than two produces an error.
pub fn print_with_cursor(self, options: PrintOptions) -> Result<PrintResult, CursorError> {
printer::print(self, options, true)
printer::print(self, options, true, 0)
}
}
39 changes: 27 additions & 12 deletions crates/swc_formatter_core/src/document/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -746,34 +746,48 @@ pub(super) fn print<'a>(
doc: Doc<'a>,
options: PrintOptions,
track_cursor: bool,
capacity: usize,
) -> Result<PrintResult, CursorError> {
if doc.root.extended_print() || track_cursor {
print_for::<true, 1>(doc, options, track_cursor)
print_for::<true, 1>(doc, options, track_cursor, capacity)
} else {
print_for::<false, 0>(doc, options, false)
print_for::<false, 0>(doc, options, false, capacity)
}
}

fn print_for<'a, const EXTENDED: bool, const INDENT_SLOTS: usize>(
doc: Doc<'a>,
options: PrintOptions,
track_cursor: bool,
capacity: usize,
) -> Result<PrintResult, CursorError> {
let mut text = String::new();
let _ = text.try_reserve_exact(capacity);
match (doc.root.has_source_groups(), doc.root.rich_indent()) {
(false, false) => {
print_impl::<false, EXTENDED, INDENT_SLOTS, SimpleIndent>(doc, options, track_cursor)
}
(true, false) => {
print_impl::<true, EXTENDED, INDENT_SLOTS, SimpleIndent>(doc, options, track_cursor)
}
(false, false) => print_impl::<false, EXTENDED, INDENT_SLOTS, SimpleIndent>(
doc,
options,
track_cursor,
text,
),
(true, false) => print_impl::<true, EXTENDED, INDENT_SLOTS, SimpleIndent>(
doc,
options,
track_cursor,
text,
),
(false, true) => print_impl::<false, EXTENDED, INDENT_SLOTS, indent::Rich<'a>>(
doc,
options,
track_cursor,
text,
),
(true, true) => print_impl::<true, EXTENDED, INDENT_SLOTS, indent::Rich<'a>>(
doc,
options,
track_cursor,
text,
),
(true, true) => {
print_impl::<true, EXTENDED, INDENT_SLOTS, indent::Rich<'a>>(doc, options, track_cursor)
}
}
}

Expand All @@ -789,6 +803,7 @@ fn print_impl<
doc: Doc<'a>,
options: PrintOptions,
track_cursor: bool,
text: String,
) -> Result<PrintResult, CursorError> {
let Doc {
root,
Expand All @@ -799,7 +814,7 @@ fn print_impl<
let elements = root.elements();
const { assert!(INDENT_SLOTS == EXTENDED as usize) };
let mut output = Output::<M, INDENT_SLOTS> {
text: String::new(),
text,
cursors: [None; 2],
view: OutputView {
column: 0,
Expand Down
62 changes: 48 additions & 14 deletions crates/swc_formatter_core/src/document/writer.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
//! Direct instruction construction with stable borrowed and generated text.

use std::borrow::Cow;
use std::{borrow::Cow, mem};

use swc_next_allocator::{Allocator, vec::ArenaVec};

use super::{
AlignText, BreakEffect, ConditionTarget, Doc, FlatFragment, FlatLineBounds, Fragment,
FragmentCapabilities, Group, GroupId, GroupRequest, IfBreak, IndentIfBreakOptions, Instruction,
LabelId, LineOptions, NeutralFragment, RecordedGroup, RichIndentKind, facts::Facts, query,
text::Text, transform,
FragmentCapabilities, FragmentSummary, Group, GroupId, GroupRequest, IfBreak,
IndentIfBreakOptions, Instruction, LabelId, LineOptions, NeutralFragment, RecordedGroup,
RichIndentKind, facts::Facts, query, text::Text, transform,
};
use crate::PrintOptions;

pub struct Writer<'a> {
allocator: &'a Allocator,
elements: ArenaVec<'a, Instruction<'a>>,
elements: Vec<Instruction<'a>>,
recording_buffer: Vec<Instruction<'a>>,
facts: Facts,
flattening: bool,
group_count: u32,
Expand Down Expand Up @@ -63,7 +64,8 @@ impl<'a> Writer<'a> {
pub fn new(allocator: &'a Allocator) -> Self {
Self {
allocator,
elements: ArenaVec::new_in(allocator),
elements: Vec::new(),
recording_buffer: Vec::new(),
facts: Facts::default(),
flattening: false,
group_count: 0,
Expand All @@ -72,6 +74,11 @@ impl<'a> Writer<'a> {
}
}

/// Makes a best-effort reservation for upcoming instructions.
pub fn reserve_instructions(&mut self, additional: usize) {
let _ = self.elements.try_reserve(additional);
}

/// Appends one string whose complete source width participates in layout.
/// Internal newlines do not reset the layout column or expand groups; LF is
/// converted to the selected output line ending. Use [`Self::literal_text`]
Expand Down Expand Up @@ -696,10 +703,15 @@ impl<'a> Writer<'a> {
write: impl FnOnce(&mut Self) -> Result<T, E>,
) -> Result<(Fragment<'a>, T), E> {
let mut child = Self::new(self.allocator);
child.elements = mem::take(&mut self.recording_buffer);
child.group_count = self.group_count;
let value = write(&mut child)?;
self.group_count = child.group_count;
Ok((child.finish_fragment(), value))
let summary = child.facts.finish(&child.elements);
let fragment = Self::seal_fragment(self.allocator, &child.elements, summary);
child.elements.clear();
self.recording_buffer = child.elements;
Ok((fragment, value))
}

/// Records content that will be printed at the current nesting level.
Expand Down Expand Up @@ -727,18 +739,26 @@ impl<'a> Writer<'a> {
let (value, prefix) = write_contents(self)?;
if let Some(prefix) = prefix {
// A nested body stays in its fragment when an outer scope also requests a prefix.
let mut body = self.elements.split_off(start);
let summary = transform::summarize_elements(&mut body);
let body = &mut self.elements[start..];
let summary = transform::summarize_elements(body);
let fragment = Self::seal_fragment(self.allocator, body, summary);
self.elements.truncate(start);
self.last_unmeasured_group_end = self.last_unmeasured_group_end.min(start);
write_prefix(self, prefix);
self.write_fragment(Fragment::new(body.into_bump_slice(), summary));
self.write_fragment(fragment);
}
Ok(value)
}

fn finish_fragment(self) -> Fragment<'a> {
let summary = self.facts.finish(&self.elements);
Fragment::new(self.elements.into_bump_slice(), summary)
fn seal_fragment(
allocator: &'a Allocator,
instructions: &[Instruction<'a>],
summary: FragmentSummary,
) -> Fragment<'a> {
// Only the sealed instructions need to live in the formatting arena.
let mut elements = ArenaVec::with_capacity_in(instructions.len(), allocator);
elements.extend_from_slice_copy(instructions);
Fragment::new(elements.into_bump_slice(), summary)
}

pub fn record_group_with_value<T, E>(
Expand Down Expand Up @@ -956,11 +976,25 @@ impl<'a> Writer<'a> {
}

pub fn finish(self) -> Doc<'a> {
drop(self.recording_buffer);
let summary = self.facts.finish(&self.elements);
Doc {
allocator: self.allocator,
group_count: self.group_count,
root: self.finish_fragment(),
root: Self::seal_fragment(self.allocator, &self.elements, summary),
label_data: &[],
}
}

/// Consumes a document while its root instructions are still in the writer's buffer.
pub fn with_doc<T>(self, consume: impl FnOnce(Doc<'_>) -> T) -> T {
drop(self.recording_buffer);
let root = Fragment::new(&self.elements, self.facts.finish(&self.elements));
consume(Doc {
allocator: self.allocator,
group_count: self.group_count,
root,
label_data: &[],
})
}
}
2 changes: 1 addition & 1 deletion crates/swc_formatter_js/src/formatter.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! JavaScript and TypeScript syntax rules meet at [`crate::ast_to_doc`] for both
//! JavaScript and TypeScript syntax rules meet at [`crate::ast_to_writer`] for both
//! source and AST input. [`expressions`] reports its emitted head to [`statements`]
//! for ASI. Call argument layouts live in `expressions/arguments/layout.rs`,
//! their separators in [`lists`], and sparse array commas in [`array_slots`].
Expand Down
9 changes: 9 additions & 0 deletions crates/swc_formatter_js/src/formatter/statements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,15 @@ impl<'ast, 'source> Formatter<'ast, 'source> {
outer_writer: &mut Writer<'ast>,
) -> Result<StatementSequence, FormatError> {
let ast = self.ast;
if !RANGE {
// Estimate the sequence's share of the program's nodes using its source span.
// Each node can add instructions for text, delimiters, and layout.
let bytes = u64::from(span.end.saturating_sub(span.start));
let nodes = (ast.node_count() as u64 * bytes)
.checked_div(ast.source().len() as u64)
.unwrap_or_default() as usize;
outer_writer.reserve_instructions(nodes.saturating_mul(4));
}
let mut range = if RANGE {
self.range
.as_mut()
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_formatter_js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! change without notice.
//!
//! [`EcmaDocumentProducer`] parses source into documents for a host session.
//! [`ast_to_doc()`] builds a document from an existing program, and
//! [`ast_to_writer()`] builds formatting instructions from an existing program, and
//! [`format_to_doc_buffer()`] returns an encoded document. Printing and source
//! formatting convenience APIs belong to `swc_next_formatter`.
//! Formatting options live in `options`. Syntax support is added incrementally;
Expand Down Expand Up @@ -33,7 +33,7 @@ pub use options::{
TrailingCommas,
};
pub use producer::{
EcmaDocumentProducer, FormatRangeError, ast_range_to_doc, ast_to_doc, format_to_doc_buffer,
EcmaDocumentProducer, FormatRangeError, ast_range_to_doc, ast_to_writer, format_to_doc_buffer,
};
pub use swc_next_formatter_host::RangeDocument;

Expand Down
38 changes: 30 additions & 8 deletions crates/swc_formatter_js/src/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@ impl EcmaDocumentProducer {
Self { parser_options }
}

/// Parses source and builds its formatting instructions.
///
/// The writer borrows the source and session storage. Use [`Writer::with_doc`]
/// to consume the document immediately or [`Writer::finish`] to retain it.
///
/// # Errors
///
/// Returns an error if parsing or document construction fails.
pub fn write<'a>(
&self,
context: FormatContext<'a, '_>,
source: &'a str,
syntax: SyntaxOptions,
) -> Result<Writer<'a>, FormatError> {
let ast = self.parse_in(context, source)?;
ast_to_writer(ast, context, syntax)
}

/// Parse a complete program with the comments and parentheses needed by the formatter.
pub fn parse<'a>(
&self,
Expand Down Expand Up @@ -86,12 +104,11 @@ impl DocumentProducer for EcmaDocumentProducer {
source: &'a str,
options: &SyntaxOptions,
) -> Result<Doc<'a>, FormatError> {
let ast = self.parse_in(context, source)?;
ast_to_doc(ast, context, *options)
self.write(context, source, *options).map(Writer::finish)
}
}

/// Build an unprinted document from an existing program AST.
/// Builds formatting instructions from an existing program AST.
///
/// The AST must have a program root, as produced by
/// [`swc_next_ecma_parser::Parser::parse`], and must retain its original source,
Expand All @@ -100,23 +117,28 @@ impl DocumentProducer for EcmaDocumentProducer {
/// parentheses can lose annotations or change which expression they apply to.
/// Use [`EcmaDocumentProducer`] to enable both parsing requirements automatically.
///
/// The document borrows the AST and context storage. It omits a leading BOM,
/// leaving printing, encoding, and BOM handling to the caller.
/// The writer borrows the AST and session storage. The instructions omit a
/// leading BOM. Use [`Writer::with_doc`] to consume the document immediately
/// or [`Writer::finish`] to retain it.
///
/// # Errors
///
/// Returns [`FormatError::Unsupported`] if document construction fails.
///
/// # Panics
///
/// Panics if the AST has no root or its root is not a program.
pub fn ast_to_doc<'a>(
pub fn ast_to_writer<'a>(
ast: &'a AstCtx<'_>,
context: FormatContext<'a, '_>,
syntax: SyntaxOptions,
) -> Result<Doc<'a>, FormatError> {
) -> Result<Writer<'a>, FormatError> {
// SAFETY: The formatter only reads handles obtained from this AST.
let ast = unsafe { ast.ast() };
let mut writer = Writer::new(context.allocator());
let options = FormatOptions::from_parts(context.print_options(), syntax);
Formatter::new(ast, options, context.allocator()).format_program(&mut writer)?;
Ok(writer.finish())
Ok(writer)
}

/// Parse source and encode an unprinted document for the SWCFMT Prettier adapter.
Expand Down
Loading
Loading