rust/crates/ra_ide_api/src/references.rs

525 lines
15 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
2019-09-21 11:35:39 -05:00
use hir::ModuleSource;
use ra_db::{SourceDatabase, SourceDatabaseExt};
2019-09-21 11:35:39 -05:00
use ra_syntax::{algo::find_node_at_offset, ast, AstNode, SyntaxNode};
2019-02-08 05:06:26 -06:00
use relative_path::{RelativePath, RelativePathBuf};
2019-01-16 07:39:01 -06:00
use crate::{
2019-09-14 06:38:10 -05:00
db::RootDatabase,
2019-10-10 10:51:51 -05:00
name_kind::{classify_name, classify_name_ref, Definition, NameKind::*},
search_scope::find_refs,
2019-09-14 06:38:10 -05:00
FileId, FilePosition, FileRange, FileSystemEdit, NavigationTarget, RangeInfo, SourceChange,
SourceFileEdit, TextRange,
2019-01-16 07:39:01 -06:00
};
2019-02-08 05:06:26 -06:00
#[derive(Debug, Clone)]
pub struct ReferenceSearchResult {
declaration: NavigationTarget,
references: Vec<FileRange>,
}
impl ReferenceSearchResult {
pub fn declaration(&self) -> &NavigationTarget {
&self.declaration
}
pub fn references(&self) -> &[FileRange] {
&self.references
}
/// Total number of references
/// At least 1 since all valid references should
/// Have a declaration
pub fn len(&self) -> usize {
self.references.len() + 1
}
}
// allow turning ReferenceSearchResult into an iterator
// over FileRanges
impl IntoIterator for ReferenceSearchResult {
type Item = FileRange;
2019-02-17 09:25:19 -06:00
type IntoIter = std::vec::IntoIter<FileRange>;
fn into_iter(mut self) -> Self::IntoIter {
let mut v = Vec::with_capacity(self.len());
v.push(FileRange { file_id: self.declaration.file_id(), range: self.declaration.range() });
v.append(&mut self.references);
v.into_iter()
}
}
pub(crate) fn find_all_refs(
db: &RootDatabase,
position: FilePosition,
2019-09-05 13:36:40 -05:00
) -> Option<RangeInfo<ReferenceSearchResult>> {
let parse = db.parse(position.file_id);
2019-09-14 06:38:10 -05:00
let syntax = parse.tree().syntax().clone();
2019-10-10 10:51:51 -05:00
let RangeInfo { range, info: (name, def) } = find_name(db, &syntax, position)?;
2019-09-14 06:38:10 -05:00
2019-10-10 10:51:51 -05:00
let declaration = match def.item {
2019-09-14 06:38:10 -05:00
Macro(mac) => NavigationTarget::from_macro_def(db, mac),
FieldAccess(field) => NavigationTarget::from_field(db, field),
AssocItem(assoc) => NavigationTarget::from_assoc_item(db, assoc),
Def(def) => NavigationTarget::from_def(db, def)?,
SelfType(ref ty) => match ty.as_adt() {
Some((def_id, _)) => NavigationTarget::from_adt_def(db, def_id),
None => return None,
},
Pat((_, pat)) => NavigationTarget::from_pat(db, position.file_id, pat),
2019-09-14 06:38:10 -05:00
SelfParam(par) => NavigationTarget::from_self_param(position.file_id, par),
GenericParam(_) => return None,
};
2019-02-08 05:06:26 -06:00
2019-10-10 10:51:51 -05:00
// let references = match name_kind {
// Pat((_, pat)) => analyzer
// .find_all_refs(&pat.to_node(&syntax))
// .into_iter()
// .map(move |ref_desc| FileRange { file_id: position.file_id, range: ref_desc.range })
// .collect::<Vec<_>>(),
// _ => vec![],
// };
let references = find_refs(db, def, name);
let references = references
.into_iter()
.map(move |ref_desc| FileRange { file_id: position.file_id, range: ref_desc.range })
.collect::<Vec<_>>();
2019-02-08 05:06:26 -06:00
2019-09-05 13:36:40 -05:00
return Some(RangeInfo::new(range, ReferenceSearchResult { declaration, references }));
2019-02-08 05:06:26 -06:00
2019-09-14 06:38:10 -05:00
fn find_name<'a>(
2019-02-08 05:06:26 -06:00
db: &RootDatabase,
2019-09-14 06:38:10 -05:00
syntax: &SyntaxNode,
2019-02-08 05:06:26 -06:00
position: FilePosition,
2019-10-10 10:51:51 -05:00
) -> Option<RangeInfo<(String, Definition)>> {
2019-09-14 06:38:10 -05:00
if let Some(name) = find_node_at_offset::<ast::Name>(&syntax, position.offset) {
2019-10-10 10:51:51 -05:00
let def = classify_name(db, position.file_id, &name)?;
2019-09-14 06:38:10 -05:00
let range = name.syntax().text_range();
2019-10-10 10:51:51 -05:00
return Some(RangeInfo::new(range, (name.text().to_string(), def)));
2019-09-14 06:38:10 -05:00
}
let name_ref = find_node_at_offset::<ast::NameRef>(&syntax, position.offset)?;
2019-09-05 13:36:40 -05:00
let range = name_ref.syntax().text_range();
2019-04-13 01:31:03 -05:00
let analyzer = hir::SourceAnalyzer::new(db, position.file_id, name_ref.syntax(), None);
2019-10-10 10:51:51 -05:00
let def = classify_name_ref(db, position.file_id, &analyzer, &name_ref)?;
Some(RangeInfo::new(range, (name_ref.text().to_string(), def)))
2019-09-14 06:38:10 -05:00
}
}
2019-01-16 07:39:01 -06:00
pub(crate) fn rename(
db: &RootDatabase,
position: FilePosition,
new_name: &str,
2019-09-05 13:36:40 -05:00
) -> Option<RangeInfo<SourceChange>> {
let parse = db.parse(position.file_id);
2019-07-19 04:56:47 -05:00
if let Some((ast_name, ast_module)) =
find_name_and_module_at_offset(parse.tree().syntax(), position)
{
2019-09-05 13:36:40 -05:00
let range = ast_name.syntax().text_range();
2019-07-19 04:56:47 -05:00
rename_mod(db, &ast_name, &ast_module, position, new_name)
2019-09-05 13:36:40 -05:00
.map(|info| RangeInfo::new(range, info))
2019-01-16 07:39:01 -06:00
} else {
rename_reference(db, position, new_name)
}
}
fn find_name_and_module_at_offset(
syntax: &SyntaxNode,
position: FilePosition,
2019-07-19 04:56:47 -05:00
) -> Option<(ast::Name, ast::Module)> {
let ast_name = find_node_at_offset::<ast::Name>(syntax, position.offset)?;
let ast_module = ast::Module::cast(ast_name.syntax().parent()?)?;
Some((ast_name, ast_module))
2019-01-16 07:39:01 -06:00
}
2019-09-05 13:36:40 -05:00
fn source_edit_from_file_id_range(
file_id: FileId,
range: TextRange,
new_name: &str,
) -> SourceFileEdit {
SourceFileEdit {
file_id,
edit: {
let mut builder = ra_text_edit::TextEditBuilder::default();
builder.replace(range, new_name.into());
builder.finish()
},
}
}
2019-01-16 07:39:01 -06:00
fn rename_mod(
db: &RootDatabase,
ast_name: &ast::Name,
ast_module: &ast::Module,
position: FilePosition,
new_name: &str,
) -> Option<SourceChange> {
let mut source_file_edits = Vec::new();
let mut file_system_edits = Vec::new();
2019-09-16 05:48:54 -05:00
let module_src = hir::Source { file_id: position.file_id.into(), ast: ast_module.clone() };
if let Some(module) = hir::Module::from_declaration(db, module_src) {
2019-06-11 09:47:24 -05:00
let src = module.definition_source(db);
let file_id = src.file_id.original_file(db);
2019-06-11 09:47:24 -05:00
match src.ast {
2019-01-16 07:39:01 -06:00
ModuleSource::SourceFile(..) => {
let mod_path: RelativePathBuf = db.file_relative_path(file_id);
// mod is defined in path/to/dir/mod.rs
let dst_path = if mod_path.file_stem() == Some("mod") {
mod_path
.parent()
.and_then(|p| p.parent())
.or_else(|| Some(RelativePath::new("")))
.map(|p| p.join(new_name).join("mod.rs"))
} else {
Some(mod_path.with_file_name(new_name).with_extension("rs"))
};
if let Some(path) = dst_path {
let move_file = FileSystemEdit::MoveFile {
src: file_id,
dst_source_root: db.file_source_root(position.file_id),
dst_path: path,
};
file_system_edits.push(move_file);
}
}
ModuleSource::Module(..) => {}
}
}
let edit = SourceFileEdit {
file_id: position.file_id,
edit: {
let mut builder = ra_text_edit::TextEditBuilder::default();
2019-07-20 04:58:27 -05:00
builder.replace(ast_name.syntax().text_range(), new_name.into());
2019-01-16 07:39:01 -06:00
builder.finish()
},
};
source_file_edits.push(edit);
Some(SourceChange::from_edits("rename", source_file_edits, file_system_edits))
2019-01-16 07:39:01 -06:00
}
fn rename_reference(
db: &RootDatabase,
position: FilePosition,
new_name: &str,
2019-09-05 13:36:40 -05:00
) -> Option<RangeInfo<SourceChange>> {
let RangeInfo { range, info: refs } = find_all_refs(db, position)?;
let edit = refs
.into_iter()
2019-09-05 13:36:40 -05:00
.map(|range| source_edit_from_file_id_range(range.file_id, range.range, new_name))
2019-01-16 07:39:01 -06:00
.collect::<Vec<_>>();
2019-01-16 07:39:01 -06:00
if edit.is_empty() {
return None;
}
2019-09-05 13:36:40 -05:00
Some(RangeInfo::new(range, SourceChange::source_file_edits("rename", edit)))
2019-01-16 07:39:01 -06:00
}
2019-01-18 02:29:09 -06:00
#[cfg(test)]
mod tests {
use crate::{
mock_analysis::analysis_and_position, mock_analysis::single_file_with_position, FileId,
ReferenceSearchResult,
};
2019-08-29 08:49:10 -05:00
use insta::assert_debug_snapshot;
2019-01-18 02:29:09 -06:00
use test_utils::assert_eq_text;
2019-03-25 15:03:32 -05:00
#[test]
fn test_find_all_refs_for_local() {
let code = r#"
fn main() {
let mut i = 1;
let j = 1;
i = i<|> + j;
{
i = 0;
}
i = 5;
}"#;
let refs = get_all_refs(code);
assert_eq!(refs.len(), 5);
}
#[test]
fn test_find_all_refs_for_param_inside() {
let code = r#"
fn foo(i : u32) -> u32 {
i<|>
}"#;
let refs = get_all_refs(code);
assert_eq!(refs.len(), 2);
}
#[test]
fn test_find_all_refs_for_fn_param() {
let code = r#"
fn foo(i<|> : u32) -> u32 {
i
}"#;
let refs = get_all_refs(code);
assert_eq!(refs.len(), 2);
}
2019-09-14 06:38:10 -05:00
#[test]
fn test_find_all_refs_field_name() {
let code = r#"
//- /lib.rs
struct Foo {
2019-10-10 10:51:51 -05:00
pub spam<|>: u32,
}
fn main(s: Foo) {
let f = s.spam;
2019-09-14 06:38:10 -05:00
}
"#;
let refs = get_all_refs(code);
2019-10-10 10:51:51 -05:00
assert_eq!(refs.len(), 2);
2019-09-14 06:38:10 -05:00
}
#[test]
fn test_find_all_refs_impl_item_name() {
let code = r#"
//- /lib.rs
struct Foo;
impl Foo {
fn f<|>(&self) { }
}
"#;
let refs = get_all_refs(code);
assert_eq!(refs.len(), 1);
}
#[test]
fn test_find_all_refs_enum_var_name() {
let code = r#"
//- /lib.rs
enum Foo {
A,
B<|>,
C,
}
"#;
let refs = get_all_refs(code);
assert_eq!(refs.len(), 1);
}
2019-03-25 15:03:32 -05:00
fn get_all_refs(text: &str) -> ReferenceSearchResult {
let (analysis, position) = single_file_with_position(text);
analysis.find_all_refs(position).unwrap().unwrap()
}
2019-01-18 02:29:09 -06:00
#[test]
fn test_rename_for_local() {
test_rename(
r#"
fn main() {
let mut i = 1;
let j = 1;
i = i<|> + j;
{
i = 0;
}
i = 5;
}"#,
"k",
r#"
fn main() {
let mut k = 1;
let j = 1;
k = k + j;
{
k = 0;
}
k = 5;
}"#,
);
}
#[test]
fn test_rename_for_param_inside() {
test_rename(
r#"
fn foo(i : u32) -> u32 {
i<|>
}"#,
"j",
r#"
fn foo(j : u32) -> u32 {
j
}"#,
);
}
#[test]
fn test_rename_refs_for_fn_param() {
test_rename(
r#"
fn foo(i<|> : u32) -> u32 {
i
}"#,
"new_name",
r#"
fn foo(new_name : u32) -> u32 {
new_name
}"#,
);
}
#[test]
fn test_rename_for_mut_param() {
test_rename(
r#"
fn foo(mut i<|> : u32) -> u32 {
i
}"#,
"new_name",
r#"
fn foo(mut new_name : u32) -> u32 {
new_name
}"#,
);
}
#[test]
fn test_rename_mod() {
let (analysis, position) = analysis_and_position(
"
//- /lib.rs
mod bar;
//- /bar.rs
mod foo<|>;
//- /bar/foo.rs
// emtpy
",
2019-01-18 02:29:09 -06:00
);
let new_name = "foo2";
let source_change = analysis.rename(position, new_name).unwrap();
2019-08-29 08:49:10 -05:00
assert_debug_snapshot!(&source_change,
2019-09-05 13:36:40 -05:00
@r###"
Some(
RangeInfo {
range: [4; 7),
info: SourceChange {
label: "rename",
source_file_edits: [
SourceFileEdit {
file_id: FileId(
2,
),
edit: TextEdit {
atoms: [
AtomTextEdit {
delete: [4; 7),
insert: "foo2",
},
],
},
},
],
file_system_edits: [
MoveFile {
src: FileId(
3,
),
dst_source_root: SourceRootId(
0,
),
dst_path: "bar/foo2.rs",
},
],
2019-09-05 13:36:40 -05:00
cursor_position: None,
},
},
2019-09-05 13:36:40 -05:00
)
"###);
2019-01-18 02:29:09 -06:00
}
#[test]
fn test_rename_mod_in_dir() {
let (analysis, position) = analysis_and_position(
"
//- /lib.rs
mod fo<|>o;
//- /foo/mod.rs
// emtpy
",
2019-01-18 02:29:09 -06:00
);
let new_name = "foo2";
let source_change = analysis.rename(position, new_name).unwrap();
2019-08-29 08:49:10 -05:00
assert_debug_snapshot!(&source_change,
2019-09-05 13:36:40 -05:00
@r###"
Some(
RangeInfo {
range: [4; 7),
info: SourceChange {
label: "rename",
source_file_edits: [
SourceFileEdit {
file_id: FileId(
1,
),
edit: TextEdit {
atoms: [
AtomTextEdit {
delete: [4; 7),
insert: "foo2",
},
],
},
},
],
file_system_edits: [
MoveFile {
src: FileId(
2,
),
dst_source_root: SourceRootId(
0,
),
dst_path: "foo2/mod.rs",
},
],
2019-09-05 13:36:40 -05:00
cursor_position: None,
},
},
2019-09-05 13:36:40 -05:00
)
"###
);
2019-01-18 02:29:09 -06:00
}
fn test_rename(text: &str, new_name: &str, expected: &str) {
let (analysis, position) = single_file_with_position(text);
let source_change = analysis.rename(position, new_name).unwrap();
2019-02-11 10:18:27 -06:00
let mut text_edit_builder = ra_text_edit::TextEditBuilder::default();
2019-01-18 02:29:09 -06:00
let mut file_id: Option<FileId> = None;
if let Some(change) = source_change {
2019-09-05 13:36:40 -05:00
for edit in change.info.source_file_edits {
2019-01-18 02:29:09 -06:00
file_id = Some(edit.file_id);
for atom in edit.edit.as_atoms() {
2019-02-11 10:18:27 -06:00
text_edit_builder.replace(atom.delete, atom.insert.clone());
2019-01-18 02:29:09 -06:00
}
}
}
2019-07-25 12:22:41 -05:00
let result =
text_edit_builder.finish().apply(&*analysis.file_text(file_id.unwrap()).unwrap());
2019-01-18 02:29:09 -06:00
assert_eq_text!(expected, &*result);
}
}