summaryrefslogtreecommitdiff
path: root/support/texlab/src/symbol/project_order.rs
blob: 8a2ec5f6d02255f1f94d28e7af5b45d7d7c99d55 (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
172
173
174
175
176
177
178
179
180
181
use crate::{
    protocol::{Options, Uri},
    workspace::{Document, DocumentContent, Snapshot},
};
use petgraph::{algo::tarjan_scc, Directed, Graph};
use std::{collections::HashSet, path::Path, sync::Arc, usize};

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ProjectOrdering {
    ordering: Vec<Arc<Document>>,
}

impl ProjectOrdering {
    pub fn get(&self, uri: &Uri) -> usize {
        self.ordering
            .iter()
            .position(|doc| doc.uri == *uri)
            .unwrap_or(usize::MAX)
    }

    pub fn analyze(snapshot: &Snapshot, options: &Options, current_dir: &Path) -> Self {
        let mut ordering = Vec::new();
        let comps = Self::connected_components(snapshot, options, current_dir);
        for comp in comps {
            let graph = Self::build_dependency_graph(&comp);

            let mut visited = HashSet::new();
            let root_index = *graph.node_weight(tarjan_scc(&graph)[0][0]).unwrap();
            let mut stack = vec![Arc::clone(&comp[root_index])];

            while let Some(doc) = stack.pop() {
                if !visited.insert(doc.uri.as_str().to_owned()) {
                    continue;
                }

                ordering.push(Arc::clone(&doc));
                if let DocumentContent::Latex(tree) = &doc.content {
                    for include in tree.includes.iter().rev() {
                        for targets in &include.all_targets {
                            for target in targets {
                                if let Some(child) = snapshot.find(target) {
                                    stack.push(child);
                                }
                            }
                        }
                    }
                }
            }
        }

        Self { ordering }
    }

    fn connected_components(
        snapshot: &Snapshot,
        options: &Options,
        current_dir: &Path,
    ) -> Vec<Vec<Arc<Document>>> {
        let mut comps = Vec::new();
        let mut visited = HashSet::new();
        for root in &snapshot.0 {
            if !visited.insert(root.uri.clone()) {
                continue;
            }

            let comp = snapshot.relations(&root.uri, options, current_dir);
            for document in &comp {
                visited.insert(document.uri.clone());
            }
            comps.push(comp);
        }
        comps
    }

    fn build_dependency_graph(docs: &[Arc<Document>]) -> Graph<usize, (), Directed> {
        let mut graph = Graph::new();
        let nodes: Vec<_> = (0..docs.len()).map(|i| graph.add_node(i)).collect();

        for (i, doc) in docs.iter().enumerate() {
            if let DocumentContent::Latex(tree) = &doc.content {
                for targets in tree
                    .includes
                    .iter()
                    .flat_map(|include| &include.all_targets)
                {
                    for target in targets {
                        if let Some(j) = docs.iter().position(|doc| doc.uri == *target) {
                            graph.add_edge(nodes[j], nodes[i], ());
                            break;
                        }
                    }
                }
            }
        }
        graph
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        tex::{Language, Resolver},
        workspace::DocumentParams,
    };
    use std::env;

    fn create_simple_document(uri: &Uri, language: Language, text: &str) -> Arc<Document> {
        Arc::new(Document::open(DocumentParams {
            uri: uri.clone(),
            text: text.into(),
            language,
            resolver: &Resolver::default(),
            options: &Options::default(),
            current_dir: &env::current_dir().unwrap(),
        }))
    }

    #[test]
    fn no_cycles() {
        let a = Uri::parse("http://example.com/a.tex").unwrap();
        let b = Uri::parse("http://example.com/b.tex").unwrap();
        let c = Uri::parse("http://example.com/c.tex").unwrap();
        let mut snapshot = Snapshot::new();
        snapshot.0 = vec![
            create_simple_document(&a, Language::Latex, ""),
            create_simple_document(&b, Language::Latex, ""),
            create_simple_document(&c, Language::Latex, r#"\include{b}\include{a}"#),
        ];

        let current_dir = env::current_dir().unwrap();
        let ordering = ProjectOrdering::analyze(&snapshot, &Options::default(), &current_dir);

        assert_eq!(ordering.get(&a), 2);
        assert_eq!(ordering.get(&b), 1);
        assert_eq!(ordering.get(&c), 0);
    }

    #[test]
    fn cycles() {
        let a = Uri::parse("http://example.com/a.tex").unwrap();
        let b = Uri::parse("http://example.com/b.tex").unwrap();
        let c = Uri::parse("http://example.com/c.tex").unwrap();
        let mut snapshot = Snapshot::new();
        snapshot.0 = vec![
            create_simple_document(&a, Language::Latex, r#"\include{b}"#),
            create_simple_document(&b, Language::Latex, r#"\include{a}"#),
            create_simple_document(&c, Language::Latex, r#"\include{a}"#),
        ];

        let current_dir = env::current_dir().unwrap();
        let ordering = ProjectOrdering::analyze(&snapshot, &Options::default(), &current_dir);

        assert_eq!(ordering.get(&a), 1);
        assert_eq!(ordering.get(&b), 2);
        assert_eq!(ordering.get(&c), 0);
    }

    #[test]
    fn multiple_roots() {
        let a = Uri::parse("http://example.com/a.tex").unwrap();
        let b = Uri::parse("http://example.com/b.tex").unwrap();
        let c = Uri::parse("http://example.com/c.tex").unwrap();
        let d = Uri::parse("http://example.com/d.tex").unwrap();
        let mut snapshot = Snapshot::new();
        snapshot.0 = vec![
            create_simple_document(&a, Language::Latex, r#"\include{b}"#),
            create_simple_document(&b, Language::Latex, ""),
            create_simple_document(&c, Language::Latex, ""),
            create_simple_document(&d, Language::Latex, r#"\include{c}"#),
        ];

        let current_dir = env::current_dir().unwrap();
        let ordering = ProjectOrdering::analyze(&snapshot, &Options::default(), &current_dir);

        assert_eq!(ordering.get(&a), 0);
        assert_eq!(ordering.get(&b), 1);
        assert_eq!(ordering.get(&d), 2);
        assert_eq!(ordering.get(&c), 3);
    }
}