Skip to main content

_diffctx/edges/semantic/
clojure.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, add_edge, add_edges_from_ids, discover_files_by_refs};
12
13fn is_clojure_file(path: &Path) -> bool {
14    let ext = base::file_ext(path);
15    matches!(ext.as_str(), ".clj" | ".cljs" | ".cljc" | ".edn")
16}
17
18static NS_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(ns\s+([\w.\-]+)").unwrap());
19static REQUIRE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r":require\s*\[([^\]]+)\]").unwrap());
20static REQUIRE_SINGLE_RE: Lazy<Regex> =
21    Lazy::new(|| Regex::new(r"\[?([\w.\-]+)(?:\s+:as\s+(\w+))?").unwrap());
22static USE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r":use\s*\[([^\]]+)\]").unwrap());
23static IMPORT_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r":import\s*\[([^\]]+)\]").unwrap());
24static DEFN_RE: Lazy<Regex> = Lazy::new(|| {
25    Regex::new(r"(?m)^\s*\((?:defn-?|def|defmacro|defprotocol|defrecord|deftype|defmulti|defmethod|defonce)\s+([\w\-!?*+<>=]+)").unwrap()
26});
27static CALL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\(([\w.\-]+/[\w\-!?*+<>=]+)").unwrap());
28
29static CLJ_KEYWORDS: Lazy<FxHashSet<&str>> = Lazy::new(|| {
30    [
31        "if", "do", "let", "fn", "def", "defn", "defmacro", "when", "cond", "case", "loop",
32        "recur", "throw", "try", "catch", "finally", "quote", "var", "ns", "require", "use",
33        "import", "in-ns", "refer", "nil", "true", "false", "println", "pr", "prn", "str", "first",
34        "rest", "cons", "conj", "assoc", "dissoc", "get", "count", "map", "filter", "reduce",
35        "apply", "partial", "comp", "identity", "not",
36    ]
37    .iter()
38    .copied()
39    .collect()
40});
41
42fn extract_requires(content: &str) -> FxHashSet<String> {
43    let mut refs = FxHashSet::default();
44    for cap in REQUIRE_RE.captures_iter(content) {
45        for single in REQUIRE_SINGLE_RE.captures_iter(&cap[1]) {
46            let name = &single[1];
47            if !name.starts_with(':') {
48                refs.insert(name.to_string());
49                if let Some(leaf) = name.split('.').last() {
50                    refs.insert(leaf.to_string());
51                }
52            }
53        }
54    }
55    for cap in USE_RE.captures_iter(content) {
56        for single in REQUIRE_SINGLE_RE.captures_iter(&cap[1]) {
57            refs.insert(single[1].to_string());
58        }
59    }
60    for cap in IMPORT_RE.captures_iter(content) {
61        for word in cap[1].split_whitespace() {
62            let w = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '.');
63            if !w.is_empty() {
64                refs.insert(w.to_string());
65            }
66        }
67    }
68    refs
69}
70
71fn extract_ns(content: &str) -> Option<String> {
72    NS_RE.captures(content).map(|c| c[1].to_string())
73}
74
75fn extract_defs(content: &str) -> FxHashSet<String> {
76    DEFN_RE
77        .captures_iter(content)
78        .map(|c| c[1].to_string())
79        .collect()
80}
81
82pub struct ClojureEdgeBuilder;
83
84impl EdgeBuilder for ClojureEdgeBuilder {
85    fn build(&self, fragments: &[Fragment], repo_root: Option<&Path>) -> EdgeDict {
86        let frags: Vec<&Fragment> = fragments
87            .iter()
88            .filter(|f| is_clojure_file(Path::new(f.path())))
89            .collect();
90        if frags.is_empty() {
91            return FxHashMap::default();
92        }
93
94        let require_w = EDGE_WEIGHTS["clojure_require"].forward;
95        let fn_w = EDGE_WEIGHTS["clojure_fn"].forward;
96        let _proto_w = EDGE_WEIGHTS["clojure_protocol"].forward;
97        let reverse_factor = EDGE_WEIGHTS["clojure_require"].reverse_factor;
98
99        let idx = base::FragmentIndex::new(fragments, repo_root);
100        let mut ns_to_frags: FxHashMap<String, Vec<_>> = FxHashMap::default();
101        let mut name_to_defs: FxHashMap<String, Vec<_>> = FxHashMap::default();
102        for f in &frags {
103            if let Some(ns) = extract_ns(&f.content) {
104                let leaf = ns.split('.').last().unwrap_or(&ns).to_lowercase();
105                ns_to_frags.entry(leaf).or_default().push(f.id.clone());
106                ns_to_frags
107                    .entry(ns.to_lowercase())
108                    .or_default()
109                    .push(f.id.clone());
110            }
111            for name in extract_defs(&f.content) {
112                name_to_defs
113                    .entry(name.to_lowercase())
114                    .or_default()
115                    .push(f.id.clone());
116            }
117        }
118
119        let mut edges: EdgeDict = FxHashMap::default();
120
121        for f in &frags {
122            let self_defs = extract_defs(&f.content);
123            for req in extract_requires(&f.content) {
124                let leaf = req.split('.').last().unwrap_or(&req).to_lowercase();
125                if let Some(targets) = ns_to_frags.get(&leaf) {
126                    add_edges_from_ids(&mut edges, &f.id, targets, require_w, reverse_factor);
127                } else {
128                    base::link_by_name(&f.id, &req, &idx, &mut edges, require_w, reverse_factor);
129                }
130            }
131            for cap in CALL_RE.captures_iter(&f.content) {
132                let full = &cap[1];
133                if let Some(func) = full.split('/').last() {
134                    if self_defs.contains(func) || CLJ_KEYWORDS.contains(func) {
135                        continue;
136                    }
137                    if let Some(targets) = name_to_defs.get(&func.to_lowercase()) {
138                        for t in targets {
139                            if t != &f.id {
140                                add_edge(&mut edges, &f.id, t, fn_w, reverse_factor);
141                            }
142                        }
143                    }
144                }
145            }
146            for id in &f.identifiers {
147                if self_defs.contains(id) || CLJ_KEYWORDS.contains(id.as_str()) {
148                    continue;
149                }
150                if let Some(targets) = name_to_defs.get(&id.to_lowercase()) {
151                    for t in targets {
152                        if t != &f.id {
153                            add_edge(&mut edges, &f.id, t, fn_w, reverse_factor);
154                        }
155                    }
156                }
157            }
158        }
159        edges
160    }
161
162    fn discover_related_files(
163        &self,
164        changed: &[PathBuf],
165        candidates: &[PathBuf],
166        repo_root: Option<&Path>,
167        file_cache: Option<&FxHashMap<PathBuf, String>>,
168    ) -> Vec<PathBuf> {
169        let clj_changed: Vec<&PathBuf> = changed.iter().filter(|f| is_clojure_file(f)).collect();
170        if clj_changed.is_empty() {
171            return vec![];
172        }
173        let mut refs = FxHashSet::default();
174        for f in &clj_changed {
175            if let Some(content) = base::read_file_cached(f, file_cache) {
176                refs.extend(extract_requires(&content));
177            }
178        }
179        discover_files_by_refs(&refs, changed, candidates, repo_root)
180    }
181}