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
//! Trivias such as comments and irregular whitespaces

use std::{
    collections::btree_map::{BTreeMap, Range},
    ops::RangeBounds,
};

use oxc_span::Span;

/// Single or multiline comment
#[derive(Debug, Clone, Copy)]
pub struct Comment {
    pub kind: CommentKind,
    pub end: u32,
}

impl Comment {
    pub fn new(end: u32, kind: CommentKind) -> Self {
        Self { kind, end }
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum CommentKind {
    SingleLine,
    MultiLine,
}

impl CommentKind {
    pub fn is_single_line(self) -> bool {
        matches!(self, Self::SingleLine)
    }

    pub fn is_multi_line(self) -> bool {
        matches!(self, Self::MultiLine)
    }
}

pub type TriviasMap = BTreeMap<u32, Comment>;

#[derive(Debug, Default)]
pub struct Trivias {
    /// Keyed by span.start
    comments: TriviasMap,

    irregular_whitespaces: Vec<Span>,
}

impl Trivias {
    pub fn new(comments: TriviasMap, irregular_whitespaces: Vec<Span>) -> Self {
        Self { comments, irregular_whitespaces }
    }

    pub fn comments(&self) -> impl Iterator<Item = (CommentKind, Span)> + '_ {
        self.comments.iter().map(|(start, comment)| (comment.kind, Span::new(*start, comment.end)))
    }

    pub fn comments_range<R>(&self, range: R) -> Range<'_, u32, Comment>
    where
        R: RangeBounds<u32>,
    {
        self.comments.range(range)
    }

    pub fn has_comments_between(&self, span: Span) -> bool {
        self.comments.range(span.start..span.end).count() > 0
    }

    pub fn irregular_whitespaces(&self) -> &Vec<Span> {
        &self.irregular_whitespaces
    }
}