Skip to main content

foundry_common/comments/
comment.rs

1//! Modified from [`rustc_ast::util::comments`](https://github.com/rust-lang/rust/blob/07d3fd1d9b9c1f07475b96a9d168564bf528db68/compiler/rustc_ast/src/util/comments.rs).
2
3use super::inline_config::{InlineConfigItem, InvalidInlineConfigItem};
4use solar::parse::{
5    ast::{CommentKind, Span},
6    interface::BytePos,
7};
8
9#[derive(Clone, Copy, PartialEq, Eq, Debug)]
10pub enum CommentStyle {
11    /// No code on either side of each line of the comment
12    Isolated,
13    /// Code exists to the left of the comment
14    Trailing,
15    /// Code before /* foo */ and after the comment
16    Mixed,
17    /// Just a manual blank line "\n\n", for layout
18    BlankLine,
19}
20
21impl CommentStyle {
22    pub const fn is_mixed(&self) -> bool {
23        matches!(self, Self::Mixed)
24    }
25    pub const fn is_trailing(&self) -> bool {
26        matches!(self, Self::Trailing)
27    }
28    pub const fn is_isolated(&self) -> bool {
29        matches!(self, Self::Isolated)
30    }
31    pub const fn is_blank(&self) -> bool {
32        matches!(self, Self::BlankLine)
33    }
34}
35
36#[derive(Clone, Debug)]
37pub struct Comment {
38    pub lines: Vec<String>,
39    pub span: Span,
40    pub style: CommentStyle,
41    pub is_doc: bool,
42    pub kind: CommentKind,
43}
44
45impl Comment {
46    pub fn pos(&self) -> BytePos {
47        self.span.lo()
48    }
49
50    pub const fn prefix(&self) -> Option<&'static str> {
51        if self.lines.is_empty() {
52            return None;
53        }
54        Some(match (self.kind, self.is_doc) {
55            (CommentKind::Line, false) => "//",
56            (CommentKind::Line, true) => "///",
57            (CommentKind::Block, false) => "/*",
58            (CommentKind::Block, true) => "/**",
59        })
60    }
61
62    pub const fn suffix(&self) -> Option<&'static str> {
63        if self.lines.is_empty() {
64            return None;
65        }
66        match self.kind {
67            CommentKind::Line => None,
68            CommentKind::Block => Some("*/"),
69        }
70    }
71
72    /// Parses formatter directives on the first and last lines of the comment.
73    pub fn format_directives(
74        &self,
75    ) -> impl Iterator<Item = Result<InlineConfigItem<()>, InvalidInlineConfigItem>> + '_ {
76        let mut lines = self.lines.iter().flat_map(|line| line.lines());
77        let first = lines.next();
78        let last = lines.last();
79        [first, last].into_iter().flatten().filter_map(|line| self.parse_format_directive(line))
80    }
81
82    fn parse_format_directive(
83        &self,
84        mut text: &str,
85    ) -> Option<Result<InlineConfigItem<()>, InvalidInlineConfigItem>> {
86        if let Some(prefix) = self.prefix() {
87            text = text.strip_prefix(prefix).unwrap_or(text);
88        }
89        if let Some(suffix) = self.suffix() {
90            text = text.strip_suffix(suffix).unwrap_or(text);
91        }
92        Some(text.trim_start().strip_prefix("forgefmt:")?.trim().parse())
93    }
94}