rust/crates/ra_ide/src/ssr.rs

52 lines
1.6 KiB
Rust
Raw Normal View History

use ra_db::SourceDatabaseExt;
2020-05-06 04:31:26 -05:00
use ra_ide_db::{symbol_index::SymbolsDatabase, RootDatabase};
use crate::SourceFileEdit;
use ra_ssr::{MatchFinder, SsrError, SsrRule};
2020-05-31 03:14:36 -05:00
// Feature: Structural Seach and Replace
//
// Search and replace with named wildcards that will match any expression, type, path, pattern or item.
2020-05-31 03:14:36 -05:00
// The syntax for a structural search replace command is `<search_pattern> ==>> <replace_pattern>`.
// A `$<name>` placeholder in the search pattern will match any AST node and `$<name>` will reference it in the replacement.
// Within a macro call, a placeholder will match up until whatever token follows the placeholder.
2020-05-31 03:14:36 -05:00
// Available via the command `rust-analyzer.ssr`.
//
// ```rust
// // Using structural search replace command [foo($a, $b) ==>> ($a).foo($b)]
2020-05-31 03:14:36 -05:00
//
// // BEFORE
// String::from(foo(y + 5, z))
//
// // AFTER
// String::from((y + 5).foo(z))
// ```
//
// |===
// | Editor | Action Name
//
// | VS Code | **Rust Analyzer: Structural Search Replace**
// |===
pub fn parse_search_replace(
rule: &str,
2020-03-15 16:23:18 -05:00
parse_only: bool,
db: &RootDatabase,
) -> Result<Vec<SourceFileEdit>, SsrError> {
let mut edits = vec![];
let rule: SsrRule = rule.parse()?;
2020-03-15 16:23:18 -05:00
if parse_only {
return Ok(edits);
}
let mut match_finder = MatchFinder::new(db);
match_finder.add_rule(rule);
for &root in db.local_roots().iter() {
let sr = db.source_root(root);
2020-06-11 04:04:09 -05:00
for file_id in sr.iter() {
if let Some(edit) = match_finder.edits_for_file(file_id) {
edits.push(SourceFileEdit { file_id, edit });
}
}
}
Ok(edits)
}