diff options
Diffstat (limited to 'crates/ra_ssr/src/resolving.rs')
-rw-r--r-- | crates/ra_ssr/src/resolving.rs | 228 |
1 files changed, 228 insertions, 0 deletions
diff --git a/crates/ra_ssr/src/resolving.rs b/crates/ra_ssr/src/resolving.rs new file mode 100644 index 000000000..78d456546 --- /dev/null +++ b/crates/ra_ssr/src/resolving.rs | |||
@@ -0,0 +1,228 @@ | |||
1 | //! This module is responsible for resolving paths within rules. | ||
2 | |||
3 | use crate::errors::error; | ||
4 | use crate::{parsing, SsrError}; | ||
5 | use parsing::Placeholder; | ||
6 | use ra_db::FilePosition; | ||
7 | use ra_syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken}; | ||
8 | use rustc_hash::{FxHashMap, FxHashSet}; | ||
9 | use test_utils::mark; | ||
10 | |||
11 | pub(crate) struct ResolutionScope<'db> { | ||
12 | scope: hir::SemanticsScope<'db>, | ||
13 | hygiene: hir::Hygiene, | ||
14 | } | ||
15 | |||
16 | pub(crate) struct ResolvedRule { | ||
17 | pub(crate) pattern: ResolvedPattern, | ||
18 | pub(crate) template: Option<ResolvedPattern>, | ||
19 | pub(crate) index: usize, | ||
20 | } | ||
21 | |||
22 | pub(crate) struct ResolvedPattern { | ||
23 | pub(crate) placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>, | ||
24 | pub(crate) node: SyntaxNode, | ||
25 | // Paths in `node` that we've resolved. | ||
26 | pub(crate) resolved_paths: FxHashMap<SyntaxNode, ResolvedPath>, | ||
27 | pub(crate) ufcs_function_calls: FxHashMap<SyntaxNode, hir::Function>, | ||
28 | } | ||
29 | |||
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, | ||
34 | } | ||
35 | |||
36 | impl ResolvedRule { | ||
37 | pub(crate) fn new( | ||
38 | rule: parsing::ParsedRule, | ||
39 | resolution_scope: &ResolutionScope, | ||
40 | index: usize, | ||
41 | ) -> Result<ResolvedRule, SsrError> { | ||
42 | let resolver = | ||
43 | Resolver { resolution_scope, placeholders_by_stand_in: rule.placeholders_by_stand_in }; | ||
44 | let resolved_template = if let Some(template) = rule.template { | ||
45 | Some(resolver.resolve_pattern_tree(template)?) | ||
46 | } else { | ||
47 | None | ||
48 | }; | ||
49 | Ok(ResolvedRule { | ||
50 | pattern: resolver.resolve_pattern_tree(rule.pattern)?, | ||
51 | template: resolved_template, | ||
52 | index, | ||
53 | }) | ||
54 | } | ||
55 | |||
56 | pub(crate) fn get_placeholder(&self, token: &SyntaxToken) -> Option<&Placeholder> { | ||
57 | if token.kind() != SyntaxKind::IDENT { | ||
58 | return None; | ||
59 | } | ||
60 | self.pattern.placeholders_by_stand_in.get(token.text()) | ||
61 | } | ||
62 | } | ||
63 | |||
64 | struct Resolver<'a, 'db> { | ||
65 | resolution_scope: &'a ResolutionScope<'db>, | ||
66 | placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>, | ||
67 | } | ||
68 | |||
69 | impl Resolver<'_, '_> { | ||
70 | fn resolve_pattern_tree(&self, pattern: SyntaxNode) -> Result<ResolvedPattern, SsrError> { | ||
71 | let mut resolved_paths = FxHashMap::default(); | ||
72 | self.resolve(pattern.clone(), 0, &mut resolved_paths)?; | ||
73 | let ufcs_function_calls = resolved_paths | ||
74 | .iter() | ||
75 | .filter_map(|(path_node, resolved)| { | ||
76 | if let Some(grandparent) = path_node.parent().and_then(|parent| parent.parent()) { | ||
77 | if grandparent.kind() == SyntaxKind::CALL_EXPR { | ||
78 | if let hir::PathResolution::AssocItem(hir::AssocItem::Function(function)) = | ||
79 | &resolved.resolution | ||
80 | { | ||
81 | return Some((grandparent, *function)); | ||
82 | } | ||
83 | } | ||
84 | } | ||
85 | None | ||
86 | }) | ||
87 | .collect(); | ||
88 | Ok(ResolvedPattern { | ||
89 | node: pattern, | ||
90 | resolved_paths, | ||
91 | placeholders_by_stand_in: self.placeholders_by_stand_in.clone(), | ||
92 | ufcs_function_calls, | ||
93 | }) | ||
94 | } | ||
95 | |||
96 | fn resolve( | ||
97 | &self, | ||
98 | node: SyntaxNode, | ||
99 | depth: u32, | ||
100 | resolved_paths: &mut FxHashMap<SyntaxNode, ResolvedPath>, | ||
101 | ) -> Result<(), SsrError> { | ||
102 | use ra_syntax::ast::AstNode; | ||
103 | if let Some(path) = ast::Path::cast(node.clone()) { | ||
104 | // Check if this is an appropriate place in the path to resolve. If the path is | ||
105 | // something like `a::B::<i32>::c` then we want to resolve `a::B`. If the path contains | ||
106 | // a placeholder. e.g. `a::$b::c` then we want to resolve `a`. | ||
107 | if !path_contains_type_arguments(path.qualifier()) | ||
108 | && !self.path_contains_placeholder(&path) | ||
109 | { | ||
110 | let resolution = self | ||
111 | .resolution_scope | ||
112 | .resolve_path(&path) | ||
113 | .ok_or_else(|| error!("Failed to resolve path `{}`", node.text()))?; | ||
114 | resolved_paths.insert(node, ResolvedPath { resolution, depth }); | ||
115 | return Ok(()); | ||
116 | } | ||
117 | } | ||
118 | for node in node.children() { | ||
119 | self.resolve(node, depth + 1, resolved_paths)?; | ||
120 | } | ||
121 | Ok(()) | ||
122 | } | ||
123 | |||
124 | /// Returns whether `path` contains a placeholder, but ignores any placeholders within type | ||
125 | /// arguments. | ||
126 | fn path_contains_placeholder(&self, path: &ast::Path) -> bool { | ||
127 | if let Some(segment) = path.segment() { | ||
128 | if let Some(name_ref) = segment.name_ref() { | ||
129 | if self.placeholders_by_stand_in.contains_key(name_ref.text()) { | ||
130 | return true; | ||
131 | } | ||
132 | } | ||
133 | } | ||
134 | if let Some(qualifier) = path.qualifier() { | ||
135 | return self.path_contains_placeholder(&qualifier); | ||
136 | } | ||
137 | false | ||
138 | } | ||
139 | } | ||
140 | |||
141 | impl<'db> ResolutionScope<'db> { | ||
142 | pub(crate) fn new( | ||
143 | sema: &hir::Semantics<'db, ra_ide_db::RootDatabase>, | ||
144 | resolve_context: FilePosition, | ||
145 | ) -> ResolutionScope<'db> { | ||
146 | use ra_syntax::ast::AstNode; | ||
147 | let file = sema.parse(resolve_context.file_id); | ||
148 | // Find a node at the requested position, falling back to the whole file. | ||
149 | let node = file | ||
150 | .syntax() | ||
151 | .token_at_offset(resolve_context.offset) | ||
152 | .left_biased() | ||
153 | .map(|token| token.parent()) | ||
154 | .unwrap_or_else(|| file.syntax().clone()); | ||
155 | let node = pick_node_for_resolution(node); | ||
156 | let scope = sema.scope(&node); | ||
157 | ResolutionScope { | ||
158 | scope, | ||
159 | hygiene: hir::Hygiene::new(sema.db, resolve_context.file_id.into()), | ||
160 | } | ||
161 | } | ||
162 | |||
163 | fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution> { | ||
164 | let hir_path = hir::Path::from_src(path.clone(), &self.hygiene)?; | ||
165 | // First try resolving the whole path. This will work for things like | ||
166 | // `std::collections::HashMap`, but will fail for things like | ||
167 | // `std::collections::HashMap::new`. | ||
168 | if let Some(resolution) = self.scope.resolve_hir_path(&hir_path) { | ||
169 | return Some(resolution); | ||
170 | } | ||
171 | // Resolution failed, try resolving the qualifier (e.g. `std::collections::HashMap` and if | ||
172 | // that succeeds, then iterate through the candidates on the resolved type with the provided | ||
173 | // name. | ||
174 | let resolved_qualifier = self.scope.resolve_hir_path_qualifier(&hir_path.qualifier()?)?; | ||
175 | if let hir::PathResolution::Def(hir::ModuleDef::Adt(adt)) = resolved_qualifier { | ||
176 | adt.ty(self.scope.db).iterate_path_candidates( | ||
177 | self.scope.db, | ||
178 | self.scope.module()?.krate(), | ||
179 | &FxHashSet::default(), | ||
180 | Some(hir_path.segments().last()?.name), | ||
181 | |_ty, assoc_item| Some(hir::PathResolution::AssocItem(assoc_item)), | ||
182 | ) | ||
183 | } else { | ||
184 | None | ||
185 | } | ||
186 | } | ||
187 | } | ||
188 | |||
189 | /// Returns a suitable node for resolving paths in the current scope. If we create a scope based on | ||
190 | /// a statement node, then we can't resolve local variables that were defined in the current scope | ||
191 | /// (only in parent scopes). So we find another node, ideally a child of the statement where local | ||
192 | /// variable resolution is permitted. | ||
193 | fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode { | ||
194 | match node.kind() { | ||
195 | SyntaxKind::EXPR_STMT => { | ||
196 | if let Some(n) = node.first_child() { | ||
197 | mark::hit!(cursor_after_semicolon); | ||
198 | return n; | ||
199 | } | ||
200 | } | ||
201 | SyntaxKind::LET_STMT | SyntaxKind::BIND_PAT => { | ||
202 | if let Some(next) = node.next_sibling() { | ||
203 | return pick_node_for_resolution(next); | ||
204 | } | ||
205 | } | ||
206 | SyntaxKind::NAME => { | ||
207 | if let Some(parent) = node.parent() { | ||
208 | return pick_node_for_resolution(parent); | ||
209 | } | ||
210 | } | ||
211 | _ => {} | ||
212 | } | ||
213 | node | ||
214 | } | ||
215 | |||
216 | /// Returns whether `path` or any of its qualifiers contains type arguments. | ||
217 | fn path_contains_type_arguments(path: Option<ast::Path>) -> bool { | ||
218 | if let Some(path) = path { | ||
219 | if let Some(segment) = path.segment() { | ||
220 | if segment.type_arg_list().is_some() { | ||
221 | mark::hit!(type_arguments_within_path); | ||
222 | return true; | ||
223 | } | ||
224 | } | ||
225 | return path_contains_type_arguments(path.qualifier()); | ||
226 | } | ||
227 | false | ||
228 | } | ||