rust/crates/ra_ide_api/src/parent_module.rs

91 lines
2.7 KiB
Rust
Raw Normal View History

2019-02-08 04:50:18 -06:00
use ra_db::{FilePosition, FileId, CrateId};
2019-01-11 09:17:20 -06:00
use crate::{NavigationTarget, db::RootDatabase};
/// This returns `Vec` because a module may be included from several places. We
/// don't handle this case yet though, so the Vec has length at most one.
2019-01-15 12:02:42 -06:00
pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec<NavigationTarget> {
2019-01-15 09:13:11 -06:00
let module = match hir::source_binder::module_from_position(db, position) {
2019-01-15 12:02:42 -06:00
None => return Vec::new(),
2019-01-11 09:17:20 -06:00
Some(it) => it,
};
let nav = NavigationTarget::from_module_to_decl(db, module);
2019-01-15 12:02:42 -06:00
vec![nav]
2019-01-11 09:17:20 -06:00
}
2019-02-08 04:50:18 -06:00
/// Returns `Vec` for the same reason as `parent_module`
pub(crate) fn crate_for(db: &RootDatabase, file_id: FileId) -> Vec<CrateId> {
let module = match hir::source_binder::module_from_file_id(db, file_id) {
Some(it) => it,
None => return Vec::new(),
};
let krate = match module.krate(db) {
Some(it) => it,
None => return Vec::new(),
};
vec![krate.crate_id()]
}
2019-01-11 09:17:20 -06:00
#[cfg(test)]
mod tests {
2019-03-25 15:03:32 -05:00
use crate::{
AnalysisChange, CrateGraph,
mock_analysis::{analysis_and_position, MockAnalysis},
Edition::Edition2018,
};
2019-01-11 09:17:20 -06:00
#[test]
fn test_resolve_parent_module() {
let (analysis, pos) = analysis_and_position(
"
//- /lib.rs
mod foo;
//- /foo.rs
<|>// empty
",
);
let nav = analysis.parent_module(pos).unwrap().pop().unwrap();
2019-01-13 12:56:20 -06:00
nav.assert_match("foo MODULE FileId(1) [0; 8)");
2019-01-11 09:17:20 -06:00
}
#[test]
fn test_resolve_parent_module_for_inline() {
let (analysis, pos) = analysis_and_position(
"
//- /lib.rs
mod foo {
mod bar {
mod baz { <|> }
}
}
",
);
let nav = analysis.parent_module(pos).unwrap().pop().unwrap();
nav.assert_match("baz MODULE FileId(1) [32; 44)");
}
2019-03-25 15:03:32 -05:00
#[test]
fn test_resolve_crate_root() {
let mock = MockAnalysis::with_files(
"
//- /bar.rs
mod foo;
//- /foo.rs
// empty <|>
",
);
let root_file = mock.id_of("/bar.rs");
let mod_file = mock.id_of("/foo.rs");
let mut host = mock.analysis_host();
assert!(host.analysis().crate_for(mod_file).unwrap().is_empty());
let mut crate_graph = CrateGraph::default();
let crate_id = crate_graph.add_crate_root(root_file, Edition2018);
let mut change = AnalysisChange::new();
change.set_crate_graph(crate_graph);
host.apply_change(change);
assert_eq!(host.analysis().crate_for(mod_file).unwrap(), vec![crate_id]);
}
2019-01-11 09:17:20 -06:00
}