1 //! This module is responsible for resolving paths within rules.
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};
10 pub(crate) struct ResolutionScope<'db> {
11 scope: hir::SemanticsScope<'db>,
15 pub(crate) struct ResolvedRule {
16 pub(crate) pattern: ResolvedPattern,
17 pub(crate) template: Option<ResolvedPattern>,
18 pub(crate) index: usize,
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,
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,
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>,
44 rule: parsing::ParsedRule,
45 resolution_scope: &ResolutionScope,
47 ) -> Result<ResolvedRule, SsrError> {
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)?),
55 pattern: resolver.resolve_pattern_tree(rule.pattern)?,
56 template: resolved_template,
61 pub(crate) fn get_placeholder(&self, token: &SyntaxToken) -> Option<&Placeholder> {
62 if token.kind() != SyntaxKind::IDENT {
65 self.pattern.placeholders_by_stand_in.get(token.text())
69 struct Resolver<'a, 'db> {
70 resolution_scope: &'a ResolutionScope<'db>,
71 placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>,
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
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)) =
88 let qualifier_type = self.resolution_scope.qualifier_type(path_node);
91 UfcsCallInfo { call_expr, function, qualifier_type },
100 pattern.descendants_with_tokens().any(|node_or_token| match node_or_token {
101 SyntaxElement::Token(t) => t.kind() == T![self],
107 placeholders_by_stand_in: self.placeholders_by_stand_in.clone(),
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()) {
122 // Self cannot be resolved like other paths.
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)
131 let resolution = self
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 });
141 for node in node.children() {
142 self.resolve(node, depth + 1, resolved_paths)?;
147 /// Returns whether `path` contains a placeholder, but ignores any placeholders within type
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()) {
157 if let Some(qualifier) = path.qualifier() {
158 return self.path_contains_placeholder(&qualifier);
163 fn ok_to_use_path_resolution(&self, resolution: &hir::PathResolution) -> bool {
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()`.
171 cov_mark::hit!(replace_associated_trait_default_function_call);
175 hir::PathResolution::AssocItem(_) => {
176 // Not a function. Could be a constant or an associated type.
177 cov_mark::hit!(replace_associated_trait_constant);
185 impl<'db> ResolutionScope<'db> {
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.
195 .token_at_offset(resolve_context.offset)
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 }
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)
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);
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
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 let module = self.scope.module()?;
223 adt.ty(self.scope.db).iterate_path_candidates(
226 &self.scope.visible_traits(),
230 let item_name = assoc_item.name(self.scope.db)?;
231 if item_name.to_smol_str().as_str() == name.text() {
232 Some(hir::PathResolution::AssocItem(assoc_item))
243 fn qualifier_type(&self, path: &SyntaxNode) -> Option<hir::Type> {
244 use syntax::ast::AstNode;
245 if let Some(path) = ast::Path::cast(path.clone()) {
246 if let Some(qualifier) = path.qualifier() {
247 if let Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) =
248 self.resolve_path(&qualifier)
250 return Some(adt.ty(self.scope.db));
258 fn is_self(path: &ast::Path) -> bool {
259 path.segment().map(|segment| segment.self_token().is_some()).unwrap_or(false)
262 /// Returns a suitable node for resolving paths in the current scope. If we create a scope based on
263 /// a statement node, then we can't resolve local variables that were defined in the current scope
264 /// (only in parent scopes). So we find another node, ideally a child of the statement where local
265 /// variable resolution is permitted.
266 fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode {
268 SyntaxKind::EXPR_STMT => {
269 if let Some(n) = node.first_child() {
270 cov_mark::hit!(cursor_after_semicolon);
274 SyntaxKind::LET_STMT | SyntaxKind::IDENT_PAT => {
275 if let Some(next) = node.next_sibling() {
276 return pick_node_for_resolution(next);
279 SyntaxKind::NAME => {
280 if let Some(parent) = node.parent() {
281 return pick_node_for_resolution(parent);
289 /// Returns whether `path` or any of its qualifiers contains type arguments.
290 fn path_contains_type_arguments(path: Option<ast::Path>) -> bool {
291 if let Some(path) = path {
292 if let Some(segment) = path.segment() {
293 if segment.generic_arg_list().is_some() {
294 cov_mark::hit!(type_arguments_within_path);
298 return path_contains_type_arguments(path.qualifier());