Skip to main content

_diffctx/edges/semantic/
lua.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, discover_files_by_refs};
12
13fn is_lua_file(path: &Path) -> bool {
14    base::file_ext(path) == ".lua"
15}
16
17static REQUIRE_RE: Lazy<Regex> =
18    Lazy::new(|| Regex::new(r#"(?m)require\s*[\(]?\s*['"]([^'"]+)['"]"#).unwrap());
19static DOFILE_RE: Lazy<Regex> =
20    Lazy::new(|| Regex::new(r#"(?m)dofile\s*\(\s*['"]([^'"]+)['"]"#).unwrap());
21static FUNC_DEF_RE: Lazy<Regex> =
22    Lazy::new(|| Regex::new(r"(?m)^\s*(?:local\s+)?function\s+([\w.:]+)").unwrap());
23static LOCAL_FUNC_RE: Lazy<Regex> =
24    Lazy::new(|| Regex::new(r"(?m)^\s*local\s+(\w+)\s*=\s*function").unwrap());
25static METHOD_CALL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\b(\w+)[:.]\w+\s*\(").unwrap());
26
27fn extract_requires(content: &str) -> FxHashSet<String> {
28    let mut refs: FxHashSet<String> = REQUIRE_RE
29        .captures_iter(content)
30        .map(|c| c[1].to_string())
31        .collect();
32    refs.extend(DOFILE_RE.captures_iter(content).map(|c| c[1].to_string()));
33    refs
34}
35
36fn extract_defs(content: &str) -> FxHashSet<String> {
37    let mut defs: FxHashSet<String> = FxHashSet::default();
38    for cap in FUNC_DEF_RE.captures_iter(content) {
39        let name = &cap[1];
40        let leaf = name.split(&['.', ':'][..]).last().unwrap_or(name);
41        defs.insert(leaf.to_string());
42    }
43    defs.extend(
44        LOCAL_FUNC_RE
45            .captures_iter(content)
46            .map(|c| c[1].to_string()),
47    );
48    defs
49}
50
51fn extract_method_targets(content: &str) -> FxHashSet<String> {
52    METHOD_CALL_RE
53        .captures_iter(content)
54        .map(|c| c[1].to_string())
55        .collect()
56}
57
58pub struct LuaEdgeBuilder;
59
60impl EdgeBuilder for LuaEdgeBuilder {
61    fn build(&self, fragments: &[Fragment], repo_root: Option<&Path>) -> EdgeDict {
62        let frags: Vec<&Fragment> = fragments
63            .iter()
64            .filter(|f| is_lua_file(Path::new(f.path())))
65            .collect();
66        if frags.is_empty() {
67            return FxHashMap::default();
68        }
69
70        let require_w = EDGE_WEIGHTS["lua_require"].forward;
71        let fn_w = EDGE_WEIGHTS["lua_fn"].forward;
72        let method_w = EDGE_WEIGHTS["lua_method"].forward;
73        let reverse_factor = EDGE_WEIGHTS["lua_require"].reverse_factor;
74
75        let idx = base::FragmentIndex::new(fragments, repo_root);
76        let mut name_to_defs: FxHashMap<String, Vec<_>> = FxHashMap::default();
77        for f in &frags {
78            for name in extract_defs(&f.content) {
79                name_to_defs
80                    .entry(name.to_lowercase())
81                    .or_default()
82                    .push(f.id.clone());
83            }
84        }
85
86        let mut edges: EdgeDict = FxHashMap::default();
87
88        for f in &frags {
89            let self_defs = extract_defs(&f.content);
90            for req in extract_requires(&f.content) {
91                base::link_by_name(&f.id, &req, &idx, &mut edges, require_w, reverse_factor);
92            }
93            for target in extract_method_targets(&f.content) {
94                if self_defs.contains(&target) {
95                    continue;
96                }
97                if let Some(targets) = name_to_defs.get(&target.to_lowercase()) {
98                    for t in targets {
99                        if t != &f.id {
100                            add_edge(&mut edges, &f.id, t, method_w, reverse_factor);
101                        }
102                    }
103                }
104            }
105            for id in &f.identifiers {
106                if self_defs.contains(id) {
107                    continue;
108                }
109                if let Some(targets) = name_to_defs.get(&id.to_lowercase()) {
110                    for t in targets {
111                        if t != &f.id {
112                            add_edge(&mut edges, &f.id, t, fn_w, reverse_factor);
113                        }
114                    }
115                }
116            }
117        }
118        edges
119    }
120
121    fn discover_related_files(
122        &self,
123        changed: &[PathBuf],
124        candidates: &[PathBuf],
125        repo_root: Option<&Path>,
126        file_cache: Option<&FxHashMap<PathBuf, String>>,
127    ) -> Vec<PathBuf> {
128        let lua_changed: Vec<&PathBuf> = changed.iter().filter(|f| is_lua_file(f)).collect();
129        if lua_changed.is_empty() {
130            return vec![];
131        }
132        let mut refs = FxHashSet::default();
133        for f in &lua_changed {
134            if let Some(content) = base::read_file_cached(f, file_cache) {
135                refs.extend(extract_requires(&content));
136            }
137        }
138        discover_files_by_refs(&refs, changed, candidates, repo_root)
139    }
140}