rust-analyzer/crates/ra_ide/src/mock_analysis.rs

210 lines
6.9 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
2020-06-11 09:04:09 +00:00
use std::{str::FromStr, sync::Arc};
2019-01-08 19:33:36 +00:00
use ra_cfg::CfgOptions;
2020-06-11 09:04:09 +00:00
use ra_db::{CrateName, Env, FileSet, SourceRoot, VfsPath};
2020-06-24 10:01:17 +00:00
use test_utils::{extract_range_or_offset, Fixture, RangeOrOffset, CURSOR_MARKER};
2019-01-08 19:33:36 +00:00
use crate::{
Analysis, AnalysisChange, AnalysisHost, CrateGraph, Edition, FileId, FilePosition, FileRange,
};
2019-01-08 19:33:36 +00:00
2020-05-16 10:17:21 +00:00
#[derive(Debug)]
enum MockFileData {
2020-06-23 16:46:56 +00:00
Fixture(Fixture),
2020-05-16 10:17:21 +00:00
}
impl MockFileData {
fn path(&self) -> &str {
match self {
2020-06-23 16:34:50 +00:00
MockFileData::Fixture(f) => f.path.as_str(),
2020-05-16 10:17:21 +00:00
}
}
fn content(&self) -> &str {
match self {
MockFileData::Fixture(f) => f.text.as_str(),
}
}
fn cfg_options(&self) -> CfgOptions {
match self {
2020-06-23 16:56:26 +00:00
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
}
2020-05-16 10:17:21 +00:00
}
}
fn edition(&self) -> Edition {
match self {
2020-06-23 16:34:50 +00:00
MockFileData::Fixture(f) => {
f.edition.as_ref().map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap())
}
}
}
fn env(&self) -> Env {
match self {
2020-06-23 16:34:50 +00:00
MockFileData::Fixture(f) => Env::from(f.env.iter()),
}
}
2020-05-16 10:17:21 +00:00
}
2020-06-23 16:46:56 +00:00
impl From<Fixture> for MockFileData {
fn from(fixture: Fixture) -> Self {
2020-05-16 10:17:21 +00:00
Self::Fixture(fixture)
}
}
2019-01-08 19:33:36 +00:00
/// Mock analysis is used in test to bootstrap an AnalysisHost/Analysis
/// from a set of in-memory files.
#[derive(Debug, Default)]
pub struct MockAnalysis {
2020-05-16 10:17:21 +00:00
files: Vec<MockFileData>,
2019-01-08 19:33:36 +00:00
}
impl MockAnalysis {
/// Creates `MockAnalysis` using a fixture data in the following format:
///
/// ```not_rust
2019-01-08 19:33:36 +00:00
/// //- /main.rs
/// mod foo;
/// fn main() {}
///
/// //- /foo.rs
/// struct Baz;
/// ```
2020-06-24 10:01:17 +00:00
pub fn with_files(ra_fixture: &str) -> MockAnalysis {
let (res, pos) = MockAnalysis::with_fixture(ra_fixture);
assert!(pos.is_none());
2019-01-08 19:33:36 +00:00
res
}
/// Same as `with_files`, but requires that a single file contains a `<|>` marker,
/// whose position is also returned.
pub fn with_files_and_position(fixture: &str) -> (MockAnalysis, FilePosition) {
2020-06-24 10:01:17 +00:00
let (res, position) = MockAnalysis::with_fixture(fixture);
let (file_id, range_or_offset) = position.expect("expected a marker (<|>)");
let offset = match range_or_offset {
RangeOrOffset::Range(_) => panic!(),
RangeOrOffset::Offset(it) => it,
};
(res, FilePosition { file_id, offset })
}
fn with_fixture(fixture: &str) -> (MockAnalysis, Option<(FileId, RangeOrOffset)>) {
2019-01-08 19:33:36 +00:00
let mut position = None;
2020-06-24 09:51:45 +00:00
let mut res = MockAnalysis::default();
2020-06-24 09:48:44 +00:00
for mut entry in Fixture::parse(fixture) {
2019-01-08 19:33:36 +00:00
if entry.text.contains(CURSOR_MARKER) {
2019-02-08 11:49:43 +00:00
assert!(position.is_none(), "only one marker (<|>) per fixture is allowed");
2020-06-24 10:01:17 +00:00
let (range_or_offset, text) = extract_range_or_offset(&entry.text);
2020-06-24 09:48:44 +00:00
entry.text = text;
let file_id = res.add_file_fixture(entry);
2020-06-24 10:01:17 +00:00
position = Some((file_id, range_or_offset));
2019-01-08 19:33:36 +00:00
} else {
2020-05-16 10:17:21 +00:00
res.add_file_fixture(entry);
2019-01-08 19:33:36 +00:00
}
}
(res, position)
}
2020-06-24 09:05:47 +00:00
fn add_file_fixture(&mut self, fixture: Fixture) -> FileId {
2020-05-16 10:17:21 +00:00
let file_id = self.next_id();
self.files.push(MockFileData::from(fixture));
file_id
}
2019-01-08 19:33:36 +00:00
pub fn id_of(&self, path: &str) -> FileId {
let (idx, _) = self
.files
.iter()
.enumerate()
2020-05-16 10:17:21 +00:00
.find(|(_, data)| path == data.path())
2019-01-08 19:33:36 +00:00
.expect("no file in this mock");
FileId(idx as u32 + 1)
}
pub fn analysis_host(self) -> AnalysisHost {
let mut host = AnalysisHost::default();
let mut change = AnalysisChange::new();
2020-06-11 09:04:09 +00:00
let mut file_set = FileSet::default();
2019-01-08 19:33:36 +00:00
let mut crate_graph = CrateGraph::default();
let mut root_crate = None;
2020-05-16 10:17:21 +00:00
for (i, data) in self.files.into_iter().enumerate() {
let path = data.path();
2019-01-08 19:33:36 +00:00
assert!(path.starts_with('/'));
2020-05-16 10:17:21 +00:00
let cfg_options = data.cfg_options();
2019-01-27 15:07:45 +00:00
let file_id = FileId(i as u32 + 1);
let edition = data.edition();
let env = data.env();
2019-01-08 19:33:36 +00:00
if path == "/lib.rs" || path == "/main.rs" {
root_crate = Some(crate_graph.add_crate_root(
file_id,
edition,
2020-03-08 13:26:57 +00:00
None,
cfg_options,
env,
2020-03-11 03:04:02 +00:00
Default::default(),
));
} else if path.ends_with("/lib.rs") {
let base = &path[..path.len() - "/lib.rs".len()];
let crate_name = &base[base.rfind('/').unwrap() + '/'.len_utf8()..];
2020-03-08 13:26:57 +00:00
let other_crate = crate_graph.add_crate_root(
file_id,
edition,
2020-03-16 09:47:52 +00:00
Some(CrateName::new(crate_name).unwrap()),
2020-03-08 13:26:57 +00:00
cfg_options,
env,
2020-03-11 03:04:02 +00:00
Default::default(),
2020-03-08 13:26:57 +00:00
);
if let Some(root_crate) = root_crate {
2020-02-05 10:47:28 +00:00
crate_graph
.add_dep(root_crate, CrateName::new(crate_name).unwrap(), other_crate)
.unwrap();
}
2019-01-08 19:33:36 +00:00
}
2020-06-11 09:04:09 +00:00
let path = VfsPath::new_virtual_path(path.to_string());
file_set.insert(file_id, path);
change.change_file(file_id, Some(Arc::new(data.content().to_owned())));
2019-01-08 19:33:36 +00:00
}
change.set_crate_graph(crate_graph);
2020-06-11 09:04:09 +00:00
change.set_roots(vec![SourceRoot::new_local(file_set)]);
2019-01-08 19:33:36 +00:00
host.apply_change(change);
host
}
pub fn analysis(self) -> Analysis {
self.analysis_host().analysis()
}
2020-05-16 10:17:21 +00:00
fn next_id(&self) -> FileId {
FileId((self.files.len() + 1) as u32)
}
2019-01-08 19:33:36 +00:00
}
/// Creates analysis from a multi-file fixture, returns positions marked with <|>.
2020-02-27 15:05:35 +00:00
pub fn analysis_and_position(ra_fixture: &str) -> (Analysis, FilePosition) {
let (mock, position) = MockAnalysis::with_files_and_position(ra_fixture);
2019-01-08 19:33:36 +00:00
(mock.analysis(), position)
}
/// Creates analysis for a single file.
2020-02-27 15:05:35 +00:00
pub fn single_file(ra_fixture: &str) -> (Analysis, FileId) {
2020-06-24 09:05:47 +00:00
let mock = MockAnalysis::with_files(ra_fixture);
let file_id = mock.id_of("/main.rs");
2019-01-08 19:33:36 +00:00
(mock.analysis(), file_id)
}
/// Creates analysis for a single file, returns range marked with a pair of <|>.
2020-06-24 10:01:17 +00:00
pub fn analysis_and_range(ra_fixture: &str) -> (Analysis, FileRange) {
let (res, position) = MockAnalysis::with_fixture(ra_fixture);
let (file_id, range_or_offset) = position.expect("expected a marker (<|>)");
let range = match range_or_offset {
RangeOrOffset::Range(it) => it,
RangeOrOffset::Offset(_) => panic!(),
};
(res.analysis(), FileRange { file_id, range })
2019-01-08 19:33:36 +00:00
}