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