diff options
Diffstat (limited to 'crates/ra_hir/src/source_analyzer.rs')
-rw-r--r-- | crates/ra_hir/src/source_analyzer.rs | 450 |
1 files changed, 450 insertions, 0 deletions
diff --git a/crates/ra_hir/src/source_analyzer.rs b/crates/ra_hir/src/source_analyzer.rs new file mode 100644 index 000000000..4f8fc9602 --- /dev/null +++ b/crates/ra_hir/src/source_analyzer.rs | |||
@@ -0,0 +1,450 @@ | |||
1 | //! Lookup hir elements using positions in the source code. This is a lossy | ||
2 | //! transformation: in general, a single source might correspond to several | ||
3 | //! modules, functions, etc, due to macros, cfgs and `#[path=]` attributes on | ||
4 | //! modules. | ||
5 | //! | ||
6 | //! So, this modules should not be used during hir construction, it exists | ||
7 | //! purely for "IDE needs". | ||
8 | use std::sync::Arc; | ||
9 | |||
10 | use either::Either; | ||
11 | use hir_def::{ | ||
12 | body::{ | ||
13 | scope::{ExprScopes, ScopeId}, | ||
14 | BodySourceMap, | ||
15 | }, | ||
16 | expr::{ExprId, PatId}, | ||
17 | resolver::{self, resolver_for_scope, Resolver, TypeNs, ValueNs}, | ||
18 | DefWithBodyId, TraitId, | ||
19 | }; | ||
20 | use hir_expand::{ | ||
21 | hygiene::Hygiene, name::AsName, AstId, HirFileId, InFile, MacroCallId, MacroCallKind, | ||
22 | }; | ||
23 | use hir_ty::{InEnvironment, InferenceResult, TraitEnvironment}; | ||
24 | use ra_syntax::{ | ||
25 | ast::{self, AstNode}, | ||
26 | AstPtr, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextUnit, | ||
27 | }; | ||
28 | use rustc_hash::FxHashSet; | ||
29 | |||
30 | use crate::{ | ||
31 | db::HirDatabase, Adt, Const, DefWithBody, EnumVariant, Function, Local, MacroDef, Name, Path, | ||
32 | ScopeDef, Static, Struct, Trait, Type, TypeAlias, TypeParam, | ||
33 | }; | ||
34 | |||
35 | /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of | ||
36 | /// original source files. It should not be used inside the HIR itself. | ||
37 | #[derive(Debug)] | ||
38 | pub struct SourceAnalyzer { | ||
39 | file_id: HirFileId, | ||
40 | resolver: Resolver, | ||
41 | body_owner: Option<DefWithBody>, | ||
42 | body_source_map: Option<Arc<BodySourceMap>>, | ||
43 | infer: Option<Arc<InferenceResult>>, | ||
44 | scopes: Option<Arc<ExprScopes>>, | ||
45 | } | ||
46 | |||
47 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
48 | pub enum PathResolution { | ||
49 | /// An item | ||
50 | Def(crate::ModuleDef), | ||
51 | /// A local binding (only value namespace) | ||
52 | Local(Local), | ||
53 | /// A generic parameter | ||
54 | TypeParam(TypeParam), | ||
55 | SelfType(crate::ImplBlock), | ||
56 | Macro(MacroDef), | ||
57 | AssocItem(crate::AssocItem), | ||
58 | } | ||
59 | |||
60 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
61 | pub struct ScopeEntryWithSyntax { | ||
62 | pub(crate) name: Name, | ||
63 | pub(crate) ptr: Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>, | ||
64 | } | ||
65 | |||
66 | impl ScopeEntryWithSyntax { | ||
67 | pub fn name(&self) -> &Name { | ||
68 | &self.name | ||
69 | } | ||
70 | |||
71 | pub fn ptr(&self) -> Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>> { | ||
72 | self.ptr | ||
73 | } | ||
74 | } | ||
75 | |||
76 | #[derive(Debug)] | ||
77 | pub struct ReferenceDescriptor { | ||
78 | pub range: TextRange, | ||
79 | pub name: String, | ||
80 | } | ||
81 | |||
82 | #[derive(Debug)] | ||
83 | pub struct Expansion { | ||
84 | macro_call_id: MacroCallId, | ||
85 | } | ||
86 | |||
87 | impl Expansion { | ||
88 | pub fn map_token_down( | ||
89 | &self, | ||
90 | db: &impl HirDatabase, | ||
91 | token: InFile<&SyntaxToken>, | ||
92 | ) -> Option<InFile<SyntaxToken>> { | ||
93 | let exp_info = self.file_id().expansion_info(db)?; | ||
94 | exp_info.map_token_down(token) | ||
95 | } | ||
96 | |||
97 | pub fn file_id(&self) -> HirFileId { | ||
98 | self.macro_call_id.as_file() | ||
99 | } | ||
100 | } | ||
101 | |||
102 | impl SourceAnalyzer { | ||
103 | pub fn new( | ||
104 | db: &impl HirDatabase, | ||
105 | node: InFile<&SyntaxNode>, | ||
106 | offset: Option<TextUnit>, | ||
107 | ) -> SourceAnalyzer { | ||
108 | crate::source_binder::SourceBinder::new(db).analyze(node, offset) | ||
109 | } | ||
110 | |||
111 | pub(crate) fn new_for_body( | ||
112 | db: &impl HirDatabase, | ||
113 | def: DefWithBodyId, | ||
114 | node: InFile<&SyntaxNode>, | ||
115 | offset: Option<TextUnit>, | ||
116 | ) -> SourceAnalyzer { | ||
117 | let (_body, source_map) = db.body_with_source_map(def); | ||
118 | let scopes = db.expr_scopes(def); | ||
119 | let scope = match offset { | ||
120 | None => scope_for(&scopes, &source_map, node), | ||
121 | Some(offset) => scope_for_offset(&scopes, &source_map, node.with_value(offset)), | ||
122 | }; | ||
123 | let resolver = resolver_for_scope(db, def, scope); | ||
124 | SourceAnalyzer { | ||
125 | resolver, | ||
126 | body_owner: Some(def.into()), | ||
127 | body_source_map: Some(source_map), | ||
128 | infer: Some(db.infer(def)), | ||
129 | scopes: Some(scopes), | ||
130 | file_id: node.file_id, | ||
131 | } | ||
132 | } | ||
133 | |||
134 | pub(crate) fn new_for_resolver( | ||
135 | resolver: Resolver, | ||
136 | node: InFile<&SyntaxNode>, | ||
137 | ) -> SourceAnalyzer { | ||
138 | SourceAnalyzer { | ||
139 | resolver, | ||
140 | body_owner: None, | ||
141 | body_source_map: None, | ||
142 | infer: None, | ||
143 | scopes: None, | ||
144 | file_id: node.file_id, | ||
145 | } | ||
146 | } | ||
147 | |||
148 | pub fn module(&self) -> Option<crate::code_model::Module> { | ||
149 | Some(crate::code_model::Module { id: self.resolver.module()? }) | ||
150 | } | ||
151 | |||
152 | fn expr_id(&self, expr: &ast::Expr) -> Option<ExprId> { | ||
153 | let src = InFile { file_id: self.file_id, value: expr }; | ||
154 | self.body_source_map.as_ref()?.node_expr(src) | ||
155 | } | ||
156 | |||
157 | fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> { | ||
158 | let src = InFile { file_id: self.file_id, value: pat }; | ||
159 | self.body_source_map.as_ref()?.node_pat(src) | ||
160 | } | ||
161 | |||
162 | fn expand_expr( | ||
163 | &self, | ||
164 | db: &impl HirDatabase, | ||
165 | expr: InFile<&ast::Expr>, | ||
166 | ) -> Option<InFile<ast::Expr>> { | ||
167 | let macro_call = ast::MacroCall::cast(expr.value.syntax().clone())?; | ||
168 | let macro_file = | ||
169 | self.body_source_map.as_ref()?.node_macro_file(expr.with_value(¯o_call))?; | ||
170 | let expanded = db.parse_or_expand(macro_file)?; | ||
171 | let kind = expanded.kind(); | ||
172 | let expr = InFile::new(macro_file, ast::Expr::cast(expanded)?); | ||
173 | |||
174 | if ast::MacroCall::can_cast(kind) { | ||
175 | self.expand_expr(db, expr.as_ref()) | ||
176 | } else { | ||
177 | Some(expr) | ||
178 | } | ||
179 | } | ||
180 | |||
181 | pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> { | ||
182 | let expr_id = if let Some(expr) = self.expand_expr(db, InFile::new(self.file_id, expr)) { | ||
183 | self.body_source_map.as_ref()?.node_expr(expr.as_ref())? | ||
184 | } else { | ||
185 | self.expr_id(expr)? | ||
186 | }; | ||
187 | |||
188 | let ty = self.infer.as_ref()?[expr_id].clone(); | ||
189 | let environment = TraitEnvironment::lower(db, &self.resolver); | ||
190 | Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } }) | ||
191 | } | ||
192 | |||
193 | pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> { | ||
194 | let pat_id = self.pat_id(pat)?; | ||
195 | let ty = self.infer.as_ref()?[pat_id].clone(); | ||
196 | let environment = TraitEnvironment::lower(db, &self.resolver); | ||
197 | Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } }) | ||
198 | } | ||
199 | |||
200 | pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> { | ||
201 | let expr_id = self.expr_id(&call.clone().into())?; | ||
202 | self.infer.as_ref()?.method_resolution(expr_id).map(Function::from) | ||
203 | } | ||
204 | |||
205 | pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> { | ||
206 | let expr_id = self.expr_id(&field.clone().into())?; | ||
207 | self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into()) | ||
208 | } | ||
209 | |||
210 | pub fn resolve_record_field(&self, field: &ast::RecordField) -> Option<crate::StructField> { | ||
211 | let expr_id = match field.expr() { | ||
212 | Some(it) => self.expr_id(&it)?, | ||
213 | None => { | ||
214 | let src = InFile { file_id: self.file_id, value: field }; | ||
215 | self.body_source_map.as_ref()?.field_init_shorthand_expr(src)? | ||
216 | } | ||
217 | }; | ||
218 | self.infer.as_ref()?.record_field_resolution(expr_id).map(|it| it.into()) | ||
219 | } | ||
220 | |||
221 | pub fn resolve_record_literal(&self, record_lit: &ast::RecordLit) -> Option<crate::VariantDef> { | ||
222 | let expr_id = self.expr_id(&record_lit.clone().into())?; | ||
223 | self.infer.as_ref()?.variant_resolution_for_expr(expr_id).map(|it| it.into()) | ||
224 | } | ||
225 | |||
226 | pub fn resolve_record_pattern(&self, record_pat: &ast::RecordPat) -> Option<crate::VariantDef> { | ||
227 | let pat_id = self.pat_id(&record_pat.clone().into())?; | ||
228 | self.infer.as_ref()?.variant_resolution_for_pat(pat_id).map(|it| it.into()) | ||
229 | } | ||
230 | |||
231 | pub fn resolve_macro_call( | ||
232 | &self, | ||
233 | db: &impl HirDatabase, | ||
234 | macro_call: InFile<&ast::MacroCall>, | ||
235 | ) -> Option<MacroDef> { | ||
236 | let hygiene = Hygiene::new(db, macro_call.file_id); | ||
237 | let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?; | ||
238 | self.resolver.resolve_path_as_macro(db, path.mod_path()).map(|it| it.into()) | ||
239 | } | ||
240 | |||
241 | pub fn resolve_hir_path( | ||
242 | &self, | ||
243 | db: &impl HirDatabase, | ||
244 | path: &crate::Path, | ||
245 | ) -> Option<PathResolution> { | ||
246 | let types = | ||
247 | self.resolver.resolve_path_in_type_ns_fully(db, path.mod_path()).map(|ty| match ty { | ||
248 | TypeNs::SelfType(it) => PathResolution::SelfType(it.into()), | ||
249 | TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }), | ||
250 | TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => { | ||
251 | PathResolution::Def(Adt::from(it).into()) | ||
252 | } | ||
253 | TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()), | ||
254 | TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()), | ||
255 | TypeNs::BuiltinType(it) => PathResolution::Def(it.into()), | ||
256 | TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()), | ||
257 | }); | ||
258 | let values = | ||
259 | self.resolver.resolve_path_in_value_ns_fully(db, path.mod_path()).and_then(|val| { | ||
260 | let res = match val { | ||
261 | ValueNs::LocalBinding(pat_id) => { | ||
262 | let var = Local { parent: self.body_owner?, pat_id }; | ||
263 | PathResolution::Local(var) | ||
264 | } | ||
265 | ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()), | ||
266 | ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()), | ||
267 | ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()), | ||
268 | ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()), | ||
269 | ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()), | ||
270 | }; | ||
271 | Some(res) | ||
272 | }); | ||
273 | |||
274 | let items = self | ||
275 | .resolver | ||
276 | .resolve_module_path_in_items(db, path.mod_path()) | ||
277 | .take_types() | ||
278 | .map(|it| PathResolution::Def(it.into())); | ||
279 | types.or(values).or(items).or_else(|| { | ||
280 | self.resolver | ||
281 | .resolve_path_as_macro(db, path.mod_path()) | ||
282 | .map(|def| PathResolution::Macro(def.into())) | ||
283 | }) | ||
284 | } | ||
285 | |||
286 | pub fn resolve_path(&self, db: &impl HirDatabase, path: &ast::Path) -> Option<PathResolution> { | ||
287 | if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) { | ||
288 | let expr_id = self.expr_id(&path_expr.into())?; | ||
289 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) { | ||
290 | return Some(PathResolution::AssocItem(assoc.into())); | ||
291 | } | ||
292 | } | ||
293 | if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) { | ||
294 | let pat_id = self.pat_id(&path_pat.into())?; | ||
295 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) { | ||
296 | return Some(PathResolution::AssocItem(assoc.into())); | ||
297 | } | ||
298 | } | ||
299 | // This must be a normal source file rather than macro file. | ||
300 | let hir_path = crate::Path::from_ast(path.clone())?; | ||
301 | self.resolve_hir_path(db, &hir_path) | ||
302 | } | ||
303 | |||
304 | fn resolve_local_name(&self, name_ref: &ast::NameRef) -> Option<ScopeEntryWithSyntax> { | ||
305 | let name = name_ref.as_name(); | ||
306 | let source_map = self.body_source_map.as_ref()?; | ||
307 | let scopes = self.scopes.as_ref()?; | ||
308 | let scope = scope_for(scopes, source_map, InFile::new(self.file_id, name_ref.syntax()))?; | ||
309 | let entry = scopes.resolve_name_in_scope(scope, &name)?; | ||
310 | Some(ScopeEntryWithSyntax { | ||
311 | name: entry.name().clone(), | ||
312 | ptr: source_map.pat_syntax(entry.pat())?.value, | ||
313 | }) | ||
314 | } | ||
315 | |||
316 | pub fn process_all_names(&self, db: &impl HirDatabase, f: &mut dyn FnMut(Name, ScopeDef)) { | ||
317 | self.resolver.process_all_names(db, &mut |name, def| { | ||
318 | let def = match def { | ||
319 | resolver::ScopeDef::PerNs(it) => it.into(), | ||
320 | resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()), | ||
321 | resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()), | ||
322 | resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }), | ||
323 | resolver::ScopeDef::Local(pat_id) => { | ||
324 | let parent = self.resolver.body_owner().unwrap().into(); | ||
325 | ScopeDef::Local(Local { parent, pat_id }) | ||
326 | } | ||
327 | }; | ||
328 | f(name, def) | ||
329 | }) | ||
330 | } | ||
331 | |||
332 | // FIXME: we only use this in `inline_local_variable` assist, ideally, we | ||
333 | // should switch to general reference search infra there. | ||
334 | pub fn find_all_refs(&self, pat: &ast::BindPat) -> Vec<ReferenceDescriptor> { | ||
335 | let fn_def = pat.syntax().ancestors().find_map(ast::FnDef::cast).unwrap(); | ||
336 | let ptr = Either::Left(AstPtr::new(&ast::Pat::from(pat.clone()))); | ||
337 | fn_def | ||
338 | .syntax() | ||
339 | .descendants() | ||
340 | .filter_map(ast::NameRef::cast) | ||
341 | .filter(|name_ref| match self.resolve_local_name(&name_ref) { | ||
342 | None => false, | ||
343 | Some(entry) => entry.ptr() == ptr, | ||
344 | }) | ||
345 | .map(|name_ref| ReferenceDescriptor { | ||
346 | name: name_ref.text().to_string(), | ||
347 | range: name_ref.syntax().text_range(), | ||
348 | }) | ||
349 | .collect() | ||
350 | } | ||
351 | |||
352 | /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type | ||
353 | pub fn traits_in_scope(&self, db: &impl HirDatabase) -> FxHashSet<TraitId> { | ||
354 | self.resolver.traits_in_scope(db) | ||
355 | } | ||
356 | |||
357 | pub fn expand( | ||
358 | &self, | ||
359 | db: &impl HirDatabase, | ||
360 | macro_call: InFile<&ast::MacroCall>, | ||
361 | ) -> Option<Expansion> { | ||
362 | let def = self.resolve_macro_call(db, macro_call)?.id; | ||
363 | let ast_id = AstId::new( | ||
364 | macro_call.file_id, | ||
365 | db.ast_id_map(macro_call.file_id).ast_id(macro_call.value), | ||
366 | ); | ||
367 | Some(Expansion { macro_call_id: def.as_call_id(db, MacroCallKind::FnLike(ast_id)) }) | ||
368 | } | ||
369 | } | ||
370 | |||
371 | fn scope_for( | ||
372 | scopes: &ExprScopes, | ||
373 | source_map: &BodySourceMap, | ||
374 | node: InFile<&SyntaxNode>, | ||
375 | ) -> Option<ScopeId> { | ||
376 | node.value | ||
377 | .ancestors() | ||
378 | .filter_map(ast::Expr::cast) | ||
379 | .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it))) | ||
380 | .find_map(|it| scopes.scope_for(it)) | ||
381 | } | ||
382 | |||
383 | fn scope_for_offset( | ||
384 | scopes: &ExprScopes, | ||
385 | source_map: &BodySourceMap, | ||
386 | offset: InFile<TextUnit>, | ||
387 | ) -> Option<ScopeId> { | ||
388 | scopes | ||
389 | .scope_by_expr() | ||
390 | .iter() | ||
391 | .filter_map(|(id, scope)| { | ||
392 | let source = source_map.expr_syntax(*id)?; | ||
393 | // FIXME: correctly handle macro expansion | ||
394 | if source.file_id != offset.file_id { | ||
395 | return None; | ||
396 | } | ||
397 | let syntax_node_ptr = | ||
398 | source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()); | ||
399 | Some((syntax_node_ptr, scope)) | ||
400 | }) | ||
401 | // find containing scope | ||
402 | .min_by_key(|(ptr, _scope)| { | ||
403 | ( | ||
404 | !(ptr.range().start() <= offset.value && offset.value <= ptr.range().end()), | ||
405 | ptr.range().len(), | ||
406 | ) | ||
407 | }) | ||
408 | .map(|(ptr, scope)| { | ||
409 | adjust(scopes, source_map, ptr, offset.file_id, offset.value).unwrap_or(*scope) | ||
410 | }) | ||
411 | } | ||
412 | |||
413 | // XXX: during completion, cursor might be outside of any particular | ||
414 | // expression. Try to figure out the correct scope... | ||
415 | fn adjust( | ||
416 | scopes: &ExprScopes, | ||
417 | source_map: &BodySourceMap, | ||
418 | ptr: SyntaxNodePtr, | ||
419 | file_id: HirFileId, | ||
420 | offset: TextUnit, | ||
421 | ) -> Option<ScopeId> { | ||
422 | let r = ptr.range(); | ||
423 | let child_scopes = scopes | ||
424 | .scope_by_expr() | ||
425 | .iter() | ||
426 | .filter_map(|(id, scope)| { | ||
427 | let source = source_map.expr_syntax(*id)?; | ||
428 | // FIXME: correctly handle macro expansion | ||
429 | if source.file_id != file_id { | ||
430 | return None; | ||
431 | } | ||
432 | let syntax_node_ptr = | ||
433 | source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()); | ||
434 | Some((syntax_node_ptr, scope)) | ||
435 | }) | ||
436 | .map(|(ptr, scope)| (ptr.range(), scope)) | ||
437 | .filter(|(range, _)| range.start() <= offset && range.is_subrange(&r) && *range != r); | ||
438 | |||
439 | child_scopes | ||
440 | .max_by(|(r1, _), (r2, _)| { | ||
441 | if r2.is_subrange(&r1) { | ||
442 | std::cmp::Ordering::Greater | ||
443 | } else if r1.is_subrange(&r2) { | ||
444 | std::cmp::Ordering::Less | ||
445 | } else { | ||
446 | r1.start().cmp(&r2.start()) | ||
447 | } | ||
448 | }) | ||
449 | .map(|(_ptr, scope)| *scope) | ||
450 | } | ||