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