From 09307be75b452bd7a10b3855b5d43083cca140a1 Mon Sep 17 00:00:00 2001 From: Josh Mcguigan Date: Mon, 8 Mar 2021 21:11:28 -0800 Subject: add apply ssr assist --- crates/ide_ssr/src/from_comment.rs | 32 ++++++++++++++++++++++++++++++++ crates/ide_ssr/src/lib.rs | 2 ++ 2 files changed, 34 insertions(+) create mode 100644 crates/ide_ssr/src/from_comment.rs (limited to 'crates/ide_ssr') diff --git a/crates/ide_ssr/src/from_comment.rs b/crates/ide_ssr/src/from_comment.rs new file mode 100644 index 000000000..f1b312284 --- /dev/null +++ b/crates/ide_ssr/src/from_comment.rs @@ -0,0 +1,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())) +} diff --git a/crates/ide_ssr/src/lib.rs b/crates/ide_ssr/src/lib.rs index a97fc8bca..e72c611a3 100644 --- a/crates/ide_ssr/src/lib.rs +++ b/crates/ide_ssr/src/lib.rs @@ -58,6 +58,7 @@ // | VS Code | **Rust Analyzer: Structural Search Replace** // |=== +mod from_comment; mod matching; mod nester; mod parsing; @@ -71,6 +72,7 @@ mod tests; use crate::errors::bail; pub use crate::errors::SsrError; +pub use crate::from_comment::ssr_from_comment; pub use crate::matching::Match; use crate::matching::MatchFailureReason; use hir::Semantics; -- cgit v1.2.3