aboutsummaryrefslogtreecommitdiff
path: root/crates/project_model/src/workspace.rs
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2020-11-13 16:54:31 +0000
committerGitHub <[email protected]>2020-11-13 16:54:31 +0000
commitd1ea9d12fa95d8f8915b44b7a993591fd528d2ba (patch)
treefbfd11e4dbe85cc58c7c195b41a0cb82df43383f /crates/project_model/src/workspace.rs
parent700e5e58b6ae51e7a1fd88b9f8da1bcef5d9ac49 (diff)
parentb1377363dffa042de5d0b3bd753753a97e488c70 (diff)
Merge #6545
6545: Simplify project model r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates/project_model/src/workspace.rs')
-rw-r--r--crates/project_model/src/workspace.rs590
1 files changed, 590 insertions, 0 deletions
diff --git a/crates/project_model/src/workspace.rs b/crates/project_model/src/workspace.rs
new file mode 100644
index 000000000..9ebb0a811
--- /dev/null
+++ b/crates/project_model/src/workspace.rs
@@ -0,0 +1,590 @@
1//! Handles lowering of build-system specific workspace information (`cargo
2//! metadata` or `rust-project.json`) into representation stored in the salsa
3//! database -- `CrateGraph`.
4
5use std::{fmt, fs, path::Component, process::Command};
6
7use anyhow::{Context, Result};
8use base_db::{CrateDisplayName, CrateGraph, CrateId, CrateName, Edition, Env, FileId};
9use cfg::CfgOptions;
10use paths::{AbsPath, AbsPathBuf};
11use proc_macro_api::ProcMacroClient;
12use rustc_hash::{FxHashMap, FxHashSet};
13
14use crate::{
15 cargo_workspace, cfg_flag::CfgFlag, utf8_stdout, CargoConfig, CargoWorkspace, ProjectJson,
16 ProjectManifest, Sysroot, TargetKind,
17};
18
19/// `PackageRoot` describes a package root folder.
20/// Which may be an external dependency, or a member of
21/// the current workspace.
22#[derive(Debug, Clone, Eq, PartialEq, Hash)]
23pub struct PackageRoot {
24 /// Is a member of the current workspace
25 pub is_member: bool,
26 pub include: Vec<AbsPathBuf>,
27 pub exclude: Vec<AbsPathBuf>,
28}
29
30#[derive(Clone, Eq, PartialEq)]
31pub enum ProjectWorkspace {
32 /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
33 Cargo { cargo: CargoWorkspace, sysroot: Sysroot, rustc: Option<CargoWorkspace> },
34 /// Project workspace was manually specified using a `rust-project.json` file.
35 Json { project: ProjectJson, sysroot: Option<Sysroot> },
36}
37
38impl fmt::Debug for ProjectWorkspace {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 match self {
41 ProjectWorkspace::Cargo { cargo, sysroot, rustc } => f
42 .debug_struct("Cargo")
43 .field("n_packages", &cargo.packages().len())
44 .field("n_sysroot_crates", &sysroot.crates().len())
45 .field(
46 "n_rustc_compiler_crates",
47 &rustc.as_ref().map_or(0, |rc| rc.packages().len()),
48 )
49 .finish(),
50 ProjectWorkspace::Json { project, sysroot } => {
51 let mut debug_struct = f.debug_struct("Json");
52 debug_struct.field("n_crates", &project.n_crates());
53 if let Some(sysroot) = sysroot {
54 debug_struct.field("n_sysroot_crates", &sysroot.crates().len());
55 }
56 debug_struct.finish()
57 }
58 }
59 }
60}
61
62impl ProjectWorkspace {
63 pub fn load(manifest: ProjectManifest, config: &CargoConfig) -> Result<ProjectWorkspace> {
64 let res = match manifest {
65 ProjectManifest::ProjectJson(project_json) => {
66 let file = fs::read_to_string(&project_json).with_context(|| {
67 format!("Failed to read json file {}", project_json.display())
68 })?;
69 let data = serde_json::from_str(&file).with_context(|| {
70 format!("Failed to deserialize json file {}", project_json.display())
71 })?;
72 let project_location = project_json.parent().unwrap().to_path_buf();
73 let project = ProjectJson::new(&project_location, data);
74 let sysroot = match &project.sysroot_src {
75 Some(path) => Some(Sysroot::load(path)?),
76 None => None,
77 };
78 ProjectWorkspace::Json { project, sysroot }
79 }
80 ProjectManifest::CargoToml(cargo_toml) => {
81 let cargo_version = utf8_stdout({
82 let mut cmd = Command::new(toolchain::cargo());
83 cmd.arg("--version");
84 cmd
85 })?;
86
87 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, config).with_context(
88 || {
89 format!(
90 "Failed to read Cargo metadata from Cargo.toml file {}, {}",
91 cargo_toml.display(),
92 cargo_version
93 )
94 },
95 )?;
96 let sysroot = if config.no_sysroot {
97 Sysroot::default()
98 } else {
99 Sysroot::discover(&cargo_toml).with_context(|| {
100 format!(
101 "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
102 cargo_toml.display()
103 )
104 })?
105 };
106
107 let rustc = if let Some(rustc_dir) = &config.rustc_source {
108 Some(CargoWorkspace::from_cargo_metadata(&rustc_dir, config).with_context(
109 || format!("Failed to read Cargo metadata for Rust sources"),
110 )?)
111 } else {
112 None
113 };
114
115 ProjectWorkspace::Cargo { cargo, sysroot, rustc }
116 }
117 };
118
119 Ok(res)
120 }
121
122 pub fn load_inline(project_json: ProjectJson) -> Result<ProjectWorkspace> {
123 let sysroot = match &project_json.sysroot_src {
124 Some(path) => Some(Sysroot::load(path)?),
125 None => None,
126 };
127
128 Ok(ProjectWorkspace::Json { project: project_json, sysroot })
129 }
130
131 /// Returns the roots for the current `ProjectWorkspace`
132 /// The return type contains the path and whether or not
133 /// the root is a member of the current workspace
134 pub fn to_roots(&self) -> Vec<PackageRoot> {
135 match self {
136 ProjectWorkspace::Json { project, sysroot } => project
137 .crates()
138 .map(|(_, krate)| PackageRoot {
139 is_member: krate.is_workspace_member,
140 include: krate.include.clone(),
141 exclude: krate.exclude.clone(),
142 })
143 .collect::<FxHashSet<_>>()
144 .into_iter()
145 .chain(sysroot.as_ref().into_iter().flat_map(|sysroot| {
146 sysroot.crates().map(move |krate| PackageRoot {
147 is_member: false,
148 include: vec![sysroot[krate].root_dir().to_path_buf()],
149 exclude: Vec::new(),
150 })
151 }))
152 .collect::<Vec<_>>(),
153 ProjectWorkspace::Cargo { cargo, sysroot, rustc } => {
154 let roots = cargo
155 .packages()
156 .map(|pkg| {
157 let is_member = cargo[pkg].is_member;
158 let pkg_root = cargo[pkg].root().to_path_buf();
159
160 let mut include = vec![pkg_root.clone()];
161 include.extend(cargo[pkg].out_dir.clone());
162
163 let mut exclude = vec![pkg_root.join(".git")];
164 if is_member {
165 exclude.push(pkg_root.join("target"));
166 } else {
167 exclude.push(pkg_root.join("tests"));
168 exclude.push(pkg_root.join("examples"));
169 exclude.push(pkg_root.join("benches"));
170 }
171 PackageRoot { is_member, include, exclude }
172 })
173 .chain(sysroot.crates().map(|krate| PackageRoot {
174 is_member: false,
175 include: vec![sysroot[krate].root_dir().to_path_buf()],
176 exclude: Vec::new(),
177 }));
178 if let Some(rustc_packages) = rustc {
179 roots
180 .chain(rustc_packages.packages().map(|krate| PackageRoot {
181 is_member: false,
182 include: vec![rustc_packages[krate].root().to_path_buf()],
183 exclude: Vec::new(),
184 }))
185 .collect()
186 } else {
187 roots.collect()
188 }
189 }
190 }
191 }
192
193 pub fn n_packages(&self) -> usize {
194 match self {
195 ProjectWorkspace::Json { project, .. } => project.n_crates(),
196 ProjectWorkspace::Cargo { cargo, sysroot, rustc } => {
197 let rustc_package_len = rustc.as_ref().map_or(0, |rc| rc.packages().len());
198 cargo.packages().len() + sysroot.crates().len() + rustc_package_len
199 }
200 }
201 }
202
203 pub fn to_crate_graph(
204 &self,
205 target: Option<&str>,
206 proc_macro_client: &ProcMacroClient,
207 load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
208 ) -> CrateGraph {
209 let mut crate_graph = CrateGraph::default();
210 match self {
211 ProjectWorkspace::Json { project, sysroot } => {
212 let sysroot_dps = sysroot
213 .as_ref()
214 .map(|sysroot| sysroot_to_crate_graph(&mut crate_graph, sysroot, target, load));
215
216 let mut cfg_cache: FxHashMap<Option<&str>, Vec<CfgFlag>> = FxHashMap::default();
217 let crates: FxHashMap<_, _> = project
218 .crates()
219 .filter_map(|(crate_id, krate)| {
220 let file_path = &krate.root_module;
221 let file_id = match load(&file_path) {
222 Some(id) => id,
223 None => {
224 log::error!("failed to load crate root {}", file_path.display());
225 return None;
226 }
227 };
228
229 let env = krate.env.clone().into_iter().collect();
230 let proc_macro = krate
231 .proc_macro_dylib_path
232 .clone()
233 .map(|it| proc_macro_client.by_dylib_path(&it));
234
235 let target = krate.target.as_deref().or(target);
236 let target_cfgs = cfg_cache
237 .entry(target)
238 .or_insert_with(|| get_rustc_cfg_options(target));
239
240 let mut cfg_options = CfgOptions::default();
241 cfg_options.extend(target_cfgs.iter().chain(krate.cfg.iter()).cloned());
242
243 Some((
244 crate_id,
245 crate_graph.add_crate_root(
246 file_id,
247 krate.edition,
248 krate.display_name.clone(),
249 cfg_options,
250 env,
251 proc_macro.unwrap_or_default(),
252 ),
253 ))
254 })
255 .collect();
256
257 for (from, krate) in project.crates() {
258 if let Some(&from) = crates.get(&from) {
259 if let Some((public_deps, _proc_macro)) = &sysroot_dps {
260 for (name, to) in public_deps.iter() {
261 if let Err(_) = crate_graph.add_dep(from, name.clone(), *to) {
262 log::error!("cyclic dependency on {} for {:?}", name, from)
263 }
264 }
265 }
266
267 for dep in &krate.deps {
268 let to_crate_id = dep.crate_id;
269 if let Some(&to) = crates.get(&to_crate_id) {
270 if let Err(_) = crate_graph.add_dep(from, dep.name.clone(), to) {
271 log::error!("cyclic dependency {:?} -> {:?}", from, to);
272 }
273 }
274 }
275 }
276 }
277 }
278 ProjectWorkspace::Cargo { cargo, sysroot, rustc } => {
279 let (public_deps, libproc_macro) =
280 sysroot_to_crate_graph(&mut crate_graph, sysroot, target, load);
281
282 let mut cfg_options = CfgOptions::default();
283 cfg_options.extend(get_rustc_cfg_options(target));
284
285 let mut pkg_to_lib_crate = FxHashMap::default();
286
287 // Add test cfg for non-sysroot crates
288 cfg_options.insert_atom("test".into());
289 cfg_options.insert_atom("debug_assertions".into());
290
291 let mut pkg_crates = FxHashMap::default();
292
293 // Next, create crates for each package, target pair
294 for pkg in cargo.packages() {
295 let mut lib_tgt = None;
296 for &tgt in cargo[pkg].targets.iter() {
297 if let Some(crate_id) = add_target_crate_root(
298 &mut crate_graph,
299 &cargo[pkg],
300 &cargo[tgt],
301 &cfg_options,
302 proc_macro_client,
303 load,
304 ) {
305 if cargo[tgt].kind == TargetKind::Lib {
306 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
307 pkg_to_lib_crate.insert(pkg, crate_id);
308 }
309 if cargo[tgt].is_proc_macro {
310 if let Some(proc_macro) = libproc_macro {
311 if let Err(_) = crate_graph.add_dep(
312 crate_id,
313 CrateName::new("proc_macro").unwrap(),
314 proc_macro,
315 ) {
316 log::error!(
317 "cyclic dependency on proc_macro for {}",
318 &cargo[pkg].name
319 )
320 }
321 }
322 }
323
324 pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
325 }
326 }
327
328 // Set deps to the core, std and to the lib target of the current package
329 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
330 if let Some((to, name)) = lib_tgt.clone() {
331 // For root projects with dashes in their name,
332 // cargo metadata does not do any normalization,
333 // so we do it ourselves currently
334 let name = CrateName::normalize_dashes(&name);
335 if to != from && crate_graph.add_dep(from, name, to).is_err() {
336 log::error!(
337 "cyclic dependency between targets of {}",
338 &cargo[pkg].name
339 )
340 }
341 }
342 for (name, krate) in public_deps.iter() {
343 if let Err(_) = crate_graph.add_dep(from, name.clone(), *krate) {
344 log::error!(
345 "cyclic dependency on {} for {}",
346 name,
347 &cargo[pkg].name
348 )
349 }
350 }
351 }
352 }
353
354 // Now add a dep edge from all targets of upstream to the lib
355 // target of downstream.
356 for pkg in cargo.packages() {
357 for dep in cargo[pkg].dependencies.iter() {
358 let name = CrateName::new(&dep.name).unwrap();
359 if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
360 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
361 if let Err(_) = crate_graph.add_dep(from, name.clone(), to) {
362 log::error!(
363 "cyclic dependency {} -> {}",
364 &cargo[pkg].name,
365 &cargo[dep.pkg].name
366 )
367 }
368 }
369 }
370 }
371 }
372
373 let mut rustc_pkg_crates = FxHashMap::default();
374
375 // If the user provided a path to rustc sources, we add all the rustc_private crates
376 // and create dependencies on them for the crates in the current workspace
377 if let Some(rustc_workspace) = rustc {
378 for pkg in rustc_workspace.packages() {
379 for &tgt in rustc_workspace[pkg].targets.iter() {
380 if rustc_workspace[tgt].kind != TargetKind::Lib {
381 continue;
382 }
383 // Exclude alloc / core / std
384 if rustc_workspace[tgt]
385 .root
386 .components()
387 .any(|c| c == Component::Normal("library".as_ref()))
388 {
389 continue;
390 }
391
392 if let Some(crate_id) = add_target_crate_root(
393 &mut crate_graph,
394 &rustc_workspace[pkg],
395 &rustc_workspace[tgt],
396 &cfg_options,
397 proc_macro_client,
398 load,
399 ) {
400 pkg_to_lib_crate.insert(pkg, crate_id);
401 // Add dependencies on the core / std / alloc for rustc
402 for (name, krate) in public_deps.iter() {
403 if let Err(_) =
404 crate_graph.add_dep(crate_id, name.clone(), *krate)
405 {
406 log::error!(
407 "cyclic dependency on {} for {}",
408 name,
409 &cargo[pkg].name
410 )
411 }
412 }
413 rustc_pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
414 }
415 }
416 }
417 // Now add a dep edge from all targets of upstream to the lib
418 // target of downstream.
419 for pkg in rustc_workspace.packages() {
420 for dep in rustc_workspace[pkg].dependencies.iter() {
421 let name = CrateName::new(&dep.name).unwrap();
422 if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
423 for &from in rustc_pkg_crates.get(&pkg).into_iter().flatten() {
424 if let Err(_) = crate_graph.add_dep(from, name.clone(), to) {
425 log::error!(
426 "cyclic dependency {} -> {}",
427 &rustc_workspace[pkg].name,
428 &rustc_workspace[dep.pkg].name
429 )
430 }
431 }
432 }
433 }
434 }
435
436 // Add dependencies for all the crates of the current workspace to rustc_private libraries
437 for dep in rustc_workspace.packages() {
438 let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
439
440 if let Some(&to) = pkg_to_lib_crate.get(&dep) {
441 for pkg in cargo.packages() {
442 if !cargo[pkg].is_member {
443 continue;
444 }
445 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
446 if let Err(_) = crate_graph.add_dep(from, name.clone(), to) {
447 log::error!(
448 "cyclic dependency {} -> {}",
449 &cargo[pkg].name,
450 &rustc_workspace[dep].name
451 )
452 }
453 }
454 }
455 }
456 }
457 }
458 }
459 }
460 if crate_graph.patch_cfg_if() {
461 log::debug!("Patched std to depend on cfg-if")
462 } else {
463 log::debug!("Did not patch std to depend on cfg-if")
464 }
465 crate_graph
466 }
467}
468
469fn add_target_crate_root(
470 crate_graph: &mut CrateGraph,
471 pkg: &cargo_workspace::PackageData,
472 tgt: &cargo_workspace::TargetData,
473 cfg_options: &CfgOptions,
474 proc_macro_client: &ProcMacroClient,
475 load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
476) -> Option<CrateId> {
477 let root = tgt.root.as_path();
478 if let Some(file_id) = load(root) {
479 let edition = pkg.edition;
480 let cfg_options = {
481 let mut opts = cfg_options.clone();
482 for feature in pkg.features.iter() {
483 opts.insert_key_value("feature".into(), feature.into());
484 }
485 opts.extend(pkg.cfgs.iter().cloned());
486 opts
487 };
488 let mut env = Env::default();
489 if let Some(out_dir) = &pkg.out_dir {
490 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
491 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
492 env.set("OUT_DIR", out_dir);
493 }
494 }
495 let proc_macro = pkg
496 .proc_macro_dylib_path
497 .as_ref()
498 .map(|it| proc_macro_client.by_dylib_path(&it))
499 .unwrap_or_default();
500
501 let display_name = CrateDisplayName::from_canonical_name(pkg.name.clone());
502 let crate_id = crate_graph.add_crate_root(
503 file_id,
504 edition,
505 Some(display_name),
506 cfg_options,
507 env,
508 proc_macro.clone(),
509 );
510
511 return Some(crate_id);
512 }
513 None
514}
515fn sysroot_to_crate_graph(
516 crate_graph: &mut CrateGraph,
517 sysroot: &Sysroot,
518 target: Option<&str>,
519 load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
520) -> (Vec<(CrateName, CrateId)>, Option<CrateId>) {
521 let mut cfg_options = CfgOptions::default();
522 cfg_options.extend(get_rustc_cfg_options(target));
523 let sysroot_crates: FxHashMap<_, _> = sysroot
524 .crates()
525 .filter_map(|krate| {
526 let file_id = load(&sysroot[krate].root)?;
527
528 let env = Env::default();
529 let proc_macro = vec![];
530 let name = CrateName::new(&sysroot[krate].name)
531 .expect("Sysroot crates' names do not contain dashes");
532 let crate_id = crate_graph.add_crate_root(
533 file_id,
534 Edition::Edition2018,
535 Some(name.into()),
536 cfg_options.clone(),
537 env,
538 proc_macro,
539 );
540 Some((krate, crate_id))
541 })
542 .collect();
543
544 for from in sysroot.crates() {
545 for &to in sysroot[from].deps.iter() {
546 let name = CrateName::new(&sysroot[to].name).unwrap();
547 if let (Some(&from), Some(&to)) = (sysroot_crates.get(&from), sysroot_crates.get(&to)) {
548 if let Err(_) = crate_graph.add_dep(from, name, to) {
549 log::error!("cyclic dependency between sysroot crates")
550 }
551 }
552 }
553 }
554
555 let public_deps = sysroot
556 .public_deps()
557 .map(|(name, idx)| (CrateName::new(name).unwrap(), sysroot_crates[&idx]))
558 .collect::<Vec<_>>();
559
560 let libproc_macro = sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
561 (public_deps, libproc_macro)
562}
563
564fn get_rustc_cfg_options(target: Option<&str>) -> Vec<CfgFlag> {
565 let mut res = Vec::new();
566
567 // Some nightly-only cfgs, which are required for stdlib
568 res.push(CfgFlag::Atom("target_thread_local".into()));
569 for &ty in ["8", "16", "32", "64", "cas", "ptr"].iter() {
570 for &key in ["target_has_atomic", "target_has_atomic_load_store"].iter() {
571 res.push(CfgFlag::KeyValue { key: key.to_string(), value: ty.into() });
572 }
573 }
574
575 let rustc_cfgs = {
576 let mut cmd = Command::new(toolchain::rustc());
577 cmd.args(&["--print", "cfg", "-O"]);
578 if let Some(target) = target {
579 cmd.args(&["--target", target]);
580 }
581 utf8_stdout(cmd)
582 };
583
584 match rustc_cfgs {
585 Ok(rustc_cfgs) => res.extend(rustc_cfgs.lines().map(|it| it.parse().unwrap())),
586 Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
587 }
588
589 res
590}