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