]> git.lizzy.rs Git - rust.git/blob - crates/ide_ssr/src/replacing.rs
Merge #11821
[rust.git] / crates / ide_ssr / src / replacing.rs
1 //! Code for applying replacement templates for matches that have previously been found.
2
3 use crate::fragments;
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};
9
10 use text_edit::TextEdit;
11
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(
16     matches: &SsrMatches,
17     file_src: &str,
18     rules: &[ResolvedRule],
19 ) -> TextEdit {
20     matches_to_edit_at_offset(matches, file_src, 0.into(), rules)
21 }
22
23 fn matches_to_edit_at_offset(
24     matches: &SsrMatches,
25     file_src: &str,
26     relative_start: TextSize,
27     rules: &[ResolvedRule],
28 ) -> TextEdit {
29     let mut edit_builder = TextEdit::builder();
30     for m in &matches.matches {
31         edit_builder.replace(
32             m.range.range.checked_sub(relative_start).unwrap(),
33             render_replace(m, file_src, rules),
34         );
35     }
36     edit_builder.finish()
37 }
38
39 struct ReplacementRenderer<'a> {
40     match_info: &'a Match,
41     file_src: &'a str,
42     rules: &'a [ResolvedRule],
43     rule: &'a ResolvedRule,
44     out: String,
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
47     // below).
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>,
53 }
54
55 fn render_replace(match_info: &Match, file_src: &str, rules: &[ResolvedRule]) -> String {
56     let rule = &rules[match_info.rule_index];
57     let template = rule
58         .template
59         .as_ref()
60         .expect("You called MatchFinder::edits after calling MatchFinder::add_search_pattern");
61     let mut renderer = ReplacementRenderer {
62         match_info,
63         file_src,
64         rules,
65         rule,
66         out: String::new(),
67         placeholder_tokens_requiring_parenthesis: FxHashSet::default(),
68         placeholder_tokens_by_range: FxHashMap::default(),
69     };
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());
74     }
75     renderer.out
76 }
77
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);
82         }
83     }
84
85     fn render_node_or_token(&mut self, node_or_token: &SyntaxElement) {
86         match node_or_token {
87             SyntaxElement::Token(token) => {
88                 self.render_token(token);
89             }
90             SyntaxElement::Node(child_node) => {
91                 self.render_node(child_node);
92             }
93         }
94     }
95
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);
106                         }
107                     }
108                 }
109             }
110         } else {
111             self.render_node_children(node);
112         }
113     }
114
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)
119             {
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
127                 // site.
128                 if !token_is_method_call_receiver(token)
129                     && (placeholder_value.autoderef_count > 0
130                         || placeholder_value.autoref_kind != ast::SelfParamKind::Owned)
131                 {
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 ",
137                     };
138                     matched_text = format!(
139                         "{}{}{}",
140                         ref_kind,
141                         "*".repeat(placeholder_value.autoderef_count),
142                         matched_text
143                     );
144                 }
145                 let edit = matches_to_edit_at_offset(
146                     &placeholder_value.inner_matches,
147                     self.file_src,
148                     range.start(),
149                     self.rules,
150                 );
151                 let needs_parenthesis =
152                     self.placeholder_tokens_requiring_parenthesis.contains(token);
153                 edit.apply(&mut matched_text);
154                 if needs_parenthesis {
155                     self.out.push('(');
156                 }
157                 self.placeholder_tokens_by_range.insert(
158                     TextRange::new(
159                         TextSize::of(&self.out),
160                         TextSize::of(&self.out) + TextSize::of(&matched_text),
161                     ),
162                     token.clone(),
163                 );
164                 self.out.push_str(&matched_text);
165                 if needs_parenthesis {
166                     self.out.push(')');
167                 }
168             } else {
169                 // We validated that all placeholder references were valid before we
170                 // started, so this shouldn't happen.
171                 panic!(
172                     "Internal error: replacement referenced unknown placeholder {}",
173                     placeholder.ident
174                 );
175             }
176         } else {
177             self.out.push_str(token.text());
178         }
179     }
180
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() {
188                 return;
189             }
190             self.placeholder_tokens_requiring_parenthesis =
191                 self.placeholder_tokens_by_range.values().cloned().collect();
192             self.out.clear();
193             self.render_node(template);
194         }
195     }
196
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);
201         }
202     }
203 }
204
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())
213     {
214         let tokens = receiver.syntax().descendants_with_tokens().filter_map(|node_or_token| {
215             match node_or_token {
216                 SyntaxElement::Token(t) => Some(t),
217                 _ => None,
218             }
219         });
220         if let Some((only_token,)) = tokens.collect_tuple() {
221             return only_token == *token;
222         }
223     }
224     false
225 }
226
227 fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option<SyntaxNode> {
228     if ast::Expr::can_cast(kind) {
229         if let Ok(expr) = fragments::expr(code) {
230             return Some(expr);
231         }
232     }
233     if ast::Item::can_cast(kind) {
234         if let Ok(item) = fragments::item(code) {
235             return Some(item);
236         }
237     }
238     None
239 }