summaryrefslogtreecommitdiff
path: root/support/texlab/src/definition/bibtex_string.rs
blob: a1fe5132c0ce265890f8a4234cef843909a9dbc1 (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
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
use crate::{
    feature::{FeatureProvider, FeatureRequest},
    protocol::{LocationLink, Position, TextDocumentPositionParams, Uri},
    syntax::{bibtex, SyntaxNode},
    workspace::DocumentContent,
};
use async_trait::async_trait;

#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub struct BibtexStringDefinitionProvider;

#[async_trait]
impl FeatureProvider for BibtexStringDefinitionProvider {
    type Params = TextDocumentPositionParams;
    type Output = Vec<LocationLink>;

    async fn execute<'a>(&'a self, req: &'a FeatureRequest<Self::Params>) -> Self::Output {
        if let DocumentContent::Bibtex(tree) = &req.current().content {
            if let Some(reference) = Self::find_reference(tree, req.params.position) {
                return Self::find_definitions(&req.current().uri, tree, reference);
            }
        }
        Vec::new()
    }
}

impl BibtexStringDefinitionProvider {
    fn find_reference(tree: &bibtex::Tree, pos: Position) -> Option<&bibtex::Token> {
        let mut nodes = tree.find(pos);
        nodes.reverse();
        match (
            &tree.graph[nodes[0]],
            nodes.get(1).map(|node| &tree.graph[*node]),
        ) {
            (bibtex::Node::Word(word), Some(bibtex::Node::Field(_)))
            | (bibtex::Node::Word(word), Some(bibtex::Node::Concat(_))) => Some(&word.token),
            _ => None,
        }
    }

    fn find_definitions(
        uri: &Uri,
        tree: &bibtex::Tree,
        reference: &bibtex::Token,
    ) -> Vec<LocationLink> {
        let mut links = Vec::new();
        for node in tree.children(tree.root) {
            if let Some(string) = tree.as_string(node) {
                if let Some(name) = &string.name {
                    if name.text() == reference.text() {
                        links.push(LocationLink {
                            origin_selection_range: Some(reference.range()),
                            target_uri: uri.clone().into(),
                            target_range: string.range(),
                            target_selection_range: name.range(),
                        });
                    }
                }
            }
        }
        links
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        feature::FeatureTester,
        protocol::{Range, RangeExt},
    };
    use indoc::indoc;

    #[tokio::test]
    async fn empty_latex_document() {
        let actual_links = FeatureTester::new()
            .file("main.tex", "")
            .main("main.tex")
            .position(0, 0)
            .test_position(BibtexStringDefinitionProvider)
            .await;

        assert!(actual_links.is_empty());
    }

    #[tokio::test]
    async fn empty_bibtex_document() {
        let actual_links = FeatureTester::new()
            .file("main.bib", "")
            .main("main.bib")
            .position(0, 0)
            .test_position(BibtexStringDefinitionProvider)
            .await;

        assert!(actual_links.is_empty());
    }

    #[tokio::test]
    async fn simple() {
        let actual_links = FeatureTester::new()
            .file(
                "main.bib",
                indoc!(
                    r#"
                        @string{foo = {bar}}
                        @article{bar, author = foo}
                    "#
                ),
            )
            .main("main.bib")
            .position(1, 24)
            .test_position(BibtexStringDefinitionProvider)
            .await;

        let expected_links = vec![LocationLink {
            origin_selection_range: Some(Range::new_simple(1, 23, 1, 26)),
            target_uri: FeatureTester::uri("main.bib").into(),
            target_range: Range::new_simple(0, 0, 0, 20),
            target_selection_range: Range::new_simple(0, 8, 0, 11),
        }];

        assert_eq!(actual_links, expected_links);
    }

    #[tokio::test]
    async fn concat() {
        let actual_links = FeatureTester::new()
            .file(
                "main.bib",
                indoc!(
                    r#"
                        @string{foo = {bar}}
                        @article{bar, author = foo # "bar"}
                    "#
                ),
            )
            .main("main.bib")
            .position(1, 24)
            .test_position(BibtexStringDefinitionProvider)
            .await;

        let expected_links = vec![LocationLink {
            origin_selection_range: Some(Range::new_simple(1, 23, 1, 26)),
            target_uri: FeatureTester::uri("main.bib").into(),
            target_range: Range::new_simple(0, 0, 0, 20),
            target_selection_range: Range::new_simple(0, 8, 0, 11),
        }];

        assert_eq!(actual_links, expected_links);
    }

    #[tokio::test]
    async fn field() {
        let actual_links = FeatureTester::new()
            .file(
                "main.bib",
                indoc!(
                    r#"
                        @string{foo = {bar}}
                        @article{bar, author = foo}
                    "#
                ),
            )
            .main("main.bib")
            .position(1, 18)
            .test_position(BibtexStringDefinitionProvider)
            .await;

        assert!(actual_links.is_empty());
    }
}