]> git.lizzy.rs Git - rust.git/blob - crates/base_db/src/fixture.rs
Merge #9328
[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                 );
135                 let prev = crates.insert(crate_name.clone(), crate_id);
136                 assert!(prev.is_none());
137                 for dep in meta.deps {
138                     let dep = CrateName::normalize_dashes(&dep);
139                     crate_deps.push((crate_name.clone(), dep))
140                 }
141             } else if meta.path == "/main.rs" || meta.path == "/lib.rs" {
142                 assert!(default_crate_root.is_none());
143                 default_crate_root = Some(file_id);
144                 default_cfg = meta.cfg;
145             }
146
147             change.change_file(file_id, Some(Arc::new(text)));
148             let path = VfsPath::new_virtual_path(meta.path);
149             file_set.insert(file_id, path);
150             files.push(file_id);
151             file_id.0 += 1;
152         }
153
154         if crates.is_empty() {
155             let crate_root = default_crate_root.unwrap();
156             crate_graph.add_crate_root(
157                 crate_root,
158                 Edition::Edition2018,
159                 Some(CrateName::new("test").unwrap().into()),
160                 default_cfg,
161                 Env::default(),
162                 Default::default(),
163             );
164         } else {
165             for (from, to) in crate_deps {
166                 let from_id = crates[&from];
167                 let to_id = crates[&to];
168                 crate_graph.add_dep(from_id, CrateName::new(&to).unwrap(), to_id).unwrap();
169             }
170         }
171
172         if let Some(mini_core) = mini_core {
173             let core_file = file_id;
174             file_id.0 += 1;
175
176             let mut fs = FileSet::default();
177             fs.insert(core_file, VfsPath::new_virtual_path("/sysroot/core/lib.rs".to_string()));
178             roots.push(SourceRoot::new_library(fs));
179
180             change.change_file(core_file, Some(Arc::new(mini_core.source_code())));
181
182             let all_crates = crate_graph.crates_in_topological_order();
183
184             let core_crate = crate_graph.add_crate_root(
185                 core_file,
186                 Edition::Edition2021,
187                 Some(CrateDisplayName::from_canonical_name("core".to_string())),
188                 CfgOptions::default(),
189                 Env::default(),
190                 Vec::new(),
191             );
192
193             for krate in all_crates {
194                 crate_graph.add_dep(krate, CrateName::new("core").unwrap(), core_crate).unwrap();
195             }
196         }
197         roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
198         change.set_roots(roots);
199         change.set_crate_graph(crate_graph);
200
201         ChangeFixture { file_position, files, change }
202     }
203 }
204
205 #[derive(Debug)]
206 struct FileMeta {
207     path: String,
208     krate: Option<String>,
209     deps: Vec<String>,
210     cfg: CfgOptions,
211     edition: Edition,
212     env: Env,
213     introduce_new_source_root: bool,
214 }
215
216 impl From<Fixture> for FileMeta {
217     fn from(f: Fixture) -> FileMeta {
218         let mut cfg = CfgOptions::default();
219         f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
220         f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
221
222         FileMeta {
223             path: f.path,
224             krate: f.krate,
225             deps: f.deps,
226             cfg,
227             edition: f
228                 .edition
229                 .as_ref()
230                 .map_or(Edition::Edition2018, |v| Edition::from_str(v).unwrap()),
231             env: f.env.into_iter().collect(),
232             introduce_new_source_root: f.introduce_new_source_root,
233         }
234     }
235 }