Skip to main content

aft_parse/callgraph_store/dispatch/static_receiver/
csharp_projects.rs

1//! Project boundaries for C# type lookup. Paths are relative to one checkout.
2
3use std::collections::{BTreeSet, HashMap, HashSet};
4use std::sync::{Arc, Mutex, OnceLock};
5
6use super::csharp_membership::{self as membership, Markers, DIRECTORY_INPUTS};
7
8#[derive(Debug, Default)]
9pub struct CSharpProjects {
10    declarations: HashMap<String, Folder>,
11    membership_imports: HashMap<String, BTreeSet<String>>,
12    projects: Vec<Project>,
13    lookups: Mutex<HashMap<String, Arc<Lookup>>>,
14}
15
16pub(super) type ProjectId = usize;
17
18#[derive(Debug, Clone, Copy)]
19enum Folder {
20    One(ProjectId),
21    Ambiguous,
22}
23
24pub(super) const UNKNOWN: u8 = 0;
25pub(super) const AGGREGATOR: u8 = 1;
26pub(super) const COMPILES: u8 = 2;
27const MAX_REACHABLE: usize = 1000;
28
29#[derive(Debug)]
30struct Project {
31    path: String,
32    folder: String,
33    references: BTreeSet<String>,
34    closure: OnceLock<Closure>,
35}
36
37#[derive(Debug, Default)]
38struct Closure {
39    projects: Option<HashSet<ProjectId>>,
40    folders: BTreeSet<String>,
41}
42
43#[derive(Debug)]
44struct Lookup {
45    project: Option<ProjectId>,
46    folders: Vec<String>,
47}
48
49impl CSharpProjects {
50    pub const PROJECT_READ_LIMIT: u64 = 64 * 1024;
51    /// Load compact project facts from the checkout snapshot. No directory or
52    /// project files are reopened during resolution.
53    pub fn new<'a>(paths: impl IntoIterator<Item = (&'a [u8], Option<&'a [u8]>)>) -> Self {
54        let mut this = Self::default();
55        let mut files = HashMap::new();
56        let mut project_paths = Vec::new();
57        for (path, bytes) in paths {
58            let markers = Markers::decode(bytes);
59            if let Some(folder) = Self::manifest_folder(path) {
60                project_paths.push((path, folder, markers));
61            }
62            if bytes.is_some() || Self::is_membership_config_path(path) {
63                if let Ok(path) = std::str::from_utf8(path) {
64                    files.insert(path, markers);
65                }
66            }
67        }
68        for (path, folder, markers) in project_paths {
69            if markers.kind == AGGREGATOR {
70                continue;
71            }
72            let supported = markers.kind == COMPILES
73                && std::str::from_utf8(path).ok().is_some_and(|path| {
74                    let check = membership::project(path, &files);
75                    this.membership_imports
76                        .entry(folder.clone())
77                        .or_default()
78                        .extend(check.imports);
79                    check.known
80                });
81            let entry = if supported {
82                let id = this.projects.len();
83                let references = markers
84                    .references()
85                    .filter_map(|path| reference_path(&folder, path))
86                    .collect();
87                this.projects.push(Project {
88                    path: String::from_utf8_lossy(path).into_owned(),
89                    folder: folder.clone(),
90                    references,
91                    closure: OnceLock::new(),
92                });
93                Folder::One(id)
94            } else {
95                Folder::Ambiguous
96            };
97            this.declarations
98                .entry(folder)
99                .and_modify(|kind| *kind = Folder::Ambiguous)
100                .or_insert(entry);
101        }
102        this
103    }
104
105    /// Compact configuration fact from the project's own bounded XML read.
106    pub fn project_markers(source: &[u8]) -> Vec<u8> {
107        let Some(facts) = super::msbuild::classify(source) else {
108            return vec![UNKNOWN, 0];
109        };
110        let mut out = vec![facts.kind, u8::from(facts.membership_safe)];
111        if facts.kind == COMPILES {
112            for path in facts.references {
113                out.extend(b"R\t");
114                out.extend(path.as_bytes());
115                out.push(b'\n');
116            }
117        }
118        for path in facts.imports {
119            out.extend(b"I\t");
120            out.extend(path.as_bytes());
121            out.push(b'\n');
122        }
123        out
124    }
125
126    pub fn is_membership_config_path(path: &[u8]) -> bool {
127        path.ends_with(b".csproj")
128            || path
129                .rsplit(|&byte| byte == b'/')
130                .next()
131                .is_some_and(|name| {
132                    DIRECTORY_INPUTS
133                        .iter()
134                        .any(|input| name == input.as_bytes())
135                })
136    }
137
138    pub fn has_project_root(source: &[u8]) -> bool {
139        super::msbuild::has_project_root(source)
140    }
141
142    pub fn manifest_folder(path: &[u8]) -> Option<String> {
143        path.ends_with(b".csproj")
144            .then(|| Self::membership_folder(path))
145            .flatten()
146    }
147
148    pub fn membership_folder(path: &[u8]) -> Option<String> {
149        if !Self::is_membership_config_path(path) {
150            return None;
151        }
152        let dir = path
153            .iter()
154            .rposition(|&byte| byte == b'/')
155            .map_or(&b""[..], |end| &path[..end]);
156        Some(String::from_utf8_lossy(dir).into_owned())
157    }
158
159    pub fn dependency(folder: &str) -> String {
160        format!("csproject:{folder}")
161    }
162
163    pub fn import_dependency(path: &str) -> String {
164        format!("csimport:{path}")
165    }
166
167    fn depend_folder(&self, folder: &str, depends: &mut impl FnMut(String)) {
168        depends(Self::dependency(folder));
169        if let Some(imports) = self.membership_imports.get(folder) {
170            for dir in membership::ancestors(folder).skip(1) {
171                depends(Self::dependency(dir));
172            }
173            for path in imports {
174                depends(Self::import_dependency(path));
175            }
176        }
177    }
178
179    pub(super) fn owner(&self, file: &str, mut depends: impl FnMut(String)) -> Option<ProjectId> {
180        let directory = parent(file);
181        let lookup = {
182            let mut lookups = self
183                .lookups
184                .lock()
185                .unwrap_or_else(std::sync::PoisonError::into_inner);
186            Arc::clone(lookups.entry(directory.to_string()).or_insert_with(|| {
187                let mut folder = directory;
188                let mut folders = Vec::new();
189                let project = loop {
190                    folders.push(folder.to_string());
191                    match self.declarations.get(folder) {
192                        Some(Folder::One(project)) => break Some(*project),
193                        Some(Folder::Ambiguous) => break None,
194                        None if folder.is_empty() => break None,
195                        None => folder = parent(folder),
196                    }
197                };
198                Arc::new(Lookup { project, folders })
199            }))
200        };
201        for folder in &lookup.folders {
202            self.depend_folder(folder, &mut depends);
203        }
204        lookup.project
205    }
206
207    pub(super) fn reachable(
208        &self,
209        project: ProjectId,
210        mut depends: impl FnMut(String),
211    ) -> Option<&HashSet<ProjectId>> {
212        let closure = self.projects[project]
213            .closure
214            .get_or_init(|| self.walk(project));
215        for folder in &closure.folders {
216            self.depend_folder(folder, &mut depends);
217        }
218        closure.projects.as_ref()
219    }
220
221    fn walk(&self, start: ProjectId) -> Closure {
222        let mut folders = BTreeSet::new();
223        let mut projects = HashSet::from([start]);
224        let mut pending = vec![start];
225        while let Some(id) = pending.pop() {
226            let project = &self.projects[id];
227            folders.insert(project.folder.clone());
228            for target in &project.references {
229                let folder = parent(target);
230                folders.insert(folder.to_string());
231                if let Some(Folder::One(next)) = self.declarations.get(folder) {
232                    // A different project filename in the same folder does
233                    // not prove a reference to the one present today.
234                    if self.projects[*next].path == *target && projects.insert(*next) {
235                        if projects.len() > MAX_REACHABLE + 1 {
236                            return Closure {
237                                projects: None,
238                                folders,
239                            };
240                        }
241                        pending.push(*next);
242                    }
243                }
244            }
245        }
246        Closure {
247            projects: Some(projects),
248            folders,
249        }
250    }
251}
252
253pub(super) fn parent(path: &str) -> &str {
254    path.rsplit_once('/').map_or("", |(dir, _)| dir)
255}
256
257fn reference_path(folder: &str, include: &str) -> Option<String> {
258    let include = include.replace('\\', "/");
259    let include = include.trim();
260    let include = include
261        .strip_prefix("$(MSBuildThisFileDirectory)")
262        .or_else(|| include.strip_prefix("$(MSBuildProjectDirectory)"))
263        .map_or_else(
264            || (!include.starts_with('/')).then_some(include),
265            |path| Some(path.trim_start_matches('/')),
266        )?;
267    include
268        .ends_with(".csproj")
269        .then(|| normalize_inside(folder, include))
270        .flatten()
271}
272
273pub(super) fn normalize_inside(folder: &str, include: &str) -> Option<String> {
274    let include = include.trim();
275    if include.is_empty()
276        || include.starts_with('/')
277        || include.contains(['$', '%', '@', '*', '?', ':', ';', '\r', '\n'])
278    {
279        return None;
280    }
281    let mut parts = folder
282        .split('/')
283        .filter(|part| !part.is_empty())
284        .collect::<Vec<_>>();
285    for part in include.split('/') {
286        match part {
287            "" | "." => {}
288            ".." => {
289                parts.pop()?;
290            }
291            part => parts.push(part),
292        }
293    }
294    (!parts.is_empty()).then(|| parts.join("/"))
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn csharp_project_reference_cap_yields_no_proof() {
303        let mut projects = (0..MAX_REACHABLE + 2).map(|i| {
304            let path = format!("p{i}/p.csproj");
305            let xml = format!("<Project><ItemGroup><ProjectReference Include=\"../p{}/p.csproj\" /></ItemGroup></Project>", i+1);
306            (path, CSharpProjects::project_markers(xml.as_bytes()))
307        }).collect::<Vec<_>>();
308        let build = |projects: &[(String, Vec<u8>)]| {
309            CSharpProjects::new(
310                projects
311                    .iter()
312                    .map(|(path, config)| (path.as_bytes(), Some(config.as_slice()))),
313            )
314        };
315        let capped = build(&projects);
316        assert!(capped.reachable(0, |_| {}).is_none());
317        projects.pop();
318        let bounded = build(&projects);
319        assert_eq!(
320            bounded.reachable(0, |_| {}).unwrap().len(),
321            MAX_REACHABLE + 1
322        );
323    }
324}