1 //! This module is responsible for resolving paths within rules.
3 use crate::errors::error;
4 use crate::{parsing, SsrError};
6 use ide_db::base_db::FilePosition;
7 use parsing::Placeholder;
8 use rustc_hash::FxHashMap;
9 use syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken};
11 pub(crate) struct ResolutionScope<'db> {
12 scope: hir::SemanticsScope<'db>,
16 pub(crate) struct ResolvedRule {
17 pub(crate) pattern: ResolvedPattern,
18 pub(crate) template: Option<ResolvedPattern>,
19 pub(crate) index: usize,
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,
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,
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>,
45 rule: parsing::ParsedRule,
46 resolution_scope: &ResolutionScope,
48 ) -> Result<ResolvedRule, SsrError> {
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)?),
56 pattern: resolver.resolve_pattern_tree(rule.pattern)?,
57 template: resolved_template,
62 pub(crate) fn get_placeholder(&self, token: &SyntaxToken) -> Option<&Placeholder> {
63 if token.kind() != SyntaxKind::IDENT {
66 self.pattern.placeholders_by_stand_in.get(token.text())
70 struct Resolver<'a, 'db> {
71 resolution_scope: &'a ResolutionScope<'db>,
72 placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>,
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
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)) =
89 if function.as_assoc_item(self.resolution_scope.scope.db).is_some() {
91 self.resolution_scope.qualifier_type(path_node);
94 UfcsCallInfo { call_expr, function, qualifier_type },
104 pattern.descendants_with_tokens().any(|node_or_token| match node_or_token {
105 SyntaxElement::Token(t) => t.kind() == T![self],
111 placeholders_by_stand_in: self.placeholders_by_stand_in.clone(),
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()) {
126 // Self cannot be resolved like other paths.
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)
135 let resolution = self
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 });
145 for node in node.children() {
146 self.resolve(node, depth + 1, resolved_paths)?;
151 /// Returns whether `path` contains a placeholder, but ignores any placeholders within type
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()) {
161 if let Some(qualifier) = path.qualifier() {
162 return self.path_contains_placeholder(&qualifier);
167 fn ok_to_use_path_resolution(&self, resolution: &hir::PathResolution) -> bool {
169 hir::PathResolution::Def(hir::ModuleDef::Function(function))
170 if function.as_assoc_item(self.resolution_scope.scope.db).is_some() =>
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()`.
177 cov_mark::hit!(replace_associated_trait_default_function_call);
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);
193 impl<'db> ResolutionScope<'db> {
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.
203 .token_at_offset(resolve_context.offset)
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 })
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)
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);
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
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(
234 &self.scope.visible_traits(),
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()))
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)
258 return Some(adt.ty(self.scope.db));
266 fn is_self(path: &ast::Path) -> bool {
267 path.segment().map(|segment| segment.self_token().is_some()).unwrap_or(false)
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 {
276 SyntaxKind::EXPR_STMT => {
277 if let Some(n) = node.first_child() {
278 cov_mark::hit!(cursor_after_semicolon);
282 SyntaxKind::LET_STMT | SyntaxKind::IDENT_PAT => {
283 if let Some(next) = node.next_sibling() {
284 return pick_node_for_resolution(next);
287 SyntaxKind::NAME => {
288 if let Some(parent) = node.parent() {
289 return pick_node_for_resolution(parent);
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);
306 return path_contains_type_arguments(path.qualifier());