aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock1
-rw-r--r--crates/ra_db/src/fixture.rs77
-rw-r--r--crates/ra_hir_def/src/nameres/tests.rs25
-rw-r--r--crates/ra_ide/src/mock_analysis.rs27
-rw-r--r--crates/rust-analyzer/tests/heavy_tests/support.rs6
-rw-r--r--crates/test_utils/Cargo.toml3
-rw-r--r--crates/test_utils/src/fixture.rs216
-rw-r--r--crates/test_utils/src/lib.rs293
8 files changed, 273 insertions, 375 deletions
diff --git a/Cargo.lock b/Cargo.lock
index f2069c55e..9ea1765cb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1664,7 +1664,6 @@ name = "test_utils"
1664version = "0.1.0" 1664version = "0.1.0"
1665dependencies = [ 1665dependencies = [
1666 "difference", 1666 "difference",
1667 "ra_cfg",
1668 "rustc-hash", 1667 "rustc-hash",
1669 "serde_json", 1668 "serde_json",
1670 "stdx", 1669 "stdx",
diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs
index f7d9118a9..20f291568 100644
--- a/crates/ra_db/src/fixture.rs
+++ b/crates/ra_db/src/fixture.rs
@@ -61,7 +61,7 @@ use std::{str::FromStr, sync::Arc};
61 61
62use ra_cfg::CfgOptions; 62use ra_cfg::CfgOptions;
63use rustc_hash::FxHashMap; 63use rustc_hash::FxHashMap;
64use test_utils::{extract_offset, parse_fixture, parse_single_fixture, FixtureMeta, CURSOR_MARKER}; 64use test_utils::{extract_offset, Fixture, CURSOR_MARKER};
65use vfs::{file_set::FileSet, VfsPath}; 65use vfs::{file_set::FileSet, VfsPath};
66 66
67use crate::{ 67use crate::{
@@ -80,14 +80,14 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static {
80 80
81 fn with_files(ra_fixture: &str) -> Self { 81 fn with_files(ra_fixture: &str) -> Self {
82 let mut db = Self::default(); 82 let mut db = Self::default();
83 let pos = with_files(&mut db, ra_fixture); 83 let (pos, _) = with_files(&mut db, ra_fixture);
84 assert!(pos.is_none()); 84 assert!(pos.is_none());
85 db 85 db
86 } 86 }
87 87
88 fn with_position(ra_fixture: &str) -> (Self, FilePosition) { 88 fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
89 let mut db = Self::default(); 89 let mut db = Self::default();
90 let pos = with_files(&mut db, ra_fixture); 90 let (pos, _) = with_files(&mut db, ra_fixture);
91 (db, pos.unwrap()) 91 (db, pos.unwrap())
92 } 92 }
93 93
@@ -109,12 +109,10 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId
109 109
110 let source_root = SourceRoot::new_local(file_set); 110 let source_root = SourceRoot::new_local(file_set);
111 111
112 let fixture = parse_single_fixture(ra_fixture); 112 let crate_graph = if let Some(meta) = ra_fixture.lines().find(|it| it.contains("//-")) {
113 113 let entry = Fixture::parse_single(meta.trim());
114 let crate_graph = if let Some(entry) = fixture { 114 let meta = match ParsedMeta::from(&entry) {
115 let meta = match ParsedMeta::from(&entry.meta) {
116 ParsedMeta::File(it) => it, 115 ParsedMeta::File(it) => it,
117 _ => panic!("with_single_file only support file meta"),
118 }; 116 };
119 117
120 let mut crate_graph = CrateGraph::default(); 118 let mut crate_graph = CrateGraph::default();
@@ -150,30 +148,27 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId
150 file_id 148 file_id
151} 149}
152 150
153fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option<FilePosition> { 151fn with_files(
154 let fixture = parse_fixture(fixture); 152 db: &mut dyn SourceDatabaseExt,
153 fixture: &str,
154) -> (Option<FilePosition>, Vec<FileId>) {
155 let fixture = Fixture::parse(fixture);
155 156
157 let mut files = Vec::new();
156 let mut crate_graph = CrateGraph::default(); 158 let mut crate_graph = CrateGraph::default();
157 let mut crates = FxHashMap::default(); 159 let mut crates = FxHashMap::default();
158 let mut crate_deps = Vec::new(); 160 let mut crate_deps = Vec::new();
159 let mut default_crate_root: Option<FileId> = None; 161 let mut default_crate_root: Option<FileId> = None;
160 162
161 let mut file_set = FileSet::default(); 163 let mut file_set = FileSet::default();
162 let mut source_root_id = WORKSPACE; 164 let source_root_id = WORKSPACE;
163 let mut source_root_prefix = "/".to_string(); 165 let source_root_prefix = "/".to_string();
164 let mut file_id = FileId(0); 166 let mut file_id = FileId(0);
165 167
166 let mut file_position = None; 168 let mut file_position = None;
167 169
168 for entry in fixture.iter() { 170 for entry in fixture.iter() {
169 let meta = match ParsedMeta::from(&entry.meta) { 171 let meta = match ParsedMeta::from(entry) {
170 ParsedMeta::Root { path } => {
171 let file_set = std::mem::replace(&mut file_set, FileSet::default());
172 db.set_source_root(source_root_id, Arc::new(SourceRoot::new_local(file_set)));
173 source_root_id.0 += 1;
174 source_root_prefix = path;
175 continue;
176 }
177 ParsedMeta::File(it) => it, 172 ParsedMeta::File(it) => it,
178 }; 173 };
179 assert!(meta.path.starts_with(&source_root_prefix)); 174 assert!(meta.path.starts_with(&source_root_prefix));
@@ -210,7 +205,7 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option<FilePosit
210 db.set_file_source_root(file_id, source_root_id); 205 db.set_file_source_root(file_id, source_root_id);
211 let path = VfsPath::new_virtual_path(meta.path); 206 let path = VfsPath::new_virtual_path(meta.path);
212 file_set.insert(file_id, path.into()); 207 file_set.insert(file_id, path.into());
213 208 files.push(file_id);
214 file_id.0 += 1; 209 file_id.0 += 1;
215 } 210 }
216 211
@@ -235,11 +230,10 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option<FilePosit
235 db.set_source_root(source_root_id, Arc::new(SourceRoot::new_local(file_set))); 230 db.set_source_root(source_root_id, Arc::new(SourceRoot::new_local(file_set)));
236 db.set_crate_graph(Arc::new(crate_graph)); 231 db.set_crate_graph(Arc::new(crate_graph));
237 232
238 file_position 233 (file_position, files)
239} 234}
240 235
241enum ParsedMeta { 236enum ParsedMeta {
242 Root { path: String },
243 File(FileMeta), 237 File(FileMeta),
244} 238}
245 239
@@ -252,25 +246,22 @@ struct FileMeta {
252 env: Env, 246 env: Env,
253} 247}
254 248
255impl From<&FixtureMeta> for ParsedMeta { 249impl From<&Fixture> for ParsedMeta {
256 fn from(meta: &FixtureMeta) -> Self { 250 fn from(f: &Fixture) -> Self {
257 match meta { 251 let mut cfg = CfgOptions::default();
258 FixtureMeta::Root { path } => { 252 f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
259 // `Self::Root` causes a false warning: 'variant is never constructed: `Root` ' 253 f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
260 // see https://github.com/rust-lang/rust/issues/69018 254
261 ParsedMeta::Root { path: path.to_owned() } 255 Self::File(FileMeta {
262 } 256 path: f.path.to_owned(),
263 FixtureMeta::File(f) => Self::File(FileMeta { 257 krate: f.crate_name.to_owned(),
264 path: f.path.to_owned(), 258 deps: f.deps.to_owned(),
265 krate: f.crate_name.to_owned(), 259 cfg,
266 deps: f.deps.to_owned(), 260 edition: f
267 cfg: f.cfg.to_owned(), 261 .edition
268 edition: f 262 .as_ref()
269 .edition 263 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
270 .as_ref() 264 env: Env::from(f.env.iter()),
271 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), 265 })
272 env: Env::from(f.env.iter()),
273 }),
274 }
275 } 266 }
276} 267}
diff --git a/crates/ra_hir_def/src/nameres/tests.rs b/crates/ra_hir_def/src/nameres/tests.rs
index 05cd0297d..503099fb7 100644
--- a/crates/ra_hir_def/src/nameres/tests.rs
+++ b/crates/ra_hir_def/src/nameres/tests.rs
@@ -424,31 +424,6 @@ fn extern_crate_rename_2015_edition() {
424} 424}
425 425
426#[test] 426#[test]
427fn import_across_source_roots() {
428 let map = def_map(
429 "
430 //- /main.rs crate:main deps:test_crate
431 use test_crate::a::b::C;
432
433 //- root /test_crate/
434
435 //- /test_crate/lib.rs crate:test_crate
436 pub mod a {
437 pub mod b {
438 pub struct C;
439 }
440 }
441
442 ",
443 );
444
445 assert_snapshot!(map, @r###"
446 ⋮crate
447 ⋮C: t v
448 "###);
449}
450
451#[test]
452fn reexport_across_crates() { 427fn reexport_across_crates() {
453 let map = def_map( 428 let map = def_map(
454 " 429 "
diff --git a/crates/ra_ide/src/mock_analysis.rs b/crates/ra_ide/src/mock_analysis.rs
index 58fafecab..981bdf924 100644
--- a/crates/ra_ide/src/mock_analysis.rs
+++ b/crates/ra_ide/src/mock_analysis.rs
@@ -3,7 +3,7 @@ use std::{str::FromStr, sync::Arc};
3 3
4use ra_cfg::CfgOptions; 4use ra_cfg::CfgOptions;
5use ra_db::{CrateName, Env, FileSet, SourceRoot, VfsPath}; 5use ra_db::{CrateName, Env, FileSet, SourceRoot, VfsPath};
6use test_utils::{extract_offset, extract_range, parse_fixture, FixtureEntry, CURSOR_MARKER}; 6use test_utils::{extract_offset, extract_range, Fixture, CURSOR_MARKER};
7 7
8use crate::{ 8use crate::{
9 Analysis, AnalysisChange, AnalysisHost, CrateGraph, Edition, FileId, FilePosition, FileRange, 9 Analysis, AnalysisChange, AnalysisHost, CrateGraph, Edition, FileId, FilePosition, FileRange,
@@ -12,7 +12,7 @@ use crate::{
12#[derive(Debug)] 12#[derive(Debug)]
13enum MockFileData { 13enum MockFileData {
14 Plain { path: String, content: String }, 14 Plain { path: String, content: String },
15 Fixture(FixtureEntry), 15 Fixture(Fixture),
16} 16}
17 17
18impl MockFileData { 18impl MockFileData {
@@ -25,7 +25,7 @@ impl MockFileData {
25 fn path(&self) -> &str { 25 fn path(&self) -> &str {
26 match self { 26 match self {
27 MockFileData::Plain { path, .. } => path.as_str(), 27 MockFileData::Plain { path, .. } => path.as_str(),
28 MockFileData::Fixture(f) => f.meta.path(), 28 MockFileData::Fixture(f) => f.path.as_str(),
29 } 29 }
30 } 30 }
31 31
@@ -39,7 +39,10 @@ impl MockFileData {
39 fn cfg_options(&self) -> CfgOptions { 39 fn cfg_options(&self) -> CfgOptions {
40 match self { 40 match self {
41 MockFileData::Fixture(f) => { 41 MockFileData::Fixture(f) => {
42 f.meta.cfg_options().map_or_else(Default::default, |o| o.clone()) 42 let mut cfg = CfgOptions::default();
43 f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
44 f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
45 cfg
43 } 46 }
44 _ => CfgOptions::default(), 47 _ => CfgOptions::default(),
45 } 48 }
@@ -48,7 +51,7 @@ impl MockFileData {
48 fn edition(&self) -> Edition { 51 fn edition(&self) -> Edition {
49 match self { 52 match self {
50 MockFileData::Fixture(f) => { 53 MockFileData::Fixture(f) => {
51 f.meta.edition().map_or(Edition::Edition2018, |v| Edition::from_str(v).unwrap()) 54 f.edition.as_ref().map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap())
52 } 55 }
53 _ => Edition::Edition2018, 56 _ => Edition::Edition2018,
54 } 57 }
@@ -56,14 +59,14 @@ impl MockFileData {
56 59
57 fn env(&self) -> Env { 60 fn env(&self) -> Env {
58 match self { 61 match self {
59 MockFileData::Fixture(f) => Env::from(f.meta.env()), 62 MockFileData::Fixture(f) => Env::from(f.env.iter()),
60 _ => Env::default(), 63 _ => Env::default(),
61 } 64 }
62 } 65 }
63} 66}
64 67
65impl From<FixtureEntry> for MockFileData { 68impl From<Fixture> for MockFileData {
66 fn from(fixture: FixtureEntry) -> Self { 69 fn from(fixture: Fixture) -> Self {
67 Self::Fixture(fixture) 70 Self::Fixture(fixture)
68 } 71 }
69} 72}
@@ -91,7 +94,7 @@ impl MockAnalysis {
91 /// ``` 94 /// ```
92 pub fn with_files(fixture: &str) -> MockAnalysis { 95 pub fn with_files(fixture: &str) -> MockAnalysis {
93 let mut res = MockAnalysis::new(); 96 let mut res = MockAnalysis::new();
94 for entry in parse_fixture(fixture) { 97 for entry in Fixture::parse(fixture) {
95 res.add_file_fixture(entry); 98 res.add_file_fixture(entry);
96 } 99 }
97 res 100 res
@@ -102,7 +105,7 @@ impl MockAnalysis {
102 pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) { 105 pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) {
103 let mut position = None; 106 let mut position = None;
104 let mut res = MockAnalysis::new(); 107 let mut res = MockAnalysis::new();
105 for entry in parse_fixture(fixture) { 108 for entry in Fixture::parse(fixture) {
106 if entry.text.contains(CURSOR_MARKER) { 109 if entry.text.contains(CURSOR_MARKER) {
107 assert!(position.is_none(), "only one marker (<|>) per fixture is allowed"); 110 assert!(position.is_none(), "only one marker (<|>) per fixture is allowed");
108 position = Some(res.add_file_fixture_with_position(entry)); 111 position = Some(res.add_file_fixture_with_position(entry));
@@ -114,13 +117,13 @@ impl MockAnalysis {
114 (res, position) 117 (res, position)
115 } 118 }
116 119
117 pub fn add_file_fixture(&mut self, fixture: FixtureEntry) -> FileId { 120 pub fn add_file_fixture(&mut self, fixture: Fixture) -> FileId {
118 let file_id = self.next_id(); 121 let file_id = self.next_id();
119 self.files.push(MockFileData::from(fixture)); 122 self.files.push(MockFileData::from(fixture));
120 file_id 123 file_id
121 } 124 }
122 125
123 pub fn add_file_fixture_with_position(&mut self, mut fixture: FixtureEntry) -> FilePosition { 126 pub fn add_file_fixture_with_position(&mut self, mut fixture: Fixture) -> FilePosition {
124 let (offset, text) = extract_offset(&fixture.text); 127 let (offset, text) = extract_offset(&fixture.text);
125 fixture.text = text; 128 fixture.text = text;
126 let file_id = self.next_id(); 129 let file_id = self.next_id();
diff --git a/crates/rust-analyzer/tests/heavy_tests/support.rs b/crates/rust-analyzer/tests/heavy_tests/support.rs
index bb8585355..e80ffe5d1 100644
--- a/crates/rust-analyzer/tests/heavy_tests/support.rs
+++ b/crates/rust-analyzer/tests/heavy_tests/support.rs
@@ -17,7 +17,7 @@ use lsp_types::{ProgressParams, ProgressParamsValue};
17use serde::Serialize; 17use serde::Serialize;
18use serde_json::{to_string_pretty, Value}; 18use serde_json::{to_string_pretty, Value};
19use tempfile::TempDir; 19use tempfile::TempDir;
20use test_utils::{find_mismatch, parse_fixture}; 20use test_utils::{find_mismatch, Fixture};
21 21
22use ra_project_model::ProjectManifest; 22use ra_project_model::ProjectManifest;
23use rust_analyzer::{ 23use rust_analyzer::{
@@ -68,8 +68,8 @@ impl<'a> Project<'a> {
68 68
69 let mut paths = vec![]; 69 let mut paths = vec![];
70 70
71 for entry in parse_fixture(self.fixture) { 71 for entry in Fixture::parse(self.fixture) {
72 let path = tmp_dir.path().join(&entry.meta.path()['/'.len_utf8()..]); 72 let path = tmp_dir.path().join(&entry.path['/'.len_utf8()..]);
73 fs::create_dir_all(path.parent().unwrap()).unwrap(); 73 fs::create_dir_all(path.parent().unwrap()).unwrap();
74 fs::write(path.as_path(), entry.text.as_bytes()).unwrap(); 74 fs::write(path.as_path(), entry.text.as_bytes()).unwrap();
75 paths.push((path, entry.text)); 75 paths.push((path, entry.text));
diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml
index afd2005f8..6821db1e8 100644
--- a/crates/test_utils/Cargo.toml
+++ b/crates/test_utils/Cargo.toml
@@ -8,10 +8,9 @@ authors = ["rust-analyzer developers"]
8doctest = false 8doctest = false
9 9
10[dependencies] 10[dependencies]
11# Avoid adding deps here, this crate is widely used in tests it should compile fast!
11difference = "2.0.0" 12difference = "2.0.0"
12text-size = "1.0.0" 13text-size = "1.0.0"
13serde_json = "1.0.48" 14serde_json = "1.0.48"
14rustc-hash = "1.1.0" 15rustc-hash = "1.1.0"
15
16ra_cfg = { path = "../ra_cfg" }
17stdx = { path = "../stdx" } 16stdx = { path = "../stdx" }
diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs
new file mode 100644
index 000000000..9108e49d9
--- /dev/null
+++ b/crates/test_utils/src/fixture.rs
@@ -0,0 +1,216 @@
1//! Defines `Fixture` -- a convenient way to describe the initial state of
2//! rust-analyzer database from a single string.
3
4use rustc_hash::FxHashMap;
5use stdx::split1;
6
7#[derive(Debug, Eq, PartialEq)]
8pub struct Fixture {
9 pub path: String,
10 pub text: String,
11 pub crate_name: Option<String>,
12 pub deps: Vec<String>,
13 pub cfg_atoms: Vec<String>,
14 pub cfg_key_values: Vec<(String, String)>,
15 pub edition: Option<String>,
16 pub env: FxHashMap<String, String>,
17}
18
19impl Fixture {
20 /// Parses text which looks like this:
21 ///
22 /// ```not_rust
23 /// //- some meta
24 /// line 1
25 /// line 2
26 /// // - other meta
27 /// ```
28 pub fn parse(ra_fixture: &str) -> Vec<Fixture> {
29 let fixture = indent_first_line(ra_fixture);
30 let margin = fixture_margin(&fixture);
31
32 let mut lines = fixture
33 .split('\n') // don't use `.lines` to not drop `\r\n`
34 .enumerate()
35 .filter_map(|(ix, line)| {
36 if line.len() >= margin {
37 assert!(line[..margin].trim().is_empty());
38 let line_content = &line[margin..];
39 if !line_content.starts_with("//-") {
40 assert!(
41 !line_content.contains("//-"),
42 r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation.
43The offending line: {:?}"#,
44 ix,
45 line
46 );
47 }
48 Some(line_content)
49 } else {
50 assert!(line.trim().is_empty());
51 None
52 }
53 });
54
55 let mut res: Vec<Fixture> = Vec::new();
56 for line in lines.by_ref() {
57 if line.starts_with("//-") {
58 let meta = Fixture::parse_single(line);
59 res.push(meta)
60 } else if let Some(entry) = res.last_mut() {
61 entry.text.push_str(line);
62 entry.text.push('\n');
63 }
64 }
65 res
66 }
67
68 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
69 pub fn parse_single(meta: &str) -> Fixture {
70 assert!(meta.starts_with("//-"));
71 let meta = meta["//-".len()..].trim();
72 let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
73
74 let path = components[0].to_string();
75 assert!(path.starts_with("/"));
76
77 let mut krate = None;
78 let mut deps = Vec::new();
79 let mut edition = None;
80 let mut cfg_atoms = Vec::new();
81 let mut cfg_key_values = Vec::new();
82 let mut env = FxHashMap::default();
83 for component in components[1..].iter() {
84 let (key, value) = split1(component, ':').unwrap();
85 match key {
86 "crate" => krate = Some(value.to_string()),
87 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
88 "edition" => edition = Some(value.to_string()),
89 "cfg" => {
90 for entry in value.split(',') {
91 match split1(entry, '=') {
92 Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
93 None => cfg_atoms.push(entry.to_string()),
94 }
95 }
96 }
97 "env" => {
98 for key in value.split(',') {
99 if let Some((k, v)) = split1(key, '=') {
100 env.insert(k.into(), v.into());
101 }
102 }
103 }
104 _ => panic!("bad component: {:?}", component),
105 }
106 }
107
108 Fixture {
109 path,
110 text: String::new(),
111 crate_name: krate,
112 deps,
113 cfg_atoms,
114 cfg_key_values,
115 edition,
116 env,
117 }
118 }
119}
120
121/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines.
122/// This allows fixtures to start off in a different indentation, e.g. to align the first line with
123/// the other lines visually:
124/// ```
125/// let fixture = "//- /lib.rs
126/// mod foo;
127/// //- /foo.rs
128/// fn bar() {}
129/// ";
130/// assert_eq!(fixture_margin(fixture),
131/// " //- /lib.rs
132/// mod foo;
133/// //- /foo.rs
134/// fn bar() {}
135/// ")
136/// ```
137fn indent_first_line(fixture: &str) -> String {
138 if fixture.is_empty() {
139 return String::new();
140 }
141 let mut lines = fixture.lines();
142 let first_line = lines.next().unwrap();
143 if first_line.contains("//-") {
144 let rest = lines.collect::<Vec<_>>().join("\n");
145 let fixed_margin = fixture_margin(&rest);
146 let fixed_indent = fixed_margin - indent_len(first_line);
147 format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest)
148 } else {
149 fixture.to_owned()
150 }
151}
152
153fn fixture_margin(fixture: &str) -> usize {
154 fixture
155 .lines()
156 .filter(|it| it.trim_start().starts_with("//-"))
157 .map(indent_len)
158 .next()
159 .expect("empty fixture")
160}
161
162fn indent_len(s: &str) -> usize {
163 s.len() - s.trim_start().len()
164}
165
166#[test]
167#[should_panic]
168fn parse_fixture_checks_further_indented_metadata() {
169 Fixture::parse(
170 r"
171 //- /lib.rs
172 mod bar;
173
174 fn foo() {}
175 //- /bar.rs
176 pub fn baz() {}
177 ",
178 );
179}
180
181#[test]
182fn parse_fixture_can_handle_dedented_first_line() {
183 let fixture = "//- /lib.rs
184 mod foo;
185 //- /foo.rs
186 struct Bar;
187";
188 assert_eq!(
189 Fixture::parse(fixture),
190 Fixture::parse(
191 "//- /lib.rs
192mod foo;
193//- /foo.rs
194struct Bar;
195"
196 )
197 )
198}
199
200#[test]
201fn parse_fixture_gets_full_meta() {
202 let parsed = Fixture::parse(
203 r"
204 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
205 mod m;
206 ",
207 );
208 assert_eq!(1, parsed.len());
209
210 let meta = &parsed[0];
211 assert_eq!("mod m;\n\n", meta.text);
212
213 assert_eq!("foo", meta.crate_name.as_ref().unwrap());
214 assert_eq!("/lib.rs", meta.path);
215 assert_eq!(2, meta.env.len());
216}
diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs
index fd917e43b..3fd8505ed 100644
--- a/crates/test_utils/src/lib.rs
+++ b/crates/test_utils/src/lib.rs
@@ -8,6 +8,7 @@
8 8
9#[macro_use] 9#[macro_use]
10pub mod mark; 10pub mod mark;
11mod fixture;
11 12
12use std::{ 13use std::{
13 env, fs, 14 env, fs,
@@ -15,13 +16,12 @@ use std::{
15}; 16};
16 17
17use serde_json::Value; 18use serde_json::Value;
18use stdx::split1;
19use text_size::{TextRange, TextSize}; 19use text_size::{TextRange, TextSize};
20 20
21pub use ra_cfg::CfgOptions; 21pub use difference::Changeset as __Changeset;
22pub use rustc_hash::FxHashMap; 22pub use rustc_hash::FxHashMap;
23 23
24pub use difference::Changeset as __Changeset; 24pub use crate::fixture::Fixture;
25 25
26pub const CURSOR_MARKER: &str = "<|>"; 26pub const CURSOR_MARKER: &str = "<|>";
27 27
@@ -97,7 +97,7 @@ impl From<RangeOrOffset> for TextRange {
97 fn from(selection: RangeOrOffset) -> Self { 97 fn from(selection: RangeOrOffset) -> Self {
98 match selection { 98 match selection {
99 RangeOrOffset::Range(it) => it, 99 RangeOrOffset::Range(it) => it,
100 RangeOrOffset::Offset(it) => TextRange::new(it, it), 100 RangeOrOffset::Offset(it) => TextRange::empty(it),
101 } 101 }
102 } 102 }
103} 103}
@@ -159,291 +159,6 @@ pub fn add_cursor(text: &str, offset: TextSize) -> String {
159 res 159 res
160} 160}
161 161
162#[derive(Debug, Eq, PartialEq)]
163pub struct FixtureEntry {
164 pub meta: FixtureMeta,
165 pub text: String,
166}
167
168#[derive(Debug, Eq, PartialEq)]
169pub enum FixtureMeta {
170 Root { path: String },
171 File(FileMeta),
172}
173
174#[derive(Debug, Eq, PartialEq)]
175pub struct FileMeta {
176 pub path: String,
177 pub crate_name: Option<String>,
178 pub deps: Vec<String>,
179 pub cfg: CfgOptions,
180 pub edition: Option<String>,
181 pub env: FxHashMap<String, String>,
182}
183
184impl FixtureMeta {
185 pub fn path(&self) -> &str {
186 match self {
187 FixtureMeta::Root { path } => &path,
188 FixtureMeta::File(f) => &f.path,
189 }
190 }
191
192 pub fn crate_name(&self) -> Option<&String> {
193 match self {
194 FixtureMeta::File(f) => f.crate_name.as_ref(),
195 _ => None,
196 }
197 }
198
199 pub fn cfg_options(&self) -> Option<&CfgOptions> {
200 match self {
201 FixtureMeta::File(f) => Some(&f.cfg),
202 _ => None,
203 }
204 }
205
206 pub fn edition(&self) -> Option<&String> {
207 match self {
208 FixtureMeta::File(f) => f.edition.as_ref(),
209 _ => None,
210 }
211 }
212
213 pub fn env(&self) -> impl Iterator<Item = (&String, &String)> {
214 struct EnvIter<'a> {
215 iter: Option<std::collections::hash_map::Iter<'a, String, String>>,
216 }
217
218 impl<'a> EnvIter<'a> {
219 fn new(meta: &'a FixtureMeta) -> Self {
220 Self {
221 iter: match meta {
222 FixtureMeta::File(f) => Some(f.env.iter()),
223 _ => None,
224 },
225 }
226 }
227 }
228
229 impl<'a> Iterator for EnvIter<'a> {
230 type Item = (&'a String, &'a String);
231 fn next(&mut self) -> Option<Self::Item> {
232 self.iter.as_mut().and_then(|i| i.next())
233 }
234 }
235
236 EnvIter::new(self)
237 }
238}
239
240/// Parses text which looks like this:
241///
242/// ```not_rust
243/// //- some meta
244/// line 1
245/// line 2
246/// // - other meta
247/// ```
248pub fn parse_fixture(ra_fixture: &str) -> Vec<FixtureEntry> {
249 let fixture = indent_first_line(ra_fixture);
250 let margin = fixture_margin(&fixture);
251
252 let mut lines = fixture
253 .split('\n') // don't use `.lines` to not drop `\r\n`
254 .enumerate()
255 .filter_map(|(ix, line)| {
256 if line.len() >= margin {
257 assert!(line[..margin].trim().is_empty());
258 let line_content = &line[margin..];
259 if !line_content.starts_with("//-") {
260 assert!(
261 !line_content.contains("//-"),
262 r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation.
263The offending line: {:?}"#,
264 ix,
265 line
266 );
267 }
268 Some(line_content)
269 } else {
270 assert!(line.trim().is_empty());
271 None
272 }
273 });
274
275 let mut res: Vec<FixtureEntry> = Vec::new();
276 for line in lines.by_ref() {
277 if line.starts_with("//-") {
278 let meta = line["//-".len()..].trim().to_string();
279 let meta = parse_meta(&meta);
280 res.push(FixtureEntry { meta, text: String::new() })
281 } else if let Some(entry) = res.last_mut() {
282 entry.text.push_str(line);
283 entry.text.push('\n');
284 }
285 }
286 res
287}
288
289//- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
290fn parse_meta(meta: &str) -> FixtureMeta {
291 let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
292
293 if components[0] == "root" {
294 let path = components[1].to_string();
295 assert!(path.starts_with("/") && path.ends_with("/"));
296 return FixtureMeta::Root { path };
297 }
298
299 let path = components[0].to_string();
300 assert!(path.starts_with("/"));
301
302 let mut krate = None;
303 let mut deps = Vec::new();
304 let mut edition = None;
305 let mut cfg = CfgOptions::default();
306 let mut env = FxHashMap::default();
307 for component in components[1..].iter() {
308 let (key, value) = split1(component, ':').unwrap();
309 match key {
310 "crate" => krate = Some(value.to_string()),
311 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
312 "edition" => edition = Some(value.to_string()),
313 "cfg" => {
314 for key in value.split(',') {
315 match split1(key, '=') {
316 None => cfg.insert_atom(key.into()),
317 Some((k, v)) => cfg.insert_key_value(k.into(), v.into()),
318 }
319 }
320 }
321 "env" => {
322 for key in value.split(',') {
323 if let Some((k, v)) = split1(key, '=') {
324 env.insert(k.into(), v.into());
325 }
326 }
327 }
328 _ => panic!("bad component: {:?}", component),
329 }
330 }
331
332 FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env })
333}
334
335/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines.
336/// This allows fixtures to start off in a different indentation, e.g. to align the first line with
337/// the other lines visually:
338/// ```
339/// let fixture = "//- /lib.rs
340/// mod foo;
341/// //- /foo.rs
342/// fn bar() {}
343/// ";
344/// assert_eq!(fixture_margin(fixture),
345/// " //- /lib.rs
346/// mod foo;
347/// //- /foo.rs
348/// fn bar() {}
349/// ")
350/// ```
351fn indent_first_line(fixture: &str) -> String {
352 if fixture.is_empty() {
353 return String::new();
354 }
355 let mut lines = fixture.lines();
356 let first_line = lines.next().unwrap();
357 if first_line.contains("//-") {
358 let rest = lines.collect::<Vec<_>>().join("\n");
359 let fixed_margin = fixture_margin(&rest);
360 let fixed_indent = fixed_margin - indent_len(first_line);
361 format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest)
362 } else {
363 fixture.to_owned()
364 }
365}
366
367fn fixture_margin(fixture: &str) -> usize {
368 fixture
369 .lines()
370 .filter(|it| it.trim_start().starts_with("//-"))
371 .map(indent_len)
372 .next()
373 .expect("empty fixture")
374}
375
376fn indent_len(s: &str) -> usize {
377 s.len() - s.trim_start().len()
378}
379
380#[test]
381#[should_panic]
382fn parse_fixture_checks_further_indented_metadata() {
383 parse_fixture(
384 r"
385 //- /lib.rs
386 mod bar;
387
388 fn foo() {}
389 //- /bar.rs
390 pub fn baz() {}
391 ",
392 );
393}
394
395#[test]
396fn parse_fixture_can_handle_dedented_first_line() {
397 let fixture = "//- /lib.rs
398 mod foo;
399 //- /foo.rs
400 struct Bar;
401";
402 assert_eq!(
403 parse_fixture(fixture),
404 parse_fixture(
405 "//- /lib.rs
406mod foo;
407//- /foo.rs
408struct Bar;
409"
410 )
411 )
412}
413
414#[test]
415fn parse_fixture_gets_full_meta() {
416 let parsed = parse_fixture(
417 r"
418 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
419 mod m;
420 ",
421 );
422 assert_eq!(1, parsed.len());
423
424 let parsed = &parsed[0];
425 assert_eq!("mod m;\n\n", parsed.text);
426
427 let meta = &parsed.meta;
428 assert_eq!("foo", meta.crate_name().unwrap());
429 assert_eq!("/lib.rs", meta.path());
430 assert!(meta.cfg_options().is_some());
431 assert_eq!(2, meta.env().count());
432}
433
434/// Same as `parse_fixture`, except it allow empty fixture
435pub fn parse_single_fixture(ra_fixture: &str) -> Option<FixtureEntry> {
436 if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) {
437 return None;
438 }
439
440 let fixtures = parse_fixture(ra_fixture);
441 if fixtures.len() > 1 {
442 panic!("too many fixtures");
443 }
444 fixtures.into_iter().nth(0)
445}
446
447// Comparison functionality borrowed from cargo: 162// Comparison functionality borrowed from cargo:
448 163
449/// Compare a line with an expected pattern. 164/// Compare a line with an expected pattern.