diff options
Diffstat (limited to 'crates/ssr/src/resolving.rs')
-rw-r--r-- | crates/ssr/src/resolving.rs | 301 |
1 files changed, 301 insertions, 0 deletions
diff --git a/crates/ssr/src/resolving.rs b/crates/ssr/src/resolving.rs new file mode 100644 index 000000000..4441fb426 --- /dev/null +++ b/crates/ssr/src/resolving.rs | |||
@@ -0,0 +1,301 @@ | |||
1 | //! This module is responsible for resolving paths within rules. | ||
2 | |||
3 | use crate::errors::error; | ||
4 | use crate::{parsing, SsrError}; | ||
5 | use base_db::FilePosition; | ||
6 | use parsing::Placeholder; | ||
7 | use rustc_hash::FxHashMap; | ||
8 | use syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken}; | ||
9 | use test_utils::mark; | ||
10 | |||
11 | pub(crate) struct ResolutionScope<'db> { | ||
12 | scope: hir::SemanticsScope<'db>, | ||
13 | node: SyntaxNode, | ||
14 | } | ||
15 | |||
16 | pub(crate) struct ResolvedRule { | ||
17 | pub(crate) pattern: ResolvedPattern, | ||
18 | pub(crate) template: Option<ResolvedPattern>, | ||
19 | pub(crate) index: usize, | ||
20 | } | ||
21 | |||
22 | pub(crate) struct ResolvedPattern { | ||
23 | pub(crate) placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>, | ||
24 | pub(crate) node: SyntaxNode, | ||
25 | // Paths in `node` that we've resolved. | ||
26 | pub(crate) resolved_paths: FxHashMap<SyntaxNode, ResolvedPath>, | ||
27 | pub(crate) ufcs_function_calls: FxHashMap<SyntaxNode, UfcsCallInfo>, | ||
28 | pub(crate) contains_self: bool, | ||
29 | } | ||
30 | |||
31 | pub(crate) struct ResolvedPath { | ||
32 | pub(crate) resolution: hir::PathResolution, | ||
33 | /// The depth of the ast::Path that was resolved within the pattern. | ||
34 | pub(crate) depth: u32, | ||
35 | } | ||
36 | |||
37 | pub(crate) struct UfcsCallInfo { | ||
38 | pub(crate) call_expr: ast::CallExpr, | ||
39 | pub(crate) function: hir::Function, | ||
40 | pub(crate) qualifier_type: Option<hir::Type>, | ||
41 | } | ||
42 | |||
43 | impl ResolvedRule { | ||
44 | pub(crate) fn new( | ||
45 | rule: parsing::ParsedRule, | ||
46 | resolution_scope: &ResolutionScope, | ||
47 | index: usize, | ||
48 | ) -> Result<ResolvedRule, SsrError> { | ||
49 | let resolver = | ||
50 | Resolver { resolution_scope, placeholders_by_stand_in: rule.placeholders_by_stand_in }; | ||
51 | let resolved_template = if let Some(template) = rule.template { | ||
52 | Some(resolver.resolve_pattern_tree(template)?) | ||
53 | } else { | ||
54 | None | ||
55 | }; | ||
56 | Ok(ResolvedRule { | ||
57 | pattern: resolver.resolve_pattern_tree(rule.pattern)?, | ||
58 | template: resolved_template, | ||
59 | index, | ||
60 | }) | ||
61 | } | ||
62 | |||
63 | pub(crate) fn get_placeholder(&self, token: &SyntaxToken) -> Option<&Placeholder> { | ||
64 | if token.kind() != SyntaxKind::IDENT { | ||
65 | return None; | ||
66 | } | ||
67 | self.pattern.placeholders_by_stand_in.get(token.text()) | ||
68 | } | ||
69 | } | ||
70 | |||
71 | struct Resolver<'a, 'db> { | ||
72 | resolution_scope: &'a ResolutionScope<'db>, | ||
73 | placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>, | ||
74 | } | ||
75 | |||
76 | impl Resolver<'_, '_> { | ||
77 | fn resolve_pattern_tree(&self, pattern: SyntaxNode) -> Result<ResolvedPattern, SsrError> { | ||
78 | use syntax::ast::AstNode; | ||
79 | use syntax::{SyntaxElement, T}; | ||
80 | let mut resolved_paths = FxHashMap::default(); | ||
81 | self.resolve(pattern.clone(), 0, &mut resolved_paths)?; | ||
82 | let ufcs_function_calls = resolved_paths | ||
83 | .iter() | ||
84 | .filter_map(|(path_node, resolved)| { | ||
85 | if let Some(grandparent) = path_node.parent().and_then(|parent| parent.parent()) { | ||
86 | if let Some(call_expr) = ast::CallExpr::cast(grandparent.clone()) { | ||
87 | if let hir::PathResolution::AssocItem(hir::AssocItem::Function(function)) = | ||
88 | resolved.resolution | ||
89 | { | ||
90 | let qualifier_type = self.resolution_scope.qualifier_type(path_node); | ||
91 | return Some(( | ||
92 | grandparent, | ||
93 | UfcsCallInfo { call_expr, function, qualifier_type }, | ||
94 | )); | ||
95 | } | ||
96 | } | ||
97 | } | ||
98 | None | ||
99 | }) | ||
100 | .collect(); | ||
101 | let contains_self = | ||
102 | pattern.descendants_with_tokens().any(|node_or_token| match node_or_token { | ||
103 | SyntaxElement::Token(t) => t.kind() == T![self], | ||
104 | _ => false, | ||
105 | }); | ||
106 | Ok(ResolvedPattern { | ||
107 | node: pattern, | ||
108 | resolved_paths, | ||
109 | placeholders_by_stand_in: self.placeholders_by_stand_in.clone(), | ||
110 | ufcs_function_calls, | ||
111 | contains_self, | ||
112 | }) | ||
113 | } | ||
114 | |||
115 | fn resolve( | ||
116 | &self, | ||
117 | node: SyntaxNode, | ||
118 | depth: u32, | ||
119 | resolved_paths: &mut FxHashMap<SyntaxNode, ResolvedPath>, | ||
120 | ) -> Result<(), SsrError> { | ||
121 | use syntax::ast::AstNode; | ||
122 | if let Some(path) = ast::Path::cast(node.clone()) { | ||
123 | if is_self(&path) { | ||
124 | // Self cannot be resolved like other paths. | ||
125 | return Ok(()); | ||
126 | } | ||
127 | // Check if this is an appropriate place in the path to resolve. If the path is | ||
128 | // something like `a::B::<i32>::c` then we want to resolve `a::B`. If the path contains | ||
129 | // a placeholder. e.g. `a::$b::c` then we want to resolve `a`. | ||
130 | if !path_contains_type_arguments(path.qualifier()) | ||
131 | && !self.path_contains_placeholder(&path) | ||
132 | { | ||
133 | let resolution = self | ||
134 | .resolution_scope | ||
135 | .resolve_path(&path) | ||
136 | .ok_or_else(|| error!("Failed to resolve path `{}`", node.text()))?; | ||
137 | if self.ok_to_use_path_resolution(&resolution) { | ||
138 | resolved_paths.insert(node, ResolvedPath { resolution, depth }); | ||
139 | return Ok(()); | ||
140 | } | ||
141 | } | ||
142 | } | ||
143 | for node in node.children() { | ||
144 | self.resolve(node, depth + 1, resolved_paths)?; | ||
145 | } | ||
146 | Ok(()) | ||
147 | } | ||
148 | |||
149 | /// Returns whether `path` contains a placeholder, but ignores any placeholders within type | ||
150 | /// arguments. | ||
151 | fn path_contains_placeholder(&self, path: &ast::Path) -> bool { | ||
152 | if let Some(segment) = path.segment() { | ||
153 | if let Some(name_ref) = segment.name_ref() { | ||
154 | if self.placeholders_by_stand_in.contains_key(name_ref.text()) { | ||
155 | return true; | ||
156 | } | ||
157 | } | ||
158 | } | ||
159 | if let Some(qualifier) = path.qualifier() { | ||
160 | return self.path_contains_placeholder(&qualifier); | ||
161 | } | ||
162 | false | ||
163 | } | ||
164 | |||
165 | fn ok_to_use_path_resolution(&self, resolution: &hir::PathResolution) -> bool { | ||
166 | match resolution { | ||
167 | hir::PathResolution::AssocItem(hir::AssocItem::Function(function)) => { | ||
168 | if function.has_self_param(self.resolution_scope.scope.db) { | ||
169 | // If we don't use this path resolution, then we won't be able to match method | ||
170 | // calls. e.g. `Foo::bar($s)` should match `x.bar()`. | ||
171 | true | ||
172 | } else { | ||
173 | mark::hit!(replace_associated_trait_default_function_call); | ||
174 | false | ||
175 | } | ||
176 | } | ||
177 | hir::PathResolution::AssocItem(_) => { | ||
178 | // Not a function. Could be a constant or an associated type. | ||
179 | mark::hit!(replace_associated_trait_constant); | ||
180 | false | ||
181 | } | ||
182 | _ => true, | ||
183 | } | ||
184 | } | ||
185 | } | ||
186 | |||
187 | impl<'db> ResolutionScope<'db> { | ||
188 | pub(crate) fn new( | ||
189 | sema: &hir::Semantics<'db, ide_db::RootDatabase>, | ||
190 | resolve_context: FilePosition, | ||
191 | ) -> ResolutionScope<'db> { | ||
192 | use syntax::ast::AstNode; | ||
193 | let file = sema.parse(resolve_context.file_id); | ||
194 | // Find a node at the requested position, falling back to the whole file. | ||
195 | let node = file | ||
196 | .syntax() | ||
197 | .token_at_offset(resolve_context.offset) | ||
198 | .left_biased() | ||
199 | .map(|token| token.parent()) | ||
200 | .unwrap_or_else(|| file.syntax().clone()); | ||
201 | let node = pick_node_for_resolution(node); | ||
202 | let scope = sema.scope(&node); | ||
203 | ResolutionScope { scope, node } | ||
204 | } | ||
205 | |||
206 | /// Returns the function in which SSR was invoked, if any. | ||
207 | pub(crate) fn current_function(&self) -> Option<SyntaxNode> { | ||
208 | self.node.ancestors().find(|node| node.kind() == SyntaxKind::FN).map(|node| node.clone()) | ||
209 | } | ||
210 | |||
211 | fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution> { | ||
212 | // First try resolving the whole path. This will work for things like | ||
213 | // `std::collections::HashMap`, but will fail for things like | ||
214 | // `std::collections::HashMap::new`. | ||
215 | if let Some(resolution) = self.scope.resolve_hypothetical(&path) { | ||
216 | return Some(resolution); | ||
217 | } | ||
218 | // Resolution failed, try resolving the qualifier (e.g. `std::collections::HashMap` and if | ||
219 | // that succeeds, then iterate through the candidates on the resolved type with the provided | ||
220 | // name. | ||
221 | let resolved_qualifier = self.scope.resolve_hypothetical(&path.qualifier()?)?; | ||
222 | if let hir::PathResolution::Def(hir::ModuleDef::Adt(adt)) = resolved_qualifier { | ||
223 | let name = path.segment()?.name_ref()?; | ||
224 | adt.ty(self.scope.db).iterate_path_candidates( | ||
225 | self.scope.db, | ||
226 | self.scope.module()?.krate(), | ||
227 | &self.scope.traits_in_scope(), | ||
228 | None, | ||
229 | |_ty, assoc_item| { | ||
230 | let item_name = assoc_item.name(self.scope.db)?; | ||
231 | if item_name.to_string().as_str() == name.text().as_str() { | ||
232 | Some(hir::PathResolution::AssocItem(assoc_item)) | ||
233 | } else { | ||
234 | None | ||
235 | } | ||
236 | }, | ||
237 | ) | ||
238 | } else { | ||
239 | None | ||
240 | } | ||
241 | } | ||
242 | |||
243 | fn qualifier_type(&self, path: &SyntaxNode) -> Option<hir::Type> { | ||
244 | use syntax::ast::AstNode; | ||
245 | if let Some(path) = ast::Path::cast(path.clone()) { | ||
246 | if let Some(qualifier) = path.qualifier() { | ||
247 | if let Some(resolved_qualifier) = self.resolve_path(&qualifier) { | ||
248 | if let hir::PathResolution::Def(hir::ModuleDef::Adt(adt)) = resolved_qualifier { | ||
249 | return Some(adt.ty(self.scope.db)); | ||
250 | } | ||
251 | } | ||
252 | } | ||
253 | } | ||
254 | None | ||
255 | } | ||
256 | } | ||
257 | |||
258 | fn is_self(path: &ast::Path) -> bool { | ||
259 | path.segment().map(|segment| segment.self_token().is_some()).unwrap_or(false) | ||
260 | } | ||
261 | |||
262 | /// Returns a suitable node for resolving paths in the current scope. If we create a scope based on | ||
263 | /// a statement node, then we can't resolve local variables that were defined in the current scope | ||
264 | /// (only in parent scopes). So we find another node, ideally a child of the statement where local | ||
265 | /// variable resolution is permitted. | ||
266 | fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode { | ||
267 | match node.kind() { | ||
268 | SyntaxKind::EXPR_STMT => { | ||
269 | if let Some(n) = node.first_child() { | ||
270 | mark::hit!(cursor_after_semicolon); | ||
271 | return n; | ||
272 | } | ||
273 | } | ||
274 | SyntaxKind::LET_STMT | SyntaxKind::IDENT_PAT => { | ||
275 | if let Some(next) = node.next_sibling() { | ||
276 | return pick_node_for_resolution(next); | ||
277 | } | ||
278 | } | ||
279 | SyntaxKind::NAME => { | ||
280 | if let Some(parent) = node.parent() { | ||
281 | return pick_node_for_resolution(parent); | ||
282 | } | ||
283 | } | ||
284 | _ => {} | ||
285 | } | ||
286 | node | ||
287 | } | ||
288 | |||
289 | /// Returns whether `path` or any of its qualifiers contains type arguments. | ||
290 | fn path_contains_type_arguments(path: Option<ast::Path>) -> bool { | ||
291 | if let Some(path) = path { | ||
292 | if let Some(segment) = path.segment() { | ||
293 | if segment.generic_arg_list().is_some() { | ||
294 | mark::hit!(type_arguments_within_path); | ||
295 | return true; | ||
296 | } | ||
297 | } | ||
298 | return path_contains_type_arguments(path.qualifier()); | ||
299 | } | ||
300 | false | ||
301 | } | ||