Skip to content

Commit 6638cd3

Browse files
committed
clarify first_comment_between
1 parent 8a4f700 commit 6638cd3

1 file changed

Lines changed: 16 additions & 5 deletions

File tree

compiler-core/src/parse/extra.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ impl ModuleExtra {
4343
/// Returns the first comment overlapping the given source locations (inclusive)
4444
/// Note that the returned span covers the text of the comment, not the `//`
4545
pub fn first_comment_between(&self, start: u32, end: u32) -> Option<SrcSpan> {
46-
let inner = |comments: &[SrcSpan], start, end| {
46+
// Helper function to find a comment that is between the given start
47+
// and end. Not guaranteed to find the first comment.
48+
let find_comment_between = |comments: &[SrcSpan], start, end| -> Option<usize> {
4749
if comments.is_empty() {
4850
return None;
4951
}
@@ -61,13 +63,22 @@ impl ModuleExtra {
6163
.ok()
6264
};
6365

64-
let mut best = None;
66+
// To find the first comment in the given span, we first see if we can
67+
// find any comment at all in the span by binary-searching over the list
68+
// of comments in the module. If we do, we need to see if any other
69+
// comment appears earlier, so we do the same search using the sub-list
70+
// of comments before the one we found.
71+
//
72+
// We repeat this, narrowing our search list each time, until we can't
73+
// find any comment earlier than our best.
74+
let mut first_index_so_far = None;
6575
let mut search_list = &self.comments[..];
66-
while let Some(index) = inner(search_list, start, end) {
67-
best = self.comments.get(index);
76+
while let Some(index) = find_comment_between(search_list, start, end) {
77+
first_index_so_far = Some(index);
6878
search_list = search_list.get(0..index).unwrap_or(&[]);
6979
}
70-
best.copied()
80+
81+
first_index_so_far.map(|index| self.comments[index])
7182
}
7283
}
7384

0 commit comments

Comments
 (0)