]> git.lizzy.rs Git - rust.git/blob - crates/base_db/src/fixture.rs
Merge #8557
[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, CrateGraph, CrateId, Edition, Env, FileId, FilePosition, FileRange,
13     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_files(ra_fixture: &str) -> Self {
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
33     }
34
35     fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
36         let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
37         let offset = match range_or_offset {
38             RangeOrOffset::Range(_) => panic!(),
39             RangeOrOffset::Offset(it) => it,
40         };
41         (db, FilePosition { file_id, offset })
42     }
43
44     fn with_range(ra_fixture: &str) -> (Self, FileRange) {
45         let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
46         let range = match range_or_offset {
47             RangeOrOffset::Range(it) => it,
48             RangeOrOffset::Offset(_) => panic!(),
49         };
50         (db, FileRange { file_id, range })
51     }
52
53     fn with_range_or_offset(ra_fixture: &str) -> (Self, FileId, RangeOrOffset) {
54         let fixture = ChangeFixture::parse(ra_fixture);
55         let mut db = Self::default();
56         fixture.change.apply(&mut db);
57         let (file_id, range_or_offset) = fixture
58             .file_position
59             .expect("Could not find file position in fixture. Did you forget to add an `$0`?");
60         (db, file_id, range_or_offset)
61     }
62
63     fn test_crate(&self) -> CrateId {
64         let crate_graph = self.crate_graph();
65         let mut it = crate_graph.iter();
66         let res = it.next().unwrap();
67         assert!(it.next().is_none());
68         res
69     }
70 }
71
72 impl<DB: SourceDatabaseExt + Default + 'static> WithFixture for DB {}
73
74 pub struct ChangeFixture {
75     pub file_position: Option<(FileId, RangeOrOffset)>,
76     pub files: Vec<FileId>,
77     pub change: Change,
78 }
79
80 impl ChangeFixture {
81     pub fn parse(ra_fixture: &str) -> ChangeFixture {
82         let fixture = Fixture::parse(ra_fixture);
83         let mut change = Change::new();
84
85         let mut files = Vec::new();
86         let mut crate_graph = CrateGraph::default();
87         let mut crates = FxHashMap::default();
88         let mut crate_deps = Vec::new();
89         let mut default_crate_root: Option<FileId> = None;
90         let mut default_cfg = CfgOptions::default();
91
92         let mut file_set = FileSet::default();
93         let source_root_prefix = "/".to_string();
94         let mut file_id = FileId(0);
95         let mut roots = Vec::new();
96
97         let mut file_position = None;
98
99         for entry in fixture {
100             let text = if entry.text.contains(CURSOR_MARKER) {
101                 if entry.text.contains(ESCAPED_CURSOR_MARKER) {
102                     entry.text.replace(ESCAPED_CURSOR_MARKER, CURSOR_MARKER)
103                 } else {
104                     let (range_or_offset, text) = extract_range_or_offset(&entry.text);
105                     assert!(file_position.is_none());
106                     file_position = Some((file_id, range_or_offset));
107                     text.to_string()
108                 }
109             } else {
110                 entry.text.clone()
111             };
112
113             let meta = FileMeta::from(entry);
114             assert!(meta.path.starts_with(&source_root_prefix));
115
116             if meta.introduce_new_source_root {
117                 roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
118             }
119
120             if let Some(krate) = meta.krate {
121                 let crate_name = CrateName::normalize_dashes(&krate);
122                 let crate_id = crate_graph.add_crate_root(
123                     file_id,
124                     meta.edition,
125                     Some(crate_name.clone().into()),
126                     meta.cfg,
127                     meta.env,
128                     Default::default(),
129                 );
130                 let prev = crates.insert(crate_name.clone(), crate_id);
131                 assert!(prev.is_none());
132                 for dep in meta.deps {
133                     let dep = CrateName::normalize_dashes(&dep);
134                     crate_deps.push((crate_name.clone(), dep))
135                 }
136             } else if meta.path == "/main.rs" || meta.path == "/lib.rs" {
137                 assert!(default_crate_root.is_none());
138                 default_crate_root = Some(file_id);
139                 default_cfg = meta.cfg;
140             }
141
142             change.change_file(file_id, Some(Arc::new(text)));
143             let path = VfsPath::new_virtual_path(meta.path);
144             file_set.insert(file_id, path);
145             files.push(file_id);
146             file_id.0 += 1;
147         }
148
149         if crates.is_empty() {
150             let crate_root = default_crate_root.unwrap();
151             crate_graph.add_crate_root(
152                 crate_root,
153                 Edition::Edition2018,
154                 Some(CrateName::new("test").unwrap().into()),
155                 default_cfg,
156                 Env::default(),
157                 Default::default(),
158             );
159         } else {
160             for (from, to) in crate_deps {
161                 let from_id = crates[&from];
162                 let to_id = crates[&to];
163                 crate_graph.add_dep(from_id, CrateName::new(&to).unwrap(), to_id).unwrap();
164             }
165         }
166
167         roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
168         change.set_roots(roots);
169         change.set_crate_graph(crate_graph);
170
171         ChangeFixture { file_position, files, change }
172     }
173 }
174
175 struct FileMeta {
176     path: String,
177     krate: Option<String>,
178     deps: Vec<String>,
179     cfg: CfgOptions,
180     edition: Edition,
181     env: Env,
182     introduce_new_source_root: bool,
183 }
184
185 impl From<Fixture> for FileMeta {
186     fn from(f: Fixture) -> FileMeta {
187         let mut cfg = CfgOptions::default();
188         f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
189         f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
190
191         FileMeta {
192             path: f.path,
193             krate: f.krate,
194             deps: f.deps,
195             cfg,
196             edition: f
197                 .edition
198                 .as_ref()
199                 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
200             env: f.env.into_iter().collect(),
201             introduce_new_source_root: f.introduce_new_source_root,
202         }
203     }
204 }