feat(prettier): add comments before expressions (#1375)

This commit is contained in:
Boshen 2023-11-17 19:38:25 +08:00 committed by GitHub
parent a8e4c3333c
commit 2d3b5eb299
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 14 additions and 10 deletions

View file

@ -35,12 +35,16 @@ impl<'a> Prettier<'a> {
false
}
#[must_use]
pub(crate) fn print_leading_comments(&mut self, range: Span) -> Option<Doc<'a>> {
let mut parts = vec![];
let mut parts = self.vec();
while let Some((start, end, kind)) = self.trivias.peek().copied() {
// Comment before the span
if end <= range.start {
parts.push(self.print_comment(start, end, kind));
if kind.is_multi_line() {
parts.push(hardline!());
}
self.trivias.next();
} else {
break;
@ -49,11 +53,10 @@ impl<'a> Prettier<'a> {
if parts.is_empty() {
return None;
}
let mut comments = self.join(Separator::Hardline, parts);
comments.push(hardline!());
Some(Doc::Array(comments))
Some(Doc::Array(parts))
}
#[must_use]
pub(crate) fn print_dangling_comments(&mut self, range: Span) -> Option<Doc<'a>> {
let mut parts = vec![];
while let Some((start, end, kind)) = self.trivias.peek().copied() {
@ -68,6 +71,7 @@ impl<'a> Prettier<'a> {
(!parts.is_empty()).then(|| Doc::Array(self.join(Separator::Hardline, parts)))
}
#[must_use]
fn print_comment(&self, start: u32, end: u32, kind: CommentKind) -> Doc<'a> {
let end_offset = if kind.is_multi_line() { 2 } else { 0 };
let comment = Span::new(start - 2, end + end_offset).source_text(self.source_text);

View file

@ -91,6 +91,9 @@ impl<'a> Format<'a> for Statement<'a> {
impl<'a> Format<'a> for ExpressionStatement<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
let mut parts = p.vec();
if let Some(doc) = p.print_leading_comments(self.span) {
parts.push(doc);
}
parts.push(self.expression.format(p));
if p.options.semi {
parts.push(ss!(";"));

View file

@ -10,10 +10,7 @@ mod options;
mod printer;
mod util;
use std::{
iter::{Peekable, Rev},
vec,
};
use std::{iter::Peekable, vec};
use doc::Doc;
use oxc_allocator::Allocator;
@ -31,7 +28,7 @@ pub struct Prettier<'a> {
options: PrettierOptions,
/// A stack of comments that will be carefully placed in the right places.
trivias: Peekable<Rev<vec::IntoIter<(u32, u32, CommentKind)>>>,
trivias: Peekable<vec::IntoIter<(u32, u32, CommentKind)>>,
}
impl<'a> Prettier<'a> {
@ -41,7 +38,7 @@ impl<'a> Prettier<'a> {
trivias: Trivias,
options: PrettierOptions,
) -> Self {
let trivias = trivias.into_iter().rev().peekable();
let trivias = trivias.into_iter().peekable();
Self { allocator, source_text, options, trivias }
}