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.rs251
1 files changed, 0 insertions, 251 deletions
diff --git a/crates/ra_ssr/src/resolving.rs b/crates/ra_ssr/src/resolving.rs
deleted file mode 100644
index df60048eb..000000000
--- a/crates/ra_ssr/src/resolving.rs
+++ /dev/null
@@ -1,251 +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, FxHashSet};
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 resolved_paths.insert(node, ResolvedPath { resolution, depth });
128 return Ok(());
129 }
130 }
131 for node in node.children() {
132 self.resolve(node, depth + 1, resolved_paths)?;
133 }
134 Ok(())
135 }
136
137 /// Returns whether `path` contains a placeholder, but ignores any placeholders within type
138 /// arguments.
139 fn path_contains_placeholder(&self, path: &ast::Path) -> bool {
140 if let Some(segment) = path.segment() {
141 if let Some(name_ref) = segment.name_ref() {
142 if self.placeholders_by_stand_in.contains_key(name_ref.text()) {
143 return true;
144 }
145 }
146 }
147 if let Some(qualifier) = path.qualifier() {
148 return self.path_contains_placeholder(&qualifier);
149 }
150 false
151 }
152}
153
154impl<'db> ResolutionScope<'db> {
155 pub(crate) fn new(
156 sema: &hir::Semantics<'db, ra_ide_db::RootDatabase>,
157 resolve_context: FilePosition,
158 ) -> ResolutionScope<'db> {
159 use ra_syntax::ast::AstNode;
160 let file = sema.parse(resolve_context.file_id);
161 // Find a node at the requested position, falling back to the whole file.
162 let node = file
163 .syntax()
164 .token_at_offset(resolve_context.offset)
165 .left_biased()
166 .map(|token| token.parent())
167 .unwrap_or_else(|| file.syntax().clone());
168 let node = pick_node_for_resolution(node);
169 let scope = sema.scope(&node);
170 ResolutionScope {
171 scope,
172 hygiene: hir::Hygiene::new(sema.db, resolve_context.file_id.into()),
173 node,
174 }
175 }
176
177 /// Returns the function in which SSR was invoked, if any.
178 pub(crate) fn current_function(&self) -> Option<SyntaxNode> {
179 self.node.ancestors().find(|node| node.kind() == SyntaxKind::FN).map(|node| node.clone())
180 }
181
182 fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution> {
183 let hir_path = hir::Path::from_src(path.clone(), &self.hygiene)?;
184 // First try resolving the whole path. This will work for things like
185 // `std::collections::HashMap`, but will fail for things like
186 // `std::collections::HashMap::new`.
187 if let Some(resolution) = self.scope.resolve_hir_path(&hir_path) {
188 return Some(resolution);
189 }
190 // Resolution failed, try resolving the qualifier (e.g. `std::collections::HashMap` and if
191 // that succeeds, then iterate through the candidates on the resolved type with the provided
192 // name.
193 let resolved_qualifier = self.scope.resolve_hir_path_qualifier(&hir_path.qualifier()?)?;
194 if let hir::PathResolution::Def(hir::ModuleDef::Adt(adt)) = resolved_qualifier {
195 adt.ty(self.scope.db).iterate_path_candidates(
196 self.scope.db,
197 self.scope.module()?.krate(),
198 &FxHashSet::default(),
199 Some(hir_path.segments().last()?.name),
200 |_ty, assoc_item| Some(hir::PathResolution::AssocItem(assoc_item)),
201 )
202 } else {
203 None
204 }
205 }
206}
207
208fn is_self(path: &ast::Path) -> bool {
209 path.segment().map(|segment| segment.self_token().is_some()).unwrap_or(false)
210}
211
212/// Returns a suitable node for resolving paths in the current scope. If we create a scope based on
213/// a statement node, then we can't resolve local variables that were defined in the current scope
214/// (only in parent scopes). So we find another node, ideally a child of the statement where local
215/// variable resolution is permitted.
216fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode {
217 match node.kind() {
218 SyntaxKind::EXPR_STMT => {
219 if let Some(n) = node.first_child() {
220 mark::hit!(cursor_after_semicolon);
221 return n;
222 }
223 }
224 SyntaxKind::LET_STMT | SyntaxKind::IDENT_PAT => {
225 if let Some(next) = node.next_sibling() {
226 return pick_node_for_resolution(next);
227 }
228 }
229 SyntaxKind::NAME => {
230 if let Some(parent) = node.parent() {
231 return pick_node_for_resolution(parent);
232 }
233 }
234 _ => {}
235 }
236 node
237}
238
239/// Returns whether `path` or any of its qualifiers contains type arguments.
240fn path_contains_type_arguments(path: Option<ast::Path>) -> bool {
241 if let Some(path) = path {
242 if let Some(segment) = path.segment() {
243 if segment.generic_arg_list().is_some() {
244 mark::hit!(type_arguments_within_path);
245 return true;
246 }
247 }
248 return path_contains_type_arguments(path.qualifier());
249 }
250 false
251}