Unnamed repository; edit this file 'description' to name the repository.
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
//! This module allows building an SSR MatchFinder by parsing the SSR rule
//! from a comment.

use ide_db::{
    base_db::{FilePosition, FileRange, SourceDatabase},
    RootDatabase,
};
use syntax::{
    ast::{self, AstNode, AstToken},
    TextRange,
};

use crate::MatchFinder;

/// Attempts to build an SSR MatchFinder from a comment at the given file
/// range. If successful, returns the MatchFinder and a TextRange covering
/// comment.
pub fn ssr_from_comment(db: &RootDatabase, frange: FileRange) -> Option<(MatchFinder, TextRange)> {
    let comment = {
        let file = db.parse(frange.file_id);
        file.tree().syntax().token_at_offset(frange.range.start()).find_map(ast::Comment::cast)
    }?;
    let comment_text_without_prefix = comment.text().strip_prefix(comment.prefix()).unwrap();
    let ssr_rule = comment_text_without_prefix.parse().ok()?;

    let lookup_context = FilePosition { file_id: frange.file_id, offset: frange.range.start() };

    let mut match_finder = MatchFinder::in_context(db, lookup_context, vec![]);
    match_finder.add_rule(ssr_rule).ok()?;

    Some((match_finder, comment.syntax().text_range()))
}
range) } }) .filter_map(move |i| { let (target_range, source_range) = self.ranges[i]; let intersection = target_range.intersect(range).unwrap(); let source_range = source_range?; Some(intersection - target_range.start() + source_range.start()) }) } pub fn map_offset_down(&self, offset: TextSize) -> Option<TextSize> { // Using a binary search here is a bit complicated because of the `None` entries. // But the number of lines in fixtures is usually low. let (target_range, source_range) = self.ranges.iter().find_map(|&(target_range, source_range)| { let source_range = source_range?; if !source_range.contains(offset) { return None; } Some((target_range, source_range)) })?; Some(offset - source_range.start() + target_range.start()) } }