-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathcomment.rs
More file actions
317 lines (284 loc) · 11.9 KB
/
comment.rs
File metadata and controls
317 lines (284 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use alloy_primitives::map::HashMap;
use derive_more::{Deref, DerefMut, derive::Display};
/// The natspec comment tag explaining the purpose of the comment.
/// See: <https://docs.soliditylang.org/en/v0.8.17/natspec-format.html#tags>.
#[derive(Clone, Debug, Display, PartialEq, Eq)]
pub enum CommentTag {
/// A title that should describe the contract/interface
Title,
/// The name of the author
Author,
/// Explain to an end user what this does
Notice,
/// Explain to a developer any extra details
Dev,
/// Documents a parameter just like in Doxygen (must be followed by parameter name)
Param,
/// Documents the return variables of a contract’s function
Return,
/// Copies all missing tags from the base function (must be followed by the contract name)
Inheritdoc,
/// Custom tag, semantics is application-defined
Custom(String),
}
impl CommentTag {
fn from_str(s: &str) -> Option<Self> {
let trimmed = s.trim();
let tag = match trimmed {
"title" => Self::Title,
"author" => Self::Author,
"notice" => Self::Notice,
"dev" => Self::Dev,
"param" => Self::Param,
"return" => Self::Return,
"inheritdoc" => Self::Inheritdoc,
_ if trimmed.starts_with("custom:") => {
// `@custom:param` tag will be parsed as `CommentTag::Param` due to a limitation
// on specifying parameter docs for unnamed function arguments.
let custom_tag = trimmed.trim_start_matches("custom:").trim();
match custom_tag {
"param" => Self::Param,
_ => Self::Custom(custom_tag.to_owned()),
}
}
_ => {
warn!(target: "forge::doc", tag=trimmed, "unknown comment tag. custom tags must be preceded by `custom:`");
return None;
}
};
Some(tag)
}
}
/// The natspec documentation comment.
///
/// Ref: <https://docs.soliditylang.org/en/v0.8.17/natspec-format.html>
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comment {
/// The doc comment tag.
pub tag: CommentTag,
/// The doc comment value.
pub value: String,
}
impl Comment {
/// Create new instance of [Comment].
pub const fn new(tag: CommentTag, value: String) -> Self {
Self { tag, value }
}
/// Create new instance of [Comment] from a tag string and value,
/// if it has a valid natspec tag.
pub fn from_tag_and_value(tag: &str, value: String) -> Option<Self> {
CommentTag::from_str(tag).map(|tag| Self { tag, value })
}
/// Split the comment at first word.
/// Useful for [CommentTag::Param] and [CommentTag::Return] comments.
pub fn split_first_word(&self) -> Option<(&str, &str)> {
self.value.trim_start().split_once(' ')
}
/// Match the first word of the comment with the expected.
/// Returns [None] if the word doesn't match.
/// Useful for [CommentTag::Param] and [CommentTag::Return] comments.
pub fn match_first_word(&self, expected: &str) -> Option<&str> {
self.split_first_word().and_then(|(word, rest)| (word == expected).then_some(rest))
}
/// Check if this comment is a custom tag.
pub const fn is_custom(&self) -> bool {
matches!(self.tag, CommentTag::Custom(_))
}
}
/// The collection of natspec [Comment] items.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deref, DerefMut)]
pub struct Comments(Vec<Comment>);
/// Forward the [Comments] function implementation to the [CommentsRef]
/// reference type.
macro_rules! ref_fn {
($vis:vis fn $name:ident(&self$(, )?$($arg_name:ident: $arg:ty),*) -> $ret:ty) => {
/// Forward the function implementation to [CommentsRef] reference type.
$vis fn $name(&self, $($arg_name: $arg),*) -> $ret {
CommentsRef::from(self).$name($($arg_name),*)
}
};
}
impl Comments {
ref_fn!(pub fn include_tag(&self, tag: CommentTag) -> CommentsRef<'_>);
ref_fn!(pub fn include_tags(&self, tags: &[CommentTag]) -> CommentsRef<'_>);
ref_fn!(pub fn exclude_tags(&self, tags: &[CommentTag]) -> CommentsRef<'_>);
ref_fn!(pub fn contains_tag(&self, tag: &Comment) -> bool);
ref_fn!(pub fn find_inheritdoc_base(&self) -> Option<&'_ str>);
/// Attempts to lookup inherited comments and merge them with the current collection.
///
/// Looks up comments in `inheritdocs` using the key `{base}.{ident}` where `base` is
/// extracted from an `@inheritdoc` tag. Merges the found comments by inserting
/// [CommentTag] from the inherited collection into the current one unless they are
/// already present.
pub fn merge_inheritdoc(
&self,
ident: &str,
inheritdocs: Option<HashMap<String, Self>>,
) -> Self {
let mut result = self.clone();
if let (Some(inheritdocs), Some(base)) = (inheritdocs, self.find_inheritdoc_base()) {
let key = format!("{base}.{ident}");
if let Some(other) = inheritdocs.get(&key) {
for comment in other.iter() {
if !result.contains_tag(comment) {
result.push(comment.clone());
}
}
}
}
result
}
}
impl Comments {
/// Parse natspec comments from raw doc comment lines.
///
/// Each line should be the raw text content of a `///` or `/** */` doc comment
/// with the comment delimiters already stripped (as provided by solar's `DocComment::symbol`).
///
/// Natspec tags start with `@` (e.g. `@notice`, `@dev`, `@param`).
/// Lines without a tag at the start are treated as continuations of the previous tag,
/// or as `@notice` if no previous tag exists.
pub fn from_doc_lines(lines: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
let mut comments = Vec::new();
let mut current_tag: Option<String> = None;
let mut current_value = String::new();
let flush = |tag: &Option<String>, value: &str, out: &mut Vec<Comment>| {
let value = value.trim();
if value.is_empty() && tag.is_none() {
return;
}
let tag_str = tag.as_deref().unwrap_or("notice");
// Filter out `@solidity` tags and empty tags
if tag_str.trim() == "solidity" || tag_str.trim().is_empty() {
return;
}
if let Some(c) = Comment::from_tag_and_value(tag_str, value.to_string()) {
out.push(c);
}
};
for raw_line in lines {
let raw = raw_line.as_ref();
// For block comments, process each line individually
for line in raw.lines() {
let trimmed = line.trim().trim_start_matches('*').trim();
if let Some(rest) = trimmed.strip_prefix('@') {
// Flush previous
flush(¤t_tag, ¤t_value, &mut comments);
// Parse new tag
let (tag, value) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
current_tag = Some(tag.to_string());
current_value = value.trim().to_string();
} else if !trimmed.is_empty() {
// Continuation of current tag
if current_value.is_empty() {
current_value = trimmed.to_string();
} else {
current_value.push('\n');
current_value.push_str(trimmed);
}
}
}
}
// Flush last
flush(¤t_tag, ¤t_value, &mut comments);
Self(comments)
}
}
/// The collection of references to natspec [Comment] items.
#[derive(Debug, Default, PartialEq, Eq, Deref)]
pub struct CommentsRef<'a>(Vec<&'a Comment>);
impl<'a> CommentsRef<'a> {
/// Filter a collection of comments and return only those that match a provided tag.
pub fn include_tag(&self, tag: CommentTag) -> Self {
self.include_tags(&[tag])
}
/// Filter a collection of comments and return only those that match provided tags.
pub fn include_tags(&self, tags: &[CommentTag]) -> Self {
// Cloning only references here
CommentsRef(self.iter().copied().filter(|c| tags.contains(&c.tag)).collect())
}
/// Filter a collection of comments and return only those that do not match provided tags.
pub fn exclude_tags(&self, tags: &[CommentTag]) -> Self {
// Cloning only references here
CommentsRef(self.iter().copied().filter(|c| !tags.contains(&c.tag)).collect())
}
/// Check if the collection contains a target comment.
pub fn contains_tag(&self, target: &Comment) -> bool {
self.iter().any(|c| match (&c.tag, &target.tag) {
(CommentTag::Inheritdoc, CommentTag::Inheritdoc) => c.value == target.value,
(CommentTag::Param, CommentTag::Param) | (CommentTag::Return, CommentTag::Return) => {
c.split_first_word().map(|(name, _)| name)
== target.split_first_word().map(|(name, _)| name)
}
(tag1, tag2) => tag1 == tag2,
})
}
/// Find an [CommentTag::Inheritdoc] comment and extract the base.
fn find_inheritdoc_base(&self) -> Option<&'a str> {
self.iter()
.find(|c| matches!(c.tag, CommentTag::Inheritdoc))
.and_then(|c| c.value.split_whitespace().next())
}
/// Filter a collection of comments and only return the custom tags.
pub fn get_custom_tags(&self) -> Self {
CommentsRef(self.iter().copied().filter(|c| c.is_custom()).collect())
}
}
impl<'a> From<&'a Comments> for CommentsRef<'a> {
fn from(value: &'a Comments) -> Self {
Self(value.iter().collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_comment_tag() {
assert_eq!(CommentTag::from_str("title"), Some(CommentTag::Title));
assert_eq!(CommentTag::from_str(" title "), Some(CommentTag::Title));
assert_eq!(CommentTag::from_str("author"), Some(CommentTag::Author));
assert_eq!(CommentTag::from_str("notice"), Some(CommentTag::Notice));
assert_eq!(CommentTag::from_str("dev"), Some(CommentTag::Dev));
assert_eq!(CommentTag::from_str("param"), Some(CommentTag::Param));
assert_eq!(CommentTag::from_str("return"), Some(CommentTag::Return));
assert_eq!(CommentTag::from_str("inheritdoc"), Some(CommentTag::Inheritdoc));
assert_eq!(CommentTag::from_str("custom:"), Some(CommentTag::Custom(String::new())));
assert_eq!(
CommentTag::from_str("custom:some"),
Some(CommentTag::Custom("some".to_owned()))
);
assert_eq!(
CommentTag::from_str(" custom: some "),
Some(CommentTag::Custom("some".to_owned()))
);
assert_eq!(CommentTag::from_str(""), None);
assert_eq!(CommentTag::from_str("custom"), None);
assert_eq!(CommentTag::from_str("sometag"), None);
}
#[test]
fn test_is_custom() {
// Test custom tag.
let custom_comment = Comment::new(
CommentTag::from_str("custom:test").unwrap(),
"dummy custom tag".to_owned(),
);
assert!(custom_comment.is_custom(), "Custom tag should return true for is_custom");
// Test non-custom tags.
let non_custom_tags = [
CommentTag::Title,
CommentTag::Author,
CommentTag::Notice,
CommentTag::Dev,
CommentTag::Param,
CommentTag::Return,
CommentTag::Inheritdoc,
];
for tag in non_custom_tags {
let comment = Comment::new(tag.clone(), "Non-custom comment".to_string());
assert!(
!comment.is_custom(),
"Non-custom tag {tag:?} should return false for is_custom"
);
}
}
}