aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_analysis/src/extend_selection.rs
blob: 805e9059efecf995d09cb4cafa6ba25d2b820b7f (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
use ra_db::SyntaxDatabase;
use ra_syntax::{
    SyntaxNodeRef, AstNode, SourceFileNode,
    ast, algo::find_covering_node,
};

use crate::{
    TextRange, FileRange,
    db::RootDatabase,
};

pub(crate) fn extend_selection(db: &RootDatabase, frange: FileRange) -> TextRange {
    let source_file = db.source_file(frange.file_id);
    if let Some(range) = extend_selection_in_macro(db, &source_file, frange) {
        return range;
    }
    ra_editor::extend_selection(source_file.syntax(), frange.range).unwrap_or(frange.range)
}

fn extend_selection_in_macro(
    db: &RootDatabase,
    source_file: &SourceFileNode,
    frange: FileRange,
) -> Option<TextRange> {
    let macro_call = find_macro_call(source_file.syntax(), frange.range)?;
    let exp = crate::macros::expand(db, frange.file_id, macro_call)?;
    let dst_range = exp.map_range_forward(frange.range)?;
    let dst_range = ra_editor::extend_selection(exp.source_file().syntax(), dst_range)?;
    let src_range = exp.map_range_back(dst_range)?;
    Some(src_range)
}

fn find_macro_call(node: SyntaxNodeRef, range: TextRange) -> Option<ast::MacroCall> {
    find_covering_node(node, range)
        .ancestors()
        .find_map(ast::MacroCall::cast)
}

#[cfg(test)]
mod tests {
    use crate::mock_analysis::single_file_with_range;
    use test_utils::assert_eq_dbg;

    #[test]
    fn extend_selection_inside_macros() {
        let (analysis, frange) = single_file_with_range(
            "
            fn main() {
                ctry!(foo(|x| <|>x<|>));
            }
        ",
        );
        let r = analysis.extend_selection(frange);
        assert_eq_dbg("[51; 56)", &r);
    }
}