Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 157 additions & 5 deletions crates/ra_ssr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ mod replacing;
#[cfg(test)]
mod tests;

use crate::matching::Match;
pub use crate::matching::Match;
use crate::matching::{record_match_fails_reasons_scope, MatchFailureReason};
use hir::Semantics;
use ra_db::{FileId, FileRange};
use ra_syntax::{ast, AstNode, SmolStr, SyntaxNode};
use ra_syntax::{ast, AstNode, SmolStr, SyntaxKind, SyntaxNode, TextRange};
use ra_text_edit::TextEdit;
use rustc_hash::FxHashMap;

Expand All @@ -26,7 +27,7 @@ pub struct SsrRule {
}

#[derive(Debug)]
struct SsrPattern {
pub struct SsrPattern {
raw: parsing::RawSearchPattern,
/// Placeholders keyed by the stand-in ident that we use in Rust source code.
placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>,
Expand All @@ -45,7 +46,7 @@ pub struct SsrError(String);

#[derive(Debug, Default)]
pub struct SsrMatches {
matches: Vec<Match>,
pub matches: Vec<Match>,
}

/// Searches a crate for pattern matches and possibly replaces them with something else.
Expand All @@ -64,6 +65,12 @@ impl<'db> MatchFinder<'db> {
self.rules.push(rule);
}

/// Adds a search pattern. For use if you intend to only call `find_matches_in_file`. If you
/// intend to do replacement, use `add_rule` instead.
pub fn add_search_pattern(&mut self, pattern: SsrPattern) {
self.add_rule(SsrRule { pattern, template: "()".parse().unwrap() })
}

pub fn edits_for_file(&self, file_id: FileId) -> Option<TextEdit> {
let matches = self.find_matches_in_file(file_id);
if matches.matches.is_empty() {
Expand All @@ -74,14 +81,40 @@ impl<'db> MatchFinder<'db> {
}
}

fn find_matches_in_file(&self, file_id: FileId) -> SsrMatches {
pub fn find_matches_in_file(&self, file_id: FileId) -> SsrMatches {
let file = self.sema.parse(file_id);
let code = file.syntax();
let mut matches = SsrMatches::default();
self.find_matches(code, &None, &mut matches);
matches
}

/// Finds all nodes in `file_id` whose text is exactly equal to `snippet` and attempts to match
/// them, while recording reasons why they don't match. This API is useful for command
/// line-based debugging where providing a range is difficult.
pub fn debug_where_text_equal(&self, file_id: FileId, snippet: &str) -> Vec<MatchDebugInfo> {
use ra_db::SourceDatabaseExt;
let file = self.sema.parse(file_id);
let mut res = Vec::new();
let file_text = self.sema.db.file_text(file_id);
let mut remaining_text = file_text.as_str();
let mut base = 0;
let len = snippet.len() as u32;
while let Some(offset) = remaining_text.find(snippet) {
let start = base + offset as u32;
let end = start + len;
self.output_debug_for_nodes_at_range(
file.syntax(),
FileRange { file_id, range: TextRange::new(start.into(), end.into()) },
&None,
&mut res,
);
remaining_text = &remaining_text[offset + snippet.len()..];
base = end;
}
res
}

fn find_matches(
&self,
code: &SyntaxNode,
Expand Down Expand Up @@ -128,6 +161,59 @@ impl<'db> MatchFinder<'db> {
self.find_matches(&child, restrict_range, matches_out);
}
}

fn output_debug_for_nodes_at_range(
&self,
node: &SyntaxNode,
range: FileRange,
restrict_range: &Option<FileRange>,
out: &mut Vec<MatchDebugInfo>,
) {
for node in node.children() {
let node_range = self.sema.original_range(&node);
if node_range.file_id != range.file_id || !node_range.range.contains_range(range.range)
{
continue;
}
if node_range.range == range.range {
for rule in &self.rules {
let pattern =
rule.pattern.tree_for_kind_with_reason(node.kind()).map(|p| p.clone());
out.push(MatchDebugInfo {
matched: matching::get_match(true, rule, &node, restrict_range, &self.sema)
.map_err(|e| MatchFailureReason {
reason: e.reason.unwrap_or_else(|| {
"Match failed, but no reason was given".to_owned()
}),
}),
pattern,
node: node.clone(),
});
}
} else if let Some(macro_call) = ast::MacroCall::cast(node.clone()) {
if let Some(expanded) = self.sema.expand(&macro_call) {
if let Some(tt) = macro_call.token_tree() {
self.output_debug_for_nodes_at_range(
&expanded,
range,
&Some(self.sema.original_range(tt.syntax())),
out,
);
}
}
} else {
self.output_debug_for_nodes_at_range(&node, range, restrict_range, out);
}
}
}
}

pub struct MatchDebugInfo {
node: SyntaxNode,
/// Our search pattern parsed as the same kind of syntax node as `node`. e.g. expression, item,
/// etc. Will be absent if the pattern can't be parsed as that kind.
pattern: Result<SyntaxNode, MatchFailureReason>,
matched: Result<Match, MatchFailureReason>,
}

impl std::fmt::Display for SsrError {
Expand All @@ -136,4 +222,70 @@ impl std::fmt::Display for SsrError {
}
}

impl std::fmt::Debug for MatchDebugInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "========= PATTERN ==========\n")?;
match &self.pattern {
Ok(pattern) => {
write!(f, "{:#?}", pattern)?;
}
Err(err) => {
write!(f, "{}", err.reason)?;
}
}
write!(
f,
"\n============ AST ===========\n\
{:#?}\n============================\n",
self.node
)?;
match &self.matched {
Ok(_) => write!(f, "Node matched")?,
Err(reason) => write!(f, "Node failed to match because: {}", reason.reason)?,
}
Ok(())
}
}

