ide_ssr/
resolving.rs

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