diff --git a/crates/rune/src/fmt/indent_writer.rs b/crates/rune/src/fmt/indent_writer.rs index f67b85f3b..9a9516e62 100644 --- a/crates/rune/src/fmt/indent_writer.rs +++ b/crates/rune/src/fmt/indent_writer.rs @@ -9,7 +9,7 @@ use core::str; use crate::alloc::fmt::TryWrite; use crate::alloc::prelude::*; use crate::alloc::{self, try_vec, Vec}; -use crate::ast::Span; +use crate::ast::{ByteIndex, Span}; use super::comments::Comment; use super::error::FormattingError; @@ -195,18 +195,12 @@ impl<'a> SpanInjectionWriter<'a> { self.write_spanned(Span::new(0, 0), text, false, false) } - pub(super) fn write_spanned( - &mut self, - span: Span, - text: &str, - newline: bool, - space: bool, - ) -> Result<(), FormattingError> { + pub(super) fn write_queued_spans(&mut self, until: ByteIndex) -> Result<(), FormattingError> { // The queued recovered spans are ordered so we can pop them from the front if they're before the current span. // If the current span is before the first queued span, we need to inject the queued span. while let Some(queued_span) = self.queued_spans.first() { - if queued_span.span().start > span.start { + if queued_span.span().start > until { break; } @@ -226,6 +220,18 @@ impl<'a> SpanInjectionWriter<'a> { } } + Ok(()) + } + + pub(super) fn write_spanned( + &mut self, + span: Span, + text: &str, + newline: bool, + space: bool, + ) -> Result<(), FormattingError> { + self.write_queued_spans(span.start)?; + write!(self.writer, "{}", text)?; if space { diff --git a/crates/rune/src/fmt/printer.rs b/crates/rune/src/fmt/printer.rs index 822f14c72..fae59dae9 100644 --- a/crates/rune/src/fmt/printer.rs +++ b/crates/rune/src/fmt/printer.rs @@ -1787,6 +1787,7 @@ impl<'a> Printer<'a> { self.visit_statement(statement)?; } + self.writer.write_queued_spans(close.span.start)?; self.writer.dedent(); self.writer.write_spanned_raw(close.span, false, false)?; diff --git a/crates/rune/src/tests/format_source.rs b/crates/rune/src/tests/format_source.rs index b65faa22b..9c8e45770 100644 --- a/crates/rune/src/tests/format_source.rs +++ b/crates/rune/src/tests/format_source.rs @@ -18,20 +18,58 @@ fn bug_684() -> Result<()> { /* test */ -}"#; +} +"#; + + assert_format_source(source, None) +} + +#[test] +fn fmt_block_comment() -> Result<()> { + let source = r#"//test1 +/*test2*/"#; + let expected = format!("{source}\n"); + + assert_format_source(source, Some(&expected)) +} + +#[test] +fn fmt_block_comment_indent() -> Result<()> { + let source = r#"struct Test { + a, /* test1 + test2 +test 3*/ +} +"#; assert_format_source(source, None) } /// https://github.com/rune-rs/rune/issues/693 #[test] -#[ignore] fn bug_693() -> Result<()> { let source = r#"pub fn main() { if true { // test } -}"#; +} +"#; + + assert_format_source(source, None) +} + +#[test] +fn fmt_comment_line() -> Result<()> { + let source = r#"pub fn main() { + // test 1 + if true { + // test 2.1 + let a = 1; + // test 2.2 + } + // test 3 +} +"#; assert_format_source(source, None) }