impl SsrPattern {
fn tree_for_kind_with_reason(
&self,
kind: SyntaxKind,
) -> Result<&SyntaxNode, MatchFailureReason> {
record_match_fails_reasons_scope(true, || self.tree_for_kind(kind))
.map_err(|e| MatchFailureReason { reason: e.reason.unwrap() })
}
}

impl SsrMatches {
/// Returns `self` with any nested matches removed and made into top-level matches.
pub fn flattened(self) -> SsrMatches {
let mut out = SsrMatches::default();
self.flatten_into(&mut out);
out
}

fn flatten_into(self, out: &mut SsrMatches) {
for mut m in self.matches {
for p in m.placeholder_values.values_mut() {
std::mem::replace(&mut p.inner_matches, SsrMatches::default()).flatten_into(out);
}
out.matches.push(m);
}
}
}

impl Match {
pub fn matched_text(&self) -> String {
self.matched_node.text().to_string()
}
}

impl std::error::Error for SsrError {}

#[cfg(test)]
impl MatchDebugInfo {
pub(crate) fn match_failure_reason(&self) -> Option<&str> {
self.matched.as_ref().err().map(|r| r.reason.as_str())
}
}
10 changes: 4 additions & 6 deletions crates/ra_ssr/src/matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ use crate::{
use hir::Semantics;
use ra_db::FileRange;
use ra_syntax::ast::{AstNode, AstToken};
use ra_syntax::{
ast, SyntaxElement, SyntaxElementChildren, SyntaxKind, SyntaxNode, SyntaxToken, TextRange,
};
use ra_syntax::{ast, SyntaxElement, SyntaxElementChildren, SyntaxKind, SyntaxNode, SyntaxToken};
use rustc_hash::FxHashMap;
use std::{cell::Cell, iter::Peekable};

Expand Down Expand Up @@ -44,8 +42,8 @@ macro_rules! fail_match {

/// Information about a match that was found.
#[derive(Debug)]
pub(crate) struct Match {
pub(crate) range: TextRange,
pub struct Match {
pub(crate) range: FileRange,
pub(crate) matched_node: SyntaxNode,
pub(crate) placeholder_values: FxHashMap<Var, PlaceholderMatch>,
pub(crate) ignored_comments: Vec<ast::Comment>,
Expand Down Expand Up @@ -135,7 +133,7 @@ impl<'db, 'sema> MatchState<'db, 'sema> {
match_state.attempt_match_node(&match_inputs, &pattern_tree, code)?;
match_state.validate_range(&sema.original_range(code))?;
match_state.match_out = Some(Match {
range: sema.original_range(code).range,
range: sema.original_range(code),
matched_node: code.clone(),
placeholder_values: FxHashMap::default(),
ignored_comments: Vec::new(),
Expand Down
6 changes: 4 additions & 2 deletions crates/ra_ssr/src/replacing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ fn matches_to_edit_at_offset(
) -> TextEdit {
let mut edit_builder = ra_text_edit::TextEditBuilder::default();
for m in &matches.matches {
edit_builder
.replace(m.range.checked_sub(relative_start).unwrap(), render_replace(m, file_src));
edit_builder.replace(
m.range.range.checked_sub(relative_start).unwrap(),
render_replace(m, file_src),
);
}
edit_builder.finish()
}
Expand Down
Loading