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