]> git.lizzy.rs Git - rust.git/blobdiff - crates/test_utils/src/fixture.rs
fix: improve parameter completion
[rust.git] / crates / test_utils / src / fixture.rs
index 6ba112de8df265e9321f64cd79fd968725cbdf2a..8c806e7925b15b0eebe1275ade8a76220ede2960 100644 (file)
@@ -70,11 +70,12 @@ pub struct Fixture {
     pub text: String,
     pub krate: Option<String>,
     pub deps: Vec<String>,
+    pub extern_prelude: Option<Vec<String>>,
     pub cfg_atoms: Vec<String>,
     pub cfg_key_values: Vec<(String, String)>,
     pub edition: Option<String>,
     pub env: FxHashMap<String, String>,
-    pub introduce_new_source_root: bool,
+    pub introduce_new_source_root: Option<String>,
 }
 
 pub struct MiniCore {
@@ -92,19 +93,32 @@ impl Fixture {
     ///  //- other meta
     ///  ```
     ///
-    /// Fixture can also start with a minicore declaration:
+    /// Fixture can also start with a proc_macros and minicore declaration(in that order):
     ///
     /// ```
+    /// //- proc_macros: identity
     /// //- minicore: sized
     /// ```
     ///
-    /// That will include a subset of `libcore` into the fixture, see
+    /// That will include predefined proc macros and a subset of `libcore` into the fixture, see
     /// `minicore.rs` for what's available.
-    pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<Fixture>) {
+    pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<String>, Vec<Fixture>) {
         let fixture = trim_indent(ra_fixture);
         let mut fixture = fixture.as_str();
         let mut mini_core = None;
         let mut res: Vec<Fixture> = Vec::new();
+        let mut test_proc_macros = vec![];
+
+        if fixture.starts_with("//- proc_macros:") {
+            let first_line = fixture.split_inclusive('\n').next().unwrap();
+            test_proc_macros = first_line
+                .strip_prefix("//- proc_macros:")
+                .unwrap()
+                .split(',')
+                .map(|it| it.trim().to_string())
+                .collect();
+            fixture = &fixture[first_line.len()..];
+        }
 
         if fixture.starts_with("//- minicore:") {
             let first_line = fixture.split_inclusive('\n').next().unwrap();
@@ -128,13 +142,24 @@ pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<Fixture>) {
 
             if line.starts_with("//-") {
                 let meta = Fixture::parse_meta_line(line);
-                res.push(meta)
-            } else if let Some(entry) = res.last_mut() {
-                entry.text.push_str(line);
+                res.push(meta);
+            } else {
+                if line.starts_with("// ")
+                    && line.contains(':')
+                    && !line.contains("::")
+                    && !line.contains('.')
+                    && line.chars().all(|it| !it.is_uppercase())
+                {
+                    panic!("looks like invalid metadata line: {:?}", line);
+                }
+
+                if let Some(entry) = res.last_mut() {
+                    entry.text.push_str(line);
+                }
             }
         }
 
-        (mini_core, res)
+        (mini_core, test_proc_macros, res)
     }
 
     //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
@@ -144,20 +169,31 @@ fn parse_meta_line(meta: &str) -> Fixture {
         let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
 
         let path = components[0].to_string();
-        assert!(path.starts_with('/'));
+        assert!(path.starts_with('/'), "fixture path does not start with `/`: {:?}", path);
 
         let mut krate = None;
         let mut deps = Vec::new();
+        let mut extern_prelude = None;
         let mut edition = None;
         let mut cfg_atoms = Vec::new();
         let mut cfg_key_values = Vec::new();
         let mut env = FxHashMap::default();
-        let mut introduce_new_source_root = false;
+        let mut introduce_new_source_root = None;
         for component in components[1..].iter() {
-            let (key, value) = component.split_once(':').unwrap();
+            let (key, value) = component
+                .split_once(':')
+                .unwrap_or_else(|| panic!("invalid meta line: {:?}", meta));
             match key {
                 "crate" => krate = Some(value.to_string()),
                 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
+                "extern-prelude" => {
+                    if value.is_empty() {
+                        extern_prelude = Some(Vec::new());
+                    } else {
+                        extern_prelude =
+                            Some(value.split(',').map(|it| it.to_string()).collect::<Vec<_>>());
+                    }
+                }
                 "edition" => edition = Some(value.to_string()),
                 "cfg" => {
                     for entry in value.split(',') {
@@ -174,16 +210,26 @@ fn parse_meta_line(meta: &str) -> Fixture {
                         }
                     }
                 }
-                "new_source_root" => introduce_new_source_root = true,
+                "new_source_root" => introduce_new_source_root = Some(value.to_string()),
                 _ => panic!("bad component: {:?}", component),
             }
         }
 
+        for prelude_dep in extern_prelude.iter().flatten() {
+            assert!(
+                deps.contains(prelude_dep),
+                "extern-prelude {:?} must be a subset of deps {:?}",
+                extern_prelude,
+                deps
+            );
+        }
+
         Fixture {
             path,
             text: String::new(),
             krate,
             deps,
+            extern_prelude,
             cfg_atoms,
             cfg_key_values,
             edition,
@@ -211,9 +257,9 @@ fn parse(line: &str) -> MiniCore {
         let line = line.strip_prefix("//- minicore:").unwrap().trim();
         for entry in line.split(", ") {
             if res.has_flag(entry) {
-                panic!("duplicate minicore flag: {:?}", entry)
+                panic!("duplicate minicore flag: {:?}", entry);
             }
-            res.activated_flags.push(entry.to_string())
+            res.activated_flags.push(entry.to_string());
         }
 
         res
@@ -265,7 +311,7 @@ pub fn source_code(mut self) -> String {
         // Fixed point loop to compute transitive closure of flags.
         loop {
             let mut changed = false;
-            for &(u, v) in implications.iter() {
+            for &(u, v) in &implications {
                 if self.has_flag(u) && !self.has_flag(v) {
                     self.activated_flags.push(v.to_string());
                     changed = true;
@@ -276,37 +322,43 @@ pub fn source_code(mut self) -> String {
             }
         }
 
-        let mut curr_region = "";
+        let mut active_regions = Vec::new();
         let mut seen_regions = Vec::new();
         for line in lines {
             let trimmed = line.trim();
             if let Some(region) = trimmed.strip_prefix("// region:") {
-                assert_eq!(curr_region, "");
-                curr_region = region;
+                active_regions.push(region);
                 continue;
             }
             if let Some(region) = trimmed.strip_prefix("// endregion:") {
-                assert_eq!(curr_region, region);
-                curr_region = "";
+                let prev = active_regions.pop().unwrap();
+                assert_eq!(prev, region);
                 continue;
             }
-            seen_regions.push(curr_region);
 
-            let mut flag = curr_region;
+            let mut line_region = false;
             if let Some(idx) = trimmed.find("// :") {
-                flag = &trimmed[idx + "// :".len()..];
+                line_region = true;
+                active_regions.push(&trimmed[idx + "// :".len()..]);
             }
 
-            let skip = if flag == "" {
-                false
-            } else {
-                assert!(!flag.starts_with(' '), "region marker starts with a space: {:?}", flag);
-                self.assert_valid_flag(flag);
-                !self.has_flag(flag)
-            };
+            let mut keep = true;
+            for &region in &active_regions {
+                assert!(
+                    !region.starts_with(' '),
+                    "region marker starts with a space: {:?}",
+                    region
+                );
+                self.assert_valid_flag(region);
+                seen_regions.push(region);
+                keep &= self.has_flag(region);
+            }
 
-            if !skip {
-                buf.push_str(line)
+            if keep {
+                buf.push_str(line);
+            }
+            if line_region {
+                active_regions.pop().unwrap();
             }
         }
 
@@ -315,7 +367,6 @@ pub fn source_code(mut self) -> String {
                 panic!("unused minicore flag: {:?}", flag);
             }
         }
-
         buf
     }
 }
@@ -337,13 +388,15 @@ pub fn baz() {}
 
 #[test]
 fn parse_fixture_gets_full_meta() {
-    let (mini_core, parsed) = Fixture::parse(
+    let (mini_core, proc_macros, parsed) = Fixture::parse(
         r#"
+//- proc_macros: identity
 //- minicore: coerce_unsized
 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
 mod m;
 "#,
     );
+    assert_eq!(proc_macros, vec!["identity".to_string()]);
     assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_string()]);
     assert_eq!(1, parsed.len());