]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir/src/source_binder.rs
Replace `ra_hir_expand::either` with crate
[rust.git] / crates / ra_hir / src / source_binder.rs
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     path::known,
18     resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs},
19     AssocItemId, DefWithBodyId,
20 };
21 use hir_expand::{
22     hygiene::Hygiene, name::AsName, AstId, HirFileId, InFile, MacroCallId, MacroFileKind,
23 };
24 use ra_syntax::{
25     ast::{self, AstNode},
26     match_ast, AstPtr,
27     SyntaxKind::*,
28     SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextUnit,
29 };
30
31 use crate::{
32     db::HirDatabase,
33     ty::{
34         method_resolution::{self, implements_trait},
35         InEnvironment, TraitEnvironment, Ty,
36     },
37     Adt, AssocItem, Const, DefWithBody, Enum, EnumVariant, FromSource, Function, GenericParam,
38     Local, MacroDef, Name, Path, ScopeDef, Static, Struct, Trait, Type, TypeAlias,
39 };
40
41 fn try_get_resolver_for_node(db: &impl HirDatabase, node: InFile<&SyntaxNode>) -> Option<Resolver> {
42     match_ast! {
43         match (node.value) {
44             ast::Module(it) => {
45                 let src = node.with_value(it);
46                 Some(crate::Module::from_declaration(db, src)?.id.resolver(db))
47             },
48              ast::SourceFile(it) => {
49                 let src = node.with_value(crate::ModuleSource::SourceFile(it));
50                 Some(crate::Module::from_definition(db, src)?.id.resolver(db))
51             },
52             ast::StructDef(it) => {
53                 let src = node.with_value(it);
54                 Some(Struct::from_source(db, src)?.id.resolver(db))
55             },
56             ast::EnumDef(it) => {
57                 let src = node.with_value(it);
58                 Some(Enum::from_source(db, src)?.id.resolver(db))
59             },
60             _ => match node.value.kind() {
61                 FN_DEF | CONST_DEF | STATIC_DEF => {
62                     let def = def_with_body_from_child_node(db, node)?;
63                     let def = DefWithBodyId::from(def);
64                     Some(def.resolver(db))
65                 }
66                 // FIXME add missing cases
67                 _ => None
68             }
69         }
70     }
71 }
72
73 fn def_with_body_from_child_node(
74     db: &impl HirDatabase,
75     child: InFile<&SyntaxNode>,
76 ) -> Option<DefWithBody> {
77     child.value.ancestors().find_map(|node| {
78         match_ast! {
79             match node {
80                 ast::FnDef(def)  => { return Function::from_source(db, child.with_value(def)).map(DefWithBody::from); },
81                 ast::ConstDef(def) => { return Const::from_source(db, child.with_value(def)).map(DefWithBody::from); },
82                 ast::StaticDef(def) => { return Static::from_source(db, child.with_value(def)).map(DefWithBody::from); },
83                 _ => { None },
84             }
85         }
86     })
87 }
88
89 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
90 /// original source files. It should not be used inside the HIR itself.
91 #[derive(Debug)]
92 pub struct SourceAnalyzer {
93     file_id: HirFileId,
94     resolver: Resolver,
95     body_owner: Option<DefWithBody>,
96     body_source_map: Option<Arc<BodySourceMap>>,
97     infer: Option<Arc<crate::ty::InferenceResult>>,
98     scopes: Option<Arc<ExprScopes>>,
99 }
100
101 #[derive(Debug, Clone, PartialEq, Eq)]
102 pub enum PathResolution {
103     /// An item
104     Def(crate::ModuleDef),
105     /// A local binding (only value namespace)
106     Local(Local),
107     /// A generic parameter
108     GenericParam(GenericParam),
109     SelfType(crate::ImplBlock),
110     Macro(MacroDef),
111     AssocItem(crate::AssocItem),
112 }
113
114 #[derive(Debug, Clone, PartialEq, Eq)]
115 pub struct ScopeEntryWithSyntax {
116     pub(crate) name: Name,
117     pub(crate) ptr: Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>>,
118 }
119
120 impl ScopeEntryWithSyntax {
121     pub fn name(&self) -> &Name {
122         &self.name
123     }
124
125     pub fn ptr(&self) -> Either<AstPtr<ast::Pat>, AstPtr<ast::SelfParam>> {
126         self.ptr
127     }
128 }
129
130 #[derive(Debug)]
131 pub struct ReferenceDescriptor {
132     pub range: TextRange,
133     pub name: String,
134 }
135
136 pub struct Expansion {
137     macro_file_kind: MacroFileKind,
138     macro_call_id: MacroCallId,
139 }
140
141 impl Expansion {
142     pub fn map_token_down(
143         &self,
144         db: &impl HirDatabase,
145         token: InFile<&SyntaxToken>,
146     ) -> Option<InFile<SyntaxToken>> {
147         let exp_info = self.file_id().expansion_info(db)?;
148         exp_info.map_token_down(token)
149     }
150
151     pub fn file_id(&self) -> HirFileId {
152         self.macro_call_id.as_file(self.macro_file_kind)
153     }
154 }
155
156 impl SourceAnalyzer {
157     pub fn new(
158         db: &impl HirDatabase,
159         node: InFile<&SyntaxNode>,
160         offset: Option<TextUnit>,
161     ) -> SourceAnalyzer {
162         let def_with_body = def_with_body_from_child_node(db, node);
163         if let Some(def) = def_with_body {
164             let (_body, source_map) = db.body_with_source_map(def.into());
165             let scopes = db.expr_scopes(def.into());
166             let scope = match offset {
167                 None => scope_for(&scopes, &source_map, node),
168                 Some(offset) => scope_for_offset(&scopes, &source_map, node.with_value(offset)),
169             };
170             let resolver = resolver_for_scope(db, def.into(), scope);
171             SourceAnalyzer {
172                 resolver,
173                 body_owner: Some(def),
174                 body_source_map: Some(source_map),
175                 infer: Some(db.infer(def.into())),
176                 scopes: Some(scopes),
177                 file_id: node.file_id,
178             }
179         } else {
180             SourceAnalyzer {
181                 resolver: node
182                     .value
183                     .ancestors()
184                     .find_map(|it| try_get_resolver_for_node(db, node.with_value(&it)))
185                     .unwrap_or_default(),
186                 body_owner: None,
187                 body_source_map: None,
188                 infer: None,
189                 scopes: None,
190                 file_id: node.file_id,
191             }
192         }
193     }
194
195     fn expr_id(&self, expr: &ast::Expr) -> Option<ExprId> {
196         let src = InFile { file_id: self.file_id, value: expr };
197         self.body_source_map.as_ref()?.node_expr(src)
198     }
199
200     fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
201         let src = InFile { file_id: self.file_id, value: pat };
202         self.body_source_map.as_ref()?.node_pat(src)
203     }
204
205     pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> {
206         let expr_id = self.expr_id(expr)?;
207         let ty = self.infer.as_ref()?[expr_id].clone();
208         let environment = TraitEnvironment::lower(db, &self.resolver);
209         Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
210     }
211
212     pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> {
213         let pat_id = self.pat_id(pat)?;
214         let ty = self.infer.as_ref()?[pat_id].clone();
215         let environment = TraitEnvironment::lower(db, &self.resolver);
216         Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
217     }
218
219     pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
220         let expr_id = self.expr_id(&call.clone().into())?;
221         self.infer.as_ref()?.method_resolution(expr_id).map(Function::from)
222     }
223
224     pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> {
225         let expr_id = self.expr_id(&field.clone().into())?;
226         self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into())
227     }
228
229     pub fn resolve_record_field(&self, field: &ast::RecordField) -> Option<crate::StructField> {
230         let expr_id = self.expr_id(&field.expr()?)?;
231         self.infer.as_ref()?.record_field_resolution(expr_id).map(|it| it.into())
232     }
233
234     pub fn resolve_record_literal(&self, record_lit: &ast::RecordLit) -> Option<crate::VariantDef> {
235         let expr_id = self.expr_id(&record_lit.clone().into())?;
236         self.infer.as_ref()?.variant_resolution_for_expr(expr_id).map(|it| it.into())
237     }
238
239     pub fn resolve_record_pattern(&self, record_pat: &ast::RecordPat) -> Option<crate::VariantDef> {
240         let pat_id = self.pat_id(&record_pat.clone().into())?;
241         self.infer.as_ref()?.variant_resolution_for_pat(pat_id).map(|it| it.into())
242     }
243
244     pub fn resolve_macro_call(
245         &self,
246         db: &impl HirDatabase,
247         macro_call: InFile<&ast::MacroCall>,
248     ) -> Option<MacroDef> {
249         let hygiene = Hygiene::new(db, macro_call.file_id);
250         let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
251         self.resolver.resolve_path_as_macro(db, &path).map(|it| it.into())
252     }
253
254     pub fn resolve_hir_path(
255         &self,
256         db: &impl HirDatabase,
257         path: &crate::Path,
258     ) -> Option<PathResolution> {
259         let types = self.resolver.resolve_path_in_type_ns_fully(db, &path).map(|ty| match ty {
260             TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
261             TypeNs::GenericParam(idx) => PathResolution::GenericParam(GenericParam {
262                 parent: self.resolver.generic_def().unwrap(),
263                 idx,
264             }),
265             TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
266                 PathResolution::Def(Adt::from(it).into())
267             }
268             TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
269             TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
270             TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
271             TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
272         });
273         let values = self.resolver.resolve_path_in_value_ns_fully(db, &path).and_then(|val| {
274             let res = match val {
275                 ValueNs::LocalBinding(pat_id) => {
276                     let var = Local { parent: self.body_owner?, pat_id };
277                     PathResolution::Local(var)
278                 }
279                 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
280                 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
281                 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
282                 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
283                 ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
284             };
285             Some(res)
286         });
287
288         let items = self
289             .resolver
290             .resolve_module_path_in_items(db, &path)
291             .take_types()
292             .map(|it| PathResolution::Def(it.into()));
293         types.or(values).or(items).or_else(|| {
294             self.resolver
295                 .resolve_path_as_macro(db, &path)
296                 .map(|def| PathResolution::Macro(def.into()))
297         })
298     }
299
300     pub fn resolve_path(&self, db: &impl HirDatabase, path: &ast::Path) -> Option<PathResolution> {
301         if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
302             let expr_id = self.expr_id(&path_expr.into())?;
303             if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) {
304                 return Some(PathResolution::AssocItem(assoc.into()));
305             }
306         }
307         if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) {
308             let pat_id = self.pat_id(&path_pat.into())?;
309             if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
310                 return Some(PathResolution::AssocItem(assoc.into()));
311             }
312         }
313         // This must be a normal source file rather than macro file.
314         let hir_path = crate::Path::from_ast(path.clone())?;
315         self.resolve_hir_path(db, &hir_path)
316     }
317
318     fn resolve_local_name(&self, name_ref: &ast::NameRef) -> Option<ScopeEntryWithSyntax> {
319         let name = name_ref.as_name();
320         let source_map = self.body_source_map.as_ref()?;
321         let scopes = self.scopes.as_ref()?;
322         let scope = scope_for(scopes, source_map, InFile::new(self.file_id, name_ref.syntax()))?;
323         let entry = scopes.resolve_name_in_scope(scope, &name)?;
324         Some(ScopeEntryWithSyntax {
325             name: entry.name().clone(),
326             ptr: source_map.pat_syntax(entry.pat())?.value,
327         })
328     }
329
330     pub fn process_all_names(&self, db: &impl HirDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
331         self.resolver.process_all_names(db, &mut |name, def| {
332             let def = match def {
333                 resolver::ScopeDef::PerNs(it) => it.into(),
334                 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
335                 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
336                 resolver::ScopeDef::GenericParam(idx) => {
337                     let parent = self.resolver.generic_def().unwrap();
338                     ScopeDef::GenericParam(GenericParam { parent, idx })
339                 }
340                 resolver::ScopeDef::Local(pat_id) => {
341                     let parent = self.resolver.body_owner().unwrap().into();
342                     ScopeDef::Local(Local { parent, pat_id })
343                 }
344             };
345             f(name, def)
346         })
347     }
348
349     // FIXME: we only use this in `inline_local_variable` assist, ideally, we
350     // should switch to general reference search infra there.
351     pub fn find_all_refs(&self, pat: &ast::BindPat) -> Vec<ReferenceDescriptor> {
352         let fn_def = pat.syntax().ancestors().find_map(ast::FnDef::cast).unwrap();
353         let ptr = Either::Left(AstPtr::new(&ast::Pat::from(pat.clone())));
354         fn_def
355             .syntax()
356             .descendants()
357             .filter_map(ast::NameRef::cast)
358             .filter(|name_ref| match self.resolve_local_name(&name_ref) {
359                 None => false,
360                 Some(entry) => entry.ptr() == ptr,
361             })
362             .map(|name_ref| ReferenceDescriptor {
363                 name: name_ref.text().to_string(),
364                 range: name_ref.syntax().text_range(),
365             })
366             .collect()
367     }
368
369     pub fn iterate_method_candidates<T>(
370         &self,
371         db: &impl HirDatabase,
372         ty: &Type,
373         name: Option<&Name>,
374         mut callback: impl FnMut(&Ty, Function) -> Option<T>,
375     ) -> Option<T> {
376         // There should be no inference vars in types passed here
377         // FIXME check that?
378         // FIXME replace Unknown by bound vars here
379         let canonical = crate::ty::Canonical { value: ty.ty.value.clone(), num_vars: 0 };
380         method_resolution::iterate_method_candidates(
381             &canonical,
382             db,
383             &self.resolver,
384             name,
385             method_resolution::LookupMode::MethodCall,
386             |ty, it| match it {
387                 AssocItemId::FunctionId(f) => callback(ty, f.into()),
388                 _ => None,
389             },
390         )
391     }
392
393     pub fn iterate_path_candidates<T>(
394         &self,
395         db: &impl HirDatabase,
396         ty: &Type,
397         name: Option<&Name>,
398         mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
399     ) -> Option<T> {
400         // There should be no inference vars in types passed here
401         // FIXME check that?
402         // FIXME replace Unknown by bound vars here
403         let canonical = crate::ty::Canonical { value: ty.ty.value.clone(), num_vars: 0 };
404         method_resolution::iterate_method_candidates(
405             &canonical,
406             db,
407             &self.resolver,
408             name,
409             method_resolution::LookupMode::Path,
410             |ty, it| callback(ty, it.into()),
411         )
412     }
413
414     // pub fn autoderef<'a>(
415     //     &'a self,
416     //     db: &'a impl HirDatabase,
417     //     ty: Ty,
418     // ) -> impl Iterator<Item = Ty> + 'a {
419     //     // There should be no inference vars in types passed here
420     //     // FIXME check that?
421     //     let canonical = crate::ty::Canonical { value: ty, num_vars: 0 };
422     //     let krate = self.resolver.krate();
423     //     let environment = TraitEnvironment::lower(db, &self.resolver);
424     //     let ty = crate::ty::InEnvironment { value: canonical, environment };
425     //     crate::ty::autoderef(db, krate, ty).map(|canonical| canonical.value)
426     // }
427
428     /// Checks that particular type `ty` implements `std::future::Future`.
429     /// This function is used in `.await` syntax completion.
430     pub fn impls_future(&self, db: &impl HirDatabase, ty: Ty) -> bool {
431         let std_future_path = known::std_future_future();
432
433         let std_future_trait = match self.resolver.resolve_known_trait(db, &std_future_path) {
434             Some(it) => it.into(),
435             _ => return false,
436         };
437
438         let krate = match self.resolver.krate() {
439             Some(krate) => krate,
440             _ => return false,
441         };
442
443         let canonical_ty = crate::ty::Canonical { value: ty, num_vars: 0 };
444         implements_trait(&canonical_ty, db, &self.resolver, krate.into(), std_future_trait)
445     }
446
447     pub fn expand(
448         &self,
449         db: &impl HirDatabase,
450         macro_call: InFile<&ast::MacroCall>,
451     ) -> Option<Expansion> {
452         let def = self.resolve_macro_call(db, macro_call)?.id;
453         let ast_id = AstId::new(
454             macro_call.file_id,
455             db.ast_id_map(macro_call.file_id).ast_id(macro_call.value),
456         );
457         Some(Expansion {
458             macro_call_id: def.as_call_id(db, ast_id),
459             macro_file_kind: to_macro_file_kind(macro_call.value),
460         })
461     }
462 }
463
464 fn scope_for(
465     scopes: &ExprScopes,
466     source_map: &BodySourceMap,
467     node: InFile<&SyntaxNode>,
468 ) -> Option<ScopeId> {
469     node.value
470         .ancestors()
471         .filter_map(ast::Expr::cast)
472         .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
473         .find_map(|it| scopes.scope_for(it))
474 }
475
476 fn scope_for_offset(
477     scopes: &ExprScopes,
478     source_map: &BodySourceMap,
479     offset: InFile<TextUnit>,
480 ) -> Option<ScopeId> {
481     scopes
482         .scope_by_expr()
483         .iter()
484         .filter_map(|(id, scope)| {
485             let source = source_map.expr_syntax(*id)?;
486             // FIXME: correctly handle macro expansion
487             if source.file_id != offset.file_id {
488                 return None;
489             }
490             let syntax_node_ptr =
491                 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
492             Some((syntax_node_ptr, scope))
493         })
494         // find containing scope
495         .min_by_key(|(ptr, _scope)| {
496             (
497                 !(ptr.range().start() <= offset.value && offset.value <= ptr.range().end()),
498                 ptr.range().len(),
499             )
500         })
501         .map(|(ptr, scope)| {
502             adjust(scopes, source_map, ptr, offset.file_id, offset.value).unwrap_or(*scope)
503         })
504 }
505
506 // XXX: during completion, cursor might be outside of any particular
507 // expression. Try to figure out the correct scope...
508 fn adjust(
509     scopes: &ExprScopes,
510     source_map: &BodySourceMap,
511     ptr: SyntaxNodePtr,
512     file_id: HirFileId,
513     offset: TextUnit,
514 ) -> Option<ScopeId> {
515     let r = ptr.range();
516     let child_scopes = scopes
517         .scope_by_expr()
518         .iter()
519         .filter_map(|(id, scope)| {
520             let source = source_map.expr_syntax(*id)?;
521             // FIXME: correctly handle macro expansion
522             if source.file_id != file_id {
523                 return None;
524             }
525             let syntax_node_ptr =
526                 source.value.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
527             Some((syntax_node_ptr, scope))
528         })
529         .map(|(ptr, scope)| (ptr.range(), scope))
530         .filter(|(range, _)| range.start() <= offset && range.is_subrange(&r) && *range != r);
531
532     child_scopes
533         .max_by(|(r1, _), (r2, _)| {
534             if r2.is_subrange(&r1) {
535                 std::cmp::Ordering::Greater
536             } else if r1.is_subrange(&r2) {
537                 std::cmp::Ordering::Less
538             } else {
539                 r1.start().cmp(&r2.start())
540             }
541         })
542         .map(|(_ptr, scope)| *scope)
543 }
544
545 /// Given a `ast::MacroCall`, return what `MacroKindFile` it belongs to.
546 /// FIXME: Not completed
547 fn to_macro_file_kind(macro_call: &ast::MacroCall) -> MacroFileKind {
548     let syn = macro_call.syntax();
549     let parent = match syn.parent() {
550         Some(it) => it,
551         None => {
552             // FIXME:
553             // If it is root, which means the parent HirFile
554             // MacroKindFile must be non-items
555             // return expr now.
556             return MacroFileKind::Expr;
557         }
558     };
559
560     match parent.kind() {
561         MACRO_ITEMS | SOURCE_FILE => MacroFileKind::Items,
562         LET_STMT => {
563             // FIXME: Handle Pattern
564             MacroFileKind::Expr
565         }
566         EXPR_STMT => MacroFileKind::Statements,
567         BLOCK => MacroFileKind::Statements,
568         ARG_LIST => MacroFileKind::Expr,
569         TRY_EXPR => MacroFileKind::Expr,
570         _ => {
571             // Unknown , Just guess it is `Items`
572             MacroFileKind::Items
573         }
574     }
575 }