From 7125192c1e46f2350707c4903a1679b2a0178ea6 Mon Sep 17 00:00:00 2001 From: kjeremy Date: Tue, 23 Apr 2019 14:11:27 -0400 Subject: Basic resolution for ADT --- crates/ra_ide_api/src/goto_type_definition.rs | 68 +++++++++++++++++++++++++++ crates/ra_ide_api/src/lib.rs | 8 ++++ 2 files changed, 76 insertions(+) create mode 100644 crates/ra_ide_api/src/goto_type_definition.rs (limited to 'crates/ra_ide_api') diff --git a/crates/ra_ide_api/src/goto_type_definition.rs b/crates/ra_ide_api/src/goto_type_definition.rs new file mode 100644 index 000000000..b6a3c1c3a --- /dev/null +++ b/crates/ra_ide_api/src/goto_type_definition.rs @@ -0,0 +1,68 @@ +use ra_db::SourceDatabase; +use ra_syntax::{ + AstNode, ast, + algo::find_token_at_offset +}; + +use crate::{FilePosition, NavigationTarget, db::RootDatabase, RangeInfo}; + +pub(crate) fn goto_type_definition( + db: &RootDatabase, + position: FilePosition, +) -> Option>> { + let file = db.parse(position.file_id); + + let node = find_token_at_offset(file.syntax(), position.offset).find_map(|token| { + token + .parent() + .ancestors() + .find(|n| ast::Expr::cast(*n).is_some() || ast::Pat::cast(*n).is_some()) + })?; + + let analyzer = hir::SourceAnalyzer::new(db, position.file_id, node, None); + + let ty: hir::Ty = if let Some(ty) = ast::Expr::cast(node).and_then(|e| analyzer.type_of(db, e)) + { + ty + } else if let Some(ty) = ast::Pat::cast(node).and_then(|p| analyzer.type_of_pat(db, p)) { + ty + } else { + return None; + }; + + if let Some((adt_def, _)) = ty.as_adt() { + let nav = NavigationTarget::from_adt_def(db, adt_def); + return Some(RangeInfo::new(node.range(), vec![nav])); + }; + + None +} + +#[cfg(test)] +mod tests { + use crate::mock_analysis::analysis_and_position; + + fn check_goto(fixture: &str, expected: &str) { + let (analysis, pos) = analysis_and_position(fixture); + + let mut navs = analysis.goto_type_definition(pos).unwrap().unwrap().info; + assert_eq!(navs.len(), 1); + let nav = navs.pop().unwrap(); + nav.assert_match(expected); + } + + #[test] + fn goto_type_definition_works_simple() { + check_goto( + " + //- /lib.rs + struct Foo; + fn foo() { + let f: Foo; + f<|> + } + ", + "Foo STRUCT_DEF FileId(1) [0; 11) [7; 10)", + ); + } +} diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs index d25795adc..d4be8bd6c 100644 --- a/crates/ra_ide_api/src/lib.rs +++ b/crates/ra_ide_api/src/lib.rs @@ -19,6 +19,7 @@ mod status; mod completion; mod runnables; mod goto_definition; +mod goto_type_definition; mod extend_selection; mod hover; mod call_info; @@ -416,6 +417,13 @@ impl Analysis { self.with_db(|db| impls::goto_implementation(db, position)) } + pub fn goto_type_definition( + &self, + position: FilePosition, + ) -> Cancelable>>> { + self.with_db(|db| goto_type_definition::goto_type_definition(db, position)) + } + /// Finds all usages of the reference at point. pub fn find_all_refs( &self, -- cgit v1.2.3