From f304874c8c12de6120663ffff7f1bfdc69f19496 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 17:59:56 +0200 Subject: Move fixtures to a separate file --- crates/test_utils/src/fixture.rs | 288 ++++++++++++++++++++++++++++++++++++++ crates/test_utils/src/lib.rs | 292 +-------------------------------------- 2 files changed, 292 insertions(+), 288 deletions(-) create mode 100644 crates/test_utils/src/fixture.rs (limited to 'crates') diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs new file mode 100644 index 000000000..d0a732031 --- /dev/null +++ b/crates/test_utils/src/fixture.rs @@ -0,0 +1,288 @@ +use ra_cfg::CfgOptions; +use rustc_hash::FxHashMap; +use stdx::split1; + +#[derive(Debug, Eq, PartialEq)] +pub struct FixtureEntry { + pub meta: FixtureMeta, + pub text: String, +} + +#[derive(Debug, Eq, PartialEq)] +pub enum FixtureMeta { + Root { path: String }, + File(FileMeta), +} + +#[derive(Debug, Eq, PartialEq)] +pub struct FileMeta { + pub path: String, + pub crate_name: Option, + pub deps: Vec, + pub cfg: CfgOptions, + pub edition: Option, + pub env: FxHashMap, +} + +impl FixtureMeta { + pub fn path(&self) -> &str { + match self { + FixtureMeta::Root { path } => &path, + FixtureMeta::File(f) => &f.path, + } + } + + pub fn crate_name(&self) -> Option<&String> { + match self { + FixtureMeta::File(f) => f.crate_name.as_ref(), + _ => None, + } + } + + pub fn cfg_options(&self) -> Option<&CfgOptions> { + match self { + FixtureMeta::File(f) => Some(&f.cfg), + _ => None, + } + } + + pub fn edition(&self) -> Option<&String> { + match self { + FixtureMeta::File(f) => f.edition.as_ref(), + _ => None, + } + } + + pub fn env(&self) -> impl Iterator { + struct EnvIter<'a> { + iter: Option>, + } + + impl<'a> EnvIter<'a> { + fn new(meta: &'a FixtureMeta) -> Self { + Self { + iter: match meta { + FixtureMeta::File(f) => Some(f.env.iter()), + _ => None, + }, + } + } + } + + impl<'a> Iterator for EnvIter<'a> { + type Item = (&'a String, &'a String); + fn next(&mut self) -> Option { + self.iter.as_mut().and_then(|i| i.next()) + } + } + + EnvIter::new(self) + } +} + +/// Same as `parse_fixture`, except it allow empty fixture +pub fn parse_single_fixture(ra_fixture: &str) -> Option { + if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) { + return None; + } + + let fixtures = parse_fixture(ra_fixture); + if fixtures.len() > 1 { + panic!("too many fixtures"); + } + fixtures.into_iter().nth(0) +} + +/// Parses text which looks like this: +/// +/// ```not_rust +/// //- some meta +/// line 1 +/// line 2 +/// // - other meta +/// ``` +pub fn parse_fixture(ra_fixture: &str) -> Vec { + let fixture = indent_first_line(ra_fixture); + let margin = fixture_margin(&fixture); + + let mut lines = fixture + .split('\n') // don't use `.lines` to not drop `\r\n` + .enumerate() + .filter_map(|(ix, line)| { + if line.len() >= margin { + assert!(line[..margin].trim().is_empty()); + let line_content = &line[margin..]; + if !line_content.starts_with("//-") { + assert!( + !line_content.contains("//-"), + r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation. +The offending line: {:?}"#, + ix, + line + ); + } + Some(line_content) + } else { + assert!(line.trim().is_empty()); + None + } + }); + + let mut res: Vec = Vec::new(); + for line in lines.by_ref() { + if line.starts_with("//-") { + let meta = line["//-".len()..].trim().to_string(); + let meta = parse_meta(&meta); + res.push(FixtureEntry { meta, text: String::new() }) + } else if let Some(entry) = res.last_mut() { + entry.text.push_str(line); + entry.text.push('\n'); + } + } + res +} + +//- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo +fn parse_meta(meta: &str) -> FixtureMeta { + let components = meta.split_ascii_whitespace().collect::>(); + + if components[0] == "root" { + let path = components[1].to_string(); + assert!(path.starts_with("/") && path.ends_with("/")); + return FixtureMeta::Root { path }; + } + + let path = components[0].to_string(); + assert!(path.starts_with("/")); + + let mut krate = None; + let mut deps = Vec::new(); + let mut edition = None; + let mut cfg = CfgOptions::default(); + let mut env = FxHashMap::default(); + for component in components[1..].iter() { + let (key, value) = split1(component, ':').unwrap(); + match key { + "crate" => krate = Some(value.to_string()), + "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), + "edition" => edition = Some(value.to_string()), + "cfg" => { + for key in value.split(',') { + match split1(key, '=') { + None => cfg.insert_atom(key.into()), + Some((k, v)) => cfg.insert_key_value(k.into(), v.into()), + } + } + } + "env" => { + for key in value.split(',') { + if let Some((k, v)) = split1(key, '=') { + env.insert(k.into(), v.into()); + } + } + } + _ => panic!("bad component: {:?}", component), + } + } + + FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env }) +} + +/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. +/// This allows fixtures to start off in a different indentation, e.g. to align the first line with +/// the other lines visually: +/// ``` +/// let fixture = "//- /lib.rs +/// mod foo; +/// //- /foo.rs +/// fn bar() {} +/// "; +/// assert_eq!(fixture_margin(fixture), +/// " //- /lib.rs +/// mod foo; +/// //- /foo.rs +/// fn bar() {} +/// ") +/// ``` +fn indent_first_line(fixture: &str) -> String { + if fixture.is_empty() { + return String::new(); + } + let mut lines = fixture.lines(); + let first_line = lines.next().unwrap(); + if first_line.contains("//-") { + let rest = lines.collect::>().join("\n"); + let fixed_margin = fixture_margin(&rest); + let fixed_indent = fixed_margin - indent_len(first_line); + format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest) + } else { + fixture.to_owned() + } +} + +fn fixture_margin(fixture: &str) -> usize { + fixture + .lines() + .filter(|it| it.trim_start().starts_with("//-")) + .map(indent_len) + .next() + .expect("empty fixture") +} + +fn indent_len(s: &str) -> usize { + s.len() - s.trim_start().len() +} + +#[test] +#[should_panic] +fn parse_fixture_checks_further_indented_metadata() { + parse_fixture( + r" + //- /lib.rs + mod bar; + + fn foo() {} + //- /bar.rs + pub fn baz() {} + ", + ); +} + +#[test] +fn parse_fixture_can_handle_dedented_first_line() { + let fixture = "//- /lib.rs + mod foo; + //- /foo.rs + struct Bar; +"; + assert_eq!( + parse_fixture(fixture), + parse_fixture( + "//- /lib.rs +mod foo; +//- /foo.rs +struct Bar; +" + ) + ) +} + +#[test] +fn parse_fixture_gets_full_meta() { + let parsed = parse_fixture( + r" + //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo + mod m; + ", + ); + assert_eq!(1, parsed.len()); + + let parsed = &parsed[0]; + assert_eq!("mod m;\n\n", parsed.text); + + let meta = &parsed.meta; + assert_eq!("foo", meta.crate_name().unwrap()); + assert_eq!("/lib.rs", meta.path()); + assert!(meta.cfg_options().is_some()); + assert_eq!(2, meta.env().count()); +} diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index fd917e43b..f22fcc8b2 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs @@ -8,6 +8,7 @@ #[macro_use] pub mod mark; +mod fixture; use std::{ env, fs, @@ -15,13 +16,13 @@ use std::{ }; use serde_json::Value; -use stdx::split1; use text_size::{TextRange, TextSize}; +pub use difference::Changeset as __Changeset; pub use ra_cfg::CfgOptions; pub use rustc_hash::FxHashMap; -pub use difference::Changeset as __Changeset; +pub use crate::fixture::{parse_fixture, parse_single_fixture, FixtureEntry, FixtureMeta}; pub const CURSOR_MARKER: &str = "<|>"; @@ -97,7 +98,7 @@ impl From for TextRange { fn from(selection: RangeOrOffset) -> Self { match selection { RangeOrOffset::Range(it) => it, - RangeOrOffset::Offset(it) => TextRange::new(it, it), + RangeOrOffset::Offset(it) => TextRange::empty(it), } } } @@ -159,291 +160,6 @@ pub fn add_cursor(text: &str, offset: TextSize) -> String { res } -#[derive(Debug, Eq, PartialEq)] -pub struct FixtureEntry { - pub meta: FixtureMeta, - pub text: String, -} - -#[derive(Debug, Eq, PartialEq)] -pub enum FixtureMeta { - Root { path: String }, - File(FileMeta), -} - -#[derive(Debug, Eq, PartialEq)] -pub struct FileMeta { - pub path: String, - pub crate_name: Option, - pub deps: Vec, - pub cfg: CfgOptions, - pub edition: Option, - pub env: FxHashMap, -} - -impl FixtureMeta { - pub fn path(&self) -> &str { - match self { - FixtureMeta::Root { path } => &path, - FixtureMeta::File(f) => &f.path, - } - } - - pub fn crate_name(&self) -> Option<&String> { - match self { - FixtureMeta::File(f) => f.crate_name.as_ref(), - _ => None, - } - } - - pub fn cfg_options(&self) -> Option<&CfgOptions> { - match self { - FixtureMeta::File(f) => Some(&f.cfg), - _ => None, - } - } - - pub fn edition(&self) -> Option<&String> { - match self { - FixtureMeta::File(f) => f.edition.as_ref(), - _ => None, - } - } - - pub fn env(&self) -> impl Iterator { - struct EnvIter<'a> { - iter: Option>, - } - - impl<'a> EnvIter<'a> { - fn new(meta: &'a FixtureMeta) -> Self { - Self { - iter: match meta { - FixtureMeta::File(f) => Some(f.env.iter()), - _ => None, - }, - } - } - } - - impl<'a> Iterator for EnvIter<'a> { - type Item = (&'a String, &'a String); - fn next(&mut self) -> Option { - self.iter.as_mut().and_then(|i| i.next()) - } - } - - EnvIter::new(self) - } -} - -/// Parses text which looks like this: -/// -/// ```not_rust -/// //- some meta -/// line 1 -/// line 2 -/// // - other meta -/// ``` -pub fn parse_fixture(ra_fixture: &str) -> Vec { - let fixture = indent_first_line(ra_fixture); - let margin = fixture_margin(&fixture); - - let mut lines = fixture - .split('\n') // don't use `.lines` to not drop `\r\n` - .enumerate() - .filter_map(|(ix, line)| { - if line.len() >= margin { - assert!(line[..margin].trim().is_empty()); - let line_content = &line[margin..]; - if !line_content.starts_with("//-") { - assert!( - !line_content.contains("//-"), - r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation. -The offending line: {:?}"#, - ix, - line - ); - } - Some(line_content) - } else { - assert!(line.trim().is_empty()); - None - } - }); - - let mut res: Vec = Vec::new(); - for line in lines.by_ref() { - if line.starts_with("//-") { - let meta = line["//-".len()..].trim().to_string(); - let meta = parse_meta(&meta); - res.push(FixtureEntry { meta, text: String::new() }) - } else if let Some(entry) = res.last_mut() { - entry.text.push_str(line); - entry.text.push('\n'); - } - } - res -} - -//- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo -fn parse_meta(meta: &str) -> FixtureMeta { - let components = meta.split_ascii_whitespace().collect::>(); - - if components[0] == "root" { - let path = components[1].to_string(); - assert!(path.starts_with("/") && path.ends_with("/")); - return FixtureMeta::Root { path }; - } - - let path = components[0].to_string(); - assert!(path.starts_with("/")); - - let mut krate = None; - let mut deps = Vec::new(); - let mut edition = None; - let mut cfg = CfgOptions::default(); - let mut env = FxHashMap::default(); - for component in components[1..].iter() { - let (key, value) = split1(component, ':').unwrap(); - match key { - "crate" => krate = Some(value.to_string()), - "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), - "edition" => edition = Some(value.to_string()), - "cfg" => { - for key in value.split(',') { - match split1(key, '=') { - None => cfg.insert_atom(key.into()), - Some((k, v)) => cfg.insert_key_value(k.into(), v.into()), - } - } - } - "env" => { - for key in value.split(',') { - if let Some((k, v)) = split1(key, '=') { - env.insert(k.into(), v.into()); - } - } - } - _ => panic!("bad component: {:?}", component), - } - } - - FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env }) -} - -/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. -/// This allows fixtures to start off in a different indentation, e.g. to align the first line with -/// the other lines visually: -/// ``` -/// let fixture = "//- /lib.rs -/// mod foo; -/// //- /foo.rs -/// fn bar() {} -/// "; -/// assert_eq!(fixture_margin(fixture), -/// " //- /lib.rs -/// mod foo; -/// //- /foo.rs -/// fn bar() {} -/// ") -/// ``` -fn indent_first_line(fixture: &str) -> String { - if fixture.is_empty() { - return String::new(); - } - let mut lines = fixture.lines(); - let first_line = lines.next().unwrap(); - if first_line.contains("//-") { - let rest = lines.collect::>().join("\n"); - let fixed_margin = fixture_margin(&rest); - let fixed_indent = fixed_margin - indent_len(first_line); - format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest) - } else { - fixture.to_owned() - } -} - -fn fixture_margin(fixture: &str) -> usize { - fixture - .lines() - .filter(|it| it.trim_start().starts_with("//-")) - .map(indent_len) - .next() - .expect("empty fixture") -} - -fn indent_len(s: &str) -> usize { - s.len() - s.trim_start().len() -} - -#[test] -#[should_panic] -fn parse_fixture_checks_further_indented_metadata() { - parse_fixture( - r" - //- /lib.rs - mod bar; - - fn foo() {} - //- /bar.rs - pub fn baz() {} - ", - ); -} - -#[test] -fn parse_fixture_can_handle_dedented_first_line() { - let fixture = "//- /lib.rs - mod foo; - //- /foo.rs - struct Bar; -"; - assert_eq!( - parse_fixture(fixture), - parse_fixture( - "//- /lib.rs -mod foo; -//- /foo.rs -struct Bar; -" - ) - ) -} - -#[test] -fn parse_fixture_gets_full_meta() { - let parsed = parse_fixture( - r" - //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo - mod m; - ", - ); - assert_eq!(1, parsed.len()); - - let parsed = &parsed[0]; - assert_eq!("mod m;\n\n", parsed.text); - - let meta = &parsed.meta; - assert_eq!("foo", meta.crate_name().unwrap()); - assert_eq!("/lib.rs", meta.path()); - assert!(meta.cfg_options().is_some()); - assert_eq!(2, meta.env().count()); -} - -/// Same as `parse_fixture`, except it allow empty fixture -pub fn parse_single_fixture(ra_fixture: &str) -> Option { - if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) { - return None; - } - - let fixtures = parse_fixture(ra_fixture); - if fixtures.len() > 1 { - panic!("too many fixtures"); - } - fixtures.into_iter().nth(0) -} - // Comparison functionality borrowed from cargo: /// Compare a line with an expected pattern. -- cgit v1.2.3 From 6996ec860bde7e6186ba8609b68ef51b8713e2ea Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 18:17:43 +0200 Subject: Drop rarely used fixture functionality --- crates/ra_db/src/fixture.rs | 18 ++---------------- crates/ra_hir_def/src/nameres/tests.rs | 25 ------------------------- crates/test_utils/src/fixture.rs | 12 ------------ 3 files changed, 2 insertions(+), 53 deletions(-) (limited to 'crates') diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index f7d9118a9..bf897baff 100644 --- a/crates/ra_db/src/fixture.rs +++ b/crates/ra_db/src/fixture.rs @@ -114,7 +114,6 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId let crate_graph = if let Some(entry) = fixture { let meta = match ParsedMeta::from(&entry.meta) { ParsedMeta::File(it) => it, - _ => panic!("with_single_file only support file meta"), }; let mut crate_graph = CrateGraph::default(); @@ -159,21 +158,14 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option = None; let mut file_set = FileSet::default(); - let mut source_root_id = WORKSPACE; - let mut source_root_prefix = "/".to_string(); + let source_root_id = WORKSPACE; + let source_root_prefix = "/".to_string(); let mut file_id = FileId(0); let mut file_position = None; for entry in fixture.iter() { let meta = match ParsedMeta::from(&entry.meta) { - ParsedMeta::Root { path } => { - let file_set = std::mem::replace(&mut file_set, FileSet::default()); - db.set_source_root(source_root_id, Arc::new(SourceRoot::new_local(file_set))); - source_root_id.0 += 1; - source_root_prefix = path; - continue; - } ParsedMeta::File(it) => it, }; assert!(meta.path.starts_with(&source_root_prefix)); @@ -239,7 +231,6 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option for ParsedMeta { fn from(meta: &FixtureMeta) -> Self { match meta { - FixtureMeta::Root { path } => { - // `Self::Root` causes a false warning: 'variant is never constructed: `Root` ' - // see https://github.com/rust-lang/rust/issues/69018 - ParsedMeta::Root { path: path.to_owned() } - } FixtureMeta::File(f) => Self::File(FileMeta { path: f.path.to_owned(), krate: f.crate_name.to_owned(), 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 @@ -423,31 +423,6 @@ fn extern_crate_rename_2015_edition() { ); } -#[test] -fn import_across_source_roots() { - let map = def_map( - " - //- /main.rs crate:main deps:test_crate - use test_crate::a::b::C; - - //- root /test_crate/ - - //- /test_crate/lib.rs crate:test_crate - pub mod a { - pub mod b { - pub struct C; - } - } - - ", - ); - - assert_snapshot!(map, @r###" - ⋮crate - ⋮C: t v - "###); -} - #[test] fn reexport_across_crates() { let map = def_map( diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs index d0a732031..0dbeb01b1 100644 --- a/crates/test_utils/src/fixture.rs +++ b/crates/test_utils/src/fixture.rs @@ -10,7 +10,6 @@ pub struct FixtureEntry { #[derive(Debug, Eq, PartialEq)] pub enum FixtureMeta { - Root { path: String }, File(FileMeta), } @@ -27,7 +26,6 @@ pub struct FileMeta { impl FixtureMeta { pub fn path(&self) -> &str { match self { - FixtureMeta::Root { path } => &path, FixtureMeta::File(f) => &f.path, } } @@ -35,21 +33,18 @@ impl FixtureMeta { pub fn crate_name(&self) -> Option<&String> { match self { FixtureMeta::File(f) => f.crate_name.as_ref(), - _ => None, } } pub fn cfg_options(&self) -> Option<&CfgOptions> { match self { FixtureMeta::File(f) => Some(&f.cfg), - _ => None, } } pub fn edition(&self) -> Option<&String> { match self { FixtureMeta::File(f) => f.edition.as_ref(), - _ => None, } } @@ -63,7 +58,6 @@ impl FixtureMeta { Self { iter: match meta { FixtureMeta::File(f) => Some(f.env.iter()), - _ => None, }, } } @@ -146,12 +140,6 @@ The offending line: {:?}"#, fn parse_meta(meta: &str) -> FixtureMeta { let components = meta.split_ascii_whitespace().collect::>(); - if components[0] == "root" { - let path = components[1].to_string(); - assert!(path.starts_with("/") && path.ends_with("/")); - return FixtureMeta::Root { path }; - } - let path = components[0].to_string(); assert!(path.starts_with("/")); -- cgit v1.2.3 From 30748161f0b4699ba9bc699a38ac9fc2fae49461 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 18:20:32 +0200 Subject: Simplify --- crates/ra_db/src/fixture.rs | 30 +++++------ crates/ra_ide/src/mock_analysis.rs | 16 +++--- crates/rust-analyzer/tests/heavy_tests/support.rs | 2 +- crates/test_utils/src/fixture.rs | 62 ++--------------------- crates/test_utils/src/lib.rs | 2 +- 5 files changed, 27 insertions(+), 85 deletions(-) (limited to 'crates') diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index bf897baff..7f006487a 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}; use ra_cfg::CfgOptions; use rustc_hash::FxHashMap; -use test_utils::{extract_offset, parse_fixture, parse_single_fixture, FixtureMeta, CURSOR_MARKER}; +use test_utils::{extract_offset, parse_fixture, parse_single_fixture, CURSOR_MARKER}; use vfs::{file_set::FileSet, VfsPath}; use crate::{ @@ -243,20 +243,18 @@ struct FileMeta { env: Env, } -impl From<&FixtureMeta> for ParsedMeta { - fn from(meta: &FixtureMeta) -> Self { - match meta { - FixtureMeta::File(f) => Self::File(FileMeta { - path: f.path.to_owned(), - krate: f.crate_name.to_owned(), - deps: f.deps.to_owned(), - cfg: f.cfg.to_owned(), - edition: f - .edition - .as_ref() - .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), - env: Env::from(f.env.iter()), - }), - } +impl From<&test_utils::FileMeta> for ParsedMeta { + fn from(f: &test_utils::FileMeta) -> Self { + Self::File(FileMeta { + path: f.path.to_owned(), + krate: f.crate_name.to_owned(), + deps: f.deps.to_owned(), + cfg: f.cfg.to_owned(), + edition: f + .edition + .as_ref() + .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), + env: Env::from(f.env.iter()), + }) } } diff --git a/crates/ra_ide/src/mock_analysis.rs b/crates/ra_ide/src/mock_analysis.rs index 58fafecab..c0840c6ea 100644 --- a/crates/ra_ide/src/mock_analysis.rs +++ b/crates/ra_ide/src/mock_analysis.rs @@ -25,7 +25,7 @@ impl MockFileData { fn path(&self) -> &str { match self { MockFileData::Plain { path, .. } => path.as_str(), - MockFileData::Fixture(f) => f.meta.path(), + MockFileData::Fixture(f) => f.meta.path.as_str(), } } @@ -38,25 +38,25 @@ impl MockFileData { fn cfg_options(&self) -> CfgOptions { match self { - MockFileData::Fixture(f) => { - f.meta.cfg_options().map_or_else(Default::default, |o| o.clone()) - } + MockFileData::Fixture(f) => f.meta.cfg.clone(), _ => CfgOptions::default(), } } fn edition(&self) -> Edition { match self { - MockFileData::Fixture(f) => { - f.meta.edition().map_or(Edition::Edition2018, |v| Edition::from_str(v).unwrap()) - } + MockFileData::Fixture(f) => f + .meta + .edition + .as_ref() + .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), _ => Edition::Edition2018, } } fn env(&self) -> Env { match self { - MockFileData::Fixture(f) => Env::from(f.meta.env()), + MockFileData::Fixture(f) => Env::from(f.meta.env.iter()), _ => Env::default(), } } diff --git a/crates/rust-analyzer/tests/heavy_tests/support.rs b/crates/rust-analyzer/tests/heavy_tests/support.rs index bb8585355..3bbfb43aa 100644 --- a/crates/rust-analyzer/tests/heavy_tests/support.rs +++ b/crates/rust-analyzer/tests/heavy_tests/support.rs @@ -69,7 +69,7 @@ impl<'a> Project<'a> { let mut paths = vec![]; for entry in parse_fixture(self.fixture) { - let path = tmp_dir.path().join(&entry.meta.path()['/'.len_utf8()..]); + let path = tmp_dir.path().join(&entry.meta.path['/'.len_utf8()..]); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path.as_path(), entry.text.as_bytes()).unwrap(); paths.push((path, entry.text)); diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs index 0dbeb01b1..a07d057e1 100644 --- a/crates/test_utils/src/fixture.rs +++ b/crates/test_utils/src/fixture.rs @@ -4,15 +4,10 @@ use stdx::split1; #[derive(Debug, Eq, PartialEq)] pub struct FixtureEntry { - pub meta: FixtureMeta, + pub meta: FileMeta, pub text: String, } -#[derive(Debug, Eq, PartialEq)] -pub enum FixtureMeta { - File(FileMeta), -} - #[derive(Debug, Eq, PartialEq)] pub struct FileMeta { pub path: String, @@ -23,57 +18,6 @@ pub struct FileMeta { pub env: FxHashMap, } -impl FixtureMeta { - pub fn path(&self) -> &str { - match self { - FixtureMeta::File(f) => &f.path, - } - } - - pub fn crate_name(&self) -> Option<&String> { - match self { - FixtureMeta::File(f) => f.crate_name.as_ref(), - } - } - - pub fn cfg_options(&self) -> Option<&CfgOptions> { - match self { - FixtureMeta::File(f) => Some(&f.cfg), - } - } - - pub fn edition(&self) -> Option<&String> { - match self { - FixtureMeta::File(f) => f.edition.as_ref(), - } - } - - pub fn env(&self) -> impl Iterator { - struct EnvIter<'a> { - iter: Option>, - } - - impl<'a> EnvIter<'a> { - fn new(meta: &'a FixtureMeta) -> Self { - Self { - iter: match meta { - FixtureMeta::File(f) => Some(f.env.iter()), - }, - } - } - } - - impl<'a> Iterator for EnvIter<'a> { - type Item = (&'a String, &'a String); - fn next(&mut self) -> Option { - self.iter.as_mut().and_then(|i| i.next()) - } - } - - EnvIter::new(self) - } -} - /// Same as `parse_fixture`, except it allow empty fixture pub fn parse_single_fixture(ra_fixture: &str) -> Option { if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) { @@ -137,7 +81,7 @@ The offending line: {:?}"#, } //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo -fn parse_meta(meta: &str) -> FixtureMeta { +fn parse_meta(meta: &str) -> FileMeta { let components = meta.split_ascii_whitespace().collect::>(); let path = components[0].to_string(); @@ -173,7 +117,7 @@ fn parse_meta(meta: &str) -> FixtureMeta { } } - FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env }) + FileMeta { path, crate_name: krate, deps, edition, cfg, env } } /// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index f22fcc8b2..f99786606 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs @@ -22,7 +22,7 @@ pub use difference::Changeset as __Changeset; pub use ra_cfg::CfgOptions; pub use rustc_hash::FxHashMap; -pub use crate::fixture::{parse_fixture, parse_single_fixture, FixtureEntry, FixtureMeta}; +pub use crate::fixture::{parse_fixture, parse_single_fixture, FileMeta, FixtureEntry}; pub const CURSOR_MARKER: &str = "<|>"; -- cgit v1.2.3 From 21f751a0e5da5dd488612e25abfc545c259050e7 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 18:34:50 +0200 Subject: Simplify --- crates/ra_db/src/fixture.rs | 12 ++++++----- crates/ra_ide/src/mock_analysis.rs | 14 ++++++------- crates/rust-analyzer/tests/heavy_tests/support.rs | 2 +- crates/test_utils/src/fixture.rs | 25 ++++++++--------------- crates/test_utils/src/lib.rs | 2 +- 5 files changed, 24 insertions(+), 31 deletions(-) (limited to 'crates') diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index 7f006487a..d65536bbc 100644 --- a/crates/ra_db/src/fixture.rs +++ b/crates/ra_db/src/fixture.rs @@ -61,7 +61,9 @@ use std::{str::FromStr, sync::Arc}; use ra_cfg::CfgOptions; use rustc_hash::FxHashMap; -use test_utils::{extract_offset, parse_fixture, parse_single_fixture, CURSOR_MARKER}; +use test_utils::{ + extract_offset, parse_fixture, parse_single_fixture, FixtureEntry, CURSOR_MARKER, +}; use vfs::{file_set::FileSet, VfsPath}; use crate::{ @@ -112,7 +114,7 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId let fixture = parse_single_fixture(ra_fixture); let crate_graph = if let Some(entry) = fixture { - let meta = match ParsedMeta::from(&entry.meta) { + let meta = match ParsedMeta::from(&entry) { ParsedMeta::File(it) => it, }; @@ -165,7 +167,7 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option it, }; assert!(meta.path.starts_with(&source_root_prefix)); @@ -243,8 +245,8 @@ struct FileMeta { env: Env, } -impl From<&test_utils::FileMeta> for ParsedMeta { - fn from(f: &test_utils::FileMeta) -> Self { +impl From<&FixtureEntry> for ParsedMeta { + fn from(f: &FixtureEntry) -> Self { Self::File(FileMeta { path: f.path.to_owned(), krate: f.crate_name.to_owned(), diff --git a/crates/ra_ide/src/mock_analysis.rs b/crates/ra_ide/src/mock_analysis.rs index c0840c6ea..d480fcf62 100644 --- a/crates/ra_ide/src/mock_analysis.rs +++ b/crates/ra_ide/src/mock_analysis.rs @@ -25,7 +25,7 @@ impl MockFileData { fn path(&self) -> &str { match self { MockFileData::Plain { path, .. } => path.as_str(), - MockFileData::Fixture(f) => f.meta.path.as_str(), + MockFileData::Fixture(f) => f.path.as_str(), } } @@ -38,25 +38,23 @@ impl MockFileData { fn cfg_options(&self) -> CfgOptions { match self { - MockFileData::Fixture(f) => f.meta.cfg.clone(), + MockFileData::Fixture(f) => f.cfg.clone(), _ => CfgOptions::default(), } } fn edition(&self) -> Edition { match self { - MockFileData::Fixture(f) => f - .meta - .edition - .as_ref() - .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), + MockFileData::Fixture(f) => { + f.edition.as_ref().map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()) + } _ => Edition::Edition2018, } } fn env(&self) -> Env { match self { - MockFileData::Fixture(f) => Env::from(f.meta.env.iter()), + MockFileData::Fixture(f) => Env::from(f.env.iter()), _ => Env::default(), } } diff --git a/crates/rust-analyzer/tests/heavy_tests/support.rs b/crates/rust-analyzer/tests/heavy_tests/support.rs index 3bbfb43aa..59565bf3d 100644 --- a/crates/rust-analyzer/tests/heavy_tests/support.rs +++ b/crates/rust-analyzer/tests/heavy_tests/support.rs @@ -69,7 +69,7 @@ impl<'a> Project<'a> { let mut paths = vec![]; for entry in parse_fixture(self.fixture) { - let path = tmp_dir.path().join(&entry.meta.path['/'.len_utf8()..]); + let path = tmp_dir.path().join(&entry.path['/'.len_utf8()..]); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path.as_path(), entry.text.as_bytes()).unwrap(); paths.push((path, entry.text)); diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs index a07d057e1..bda826d50 100644 --- a/crates/test_utils/src/fixture.rs +++ b/crates/test_utils/src/fixture.rs @@ -4,13 +4,8 @@ use stdx::split1; #[derive(Debug, Eq, PartialEq)] pub struct FixtureEntry { - pub meta: FileMeta, - pub text: String, -} - -#[derive(Debug, Eq, PartialEq)] -pub struct FileMeta { pub path: String, + pub text: String, pub crate_name: Option, pub deps: Vec, pub cfg: CfgOptions, @@ -71,7 +66,7 @@ The offending line: {:?}"#, if line.starts_with("//-") { let meta = line["//-".len()..].trim().to_string(); let meta = parse_meta(&meta); - res.push(FixtureEntry { meta, text: String::new() }) + res.push(meta) } else if let Some(entry) = res.last_mut() { entry.text.push_str(line); entry.text.push('\n'); @@ -81,7 +76,7 @@ The offending line: {:?}"#, } //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo -fn parse_meta(meta: &str) -> FileMeta { +fn parse_meta(meta: &str) -> FixtureEntry { let components = meta.split_ascii_whitespace().collect::>(); let path = components[0].to_string(); @@ -117,7 +112,7 @@ fn parse_meta(meta: &str) -> FileMeta { } } - FileMeta { path, crate_name: krate, deps, edition, cfg, env } + FixtureEntry { path, text: String::new(), crate_name: krate, deps, edition, cfg, env } } /// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. @@ -209,12 +204,10 @@ fn parse_fixture_gets_full_meta() { ); assert_eq!(1, parsed.len()); - let parsed = &parsed[0]; - assert_eq!("mod m;\n\n", parsed.text); + let meta = &parsed[0]; + assert_eq!("mod m;\n\n", meta.text); - let meta = &parsed.meta; - assert_eq!("foo", meta.crate_name().unwrap()); - assert_eq!("/lib.rs", meta.path()); - assert!(meta.cfg_options().is_some()); - assert_eq!(2, meta.env().count()); + assert_eq!("foo", meta.crate_name.as_ref().unwrap()); + assert_eq!("/lib.rs", meta.path); + assert_eq!(2, meta.env.len()); } diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index f99786606..0fdd1a36b 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs @@ -22,7 +22,7 @@ pub use difference::Changeset as __Changeset; pub use ra_cfg::CfgOptions; pub use rustc_hash::FxHashMap; -pub use crate::fixture::{parse_fixture, parse_single_fixture, FileMeta, FixtureEntry}; +pub use crate::fixture::{parse_fixture, parse_single_fixture, FixtureEntry}; pub const CURSOR_MARKER: &str = "<|>"; -- cgit v1.2.3 From 3486b47e5c4f71479cc3c876da1fd1dcbfcab257 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 18:43:55 +0200 Subject: Simplify --- crates/ra_db/src/fixture.rs | 70 ++++++++-------------------------------- crates/test_utils/src/fixture.rs | 13 -------- crates/test_utils/src/lib.rs | 2 +- 3 files changed, 14 insertions(+), 71 deletions(-) (limited to 'crates') diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index d65536bbc..f786fb87f 100644 --- a/crates/ra_db/src/fixture.rs +++ b/crates/ra_db/src/fixture.rs @@ -61,9 +61,7 @@ use std::{str::FromStr, sync::Arc}; use ra_cfg::CfgOptions; use rustc_hash::FxHashMap; -use test_utils::{ - extract_offset, parse_fixture, parse_single_fixture, FixtureEntry, CURSOR_MARKER, -}; +use test_utils::{extract_offset, parse_fixture, FixtureEntry, CURSOR_MARKER}; use vfs::{file_set::FileSet, VfsPath}; use crate::{ @@ -76,20 +74,21 @@ pub const WORKSPACE: SourceRootId = SourceRootId(0); pub trait WithFixture: Default + SourceDatabaseExt + 'static { fn with_single_file(text: &str) -> (Self, FileId) { let mut db = Self::default(); - let file_id = with_single_file(&mut db, text); - (db, file_id) + let (_, files) = with_files(&mut db, text); + assert!(files.len() == 1); + (db, files[0]) } fn with_files(ra_fixture: &str) -> Self { let mut db = Self::default(); - let pos = with_files(&mut db, ra_fixture); + let (pos, _) = with_files(&mut db, ra_fixture); assert!(pos.is_none()); db } fn with_position(ra_fixture: &str) -> (Self, FilePosition) { let mut db = Self::default(); - let pos = with_files(&mut db, ra_fixture); + let (pos, _) = with_files(&mut db, ra_fixture); (db, pos.unwrap()) } @@ -104,54 +103,11 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static { impl WithFixture for DB {} -fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId { - let file_id = FileId(0); - let mut file_set = vfs::file_set::FileSet::default(); - file_set.insert(file_id, vfs::VfsPath::new_virtual_path("/main.rs".to_string())); - - let source_root = SourceRoot::new_local(file_set); - - let fixture = parse_single_fixture(ra_fixture); - - let crate_graph = if let Some(entry) = fixture { - let meta = match ParsedMeta::from(&entry) { - ParsedMeta::File(it) => it, - }; - - let mut crate_graph = CrateGraph::default(); - crate_graph.add_crate_root( - file_id, - meta.edition, - meta.krate.map(|name| { - CrateName::new(&name).expect("Fixture crate name should not contain dashes") - }), - meta.cfg, - meta.env, - Default::default(), - ); - crate_graph - } else { - let mut crate_graph = CrateGraph::default(); - crate_graph.add_crate_root( - file_id, - Edition::Edition2018, - None, - CfgOptions::default(), - Env::default(), - Default::default(), - ); - crate_graph - }; - - db.set_file_text(file_id, Arc::new(ra_fixture.to_string())); - db.set_file_source_root(file_id, WORKSPACE); - db.set_source_root(WORKSPACE, Arc::new(source_root)); - db.set_crate_graph(Arc::new(crate_graph)); - - file_id -} - -fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option { +fn with_files( + db: &mut dyn SourceDatabaseExt, + fixture: &str, +) -> (Option, Vec) { + let mut files = Vec::new(); let fixture = parse_fixture(fixture); let mut crate_graph = CrateGraph::default(); @@ -204,7 +160,7 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option Option, } -/// Same as `parse_fixture`, except it allow empty fixture -pub fn parse_single_fixture(ra_fixture: &str) -> Option { - if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) { - return None; - } - - let fixtures = parse_fixture(ra_fixture); - if fixtures.len() > 1 { - panic!("too many fixtures"); - } - fixtures.into_iter().nth(0) -} - /// Parses text which looks like this: /// /// ```not_rust diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index 0fdd1a36b..d44b2f9ab 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs @@ -22,7 +22,7 @@ pub use difference::Changeset as __Changeset; pub use ra_cfg::CfgOptions; pub use rustc_hash::FxHashMap; -pub use crate::fixture::{parse_fixture, parse_single_fixture, FixtureEntry}; +pub use crate::fixture::{parse_fixture, FixtureEntry}; pub const CURSOR_MARKER: &str = "<|>"; -- cgit v1.2.3 From fdf86aee18e396d393d50df7df27b02111838507 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 18:46:56 +0200 Subject: Nicer API --- crates/ra_db/src/fixture.rs | 10 ++-- crates/ra_ide/src/mock_analysis.rs | 16 ++--- crates/test_utils/src/fixture.rs | 120 +++++++++++++++++++------------------ crates/test_utils/src/lib.rs | 2 +- 4 files changed, 75 insertions(+), 73 deletions(-) (limited to 'crates') diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index f786fb87f..6c13e62bb 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}; use ra_cfg::CfgOptions; use rustc_hash::FxHashMap; -use test_utils::{extract_offset, parse_fixture, FixtureEntry, CURSOR_MARKER}; +use test_utils::{extract_offset, Fixture, CURSOR_MARKER}; use vfs::{file_set::FileSet, VfsPath}; use crate::{ @@ -107,9 +107,9 @@ fn with_files( db: &mut dyn SourceDatabaseExt, fixture: &str, ) -> (Option, Vec) { - let mut files = Vec::new(); - let fixture = parse_fixture(fixture); + let fixture = Fixture::parse(fixture); + let mut files = Vec::new(); let mut crate_graph = CrateGraph::default(); let mut crates = FxHashMap::default(); let mut crate_deps = Vec::new(); @@ -201,8 +201,8 @@ struct FileMeta { env: Env, } -impl From<&FixtureEntry> for ParsedMeta { - fn from(f: &FixtureEntry) -> Self { +impl From<&Fixture> for ParsedMeta { + fn from(f: &Fixture) -> Self { Self::File(FileMeta { path: f.path.to_owned(), krate: f.crate_name.to_owned(), diff --git a/crates/ra_ide/src/mock_analysis.rs b/crates/ra_ide/src/mock_analysis.rs index d480fcf62..f15990158 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}; use ra_cfg::CfgOptions; use ra_db::{CrateName, Env, FileSet, SourceRoot, VfsPath}; -use test_utils::{extract_offset, extract_range, parse_fixture, FixtureEntry, CURSOR_MARKER}; +use test_utils::{extract_offset, extract_range, Fixture, CURSOR_MARKER}; use crate::{ Analysis, AnalysisChange, AnalysisHost, CrateGraph, Edition, FileId, FilePosition, FileRange, @@ -12,7 +12,7 @@ use crate::{ #[derive(Debug)] enum MockFileData { Plain { path: String, content: String }, - Fixture(FixtureEntry), + Fixture(Fixture), } impl MockFileData { @@ -60,8 +60,8 @@ impl MockFileData { } } -impl From for MockFileData { - fn from(fixture: FixtureEntry) -> Self { +impl From for MockFileData { + fn from(fixture: Fixture) -> Self { Self::Fixture(fixture) } } @@ -89,7 +89,7 @@ impl MockAnalysis { /// ``` pub fn with_files(fixture: &str) -> MockAnalysis { let mut res = MockAnalysis::new(); - for entry in parse_fixture(fixture) { + for entry in Fixture::parse(fixture) { res.add_file_fixture(entry); } res @@ -100,7 +100,7 @@ impl MockAnalysis { pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) { let mut position = None; let mut res = MockAnalysis::new(); - for entry in parse_fixture(fixture) { + for entry in Fixture::parse(fixture) { if entry.text.contains(CURSOR_MARKER) { assert!(position.is_none(), "only one marker (<|>) per fixture is allowed"); position = Some(res.add_file_fixture_with_position(entry)); @@ -112,13 +112,13 @@ impl MockAnalysis { (res, position) } - pub fn add_file_fixture(&mut self, fixture: FixtureEntry) -> FileId { + pub fn add_file_fixture(&mut self, fixture: Fixture) -> FileId { let file_id = self.next_id(); self.files.push(MockFileData::from(fixture)); file_id } - pub fn add_file_fixture_with_position(&mut self, mut fixture: FixtureEntry) -> FilePosition { + pub fn add_file_fixture_with_position(&mut self, mut fixture: Fixture) -> FilePosition { let (offset, text) = extract_offset(&fixture.text); fixture.text = text; let file_id = self.next_id(); diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs index 25d80806b..2a51bb559 100644 --- a/crates/test_utils/src/fixture.rs +++ b/crates/test_utils/src/fixture.rs @@ -3,7 +3,7 @@ use rustc_hash::FxHashMap; use stdx::split1; #[derive(Debug, Eq, PartialEq)] -pub struct FixtureEntry { +pub struct Fixture { pub path: String, pub text: String, pub crate_name: Option, @@ -13,19 +13,20 @@ pub struct FixtureEntry { pub env: FxHashMap, } -/// Parses text which looks like this: -/// -/// ```not_rust -/// //- some meta -/// line 1 -/// line 2 -/// // - other meta -/// ``` -pub fn parse_fixture(ra_fixture: &str) -> Vec { - let fixture = indent_first_line(ra_fixture); - let margin = fixture_margin(&fixture); - - let mut lines = fixture +impl Fixture { + /// Parses text which looks like this: + /// + /// ```not_rust + /// //- some meta + /// line 1 + /// line 2 + /// // - other meta + /// ``` + pub fn parse(ra_fixture: &str) -> Vec { + let fixture = indent_first_line(ra_fixture); + let margin = fixture_margin(&fixture); + + let mut lines = fixture .split('\n') // don't use `.lines` to not drop `\r\n` .enumerate() .filter_map(|(ix, line)| { @@ -48,58 +49,59 @@ The offending line: {:?}"#, } }); - let mut res: Vec = Vec::new(); - for line in lines.by_ref() { - if line.starts_with("//-") { - let meta = line["//-".len()..].trim().to_string(); - let meta = parse_meta(&meta); - res.push(meta) - } else if let Some(entry) = res.last_mut() { - entry.text.push_str(line); - entry.text.push('\n'); + let mut res: Vec = Vec::new(); + for line in lines.by_ref() { + if line.starts_with("//-") { + let meta = line["//-".len()..].trim().to_string(); + let meta = Fixture::parse_single(&meta); + res.push(meta) + } else if let Some(entry) = res.last_mut() { + entry.text.push_str(line); + entry.text.push('\n'); + } } + res } - res -} -//- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo -fn parse_meta(meta: &str) -> FixtureEntry { - let components = meta.split_ascii_whitespace().collect::>(); - - let path = components[0].to_string(); - assert!(path.starts_with("/")); - - let mut krate = None; - let mut deps = Vec::new(); - let mut edition = None; - let mut cfg = CfgOptions::default(); - let mut env = FxHashMap::default(); - for component in components[1..].iter() { - let (key, value) = split1(component, ':').unwrap(); - match key { - "crate" => krate = Some(value.to_string()), - "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), - "edition" => edition = Some(value.to_string()), - "cfg" => { - for key in value.split(',') { - match split1(key, '=') { - None => cfg.insert_atom(key.into()), - Some((k, v)) => cfg.insert_key_value(k.into(), v.into()), + //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo + fn parse_single(meta: &str) -> Fixture { + let components = meta.split_ascii_whitespace().collect::>(); + + let path = components[0].to_string(); + assert!(path.starts_with("/")); + + let mut krate = None; + let mut deps = Vec::new(); + let mut edition = None; + let mut cfg = CfgOptions::default(); + let mut env = FxHashMap::default(); + for component in components[1..].iter() { + let (key, value) = split1(component, ':').unwrap(); + match key { + "crate" => krate = Some(value.to_string()), + "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), + "edition" => edition = Some(value.to_string()), + "cfg" => { + for key in value.split(',') { + match split1(key, '=') { + None => cfg.insert_atom(key.into()), + Some((k, v)) => cfg.insert_key_value(k.into(), v.into()), + } } } - } - "env" => { - for key in value.split(',') { - if let Some((k, v)) = split1(key, '=') { - env.insert(k.into(), v.into()); + "env" => { + for key in value.split(',') { + if let Some((k, v)) = split1(key, '=') { + env.insert(k.into(), v.into()); + } } } + _ => panic!("bad component: {:?}", component), } - _ => panic!("bad component: {:?}", component), } - } - FixtureEntry { path, text: String::new(), crate_name: krate, deps, edition, cfg, env } + Fixture { path, text: String::new(), crate_name: krate, deps, edition, cfg, env } + } } /// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. @@ -170,8 +172,8 @@ fn parse_fixture_can_handle_dedented_first_line() { struct Bar; "; assert_eq!( - parse_fixture(fixture), - parse_fixture( + Fixture::parse(fixture), + Fixture::parse( "//- /lib.rs mod foo; //- /foo.rs @@ -183,7 +185,7 @@ struct Bar; #[test] fn parse_fixture_gets_full_meta() { - let parsed = parse_fixture( + let parsed = Fixture::parse( r" //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo mod m; diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index d44b2f9ab..316f3d501 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs @@ -22,7 +22,7 @@ pub use difference::Changeset as __Changeset; pub use ra_cfg::CfgOptions; pub use rustc_hash::FxHashMap; -pub use crate::fixture::{parse_fixture, FixtureEntry}; +pub use crate::fixture::Fixture; pub const CURSOR_MARKER: &str = "<|>"; -- cgit v1.2.3 From 84cd28fddc89bfa75760e81f4fbc5aa21ce2742c Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 18:56:26 +0200 Subject: Cut problematic dependency --- crates/ra_db/src/fixture.rs | 6 +++++- crates/ra_ide/src/mock_analysis.rs | 7 ++++++- crates/test_utils/Cargo.toml | 3 +-- crates/test_utils/src/fixture.rs | 28 +++++++++++++++++++--------- crates/test_utils/src/lib.rs | 1 - 5 files changed, 31 insertions(+), 14 deletions(-) (limited to 'crates') diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index 6c13e62bb..ea52ec563 100644 --- a/crates/ra_db/src/fixture.rs +++ b/crates/ra_db/src/fixture.rs @@ -203,11 +203,15 @@ struct FileMeta { impl From<&Fixture> for ParsedMeta { fn from(f: &Fixture) -> Self { + let mut cfg = CfgOptions::default(); + f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into())); + f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into())); + Self::File(FileMeta { path: f.path.to_owned(), krate: f.crate_name.to_owned(), deps: f.deps.to_owned(), - cfg: f.cfg.to_owned(), + cfg, edition: f .edition .as_ref() diff --git a/crates/ra_ide/src/mock_analysis.rs b/crates/ra_ide/src/mock_analysis.rs index f15990158..981bdf924 100644 --- a/crates/ra_ide/src/mock_analysis.rs +++ b/crates/ra_ide/src/mock_analysis.rs @@ -38,7 +38,12 @@ impl MockFileData { fn cfg_options(&self) -> CfgOptions { match self { - MockFileData::Fixture(f) => f.cfg.clone(), + MockFileData::Fixture(f) => { + let mut cfg = CfgOptions::default(); + f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into())); + f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into())); + cfg + } _ => CfgOptions::default(), } } 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"] doctest = false [dependencies] +# Avoid adding deps here, this crate is widely used in tests it should compile fast! difference = "2.0.0" text-size = "1.0.0" serde_json = "1.0.48" rustc-hash = "1.1.0" - -ra_cfg = { path = "../ra_cfg" } stdx = { path = "../stdx" } diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs index 2a51bb559..44cf835b3 100644 --- a/crates/test_utils/src/fixture.rs +++ b/crates/test_utils/src/fixture.rs @@ -1,4 +1,3 @@ -use ra_cfg::CfgOptions; use rustc_hash::FxHashMap; use stdx::split1; @@ -8,7 +7,8 @@ pub struct Fixture { pub text: String, pub crate_name: Option, pub deps: Vec, - pub cfg: CfgOptions, + pub cfg_atoms: Vec, + pub cfg_key_values: Vec<(String, String)>, pub edition: Option, pub env: FxHashMap, } @@ -73,7 +73,8 @@ The offending line: {:?}"#, let mut krate = None; let mut deps = Vec::new(); let mut edition = None; - let mut cfg = CfgOptions::default(); + let mut cfg_atoms = Vec::new(); + let mut cfg_key_values = Vec::new(); let mut env = FxHashMap::default(); for component in components[1..].iter() { let (key, value) = split1(component, ':').unwrap(); @@ -82,10 +83,10 @@ The offending line: {:?}"#, "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), "edition" => edition = Some(value.to_string()), "cfg" => { - for key in value.split(',') { - match split1(key, '=') { - None => cfg.insert_atom(key.into()), - Some((k, v)) => cfg.insert_key_value(k.into(), v.into()), + for entry in value.split(',') { + match split1(entry, '=') { + Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())), + None => cfg_atoms.push(entry.to_string()), } } } @@ -100,7 +101,16 @@ The offending line: {:?}"#, } } - Fixture { path, text: String::new(), crate_name: krate, deps, edition, cfg, env } + Fixture { + path, + text: String::new(), + crate_name: krate, + deps, + cfg_atoms, + cfg_key_values, + edition, + env, + } } } @@ -152,7 +162,7 @@ fn indent_len(s: &str) -> usize { #[test] #[should_panic] fn parse_fixture_checks_further_indented_metadata() { - parse_fixture( + Fixture::parse( r" //- /lib.rs mod bar; diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index 316f3d501..3fd8505ed 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs @@ -19,7 +19,6 @@ use serde_json::Value; use text_size::{TextRange, TextSize}; pub use difference::Changeset as __Changeset; -pub use ra_cfg::CfgOptions; pub use rustc_hash::FxHashMap; pub use crate::fixture::Fixture; -- cgit v1.2.3 From a34f9b7fb343114446be08c7867b699b2210710f Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 18:58:45 +0200 Subject: Docs for Fixture --- crates/rust-analyzer/tests/heavy_tests/support.rs | 4 ++-- crates/test_utils/src/fixture.rs | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'crates') diff --git a/crates/rust-analyzer/tests/heavy_tests/support.rs b/crates/rust-analyzer/tests/heavy_tests/support.rs index 59565bf3d..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}; use serde::Serialize; use serde_json::{to_string_pretty, Value}; use tempfile::TempDir; -use test_utils::{find_mismatch, parse_fixture}; +use test_utils::{find_mismatch, Fixture}; use ra_project_model::ProjectManifest; use rust_analyzer::{ @@ -68,7 +68,7 @@ impl<'a> Project<'a> { let mut paths = vec![]; - for entry in parse_fixture(self.fixture) { + for entry in Fixture::parse(self.fixture) { let path = tmp_dir.path().join(&entry.path['/'.len_utf8()..]); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path.as_path(), entry.text.as_bytes()).unwrap(); diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs index 44cf835b3..ba00607f2 100644 --- a/crates/test_utils/src/fixture.rs +++ b/crates/test_utils/src/fixture.rs @@ -1,3 +1,6 @@ +//! Defines `Fixture` -- a convenient way to describe the initial state of +//! rust-analyzer database from a single string. + use rustc_hash::FxHashMap; use stdx::split1; -- cgit v1.2.3 From 295c8d4f7f9ce9d3dc67e8a988914d90424c1b7e Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 23 Jun 2020 20:38:36 +0200 Subject: Complicate Fixing test fallout unfortunately requires more work, we need to do it, but let's merge something at least! --- crates/ra_db/src/fixture.rs | 51 +++++++++++++++++++++++++++++++++++++--- crates/test_utils/src/fixture.rs | 7 +++--- 2 files changed, 52 insertions(+), 6 deletions(-) (limited to 'crates') diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs index ea52ec563..20f291568 100644 --- a/crates/ra_db/src/fixture.rs +++ b/crates/ra_db/src/fixture.rs @@ -74,9 +74,8 @@ pub const WORKSPACE: SourceRootId = SourceRootId(0); pub trait WithFixture: Default + SourceDatabaseExt + 'static { fn with_single_file(text: &str) -> (Self, FileId) { let mut db = Self::default(); - let (_, files) = with_files(&mut db, text); - assert!(files.len() == 1); - (db, files[0]) + let file_id = with_single_file(&mut db, text); + (db, file_id) } fn with_files(ra_fixture: &str) -> Self { @@ -103,6 +102,52 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static { impl WithFixture for DB {} +fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId { + let file_id = FileId(0); + let mut file_set = vfs::file_set::FileSet::default(); + file_set.insert(file_id, vfs::VfsPath::new_virtual_path("/main.rs".to_string())); + + let source_root = SourceRoot::new_local(file_set); + + let crate_graph = if let Some(meta) = ra_fixture.lines().find(|it| it.contains("//-")) { + let entry = Fixture::parse_single(meta.trim()); + let meta = match ParsedMeta::from(&entry) { + ParsedMeta::File(it) => it, + }; + + let mut crate_graph = CrateGraph::default(); + crate_graph.add_crate_root( + file_id, + meta.edition, + meta.krate.map(|name| { + CrateName::new(&name).expect("Fixture crate name should not contain dashes") + }), + meta.cfg, + meta.env, + Default::default(), + ); + crate_graph + } else { + let mut crate_graph = CrateGraph::default(); + crate_graph.add_crate_root( + file_id, + Edition::Edition2018, + None, + CfgOptions::default(), + Env::default(), + Default::default(), + ); + crate_graph + }; + + db.set_file_text(file_id, Arc::new(ra_fixture.to_string())); + db.set_file_source_root(file_id, WORKSPACE); + db.set_source_root(WORKSPACE, Arc::new(source_root)); + db.set_crate_graph(Arc::new(crate_graph)); + + file_id +} + fn with_files( db: &mut dyn SourceDatabaseExt, fixture: &str, diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs index ba00607f2..9108e49d9 100644 --- a/crates/test_utils/src/fixture.rs +++ b/crates/test_utils/src/fixture.rs @@ -55,8 +55,7 @@ The offending line: {:?}"#, let mut res: Vec = Vec::new(); for line in lines.by_ref() { if line.starts_with("//-") { - let meta = line["//-".len()..].trim().to_string(); - let meta = Fixture::parse_single(&meta); + let meta = Fixture::parse_single(line); res.push(meta) } else if let Some(entry) = res.last_mut() { entry.text.push_str(line); @@ -67,7 +66,9 @@ The offending line: {:?}"#, } //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo - fn parse_single(meta: &str) -> Fixture { + pub fn parse_single(meta: &str) -> Fixture { + assert!(meta.starts_with("//-")); + let meta = meta["//-".len()..].trim(); let components = meta.split_ascii_whitespace().collect::>(); let path = components[0].to_string(); -- cgit v1.2.3