aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide/src/parent_module.rs
blob: aaf4460dfa34311ce11c6c824bd207aa6fa96e5c (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//! FIXME: write short doc here

use hir::Semantics;
use ra_db::{CrateId, FileId, FilePosition};
use ra_ide_db::RootDatabase;
use ra_syntax::{
    algo::find_node_at_offset,
    ast::{self, AstNode},
};
use test_utils::tested_by;

use crate::NavigationTarget;

/// 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) -> Vec<NavigationTarget> {
    let sema = Semantics::new(db);
    let source_file = sema.parse(position.file_id);

    let mut module = find_node_at_offset::<ast::Module>(source_file.syntax(), position.offset);

    // If cursor is literally on `mod foo`, go to the grandpa.
    if let Some(m) = &module {
        if !m
            .item_list()
            .map_or(false, |it| it.syntax().text_range().contains_inclusive(position.offset))
        {
            tested_by!(test_resolve_parent_module_on_module_decl);
            module = m.syntax().ancestors().skip(1).find_map(ast::Module::cast);
        }
    }

    let module = match module {
        Some(module) => sema.to_def(&module),
        None => sema.to_module_def(position.file_id),
    };
    let module = match module {
        None => return Vec::new(),
        Some(it) => it,
    };
    let nav = NavigationTarget::from_module_to_decl(db, module);
    vec![nav]
}

/// Returns `Vec` for the same reason as `parent_module`
pub(crate) fn crate_for(db: &RootDatabase, file_id: FileId) -> Vec<CrateId> {
    let sema = Semantics::new(db);
    let module = match sema.to_module_def(file_id) {
        Some(it) => it,
        None => return Vec::new(),
    };
    let krate = module.krate();
    vec![krate.into()]
}

#[cfg(test)]
mod tests {
    use ra_cfg::CfgOptions;
    use ra_db::Env;
    use test_utils::covers;

    use crate::{
        mock_analysis::{analysis_and_position, MockAnalysis},
        AnalysisChange, CrateGraph,
        Edition::Edition2018,
    };

    #[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_on_module_decl() {
        covers!(test_resolve_parent_module_on_module_decl);
        let (analysis, pos) = analysis_and_position(
            "
            //- /lib.rs
            mod foo;

            //- /foo.rs
            mod <|>bar;

            //- /foo/bar.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");
    }

    #[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,
            None,
            CfgOptions::default(),
            Env::default(),
            Default::default(),
            Default::default(),
        );
        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]);
    }
}