Skip to main content

_diffctx/edges/semantic/
latex.rs

1use std::path::{Path, PathBuf};
2
3use once_cell::sync::Lazy;
4use regex::Regex;
5use rustc_hash::{FxHashMap, FxHashSet};
6
7use crate::config::weights::EDGE_WEIGHTS;
8use crate::types::Fragment;
9
10use super::super::EdgeDict;
11use super::super::base::{self, EdgeBuilder, discover_files_by_refs};
12
13fn is_latex_file(path: &Path) -> bool {
14    let ext = base::file_ext(path);
15    matches!(ext.as_str(), ".tex" | ".sty" | ".cls" | ".bib")
16}
17
18static INPUT_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\\(?:input|include)\{([^}]+)\}").unwrap());
19static USEPACKAGE_RE: Lazy<Regex> =
20    Lazy::new(|| Regex::new(r"\\usepackage(?:\[.*?\])?\{([^}]+)\}").unwrap());
21static BIB_RE: Lazy<Regex> =
22    Lazy::new(|| Regex::new(r"\\(?:bibliography|addbibresource)\{([^}]+)\}").unwrap());
23static SUBFILE_RE: Lazy<Regex> =
24    Lazy::new(|| Regex::new(r"\\(?:subfile|subimport\{[^}]*\})\{([^}]+)\}").unwrap());
25
26fn extract_refs(content: &str) -> FxHashSet<String> {
27    let mut refs = FxHashSet::default();
28    for re in [&*INPUT_RE, &*SUBFILE_RE] {
29        refs.extend(re.captures_iter(content).map(|c| c[1].to_string()));
30    }
31    for cap in USEPACKAGE_RE.captures_iter(content) {
32        for pkg in cap[1].split(',') {
33            let name = pkg.trim();
34            if !name.is_empty() {
35                refs.insert(name.to_string());
36            }
37        }
38    }
39    for cap in BIB_RE.captures_iter(content) {
40        for bib in cap[1].split(',') {
41            let name = bib.trim();
42            if !name.is_empty() {
43                refs.insert(name.to_string());
44            }
45        }
46    }
47    refs
48}
49
50pub struct LatexEdgeBuilder;
51
52impl EdgeBuilder for LatexEdgeBuilder {
53    fn build(&self, fragments: &[Fragment], repo_root: Option<&Path>) -> EdgeDict {
54        let frags: Vec<&Fragment> = fragments
55            .iter()
56            .filter(|f| is_latex_file(Path::new(f.path())))
57            .collect();
58        if frags.is_empty() {
59            return FxHashMap::default();
60        }
61
62        let input_w = EDGE_WEIGHTS["latex_input"].forward;
63        let pkg_w = EDGE_WEIGHTS["latex_package"].forward;
64        let bib_w = EDGE_WEIGHTS["latex_bib"].forward;
65        let reverse_factor = EDGE_WEIGHTS["latex_input"].reverse_factor;
66
67        let idx = base::FragmentIndex::new(fragments, repo_root);
68        let mut edges: EdgeDict = FxHashMap::default();
69
70        for f in &frags {
71            for cap in INPUT_RE.captures_iter(&f.content) {
72                base::link_by_name(&f.id, &cap[1], &idx, &mut edges, input_w, reverse_factor);
73            }
74            for cap in SUBFILE_RE.captures_iter(&f.content) {
75                base::link_by_name(&f.id, &cap[1], &idx, &mut edges, input_w, reverse_factor);
76            }
77            for cap in USEPACKAGE_RE.captures_iter(&f.content) {
78                for pkg in cap[1].split(',') {
79                    let name = pkg.trim();
80                    if !name.is_empty() {
81                        base::link_by_name(&f.id, name, &idx, &mut edges, pkg_w, reverse_factor);
82                    }
83                }
84            }
85            for cap in BIB_RE.captures_iter(&f.content) {
86                for bib in cap[1].split(',') {
87                    let name = bib.trim();
88                    if !name.is_empty() {
89                        base::link_by_name(&f.id, name, &idx, &mut edges, bib_w, reverse_factor);
90                    }
91                }
92            }
93        }
94        edges
95    }
96
97    fn discover_related_files(
98        &self,
99        changed: &[PathBuf],
100        candidates: &[PathBuf],
101        repo_root: Option<&Path>,
102        file_cache: Option<&FxHashMap<PathBuf, String>>,
103    ) -> Vec<PathBuf> {
104        let tex_changed: Vec<&PathBuf> = changed.iter().filter(|f| is_latex_file(f)).collect();
105        if tex_changed.is_empty() {
106            return vec![];
107        }
108        let mut refs = FxHashSet::default();
109        for f in &tex_changed {
110            if let Some(content) = base::read_file_cached(f, file_cache) {
111                refs.extend(extract_refs(&content));
112            }
113        }
114        discover_files_by_refs(&refs, changed, candidates, repo_root)
115    }
116}