emmylua_parser/syntax/node/doc/
description.rs

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
use crate::{LuaAstNode, LuaDocDetailToken, LuaSyntaxKind, LuaSyntaxNode, LuaTokenKind};

#[allow(unused)]
pub trait LuaDocDescriptionOwner: LuaAstNode {
    fn get_description(&self) -> Option<LuaDocDescription> {
        self.child()
    }
}

#[allow(unused)]
pub trait LuaDocDetailOwner: LuaAstNode {
    fn get_detail(&self) -> Option<LuaDocDetailToken> {
        self.token()
    }

    fn get_detail_text(&self) -> Option<String> {
        self.get_detail().map(|it| it.get_detail().to_string())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LuaDocDescription {
    syntax: LuaSyntaxNode,
}

impl LuaAstNode for LuaDocDescription {
    fn syntax(&self) -> &LuaSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: LuaSyntaxKind) -> bool
    where
        Self: Sized,
    {
        kind == LuaSyntaxKind::DocDescription
    }

    fn cast(syntax: LuaSyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        if syntax.kind() == LuaSyntaxKind::DocDescription.into() {
            Some(Self { syntax })
        } else {
            None
        }
    }
}

impl LuaDocDetailOwner for LuaDocDescription {}

impl LuaDocDescription {
    pub fn get_description_text(&self) -> String {
        let mut text = String::new();
        for token in self
            .syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
        {
            match token.kind().into() {
                LuaTokenKind::TkDocDetail => {
                    text.push_str(token.text());
                }
                LuaTokenKind::TkEndOfLine => {
                    text.push('\n');
                }
                LuaTokenKind::TkNormalStart | LuaTokenKind::TkDocContinue => {
                    let mut white_space_count = 0;
                    let mut start_text_chars = token.text().chars();
                    while let Some(c) = start_text_chars.next() {
                        if c == ' ' {
                            white_space_count += 1;
                        } else if c == '\t' {
                            white_space_count += 4;
                        }
                    }

                    if white_space_count > 0 {
                        let white_space = " ".repeat(white_space_count);
                        text.push_str(&white_space);
                    }
                }
                _ => {}
            }
        }

        text
    }
}