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