]> git.lizzy.rs Git - rust.git/blob - crates/base_db/src/fixture.rs
Merge #7749
[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, 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
152         let mut file_position = None;
153
154         for entry in fixture {
155             let text = if entry.text.contains(CURSOR_MARKER) {
156                 if entry.text.contains(ESCAPED_CURSOR_MARKER) {
157                     entry.text.replace(ESCAPED_CURSOR_MARKER, CURSOR_MARKER)
158                 } else {
159                     let (range_or_offset, text) = extract_range_or_offset(&entry.text);
160                     assert!(file_position.is_none());
161                     file_position = Some((file_id, range_or_offset));
162                     text.to_string()
163                 }
164             } else {
165                 entry.text.clone()
166             };
167
168             let meta = FileMeta::from(entry);
169             assert!(meta.path.starts_with(&source_root_prefix));
170
171             if let Some(krate) = meta.krate {
172                 let crate_name = CrateName::normalize_dashes(&krate);
173                 let crate_id = crate_graph.add_crate_root(
174                     file_id,
175                     meta.edition,
176                     Some(crate_name.clone().into()),
177                     meta.cfg,
178                     meta.env,
179                     Default::default(),
180                 );
181                 let prev = crates.insert(crate_name.clone(), crate_id);
182                 assert!(prev.is_none());
183                 for dep in meta.deps {
184                     let dep = CrateName::normalize_dashes(&dep);
185                     crate_deps.push((crate_name.clone(), dep))
186                 }
187             } else if meta.path == "/main.rs" || meta.path == "/lib.rs" {
188                 assert!(default_crate_root.is_none());
189                 default_crate_root = Some(file_id);
190                 default_cfg = meta.cfg;
191             }
192
193             change.change_file(file_id, Some(Arc::new(text)));
194             let path = VfsPath::new_virtual_path(meta.path);
195             file_set.insert(file_id, path.into());
196             files.push(file_id);
197             file_id.0 += 1;
198         }
199
200         if crates.is_empty() {
201             let crate_root = default_crate_root.unwrap();
202             crate_graph.add_crate_root(
203                 crate_root,
204                 Edition::Edition2018,
205                 Some(CrateName::new("test").unwrap().into()),
206                 default_cfg,
207                 Env::default(),
208                 Default::default(),
209             );
210         } else {
211             for (from, to) in crate_deps {
212                 let from_id = crates[&from];
213                 let to_id = crates[&to];
214                 crate_graph.add_dep(from_id, CrateName::new(&to).unwrap(), to_id).unwrap();
215             }
216         }
217
218         change.set_roots(vec![SourceRoot::new_local(file_set)]);
219         change.set_crate_graph(crate_graph);
220
221         ChangeFixture { file_position, files, change }
222     }
223 }
224
225 struct FileMeta {
226     path: String,
227     krate: Option<String>,
228     deps: Vec<String>,
229     cfg: CfgOptions,
230     edition: Edition,
231     env: Env,
232 }
233
234 impl From<Fixture> for FileMeta {
235     fn from(f: Fixture) -> FileMeta {
236         let mut cfg = CfgOptions::default();
237         f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
238         f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
239
240         FileMeta {
241             path: f.path,
242             krate: f.krate,
243             deps: f.deps,
244             cfg,
245             edition: f
246                 .edition
247                 .as_ref()
248                 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
249             env: f.env.into_iter().collect(),
250         }
251     }
252 }