]> git.lizzy.rs Git - rust.git/blob - crates/test_utils/src/fixture.rs
Merge #10440
[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 extern_prelude: Option<Vec<String>>,
74     pub cfg_atoms: Vec<String>,
75     pub cfg_key_values: Vec<(String, String)>,
76     pub edition: Option<String>,
77     pub env: FxHashMap<String, String>,
78     pub introduce_new_source_root: Option<String>,
79 }
80
81 pub struct MiniCore {
82     activated_flags: Vec<String>,
83     valid_flags: Vec<String>,
84 }
85
86 impl Fixture {
87     /// Parses text which looks like this:
88     ///
89     ///  ```not_rust
90     ///  //- some meta
91     ///  line 1
92     ///  line 2
93     ///  //- other meta
94     ///  ```
95     ///
96     /// Fixture can also start with a proc_macros and minicore declaration(in that order):
97     ///
98     /// ```
99     /// //- proc_macros: identity
100     /// //- minicore: sized
101     /// ```
102     ///
103     /// That will include predefined proc macros and a subset of `libcore` into the fixture, see
104     /// `minicore.rs` for what's available.
105     pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<String>, Vec<Fixture>) {
106         let fixture = trim_indent(ra_fixture);
107         let mut fixture = fixture.as_str();
108         let mut mini_core = None;
109         let mut res: Vec<Fixture> = Vec::new();
110         let mut test_proc_macros = vec![];
111
112         if fixture.starts_with("//- proc_macros:") {
113             let first_line = fixture.split_inclusive('\n').next().unwrap();
114             test_proc_macros = first_line
115                 .strip_prefix("//- proc_macros:")
116                 .unwrap()
117                 .split(',')
118                 .map(|it| it.trim().to_string())
119                 .collect();
120             fixture = &fixture[first_line.len()..];
121         }
122
123         if fixture.starts_with("//- minicore:") {
124             let first_line = fixture.split_inclusive('\n').next().unwrap();
125             mini_core = Some(MiniCore::parse(first_line));
126             fixture = &fixture[first_line.len()..];
127         }
128
129         let default = if fixture.contains("//-") { None } else { Some("//- /main.rs") };
130
131         for (ix, line) in default.into_iter().chain(fixture.split_inclusive('\n')).enumerate() {
132             if line.contains("//-") {
133                 assert!(
134                     line.starts_with("//-"),
135                     "Metadata line {} has invalid indentation. \
136                      All metadata lines need to have the same indentation.\n\
137                      The offending line: {:?}",
138                     ix,
139                     line
140                 );
141             }
142
143             if line.starts_with("//-") {
144                 let meta = Fixture::parse_meta_line(line);
145                 res.push(meta);
146             } else {
147                 if line.starts_with("// ")
148                     && line.contains(':')
149                     && !line.contains("::")
150                     && line.chars().all(|it| !it.is_uppercase())
151                 {
152                     panic!("looks like invalid metadata line: {:?}", line);
153                 }
154
155                 if let Some(entry) = res.last_mut() {
156                     entry.text.push_str(line);
157                 }
158             }
159         }
160
161         (mini_core, test_proc_macros, res)
162     }
163
164     //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
165     fn parse_meta_line(meta: &str) -> Fixture {
166         assert!(meta.starts_with("//-"));
167         let meta = meta["//-".len()..].trim();
168         let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
169
170         let path = components[0].to_string();
171         assert!(path.starts_with('/'), "fixture path does not start with `/`: {:?}", path);
172
173         let mut krate = None;
174         let mut deps = Vec::new();
175         let mut extern_prelude = None;
176         let mut edition = None;
177         let mut cfg_atoms = Vec::new();
178         let mut cfg_key_values = Vec::new();
179         let mut env = FxHashMap::default();
180         let mut introduce_new_source_root = None;
181         for component in components[1..].iter() {
182             let (key, value) = component
183                 .split_once(':')
184                 .unwrap_or_else(|| panic!("invalid meta line: {:?}", meta));
185             match key {
186                 "crate" => krate = Some(value.to_string()),
187                 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
188                 "extern-prelude" => {
189                     if value.is_empty() {
190                         extern_prelude = Some(Vec::new());
191                     } else {
192                         extern_prelude =
193                             Some(value.split(',').map(|it| it.to_string()).collect::<Vec<_>>());
194                     }
195                 }
196                 "edition" => edition = Some(value.to_string()),
197                 "cfg" => {
198                     for entry in value.split(',') {
199                         match entry.split_once('=') {
200                             Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
201                             None => cfg_atoms.push(entry.to_string()),
202                         }
203                     }
204                 }
205                 "env" => {
206                     for key in value.split(',') {
207                         if let Some((k, v)) = key.split_once('=') {
208                             env.insert(k.into(), v.into());
209                         }
210                     }
211                 }
212                 "new_source_root" => introduce_new_source_root = Some(value.to_string()),
213                 _ => panic!("bad component: {:?}", component),
214             }
215         }
216
217         for prelude_dep in extern_prelude.iter().flatten() {
218             assert!(
219                 deps.contains(prelude_dep),
220                 "extern-prelude {:?} must be a subset of deps {:?}",
221                 extern_prelude,
222                 deps
223             );
224         }
225
226         Fixture {
227             path,
228             text: String::new(),
229             krate,
230             deps,
231             extern_prelude,
232             cfg_atoms,
233             cfg_key_values,
234             edition,
235             env,
236             introduce_new_source_root,
237         }
238     }
239 }
240
241 impl MiniCore {
242     fn has_flag(&self, flag: &str) -> bool {
243         self.activated_flags.iter().any(|it| it == flag)
244     }
245
246     #[track_caller]
247     fn assert_valid_flag(&self, flag: &str) {
248         if !self.valid_flags.iter().any(|it| it == flag) {
249             panic!("invalid flag: {:?}, valid flags: {:?}", flag, self.valid_flags);
250         }
251     }
252
253     fn parse(line: &str) -> MiniCore {
254         let mut res = MiniCore { activated_flags: Vec::new(), valid_flags: Vec::new() };
255
256         let line = line.strip_prefix("//- minicore:").unwrap().trim();
257         for entry in line.split(", ") {
258             if res.has_flag(entry) {
259                 panic!("duplicate minicore flag: {:?}", entry);
260             }
261             res.activated_flags.push(entry.to_string());
262         }
263
264         res
265     }
266
267     /// Strips parts of minicore.rs which are flagged by inactive flags.
268     ///
269     /// This is probably over-engineered to support flags dependencies.
270     pub fn source_code(mut self) -> String {
271         let mut buf = String::new();
272         let raw_mini_core = include_str!("./minicore.rs");
273         let mut lines = raw_mini_core.split_inclusive('\n');
274
275         let mut parsing_flags = false;
276         let mut implications = Vec::new();
277
278         // Parse `//!` preamble and extract flags and dependencies.
279         for line in lines.by_ref() {
280             let line = match line.strip_prefix("//!") {
281                 Some(it) => it,
282                 None => {
283                     assert!(line.trim().is_empty());
284                     break;
285                 }
286             };
287
288             if parsing_flags {
289                 let (flag, deps) = line.split_once(':').unwrap();
290                 let flag = flag.trim();
291                 self.valid_flags.push(flag.to_string());
292                 for dep in deps.split(", ") {
293                     let dep = dep.trim();
294                     if !dep.is_empty() {
295                         self.assert_valid_flag(dep);
296                         implications.push((flag, dep));
297                     }
298                 }
299             }
300
301             if line.contains("Available flags:") {
302                 parsing_flags = true;
303             }
304         }
305
306         for flag in &self.activated_flags {
307             self.assert_valid_flag(flag);
308         }
309
310         // Fixed point loop to compute transitive closure of flags.
311         loop {
312             let mut changed = false;
313             for &(u, v) in &implications {
314                 if self.has_flag(u) && !self.has_flag(v) {
315                     self.activated_flags.push(v.to_string());
316                     changed = true;
317                 }
318             }
319             if !changed {
320                 break;
321             }
322         }
323
324         let mut active_regions = Vec::new();
325         let mut seen_regions = Vec::new();
326         for line in lines {
327             let trimmed = line.trim();
328             if let Some(region) = trimmed.strip_prefix("// region:") {
329                 active_regions.push(region);
330                 continue;
331             }
332             if let Some(region) = trimmed.strip_prefix("// endregion:") {
333                 let prev = active_regions.pop().unwrap();
334                 assert_eq!(prev, region);
335                 continue;
336             }
337
338             let mut line_region = false;
339             if let Some(idx) = trimmed.find("// :") {
340                 line_region = true;
341                 active_regions.push(&trimmed[idx + "// :".len()..]);
342             }
343
344             let mut keep = true;
345             for &region in &active_regions {
346                 assert!(
347                     !region.starts_with(' '),
348                     "region marker starts with a space: {:?}",
349                     region
350                 );
351                 self.assert_valid_flag(region);
352                 seen_regions.push(region);
353                 keep &= self.has_flag(region);
354             }
355
356             if keep {
357                 buf.push_str(line);
358             }
359             if line_region {
360                 active_regions.pop().unwrap();
361             }
362         }
363
364         for flag in &self.valid_flags {
365             if !seen_regions.iter().any(|it| it == flag) {
366                 panic!("unused minicore flag: {:?}", flag);
367             }
368         }
369         buf
370     }
371 }
372
373 #[test]
374 #[should_panic]
375 fn parse_fixture_checks_further_indented_metadata() {
376     Fixture::parse(
377         r"
378         //- /lib.rs
379           mod bar;
380
381           fn foo() {}
382           //- /bar.rs
383           pub fn baz() {}
384           ",
385     );
386 }
387
388 #[test]
389 fn parse_fixture_gets_full_meta() {
390     let (mini_core, proc_macros, parsed) = Fixture::parse(
391         r#"
392 //- proc_macros: identity
393 //- minicore: coerce_unsized
394 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
395 mod m;
396 "#,
397     );
398     assert_eq!(proc_macros, vec!["identity".to_string()]);
399     assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_string()]);
400     assert_eq!(1, parsed.len());
401
402     let meta = &parsed[0];
403     assert_eq!("mod m;\n", meta.text);
404
405     assert_eq!("foo", meta.krate.as_ref().unwrap());
406     assert_eq!("/lib.rs", meta.path);
407     assert_eq!(2, meta.env.len());
408 }