]> git.lizzy.rs Git - rust.git/blob - crates/base_db/src/fixture.rs
6d3b1266e6fd99b2b97d301d77947fb80d52a9fd
[rust.git] / crates / base_db / src / fixture.rs
1 //! A set of high-level utility fixture methods to use in tests.
2 use std::{mem, str::FromStr, sync::Arc};
3
4 use cfg::CfgOptions;
5 use rustc_hash::FxHashMap;
6 use test_utils::{
7     extract_range_or_offset, Fixture, RangeOrOffset, CURSOR_MARKER, ESCAPED_CURSOR_MARKER,
8 };
9 use vfs::{file_set::FileSet, VfsPath};
10
11 use crate::{
12     input::CrateName, Change, CrateDisplayName, CrateGraph, CrateId, Edition, Env, FileId,
13     FilePosition, FileRange, SourceDatabaseExt, SourceRoot, SourceRootId,
14 };
15
16 pub const WORKSPACE: SourceRootId = SourceRootId(0);
17
18 pub trait WithFixture: Default + SourceDatabaseExt + 'static {
19     fn with_single_file(text: &str) -> (Self, FileId) {
20         let fixture = ChangeFixture::parse(text);
21         let mut db = Self::default();
22         fixture.change.apply(&mut db);
23         assert_eq!(fixture.files.len(), 1);
24         (db, fixture.files[0])
25     }
26
27     fn with_many_files(ra_fixture: &str) -> (Self, Vec<FileId>) {
28         let fixture = ChangeFixture::parse(ra_fixture);
29         let mut db = Self::default();
30         fixture.change.apply(&mut db);
31         assert!(fixture.file_position.is_none());
32         (db, fixture.files)
33     }
34
35     fn with_files(ra_fixture: &str) -> Self {
36         let fixture = ChangeFixture::parse(ra_fixture);
37         let mut db = Self::default();
38         fixture.change.apply(&mut db);
39         assert!(fixture.file_position.is_none());
40         db
41     }
42
43     fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
44         let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
45         let offset = range_or_offset.expect_offset();
46         (db, FilePosition { file_id, offset })
47     }
48
49     fn with_range(ra_fixture: &str) -> (Self, FileRange) {
50         let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
51         let range = range_or_offset.expect_range();
52         (db, FileRange { file_id, range })
53     }
54
55     fn with_range_or_offset(ra_fixture: &str) -> (Self, FileId, RangeOrOffset) {
56         let fixture = ChangeFixture::parse(ra_fixture);
57         let mut db = Self::default();
58         fixture.change.apply(&mut db);
59         let (file_id, range_or_offset) = fixture
60             .file_position
61             .expect("Could not find file position in fixture. Did you forget to add an `$0`?");
62         (db, file_id, range_or_offset)
63     }
64
65     fn test_crate(&self) -> CrateId {
66         let crate_graph = self.crate_graph();
67         let mut it = crate_graph.iter();
68         let res = it.next().unwrap();
69         assert!(it.next().is_none());
70         res
71     }
72 }
73
74 impl<DB: SourceDatabaseExt + Default + 'static> WithFixture for DB {}
75
76 pub struct ChangeFixture {
77     pub file_position: Option<(FileId, RangeOrOffset)>,
78     pub files: Vec<FileId>,
79     pub change: Change,
80 }
81
82 impl ChangeFixture {
83     pub fn parse(ra_fixture: &str) -> ChangeFixture {
84         let (mini_core, fixture) = Fixture::parse(ra_fixture);
85         let mut change = Change::new();
86
87         let mut files = Vec::new();
88         let mut crate_graph = CrateGraph::default();
89         let mut crates = FxHashMap::default();
90         let mut crate_deps = Vec::new();
91         let mut default_crate_root: Option<FileId> = None;
92         let mut default_cfg = CfgOptions::default();
93
94         let mut file_set = FileSet::default();
95         let source_root_prefix = "/".to_string();
96         let mut file_id = FileId(0);
97         let mut roots = Vec::new();
98
99         let mut file_position = None;
100
101         for entry in fixture {
102             let text = if entry.text.contains(CURSOR_MARKER) {
103                 if entry.text.contains(ESCAPED_CURSOR_MARKER) {
104                     entry.text.replace(ESCAPED_CURSOR_MARKER, CURSOR_MARKER)
105                 } else {
106                     let (range_or_offset, text) = extract_range_or_offset(&entry.text);
107                     assert!(file_position.is_none());
108                     file_position = Some((file_id, range_or_offset));
109                     text
110                 }
111             } else {
112                 entry.text.clone()
113             };
114
115             let meta = FileMeta::from(entry);
116             assert!(meta.path.starts_with(&source_root_prefix));
117             if !meta.deps.is_empty() {
118                 assert!(meta.krate.is_some(), "can't specify deps without naming the crate")
119             }
120
121             if meta.introduce_new_source_root {
122                 roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
123             }
124
125             if let Some(krate) = meta.krate {
126                 let crate_name = CrateName::normalize_dashes(&krate);
127                 let crate_id = crate_graph.add_crate_root(
128                     file_id,
129                     meta.edition,
130                     Some(crate_name.clone().into()),
131                     meta.cfg,
132                     meta.env,
133                     Default::default(),
134                     Default::default(),
135                 );
136                 let prev = crates.insert(crate_name.clone(), crate_id);
137                 assert!(prev.is_none());
138                 for dep in meta.deps {
139                     let dep = CrateName::normalize_dashes(&dep);
140                     crate_deps.push((crate_name.clone(), dep))
141                 }
142             } else if meta.path == "/main.rs" || meta.path == "/lib.rs" {
143                 assert!(default_crate_root.is_none());
144                 default_crate_root = Some(file_id);
145                 default_cfg = meta.cfg;
146             }
147
148             change.change_file(file_id, Some(Arc::new(text)));
149             let path = VfsPath::new_virtual_path(meta.path);
150             file_set.insert(file_id, path);
151             files.push(file_id);
152             file_id.0 += 1;
153         }
154
155         if crates.is_empty() {
156             let crate_root = default_crate_root.unwrap();
157             crate_graph.add_crate_root(
158                 crate_root,
159                 Edition::Edition2018,
160                 Some(CrateName::new("test").unwrap().into()),
161                 default_cfg,
162                 Env::default(),
163                 Default::default(),
164                 Default::default(),
165             );
166         } else {
167             for (from, to) in crate_deps {
168                 let from_id = crates[&from];
169                 let to_id = crates[&to];
170                 crate_graph.add_dep(from_id, CrateName::new(&to).unwrap(), to_id).unwrap();
171             }
172         }
173
174         if let Some(mini_core) = mini_core {
175             let core_file = file_id;
176             file_id.0 += 1;
177
178             let mut fs = FileSet::default();
179             fs.insert(core_file, VfsPath::new_virtual_path("/sysroot/core/lib.rs".to_string()));
180             roots.push(SourceRoot::new_library(fs));
181
182             change.change_file(core_file, Some(Arc::new(mini_core.source_code())));
183
184             let all_crates = crate_graph.crates_in_topological_order();
185
186             let core_crate = crate_graph.add_crate_root(
187                 core_file,
188                 Edition::Edition2021,
189                 Some(CrateDisplayName::from_canonical_name("core".to_string())),
190                 CfgOptions::default(),
191                 Env::default(),
192                 Vec::new(),
193             );
194
195             for krate in all_crates {
196                 crate_graph.add_dep(krate, CrateName::new("core").unwrap(), core_crate).unwrap();
197             }
198         }
199         roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
200         change.set_roots(roots);
201         change.set_crate_graph(crate_graph);
202
203         ChangeFixture { file_position, files, change }
204     }
205 }
206
207 #[derive(Debug)]
208 struct FileMeta {
209     path: String,
210     krate: Option<String>,
211     deps: Vec<String>,
212     cfg: CfgOptions,
213     edition: Edition,
214     env: Env,
215     introduce_new_source_root: bool,
216 }
217
218 impl From<Fixture> for FileMeta {
219     fn from(f: Fixture) -> FileMeta {
220         let mut cfg = CfgOptions::default();
221         f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
222         f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
223
224         FileMeta {
225             path: f.path,
226             krate: f.krate,
227             deps: f.deps,
228             cfg,
229             edition: f
230                 .edition
231                 .as_ref()
232                 .map_or(Edition::Edition2018, |v| Edition::from_str(v).unwrap()),
233             env: f.env.into_iter().collect(),
234             introduce_new_source_root: f.introduce_new_source_root,
235         }
236     }
237 }