]> git.lizzy.rs Git - rust.git/blob - crates/test_utils/src/fixture.rs
Merge #10225
[rust.git] / crates / test_utils / src / fixture.rs
1 //! Defines `Fixture` -- a convenient way to describe the initial state of
2 //! rust-analyzer database from a single string.
3 //!
4 //! Fixtures are strings containing rust source code with optional metadata.
5 //! A fixture without metadata is parsed into a single source file.
6 //! Use this to test functionality local to one file.
7 //!
8 //! Simple Example:
9 //! ```
10 //! r#"
11 //! fn main() {
12 //!     println!("Hello World")
13 //! }
14 //! "#
15 //! ```
16 //!
17 //! Metadata can be added to a fixture after a `//-` comment.
18 //! The basic form is specifying filenames,
19 //! which is also how to define multiple files in a single test fixture
20 //!
21 //! Example using two files in the same crate:
22 //! ```
23 //! "
24 //! //- /main.rs
25 //! mod foo;
26 //! fn main() {
27 //!     foo::bar();
28 //! }
29 //!
30 //! //- /foo.rs
31 //! pub fn bar() {}
32 //! "
33 //! ```
34 //!
35 //! Example using two crates with one file each, with one crate depending on the other:
36 //! ```
37 //! r#"
38 //! //- /main.rs crate:a deps:b
39 //! fn main() {
40 //!     b::foo();
41 //! }
42 //! //- /lib.rs crate:b
43 //! pub fn b() {
44 //!     println!("Hello World")
45 //! }
46 //! "#
47 //! ```
48 //!
49 //! Metadata allows specifying all settings and variables
50 //! that are available in a real rust project:
51 //! - crate names via `crate:cratename`
52 //! - dependencies via `deps:dep1,dep2`
53 //! - configuration settings via `cfg:dbg=false,opt_level=2`
54 //! - environment variables via `env:PATH=/bin,RUST_LOG=debug`
55 //!
56 //! Example using all available metadata:
57 //! ```
58 //! "
59 //! //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
60 //! fn insert_source_code_here() {}
61 //! "
62 //! ```
63
64 use rustc_hash::FxHashMap;
65 use stdx::trim_indent;
66
67 #[derive(Debug, Eq, PartialEq)]
68 pub struct Fixture {
69     pub path: String,
70     pub text: String,
71     pub krate: Option<String>,
72     pub deps: Vec<String>,
73     pub cfg_atoms: Vec<String>,
74     pub cfg_key_values: Vec<(String, String)>,
75     pub edition: Option<String>,
76     pub env: FxHashMap<String, String>,
77     pub introduce_new_source_root: Option<String>,
78 }
79
80 pub struct MiniCore {
81     activated_flags: Vec<String>,
82     valid_flags: Vec<String>,
83 }
84
85 impl Fixture {
86     /// Parses text which looks like this:
87     ///
88     ///  ```not_rust
89     ///  //- some meta
90     ///  line 1
91     ///  line 2
92     ///  //- other meta
93     ///  ```
94     ///
95     /// Fixture can also start with a proc_macros and minicore declaration(in that order):
96     ///
97     /// ```
98     /// //- proc_macros: identity
99     /// //- minicore: sized
100     /// ```
101     ///
102     /// That will include predefined proc macros and a subset of `libcore` into the fixture, see
103     /// `minicore.rs` for what's available.
104     pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<String>, Vec<Fixture>) {
105         let fixture = trim_indent(ra_fixture);
106         let mut fixture = fixture.as_str();
107         let mut mini_core = None;
108         let mut res: Vec<Fixture> = Vec::new();
109         let mut test_proc_macros = vec![];
110
111         if fixture.starts_with("//- proc_macros:") {
112             let first_line = fixture.split_inclusive('\n').next().unwrap();
113             test_proc_macros = first_line
114                 .strip_prefix("//- proc_macros:")
115                 .unwrap()
116                 .split(',')
117                 .map(|it| it.trim().to_string())
118                 .collect();
119             fixture = &fixture[first_line.len()..];
120         }
121
122         if fixture.starts_with("//- minicore:") {
123             let first_line = fixture.split_inclusive('\n').next().unwrap();
124             mini_core = Some(MiniCore::parse(first_line));
125             fixture = &fixture[first_line.len()..];
126         }
127
128         let default = if fixture.contains("//-") { None } else { Some("//- /main.rs") };
129
130         for (ix, line) in default.into_iter().chain(fixture.split_inclusive('\n')).enumerate() {
131             if line.contains("//-") {
132                 assert!(
133                     line.starts_with("//-"),
134                     "Metadata line {} has invalid indentation. \
135                      All metadata lines need to have the same indentation.\n\
136                      The offending line: {:?}",
137                     ix,
138                     line
139                 );
140             }
141
142             if line.starts_with("//-") {
143                 let meta = Fixture::parse_meta_line(line);
144                 res.push(meta)
145             } else {
146                 if line.starts_with("// ")
147                     && line.contains(':')
148                     && !line.contains("::")
149                     && line.chars().all(|it| !it.is_uppercase())
150                 {
151                     panic!("looks like invalid metadata line: {:?}", line)
152                 }
153
154                 if let Some(entry) = res.last_mut() {
155                     entry.text.push_str(line);
156                 }
157             }
158         }
159
160         (mini_core, test_proc_macros, res)
161     }
162
163     //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
164     fn parse_meta_line(meta: &str) -> Fixture {
165         assert!(meta.starts_with("//-"));
166         let meta = meta["//-".len()..].trim();
167         let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
168
169         let path = components[0].to_string();
170         assert!(path.starts_with('/'), "fixture path does not start with `/`: {:?}", path);
171
172         let mut krate = None;
173         let mut deps = Vec::new();
174         let mut edition = None;
175         let mut cfg_atoms = Vec::new();
176         let mut cfg_key_values = Vec::new();
177         let mut env = FxHashMap::default();
178         let mut introduce_new_source_root = None;
179         for component in components[1..].iter() {
180             let (key, value) = component
181                 .split_once(':')
182                 .unwrap_or_else(|| panic!("invalid meta line: {:?}", meta));
183             match key {
184                 "crate" => krate = Some(value.to_string()),
185                 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
186                 "edition" => edition = Some(value.to_string()),
187                 "cfg" => {
188                     for entry in value.split(',') {
189                         match entry.split_once('=') {
190                             Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
191                             None => cfg_atoms.push(entry.to_string()),
192                         }
193                     }
194                 }
195                 "env" => {
196                     for key in value.split(',') {
197                         if let Some((k, v)) = key.split_once('=') {
198                             env.insert(k.into(), v.into());
199                         }
200                     }
201                 }
202                 "new_source_root" => introduce_new_source_root = Some(value.to_string()),
203                 _ => panic!("bad component: {:?}", component),
204             }
205         }
206
207         Fixture {
208             path,
209             text: String::new(),
210             krate,
211             deps,
212             cfg_atoms,
213             cfg_key_values,
214             edition,
215             env,
216             introduce_new_source_root,
217         }
218     }
219 }
220
221 impl MiniCore {
222     fn has_flag(&self, flag: &str) -> bool {
223         self.activated_flags.iter().any(|it| it == flag)
224     }
225
226     #[track_caller]
227     fn assert_valid_flag(&self, flag: &str) {
228         if !self.valid_flags.iter().any(|it| it == flag) {
229             panic!("invalid flag: {:?}, valid flags: {:?}", flag, self.valid_flags);
230         }
231     }
232
233     fn parse(line: &str) -> MiniCore {
234         let mut res = MiniCore { activated_flags: Vec::new(), valid_flags: Vec::new() };
235
236         let line = line.strip_prefix("//- minicore:").unwrap().trim();
237         for entry in line.split(", ") {
238             if res.has_flag(entry) {
239                 panic!("duplicate minicore flag: {:?}", entry)
240             }
241             res.activated_flags.push(entry.to_string())
242         }
243
244         res
245     }
246
247     /// Strips parts of minicore.rs which are flagged by inactive flags.
248     ///
249     /// This is probably over-engineered to support flags dependencies.
250     pub fn source_code(mut self) -> String {
251         let mut buf = String::new();
252         let raw_mini_core = include_str!("./minicore.rs");
253         let mut lines = raw_mini_core.split_inclusive('\n');
254
255         let mut parsing_flags = false;
256         let mut implications = Vec::new();
257
258         // Parse `//!` preamble and extract flags and dependencies.
259         for line in lines.by_ref() {
260             let line = match line.strip_prefix("//!") {
261                 Some(it) => it,
262                 None => {
263                     assert!(line.trim().is_empty());
264                     break;
265                 }
266             };
267
268             if parsing_flags {
269                 let (flag, deps) = line.split_once(':').unwrap();
270                 let flag = flag.trim();
271                 self.valid_flags.push(flag.to_string());
272                 for dep in deps.split(", ") {
273                     let dep = dep.trim();
274                     if !dep.is_empty() {
275                         self.assert_valid_flag(dep);
276                         implications.push((flag, dep));
277                     }
278                 }
279             }
280
281             if line.contains("Available flags:") {
282                 parsing_flags = true;
283             }
284         }
285
286         for flag in &self.activated_flags {
287             self.assert_valid_flag(flag);
288         }
289
290         // Fixed point loop to compute transitive closure of flags.
291         loop {
292             let mut changed = false;
293             for &(u, v) in implications.iter() {
294                 if self.has_flag(u) && !self.has_flag(v) {
295                     self.activated_flags.push(v.to_string());
296                     changed = true;
297                 }
298             }
299             if !changed {
300                 break;
301             }
302         }
303
304         let mut active_regions = Vec::new();
305         let mut seen_regions = Vec::new();
306         for line in lines {
307             let trimmed = line.trim();
308             if let Some(region) = trimmed.strip_prefix("// region:") {
309                 active_regions.push(region);
310                 continue;
311             }
312             if let Some(region) = trimmed.strip_prefix("// endregion:") {
313                 let prev = active_regions.pop().unwrap();
314                 assert_eq!(prev, region);
315                 continue;
316             }
317
318             let mut line_region = false;
319             if let Some(idx) = trimmed.find("// :") {
320                 line_region = true;
321                 active_regions.push(&trimmed[idx + "// :".len()..]);
322             }
323
324             let mut keep = true;
325             for &region in &active_regions {
326                 assert!(
327                     !region.starts_with(' '),
328                     "region marker starts with a space: {:?}",
329                     region
330                 );
331                 self.assert_valid_flag(region);
332                 seen_regions.push(region);
333                 keep &= self.has_flag(region);
334             }
335
336             if keep {
337                 buf.push_str(line)
338             }
339             if line_region {
340                 active_regions.pop().unwrap();
341             }
342         }
343
344         for flag in &self.valid_flags {
345             if !seen_regions.iter().any(|it| it == flag) {
346                 panic!("unused minicore flag: {:?}", flag);
347             }
348         }
349         format!("{}", buf);
350         buf
351     }
352 }
353
354 #[test]
355 #[should_panic]
356 fn parse_fixture_checks_further_indented_metadata() {
357     Fixture::parse(
358         r"
359         //- /lib.rs
360           mod bar;
361
362           fn foo() {}
363           //- /bar.rs
364           pub fn baz() {}
365           ",
366     );
367 }
368
369 #[test]
370 fn parse_fixture_gets_full_meta() {
371     let (mini_core, proc_macros, parsed) = Fixture::parse(
372         r#"
373 //- proc_macros: identity
374 //- minicore: coerce_unsized
375 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
376 mod m;
377 "#,
378     );
379     assert_eq!(proc_macros, vec!["identity".to_string()]);
380     assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_string()]);
381     assert_eq!(1, parsed.len());
382
383     let meta = &parsed[0];
384     assert_eq!("mod m;\n", meta.text);
385
386     assert_eq!("foo", meta.krate.as_ref().unwrap());
387     assert_eq!("/lib.rs", meta.path);
388     assert_eq!(2, meta.env.len());
389 }