1 //! This module implements a methods and free functions search in the specified file.
2 //! We have to skip tests, so cannot reuse file_structure module.
5 use ide_assists::utils::test_related_attribute;
6 use ide_db::RootDatabase;
7 use syntax::{ast, ast::NameOwner, AstNode, SyntaxNode};
9 use crate::{FileId, FileRange};
11 pub(crate) fn find_all_methods(db: &RootDatabase, file_id: FileId) -> Vec<FileRange> {
12 let sema = Semantics::new(db);
13 let source_file = sema.parse(file_id);
14 source_file.syntax().descendants().filter_map(|it| method_range(it, file_id)).collect()
17 fn method_range(item: SyntaxNode, file_id: FileId) -> Option<FileRange> {
18 ast::Fn::cast(item).and_then(|fn_def| {
19 if test_related_attribute(&fn_def).is_some() {
22 fn_def.name().map(|name| FileRange { file_id, range: name.syntax().text_range() })
30 use crate::{FileRange, TextSize};
31 use std::ops::RangeInclusive;
34 fn test_find_all_methods() {
35 let (analysis, pos) = fixture::position(
41 pub fn generic_fn<T>(arg: T) {}
45 let refs = analysis.find_all_methods(pos.file_id).unwrap();
46 check_result(&refs, &[3..=13, 27..=33, 47..=57]);
50 fn test_find_trait_methods() {
51 let (analysis, pos) = fixture::position(
60 let refs = analysis.find_all_methods(pos.file_id).unwrap();
61 check_result(&refs, &[19..=22, 35..=38]);
65 fn test_skip_tests() {
66 let (analysis, pos) = fixture::position(
81 let refs = analysis.find_all_methods(pos.file_id).unwrap();
82 check_result(&refs, &[28..=34]);
85 fn check_result(refs: &[FileRange], expected: &[RangeInclusive<u32>]) {
86 assert_eq!(refs.len(), expected.len());
88 for (i, item) in refs.iter().enumerate() {
89 let range = &expected[i];
90 assert_eq!(TextSize::from(*range.start()), item.range.start());
91 assert_eq!(TextSize::from(*range.end()), item.range.end());