aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_project_model/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_project_model/src')
-rw-r--r--crates/ra_project_model/src/cargo_workspace.rs173
-rw-r--r--crates/ra_project_model/src/lib.rs45
-rw-r--r--crates/ra_project_model/src/sysroot.rs138
3 files changed, 356 insertions, 0 deletions
diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs
new file mode 100644
index 000000000..f3e67d0e5
--- /dev/null
+++ b/crates/ra_project_model/src/cargo_workspace.rs
@@ -0,0 +1,173 @@
1use std::path::{Path, PathBuf};
2
3use cargo_metadata::{MetadataCommand, CargoOpt};
4use smol_str::SmolStr;
5use ra_arena::{Arena, RawId, impl_arena_id};
6use rustc_hash::FxHashMap;
7use failure::format_err;
8
9use crate::Result;
10
11/// `CargoWorkspace` represents the logical structure of, well, a Cargo
12/// workspace. It pretty closely mirrors `cargo metadata` output.
13///
14/// Note that internally, rust analyzer uses a different structure:
15/// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
16/// while this knows about `Pacakges` & `Targets`: purely cargo-related
17/// concepts.
18#[derive(Debug, Clone)]
19pub struct CargoWorkspace {
20 packages: Arena<Package, PackageData>,
21 targets: Arena<Target, TargetData>,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub struct Package(RawId);
26impl_arena_id!(Package);
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29pub struct Target(RawId);
30impl_arena_id!(Target);
31
32#[derive(Debug, Clone)]
33struct PackageData {
34 name: SmolStr,
35 manifest: PathBuf,
36 targets: Vec<Target>,
37 is_member: bool,
38 dependencies: Vec<PackageDependency>,
39}
40
41#[derive(Debug, Clone)]
42pub struct PackageDependency {
43 pub pkg: Package,
44 pub name: SmolStr,
45}
46
47#[derive(Debug, Clone)]
48struct TargetData {
49 pkg: Package,
50 name: SmolStr,
51 root: PathBuf,
52 kind: TargetKind,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum TargetKind {
57 Bin,
58 Lib,
59 Example,
60 Test,
61 Bench,
62 Other,
63}
64
65impl TargetKind {
66 fn new(kinds: &[String]) -> TargetKind {
67 for kind in kinds {
68 return match kind.as_str() {
69 "bin" => TargetKind::Bin,
70 "test" => TargetKind::Test,
71 "bench" => TargetKind::Bench,
72 "example" => TargetKind::Example,
73 _ if kind.contains("lib") => TargetKind::Lib,
74 _ => continue,
75 };
76 }
77 TargetKind::Other
78 }
79}
80
81impl Package {
82 pub fn name(self, ws: &CargoWorkspace) -> &str {
83 ws.packages[self].name.as_str()
84 }
85 pub fn root(self, ws: &CargoWorkspace) -> &Path {
86 ws.packages[self].manifest.parent().unwrap()
87 }
88 pub fn targets<'a>(self, ws: &'a CargoWorkspace) -> impl Iterator<Item = Target> + 'a {
89 ws.packages[self].targets.iter().cloned()
90 }
91 #[allow(unused)]
92 pub fn is_member(self, ws: &CargoWorkspace) -> bool {
93 ws.packages[self].is_member
94 }
95 pub fn dependencies<'a>(
96 self,
97 ws: &'a CargoWorkspace,
98 ) -> impl Iterator<Item = &'a PackageDependency> + 'a {
99 ws.packages[self].dependencies.iter()
100 }
101}
102
103impl Target {
104 pub fn package(self, ws: &CargoWorkspace) -> Package {
105 ws.targets[self].pkg
106 }
107 pub fn name(self, ws: &CargoWorkspace) -> &str {
108 ws.targets[self].name.as_str()
109 }
110 pub fn root(self, ws: &CargoWorkspace) -> &Path {
111 ws.targets[self].root.as_path()
112 }
113 pub fn kind(self, ws: &CargoWorkspace) -> TargetKind {
114 ws.targets[self].kind
115 }
116}
117
118impl CargoWorkspace {
119 pub fn from_cargo_metadata(cargo_toml: &Path) -> Result<CargoWorkspace> {
120 let mut meta = MetadataCommand::new();
121 meta.manifest_path(cargo_toml).features(CargoOpt::AllFeatures);
122 if let Some(parent) = cargo_toml.parent() {
123 meta.current_dir(parent);
124 }
125 let meta = meta.exec().map_err(|e| format_err!("cargo metadata failed: {}", e))?;
126 let mut pkg_by_id = FxHashMap::default();
127 let mut packages = Arena::default();
128 let mut targets = Arena::default();
129
130 let ws_members = &meta.workspace_members;
131
132 for meta_pkg in meta.packages {
133 let is_member = ws_members.contains(&meta_pkg.id);
134 let pkg = packages.alloc(PackageData {
135 name: meta_pkg.name.into(),
136 manifest: meta_pkg.manifest_path.clone(),
137 targets: Vec::new(),
138 is_member,
139 dependencies: Vec::new(),
140 });
141 let pkg_data = &mut packages[pkg];
142 pkg_by_id.insert(meta_pkg.id.clone(), pkg);
143 for meta_tgt in meta_pkg.targets {
144 let tgt = targets.alloc(TargetData {
145 pkg,
146 name: meta_tgt.name.into(),
147 root: meta_tgt.src_path.clone(),
148 kind: TargetKind::new(meta_tgt.kind.as_slice()),
149 });
150 pkg_data.targets.push(tgt);
151 }
152 }
153 let resolve = meta.resolve.expect("metadata executed with deps");
154 for node in resolve.nodes {
155 let source = pkg_by_id[&node.id];
156 for dep_node in node.deps {
157 let dep =
158 PackageDependency { name: dep_node.name.into(), pkg: pkg_by_id[&dep_node.pkg] };
159 packages[source].dependencies.push(dep);
160 }
161 }
162
163 Ok(CargoWorkspace { packages, targets })
164 }
165
166 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + 'a {
167 self.packages.iter().map(|(id, _pkg)| id)
168 }
169
170 pub fn target_by_root(&self, root: &Path) -> Option<Target> {
171 self.packages().filter_map(|pkg| pkg.targets(self).find(|it| it.root(self) == root)).next()
172 }
173}
diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs
new file mode 100644
index 000000000..3a7bbace7
--- /dev/null
+++ b/crates/ra_project_model/src/lib.rs
@@ -0,0 +1,45 @@
1mod cargo_workspace;
2mod sysroot;
3
4use std::path::{Path, PathBuf};
5
6use failure::bail;
7
8pub use crate::{
9 cargo_workspace::{CargoWorkspace, Package, Target, TargetKind},
10 sysroot::Sysroot,
11};
12
13// TODO use own error enum?
14pub type Result<T> = ::std::result::Result<T, ::failure::Error>;
15
16#[derive(Debug, Clone)]
17pub struct ProjectWorkspace {
18 pub cargo: CargoWorkspace,
19 pub sysroot: Sysroot,
20}
21
22impl ProjectWorkspace {
23 pub fn discover(path: &Path) -> Result<ProjectWorkspace> {
24 let cargo_toml = find_cargo_toml(path)?;
25 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml)?;
26 let sysroot = Sysroot::discover(&cargo_toml)?;
27 let res = ProjectWorkspace { cargo, sysroot };
28 Ok(res)
29 }
30}
31
32fn find_cargo_toml(path: &Path) -> Result<PathBuf> {
33 if path.ends_with("Cargo.toml") {
34 return Ok(path.to_path_buf());
35 }
36 let mut curr = Some(path);
37 while let Some(path) = curr {
38 let candidate = path.join("Cargo.toml");
39 if candidate.exists() {
40 return Ok(candidate);
41 }
42 curr = path.parent();
43 }
44 bail!("can't find Cargo.toml at {}", path.display())
45}
diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs
new file mode 100644
index 000000000..18824dbe5
--- /dev/null
+++ b/crates/ra_project_model/src/sysroot.rs
@@ -0,0 +1,138 @@
1use std::{
2 path::{Path, PathBuf},
3 process::Command,
4};
5
6use smol_str::SmolStr;
7
8use ra_arena::{Arena, RawId, impl_arena_id};
9
10use crate::Result;
11
12#[derive(Debug, Clone)]
13pub struct Sysroot {
14 crates: Arena<SysrootCrate, SysrootCrateData>,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub struct SysrootCrate(RawId);
19impl_arena_id!(SysrootCrate);
20
21#[derive(Debug, Clone)]
22struct SysrootCrateData {
23 name: SmolStr,
24 root: PathBuf,
25 deps: Vec<SysrootCrate>,
26}
27
28impl Sysroot {
29 pub fn std(&self) -> Option<SysrootCrate> {
30 self.by_name("std")
31 }
32
33 pub fn crates<'a>(&'a self) -> impl Iterator<Item = SysrootCrate> + 'a {
34 self.crates.iter().map(|(id, _data)| id)
35 }
36
37 pub fn discover(cargo_toml: &Path) -> Result<Sysroot> {
38 let rustc_output = Command::new("rustc")
39 .current_dir(cargo_toml.parent().unwrap())
40 .args(&["--print", "sysroot"])
41 .output()?;
42 if !rustc_output.status.success() {
43 failure::bail!("failed to locate sysroot")
44 }
45 let stdout = String::from_utf8(rustc_output.stdout)?;
46 let sysroot_path = Path::new(stdout.trim());
47 let src = sysroot_path.join("lib/rustlib/src/rust/src");
48 if !src.exists() {
49 failure::bail!(
50 "can't load standard library from sysroot\n\
51 {:?}\n\
52 try running `rustup component add rust-src`",
53 src,
54 );
55 }
56
57 let mut sysroot = Sysroot { crates: Arena::default() };
58 for name in SYSROOT_CRATES.trim().lines() {
59 let root = src.join(format!("lib{}", name)).join("lib.rs");
60 if root.exists() {
61 sysroot.crates.alloc(SysrootCrateData {
62 name: name.into(),
63 root,
64 deps: Vec::new(),
65 });
66 }
67 }
68 if let Some(std) = sysroot.std() {
69 for dep in STD_DEPS.trim().lines() {
70 if let Some(dep) = sysroot.by_name(dep) {
71 sysroot.crates[std].deps.push(dep)
72 }
73 }
74 }
75 Ok(sysroot)
76 }
77
78 fn by_name(&self, name: &str) -> Option<SysrootCrate> {
79 self.crates.iter().find(|(_id, data)| data.name == name).map(|(id, _data)| id)
80 }
81}
82
83impl SysrootCrate {
84 pub fn name(self, sysroot: &Sysroot) -> &SmolStr {
85 &sysroot.crates[self].name
86 }
87 pub fn root(self, sysroot: &Sysroot) -> &Path {
88 sysroot.crates[self].root.as_path()
89 }
90 pub fn root_dir(self, sysroot: &Sysroot) -> &Path {
91 self.root(sysroot).parent().unwrap()
92 }
93 pub fn deps<'a>(self, sysroot: &'a Sysroot) -> impl Iterator<Item = SysrootCrate> + 'a {
94 sysroot.crates[self].deps.iter().map(|&it| it)
95 }
96}
97
98const SYSROOT_CRATES: &str = "
99std
100core
101alloc
102collections
103libc
104panic_unwind
105proc_macro
106rustc_unicode
107std_unicode
108test
109alloc_jemalloc
110alloc_system
111compiler_builtins
112getopts
113panic_unwind
114panic_abort
115rand
116term
117unwind
118build_helper
119rustc_asan
120rustc_lsan
121rustc_msan
122rustc_tsan
123syntax";
124
125const STD_DEPS: &str = "
126alloc
127alloc_jemalloc
128alloc_system
129core
130panic_abort
131rand
132compiler_builtins
133unwind
134rustc_asan
135rustc_lsan
136rustc_msan
137rustc_tsan
138build_helper";