aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api/src/parent_module.rs
blob: 379b3f3a4f22cf9c40a35d0b30a5b92812ed62b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use ra_db::{Cancelable, FilePosition};

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.
pub(crate) fn parent_module(
    db: &RootDatabase,
    position: FilePosition,
) -> Cancelable<Vec<NavigationTarget>> {
    let module = match hir::source_binder::module_from_position(db, position) {
        None => return Ok(Vec::new()),
        Some(it) => it,
    };
    let nav = NavigationTarget::from_module_to_decl(db, module);
    Ok(vec![nav])
}

#[cfg(test)]
mod tests {
    use crate::mock_analysis::analysis_and_position;

    #[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();
        nav.assert_match("foo MODULE FileId(1) [0; 8)");
    }

    #[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)");
    }
}