From 4c5eb9b796eaf024287e70d930b43a0830562a83 Mon Sep 17 00:00:00 2001 From: Richard Feldman Date: Wed, 6 Jul 2022 15:08:36 -0400 Subject: [PATCH] Ensure comments begin with space or newline --- crates/compiler/fmt/src/lib.rs | 12 ++++++++++++ crates/compiler/fmt/src/spaces.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/compiler/fmt/src/lib.rs b/crates/compiler/fmt/src/lib.rs index 3e66f142ba..a66a28d97a 100644 --- a/crates/compiler/fmt/src/lib.rs +++ b/crates/compiler/fmt/src/lib.rs @@ -120,6 +120,18 @@ impl<'a> Buf<'a> { pub fn fmt_end_of_file(&mut self) { fmt_text_eof(&mut self.text) } + + pub fn ends_with_space(&self) -> bool { + self.spaces_to_flush > 0 || self.text.ends_with(' ') + } + + pub fn ends_with_newline(&self) -> bool { + self.spaces_to_flush == 0 && self.text.ends_with('\n') + } + + fn is_empty(&self) -> bool { + self.spaces_to_flush == 0 && self.text.is_empty() + } } /// Ensures the text ends in a newline with no whitespace preceding it. diff --git a/crates/compiler/fmt/src/spaces.rs b/crates/compiler/fmt/src/spaces.rs index f3b7e72dc0..fb915ea852 100644 --- a/crates/compiler/fmt/src/spaces.rs +++ b/crates/compiler/fmt/src/spaces.rs @@ -125,6 +125,12 @@ pub fn fmt_comments_only<'a, 'buf, I>( } fn fmt_comment<'buf>(buf: &mut Buf<'buf>, comment: &str) { + // The '#' in a comment should always be preceded by a newline or a space, + // unless it's the very beginning of the buffer. + if !buf.is_empty() && !buf.ends_with_space() && !buf.ends_with_newline() { + buf.spaces(1); + } + buf.push('#'); if !comment.starts_with(' ') { buf.spaces(1); @@ -158,6 +164,12 @@ where } fn fmt_docs<'buf>(buf: &mut Buf<'buf>, docs: &str) { + // The "##" in a doc comment should always be preceded by a newline or a space, + // unless it's the very beginning of the buffer. + if !buf.is_empty() && !buf.ends_with_space() && !buf.ends_with_newline() { + buf.spaces(1); + } + buf.push_str("##"); if !docs.is_empty() { buf.spaces(1);