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