mirror of
https://github.com/rust-lang/rust.git
synced 2025-01-10 06:47:34 +00:00
Merge #5011
5011: Simplify fixtures r=matklad a=matklad
bors r+
🤖
Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
commit
9caf810129
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -1664,7 +1664,6 @@ name = "test_utils"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"difference",
|
"difference",
|
||||||
"ra_cfg",
|
|
||||||
"rustc-hash",
|
"rustc-hash",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"stdx",
|
"stdx",
|
||||||
|
@ -61,7 +61,7 @@ use std::{str::FromStr, sync::Arc};
|
|||||||
|
|
||||||
use ra_cfg::CfgOptions;
|
use ra_cfg::CfgOptions;
|
||||||
use rustc_hash::FxHashMap;
|
use rustc_hash::FxHashMap;
|
||||||
use test_utils::{extract_offset, parse_fixture, parse_single_fixture, FixtureMeta, CURSOR_MARKER};
|
use test_utils::{extract_offset, Fixture, CURSOR_MARKER};
|
||||||
use vfs::{file_set::FileSet, VfsPath};
|
use vfs::{file_set::FileSet, VfsPath};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@ -80,14 +80,14 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static {
|
|||||||
|
|
||||||
fn with_files(ra_fixture: &str) -> Self {
|
fn with_files(ra_fixture: &str) -> Self {
|
||||||
let mut db = Self::default();
|
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());
|
assert!(pos.is_none());
|
||||||
db
|
db
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
|
fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
|
||||||
let mut db = Self::default();
|
let mut db = Self::default();
|
||||||
let pos = with_files(&mut db, ra_fixture);
|
let (pos, _) = with_files(&mut db, ra_fixture);
|
||||||
(db, pos.unwrap())
|
(db, pos.unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,12 +109,10 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId
|
|||||||
|
|
||||||
let source_root = SourceRoot::new_local(file_set);
|
let source_root = SourceRoot::new_local(file_set);
|
||||||
|
|
||||||
let fixture = parse_single_fixture(ra_fixture);
|
let crate_graph = if let Some(meta) = ra_fixture.lines().find(|it| it.contains("//-")) {
|
||||||
|
let entry = Fixture::parse_single(meta.trim());
|
||||||
let crate_graph = if let Some(entry) = fixture {
|
let meta = match ParsedMeta::from(&entry) {
|
||||||
let meta = match ParsedMeta::from(&entry.meta) {
|
|
||||||
ParsedMeta::File(it) => it,
|
ParsedMeta::File(it) => it,
|
||||||
_ => panic!("with_single_file only support file meta"),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut crate_graph = CrateGraph::default();
|
let mut crate_graph = CrateGraph::default();
|
||||||
@ -150,30 +148,27 @@ fn with_single_file(db: &mut dyn SourceDatabaseExt, ra_fixture: &str) -> FileId
|
|||||||
file_id
|
file_id
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option<FilePosition> {
|
fn with_files(
|
||||||
let fixture = parse_fixture(fixture);
|
db: &mut dyn SourceDatabaseExt,
|
||||||
|
fixture: &str,
|
||||||
|
) -> (Option<FilePosition>, Vec<FileId>) {
|
||||||
|
let fixture = Fixture::parse(fixture);
|
||||||
|
|
||||||
|
let mut files = Vec::new();
|
||||||
let mut crate_graph = CrateGraph::default();
|
let mut crate_graph = CrateGraph::default();
|
||||||
let mut crates = FxHashMap::default();
|
let mut crates = FxHashMap::default();
|
||||||
let mut crate_deps = Vec::new();
|
let mut crate_deps = Vec::new();
|
||||||
let mut default_crate_root: Option<FileId> = None;
|
let mut default_crate_root: Option<FileId> = None;
|
||||||
|
|
||||||
let mut file_set = FileSet::default();
|
let mut file_set = FileSet::default();
|
||||||
let mut source_root_id = WORKSPACE;
|
let source_root_id = WORKSPACE;
|
||||||
let mut source_root_prefix = "/".to_string();
|
let source_root_prefix = "/".to_string();
|
||||||
let mut file_id = FileId(0);
|
let mut file_id = FileId(0);
|
||||||
|
|
||||||
let mut file_position = None;
|
let mut file_position = None;
|
||||||
|
|
||||||
for entry in fixture.iter() {
|
for entry in fixture.iter() {
|
||||||
let meta = match ParsedMeta::from(&entry.meta) {
|
let meta = match ParsedMeta::from(entry) {
|
||||||
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,
|
ParsedMeta::File(it) => it,
|
||||||
};
|
};
|
||||||
assert!(meta.path.starts_with(&source_root_prefix));
|
assert!(meta.path.starts_with(&source_root_prefix));
|
||||||
@ -210,7 +205,7 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option<FilePosit
|
|||||||
db.set_file_source_root(file_id, source_root_id);
|
db.set_file_source_root(file_id, source_root_id);
|
||||||
let path = VfsPath::new_virtual_path(meta.path);
|
let path = VfsPath::new_virtual_path(meta.path);
|
||||||
file_set.insert(file_id, path.into());
|
file_set.insert(file_id, path.into());
|
||||||
|
files.push(file_id);
|
||||||
file_id.0 += 1;
|
file_id.0 += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -235,11 +230,10 @@ fn with_files(db: &mut dyn SourceDatabaseExt, fixture: &str) -> Option<FilePosit
|
|||||||
db.set_source_root(source_root_id, Arc::new(SourceRoot::new_local(file_set)));
|
db.set_source_root(source_root_id, Arc::new(SourceRoot::new_local(file_set)));
|
||||||
db.set_crate_graph(Arc::new(crate_graph));
|
db.set_crate_graph(Arc::new(crate_graph));
|
||||||
|
|
||||||
file_position
|
(file_position, files)
|
||||||
}
|
}
|
||||||
|
|
||||||
enum ParsedMeta {
|
enum ParsedMeta {
|
||||||
Root { path: String },
|
|
||||||
File(FileMeta),
|
File(FileMeta),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -252,25 +246,22 @@ struct FileMeta {
|
|||||||
env: Env,
|
env: Env,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&FixtureMeta> for ParsedMeta {
|
impl From<&Fixture> for ParsedMeta {
|
||||||
fn from(meta: &FixtureMeta) -> Self {
|
fn from(f: &Fixture) -> Self {
|
||||||
match meta {
|
let mut cfg = CfgOptions::default();
|
||||||
FixtureMeta::Root { path } => {
|
f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
|
||||||
// `Self::Root` causes a false warning: 'variant is never constructed: `Root` '
|
f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
|
||||||
// see https://github.com/rust-lang/rust/issues/69018
|
|
||||||
ParsedMeta::Root { path: path.to_owned() }
|
Self::File(FileMeta {
|
||||||
}
|
path: f.path.to_owned(),
|
||||||
FixtureMeta::File(f) => Self::File(FileMeta {
|
krate: f.crate_name.to_owned(),
|
||||||
path: f.path.to_owned(),
|
deps: f.deps.to_owned(),
|
||||||
krate: f.crate_name.to_owned(),
|
cfg,
|
||||||
deps: f.deps.to_owned(),
|
edition: f
|
||||||
cfg: f.cfg.to_owned(),
|
.edition
|
||||||
edition: f
|
.as_ref()
|
||||||
.edition
|
.map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
|
||||||
.as_ref()
|
env: Env::from(f.env.iter()),
|
||||||
.map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
|
})
|
||||||
env: Env::from(f.env.iter()),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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]
|
#[test]
|
||||||
fn reexport_across_crates() {
|
fn reexport_across_crates() {
|
||||||
let map = def_map(
|
let map = def_map(
|
||||||
|
@ -3,7 +3,7 @@ use std::{str::FromStr, sync::Arc};
|
|||||||
|
|
||||||
use ra_cfg::CfgOptions;
|
use ra_cfg::CfgOptions;
|
||||||
use ra_db::{CrateName, Env, FileSet, SourceRoot, VfsPath};
|
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::{
|
use crate::{
|
||||||
Analysis, AnalysisChange, AnalysisHost, CrateGraph, Edition, FileId, FilePosition, FileRange,
|
Analysis, AnalysisChange, AnalysisHost, CrateGraph, Edition, FileId, FilePosition, FileRange,
|
||||||
@ -12,7 +12,7 @@ use crate::{
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum MockFileData {
|
enum MockFileData {
|
||||||
Plain { path: String, content: String },
|
Plain { path: String, content: String },
|
||||||
Fixture(FixtureEntry),
|
Fixture(Fixture),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MockFileData {
|
impl MockFileData {
|
||||||
@ -25,7 +25,7 @@ impl MockFileData {
|
|||||||
fn path(&self) -> &str {
|
fn path(&self) -> &str {
|
||||||
match self {
|
match self {
|
||||||
MockFileData::Plain { path, .. } => path.as_str(),
|
MockFileData::Plain { path, .. } => path.as_str(),
|
||||||
MockFileData::Fixture(f) => f.meta.path(),
|
MockFileData::Fixture(f) => f.path.as_str(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,7 +39,10 @@ impl MockFileData {
|
|||||||
fn cfg_options(&self) -> CfgOptions {
|
fn cfg_options(&self) -> CfgOptions {
|
||||||
match self {
|
match self {
|
||||||
MockFileData::Fixture(f) => {
|
MockFileData::Fixture(f) => {
|
||||||
f.meta.cfg_options().map_or_else(Default::default, |o| o.clone())
|
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(),
|
_ => CfgOptions::default(),
|
||||||
}
|
}
|
||||||
@ -48,7 +51,7 @@ impl MockFileData {
|
|||||||
fn edition(&self) -> Edition {
|
fn edition(&self) -> Edition {
|
||||||
match self {
|
match self {
|
||||||
MockFileData::Fixture(f) => {
|
MockFileData::Fixture(f) => {
|
||||||
f.meta.edition().map_or(Edition::Edition2018, |v| Edition::from_str(v).unwrap())
|
f.edition.as_ref().map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap())
|
||||||
}
|
}
|
||||||
_ => Edition::Edition2018,
|
_ => Edition::Edition2018,
|
||||||
}
|
}
|
||||||
@ -56,14 +59,14 @@ impl MockFileData {
|
|||||||
|
|
||||||
fn env(&self) -> Env {
|
fn env(&self) -> Env {
|
||||||
match self {
|
match self {
|
||||||
MockFileData::Fixture(f) => Env::from(f.meta.env()),
|
MockFileData::Fixture(f) => Env::from(f.env.iter()),
|
||||||
_ => Env::default(),
|
_ => Env::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<FixtureEntry> for MockFileData {
|
impl From<Fixture> for MockFileData {
|
||||||
fn from(fixture: FixtureEntry) -> Self {
|
fn from(fixture: Fixture) -> Self {
|
||||||
Self::Fixture(fixture)
|
Self::Fixture(fixture)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -91,7 +94,7 @@ impl MockAnalysis {
|
|||||||
/// ```
|
/// ```
|
||||||
pub fn with_files(fixture: &str) -> MockAnalysis {
|
pub fn with_files(fixture: &str) -> MockAnalysis {
|
||||||
let mut res = MockAnalysis::new();
|
let mut res = MockAnalysis::new();
|
||||||
for entry in parse_fixture(fixture) {
|
for entry in Fixture::parse(fixture) {
|
||||||
res.add_file_fixture(entry);
|
res.add_file_fixture(entry);
|
||||||
}
|
}
|
||||||
res
|
res
|
||||||
@ -102,7 +105,7 @@ impl MockAnalysis {
|
|||||||
pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) {
|
pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) {
|
||||||
let mut position = None;
|
let mut position = None;
|
||||||
let mut res = MockAnalysis::new();
|
let mut res = MockAnalysis::new();
|
||||||
for entry in parse_fixture(fixture) {
|
for entry in Fixture::parse(fixture) {
|
||||||
if entry.text.contains(CURSOR_MARKER) {
|
if entry.text.contains(CURSOR_MARKER) {
|
||||||
assert!(position.is_none(), "only one marker (<|>) per fixture is allowed");
|
assert!(position.is_none(), "only one marker (<|>) per fixture is allowed");
|
||||||
position = Some(res.add_file_fixture_with_position(entry));
|
position = Some(res.add_file_fixture_with_position(entry));
|
||||||
@ -114,13 +117,13 @@ impl MockAnalysis {
|
|||||||
(res, position)
|
(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();
|
let file_id = self.next_id();
|
||||||
self.files.push(MockFileData::from(fixture));
|
self.files.push(MockFileData::from(fixture));
|
||||||
file_id
|
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);
|
let (offset, text) = extract_offset(&fixture.text);
|
||||||
fixture.text = text;
|
fixture.text = text;
|
||||||
let file_id = self.next_id();
|
let file_id = self.next_id();
|
||||||
|
@ -17,7 +17,7 @@ use lsp_types::{ProgressParams, ProgressParamsValue};
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json::{to_string_pretty, Value};
|
use serde_json::{to_string_pretty, Value};
|
||||||
use tempfile::TempDir;
|
use tempfile::TempDir;
|
||||||
use test_utils::{find_mismatch, parse_fixture};
|
use test_utils::{find_mismatch, Fixture};
|
||||||
|
|
||||||
use ra_project_model::ProjectManifest;
|
use ra_project_model::ProjectManifest;
|
||||||
use rust_analyzer::{
|
use rust_analyzer::{
|
||||||
@ -68,8 +68,8 @@ impl<'a> Project<'a> {
|
|||||||
|
|
||||||
let mut paths = vec![];
|
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.meta.path()['/'.len_utf8()..]);
|
let path = tmp_dir.path().join(&entry.path['/'.len_utf8()..]);
|
||||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
fs::write(path.as_path(), entry.text.as_bytes()).unwrap();
|
fs::write(path.as_path(), entry.text.as_bytes()).unwrap();
|
||||||
paths.push((path, entry.text));
|
paths.push((path, entry.text));
|
||||||
|
@ -8,10 +8,9 @@ authors = ["rust-analyzer developers"]
|
|||||||
doctest = false
|
doctest = false
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
# Avoid adding deps here, this crate is widely used in tests it should compile fast!
|
||||||
difference = "2.0.0"
|
difference = "2.0.0"
|
||||||
text-size = "1.0.0"
|
text-size = "1.0.0"
|
||||||
serde_json = "1.0.48"
|
serde_json = "1.0.48"
|
||||||
rustc-hash = "1.1.0"
|
rustc-hash = "1.1.0"
|
||||||
|
|
||||||
ra_cfg = { path = "../ra_cfg" }
|
|
||||||
stdx = { path = "../stdx" }
|
stdx = { path = "../stdx" }
|
||||||
|
216
crates/test_utils/src/fixture.rs
Normal file
216
crates/test_utils/src/fixture.rs
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
//! 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;
|
||||||
|
|
||||||
|
#[derive(Debug, Eq, PartialEq)]
|
||||||
|
pub struct Fixture {
|
||||||
|
pub path: String,
|
||||||
|
pub text: String,
|
||||||
|
pub crate_name: Option<String>,
|
||||||
|
pub deps: Vec<String>,
|
||||||
|
pub cfg_atoms: Vec<String>,
|
||||||
|
pub cfg_key_values: Vec<(String, String)>,
|
||||||
|
pub edition: Option<String>,
|
||||||
|
pub env: FxHashMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Fixture> {
|
||||||
|
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<Fixture> = Vec::new();
|
||||||
|
for line in lines.by_ref() {
|
||||||
|
if line.starts_with("//-") {
|
||||||
|
let meta = Fixture::parse_single(line);
|
||||||
|
res.push(meta)
|
||||||
|
} 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
|
||||||
|
pub fn parse_single(meta: &str) -> Fixture {
|
||||||
|
assert!(meta.starts_with("//-"));
|
||||||
|
let meta = meta["//-".len()..].trim();
|
||||||
|
let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
|
||||||
|
|
||||||
|
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_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();
|
||||||
|
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 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()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"env" => {
|
||||||
|
for key in value.split(',') {
|
||||||
|
if let Some((k, v)) = split1(key, '=') {
|
||||||
|
env.insert(k.into(), v.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => panic!("bad component: {:?}", component),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Fixture {
|
||||||
|
path,
|
||||||
|
text: String::new(),
|
||||||
|
crate_name: krate,
|
||||||
|
deps,
|
||||||
|
cfg_atoms,
|
||||||
|
cfg_key_values,
|
||||||
|
edition,
|
||||||
|
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::<Vec<_>>().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() {
|
||||||
|
Fixture::parse(
|
||||||
|
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!(
|
||||||
|
Fixture::parse(fixture),
|
||||||
|
Fixture::parse(
|
||||||
|
"//- /lib.rs
|
||||||
|
mod foo;
|
||||||
|
//- /foo.rs
|
||||||
|
struct Bar;
|
||||||
|
"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_fixture_gets_full_meta() {
|
||||||
|
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;
|
||||||
|
",
|
||||||
|
);
|
||||||
|
assert_eq!(1, parsed.len());
|
||||||
|
|
||||||
|
let meta = &parsed[0];
|
||||||
|
assert_eq!("mod m;\n\n", meta.text);
|
||||||
|
|
||||||
|
assert_eq!("foo", meta.crate_name.as_ref().unwrap());
|
||||||
|
assert_eq!("/lib.rs", meta.path);
|
||||||
|
assert_eq!(2, meta.env.len());
|
||||||
|
}
|
@ -8,6 +8,7 @@
|
|||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
pub mod mark;
|
pub mod mark;
|
||||||
|
mod fixture;
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
env, fs,
|
env, fs,
|
||||||
@ -15,13 +16,12 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use stdx::split1;
|
|
||||||
use text_size::{TextRange, TextSize};
|
use text_size::{TextRange, TextSize};
|
||||||
|
|
||||||
pub use ra_cfg::CfgOptions;
|
pub use difference::Changeset as __Changeset;
|
||||||
pub use rustc_hash::FxHashMap;
|
pub use rustc_hash::FxHashMap;
|
||||||
|
|
||||||
pub use difference::Changeset as __Changeset;
|
pub use crate::fixture::Fixture;
|
||||||
|
|
||||||
pub const CURSOR_MARKER: &str = "<|>";
|
pub const CURSOR_MARKER: &str = "<|>";
|
||||||
|
|
||||||
@ -97,7 +97,7 @@ impl From<RangeOrOffset> for TextRange {
|
|||||||
fn from(selection: RangeOrOffset) -> Self {
|
fn from(selection: RangeOrOffset) -> Self {
|
||||||
match selection {
|
match selection {
|
||||||
RangeOrOffset::Range(it) => it,
|
RangeOrOffset::Range(it) => it,
|
||||||
RangeOrOffset::Offset(it) => TextRange::new(it, it),
|
RangeOrOffset::Offset(it) => TextRange::empty(it),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -159,291 +159,6 @@ pub fn add_cursor(text: &str, offset: TextSize) -> String {
|
|||||||
res
|
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<String>,
|
|
||||||
pub deps: Vec<String>,
|
|
||||||
pub cfg: CfgOptions,
|
|
||||||
pub edition: Option<String>,
|
|
||||||
pub env: FxHashMap<String, String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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<Item = (&String, &String)> {
|
|
||||||
struct EnvIter<'a> {
|
|
||||||
iter: Option<std::collections::hash_map::Iter<'a, String, String>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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::Item> {
|
|
||||||
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<FixtureEntry> {
|
|
||||||
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<FixtureEntry> = 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::<Vec<_>>();
|
|
||||||
|
|
||||||
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::<Vec<_>>().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<FixtureEntry> {
|
|
||||||
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:
|
// Comparison functionality borrowed from cargo:
|
||||||
|
|
||||||
/// Compare a line with an expected pattern.
|
/// Compare a line with an expected pattern.
|
||||||
|
Loading…
Reference in New Issue
Block a user