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