]> git.lizzy.rs Git - rust.git/blob - crates/ra_project_model/src/lib.rs
Merge branch 'fix_renaming_mod_in_use_tree' of https://github.com/unexge/rust-analyze...
[rust.git] / crates / ra_project_model / src / lib.rs
1 //! FIXME: write short doc here
2
3 mod cargo_workspace;
4 mod json_project;
5 mod sysroot;
6
7 use std::{
8     fs::{read_dir, File, ReadDir},
9     io::{self, BufReader},
10     path::{Path, PathBuf},
11     process::{Command, Output},
12 };
13
14 use anyhow::{bail, Context, Result};
15 use ra_cfg::CfgOptions;
16 use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId};
17 use rustc_hash::{FxHashMap, FxHashSet};
18 use serde_json::from_reader;
19
20 pub use crate::{
21     cargo_workspace::{CargoConfig, CargoWorkspace, Package, Target, TargetKind},
22     json_project::JsonProject,
23     sysroot::Sysroot,
24 };
25 pub use ra_proc_macro::ProcMacroClient;
26
27 #[derive(Debug, Clone)]
28 pub enum ProjectWorkspace {
29     /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
30     Cargo { cargo: CargoWorkspace, sysroot: Sysroot },
31     /// Project workspace was manually specified using a `rust-project.json` file.
32     Json { project: JsonProject, project_location: PathBuf },
33 }
34
35 /// `PackageRoot` describes a package root folder.
36 /// Which may be an external dependency, or a member of
37 /// the current workspace.
38 #[derive(Debug, Clone)]
39 pub struct PackageRoot {
40     /// Path to the root folder
41     path: PathBuf,
42     /// Is a member of the current workspace
43     is_member: bool,
44     out_dir: Option<PathBuf>,
45 }
46 impl PackageRoot {
47     pub fn new_member(path: PathBuf) -> PackageRoot {
48         Self { path, is_member: true, out_dir: None }
49     }
50     pub fn new_non_member(path: PathBuf) -> PackageRoot {
51         Self { path, is_member: false, out_dir: None }
52     }
53     pub fn path(&self) -> &Path {
54         &self.path
55     }
56     pub fn out_dir(&self) -> Option<&Path> {
57         self.out_dir.as_deref()
58     }
59     pub fn is_member(&self) -> bool {
60         self.is_member
61     }
62 }
63
64 #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
65 pub enum ProjectManifest {
66     ProjectJson(PathBuf),
67     CargoToml(PathBuf),
68 }
69
70 impl ProjectManifest {
71     pub fn from_manifest_file(path: PathBuf) -> Result<ProjectManifest> {
72         if path.ends_with("rust-project.json") {
73             return Ok(ProjectManifest::ProjectJson(path));
74         }
75         if path.ends_with("Cargo.toml") {
76             return Ok(ProjectManifest::CargoToml(path));
77         }
78         bail!("project root must point to Cargo.toml or rust-project.json: {}", path.display())
79     }
80
81     pub fn discover_single(path: &Path) -> Result<ProjectManifest> {
82         let mut candidates = ProjectManifest::discover(path)?;
83         let res = match candidates.pop() {
84             None => bail!("no projects"),
85             Some(it) => it,
86         };
87
88         if !candidates.is_empty() {
89             bail!("more than one project")
90         }
91         Ok(res)
92     }
93
94     pub fn discover(path: &Path) -> io::Result<Vec<ProjectManifest>> {
95         if let Some(project_json) = find_in_parent_dirs(path, "rust-project.json") {
96             return Ok(vec![ProjectManifest::ProjectJson(project_json)]);
97         }
98         return find_cargo_toml(path)
99             .map(|paths| paths.into_iter().map(ProjectManifest::CargoToml).collect());
100
101         fn find_cargo_toml(path: &Path) -> io::Result<Vec<PathBuf>> {
102             match find_in_parent_dirs(path, "Cargo.toml") {
103                 Some(it) => Ok(vec![it]),
104                 None => Ok(find_cargo_toml_in_child_dir(read_dir(path)?)),
105             }
106         }
107
108         fn find_in_parent_dirs(path: &Path, target_file_name: &str) -> Option<PathBuf> {
109             if path.ends_with(target_file_name) {
110                 return Some(path.to_owned());
111             }
112
113             let mut curr = Some(path);
114
115             while let Some(path) = curr {
116                 let candidate = path.join(target_file_name);
117                 if candidate.exists() {
118                     return Some(candidate);
119                 }
120                 curr = path.parent();
121             }
122
123             None
124         }
125
126         fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec<PathBuf> {
127             // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects
128             entities
129                 .filter_map(Result::ok)
130                 .map(|it| it.path().join("Cargo.toml"))
131                 .filter(|it| it.exists())
132                 .collect()
133         }
134     }
135
136     pub fn discover_all(paths: &[impl AsRef<Path>]) -> Vec<ProjectManifest> {
137         let mut res = paths
138             .iter()
139             .filter_map(|it| ProjectManifest::discover(it.as_ref()).ok())
140             .flatten()
141             .collect::<FxHashSet<_>>()
142             .into_iter()
143             .collect::<Vec<_>>();
144         res.sort();
145         res
146     }
147 }
148
149 impl ProjectWorkspace {
150     pub fn load(
151         manifest: ProjectManifest,
152         cargo_features: &CargoConfig,
153         with_sysroot: bool,
154     ) -> Result<ProjectWorkspace> {
155         let res = match manifest {
156             ProjectManifest::ProjectJson(project_json) => {
157                 let file = File::open(&project_json).with_context(|| {
158                     format!("Failed to open json file {}", project_json.display())
159                 })?;
160                 let reader = BufReader::new(file);
161                 let project_location = match project_json.parent() {
162                     Some(parent) => PathBuf::from(parent),
163                     None => PathBuf::new(),
164                 };
165                 ProjectWorkspace::Json {
166                     project: from_reader(reader).with_context(|| {
167                         format!("Failed to deserialize json file {}", project_json.display())
168                     })?,
169                     project_location: project_location,
170                 }
171             }
172             ProjectManifest::CargoToml(cargo_toml) => {
173                 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, cargo_features)
174                     .with_context(|| {
175                         format!(
176                             "Failed to read Cargo metadata from Cargo.toml file {}",
177                             cargo_toml.display()
178                         )
179                     })?;
180                 let sysroot = if with_sysroot {
181                     Sysroot::discover(&cargo_toml).with_context(|| {
182                         format!(
183                             "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
184                             cargo_toml.display()
185                         )
186                     })?
187                 } else {
188                     Sysroot::default()
189                 };
190                 ProjectWorkspace::Cargo { cargo, sysroot }
191             }
192         };
193
194         Ok(res)
195     }
196
197     /// Returns the roots for the current `ProjectWorkspace`
198     /// The return type contains the path and whether or not
199     /// the root is a member of the current workspace
200     pub fn to_roots(&self) -> Vec<PackageRoot> {
201         match self {
202             ProjectWorkspace::Json { project, project_location } => project
203                 .roots
204                 .iter()
205                 .map(|r| PackageRoot::new_member(project_location.join(&r.path)))
206                 .collect(),
207             ProjectWorkspace::Cargo { cargo, sysroot } => cargo
208                 .packages()
209                 .map(|pkg| PackageRoot {
210                     path: cargo[pkg].root().to_path_buf(),
211                     is_member: cargo[pkg].is_member,
212                     out_dir: cargo[pkg].out_dir.clone(),
213                 })
214                 .chain(sysroot.crates().map(|krate| {
215                     PackageRoot::new_non_member(sysroot[krate].root_dir().to_path_buf())
216                 }))
217                 .collect(),
218         }
219     }
220
221     pub fn proc_macro_dylib_paths(&self) -> Vec<PathBuf> {
222         match self {
223             ProjectWorkspace::Json { project, .. } => project
224                 .crates
225                 .iter()
226                 .filter_map(|krate| krate.proc_macro_dylib_path.as_ref())
227                 .cloned()
228                 .collect(),
229             ProjectWorkspace::Cargo { cargo, sysroot: _sysroot } => cargo
230                 .packages()
231                 .filter_map(|pkg| cargo[pkg].proc_macro_dylib_path.as_ref())
232                 .cloned()
233                 .collect(),
234         }
235     }
236
237     pub fn n_packages(&self) -> usize {
238         match self {
239             ProjectWorkspace::Json { project, .. } => project.crates.len(),
240             ProjectWorkspace::Cargo { cargo, sysroot } => {
241                 cargo.packages().len() + sysroot.crates().len()
242             }
243         }
244     }
245
246     pub fn to_crate_graph(
247         &self,
248         target: Option<&str>,
249         extern_source_roots: &FxHashMap<PathBuf, ExternSourceId>,
250         proc_macro_client: &ProcMacroClient,
251         load: &mut dyn FnMut(&Path) -> Option<FileId>,
252     ) -> CrateGraph {
253         let mut crate_graph = CrateGraph::default();
254         match self {
255             ProjectWorkspace::Json { project, project_location } => {
256                 let crates: FxHashMap<_, _> = project
257                     .crates
258                     .iter()
259                     .enumerate()
260                     .filter_map(|(seq_index, krate)| {
261                         let file_path = project_location.join(&krate.root_module);
262                         let file_id = load(&file_path)?;
263                         let edition = match krate.edition {
264                             json_project::Edition::Edition2015 => Edition::Edition2015,
265                             json_project::Edition::Edition2018 => Edition::Edition2018,
266                         };
267                         let cfg_options = {
268                             let mut opts = CfgOptions::default();
269                             for cfg in &krate.cfg {
270                                 match cfg.find('=') {
271                                     None => opts.insert_atom(cfg.into()),
272                                     Some(pos) => {
273                                         let key = &cfg[..pos];
274                                         let value = cfg[pos + 1..].trim_matches('"');
275                                         opts.insert_key_value(key.into(), value.into());
276                                     }
277                                 }
278                             }
279                             opts
280                         };
281
282                         let mut env = Env::default();
283                         let mut extern_source = ExternSource::default();
284                         if let Some(out_dir) = &krate.out_dir {
285                             // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
286                             if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
287                                 env.set("OUT_DIR", out_dir);
288                             }
289                             if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
290                                 extern_source.set_extern_path(&out_dir, extern_source_id);
291                             }
292                         }
293                         let proc_macro = krate
294                             .proc_macro_dylib_path
295                             .clone()
296                             .map(|it| proc_macro_client.by_dylib_path(&it));
297                         // FIXME: No crate name in json definition such that we cannot add OUT_DIR to env
298                         Some((
299                             json_project::CrateId(seq_index),
300                             crate_graph.add_crate_root(
301                                 file_id,
302                                 edition,
303                                 // FIXME json definitions can store the crate name
304                                 None,
305                                 cfg_options,
306                                 env,
307                                 extern_source,
308                                 proc_macro.unwrap_or_default(),
309                             ),
310                         ))
311                     })
312                     .collect();
313
314                 for (id, krate) in project.crates.iter().enumerate() {
315                     for dep in &krate.deps {
316                         let from_crate_id = json_project::CrateId(id);
317                         let to_crate_id = dep.krate;
318                         if let (Some(&from), Some(&to)) =
319                             (crates.get(&from_crate_id), crates.get(&to_crate_id))
320                         {
321                             if crate_graph
322                                 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
323                                 .is_err()
324                             {
325                                 log::error!(
326                                     "cyclic dependency {:?} -> {:?}",
327                                     from_crate_id,
328                                     to_crate_id
329                                 );
330                             }
331                         }
332                     }
333                 }
334             }
335             ProjectWorkspace::Cargo { cargo, sysroot } => {
336                 let mut cfg_options = get_rustc_cfg_options(target);
337
338                 let sysroot_crates: FxHashMap<_, _> = sysroot
339                     .crates()
340                     .filter_map(|krate| {
341                         let file_id = load(&sysroot[krate].root)?;
342
343                         let env = Env::default();
344                         let extern_source = ExternSource::default();
345                         let proc_macro = vec![];
346                         let crate_name = CrateName::new(&sysroot[krate].name)
347                             .expect("Sysroot crate names should not contain dashes");
348
349                         let crate_id = crate_graph.add_crate_root(
350                             file_id,
351                             Edition::Edition2018,
352                             Some(crate_name),
353                             cfg_options.clone(),
354                             env,
355                             extern_source,
356                             proc_macro,
357                         );
358                         Some((krate, crate_id))
359                     })
360                     .collect();
361
362                 for from in sysroot.crates() {
363                     for &to in sysroot[from].deps.iter() {
364                         let name = &sysroot[to].name;
365                         if let (Some(&from), Some(&to)) =
366                             (sysroot_crates.get(&from), sysroot_crates.get(&to))
367                         {
368                             if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
369                             {
370                                 log::error!("cyclic dependency between sysroot crates")
371                             }
372                         }
373                     }
374                 }
375
376                 let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied());
377                 let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied());
378                 let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied());
379                 let libproc_macro =
380                     sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
381
382                 let mut pkg_to_lib_crate = FxHashMap::default();
383                 let mut pkg_crates = FxHashMap::default();
384
385                 // Add test cfg for non-sysroot crates
386                 cfg_options.insert_atom("test".into());
387
388                 // Next, create crates for each package, target pair
389                 for pkg in cargo.packages() {
390                     let mut lib_tgt = None;
391                     for &tgt in cargo[pkg].targets.iter() {
392                         let root = cargo[tgt].root.as_path();
393                         if let Some(file_id) = load(root) {
394                             let edition = cargo[pkg].edition;
395                             let cfg_options = {
396                                 let mut opts = cfg_options.clone();
397                                 for feature in cargo[pkg].features.iter() {
398                                     opts.insert_key_value("feature".into(), feature.into());
399                                 }
400                                 for cfg in cargo[pkg].cfgs.iter() {
401                                     match cfg.find('=') {
402                                         Some(split) => opts.insert_key_value(
403                                             cfg[..split].into(),
404                                             cfg[split + 1..].trim_matches('"').into(),
405                                         ),
406                                         None => opts.insert_atom(cfg.into()),
407                                     };
408                                 }
409                                 opts
410                             };
411                             let mut env = Env::default();
412                             let mut extern_source = ExternSource::default();
413                             if let Some(out_dir) = &cargo[pkg].out_dir {
414                                 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
415                                 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
416                                     env.set("OUT_DIR", out_dir);
417                                 }
418                                 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
419                                     extern_source.set_extern_path(&out_dir, extern_source_id);
420                                 }
421                             }
422                             let proc_macro = cargo[pkg]
423                                 .proc_macro_dylib_path
424                                 .as_ref()
425                                 .map(|it| proc_macro_client.by_dylib_path(&it))
426                                 .unwrap_or_default();
427
428                             let crate_id = crate_graph.add_crate_root(
429                                 file_id,
430                                 edition,
431                                 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
432                                 cfg_options,
433                                 env,
434                                 extern_source,
435                                 proc_macro.clone(),
436                             );
437                             if cargo[tgt].kind == TargetKind::Lib {
438                                 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
439                                 pkg_to_lib_crate.insert(pkg, crate_id);
440                             }
441                             if cargo[tgt].is_proc_macro {
442                                 if let Some(proc_macro) = libproc_macro {
443                                     if crate_graph
444                                         .add_dep(
445                                             crate_id,
446                                             CrateName::new("proc_macro").unwrap(),
447                                             proc_macro,
448                                         )
449                                         .is_err()
450                                     {
451                                         log::error!(
452                                             "cyclic dependency on proc_macro for {}",
453                                             &cargo[pkg].name
454                                         )
455                                     }
456                                 }
457                             }
458
459                             pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
460                         }
461                     }
462
463                     // Set deps to the core, std and to the lib target of the current package
464                     for &from in pkg_crates.get(&pkg).into_iter().flatten() {
465                         if let Some((to, name)) = lib_tgt.clone() {
466                             if to != from
467                                 && crate_graph
468                                     .add_dep(
469                                         from,
470                                         // For root projects with dashes in their name,
471                                         // cargo metadata does not do any normalization,
472                                         // so we do it ourselves currently
473                                         CrateName::normalize_dashes(&name),
474                                         to,
475                                     )
476                                     .is_err()
477                             {
478                                 {
479                                     log::error!(
480                                         "cyclic dependency between targets of {}",
481                                         &cargo[pkg].name
482                                     )
483                                 }
484                             }
485                         }
486                         // core is added as a dependency before std in order to
487                         // mimic rustcs dependency order
488                         if let Some(core) = libcore {
489                             if crate_graph
490                                 .add_dep(from, CrateName::new("core").unwrap(), core)
491                                 .is_err()
492                             {
493                                 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
494                             }
495                         }
496                         if let Some(alloc) = liballoc {
497                             if crate_graph
498                                 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
499                                 .is_err()
500                             {
501                                 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
502                             }
503                         }
504                         if let Some(std) = libstd {
505                             if crate_graph
506                                 .add_dep(from, CrateName::new("std").unwrap(), std)
507                                 .is_err()
508                             {
509                                 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
510                             }
511                         }
512                     }
513                 }
514
515                 // Now add a dep edge from all targets of upstream to the lib
516                 // target of downstream.
517                 for pkg in cargo.packages() {
518                     for dep in cargo[pkg].dependencies.iter() {
519                         if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
520                             for &from in pkg_crates.get(&pkg).into_iter().flatten() {
521                                 if crate_graph
522                                     .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
523                                     .is_err()
524                                 {
525                                     log::error!(
526                                         "cyclic dependency {} -> {}",
527                                         &cargo[pkg].name,
528                                         &cargo[dep.pkg].name
529                                     )
530                                 }
531                             }
532                         }
533                     }
534                 }
535             }
536         }
537         crate_graph
538     }
539
540     pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
541         match self {
542             ProjectWorkspace::Cargo { cargo, .. } => {
543                 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
544             }
545             ProjectWorkspace::Json { project: JsonProject { roots, .. }, .. } => roots
546                 .iter()
547                 .find(|root| path.starts_with(&root.path))
548                 .map(|root| root.path.as_ref()),
549         }
550     }
551 }
552
553 fn get_rustc_cfg_options(target: Option<&str>) -> CfgOptions {
554     let mut cfg_options = CfgOptions::default();
555
556     // Some nightly-only cfgs, which are required for stdlib
557     {
558         cfg_options.insert_atom("target_thread_local".into());
559         for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() {
560             cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into());
561             cfg_options
562                 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
563         }
564     }
565
566     let rustc_cfgs = || -> Result<String> {
567         // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
568         let mut cmd = Command::new(ra_toolchain::rustc());
569         cmd.args(&["--print", "cfg", "-O"]);
570         if let Some(target) = target {
571             cmd.args(&["--target", target]);
572         }
573         let output = output(cmd)?;
574         Ok(String::from_utf8(output.stdout)?)
575     }();
576
577     match rustc_cfgs {
578         Ok(rustc_cfgs) => {
579             for line in rustc_cfgs.lines() {
580                 match line.find('=') {
581                     None => cfg_options.insert_atom(line.into()),
582                     Some(pos) => {
583                         let key = &line[..pos];
584                         let value = line[pos + 1..].trim_matches('"');
585                         cfg_options.insert_key_value(key.into(), value.into());
586                     }
587                 }
588             }
589         }
590         Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
591     }
592
593     cfg_options.insert_atom("debug_assertions".into());
594
595     cfg_options
596 }
597
598 fn output(mut cmd: Command) -> Result<Output> {
599     let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
600     if !output.status.success() {
601         match String::from_utf8(output.stderr) {
602             Ok(stderr) if !stderr.is_empty() => {
603                 bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr)
604             }
605             _ => bail!("{:?} failed, {}", cmd, output.status),
606         }
607     }
608     Ok(output)
609 }