diff options
Diffstat (limited to 'crates/ssr/src/replacing.rs')
-rw-r--r-- | crates/ssr/src/replacing.rs | 240 |
1 files changed, 240 insertions, 0 deletions
diff --git a/crates/ssr/src/replacing.rs b/crates/ssr/src/replacing.rs new file mode 100644 index 000000000..29284e3f1 --- /dev/null +++ b/crates/ssr/src/replacing.rs | |||
@@ -0,0 +1,240 @@ | |||
1 | //! Code for applying replacement templates for matches that have previously been found. | ||
2 | |||
3 | use crate::{resolving::ResolvedRule, Match, SsrMatches}; | ||
4 | use itertools::Itertools; | ||
5 | use rustc_hash::{FxHashMap, FxHashSet}; | ||
6 | use syntax::ast::{self, AstToken}; | ||
7 | use syntax::{SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize}; | ||
8 | use test_utils::mark; | ||
9 | use text_edit::TextEdit; | ||
10 | |||
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( | ||
15 | matches: &SsrMatches, | ||
16 | file_src: &str, | ||
17 | rules: &[ResolvedRule], | ||
18 | ) -> TextEdit { | ||
19 | matches_to_edit_at_offset(matches, file_src, 0.into(), rules) | ||
20 | } | ||
21 | |||
22 | fn matches_to_edit_at_offset( | ||
23 | matches: &SsrMatches, | ||
24 | file_src: &str, | ||
25 | relative_start: TextSize, | ||
26 | rules: &[ResolvedRule], | ||
27 | ) -> TextEdit { | ||
28 | let mut edit_builder = TextEdit::builder(); | ||
29 | for m in &matches.matches { | ||
30 | edit_builder.replace( | ||
31 | m.range.range.checked_sub(relative_start).unwrap(), | ||
32 | render_replace(m, file_src, rules), | ||
33 | ); | ||
34 | } | ||
35 | edit_builder.finish() | ||
36 | } | ||
37 | |||
38 | struct ReplacementRenderer<'a> { | ||
39 | match_info: &'a Match, | ||
40 | file_src: &'a str, | ||
41 | rules: &'a [ResolvedRule], | ||
42 | rule: &'a ResolvedRule, | ||
43 | out: String, | ||
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 | ||
46 | // below). | ||
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>, | ||
52 | } | ||
53 | |||
54 | fn render_replace(match_info: &Match, file_src: &str, rules: &[ResolvedRule]) -> String { | ||
55 | let rule = &rules[match_info.rule_index]; | ||
56 | let template = rule | ||
57 | .template | ||
58 | .as_ref() | ||
59 | .expect("You called MatchFinder::edits after calling MatchFinder::add_search_pattern"); | ||
60 | let mut renderer = ReplacementRenderer { | ||
61 | match_info, | ||
62 | file_src, | ||
63 | rules, | ||
64 | rule, | ||
65 | out: String::new(), | ||
66 | placeholder_tokens_requiring_parenthesis: FxHashSet::default(), | ||
67 | placeholder_tokens_by_range: FxHashMap::default(), | ||
68 | }; | ||
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()); | ||
73 | } | ||
74 | renderer.out | ||
75 | } | ||
76 | |||
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); | ||
81 | } | ||
82 | } | ||
83 | |||
84 | fn render_node_or_token(&mut self, node_or_token: &SyntaxElement) { | ||
85 | match node_or_token { | ||
86 | SyntaxElement::Token(token) => { | ||
87 | self.render_token(&token); | ||
88 | } | ||
89 | SyntaxElement::Node(child_node) => { | ||
90 | self.render_node(&child_node); | ||
91 | } | ||
92 | } | ||
93 | } | ||
94 | |||
95 | fn render_node(&mut self, node: &SyntaxNode) { | ||
96 | use syntax::ast::AstNode; | ||
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 | 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().as_str()); | ||
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 | use syntax::ast::AstNode; | ||
210 | // Find the first method call among the ancestors of `token`, then check if the only token | ||
211 | // within the receiver is `token`. | ||
212 | if let Some(receiver) = | ||
213 | token.ancestors().find_map(ast::MethodCallExpr::cast).and_then(|call| call.expr()) | ||
214 | { | ||
215 | let tokens = receiver.syntax().descendants_with_tokens().filter_map(|node_or_token| { | ||
216 | match node_or_token { | ||
217 | SyntaxElement::Token(t) => Some(t), | ||
218 | _ => None, | ||
219 | } | ||
220 | }); | ||
221 | if let Some((only_token,)) = tokens.collect_tuple() { | ||
222 | return only_token == *token; | ||
223 | } | ||
224 | } | ||
225 | false | ||
226 | } | ||
227 | |||
228 | fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option<SyntaxNode> { | ||
229 | use syntax::ast::AstNode; | ||
230 | if ast::Expr::can_cast(kind) { | ||
231 | if let Ok(expr) = ast::Expr::parse(code) { | ||
232 | return Some(expr.syntax().clone()); | ||
233 | } | ||
234 | } else if ast::Item::can_cast(kind) { | ||
235 | if let Ok(item) = ast::Item::parse(code) { | ||
236 | return Some(item.syntax().clone()); | ||
237 | } | ||
238 | } | ||
239 | None | ||
240 | } | ||