|
| 1 | +use crate::comment::CommentStyle; |
| 2 | +use std::fmt::{self, Display}; |
| 3 | +use syntax_pos::symbol::Symbol; |
| 4 | + |
| 5 | +pub(super) struct DocCommentFormatter<'a> { |
| 6 | + literal: &'a Symbol, |
| 7 | + style: CommentStyle<'a>, |
| 8 | +} |
| 9 | + |
| 10 | +impl<'a> DocCommentFormatter<'a> { |
| 11 | + pub(super) fn new(literal: &'a Symbol, style: CommentStyle<'a>) -> Self { |
| 12 | + Self { literal, style } |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +impl Display for DocCommentFormatter<'_> { |
| 17 | + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 18 | + let opener = self.style.opener().trim_end(); |
| 19 | + |
| 20 | + let literal_as_str = self.literal.as_str().get(); |
| 21 | + let line_count = literal_as_str.lines().count(); |
| 22 | + let last_line_index = line_count - 1; |
| 23 | + let lines = literal_as_str.lines().enumerate(); |
| 24 | + |
| 25 | + for (index, line) in lines { |
| 26 | + if index == last_line_index { |
| 27 | + write!(formatter, "{}{}", opener, line)?; |
| 28 | + } else { |
| 29 | + writeln!(formatter, "{}{}", opener, line)?; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + Ok(()) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +#[cfg(test)] |
| 38 | +mod tests { |
| 39 | + use super::*; |
| 40 | + use syntax_pos::{Globals, GLOBALS}; |
| 41 | + |
| 42 | + #[test] |
| 43 | + fn literal_controls_leading_spaces() { |
| 44 | + test_doc_comment_is_formatted_correctly( |
| 45 | + " Lorem ipsum", |
| 46 | + "/// Lorem ipsum", |
| 47 | + CommentStyle::TripleSlash, |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + #[test] |
| 52 | + fn single_line_doc_comment_is_formatted_correctly() { |
| 53 | + test_doc_comment_is_formatted_correctly( |
| 54 | + "Lorem ipsum", |
| 55 | + "///Lorem ipsum", |
| 56 | + CommentStyle::TripleSlash, |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | + #[test] |
| 61 | + fn multi_line_doc_comment_is_formatted_correctly() { |
| 62 | + test_doc_comment_is_formatted_correctly( |
| 63 | + "Lorem ipsum\nDolor sit amet", |
| 64 | + "///Lorem ipsum\n///Dolor sit amet", |
| 65 | + CommentStyle::TripleSlash, |
| 66 | + ); |
| 67 | + } |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn whitespace_within_lines_is_preserved() { |
| 71 | + test_doc_comment_is_formatted_correctly( |
| 72 | + " Lorem ipsum \n Dolor sit amet ", |
| 73 | + "/// Lorem ipsum \n/// Dolor sit amet ", |
| 74 | + CommentStyle::TripleSlash, |
| 75 | + ); |
| 76 | + } |
| 77 | + |
| 78 | + fn test_doc_comment_is_formatted_correctly( |
| 79 | + literal: &str, |
| 80 | + expected_comment: &str, |
| 81 | + style: CommentStyle<'_>, |
| 82 | + ) { |
| 83 | + GLOBALS.set(&Globals::new(), || { |
| 84 | + let literal = Symbol::gensym(literal); |
| 85 | + |
| 86 | + assert_eq!( |
| 87 | + expected_comment, |
| 88 | + format!("{}", DocCommentFormatter::new(&literal, style)) |
| 89 | + ); |
| 90 | + }); |
| 91 | + } |
| 92 | +} |
0 commit comments