From 18f19ee16430b38b70013ab75806138bfdcbf831 Mon Sep 17 00:00:00 2001 From: Boshen Date: Sun, 19 Nov 2023 23:08:23 +0800 Subject: [PATCH] refactor(prettier): improve comment handling API (#1435) --- crates/oxc_prettier/src/comment.rs | 8 ++++++-- crates/oxc_prettier/src/lib.rs | 15 +++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/crates/oxc_prettier/src/comment.rs b/crates/oxc_prettier/src/comment.rs index 9b1f94a9f..6977d3e28 100644 --- a/crates/oxc_prettier/src/comment.rs +++ b/crates/oxc_prettier/src/comment.rs @@ -68,8 +68,12 @@ impl<'a> Prettier<'a> { parts.push(hardline!()); } - let end = self.get_comment_end(kind, end); - if self.skip_newline(self.skip_spaces(end)).is_some_and(|i| self.has_newline(i)) { + if self + .get_comment_end(kind, end) + .map(|end| self.skip_spaces(end)) + .and_then(|idx| self.skip_newline(idx)) + .is_some_and(|i| self.has_newline(i)) + { parts.push(hardline!()); } } else { diff --git a/crates/oxc_prettier/src/lib.rs b/crates/oxc_prettier/src/lib.rs index 81ade9e08..6fcd9e98a 100644 --- a/crates/oxc_prettier/src/lib.rs +++ b/crates/oxc_prettier/src/lib.rs @@ -110,27 +110,26 @@ impl<'a> Prettier<'a> { } #[allow(clippy::cast_possible_truncation)] - fn skip_newline(&self, start_index: Option) -> Option { - let start_index = start_index?; + fn skip_newline(&self, start_index: u32) -> Option { let c = self.source_text[start_index as usize..].chars().next()?; is_line_terminator(c).then(|| start_index + c.len_utf8() as u32) } - fn skip_spaces(&self, start_index: Option) -> Option { - let mut start_index = start_index?; + fn skip_spaces(&self, start_index: u32) -> u32 { + let mut index = start_index; for c in self.source_text[start_index as usize..].chars() { if matches!(c, ' ' | '\t') { - start_index += 1; + index += 1; } else { break; } } - Some(start_index) + index } fn has_newline(&self, start_index: u32) -> bool { - let idx = self.skip_spaces(Some(start_index)); + let idx = self.skip_spaces(start_index); let idx2 = self.skip_newline(idx); - idx != idx2 + Some(idx) != idx2 } }