]> git.lizzy.rs Git - rust.git/blob - crates/base_db/src/fixture.rs
Merge #7196
[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::{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,
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_or_offset(ra_fixture: &str) -> (Self, FileId, RangeOrOffset) {
103         let fixture = ChangeFixture::parse(ra_fixture);
104         let mut db = Self::default();
105         fixture.change.apply(&mut db);
106         let (file_id, range_or_offset) = fixture.file_position.unwrap();
107         (db, file_id, range_or_offset)
108     }
109
110     fn test_crate(&self) -> CrateId {
111         let crate_graph = self.crate_graph();
112         let mut it = crate_graph.iter();
113         let res = it.next().unwrap();
114         assert!(it.next().is_none());
115         res
116     }
117 }
118
119 impl<DB: SourceDatabaseExt + Default + 'static> WithFixture for DB {}
120
121 pub struct ChangeFixture {
122     pub file_position: Option<(FileId, RangeOrOffset)>,
123     pub files: Vec<FileId>,
124     pub change: Change,
125 }
126
127 impl ChangeFixture {
128     pub fn parse(ra_fixture: &str) -> ChangeFixture {
129         let fixture = Fixture::parse(ra_fixture);
130         let mut change = Change::new();
131
132         let mut files = Vec::new();
133         let mut crate_graph = CrateGraph::default();
134         let mut crates = FxHashMap::default();
135         let mut crate_deps = Vec::new();
136         let mut default_crate_root: Option<FileId> = None;
137         let mut default_cfg = CfgOptions::default();
138
139         let mut file_set = FileSet::default();
140         let source_root_prefix = "/".to_string();
141         let mut file_id = FileId(0);
142
143         let mut file_position = None;
144
145         for entry in fixture {
146             let text = if entry.text.contains(CURSOR_MARKER) {
147                 if entry.text.contains(ESCAPED_CURSOR_MARKER) {
148                     entry.text.replace(ESCAPED_CURSOR_MARKER, CURSOR_MARKER)
149                 } else {
150                     let (range_or_offset, text) = extract_range_or_offset(&entry.text);
151                     assert!(file_position.is_none());
152                     file_position = Some((file_id, range_or_offset));
153                     text.to_string()
154                 }
155             } else {
156                 entry.text.clone()
157             };
158
159             let meta = FileMeta::from(entry);
160             assert!(meta.path.starts_with(&source_root_prefix));
161
162             if let Some(krate) = meta.krate {
163                 let crate_name = CrateName::normalize_dashes(&krate);
164                 let crate_id = crate_graph.add_crate_root(
165                     file_id,
166                     meta.edition,
167                     Some(crate_name.clone().into()),
168                     meta.cfg,
169                     meta.env,
170                     Default::default(),
171                 );
172                 let prev = crates.insert(crate_name.clone(), crate_id);
173                 assert!(prev.is_none());
174                 for dep in meta.deps {
175                     let dep = CrateName::normalize_dashes(&dep);
176                     crate_deps.push((crate_name.clone(), dep))
177                 }
178             } else if meta.path == "/main.rs" || meta.path == "/lib.rs" {
179                 assert!(default_crate_root.is_none());
180                 default_crate_root = Some(file_id);
181                 default_cfg = meta.cfg;
182             }
183
184             change.change_file(file_id, Some(Arc::new(text)));
185             let path = VfsPath::new_virtual_path(meta.path);
186             file_set.insert(file_id, path.into());
187             files.push(file_id);
188             file_id.0 += 1;
189         }
190
191         if crates.is_empty() {
192             let crate_root = default_crate_root.unwrap();
193             crate_graph.add_crate_root(
194                 crate_root,
195                 Edition::Edition2018,
196                 Some(CrateName::new("test").unwrap().into()),
197                 default_cfg,
198                 Env::default(),
199                 Default::default(),
200             );
201         } else {
202             for (from, to) in crate_deps {
203                 let from_id = crates[&from];
204                 let to_id = crates[&to];
205                 crate_graph.add_dep(from_id, CrateName::new(&to).unwrap(), to_id).unwrap();
206             }
207         }
208
209         change.set_roots(vec![SourceRoot::new_local(file_set)]);
210         change.set_crate_graph(crate_graph);
211
212         ChangeFixture { file_position, files, change }
213     }
214 }
215
216 struct FileMeta {
217     path: String,
218     krate: Option<String>,
219     deps: Vec<String>,
220     cfg: CfgOptions,
221     edition: Edition,
222     env: Env,
223 }
224
225 impl From<Fixture> for FileMeta {
226     fn from(f: Fixture) -> FileMeta {
227         let mut cfg = CfgOptions::default();
228         f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
229         f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
230
231         FileMeta {
232             path: f.path,
233             krate: f.krate,
234             deps: f.deps,
235             cfg,
236             edition: f
237                 .edition
238                 .as_ref()
239                 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
240             env: f.env.into_iter().collect(),
241         }
242     }
243 }