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