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 = if let Some(template) = rule.template {
51 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::AssocItem(hir::AssocItem::Function(function)) =
89 let qualifier_type = self.resolution_scope.qualifier_type(path_node);
92 UfcsCallInfo { call_expr, function, qualifier_type },
101 pattern.descendants_with_tokens().any(|node_or_token| match node_or_token {
102 SyntaxElement::Token(t) => t.kind() == T![self],
108 placeholders_by_stand_in: self.placeholders_by_stand_in.clone(),
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()) {
123 // Self cannot be resolved like other paths.
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)
132 let resolution = self
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 });
142 for node in node.children() {
143 self.resolve(node, depth + 1, resolved_paths)?;
148 /// Returns whether `path` contains a placeholder, but ignores any placeholders within type
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()) {
158 if let Some(qualifier) = path.qualifier() {
159 return self.path_contains_placeholder(&qualifier);
164 fn ok_to_use_path_resolution(&self, resolution: &hir::PathResolution) -> bool {
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()`.
172 cov_mark::hit!(replace_associated_trait_default_function_call);
176 hir::PathResolution::AssocItem(_) => {
177 // Not a function. Could be a constant or an associated type.
178 cov_mark::hit!(replace_associated_trait_constant);
186 impl<'db> ResolutionScope<'db> {
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.
196 .token_at_offset(resolve_context.offset)
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 }
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)
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);
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
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(
225 self.scope.module()?.krate(),
226 &self.scope.traits_in_scope(),
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))
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)
249 return Some(adt.ty(self.scope.db));
257 fn is_self(path: &ast::Path) -> bool {
258 path.segment().map(|segment| segment.self_token().is_some()).unwrap_or(false)
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 {
267 SyntaxKind::EXPR_STMT => {
268 if let Some(n) = node.first_child() {
269 cov_mark::hit!(cursor_after_semicolon);
273 SyntaxKind::LET_STMT | SyntaxKind::IDENT_PAT => {
274 if let Some(next) = node.next_sibling() {
275 return pick_node_for_resolution(next);
278 SyntaxKind::NAME => {
279 if let Some(parent) = node.parent() {
280 return pick_node_for_resolution(parent);
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);
297 return path_contains_type_arguments(path.qualifier());