aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_syntax/src/ast/tokens.rs
blob: 76a12cd6453bdb0713a2c95040d47c80a07a1374 (plain)
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
use crate::{
    SyntaxToken,
    SyntaxKind::{COMMENT, WHITESPACE},
    ast::AstToken,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Comment<'a>(SyntaxToken<'a>);

impl<'a> AstToken<'a> for Comment<'a> {
    fn cast(token: SyntaxToken<'a>) -> Option<Self> {
        if token.kind() == COMMENT {
            Some(Comment(token))
        } else {
            None
        }
    }
    fn syntax(&self) -> SyntaxToken<'a> {
        self.0
    }
}

impl<'a> Comment<'a> {
    pub fn flavor(&self) -> CommentFlavor {
        let text = self.text();
        if text.starts_with("///") {
            CommentFlavor::OuterDoc
        } else if text.starts_with("//!") {
            CommentFlavor::InnerDoc
        } else if text.starts_with("//") {
            CommentFlavor::Line
        } else {
            CommentFlavor::Multiline
        }
    }

    pub fn is_doc_comment(&self) -> bool {
        self.flavor().is_doc_comment()
    }

    pub fn prefix(&self) -> &'static str {
        self.flavor().prefix()
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum CommentFlavor {
    Line,
    OuterDoc,
    InnerDoc,
    Multiline,
}

impl CommentFlavor {
    pub fn prefix(&self) -> &'static str {
        match *self {
            CommentFlavor::Line => "//",
            CommentFlavor::OuterDoc => "///",
            CommentFlavor::InnerDoc => "//!",
            CommentFlavor::Multiline => "/*",
        }
    }

    pub fn is_doc_comment(&self) -> bool {
        match self {
            CommentFlavor::OuterDoc | CommentFlavor::InnerDoc => true,
            _ => false,
        }
    }
}

pub struct Whitespace<'a>(SyntaxToken<'a>);

impl<'a> AstToken<'a> for Whitespace<'a> {
    fn cast(token: SyntaxToken<'a>) -> Option<Self> {
        if token.kind() == WHITESPACE {
            Some(Whitespace(token))
        } else {
            None
        }
    }
    fn syntax(&self) -> SyntaxToken<'a> {
        self.0
    }
}

impl<'a> Whitespace<'a> {
    pub fn spans_multiple_lines(&self) -> bool {
        let text = self.text();
        text.find('\n').map_or(false, |idx| text[idx + 1..].contains('\n'))
    }
}