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