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