ide_ssr/
from_comment.rs

1//! This module allows building an SSR MatchFinder by parsing the SSR rule
2//! from a comment.
3
4use ide_db::{EditionedFileId, FilePosition, FileRange, RootDatabase, base_db::RootQueryDb};
5use syntax::{
6    TextRange,
7    ast::{self, AstNode, AstToken},
8};
9
10use crate::MatchFinder;
11
12/// Attempts to build an SSR MatchFinder from a comment at the given file
13/// range. If successful, returns the MatchFinder and a TextRange covering
14/// comment.
15pub fn ssr_from_comment(
16    db: &RootDatabase,
17    frange: FileRange,
18) -> Option<(MatchFinder<'_>, TextRange)> {
19    let comment = {
20        let file_id = EditionedFileId::current_edition(db, frange.file_id);
21
22        let file = db.parse(file_id);
23        file.tree().syntax().token_at_offset(frange.range.start()).find_map(ast::Comment::cast)
24    }?;
25    let comment_text_without_prefix = comment.text().strip_prefix(comment.prefix()).unwrap();
26    let ssr_rule = comment_text_without_prefix.parse().ok()?;
27
28    let lookup_context = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
29
30    let mut match_finder = MatchFinder::in_context(db, lookup_context, vec![]).ok()?;
31    match_finder.add_rule(ssr_rule).ok()?;
32
33    Some((match_finder, comment.syntax().text_range()))
34}