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