summaryrefslogtreecommitdiff
path: root/support/texlab/crates/base-db/src/graph.rs
blob: b16245e011c0017e9730e0bb4a945a9da3b05a8a (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
use std::{ffi::OsStr, path::PathBuf};

use distro::Language;
use itertools::Itertools;
use once_cell::sync::Lazy;
use percent_encoding::percent_decode_str;
use rustc_hash::FxHashSet;
use url::Url;

use crate::{semantics, Document, DocumentData, Workspace};

pub static HOME_DIR: Lazy<Option<PathBuf>> = Lazy::new(dirs::home_dir);

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct Edge<'a> {
    pub source: &'a Document,
    pub target: &'a Document,
    pub weight: Option<EdgeWeight<'a>>,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct EdgeWeight<'a> {
    pub link: &'a semantics::tex::Link,
    pub old_base_dir: Url,
    pub new_base_dir: Url,
}

#[derive(Debug)]
pub struct Graph<'a> {
    pub workspace: &'a Workspace,
    pub start: &'a Document,
    pub edges: Vec<Edge<'a>>,
    pub missing: Vec<Url>,
}

impl<'a> Graph<'a> {
    pub fn new(workspace: &'a Workspace, start: &'a Document) -> Self {
        let mut graph = Self {
            workspace,
            start,
            edges: Vec::new(),
            missing: Vec::new(),
        };

        let base_dir = workspace.current_dir(&start.dir);
        let mut stack = vec![(start, base_dir)];
        let mut visited = FxHashSet::default();

        while let Some((source, base_dir)) = stack.pop() {
            let index = graph.edges.len();
            graph.explicit_edges(source, &base_dir);
            for edge in &graph.edges[index..] {
                let Some(weight) = edge.weight.as_ref() else { continue };
                if visited.insert(&edge.target.uri) {
                    stack.push((edge.target, weight.new_base_dir.clone()));
                }
            }

            graph.implicit_edges(source, &base_dir);
        }

        graph
    }

    pub fn preorder(&self) -> impl DoubleEndedIterator<Item = &'a Document> + '_ {
        std::iter::once(self.start)
            .chain(self.edges.iter().map(|group| group.target))
            .unique_by(|document| &document.uri)
    }

    fn explicit_edges(&mut self, source: &'a Document, base_dir: &Url) {
        let DocumentData::Tex(data) = &source.data else { return };
        for link in &data.semantics.links {
            self.explicit_edge(source, base_dir, link);
        }
    }

    fn explicit_edge(
        &mut self,
        source: &'a Document,
        base_dir: &Url,
        link: &'a semantics::tex::Link,
    ) {
        let home_dir = HOME_DIR.as_deref();

        let stem = &link.path.text;
        let mut file_names = vec![stem.clone()];
        link.kind
            .extensions()
            .iter()
            .map(|ext| format!("{stem}.{ext}"))
            .for_each(|name| file_names.push(name));

        let file_name_db = &self.workspace.distro().file_name_db;
        let distro_files = file_names
            .iter()
            .filter_map(|name| file_name_db.get(name))
            .filter(|path| home_dir.map_or(false, |dir| path.starts_with(dir)))
            .flat_map(Url::from_file_path);

        for target_uri in file_names
            .iter()
            .flat_map(|file_name| base_dir.join(file_name))
            .chain(distro_files)
        {
            match self.workspace.lookup(&target_uri) {
                Some(target) => {
                    let new_base_dir = link
                        .base_dir
                        .as_deref()
                        .and_then(|path| base_dir.join(&path).ok())
                        .unwrap_or_else(|| base_dir.clone());

                    let weight = Some(EdgeWeight {
                        link,
                        old_base_dir: base_dir.clone(),
                        new_base_dir,
                    });

                    self.edges.push(Edge {
                        source,
                        target,
                        weight,
                    });
                }
                None => {
                    self.missing.push(target_uri);
                }
            };
        }
    }

    fn implicit_edges(&mut self, source: &'a Document, base_dir: &Url) {
        let uri = source.uri.as_str();
        if source.language == Language::Tex && !uri.ends_with(".aux") {
            self.implicit_edge(source, base_dir, "log");
            self.implicit_edge(source, base_dir, "aux");
        }
    }

    fn implicit_edge(&mut self, source: &'a Document, base_dir: &Url, extension: &str) {
        let mut path = PathBuf::from(
            percent_decode_str(source.uri.path())
                .decode_utf8_lossy()
                .as_ref(),
        );

        path.set_extension(extension);
        let Some(target_uri) = path.file_name()
            .and_then(OsStr::to_str)
            .and_then(|name| self.workspace.output_dir(base_dir).join(&name).ok()) else { return };

        match self.workspace.lookup(&target_uri) {
            Some(target) => {
                self.edges.push(Edge {
                    source,
                    target,
                    weight: None,
                });
            }
            None => {
                self.missing.push(target_uri);
            }
        }
    }
}