]> git.lizzy.rs Git - rust.git/blob - crates/base_db/src/fixture.rs
avoid converting types into themselves via .into() (clippy::useless-conversion)
[rust.git] / crates / base_db / src / fixture.rs
1 //! Fixtures are strings containing rust source code with optional metadata.
2 //! A fixture without metadata is parsed into a single source file.
3 //! Use this to test functionality local to one file.
4 //!
5 //! Simple Example:
6 //! ```
7 //! r#"
8 //! fn main() {
9 //!     println!("Hello World")
10 //! }
11 //! "#
12 //! ```
13 //!
14 //! Metadata can be added to a fixture after a `//-` comment.
15 //! The basic form is specifying filenames,
16 //! which is also how to define multiple files in a single test fixture
17 //!
18 //! Example using two files in the same crate:
19 //! ```
20 //! "
21 //! //- /main.rs
22 //! mod foo;
23 //! fn main() {
24 //!     foo::bar();
25 //! }
26 //!
27 //! //- /foo.rs
28 //! pub fn bar() {}
29 //! "
30 //! ```
31 //!
32 //! Example using two crates with one file each, with one crate depending on the other:
33 //! ```
34 //! r#"
35 //! //- /main.rs crate:a deps:b
36 //! fn main() {
37 //!     b::foo();
38 //! }
39 //! //- /lib.rs crate:b
40 //! pub fn b() {
41 //!     println!("Hello World")
42 //! }
43 //! "#
44 //! ```
45 //!
46 //! Metadata allows specifying all settings and variables
47 //! that are available in a real rust project:
48 //! - crate names via `crate:cratename`
49 //! - dependencies via `deps:dep1,dep2`
50 //! - configuration settings via `cfg:dbg=false,opt_level=2`
51 //! - environment variables via `env:PATH=/bin,RUST_LOG=debug`
52 //!
53 //! Example using all available metadata:
54 //! ```
55 //! "
56 //! //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
57 //! fn insert_source_code_here() {}
58 //! "
59 //! ```
60 use std::{mem, str::FromStr, sync::Arc};
61
62 use cfg::CfgOptions;
63 use rustc_hash::FxHashMap;
64 use test_utils::{
65     extract_range_or_offset, Fixture, RangeOrOffset, CURSOR_MARKER, ESCAPED_CURSOR_MARKER,
66 };
67 use vfs::{file_set::FileSet, VfsPath};
68
69 use crate::{
70     input::CrateName, Change, CrateGraph, CrateId, Edition, Env, FileId, FilePosition, FileRange,
71     SourceDatabaseExt, SourceRoot, SourceRootId,
72 };
73
74 pub const WORKSPACE: SourceRootId = SourceRootId(0);
75
76 pub trait WithFixture: Default + SourceDatabaseExt + 'static {
77     fn with_single_file(text: &str) -> (Self, FileId) {
78         let fixture = ChangeFixture::parse(text);
79         let mut db = Self::default();
80         fixture.change.apply(&mut db);
81         assert_eq!(fixture.files.len(), 1);
82         (db, fixture.files[0])
83     }
84
85     fn with_files(ra_fixture: &str) -> Self {
86         let fixture = ChangeFixture::parse(ra_fixture);
87         let mut db = Self::default();
88         fixture.change.apply(&mut db);
89         assert!(fixture.file_position.is_none());
90         db
91     }
92
93     fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
94         let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
95         let offset = match range_or_offset {
96             RangeOrOffset::Range(_) => panic!(),
97             RangeOrOffset::Offset(it) => it,
98         };
99         (db, FilePosition { file_id, offset })
100     }
101
102     fn with_range(ra_fixture: &str) -> (Self, FileRange) {
103         let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
104         let range = match range_or_offset {
105             RangeOrOffset::Range(it) => it,
106             RangeOrOffset::Offset(_) => panic!(),
107         };
108         (db, FileRange { file_id, range })
109     }
110
111     fn with_range_or_offset(ra_fixture: &str) -> (Self, FileId, RangeOrOffset) {
112         let fixture = ChangeFixture::parse(ra_fixture);
113         let mut db = Self::default();
114         fixture.change.apply(&mut db);
115         let (file_id, range_or_offset) = fixture.file_position.unwrap();
116         (db, file_id, range_or_offset)
117     }
118
119     fn test_crate(&self) -> CrateId {
120         let crate_graph = self.crate_graph();
121         let mut it = crate_graph.iter();
122         let res = it.next().unwrap();
123         assert!(it.next().is_none());
124         res
125     }
126 }
127
128 impl<DB: SourceDatabaseExt + Default + 'static> WithFixture for DB {}
129
130 pub struct ChangeFixture {
131     pub file_position: Option<(FileId, RangeOrOffset)>,
132     pub files: Vec<FileId>,
133     pub change: Change,
134 }
135
136 impl ChangeFixture {
137     pub fn parse(ra_fixture: &str) -> ChangeFixture {
138         let fixture = Fixture::parse(ra_fixture);
139         let mut change = Change::new();
140
141         let mut files = Vec::new();
142         let mut crate_graph = CrateGraph::default();
143         let mut crates = FxHashMap::default();
144         let mut crate_deps = Vec::new();
145         let mut default_crate_root: Option<FileId> = None;
146         let mut default_cfg = CfgOptions::default();
147
148         let mut file_set = FileSet::default();
149         let source_root_prefix = "/".to_string();
150         let mut file_id = FileId(0);
151         let mut roots = Vec::new();
152
153         let mut file_position = None;
154
155         for entry in fixture {
156             let text = if entry.text.contains(CURSOR_MARKER) {
157                 if entry.text.contains(ESCAPED_CURSOR_MARKER) {
158                     entry.text.replace(ESCAPED_CURSOR_MARKER, CURSOR_MARKER)
159                 } else {
160                     let (range_or_offset, text) = extract_range_or_offset(&entry.text);
161                     assert!(file_position.is_none());
162                     file_position = Some((file_id, range_or_offset));
163                     text.to_string()
164                 }
165             } else {
166                 entry.text.clone()
167             };
168
169             let meta = FileMeta::from(entry);
170             assert!(meta.path.starts_with(&source_root_prefix));
171
172             if meta.introduce_new_source_root {
173                 roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
174             }
175
176             if let Some(krate) = meta.krate {
177                 let crate_name = CrateName::normalize_dashes(&krate);
178                 let crate_id = crate_graph.add_crate_root(
179                     file_id,
180                     meta.edition,
181                     Some(crate_name.clone().into()),
182                     meta.cfg,
183                     meta.env,
184                     Default::default(),
185                 );
186                 let prev = crates.insert(crate_name.clone(), crate_id);
187                 assert!(prev.is_none());
188                 for dep in meta.deps {
189                     let dep = CrateName::normalize_dashes(&dep);
190                     crate_deps.push((crate_name.clone(), dep))
191                 }
192             } else if meta.path == "/main.rs" || meta.path == "/lib.rs" {
193                 assert!(default_crate_root.is_none());
194                 default_crate_root = Some(file_id);
195                 default_cfg = meta.cfg;
196             }
197
198             change.change_file(file_id, Some(Arc::new(text)));
199             let path = VfsPath::new_virtual_path(meta.path);
200             file_set.insert(file_id, path);
201             files.push(file_id);
202             file_id.0 += 1;
203         }
204
205         if crates.is_empty() {
206             let crate_root = default_crate_root.unwrap();
207             crate_graph.add_crate_root(
208                 crate_root,
209                 Edition::Edition2018,
210                 Some(CrateName::new("test").unwrap().into()),
211                 default_cfg,
212                 Env::default(),
213                 Default::default(),
214             );
215         } else {
216             for (from, to) in crate_deps {
217                 let from_id = crates[&from];
218                 let to_id = crates[&to];
219                 crate_graph.add_dep(from_id, CrateName::new(&to).unwrap(), to_id).unwrap();
220             }
221         }
222
223         roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
224         change.set_roots(roots);
225         change.set_crate_graph(crate_graph);
226
227         ChangeFixture { file_position, files, change }
228     }
229 }
230
231 struct FileMeta {
232     path: String,
233     krate: Option<String>,
234     deps: Vec<String>,
235     cfg: CfgOptions,
236     edition: Edition,
237     env: Env,
238     introduce_new_source_root: bool,
239 }
240
241 impl From<Fixture> for FileMeta {
242     fn from(f: Fixture) -> FileMeta {
243         let mut cfg = CfgOptions::default();
244         f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
245         f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
246
247         FileMeta {
248             path: f.path,
249             krate: f.krate,
250             deps: f.deps,
251             cfg,
252             edition: f
253                 .edition
254                 .as_ref()
255                 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
256             env: f.env.into_iter().collect(),
257             introduce_new_source_root: f.introduce_new_source_root,
258         }
259     }
260 }