1 //! Code for applying replacement templates for matches that have previously been found.
4 use crate::{resolving::ResolvedRule, Match, SsrMatches};
5 use itertools::Itertools;
6 use rustc_hash::{FxHashMap, FxHashSet};
7 use syntax::ast::{self, AstNode, AstToken};
8 use syntax::{SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize};
10 use text_edit::TextEdit;
12 /// Returns a text edit that will replace each match in `matches` with its corresponding replacement
13 /// template. Placeholders in the template will have been substituted with whatever they matched to
14 /// in the original code.
15 pub(crate) fn matches_to_edit(
18 rules: &[ResolvedRule],
20 matches_to_edit_at_offset(matches, file_src, 0.into(), rules)
23 fn matches_to_edit_at_offset(
26 relative_start: TextSize,
27 rules: &[ResolvedRule],
29 let mut edit_builder = TextEdit::builder();
30 for m in &matches.matches {
32 m.range.range.checked_sub(relative_start).unwrap(),
33 render_replace(m, file_src, rules),
39 struct ReplacementRenderer<'a> {
40 match_info: &'a Match,
42 rules: &'a [ResolvedRule],
43 rule: &'a ResolvedRule,
45 // Map from a range within `out` to a token in `template` that represents a placeholder. This is
46 // used to validate that the generated source code doesn't split any placeholder expansions (see
48 placeholder_tokens_by_range: FxHashMap<TextRange, SyntaxToken>,
49 // Which placeholder tokens need to be wrapped in parenthesis in order to ensure that when `out`
50 // is parsed, placeholders don't get split. e.g. if a template of `$a.to_string()` results in `1
51 // + 2.to_string()` then the placeholder value `1 + 2` was split and needs parenthesis.
52 placeholder_tokens_requiring_parenthesis: FxHashSet<SyntaxToken>,
55 fn render_replace(match_info: &Match, file_src: &str, rules: &[ResolvedRule]) -> String {
56 let rule = &rules[match_info.rule_index];
60 .expect("You called MatchFinder::edits after calling MatchFinder::add_search_pattern");
61 let mut renderer = ReplacementRenderer {
67 placeholder_tokens_requiring_parenthesis: FxHashSet::default(),
68 placeholder_tokens_by_range: FxHashMap::default(),
70 renderer.render_node(&template.node);
71 renderer.maybe_rerender_with_extra_parenthesis(&template.node);
72 for comment in &match_info.ignored_comments {
73 renderer.out.push_str(&comment.syntax().to_string());
78 impl ReplacementRenderer<'_> {
79 fn render_node_children(&mut self, node: &SyntaxNode) {
80 for node_or_token in node.children_with_tokens() {
81 self.render_node_or_token(&node_or_token);
85 fn render_node_or_token(&mut self, node_or_token: &SyntaxElement) {
87 SyntaxElement::Token(token) => {
88 self.render_token(token);
90 SyntaxElement::Node(child_node) => {
91 self.render_node(child_node);
96 fn render_node(&mut self, node: &SyntaxNode) {
97 if let Some(mod_path) = self.match_info.rendered_template_paths.get(node) {
98 self.out.push_str(&mod_path.to_string());
99 // Emit everything except for the segment's name-ref, since we already effectively
100 // emitted that as part of `mod_path`.
101 if let Some(path) = ast::Path::cast(node.clone()) {
102 if let Some(segment) = path.segment() {
103 for node_or_token in segment.syntax().children_with_tokens() {
104 if node_or_token.kind() != SyntaxKind::NAME_REF {
105 self.render_node_or_token(&node_or_token);
111 self.render_node_children(node);
115 fn render_token(&mut self, token: &SyntaxToken) {
116 if let Some(placeholder) = self.rule.get_placeholder(token) {
117 if let Some(placeholder_value) =
118 self.match_info.placeholder_values.get(&placeholder.ident)
120 let range = &placeholder_value.range.range;
121 let mut matched_text =
122 self.file_src[usize::from(range.start())..usize::from(range.end())].to_owned();
123 // If a method call is performed directly on the placeholder, then autoderef and
124 // autoref will apply, so we can just substitute whatever the placeholder matched to
125 // directly. If we're not applying a method call, then we need to add explicitly
126 // deref and ref in order to match whatever was being done implicitly at the match
128 if !token_is_method_call_receiver(token)
129 && (placeholder_value.autoderef_count > 0
130 || placeholder_value.autoref_kind != ast::SelfParamKind::Owned)
132 cov_mark::hit!(replace_autoref_autoderef_capture);
133 let ref_kind = match placeholder_value.autoref_kind {
134 ast::SelfParamKind::Owned => "",
135 ast::SelfParamKind::Ref => "&",
136 ast::SelfParamKind::MutRef => "&mut ",
138 matched_text = format!(
141 "*".repeat(placeholder_value.autoderef_count),
145 let edit = matches_to_edit_at_offset(
146 &placeholder_value.inner_matches,
151 let needs_parenthesis =
152 self.placeholder_tokens_requiring_parenthesis.contains(token);
153 edit.apply(&mut matched_text);
154 if needs_parenthesis {
157 self.placeholder_tokens_by_range.insert(
159 TextSize::of(&self.out),
160 TextSize::of(&self.out) + TextSize::of(&matched_text),
164 self.out.push_str(&matched_text);
165 if needs_parenthesis {
169 // We validated that all placeholder references were valid before we
170 // started, so this shouldn't happen.
172 "Internal error: replacement referenced unknown placeholder {}",
177 self.out.push_str(token.text());
181 // Checks if the resulting code, when parsed doesn't split any placeholders due to different
182 // order of operations between the search pattern and the replacement template. If any do, then
183 // we rerender the template and wrap the problematic placeholders with parenthesis.
184 fn maybe_rerender_with_extra_parenthesis(&mut self, template: &SyntaxNode) {
185 if let Some(node) = parse_as_kind(&self.out, template.kind()) {
186 self.remove_node_ranges(node);
187 if self.placeholder_tokens_by_range.is_empty() {
190 self.placeholder_tokens_requiring_parenthesis =
191 self.placeholder_tokens_by_range.values().cloned().collect();
193 self.render_node(template);
197 fn remove_node_ranges(&mut self, node: SyntaxNode) {
198 self.placeholder_tokens_by_range.remove(&node.text_range());
199 for child in node.children() {
200 self.remove_node_ranges(child);
205 /// Returns whether token is the receiver of a method call. Note, being within the receiver of a
206 /// method call doesn't count. e.g. if the token is `$a`, then `$a.foo()` will return true, while
207 /// `($a + $b).foo()` or `x.foo($a)` will return false.
208 fn token_is_method_call_receiver(token: &SyntaxToken) -> bool {
209 // Find the first method call among the ancestors of `token`, then check if the only token
210 // within the receiver is `token`.
211 if let Some(receiver) =
212 token.ancestors().find_map(ast::MethodCallExpr::cast).and_then(|call| call.receiver())
214 let tokens = receiver.syntax().descendants_with_tokens().filter_map(|node_or_token| {
215 match node_or_token {
216 SyntaxElement::Token(t) => Some(t),
220 if let Some((only_token,)) = tokens.collect_tuple() {
221 return only_token == *token;
227 fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option<SyntaxNode> {
228 if ast::Expr::can_cast(kind) {
229 if let Ok(expr) = ast::Expr::parse(code) {
230 return Some(expr.syntax().clone());
233 if ast::Item::can_cast(kind) {
234 if let Ok(item) = fragments::item(code) {