aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_lsp_server/src/project_model
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_lsp_server/src/project_model')
-rw-r--r--crates/ra_lsp_server/src/project_model/cargo_workspace.rs171
-rw-r--r--crates/ra_lsp_server/src/project_model/sysroot.rs132
2 files changed, 303 insertions, 0 deletions
diff --git a/crates/ra_lsp_server/src/project_model/cargo_workspace.rs b/crates/ra_lsp_server/src/project_model/cargo_workspace.rs
new file mode 100644
index 000000000..8f7518860
--- /dev/null
+++ b/crates/ra_lsp_server/src/project_model/cargo_workspace.rs
@@ -0,0 +1,171 @@
1use std::path::{Path, PathBuf};
2
3use cargo_metadata::{metadata_run, CargoOpt};
4use ra_syntax::SmolStr;
5use ra_arena::{Arena, RawId, impl_arena_id};
6use rustc_hash::FxHashMap;
7use failure::format_err;
8
9use crate::Result;
10
11/// `CargoWorksapce` 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 differnet 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 meta = metadata_run(Some(cargo_toml), true, Some(CargoOpt::AllFeatures))
121 .map_err(|e| format_err!("cargo metadata failed: {}", e))?;
122 let mut pkg_by_id = FxHashMap::default();
123 let mut packages = Arena::default();
124 let mut targets = Arena::default();
125
126 let ws_members = &meta.workspace_members;
127
128 for meta_pkg in meta.packages {
129 let is_member = ws_members.contains(&meta_pkg.id);
130 let pkg = packages.alloc(PackageData {
131 name: meta_pkg.name.into(),
132 manifest: meta_pkg.manifest_path.clone(),
133 targets: Vec::new(),
134 is_member,
135 dependencies: Vec::new(),
136 });
137 let pkg_data = &mut packages[pkg];
138 pkg_by_id.insert(meta_pkg.id.clone(), pkg);
139 for meta_tgt in meta_pkg.targets {
140 let tgt = targets.alloc(TargetData {
141 pkg,
142 name: meta_tgt.name.into(),
143 root: meta_tgt.src_path.clone(),
144 kind: TargetKind::new(meta_tgt.kind.as_slice()),
145 });
146 pkg_data.targets.push(tgt);
147 }
148 }
149 let resolve = meta.resolve.expect("metadata executed with deps");
150 for node in resolve.nodes {
151 let source = pkg_by_id[&node.id];
152 for dep_node in node.deps {
153 let dep = PackageDependency {
154 name: dep_node.name.into(),
155 pkg: pkg_by_id[&dep_node.pkg],
156 };
157 packages[source].dependencies.push(dep);
158 }
159 }
160
161 Ok(CargoWorkspace { packages, targets })
162 }
163 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + 'a {
164 self.packages.iter().map(|(id, _pkg)| id)
165 }
166 pub fn target_by_root(&self, root: &Path) -> Option<Target> {
167 self.packages()
168 .filter_map(|pkg| pkg.targets(self).find(|it| it.root(self) == root))
169 .next()
170 }
171}
diff --git a/crates/ra_lsp_server/src/project_model/sysroot.rs b/crates/ra_lsp_server/src/project_model/sysroot.rs
new file mode 100644
index 000000000..1dbab57f8
--- /dev/null
+++ b/crates/ra_lsp_server/src/project_model/sysroot.rs
@@ -0,0 +1,132 @@
1use std::{
2 path::{Path, PathBuf},
3 process::Command,
4};
5
6use ra_syntax::SmolStr;
7use ra_arena::{Arena, RawId, impl_arena_id};
8
9use crate::Result;
10
11#[derive(Debug, Clone)]
12pub struct Sysroot {
13 crates: Arena<SysrootCrate, SysrootCrateData>,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct SysrootCrate(RawId);
18impl_arena_id!(SysrootCrate);
19
20#[derive(Debug, Clone)]
21struct SysrootCrateData {
22 name: SmolStr,
23 root: PathBuf,
24 deps: Vec<SysrootCrate>,
25}
26
27impl Sysroot {
28 pub(crate) fn std(&self) -> Option<SysrootCrate> {
29 self.by_name("std")
30 }
31
32 pub(crate) fn crates<'a>(&'a self) -> impl Iterator<Item = SysrootCrate> + 'a {
33 self.crates.iter().map(|(id, _data)| id)
34 }
35
36 pub(super) fn discover(cargo_toml: &Path) -> Result<Sysroot> {
37 let rustc_output = Command::new("rustc")
38 .current_dir(cargo_toml.parent().unwrap())
39 .args(&["--print", "sysroot"])
40 .output()?;
41 if !rustc_output.status.success() {
42 failure::bail!("failed to locate sysroot")
43 }
44 let stdout = String::from_utf8(rustc_output.stdout)?;
45 let sysroot_path = Path::new(stdout.trim());
46 let src = sysroot_path.join("lib/rustlib/src/rust/src");
47
48 let mut sysroot = Sysroot {
49 crates: Arena::default(),
50 };
51 for name in SYSROOT_CRATES.trim().lines() {
52 let root = src.join(format!("lib{}", name)).join("lib.rs");
53 if root.exists() {
54 sysroot.crates.alloc(SysrootCrateData {
55 name: name.into(),
56 root,
57 deps: Vec::new(),
58 });
59 }
60 }
61 if let Some(std) = sysroot.std() {
62 for dep in STD_DEPS.trim().lines() {
63 if let Some(dep) = sysroot.by_name(dep) {
64 sysroot.crates[std].deps.push(dep)
65 }
66 }
67 }
68 Ok(sysroot)
69 }
70
71 fn by_name(&self, name: &str) -> Option<SysrootCrate> {
72 self.crates
73 .iter()
74 .find(|(_id, data)| data.name == name)
75 .map(|(id, _data)| id)
76 }
77}
78
79impl SysrootCrate {
80 pub(crate) fn name(self, sysroot: &Sysroot) -> &SmolStr {
81 &sysroot.crates[self].name
82 }
83 pub(crate) fn root(self, sysroot: &Sysroot) -> &Path {
84 sysroot.crates[self].root.as_path()
85 }
86 pub(crate) fn root_dir(self, sysroot: &Sysroot) -> &Path {
87 self.root(sysroot).parent().unwrap()
88 }
89 pub(crate) fn deps<'a>(self, sysroot: &'a Sysroot) -> impl Iterator<Item = SysrootCrate> + 'a {
90 sysroot.crates[self].deps.iter().map(|&it| it)
91 }
92}
93
94const SYSROOT_CRATES: &str = "
95std
96core
97alloc
98collections
99libc
100panic_unwind
101proc_macro
102rustc_unicode
103std_unicode
104test
105alloc_jemalloc
106alloc_system
107compiler_builtins
108getopts
109panic_unwind
110panic_abort
111rand
112term
113unwind
114build_helper
115rustc_asan
116rustc_lsan
117rustc_msan
118rustc_tsan
119syntax";
120
121const STD_DEPS: &str = "
122alloc_jemalloc
123alloc_system
124panic_abort
125rand
126compiler_builtins
127unwind
128rustc_asan
129rustc_lsan
130rustc_msan
131rustc_tsan
132build_helper";