aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_ssr/src/replacing.rs
diff options
context:
space:
mode:
authorChetan Khilosiya <[email protected]>2021-02-22 19:14:58 +0000
committerChetan Khilosiya <[email protected]>2021-02-22 19:29:16 +0000
commiteb6cfa7f157690480fca5d55c69dba3fae87ad4f (patch)
treea49a763fee848041fd607f449ad13a0b1040636e /crates/ide_ssr/src/replacing.rs
parente4756cb4f6e66097638b9d101589358976be2ba8 (diff)
7526: Renamed create ssr to ide_ssr.
Diffstat (limited to 'crates/ide_ssr/src/replacing.rs')
-rw-r--r--crates/ide_ssr/src/replacing.rs237
1 files changed, 237 insertions, 0 deletions
diff --git a/crates/ide_ssr/src/replacing.rs b/crates/ide_ssr/src/replacing.rs
new file mode 100644
index 000000000..06a94a46c
--- /dev/null
+++ b/crates/ide_ssr/src/replacing.rs
@@ -0,0 +1,237 @@
1//! Code for applying replacement templates for matches that have previously been found.
2
3use crate::{resolving::ResolvedRule, Match, SsrMatches};
4use itertools::Itertools;
5use rustc_hash::{FxHashMap, FxHashSet};
6use syntax::ast::{self, AstNode, AstToken};
7use syntax::{SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize};
8use test_utils::mark;
9use 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.
14pub(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
22fn 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
38struct 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
54fn 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
77impl 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 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);
105 }
106 }
107 }
108 }
109 } else {
110 self.render_node_children(&node);
111 }
112 }
113
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)
118 {
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
126 // site.
127 if !token_is_method_call_receiver(token)
128 && (placeholder_value.autoderef_count > 0
129 || placeholder_value.autoref_kind != ast::SelfParamKind::Owned)
130 {
131 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 ",
136 };
137 matched_text = format!(
138 "{}{}{}",
139 ref_kind,
140 "*".repeat(placeholder_value.autoderef_count),
141 matched_text
142 );
143 }
144 let edit = matches_to_edit_at_offset(
145 &placeholder_value.inner_matches,
146 self.file_src,
147 range.start(),
148 self.rules,
149 );
150 let needs_parenthesis =
151 self.placeholder_tokens_requiring_parenthesis.contains(token);
152 edit.apply(&mut matched_text);
153 if needs_parenthesis {
154 self.out.push('(');
155 }
156 self.placeholder_tokens_by_range.insert(
157 TextRange::new(
158 TextSize::of(&self.out),
159 TextSize::of(&self.out) + TextSize::of(&matched_text),
160 ),
161 token.clone(),
162 );
163 self.out.push_str(&matched_text);
164 if needs_parenthesis {
165 self.out.push(')');
166 }
167 } else {
168 // We validated that all placeholder references were valid before we
169 // started, so this shouldn't happen.
170 panic!(
171 "Internal error: replacement referenced unknown placeholder {}",
172 placeholder.ident
173 );
174 }
175 } else {
176 self.out.push_str(token.text());
177 }
178 }
179
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() {
187 return;
188 }
189 self.placeholder_tokens_requiring_parenthesis =
190 self.placeholder_tokens_by_range.values().cloned().collect();
191 self.out.clear();
192 self.render_node(template);
193 }
194 }
195
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);
200 }
201 }
202}
203
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.
207fn 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())
212 {
213 let tokens = receiver.syntax().descendants_with_tokens().filter_map(|node_or_token| {
214 match node_or_token {
215 SyntaxElement::Token(t) => Some(t),
216 _ => None,
217 }
218 });
219 if let Some((only_token,)) = tokens.collect_tuple() {
220 return only_token == *token;
221 }
222 }
223 false
224}
225
226fn 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());
230 }
231 } else if ast::Item::can_cast(kind) {
232 if let Ok(item) = ast::Item::parse(code) {
233 return Some(item.syntax().clone());
234 }
235 }
236 None
237}