]> git.lizzy.rs Git - rust.git/blob - crates/ra_project_model/src/lib.rs
New VFS
[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, 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         proc_macro_client: &ProcMacroClient,
250         load: &mut dyn FnMut(&Path) -> Option<FileId>,
251     ) -> CrateGraph {
252         let mut crate_graph = CrateGraph::default();
253         match self {
254             ProjectWorkspace::Json { project, project_location } => {
255                 let crates: FxHashMap<_, _> = project
256                     .crates
257                     .iter()
258                     .enumerate()
259                     .filter_map(|(seq_index, krate)| {
260                         let file_path = project_location.join(&krate.root_module);
261                         let file_id = load(&file_path)?;
262                         let edition = match krate.edition {
263                             json_project::Edition::Edition2015 => Edition::Edition2015,
264                             json_project::Edition::Edition2018 => Edition::Edition2018,
265                         };
266                         let cfg_options = {
267                             let mut opts = CfgOptions::default();
268                             for cfg in &krate.cfg {
269                                 match cfg.find('=') {
270                                     None => opts.insert_atom(cfg.into()),
271                                     Some(pos) => {
272                                         let key = &cfg[..pos];
273                                         let value = cfg[pos + 1..].trim_matches('"');
274                                         opts.insert_key_value(key.into(), value.into());
275                                     }
276                                 }
277                             }
278                             opts
279                         };
280
281                         let mut env = Env::default();
282                         if let Some(out_dir) = &krate.out_dir {
283                             // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
284                             if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
285                                 env.set("OUT_DIR", out_dir);
286                             }
287                         }
288                         let proc_macro = krate
289                             .proc_macro_dylib_path
290                             .clone()
291                             .map(|it| proc_macro_client.by_dylib_path(&it));
292                         // FIXME: No crate name in json definition such that we cannot add OUT_DIR to env
293                         Some((
294                             json_project::CrateId(seq_index),
295                             crate_graph.add_crate_root(
296                                 file_id,
297                                 edition,
298                                 // FIXME json definitions can store the crate name
299                                 None,
300                                 cfg_options,
301                                 env,
302                                 proc_macro.unwrap_or_default(),
303                             ),
304                         ))
305                     })
306                     .collect();
307
308                 for (id, krate) in project.crates.iter().enumerate() {
309                     for dep in &krate.deps {
310                         let from_crate_id = json_project::CrateId(id);
311                         let to_crate_id = dep.krate;
312                         if let (Some(&from), Some(&to)) =
313                             (crates.get(&from_crate_id), crates.get(&to_crate_id))
314                         {
315                             if crate_graph
316                                 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
317                                 .is_err()
318                             {
319                                 log::error!(
320                                     "cyclic dependency {:?} -> {:?}",
321                                     from_crate_id,
322                                     to_crate_id
323                                 );
324                             }
325                         }
326                     }
327                 }
328             }
329             ProjectWorkspace::Cargo { cargo, sysroot } => {
330                 let mut cfg_options = get_rustc_cfg_options(target);
331
332                 let sysroot_crates: FxHashMap<_, _> = sysroot
333                     .crates()
334                     .filter_map(|krate| {
335                         let file_id = load(&sysroot[krate].root)?;
336
337                         let env = Env::default();
338                         let proc_macro = vec![];
339                         let crate_name = CrateName::new(&sysroot[krate].name)
340                             .expect("Sysroot crate names should not contain dashes");
341
342                         let crate_id = crate_graph.add_crate_root(
343                             file_id,
344                             Edition::Edition2018,
345                             Some(crate_name),
346                             cfg_options.clone(),
347                             env,
348                             proc_macro,
349                         );
350                         Some((krate, crate_id))
351                     })
352                     .collect();
353
354                 for from in sysroot.crates() {
355                     for &to in sysroot[from].deps.iter() {
356                         let name = &sysroot[to].name;
357                         if let (Some(&from), Some(&to)) =
358                             (sysroot_crates.get(&from), sysroot_crates.get(&to))
359                         {
360                             if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
361                             {
362                                 log::error!("cyclic dependency between sysroot crates")
363                             }
364                         }
365                     }
366                 }
367
368                 let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied());
369                 let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied());
370                 let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied());
371                 let libproc_macro =
372                     sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
373
374                 let mut pkg_to_lib_crate = FxHashMap::default();
375                 let mut pkg_crates = FxHashMap::default();
376
377                 // Add test cfg for non-sysroot crates
378                 cfg_options.insert_atom("test".into());
379
380                 // Next, create crates for each package, target pair
381                 for pkg in cargo.packages() {
382                     let mut lib_tgt = None;
383                     for &tgt in cargo[pkg].targets.iter() {
384                         let root = cargo[tgt].root.as_path();
385                         if let Some(file_id) = load(root) {
386                             let edition = cargo[pkg].edition;
387                             let cfg_options = {
388                                 let mut opts = cfg_options.clone();
389                                 for feature in cargo[pkg].features.iter() {
390                                     opts.insert_key_value("feature".into(), feature.into());
391                                 }
392                                 for cfg in cargo[pkg].cfgs.iter() {
393                                     match cfg.find('=') {
394                                         Some(split) => opts.insert_key_value(
395                                             cfg[..split].into(),
396                                             cfg[split + 1..].trim_matches('"').into(),
397                                         ),
398                                         None => opts.insert_atom(cfg.into()),
399                                     };
400                                 }
401                                 opts
402                             };
403                             let mut env = Env::default();
404                             if let Some(out_dir) = &cargo[pkg].out_dir {
405                                 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
406                                 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
407                                     env.set("OUT_DIR", out_dir);
408                                 }
409                             }
410                             let proc_macro = cargo[pkg]
411                                 .proc_macro_dylib_path
412                                 .as_ref()
413                                 .map(|it| proc_macro_client.by_dylib_path(&it))
414                                 .unwrap_or_default();
415
416                             let crate_id = crate_graph.add_crate_root(
417                                 file_id,
418                                 edition,
419                                 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
420                                 cfg_options,
421                                 env,
422                                 proc_macro.clone(),
423                             );
424                             if cargo[tgt].kind == TargetKind::Lib {
425                                 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
426                                 pkg_to_lib_crate.insert(pkg, crate_id);
427                             }
428                             if cargo[tgt].is_proc_macro {
429                                 if let Some(proc_macro) = libproc_macro {
430                                     if crate_graph
431                                         .add_dep(
432                                             crate_id,
433                                             CrateName::new("proc_macro").unwrap(),
434                                             proc_macro,
435                                         )
436                                         .is_err()
437                                     {
438                                         log::error!(
439                                             "cyclic dependency on proc_macro for {}",
440                                             &cargo[pkg].name
441                                         )
442                                     }
443                                 }
444                             }
445
446                             pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
447                         }
448                     }
449
450                     // Set deps to the core, std and to the lib target of the current package
451                     for &from in pkg_crates.get(&pkg).into_iter().flatten() {
452                         if let Some((to, name)) = lib_tgt.clone() {
453                             if to != from
454                                 && crate_graph
455                                     .add_dep(
456                                         from,
457                                         // For root projects with dashes in their name,
458                                         // cargo metadata does not do any normalization,
459                                         // so we do it ourselves currently
460                                         CrateName::normalize_dashes(&name),
461                                         to,
462                                     )
463                                     .is_err()
464                             {
465                                 {
466                                     log::error!(
467                                         "cyclic dependency between targets of {}",
468                                         &cargo[pkg].name
469                                     )
470                                 }
471                             }
472                         }
473                         // core is added as a dependency before std in order to
474                         // mimic rustcs dependency order
475                         if let Some(core) = libcore {
476                             if crate_graph
477                                 .add_dep(from, CrateName::new("core").unwrap(), core)
478                                 .is_err()
479                             {
480                                 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
481                             }
482                         }
483                         if let Some(alloc) = liballoc {
484                             if crate_graph
485                                 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
486                                 .is_err()
487                             {
488                                 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
489                             }
490                         }
491                         if let Some(std) = libstd {
492                             if crate_graph
493                                 .add_dep(from, CrateName::new("std").unwrap(), std)
494                                 .is_err()
495                             {
496                                 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
497                             }
498                         }
499                     }
500                 }
501
502                 // Now add a dep edge from all targets of upstream to the lib
503                 // target of downstream.
504                 for pkg in cargo.packages() {
505                     for dep in cargo[pkg].dependencies.iter() {
506                         if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
507                             for &from in pkg_crates.get(&pkg).into_iter().flatten() {
508                                 if crate_graph
509                                     .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
510                                     .is_err()
511                                 {
512                                     log::error!(
513                                         "cyclic dependency {} -> {}",
514                                         &cargo[pkg].name,
515                                         &cargo[dep.pkg].name
516                                     )
517                                 }
518                             }
519                         }
520                     }
521                 }
522             }
523         }
524         crate_graph
525     }
526
527     pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
528         match self {
529             ProjectWorkspace::Cargo { cargo, .. } => {
530                 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
531             }
532             ProjectWorkspace::Json { project: JsonProject { roots, .. }, .. } => roots
533                 .iter()
534                 .find(|root| path.starts_with(&root.path))
535                 .map(|root| root.path.as_ref()),
536         }
537     }
538 }
539
540 fn get_rustc_cfg_options(target: Option<&str>) -> CfgOptions {
541     let mut cfg_options = CfgOptions::default();
542
543     // Some nightly-only cfgs, which are required for stdlib
544     {
545         cfg_options.insert_atom("target_thread_local".into());
546         for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() {
547             cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into());
548             cfg_options
549                 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
550         }
551     }
552
553     let rustc_cfgs = || -> Result<String> {
554         // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
555         let mut cmd = Command::new(ra_toolchain::rustc());
556         cmd.args(&["--print", "cfg", "-O"]);
557         if let Some(target) = target {
558             cmd.args(&["--target", target]);
559         }
560         let output = output(cmd)?;
561         Ok(String::from_utf8(output.stdout)?)
562     }();
563
564     match rustc_cfgs {
565         Ok(rustc_cfgs) => {
566             for line in rustc_cfgs.lines() {
567                 match line.find('=') {
568                     None => cfg_options.insert_atom(line.into()),
569                     Some(pos) => {
570                         let key = &line[..pos];
571                         let value = line[pos + 1..].trim_matches('"');
572                         cfg_options.insert_key_value(key.into(), value.into());
573                     }
574                 }
575             }
576         }
577         Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
578     }
579
580     cfg_options.insert_atom("debug_assertions".into());
581
582     cfg_options
583 }
584
585 fn output(mut cmd: Command) -> Result<Output> {
586     let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
587     if !output.status.success() {
588         match String::from_utf8(output.stderr) {
589             Ok(stderr) if !stderr.is_empty() => {
590                 bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr)
591             }
592             _ => bail!("{:?} failed, {}", cmd, output.status),
593         }
594     }
595     Ok(output)
596 }