ra_ap_load_cargo/
lib.rs

1//! Loads a Cargo project into a static instance of analysis, without support
2//! for incorporating changes.
3// Note, don't remove any public api from this. This API is consumed by external tools
4// to run rust-analyzer as a library.
5use std::{any::Any, collections::hash_map::Entry, mem, path::Path, sync};
6
7use crossbeam_channel::{Receiver, unbounded};
8use hir_expand::proc_macro::{
9    ProcMacro, ProcMacroExpander, ProcMacroExpansionError, ProcMacroKind, ProcMacroLoadResult,
10    ProcMacrosBuilder,
11};
12use ide_db::{
13    ChangeWithProcMacros, FxHashMap, RootDatabase,
14    base_db::{CrateGraphBuilder, Env, ProcMacroLoadingError, SourceRoot, SourceRootId},
15    prime_caches,
16};
17use itertools::Itertools;
18use proc_macro_api::{MacroDylib, ProcMacroClient};
19use project_model::{CargoConfig, PackageRoot, ProjectManifest, ProjectWorkspace};
20use span::Span;
21use vfs::{
22    AbsPath, AbsPathBuf, VfsPath,
23    file_set::FileSetConfig,
24    loader::{Handle, LoadingProgress},
25};
26
27#[derive(Debug)]
28pub struct LoadCargoConfig {
29    pub load_out_dirs_from_check: bool,
30    pub with_proc_macro_server: ProcMacroServerChoice,
31    pub prefill_caches: bool,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum ProcMacroServerChoice {
36    Sysroot,
37    Explicit(AbsPathBuf),
38    None,
39}
40
41pub fn load_workspace_at(
42    root: &Path,
43    cargo_config: &CargoConfig,
44    load_config: &LoadCargoConfig,
45    progress: &(dyn Fn(String) + Sync),
46) -> anyhow::Result<(RootDatabase, vfs::Vfs, Option<ProcMacroClient>)> {
47    let root = AbsPathBuf::assert_utf8(std::env::current_dir()?.join(root));
48    let root = ProjectManifest::discover_single(&root)?;
49    let manifest_path = root.manifest_path().clone();
50    let mut workspace = ProjectWorkspace::load(root, cargo_config, progress)?;
51
52    if load_config.load_out_dirs_from_check {
53        let build_scripts = workspace.run_build_scripts(cargo_config, progress)?;
54        if let Some(error) = build_scripts.error() {
55            tracing::debug!(
56                "Errors occurred while running build scripts for {}: {}",
57                manifest_path,
58                error
59            );
60        }
61        workspace.set_build_scripts(build_scripts)
62    }
63
64    load_workspace(workspace, &cargo_config.extra_env, load_config)
65}
66
67pub fn load_workspace(
68    ws: ProjectWorkspace,
69    extra_env: &FxHashMap<String, Option<String>>,
70    load_config: &LoadCargoConfig,
71) -> anyhow::Result<(RootDatabase, vfs::Vfs, Option<ProcMacroClient>)> {
72    let lru_cap = std::env::var("RA_LRU_CAP").ok().and_then(|it| it.parse::<u16>().ok());
73    let mut db = RootDatabase::new(lru_cap);
74
75    let (vfs, proc_macro_server) = load_workspace_into_db(ws, extra_env, load_config, &mut db)?;
76
77    Ok((db, vfs, proc_macro_server))
78}
79
80// This variant of `load_workspace` allows deferring the loading of rust-analyzer
81// into an existing database, which is useful in certain third-party scenarios,
82// now that `salsa` supports extending foreign databases (e.g. `RootDatabase`).
83pub fn load_workspace_into_db(
84    ws: ProjectWorkspace,
85    extra_env: &FxHashMap<String, Option<String>>,
86    load_config: &LoadCargoConfig,
87    db: &mut RootDatabase,
88) -> anyhow::Result<(vfs::Vfs, Option<ProcMacroClient>)> {
89    let (sender, receiver) = unbounded();
90    let mut vfs = vfs::Vfs::default();
91    let mut loader = {
92        let loader = vfs_notify::NotifyHandle::spawn(sender);
93        Box::new(loader)
94    };
95
96    tracing::debug!(?load_config, "LoadCargoConfig");
97    let proc_macro_server = match &load_config.with_proc_macro_server {
98        ProcMacroServerChoice::Sysroot => ws.find_sysroot_proc_macro_srv().map(|it| {
99            it.and_then(|it| ProcMacroClient::spawn(&it, extra_env).map_err(Into::into)).map_err(
100                |e| ProcMacroLoadingError::ProcMacroSrvError(e.to_string().into_boxed_str()),
101            )
102        }),
103        ProcMacroServerChoice::Explicit(path) => {
104            Some(ProcMacroClient::spawn(path, extra_env).map_err(|e| {
105                ProcMacroLoadingError::ProcMacroSrvError(e.to_string().into_boxed_str())
106            }))
107        }
108        ProcMacroServerChoice::None => Some(Err(ProcMacroLoadingError::Disabled)),
109    };
110    match &proc_macro_server {
111        Some(Ok(server)) => {
112            tracing::info!(manifest=%ws.manifest_or_root(), path=%server.server_path(), "Proc-macro server started")
113        }
114        Some(Err(e)) => {
115            tracing::info!(manifest=%ws.manifest_or_root(), %e, "Failed to start proc-macro server")
116        }
117        None => {
118            tracing::info!(manifest=%ws.manifest_or_root(), "No proc-macro server started")
119        }
120    }
121
122    let (crate_graph, proc_macros) = ws.to_crate_graph(
123        &mut |path: &AbsPath| {
124            let contents = loader.load_sync(path);
125            let path = vfs::VfsPath::from(path.to_path_buf());
126            vfs.set_file_contents(path.clone(), contents);
127            vfs.file_id(&path).and_then(|(file_id, excluded)| {
128                (excluded == vfs::FileExcluded::No).then_some(file_id)
129            })
130        },
131        extra_env,
132    );
133    let proc_macros = {
134        let proc_macro_server = match &proc_macro_server {
135            Some(Ok(it)) => Ok(it),
136            Some(Err(e)) => {
137                Err(ProcMacroLoadingError::ProcMacroSrvError(e.to_string().into_boxed_str()))
138            }
139            None => Err(ProcMacroLoadingError::ProcMacroSrvError(
140                "proc-macro-srv is not running, workspace is missing a sysroot".into(),
141            )),
142        };
143        proc_macros
144            .into_iter()
145            .map(|(crate_id, path)| {
146                (
147                    crate_id,
148                    path.map_or_else(Err, |(_, path)| {
149                        proc_macro_server.as_ref().map_err(Clone::clone).and_then(
150                            |proc_macro_server| load_proc_macro(proc_macro_server, &path, &[]),
151                        )
152                    }),
153                )
154            })
155            .collect()
156    };
157
158    let project_folders = ProjectFolders::new(std::slice::from_ref(&ws), &[], None);
159    loader.set_config(vfs::loader::Config {
160        load: project_folders.load,
161        watch: vec![],
162        version: 0,
163    });
164
165    load_crate_graph_into_db(
166        crate_graph,
167        proc_macros,
168        project_folders.source_root_config,
169        &mut vfs,
170        &receiver,
171        db,
172    );
173
174    if load_config.prefill_caches {
175        prime_caches::parallel_prime_caches(db, 1, &|_| ());
176    }
177
178    Ok((vfs, proc_macro_server.and_then(Result::ok)))
179}
180
181#[derive(Default)]
182pub struct ProjectFolders {
183    pub load: Vec<vfs::loader::Entry>,
184    pub watch: Vec<usize>,
185    pub source_root_config: SourceRootConfig,
186}
187
188impl ProjectFolders {
189    pub fn new(
190        workspaces: &[ProjectWorkspace],
191        global_excludes: &[AbsPathBuf],
192        user_config_dir_path: Option<&AbsPath>,
193    ) -> ProjectFolders {
194        let mut res = ProjectFolders::default();
195        let mut fsc = FileSetConfig::builder();
196        let mut local_filesets = vec![];
197
198        // Dedup source roots
199        // Depending on the project setup, we can have duplicated source roots, or for example in
200        // the case of the rustc workspace, we can end up with two source roots that are almost the
201        // same but not quite, like:
202        // PackageRoot { is_local: false, include: [AbsPathBuf(".../rust/src/tools/miri/cargo-miri")], exclude: [] }
203        // PackageRoot {
204        //     is_local: true,
205        //     include: [AbsPathBuf(".../rust/src/tools/miri/cargo-miri"), AbsPathBuf(".../rust/build/x86_64-pc-windows-msvc/stage0-tools/x86_64-pc-windows-msvc/release/build/cargo-miri-85801cd3d2d1dae4/out")],
206        //     exclude: [AbsPathBuf(".../rust/src/tools/miri/cargo-miri/.git"), AbsPathBuf(".../rust/src/tools/miri/cargo-miri/target")]
207        // }
208        //
209        // The first one comes from the explicit rustc workspace which points to the rustc workspace itself
210        // The second comes from the rustc workspace that we load as the actual project workspace
211        // These `is_local` differing in this kind of way gives us problems, especially when trying to filter diagnostics as we don't report diagnostics for external libraries.
212        // So we need to deduplicate these, usually it would be enough to deduplicate by `include`, but as the rustc example shows here that doesn't work,
213        // so we need to also coalesce the includes if they overlap.
214
215        let mut roots: Vec<_> = workspaces
216            .iter()
217            .flat_map(|ws| ws.to_roots())
218            .update(|root| root.include.sort())
219            .sorted_by(|a, b| a.include.cmp(&b.include))
220            .collect();
221
222        // map that tracks indices of overlapping roots
223        let mut overlap_map = FxHashMap::<_, Vec<_>>::default();
224        let mut done = false;
225
226        while !mem::replace(&mut done, true) {
227            // maps include paths to indices of the corresponding root
228            let mut include_to_idx = FxHashMap::default();
229            // Find and note down the indices of overlapping roots
230            for (idx, root) in roots.iter().enumerate().filter(|(_, it)| !it.include.is_empty()) {
231                for include in &root.include {
232                    match include_to_idx.entry(include) {
233                        Entry::Occupied(e) => {
234                            overlap_map.entry(*e.get()).or_default().push(idx);
235                        }
236                        Entry::Vacant(e) => {
237                            e.insert(idx);
238                        }
239                    }
240                }
241            }
242            for (k, v) in overlap_map.drain() {
243                done = false;
244                for v in v {
245                    let r = mem::replace(
246                        &mut roots[v],
247                        PackageRoot { is_local: false, include: vec![], exclude: vec![] },
248                    );
249                    roots[k].is_local |= r.is_local;
250                    roots[k].include.extend(r.include);
251                    roots[k].exclude.extend(r.exclude);
252                }
253                roots[k].include.sort();
254                roots[k].exclude.sort();
255                roots[k].include.dedup();
256                roots[k].exclude.dedup();
257            }
258        }
259
260        for root in roots.into_iter().filter(|it| !it.include.is_empty()) {
261            let file_set_roots: Vec<VfsPath> =
262                root.include.iter().cloned().map(VfsPath::from).collect();
263
264            let entry = {
265                let mut dirs = vfs::loader::Directories::default();
266                dirs.extensions.push("rs".into());
267                dirs.extensions.push("toml".into());
268                dirs.include.extend(root.include);
269                dirs.exclude.extend(root.exclude);
270                for excl in global_excludes {
271                    if dirs
272                        .include
273                        .iter()
274                        .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
275                    {
276                        dirs.exclude.push(excl.clone());
277                    }
278                }
279
280                vfs::loader::Entry::Directories(dirs)
281            };
282
283            if root.is_local {
284                res.watch.push(res.load.len());
285            }
286            res.load.push(entry);
287
288            if root.is_local {
289                local_filesets.push(fsc.len() as u64);
290            }
291            fsc.add_file_set(file_set_roots)
292        }
293
294        for ws in workspaces.iter() {
295            let mut file_set_roots: Vec<VfsPath> = vec![];
296            let mut entries = vec![];
297
298            for buildfile in ws.buildfiles() {
299                file_set_roots.push(VfsPath::from(buildfile.to_owned()));
300                entries.push(buildfile.to_owned());
301            }
302
303            if !file_set_roots.is_empty() {
304                let entry = vfs::loader::Entry::Files(entries);
305                res.watch.push(res.load.len());
306                res.load.push(entry);
307                local_filesets.push(fsc.len() as u64);
308                fsc.add_file_set(file_set_roots)
309            }
310        }
311
312        if let Some(user_config_path) = user_config_dir_path {
313            let ratoml_path = {
314                let mut p = user_config_path.to_path_buf();
315                p.push("rust-analyzer.toml");
316                p
317            };
318
319            let file_set_roots = vec![VfsPath::from(ratoml_path.to_owned())];
320            let entry = vfs::loader::Entry::Files(vec![ratoml_path]);
321
322            res.watch.push(res.load.len());
323            res.load.push(entry);
324            local_filesets.push(fsc.len() as u64);
325            fsc.add_file_set(file_set_roots)
326        }
327
328        let fsc = fsc.build();
329        res.source_root_config = SourceRootConfig { fsc, local_filesets };
330
331        res
332    }
333}
334
335#[derive(Default, Debug)]
336pub struct SourceRootConfig {
337    pub fsc: FileSetConfig,
338    pub local_filesets: Vec<u64>,
339}
340
341impl SourceRootConfig {
342    pub fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
343        self.fsc
344            .partition(vfs)
345            .into_iter()
346            .enumerate()
347            .map(|(idx, file_set)| {
348                let is_local = self.local_filesets.contains(&(idx as u64));
349                if is_local {
350                    SourceRoot::new_local(file_set)
351                } else {
352                    SourceRoot::new_library(file_set)
353                }
354            })
355            .collect()
356    }
357
358    /// Maps local source roots to their parent source roots by bytewise comparing of root paths .
359    /// If a `SourceRoot` doesn't have a parent and is local then it is not contained in this mapping but it can be asserted that it is a root `SourceRoot`.
360    pub fn source_root_parent_map(&self) -> FxHashMap<SourceRootId, SourceRootId> {
361        let roots = self.fsc.roots();
362
363        let mut map = FxHashMap::default();
364
365        // See https://github.com/rust-lang/rust-analyzer/issues/17409
366        //
367        // We can view the connections between roots as a graph. The problem is
368        // that this graph may contain cycles, so when adding edges, it is necessary
369        // to check whether it will lead to a cycle.
370        //
371        // Since we ensure that each node has at most one outgoing edge (because
372        // each SourceRoot can have only one parent), we can use a disjoint-set to
373        // maintain the connectivity between nodes. If an edge’s two nodes belong
374        // to the same set, they are already connected.
375        let mut dsu = FxHashMap::default();
376        fn find_parent(dsu: &mut FxHashMap<u64, u64>, id: u64) -> u64 {
377            if let Some(&parent) = dsu.get(&id) {
378                let parent = find_parent(dsu, parent);
379                dsu.insert(id, parent);
380                parent
381            } else {
382                id
383            }
384        }
385
386        for (idx, (root, root_id)) in roots.iter().enumerate() {
387            if !self.local_filesets.contains(root_id)
388                || map.contains_key(&SourceRootId(*root_id as u32))
389            {
390                continue;
391            }
392
393            for (root2, root2_id) in roots[..idx].iter().rev() {
394                if self.local_filesets.contains(root2_id)
395                    && root_id != root2_id
396                    && root.starts_with(root2)
397                {
398                    // check if the edge will create a cycle
399                    if find_parent(&mut dsu, *root_id) != find_parent(&mut dsu, *root2_id) {
400                        map.insert(SourceRootId(*root_id as u32), SourceRootId(*root2_id as u32));
401                        dsu.insert(*root_id, *root2_id);
402                    }
403
404                    break;
405                }
406            }
407        }
408
409        map
410    }
411}
412
413/// Load the proc-macros for the given lib path, disabling all expanders whose names are in `ignored_macros`.
414pub fn load_proc_macro(
415    server: &ProcMacroClient,
416    path: &AbsPath,
417    ignored_macros: &[Box<str>],
418) -> ProcMacroLoadResult {
419    let res: Result<Vec<_>, _> = (|| {
420        let dylib = MacroDylib::new(path.to_path_buf());
421        let vec = server.load_dylib(dylib).map_err(|e| {
422            ProcMacroLoadingError::ProcMacroSrvError(format!("{e}").into_boxed_str())
423        })?;
424        if vec.is_empty() {
425            return Err(ProcMacroLoadingError::NoProcMacros);
426        }
427        Ok(vec
428            .into_iter()
429            .map(|expander| expander_to_proc_macro(expander, ignored_macros))
430            .collect())
431    })();
432    match res {
433        Ok(proc_macros) => {
434            tracing::info!(
435                "Loaded proc-macros for {path}: {:?}",
436                proc_macros.iter().map(|it| it.name.clone()).collect::<Vec<_>>()
437            );
438            Ok(proc_macros)
439        }
440        Err(e) => {
441            tracing::warn!("proc-macro loading for {path} failed: {e}");
442            Err(e)
443        }
444    }
445}
446
447fn load_crate_graph_into_db(
448    crate_graph: CrateGraphBuilder,
449    proc_macros: ProcMacrosBuilder,
450    source_root_config: SourceRootConfig,
451    vfs: &mut vfs::Vfs,
452    receiver: &Receiver<vfs::loader::Message>,
453    db: &mut RootDatabase,
454) {
455    let mut analysis_change = ChangeWithProcMacros::default();
456
457    db.enable_proc_attr_macros();
458
459    // wait until Vfs has loaded all roots
460    for task in receiver {
461        match task {
462            vfs::loader::Message::Progress { n_done, .. } => {
463                if n_done == LoadingProgress::Finished {
464                    break;
465                }
466            }
467            vfs::loader::Message::Loaded { files } | vfs::loader::Message::Changed { files } => {
468                let _p =
469                    tracing::info_span!("load_cargo::load_crate_craph/LoadedChanged").entered();
470                for (path, contents) in files {
471                    vfs.set_file_contents(path.into(), contents);
472                }
473            }
474        }
475    }
476    let changes = vfs.take_changes();
477    for (_, file) in changes {
478        if let vfs::Change::Create(v, _) | vfs::Change::Modify(v, _) = file.change
479            && let Ok(text) = String::from_utf8(v)
480        {
481            analysis_change.change_file(file.file_id, Some(text))
482        }
483    }
484    let source_roots = source_root_config.partition(vfs);
485    analysis_change.set_roots(source_roots);
486
487    analysis_change.set_crate_graph(crate_graph);
488    analysis_change.set_proc_macros(proc_macros);
489
490    db.apply_change(analysis_change);
491}
492
493fn expander_to_proc_macro(
494    expander: proc_macro_api::ProcMacro,
495    ignored_macros: &[Box<str>],
496) -> ProcMacro {
497    let name = expander.name();
498    let kind = match expander.kind() {
499        proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
500        proc_macro_api::ProcMacroKind::Bang => ProcMacroKind::Bang,
501        proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
502    };
503    let disabled = ignored_macros.iter().any(|replace| **replace == *name);
504    ProcMacro {
505        name: intern::Symbol::intern(name),
506        kind,
507        expander: sync::Arc::new(Expander(expander)),
508        disabled,
509    }
510}
511
512#[derive(Debug, PartialEq, Eq)]
513struct Expander(proc_macro_api::ProcMacro);
514
515impl ProcMacroExpander for Expander {
516    fn expand(
517        &self,
518        subtree: &tt::TopSubtree<Span>,
519        attrs: Option<&tt::TopSubtree<Span>>,
520        env: &Env,
521        def_site: Span,
522        call_site: Span,
523        mixed_site: Span,
524        current_dir: String,
525    ) -> Result<tt::TopSubtree<Span>, ProcMacroExpansionError> {
526        match self.0.expand(
527            subtree.view(),
528            attrs.map(|attrs| attrs.view()),
529            env.clone().into(),
530            def_site,
531            call_site,
532            mixed_site,
533            current_dir,
534        ) {
535            Ok(Ok(subtree)) => Ok(subtree),
536            Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err)),
537            Err(err) => Err(ProcMacroExpansionError::System(err.to_string())),
538        }
539    }
540
541    fn eq_dyn(&self, other: &dyn ProcMacroExpander) -> bool {
542        (other as &dyn Any).downcast_ref::<Self>() == Some(self)
543    }
544}
545
546#[cfg(test)]
547mod tests {
548    use ide_db::base_db::RootQueryDb;
549    use vfs::file_set::FileSetConfigBuilder;
550
551    use super::*;
552
553    #[test]
554    fn test_loading_rust_analyzer() {
555        let path = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap().parent().unwrap();
556        let cargo_config = CargoConfig { set_test: true, ..CargoConfig::default() };
557        let load_cargo_config = LoadCargoConfig {
558            load_out_dirs_from_check: false,
559            with_proc_macro_server: ProcMacroServerChoice::None,
560            prefill_caches: false,
561        };
562        let (db, _vfs, _proc_macro) =
563            load_workspace_at(path, &cargo_config, &load_cargo_config, &|_| {}).unwrap();
564
565        let n_crates = db.all_crates().len();
566        // RA has quite a few crates, but the exact count doesn't matter
567        assert!(n_crates > 20);
568    }
569
570    #[test]
571    fn unrelated_sources() {
572        let mut builder = FileSetConfigBuilder::default();
573        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
574        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def".to_owned())]);
575        let fsc = builder.build();
576        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1] };
577        let vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
578
579        assert_eq!(vc, vec![])
580    }
581
582    #[test]
583    fn unrelated_source_sharing_dirname() {
584        let mut builder = FileSetConfigBuilder::default();
585        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
586        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/abc".to_owned())]);
587        let fsc = builder.build();
588        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1] };
589        let vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
590
591        assert_eq!(vc, vec![])
592    }
593
594    #[test]
595    fn basic_child_parent() {
596        let mut builder = FileSetConfigBuilder::default();
597        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
598        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc/def".to_owned())]);
599        let fsc = builder.build();
600        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1] };
601        let vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
602
603        assert_eq!(vc, vec![(SourceRootId(1), SourceRootId(0))])
604    }
605
606    #[test]
607    fn basic_child_parent_with_unrelated_parents_sib() {
608        let mut builder = FileSetConfigBuilder::default();
609        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
610        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def".to_owned())]);
611        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/abc".to_owned())]);
612        let fsc = builder.build();
613        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1, 2] };
614        let vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
615
616        assert_eq!(vc, vec![(SourceRootId(2), SourceRootId(1))])
617    }
618
619    #[test]
620    fn deep_sources_with_parent_missing() {
621        let mut builder = FileSetConfigBuilder::default();
622        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
623        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/ghi".to_owned())]);
624        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/abc".to_owned())]);
625        let fsc = builder.build();
626        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1, 2] };
627        let vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
628
629        assert_eq!(vc, vec![])
630    }
631
632    #[test]
633    fn ancestor_can_be_parent() {
634        let mut builder = FileSetConfigBuilder::default();
635        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
636        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def".to_owned())]);
637        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/ghi/jkl".to_owned())]);
638        let fsc = builder.build();
639        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1, 2] };
640        let vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
641
642        assert_eq!(vc, vec![(SourceRootId(2), SourceRootId(1))])
643    }
644
645    #[test]
646    fn ancestor_can_be_parent_2() {
647        let mut builder = FileSetConfigBuilder::default();
648        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
649        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def".to_owned())]);
650        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/ghi/jkl".to_owned())]);
651        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/ghi/klm".to_owned())]);
652        let fsc = builder.build();
653        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1, 2, 3] };
654        let mut vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
655        vc.sort_by(|x, y| x.0.0.cmp(&y.0.0));
656
657        assert_eq!(vc, vec![(SourceRootId(2), SourceRootId(1)), (SourceRootId(3), SourceRootId(1))])
658    }
659
660    #[test]
661    fn non_locals_are_skipped() {
662        let mut builder = FileSetConfigBuilder::default();
663        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
664        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def".to_owned())]);
665        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/ghi/jkl".to_owned())]);
666        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/klm".to_owned())]);
667        let fsc = builder.build();
668        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1, 3] };
669        let mut vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
670        vc.sort_by(|x, y| x.0.0.cmp(&y.0.0));
671
672        assert_eq!(vc, vec![(SourceRootId(3), SourceRootId(1)),])
673    }
674
675    #[test]
676    fn child_binds_ancestor_if_parent_nonlocal() {
677        let mut builder = FileSetConfigBuilder::default();
678        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/abc".to_owned())]);
679        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def".to_owned())]);
680        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/klm".to_owned())]);
681        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/klm/jkl".to_owned())]);
682        let fsc = builder.build();
683        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1, 3] };
684        let mut vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
685        vc.sort_by(|x, y| x.0.0.cmp(&y.0.0));
686
687        assert_eq!(vc, vec![(SourceRootId(3), SourceRootId(1)),])
688    }
689
690    #[test]
691    fn parents_with_identical_root_id() {
692        let mut builder = FileSetConfigBuilder::default();
693        builder.add_file_set(vec![
694            VfsPath::new_virtual_path("/ROOT/def".to_owned()),
695            VfsPath::new_virtual_path("/ROOT/def/abc/def".to_owned()),
696        ]);
697        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/abc/def/ghi".to_owned())]);
698        let fsc = builder.build();
699        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1] };
700        let mut vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
701        vc.sort_by(|x, y| x.0.0.cmp(&y.0.0));
702
703        assert_eq!(vc, vec![(SourceRootId(1), SourceRootId(0)),])
704    }
705
706    #[test]
707    fn circular_reference() {
708        let mut builder = FileSetConfigBuilder::default();
709        builder.add_file_set(vec![
710            VfsPath::new_virtual_path("/ROOT/def".to_owned()),
711            VfsPath::new_virtual_path("/ROOT/def/abc/def".to_owned()),
712        ]);
713        builder.add_file_set(vec![VfsPath::new_virtual_path("/ROOT/def/abc".to_owned())]);
714        let fsc = builder.build();
715        let src = SourceRootConfig { fsc, local_filesets: vec![0, 1] };
716        let mut vc = src.source_root_parent_map().into_iter().collect::<Vec<_>>();
717        vc.sort_by(|x, y| x.0.0.cmp(&y.0.0));
718
719        assert_eq!(vc, vec![(SourceRootId(1), SourceRootId(0)),])
720    }
721}