]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/cli/load_cargo.rs
Merge #4273
[rust.git] / crates / rust-analyzer / src / cli / load_cargo.rs
1 //! Loads a Cargo project into a static instance of analysis, without support
2 //! for incorporating changes.
3
4 use std::path::{Path, PathBuf};
5
6 use anyhow::Result;
7 use crossbeam_channel::{unbounded, Receiver};
8 use ra_db::{ExternSourceId, FileId, SourceRootId};
9 use ra_ide::{AnalysisChange, AnalysisHost};
10 use ra_project_model::{
11     get_rustc_cfg_options, CargoConfig, PackageRoot, ProcMacroClient, ProjectRoot, ProjectWorkspace,
12 };
13 use ra_vfs::{RootEntry, Vfs, VfsChange, VfsTask, Watch};
14 use rustc_hash::{FxHashMap, FxHashSet};
15
16 use crate::vfs_glob::RustPackageFilterBuilder;
17
18 fn vfs_file_to_id(f: ra_vfs::VfsFile) -> FileId {
19     FileId(f.0)
20 }
21 fn vfs_root_to_id(r: ra_vfs::VfsRoot) -> SourceRootId {
22     SourceRootId(r.0)
23 }
24
25 pub fn load_cargo(
26     root: &Path,
27     load_out_dirs_from_check: bool,
28     with_proc_macro: bool,
29 ) -> Result<(AnalysisHost, FxHashMap<SourceRootId, PackageRoot>)> {
30     let root = std::env::current_dir()?.join(root);
31     let root = ProjectRoot::discover_single(&root)?;
32     let ws = ProjectWorkspace::load(
33         root,
34         &CargoConfig { load_out_dirs_from_check, ..Default::default() },
35         true,
36     )?;
37
38     let mut extern_dirs = FxHashSet::default();
39     extern_dirs.extend(ws.out_dirs());
40
41     let mut project_roots = ws.to_roots();
42     project_roots.extend(extern_dirs.iter().cloned().map(PackageRoot::new_non_member));
43
44     let (sender, receiver) = unbounded();
45     let sender = Box::new(move |t| sender.send(t).unwrap());
46     let (mut vfs, roots) = Vfs::new(
47         project_roots
48             .iter()
49             .map(|pkg_root| {
50                 RootEntry::new(
51                     pkg_root.path().to_owned(),
52                     RustPackageFilterBuilder::default()
53                         .set_member(pkg_root.is_member())
54                         .into_vfs_filter(),
55                 )
56             })
57             .collect(),
58         sender,
59         Watch(false),
60     );
61
62     let source_roots = roots
63         .into_iter()
64         .map(|vfs_root| {
65             let source_root_id = vfs_root_to_id(vfs_root);
66             let project_root = project_roots
67                 .iter()
68                 .find(|it| it.path() == vfs.root2path(vfs_root))
69                 .unwrap()
70                 .clone();
71             (source_root_id, project_root)
72         })
73         .collect::<FxHashMap<_, _>>();
74
75     let proc_macro_client = if !with_proc_macro {
76         ProcMacroClient::dummy()
77     } else {
78         let path = std::env::current_exe()?;
79         ProcMacroClient::extern_process(path, &["proc-macro"]).unwrap()
80     };
81     let host = load(&source_roots, ws, &mut vfs, receiver, extern_dirs, &proc_macro_client);
82     Ok((host, source_roots))
83 }
84
85 pub(crate) fn load(
86     source_roots: &FxHashMap<SourceRootId, PackageRoot>,
87     ws: ProjectWorkspace,
88     vfs: &mut Vfs,
89     receiver: Receiver<VfsTask>,
90     extern_dirs: FxHashSet<PathBuf>,
91     proc_macro_client: &ProcMacroClient,
92 ) -> AnalysisHost {
93     let lru_cap = std::env::var("RA_LRU_CAP").ok().and_then(|it| it.parse::<usize>().ok());
94     let mut host = AnalysisHost::new(lru_cap);
95     let mut analysis_change = AnalysisChange::new();
96
97     // wait until Vfs has loaded all roots
98     let mut roots_loaded = FxHashSet::default();
99     let mut extern_source_roots = FxHashMap::default();
100     for task in receiver {
101         vfs.handle_task(task);
102         let mut done = false;
103         for change in vfs.commit_changes() {
104             match change {
105                 VfsChange::AddRoot { root, files } => {
106                     let source_root_id = vfs_root_to_id(root);
107                     let is_local = source_roots[&source_root_id].is_member();
108                     log::debug!(
109                         "loaded source root {:?} with path {:?}",
110                         source_root_id,
111                         vfs.root2path(root)
112                     );
113                     analysis_change.add_root(source_root_id, is_local);
114                     analysis_change.set_debug_root_path(
115                         source_root_id,
116                         source_roots[&source_root_id].path().display().to_string(),
117                     );
118
119                     let vfs_root_path = vfs.root2path(root);
120                     if extern_dirs.contains(&vfs_root_path) {
121                         extern_source_roots.insert(vfs_root_path, ExternSourceId(root.0));
122                     }
123
124                     let mut file_map = FxHashMap::default();
125                     for (vfs_file, path, text) in files {
126                         let file_id = vfs_file_to_id(vfs_file);
127                         analysis_change.add_file(source_root_id, file_id, path.clone(), text);
128                         file_map.insert(path, file_id);
129                     }
130                     roots_loaded.insert(source_root_id);
131                     if roots_loaded.len() == vfs.n_roots() {
132                         done = true;
133                     }
134                 }
135                 VfsChange::AddFile { root, file, path, text } => {
136                     let source_root_id = vfs_root_to_id(root);
137                     let file_id = vfs_file_to_id(file);
138                     analysis_change.add_file(source_root_id, file_id, path, text);
139                 }
140                 VfsChange::RemoveFile { .. } | VfsChange::ChangeFile { .. } => {
141                     // We just need the first scan, so just ignore these
142                 }
143             }
144         }
145         if done {
146             break;
147         }
148     }
149
150     // FIXME: cfg options?
151     let default_cfg_options = {
152         let mut opts = get_rustc_cfg_options(None);
153         opts.insert_atom("test".into());
154         opts.insert_atom("debug_assertion".into());
155         opts
156     };
157
158     let crate_graph = ws.to_crate_graph(
159         &default_cfg_options,
160         &extern_source_roots,
161         proc_macro_client,
162         &mut |path: &Path| {
163             // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
164             let path = path.canonicalize().ok()?;
165             let vfs_file = vfs.load(&path);
166             log::debug!("vfs file {:?} -> {:?}", path, vfs_file);
167             vfs_file.map(vfs_file_to_id)
168         },
169     );
170     log::debug!("crate graph: {:?}", crate_graph);
171     analysis_change.set_crate_graph(crate_graph);
172
173     host.apply_change(analysis_change);
174     host
175 }
176
177 #[cfg(test)]
178 mod tests {
179     use super::*;
180
181     use hir::Crate;
182
183     #[test]
184     fn test_loading_rust_analyzer() {
185         let path = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap().parent().unwrap();
186         let (host, _roots) = load_cargo(path, false, false).unwrap();
187         let n_crates = Crate::all(host.raw_database()).len();
188         // RA has quite a few crates, but the exact count doesn't matter
189         assert!(n_crates > 20);
190     }
191 }