foundry_common/comments/
comment.rs1use 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 Isolated,
13 Trailing,
15 Mixed,
17 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 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}