]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/lib.rs
Merge #8087
[rust.git] / crates / hir / src / lib.rs
1 //! HIR (previously known as descriptors) provides a high-level object oriented
2 //! access to Rust code.
3 //!
4 //! The principal difference between HIR and syntax trees is that HIR is bound
5 //! to a particular crate instance. That is, it has cfg flags and features
6 //! applied. So, the relation between syntax and HIR is many-to-one.
7 //!
8 //! HIR is the public API of the all of the compiler logic above syntax trees.
9 //! It is written in "OO" style. Each type is self contained (as in, it knows it's
10 //! parents and full context). It should be "clean code".
11 //!
12 //! `hir_*` crates are the implementation of the compiler logic.
13 //! They are written in "ECS" style, with relatively little abstractions.
14 //! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
15 //!
16 //! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
17 //! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
18 //! https://www.tedinski.com/2018/02/06/system-boundaries.html.
19
20 #![recursion_limit = "512"]
21
22 mod semantics;
23 mod source_analyzer;
24
25 mod from_id;
26 mod attrs;
27 mod has_source;
28
29 pub mod diagnostics;
30 pub mod db;
31
32 mod display;
33
34 use std::{iter, sync::Arc};
35
36 use arrayvec::ArrayVec;
37 use base_db::{CrateDisplayName, CrateId, Edition, FileId};
38 use either::Either;
39 use hir_def::{
40     adt::{ReprKind, VariantData},
41     expr::{BindingAnnotation, LabelId, Pat, PatId},
42     item_tree::ItemTreeNode,
43     lang_item::LangItemTarget,
44     per_ns::PerNs,
45     resolver::{HasResolver, Resolver},
46     src::HasSource as _,
47     AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
48     DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
49     LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
50     TypeParamId, UnionId,
51 };
52 use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
53 use hir_ty::{
54     autoderef,
55     method_resolution::{self, TyFingerprint},
56     primitive::UintTy,
57     to_assoc_type_id,
58     traits::{FnTrait, Solution, SolutionVariables},
59     AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate,
60     InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substitution,
61     Ty, TyDefId, TyKind, TyVariableKind,
62 };
63 use itertools::Itertools;
64 use rustc_hash::FxHashSet;
65 use stdx::{format_to, impl_from};
66 use syntax::{
67     ast::{self, AttrsOwner, NameOwner},
68     AstNode, SmolStr,
69 };
70 use tt::{Ident, Leaf, Literal, TokenTree};
71
72 use crate::db::{DefDatabase, HirDatabase};
73
74 pub use crate::{
75     attrs::{HasAttrs, Namespace},
76     has_source::HasSource,
77     semantics::{PathResolution, Semantics, SemanticsScope},
78 };
79
80 // Be careful with these re-exports.
81 //
82 // `hir` is the boundary between the compiler and the IDE. It should try hard to
83 // isolate the compiler from the ide, to allow the two to be refactored
84 // independently. Re-exporting something from the compiler is the sure way to
85 // breach the boundary.
86 //
87 // Generally, a refactoring which *removes* a name from this list is a good
88 // idea!
89 pub use {
90     hir_def::{
91         adt::StructKind,
92         attr::{Attr, Attrs, Documentation},
93         body::scope::ExprScopes,
94         find_path::PrefixKind,
95         import_map,
96         item_scope::ItemInNs,
97         nameres::ModuleSource,
98         path::{ModPath, PathKind},
99         type_ref::{Mutability, TypeRef},
100         visibility::Visibility,
101     },
102     hir_expand::{
103         name::{known, Name},
104         ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
105         MacroFile, Origin,
106     },
107     hir_ty::display::HirDisplay,
108 };
109
110 // These are negative re-exports: pub using these names is forbidden, they
111 // should remain private to hir internals.
112 #[allow(unused)]
113 use {
114     hir_def::path::Path,
115     hir_expand::{hygiene::Hygiene, name::AsName},
116 };
117
118 /// hir::Crate describes a single crate. It's the main interface with which
119 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
120 /// root module.
121 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122 pub struct Crate {
123     pub(crate) id: CrateId,
124 }
125
126 #[derive(Debug)]
127 pub struct CrateDependency {
128     pub krate: Crate,
129     pub name: Name,
130 }
131
132 impl Crate {
133     pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
134         db.crate_graph()[self.id]
135             .dependencies
136             .iter()
137             .map(|dep| {
138                 let krate = Crate { id: dep.crate_id };
139                 let name = dep.as_name();
140                 CrateDependency { krate, name }
141             })
142             .collect()
143     }
144
145     pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
146         let crate_graph = db.crate_graph();
147         crate_graph
148             .iter()
149             .filter(|&krate| {
150                 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
151             })
152             .map(|id| Crate { id })
153             .collect()
154     }
155
156     pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
157         db.crate_graph()
158             .transitive_reverse_dependencies(self.id)
159             .into_iter()
160             .map(|id| Crate { id })
161             .collect()
162     }
163
164     pub fn root_module(self, db: &dyn HirDatabase) -> Module {
165         let def_map = db.crate_def_map(self.id);
166         Module { id: def_map.module_id(def_map.root()) }
167     }
168
169     pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
170         db.crate_graph()[self.id].root_file_id
171     }
172
173     pub fn edition(self, db: &dyn HirDatabase) -> Edition {
174         db.crate_graph()[self.id].edition
175     }
176
177     pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
178         db.crate_graph()[self.id].display_name.clone()
179     }
180
181     pub fn query_external_importables(
182         self,
183         db: &dyn DefDatabase,
184         query: import_map::Query,
185     ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
186         import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
187             ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
188             ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
189         })
190     }
191
192     pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
193         db.crate_graph().iter().map(|id| Crate { id }).collect()
194     }
195
196     /// Try to get the root URL of the documentation of a crate.
197     pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
198         // Look for #![doc(html_root_url = "...")]
199         let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
200         let doc_attr_q = attrs.by_key("doc");
201
202         if !doc_attr_q.exists() {
203             return None;
204         }
205
206         let doc_url = doc_attr_q.tt_values().map(|tt| {
207             let name = tt.token_trees.iter()
208                 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
209                 .skip(2)
210                 .next();
211
212             match name {
213                 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
214                 _ => None
215             }
216         }).flat_map(|t| t).next();
217
218         doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
219     }
220 }
221
222 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
223 pub struct Module {
224     pub(crate) id: ModuleId,
225 }
226
227 /// The defs which can be visible in the module.
228 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229 pub enum ModuleDef {
230     Module(Module),
231     Function(Function),
232     Adt(Adt),
233     // Can't be directly declared, but can be imported.
234     Variant(Variant),
235     Const(Const),
236     Static(Static),
237     Trait(Trait),
238     TypeAlias(TypeAlias),
239     BuiltinType(BuiltinType),
240 }
241 impl_from!(
242     Module,
243     Function,
244     Adt(Struct, Enum, Union),
245     Variant,
246     Const,
247     Static,
248     Trait,
249     TypeAlias,
250     BuiltinType
251     for ModuleDef
252 );
253
254 impl From<VariantDef> for ModuleDef {
255     fn from(var: VariantDef) -> Self {
256         match var {
257             VariantDef::Struct(t) => Adt::from(t).into(),
258             VariantDef::Union(t) => Adt::from(t).into(),
259             VariantDef::Variant(t) => t.into(),
260         }
261     }
262 }
263
264 impl ModuleDef {
265     pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
266         match self {
267             ModuleDef::Module(it) => it.parent(db),
268             ModuleDef::Function(it) => Some(it.module(db)),
269             ModuleDef::Adt(it) => Some(it.module(db)),
270             ModuleDef::Variant(it) => Some(it.module(db)),
271             ModuleDef::Const(it) => Some(it.module(db)),
272             ModuleDef::Static(it) => Some(it.module(db)),
273             ModuleDef::Trait(it) => Some(it.module(db)),
274             ModuleDef::TypeAlias(it) => Some(it.module(db)),
275             ModuleDef::BuiltinType(_) => None,
276         }
277     }
278
279     pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
280         let mut segments = vec![self.name(db)?.to_string()];
281         for m in self.module(db)?.path_to_root(db) {
282             segments.extend(m.name(db).map(|it| it.to_string()))
283         }
284         segments.reverse();
285         Some(segments.join("::"))
286     }
287
288     pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
289         let module = match self {
290             ModuleDef::Module(it) => it.parent(db)?,
291             ModuleDef::Function(it) => return Some(it.visibility(db)),
292             ModuleDef::Adt(it) => it.module(db),
293             ModuleDef::Variant(it) => {
294                 let parent = it.parent_enum(db);
295                 let module = it.module(db);
296                 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
297             }
298             ModuleDef::Const(it) => return Some(it.visibility(db)),
299             ModuleDef::Static(it) => it.module(db),
300             ModuleDef::Trait(it) => it.module(db),
301             ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
302             ModuleDef::BuiltinType(_) => return None,
303         };
304
305         module.visibility_of(db, self)
306     }
307
308     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
309         match self {
310             ModuleDef::Adt(it) => Some(it.name(db)),
311             ModuleDef::Trait(it) => Some(it.name(db)),
312             ModuleDef::Function(it) => Some(it.name(db)),
313             ModuleDef::Variant(it) => Some(it.name(db)),
314             ModuleDef::TypeAlias(it) => Some(it.name(db)),
315             ModuleDef::Module(it) => it.name(db),
316             ModuleDef::Const(it) => it.name(db),
317             ModuleDef::Static(it) => it.name(db),
318             ModuleDef::BuiltinType(it) => Some(it.name()),
319         }
320     }
321
322     pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
323         let id = match self {
324             ModuleDef::Adt(it) => match it {
325                 Adt::Struct(it) => it.id.into(),
326                 Adt::Enum(it) => it.id.into(),
327                 Adt::Union(it) => it.id.into(),
328             },
329             ModuleDef::Trait(it) => it.id.into(),
330             ModuleDef::Function(it) => it.id.into(),
331             ModuleDef::TypeAlias(it) => it.id.into(),
332             ModuleDef::Module(it) => it.id.into(),
333             ModuleDef::Const(it) => it.id.into(),
334             ModuleDef::Static(it) => it.id.into(),
335             _ => return,
336         };
337
338         let module = match self.module(db) {
339             Some(it) => it,
340             None => return,
341         };
342
343         hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
344     }
345 }
346
347 impl Module {
348     /// Name of this module.
349     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
350         let def_map = self.id.def_map(db.upcast());
351         let parent = def_map[self.id.local_id].parent?;
352         def_map[parent].children.iter().find_map(|(name, module_id)| {
353             if *module_id == self.id.local_id {
354                 Some(name.clone())
355             } else {
356                 None
357             }
358         })
359     }
360
361     /// Returns the crate this module is part of.
362     pub fn krate(self) -> Crate {
363         Crate { id: self.id.krate() }
364     }
365
366     /// Topmost parent of this module. Every module has a `crate_root`, but some
367     /// might be missing `krate`. This can happen if a module's file is not included
368     /// in the module tree of any target in `Cargo.toml`.
369     pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
370         let def_map = db.crate_def_map(self.id.krate());
371         Module { id: def_map.module_id(def_map.root()) }
372     }
373
374     /// Iterates over all child modules.
375     pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
376         let def_map = self.id.def_map(db.upcast());
377         let children = def_map[self.id.local_id]
378             .children
379             .iter()
380             .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
381             .collect::<Vec<_>>();
382         children.into_iter()
383     }
384
385     /// Finds a parent module.
386     pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
387         // FIXME: handle block expressions as modules (their parent is in a different DefMap)
388         let def_map = self.id.def_map(db.upcast());
389         let parent_id = def_map[self.id.local_id].parent?;
390         Some(Module { id: def_map.module_id(parent_id) })
391     }
392
393     pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
394         let mut res = vec![self];
395         let mut curr = self;
396         while let Some(next) = curr.parent(db) {
397             res.push(next);
398             curr = next
399         }
400         res
401     }
402
403     /// Returns a `ModuleScope`: a set of items, visible in this module.
404     pub fn scope(
405         self,
406         db: &dyn HirDatabase,
407         visible_from: Option<Module>,
408     ) -> Vec<(Name, ScopeDef)> {
409         self.id.def_map(db.upcast())[self.id.local_id]
410             .scope
411             .entries()
412             .filter_map(|(name, def)| {
413                 if let Some(m) = visible_from {
414                     let filtered =
415                         def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
416                     if filtered.is_none() && !def.is_none() {
417                         None
418                     } else {
419                         Some((name, filtered))
420                     }
421                 } else {
422                     Some((name, def))
423                 }
424             })
425             .flat_map(|(name, def)| {
426                 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
427             })
428             .collect()
429     }
430
431     pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
432         self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
433     }
434
435     pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
436         let _p = profile::span("Module::diagnostics").detail(|| {
437             format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
438         });
439         let def_map = self.id.def_map(db.upcast());
440         def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
441         for decl in self.declarations(db) {
442             match decl {
443                 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
444                 crate::ModuleDef::Module(m) => {
445                     // Only add diagnostics from inline modules
446                     if def_map[m.id.local_id].origin.is_inline() {
447                         m.diagnostics(db, sink)
448                     }
449                 }
450                 _ => {
451                     decl.diagnostics(db, sink);
452                 }
453             }
454         }
455
456         for impl_def in self.impl_defs(db) {
457             for item in impl_def.items(db) {
458                 if let AssocItem::Function(f) = item {
459                     f.diagnostics(db, sink);
460                 }
461             }
462         }
463     }
464
465     pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
466         let def_map = self.id.def_map(db.upcast());
467         def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
468     }
469
470     pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
471         let def_map = self.id.def_map(db.upcast());
472         def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
473     }
474
475     /// Finds a path that can be used to refer to the given item from within
476     /// this module, if possible.
477     pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
478         hir_def::find_path::find_path(db, item.into(), self.into())
479     }
480
481     /// Finds a path that can be used to refer to the given item from within
482     /// this module, if possible. This is used for returning import paths for use-statements.
483     pub fn find_use_path_prefixed(
484         self,
485         db: &dyn DefDatabase,
486         item: impl Into<ItemInNs>,
487         prefix_kind: PrefixKind,
488     ) -> Option<ModPath> {
489         hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
490     }
491 }
492
493 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
494 pub struct Field {
495     pub(crate) parent: VariantDef,
496     pub(crate) id: LocalFieldId,
497 }
498
499 #[derive(Debug, PartialEq, Eq)]
500 pub enum FieldSource {
501     Named(ast::RecordField),
502     Pos(ast::TupleField),
503 }
504
505 impl Field {
506     pub fn name(&self, db: &dyn HirDatabase) -> Name {
507         self.parent.variant_data(db).fields()[self.id].name.clone()
508     }
509
510     /// Returns the type as in the signature of the struct (i.e., with
511     /// placeholder types for type parameters). This is good for showing
512     /// signature help, but not so good to actually get the type of the field
513     /// when you actually have a variable of the struct.
514     pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
515         let var_id = self.parent.into();
516         let generic_def_id: GenericDefId = match self.parent {
517             VariantDef::Struct(it) => it.id.into(),
518             VariantDef::Union(it) => it.id.into(),
519             VariantDef::Variant(it) => it.parent.id.into(),
520         };
521         let substs = Substitution::type_params(db, generic_def_id);
522         let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
523         Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
524     }
525
526     pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
527         self.parent
528     }
529 }
530
531 impl HasVisibility for Field {
532     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
533         let variant_data = self.parent.variant_data(db);
534         let visibility = &variant_data.fields()[self.id].visibility;
535         let parent_id: hir_def::VariantId = self.parent.into();
536         visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
537     }
538 }
539
540 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
541 pub struct Struct {
542     pub(crate) id: StructId,
543 }
544
545 impl Struct {
546     pub fn module(self, db: &dyn HirDatabase) -> Module {
547         Module { id: self.id.lookup(db.upcast()).container }
548     }
549
550     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
551         Some(self.module(db).krate())
552     }
553
554     pub fn name(self, db: &dyn HirDatabase) -> Name {
555         db.struct_data(self.id).name.clone()
556     }
557
558     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
559         db.struct_data(self.id)
560             .variant_data
561             .fields()
562             .iter()
563             .map(|(id, _)| Field { parent: self.into(), id })
564             .collect()
565     }
566
567     pub fn ty(self, db: &dyn HirDatabase) -> Type {
568         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
569     }
570
571     pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
572         db.struct_data(self.id).repr.clone()
573     }
574
575     pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
576         self.variant_data(db).kind()
577     }
578
579     fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
580         db.struct_data(self.id).variant_data.clone()
581     }
582 }
583
584 impl HasVisibility for Struct {
585     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
586         db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
587     }
588 }
589
590 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
591 pub struct Union {
592     pub(crate) id: UnionId,
593 }
594
595 impl Union {
596     pub fn name(self, db: &dyn HirDatabase) -> Name {
597         db.union_data(self.id).name.clone()
598     }
599
600     pub fn module(self, db: &dyn HirDatabase) -> Module {
601         Module { id: self.id.lookup(db.upcast()).container }
602     }
603
604     pub fn ty(self, db: &dyn HirDatabase) -> Type {
605         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
606     }
607
608     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
609         db.union_data(self.id)
610             .variant_data
611             .fields()
612             .iter()
613             .map(|(id, _)| Field { parent: self.into(), id })
614             .collect()
615     }
616
617     fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
618         db.union_data(self.id).variant_data.clone()
619     }
620 }
621
622 impl HasVisibility for Union {
623     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
624         db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
625     }
626 }
627
628 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
629 pub struct Enum {
630     pub(crate) id: EnumId,
631 }
632
633 impl Enum {
634     pub fn module(self, db: &dyn HirDatabase) -> Module {
635         Module { id: self.id.lookup(db.upcast()).container }
636     }
637
638     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
639         Some(self.module(db).krate())
640     }
641
642     pub fn name(self, db: &dyn HirDatabase) -> Name {
643         db.enum_data(self.id).name.clone()
644     }
645
646     pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
647         db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
648     }
649
650     pub fn ty(self, db: &dyn HirDatabase) -> Type {
651         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
652     }
653 }
654
655 impl HasVisibility for Enum {
656     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
657         db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
658     }
659 }
660
661 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
662 pub struct Variant {
663     pub(crate) parent: Enum,
664     pub(crate) id: LocalEnumVariantId,
665 }
666
667 impl Variant {
668     pub fn module(self, db: &dyn HirDatabase) -> Module {
669         self.parent.module(db)
670     }
671     pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
672         self.parent
673     }
674
675     pub fn name(self, db: &dyn HirDatabase) -> Name {
676         db.enum_data(self.parent.id).variants[self.id].name.clone()
677     }
678
679     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
680         self.variant_data(db)
681             .fields()
682             .iter()
683             .map(|(id, _)| Field { parent: self.into(), id })
684             .collect()
685     }
686
687     pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
688         self.variant_data(db).kind()
689     }
690
691     pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
692         db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
693     }
694 }
695
696 /// A Data Type
697 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
698 pub enum Adt {
699     Struct(Struct),
700     Union(Union),
701     Enum(Enum),
702 }
703 impl_from!(Struct, Union, Enum for Adt);
704
705 impl Adt {
706     pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
707         let subst = db.generic_defaults(self.into());
708         subst.iter().any(|ty| ty.value.is_unknown())
709     }
710
711     /// Turns this ADT into a type. Any type parameters of the ADT will be
712     /// turned into unknown types, which is good for e.g. finding the most
713     /// general set of completions, but will not look very nice when printed.
714     pub fn ty(self, db: &dyn HirDatabase) -> Type {
715         let id = AdtId::from(self);
716         Type::from_def(db, id.module(db.upcast()).krate(), id)
717     }
718
719     pub fn module(self, db: &dyn HirDatabase) -> Module {
720         match self {
721             Adt::Struct(s) => s.module(db),
722             Adt::Union(s) => s.module(db),
723             Adt::Enum(e) => e.module(db),
724         }
725     }
726
727     pub fn krate(self, db: &dyn HirDatabase) -> Crate {
728         self.module(db).krate()
729     }
730
731     pub fn name(self, db: &dyn HirDatabase) -> Name {
732         match self {
733             Adt::Struct(s) => s.name(db),
734             Adt::Union(u) => u.name(db),
735             Adt::Enum(e) => e.name(db),
736         }
737     }
738 }
739
740 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
741 pub enum VariantDef {
742     Struct(Struct),
743     Union(Union),
744     Variant(Variant),
745 }
746 impl_from!(Struct, Union, Variant for VariantDef);
747
748 impl VariantDef {
749     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
750         match self {
751             VariantDef::Struct(it) => it.fields(db),
752             VariantDef::Union(it) => it.fields(db),
753             VariantDef::Variant(it) => it.fields(db),
754         }
755     }
756
757     pub fn module(self, db: &dyn HirDatabase) -> Module {
758         match self {
759             VariantDef::Struct(it) => it.module(db),
760             VariantDef::Union(it) => it.module(db),
761             VariantDef::Variant(it) => it.module(db),
762         }
763     }
764
765     pub fn name(&self, db: &dyn HirDatabase) -> Name {
766         match self {
767             VariantDef::Struct(s) => s.name(db),
768             VariantDef::Union(u) => u.name(db),
769             VariantDef::Variant(e) => e.name(db),
770         }
771     }
772
773     pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
774         match self {
775             VariantDef::Struct(it) => it.variant_data(db),
776             VariantDef::Union(it) => it.variant_data(db),
777             VariantDef::Variant(it) => it.variant_data(db),
778         }
779     }
780 }
781
782 /// The defs which have a body.
783 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
784 pub enum DefWithBody {
785     Function(Function),
786     Static(Static),
787     Const(Const),
788 }
789 impl_from!(Function, Const, Static for DefWithBody);
790
791 impl DefWithBody {
792     pub fn module(self, db: &dyn HirDatabase) -> Module {
793         match self {
794             DefWithBody::Const(c) => c.module(db),
795             DefWithBody::Function(f) => f.module(db),
796             DefWithBody::Static(s) => s.module(db),
797         }
798     }
799
800     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
801         match self {
802             DefWithBody::Function(f) => Some(f.name(db)),
803             DefWithBody::Static(s) => s.name(db),
804             DefWithBody::Const(c) => c.name(db),
805         }
806     }
807 }
808
809 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
810 pub struct Function {
811     pub(crate) id: FunctionId,
812 }
813
814 impl Function {
815     pub fn module(self, db: &dyn HirDatabase) -> Module {
816         self.id.lookup(db.upcast()).module(db.upcast()).into()
817     }
818
819     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
820         Some(self.module(db).krate())
821     }
822
823     pub fn name(self, db: &dyn HirDatabase) -> Name {
824         db.function_data(self.id).name.clone()
825     }
826
827     /// Get this function's return type
828     pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
829         let resolver = self.id.resolver(db.upcast());
830         let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
831         let ret_type = &db.function_data(self.id).ret_type;
832         let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
833         let ty = ctx.lower_ty(ret_type);
834         Type::new_with_resolver_inner(db, krate, &resolver, ty)
835     }
836
837     pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
838         if !db.function_data(self.id).has_self_param {
839             return None;
840         }
841         Some(SelfParam { func: self.id })
842     }
843
844     pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
845         let resolver = self.id.resolver(db.upcast());
846         let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
847         let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
848         let environment = db.trait_environment(self.id.into());
849         db.function_data(self.id)
850             .params
851             .iter()
852             .enumerate()
853             .map(|(idx, type_ref)| {
854                 let ty = Type {
855                     krate,
856                     ty: InEnvironment {
857                         value: ctx.lower_ty(type_ref),
858                         environment: environment.clone(),
859                     },
860                 };
861                 Param { func: self, ty, idx }
862             })
863             .collect()
864     }
865     pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
866         if self.self_param(db).is_none() {
867             return None;
868         }
869         let mut res = self.assoc_fn_params(db);
870         res.remove(0);
871         Some(res)
872     }
873
874     pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
875         db.function_data(self.id).qualifier.is_unsafe
876     }
877
878     pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
879         let krate = self.module(db).id.krate();
880         hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
881         hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
882         hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
883     }
884
885     /// Whether this function declaration has a definition.
886     ///
887     /// This is false in the case of required (not provided) trait methods.
888     pub fn has_body(self, db: &dyn HirDatabase) -> bool {
889         db.function_data(self.id).has_body
890     }
891
892     /// A textual representation of the HIR of this function for debugging purposes.
893     pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
894         let body = db.body(self.id.into());
895
896         let mut result = String::new();
897         format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
898         for (id, expr) in body.exprs.iter() {
899             format_to!(result, "{:?}: {:?}\n", id, expr);
900         }
901
902         result
903     }
904 }
905
906 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
907 pub enum Access {
908     Shared,
909     Exclusive,
910     Owned,
911 }
912
913 impl From<hir_ty::Mutability> for Access {
914     fn from(mutability: hir_ty::Mutability) -> Access {
915         match mutability {
916             hir_ty::Mutability::Not => Access::Shared,
917             hir_ty::Mutability::Mut => Access::Exclusive,
918         }
919     }
920 }
921
922 #[derive(Debug)]
923 pub struct Param {
924     func: Function,
925     /// The index in parameter list, including self parameter.
926     idx: usize,
927     ty: Type,
928 }
929
930 impl Param {
931     pub fn ty(&self) -> &Type {
932         &self.ty
933     }
934
935     pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
936         let params = self.func.source(db)?.value.param_list()?;
937         if params.self_param().is_some() {
938             params.params().nth(self.idx.checked_sub(1)?)?.pat()
939         } else {
940             params.params().nth(self.idx)?.pat()
941         }
942     }
943 }
944
945 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
946 pub struct SelfParam {
947     func: FunctionId,
948 }
949
950 impl SelfParam {
951     pub fn access(self, db: &dyn HirDatabase) -> Access {
952         let func_data = db.function_data(self.func);
953         func_data
954             .params
955             .first()
956             .map(|param| match *param {
957                 TypeRef::Reference(.., mutability) => match mutability {
958                     hir_def::type_ref::Mutability::Shared => Access::Shared,
959                     hir_def::type_ref::Mutability::Mut => Access::Exclusive,
960                 },
961                 _ => Access::Owned,
962             })
963             .unwrap_or(Access::Owned)
964     }
965
966     pub fn display(self, db: &dyn HirDatabase) -> &'static str {
967         match self.access(db) {
968             Access::Shared => "&self",
969             Access::Exclusive => "&mut self",
970             Access::Owned => "self",
971         }
972     }
973 }
974
975 impl HasVisibility for Function {
976     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
977         let function_data = db.function_data(self.id);
978         let visibility = &function_data.visibility;
979         visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
980     }
981 }
982
983 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
984 pub struct Const {
985     pub(crate) id: ConstId,
986 }
987
988 impl Const {
989     pub fn module(self, db: &dyn HirDatabase) -> Module {
990         Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
991     }
992
993     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
994         Some(self.module(db).krate())
995     }
996
997     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
998         db.const_data(self.id).name.clone()
999     }
1000
1001     pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
1002         db.const_data(self.id).type_ref.clone()
1003     }
1004 }
1005
1006 impl HasVisibility for Const {
1007     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1008         let function_data = db.const_data(self.id);
1009         let visibility = &function_data.visibility;
1010         visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1011     }
1012 }
1013
1014 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1015 pub struct Static {
1016     pub(crate) id: StaticId,
1017 }
1018
1019 impl Static {
1020     pub fn module(self, db: &dyn HirDatabase) -> Module {
1021         Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1022     }
1023
1024     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1025         Some(self.module(db).krate())
1026     }
1027
1028     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1029         db.static_data(self.id).name.clone()
1030     }
1031
1032     pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1033         db.static_data(self.id).mutable
1034     }
1035 }
1036
1037 impl HasVisibility for Static {
1038     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1039         db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1040     }
1041 }
1042
1043 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1044 pub struct Trait {
1045     pub(crate) id: TraitId,
1046 }
1047
1048 impl Trait {
1049     pub fn module(self, db: &dyn HirDatabase) -> Module {
1050         Module { id: self.id.lookup(db.upcast()).container }
1051     }
1052
1053     pub fn name(self, db: &dyn HirDatabase) -> Name {
1054         db.trait_data(self.id).name.clone()
1055     }
1056
1057     pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1058         db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1059     }
1060
1061     pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1062         db.trait_data(self.id).is_auto
1063     }
1064 }
1065
1066 impl HasVisibility for Trait {
1067     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1068         db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1069     }
1070 }
1071
1072 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1073 pub struct TypeAlias {
1074     pub(crate) id: TypeAliasId,
1075 }
1076
1077 impl TypeAlias {
1078     pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1079         let subst = db.generic_defaults(self.id.into());
1080         subst.iter().any(|ty| ty.value.is_unknown())
1081     }
1082
1083     pub fn module(self, db: &dyn HirDatabase) -> Module {
1084         Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1085     }
1086
1087     pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1088         self.module(db).krate()
1089     }
1090
1091     pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1092         db.type_alias_data(self.id).type_ref.clone()
1093     }
1094
1095     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1096         Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1097     }
1098
1099     pub fn name(self, db: &dyn HirDatabase) -> Name {
1100         db.type_alias_data(self.id).name.clone()
1101     }
1102 }
1103
1104 impl HasVisibility for TypeAlias {
1105     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1106         let function_data = db.type_alias_data(self.id);
1107         let visibility = &function_data.visibility;
1108         visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1109     }
1110 }
1111
1112 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1113 pub struct BuiltinType {
1114     pub(crate) inner: hir_def::builtin_type::BuiltinType,
1115 }
1116
1117 impl BuiltinType {
1118     pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1119         let resolver = module.id.resolver(db.upcast());
1120         Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1121             .expect("crate not present in resolver")
1122     }
1123
1124     pub fn name(self) -> Name {
1125         self.inner.as_name()
1126     }
1127 }
1128
1129 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1130 pub struct MacroDef {
1131     pub(crate) id: MacroDefId,
1132 }
1133
1134 impl MacroDef {
1135     /// FIXME: right now, this just returns the root module of the crate that
1136     /// defines this macro. The reasons for this is that macros are expanded
1137     /// early, in `hir_expand`, where modules simply do not exist yet.
1138     pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1139         let krate = self.id.krate;
1140         let def_map = db.crate_def_map(krate);
1141         let module_id = def_map.root();
1142         Some(Module { id: def_map.module_id(module_id) })
1143     }
1144
1145     /// XXX: this parses the file
1146     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1147         self.source(db)?.value.name().map(|it| it.as_name())
1148     }
1149
1150     /// Indicate it is a proc-macro
1151     pub fn is_proc_macro(&self) -> bool {
1152         matches!(self.id.kind, MacroDefKind::ProcMacro(_))
1153     }
1154
1155     /// Indicate it is a derive macro
1156     pub fn is_derive_macro(&self) -> bool {
1157         // FIXME: wrong for `ProcMacro`
1158         matches!(self.id.kind, MacroDefKind::ProcMacro(..) | MacroDefKind::BuiltInDerive(..))
1159     }
1160 }
1161
1162 /// Invariant: `inner.as_assoc_item(db).is_some()`
1163 /// We do not actively enforce this invariant.
1164 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1165 pub enum AssocItem {
1166     Function(Function),
1167     Const(Const),
1168     TypeAlias(TypeAlias),
1169 }
1170 #[derive(Debug)]
1171 pub enum AssocItemContainer {
1172     Trait(Trait),
1173     Impl(Impl),
1174 }
1175 pub trait AsAssocItem {
1176     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1177 }
1178
1179 impl AsAssocItem for Function {
1180     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1181         as_assoc_item(db, AssocItem::Function, self.id)
1182     }
1183 }
1184 impl AsAssocItem for Const {
1185     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1186         as_assoc_item(db, AssocItem::Const, self.id)
1187     }
1188 }
1189 impl AsAssocItem for TypeAlias {
1190     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1191         as_assoc_item(db, AssocItem::TypeAlias, self.id)
1192     }
1193 }
1194 impl AsAssocItem for ModuleDef {
1195     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1196         match self {
1197             ModuleDef::Function(it) => it.as_assoc_item(db),
1198             ModuleDef::Const(it) => it.as_assoc_item(db),
1199             ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1200             _ => None,
1201         }
1202     }
1203 }
1204 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1205 where
1206     ID: Lookup<Data = AssocItemLoc<AST>>,
1207     DEF: From<ID>,
1208     CTOR: FnOnce(DEF) -> AssocItem,
1209     AST: ItemTreeNode,
1210 {
1211     match id.lookup(db.upcast()).container {
1212         AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1213         AssocContainerId::ModuleId(_) => None,
1214     }
1215 }
1216
1217 impl AssocItem {
1218     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1219         match self {
1220             AssocItem::Function(it) => Some(it.name(db)),
1221             AssocItem::Const(it) => it.name(db),
1222             AssocItem::TypeAlias(it) => Some(it.name(db)),
1223         }
1224     }
1225     pub fn module(self, db: &dyn HirDatabase) -> Module {
1226         match self {
1227             AssocItem::Function(f) => f.module(db),
1228             AssocItem::Const(c) => c.module(db),
1229             AssocItem::TypeAlias(t) => t.module(db),
1230         }
1231     }
1232     pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1233         let container = match self {
1234             AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1235             AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1236             AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1237         };
1238         match container {
1239             AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1240             AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1241             AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1242         }
1243     }
1244
1245     pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1246         match self.container(db) {
1247             AssocItemContainer::Trait(t) => Some(t),
1248             _ => None,
1249         }
1250     }
1251 }
1252
1253 impl HasVisibility for AssocItem {
1254     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1255         match self {
1256             AssocItem::Function(f) => f.visibility(db),
1257             AssocItem::Const(c) => c.visibility(db),
1258             AssocItem::TypeAlias(t) => t.visibility(db),
1259         }
1260     }
1261 }
1262
1263 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1264 pub enum GenericDef {
1265     Function(Function),
1266     Adt(Adt),
1267     Trait(Trait),
1268     TypeAlias(TypeAlias),
1269     Impl(Impl),
1270     // enum variants cannot have generics themselves, but their parent enums
1271     // can, and this makes some code easier to write
1272     Variant(Variant),
1273     // consts can have type parameters from their parents (i.e. associated consts of traits)
1274     Const(Const),
1275 }
1276 impl_from!(
1277     Function,
1278     Adt(Struct, Enum, Union),
1279     Trait,
1280     TypeAlias,
1281     Impl,
1282     Variant,
1283     Const
1284     for GenericDef
1285 );
1286
1287 impl GenericDef {
1288     pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1289         let generics = db.generic_params(self.into());
1290         let ty_params = generics
1291             .types
1292             .iter()
1293             .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1294             .map(GenericParam::TypeParam);
1295         let lt_params = generics
1296             .lifetimes
1297             .iter()
1298             .map(|(local_id, _)| LifetimeParam {
1299                 id: LifetimeParamId { parent: self.into(), local_id },
1300             })
1301             .map(GenericParam::LifetimeParam);
1302         let const_params = generics
1303             .consts
1304             .iter()
1305             .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1306             .map(GenericParam::ConstParam);
1307         ty_params.chain(lt_params).chain(const_params).collect()
1308     }
1309
1310     pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1311         let generics = db.generic_params(self.into());
1312         generics
1313             .types
1314             .iter()
1315             .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1316             .collect()
1317     }
1318 }
1319
1320 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1321 pub struct Local {
1322     pub(crate) parent: DefWithBodyId,
1323     pub(crate) pat_id: PatId,
1324 }
1325
1326 impl Local {
1327     pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1328         let src = self.source(db);
1329         match src.value {
1330             Either::Left(bind_pat) => {
1331                 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1332             }
1333             Either::Right(_self_param) => true,
1334         }
1335     }
1336
1337     // FIXME: why is this an option? It shouldn't be?
1338     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1339         let body = db.body(self.parent);
1340         match &body[self.pat_id] {
1341             Pat::Bind { name, .. } => Some(name.clone()),
1342             _ => None,
1343         }
1344     }
1345
1346     pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1347         self.name(db) == Some(name![self])
1348     }
1349
1350     pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1351         let body = db.body(self.parent);
1352         matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1353     }
1354
1355     pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1356         self.parent.into()
1357     }
1358
1359     pub fn module(self, db: &dyn HirDatabase) -> Module {
1360         self.parent(db).module(db)
1361     }
1362
1363     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1364         let def = self.parent;
1365         let infer = db.infer(def);
1366         let ty = infer[self.pat_id].clone();
1367         let krate = def.module(db.upcast()).krate();
1368         Type::new(db, krate, def, ty)
1369     }
1370
1371     pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1372         let (_body, source_map) = db.body_with_source_map(self.parent);
1373         let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1374         let root = src.file_syntax(db.upcast());
1375         src.map(|ast| {
1376             ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1377         })
1378     }
1379 }
1380
1381 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1382 pub struct Label {
1383     pub(crate) parent: DefWithBodyId,
1384     pub(crate) label_id: LabelId,
1385 }
1386
1387 impl Label {
1388     pub fn module(self, db: &dyn HirDatabase) -> Module {
1389         self.parent(db).module(db)
1390     }
1391
1392     pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1393         self.parent.into()
1394     }
1395
1396     pub fn name(self, db: &dyn HirDatabase) -> Name {
1397         let body = db.body(self.parent);
1398         body[self.label_id].name.clone()
1399     }
1400
1401     pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1402         let (_body, source_map) = db.body_with_source_map(self.parent);
1403         let src = source_map.label_syntax(self.label_id);
1404         let root = src.file_syntax(db.upcast());
1405         src.map(|ast| ast.to_node(&root))
1406     }
1407 }
1408
1409 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1410 pub enum GenericParam {
1411     TypeParam(TypeParam),
1412     LifetimeParam(LifetimeParam),
1413     ConstParam(ConstParam),
1414 }
1415 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1416
1417 impl GenericParam {
1418     pub fn module(self, db: &dyn HirDatabase) -> Module {
1419         match self {
1420             GenericParam::TypeParam(it) => it.module(db),
1421             GenericParam::LifetimeParam(it) => it.module(db),
1422             GenericParam::ConstParam(it) => it.module(db),
1423         }
1424     }
1425
1426     pub fn name(self, db: &dyn HirDatabase) -> Name {
1427         match self {
1428             GenericParam::TypeParam(it) => it.name(db),
1429             GenericParam::LifetimeParam(it) => it.name(db),
1430             GenericParam::ConstParam(it) => it.name(db),
1431         }
1432     }
1433 }
1434
1435 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1436 pub struct TypeParam {
1437     pub(crate) id: TypeParamId,
1438 }
1439
1440 impl TypeParam {
1441     pub fn name(self, db: &dyn HirDatabase) -> Name {
1442         let params = db.generic_params(self.id.parent);
1443         params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1444     }
1445
1446     pub fn module(self, db: &dyn HirDatabase) -> Module {
1447         self.id.parent.module(db.upcast()).into()
1448     }
1449
1450     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1451         let resolver = self.id.parent.resolver(db.upcast());
1452         let krate = self.id.parent.module(db.upcast()).krate();
1453         let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1454         Type::new_with_resolver_inner(db, krate, &resolver, ty)
1455     }
1456
1457     pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1458         db.generic_predicates_for_param(self.id)
1459             .into_iter()
1460             .filter_map(|pred| match &pred.value {
1461                 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1462                     Some(Trait::from(trait_ref.trait_))
1463                 }
1464                 _ => None,
1465             })
1466             .collect()
1467     }
1468
1469     pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1470         let params = db.generic_defaults(self.id.parent);
1471         let local_idx = hir_ty::param_idx(db, self.id)?;
1472         let resolver = self.id.parent.resolver(db.upcast());
1473         let krate = self.id.parent.module(db.upcast()).krate();
1474         let ty = params.get(local_idx)?.clone();
1475         let subst = Substitution::type_params(db, self.id.parent);
1476         let ty = ty.subst(&subst.prefix(local_idx));
1477         Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1478     }
1479 }
1480
1481 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1482 pub struct LifetimeParam {
1483     pub(crate) id: LifetimeParamId,
1484 }
1485
1486 impl LifetimeParam {
1487     pub fn name(self, db: &dyn HirDatabase) -> Name {
1488         let params = db.generic_params(self.id.parent);
1489         params.lifetimes[self.id.local_id].name.clone()
1490     }
1491
1492     pub fn module(self, db: &dyn HirDatabase) -> Module {
1493         self.id.parent.module(db.upcast()).into()
1494     }
1495
1496     pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1497         self.id.parent.into()
1498     }
1499 }
1500
1501 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1502 pub struct ConstParam {
1503     pub(crate) id: ConstParamId,
1504 }
1505
1506 impl ConstParam {
1507     pub fn name(self, db: &dyn HirDatabase) -> Name {
1508         let params = db.generic_params(self.id.parent);
1509         params.consts[self.id.local_id].name.clone()
1510     }
1511
1512     pub fn module(self, db: &dyn HirDatabase) -> Module {
1513         self.id.parent.module(db.upcast()).into()
1514     }
1515
1516     pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1517         self.id.parent.into()
1518     }
1519
1520     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1521         let def = self.id.parent;
1522         let krate = def.module(db.upcast()).krate();
1523         Type::new(db, krate, def, db.const_param_ty(self.id))
1524     }
1525 }
1526
1527 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1528 pub struct Impl {
1529     pub(crate) id: ImplId,
1530 }
1531
1532 impl Impl {
1533     pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1534         let inherent = db.inherent_impls_in_crate(krate.id);
1535         let trait_ = db.trait_impls_in_crate(krate.id);
1536
1537         inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1538     }
1539
1540     pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty }: Type) -> Vec<Impl> {
1541         let def_crates = match ty.value.def_crates(db, krate) {
1542             Some(def_crates) => def_crates,
1543             None => return Vec::new(),
1544         };
1545
1546         let filter = |impl_def: &Impl| {
1547             let target_ty = impl_def.target_ty(db);
1548             let rref = target_ty.remove_ref();
1549             ty.value.equals_ctor(rref.as_ref().map_or(&target_ty.ty.value, |it| &it.ty.value))
1550         };
1551
1552         let mut all = Vec::new();
1553         def_crates.iter().for_each(|&id| {
1554             all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
1555         });
1556         let fp = TyFingerprint::for_impl(&ty.value);
1557         for id in def_crates
1558             .iter()
1559             .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1560             .map(|Crate { id }| id)
1561             .chain(def_crates.iter().copied())
1562             .unique()
1563         {
1564             match fp {
1565                 Some(fp) => all.extend(
1566                     db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
1567                 ),
1568                 None => all
1569                     .extend(db.trait_impls_in_crate(id).all_impls().map(Self::from).filter(filter)),
1570             }
1571         }
1572         all
1573     }
1574
1575     pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1576         let krate = trait_.module(db).krate();
1577         let mut all = Vec::new();
1578         for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter().chain(Some(krate))
1579         {
1580             let impls = db.trait_impls_in_crate(id);
1581             all.extend(impls.for_trait(trait_.id).map(Self::from))
1582         }
1583         all
1584     }
1585
1586     // FIXME: the return type is wrong. This should be a hir version of
1587     // `TraitRef` (ie, resolved `TypeRef`).
1588     pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1589         db.impl_data(self.id).target_trait.clone()
1590     }
1591
1592     pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1593         let impl_data = db.impl_data(self.id);
1594         let resolver = self.id.resolver(db.upcast());
1595         let krate = self.id.lookup(db.upcast()).container.krate();
1596         let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1597         let ty = ctx.lower_ty(&impl_data.target_type);
1598         Type::new_with_resolver_inner(db, krate, &resolver, ty)
1599     }
1600
1601     pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1602         db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1603     }
1604
1605     pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1606         db.impl_data(self.id).is_negative
1607     }
1608
1609     pub fn module(self, db: &dyn HirDatabase) -> Module {
1610         self.id.lookup(db.upcast()).container.into()
1611     }
1612
1613     pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1614         Crate { id: self.module(db).id.krate() }
1615     }
1616
1617     pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1618         let src = self.source(db)?;
1619         let item = src.file_id.is_builtin_derive(db.upcast())?;
1620         let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1621
1622         // FIXME: handle `cfg_attr`
1623         let attr = item
1624             .value
1625             .attrs()
1626             .filter_map(|it| {
1627                 let path = ModPath::from_src(it.path()?, &hygenic)?;
1628                 if path.as_ident()?.to_string() == "derive" {
1629                     Some(it)
1630                 } else {
1631                     None
1632                 }
1633             })
1634             .last()?;
1635
1636         Some(item.with_value(attr))
1637     }
1638 }
1639
1640 #[derive(Clone, PartialEq, Eq, Debug)]
1641 pub struct Type {
1642     krate: CrateId,
1643     ty: InEnvironment<Ty>,
1644 }
1645
1646 impl Type {
1647     pub(crate) fn new_with_resolver(
1648         db: &dyn HirDatabase,
1649         resolver: &Resolver,
1650         ty: Ty,
1651     ) -> Option<Type> {
1652         let krate = resolver.krate()?;
1653         Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1654     }
1655     pub(crate) fn new_with_resolver_inner(
1656         db: &dyn HirDatabase,
1657         krate: CrateId,
1658         resolver: &Resolver,
1659         ty: Ty,
1660     ) -> Type {
1661         let environment =
1662             resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1663         Type { krate, ty: InEnvironment { value: ty, environment } }
1664     }
1665
1666     fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1667         let resolver = lexical_env.resolver(db.upcast());
1668         let environment =
1669             resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1670         Type { krate, ty: InEnvironment { value: ty, environment } }
1671     }
1672
1673     fn from_def(
1674         db: &dyn HirDatabase,
1675         krate: CrateId,
1676         def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1677     ) -> Type {
1678         let substs = Substitution::build_for_def(db, def).fill_with_unknown().build();
1679         let ty = db.ty(def.into()).subst(&substs);
1680         Type::new(db, krate, def, ty)
1681     }
1682
1683     pub fn is_unit(&self) -> bool {
1684         matches!(self.ty.value.interned(&Interner), TyKind::Tuple(0, ..))
1685     }
1686     pub fn is_bool(&self) -> bool {
1687         matches!(self.ty.value.interned(&Interner), TyKind::Scalar(Scalar::Bool))
1688     }
1689
1690     pub fn is_mutable_reference(&self) -> bool {
1691         matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1692     }
1693
1694     pub fn is_usize(&self) -> bool {
1695         matches!(self.ty.value.interned(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1696     }
1697
1698     pub fn remove_ref(&self) -> Option<Type> {
1699         match &self.ty.value.interned(&Interner) {
1700             TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
1701             _ => None,
1702         }
1703     }
1704
1705     pub fn is_unknown(&self) -> bool {
1706         self.ty.value.is_unknown()
1707     }
1708
1709     /// Checks that particular type `ty` implements `std::future::Future`.
1710     /// This function is used in `.await` syntax completion.
1711     pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1712         // No special case for the type of async block, since Chalk can figure it out.
1713
1714         let krate = self.krate;
1715
1716         let std_future_trait =
1717             db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1718         let std_future_trait = match std_future_trait {
1719             Some(it) => it,
1720             None => return false,
1721         };
1722
1723         let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1724         method_resolution::implements_trait(
1725             &canonical_ty,
1726             db,
1727             self.ty.environment.clone(),
1728             krate,
1729             std_future_trait,
1730         )
1731     }
1732
1733     /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1734     ///
1735     /// This function can be used to check if a particular type is callable, since FnOnce is a
1736     /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1737     pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1738         let krate = self.krate;
1739
1740         let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1741             Some(it) => it,
1742             None => return false,
1743         };
1744
1745         let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1746         method_resolution::implements_trait_unique(
1747             &canonical_ty,
1748             db,
1749             self.ty.environment.clone(),
1750             krate,
1751             fnonce_trait,
1752         )
1753     }
1754
1755     pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1756         let trait_ref = hir_ty::TraitRef {
1757             trait_: trait_.id,
1758             substs: Substitution::build_for_def(db, trait_.id)
1759                 .push(self.ty.value.clone())
1760                 .fill(args.iter().map(|t| t.ty.value.clone()))
1761                 .build(),
1762         };
1763
1764         let goal = Canonical {
1765             value: hir_ty::InEnvironment::new(
1766                 self.ty.environment.clone(),
1767                 hir_ty::Obligation::Trait(trait_ref),
1768             ),
1769             kinds: Arc::new([]),
1770         };
1771
1772         db.trait_solve(self.krate, goal).is_some()
1773     }
1774
1775     pub fn normalize_trait_assoc_type(
1776         &self,
1777         db: &dyn HirDatabase,
1778         trait_: Trait,
1779         args: &[Type],
1780         alias: TypeAlias,
1781     ) -> Option<Type> {
1782         let subst = Substitution::build_for_def(db, trait_.id)
1783             .push(self.ty.value.clone())
1784             .fill(args.iter().map(|t| t.ty.value.clone()))
1785             .build();
1786         let predicate = ProjectionPredicate {
1787             projection_ty: ProjectionTy {
1788                 associated_ty_id: to_assoc_type_id(alias.id),
1789                 substitution: subst,
1790             },
1791             ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner),
1792         };
1793         let goal = Canonical {
1794             value: InEnvironment::new(
1795                 self.ty.environment.clone(),
1796                 Obligation::Projection(predicate),
1797             ),
1798             kinds: Arc::new([TyVariableKind::General]),
1799         };
1800
1801         match db.trait_solve(self.krate, goal)? {
1802             Solution::Unique(SolutionVariables(subst)) => {
1803                 subst.value.first().map(|ty| self.derived(ty.clone()))
1804             }
1805             Solution::Ambig(_) => None,
1806         }
1807     }
1808
1809     pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1810         let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1811         let copy_trait = match lang_item {
1812             Some(LangItemTarget::TraitId(it)) => it,
1813             _ => return false,
1814         };
1815         self.impls_trait(db, copy_trait.into(), &[])
1816     }
1817
1818     pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1819         let def = self.ty.value.callable_def(db);
1820
1821         let sig = self.ty.value.callable_sig(db)?;
1822         Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1823     }
1824
1825     pub fn is_closure(&self) -> bool {
1826         matches!(&self.ty.value.interned(&Interner), TyKind::Closure { .. })
1827     }
1828
1829     pub fn is_fn(&self) -> bool {
1830         matches!(&self.ty.value.interned(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1831     }
1832
1833     pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1834         let adt_id = match self.ty.value.interned(&Interner) {
1835             &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1836             _ => return false,
1837         };
1838
1839         let adt = adt_id.into();
1840         match adt {
1841             Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1842             _ => false,
1843         }
1844     }
1845
1846     pub fn is_raw_ptr(&self) -> bool {
1847         matches!(&self.ty.value.interned(&Interner), TyKind::Raw(..))
1848     }
1849
1850     pub fn contains_unknown(&self) -> bool {
1851         return go(&self.ty.value);
1852
1853         fn go(ty: &Ty) -> bool {
1854             match ty.interned(&Interner) {
1855                 TyKind::Unknown => true,
1856
1857                 TyKind::Adt(_, substs)
1858                 | TyKind::AssociatedType(_, substs)
1859                 | TyKind::Tuple(_, substs)
1860                 | TyKind::OpaqueType(_, substs)
1861                 | TyKind::FnDef(_, substs)
1862                 | TyKind::Closure(_, substs) => substs.iter().any(go),
1863
1864                 TyKind::Array(ty) | TyKind::Slice(ty) | TyKind::Raw(_, ty) | TyKind::Ref(_, ty) => {
1865                     go(ty)
1866                 }
1867
1868                 TyKind::Scalar(_)
1869                 | TyKind::Str
1870                 | TyKind::Never
1871                 | TyKind::Placeholder(_)
1872                 | TyKind::BoundVar(_)
1873                 | TyKind::InferenceVar(_, _)
1874                 | TyKind::Dyn(_)
1875                 | TyKind::Function(_)
1876                 | TyKind::Alias(_)
1877                 | TyKind::ForeignType(_) => false,
1878             }
1879         }
1880     }
1881
1882     pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1883         let (variant_id, substs) = match self.ty.value.interned(&Interner) {
1884             &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1885             &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1886             _ => return Vec::new(),
1887         };
1888
1889         db.field_types(variant_id)
1890             .iter()
1891             .map(|(local_id, ty)| {
1892                 let def = Field { parent: variant_id.into(), id: local_id };
1893                 let ty = ty.clone().subst(substs);
1894                 (def, self.derived(ty))
1895             })
1896             .collect()
1897     }
1898
1899     pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1900         if let TyKind::Tuple(_, substs) = &self.ty.value.interned(&Interner) {
1901             substs.iter().map(|ty| self.derived(ty.clone())).collect()
1902         } else {
1903             Vec::new()
1904         }
1905     }
1906
1907     pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1908         // There should be no inference vars in types passed here
1909         // FIXME check that?
1910         let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1911         let environment = self.ty.environment.clone();
1912         let ty = InEnvironment { value: canonical, environment };
1913         autoderef(db, Some(self.krate), ty)
1914             .map(|canonical| canonical.value)
1915             .map(move |ty| self.derived(ty))
1916     }
1917
1918     // This would be nicer if it just returned an iterator, but that runs into
1919     // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1920     pub fn iterate_assoc_items<T>(
1921         self,
1922         db: &dyn HirDatabase,
1923         krate: Crate,
1924         mut callback: impl FnMut(AssocItem) -> Option<T>,
1925     ) -> Option<T> {
1926         for krate in self.ty.value.def_crates(db, krate.id)? {
1927             let impls = db.inherent_impls_in_crate(krate);
1928
1929             for impl_def in impls.for_self_ty(&self.ty.value) {
1930                 for &item in db.impl_data(*impl_def).items.iter() {
1931                     if let Some(result) = callback(item.into()) {
1932                         return Some(result);
1933                     }
1934                 }
1935             }
1936         }
1937         None
1938     }
1939
1940     pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1941         self.ty
1942             .value
1943             .strip_references()
1944             .substs()
1945             .into_iter()
1946             .flat_map(|substs| substs.iter())
1947             .map(move |ty| self.derived(ty.clone()))
1948     }
1949
1950     pub fn iterate_method_candidates<T>(
1951         &self,
1952         db: &dyn HirDatabase,
1953         krate: Crate,
1954         traits_in_scope: &FxHashSet<TraitId>,
1955         name: Option<&Name>,
1956         mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1957     ) -> Option<T> {
1958         // There should be no inference vars in types passed here
1959         // FIXME check that?
1960         // FIXME replace Unknown by bound vars here
1961         let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1962
1963         let env = self.ty.environment.clone();
1964         let krate = krate.id;
1965
1966         method_resolution::iterate_method_candidates(
1967             &canonical,
1968             db,
1969             env,
1970             krate,
1971             traits_in_scope,
1972             name,
1973             method_resolution::LookupMode::MethodCall,
1974             |ty, it| match it {
1975                 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1976                 _ => None,
1977             },
1978         )
1979     }
1980
1981     pub fn iterate_path_candidates<T>(
1982         &self,
1983         db: &dyn HirDatabase,
1984         krate: Crate,
1985         traits_in_scope: &FxHashSet<TraitId>,
1986         name: Option<&Name>,
1987         mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1988     ) -> Option<T> {
1989         // There should be no inference vars in types passed here
1990         // FIXME check that?
1991         // FIXME replace Unknown by bound vars here
1992         let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1993
1994         let env = self.ty.environment.clone();
1995         let krate = krate.id;
1996
1997         method_resolution::iterate_method_candidates(
1998             &canonical,
1999             db,
2000             env,
2001             krate,
2002             traits_in_scope,
2003             name,
2004             method_resolution::LookupMode::Path,
2005             |ty, it| callback(ty, it.into()),
2006         )
2007     }
2008
2009     pub fn as_adt(&self) -> Option<Adt> {
2010         let (adt, _subst) = self.ty.value.as_adt()?;
2011         Some(adt.into())
2012     }
2013
2014     pub fn as_dyn_trait(&self) -> Option<Trait> {
2015         self.ty.value.dyn_trait().map(Into::into)
2016     }
2017
2018     pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2019         self.ty.value.impl_trait_bounds(db).map(|it| {
2020             it.into_iter()
2021                 .filter_map(|pred| match pred {
2022                     hir_ty::GenericPredicate::Implemented(trait_ref) => {
2023                         Some(Trait::from(trait_ref.trait_))
2024                     }
2025                     _ => None,
2026                 })
2027                 .collect()
2028         })
2029     }
2030
2031     pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2032         self.ty.value.associated_type_parent_trait(db).map(Into::into)
2033     }
2034
2035     fn derived(&self, ty: Ty) -> Type {
2036         Type {
2037             krate: self.krate,
2038             ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
2039         }
2040     }
2041
2042     pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2043         // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2044         // We need a different order here.
2045
2046         fn walk_substs(
2047             db: &dyn HirDatabase,
2048             type_: &Type,
2049             substs: &Substitution,
2050             cb: &mut impl FnMut(Type),
2051         ) {
2052             for ty in substs.iter() {
2053                 walk_type(db, &type_.derived(ty.clone()), cb);
2054             }
2055         }
2056
2057         fn walk_bounds(
2058             db: &dyn HirDatabase,
2059             type_: &Type,
2060             bounds: &[GenericPredicate],
2061             cb: &mut impl FnMut(Type),
2062         ) {
2063             for pred in bounds {
2064                 match pred {
2065                     GenericPredicate::Implemented(trait_ref) => {
2066                         cb(type_.clone());
2067                         walk_substs(db, type_, &trait_ref.substs, cb);
2068                     }
2069                     _ => (),
2070                 }
2071             }
2072         }
2073
2074         fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2075             let ty = type_.ty.value.strip_references();
2076             match ty.interned(&Interner) {
2077                 TyKind::Adt(..) => {
2078                     cb(type_.derived(ty.clone()));
2079                 }
2080                 TyKind::AssociatedType(..) => {
2081                     if let Some(_) = ty.associated_type_parent_trait(db) {
2082                         cb(type_.derived(ty.clone()));
2083                     }
2084                 }
2085                 TyKind::OpaqueType(..) => {
2086                     if let Some(bounds) = ty.impl_trait_bounds(db) {
2087                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2088                     }
2089                 }
2090                 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2091                     if let Some(bounds) = ty.impl_trait_bounds(db) {
2092                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2093                     }
2094
2095                     walk_substs(db, type_, &opaque_ty.substitution, cb);
2096                 }
2097                 TyKind::Placeholder(_) => {
2098                     if let Some(bounds) = ty.impl_trait_bounds(db) {
2099                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2100                     }
2101                 }
2102                 TyKind::Dyn(bounds) => {
2103                     walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
2104                 }
2105
2106                 TyKind::Ref(_, ty) | TyKind::Raw(_, ty) | TyKind::Array(ty) | TyKind::Slice(ty) => {
2107                     walk_type(db, &type_.derived(ty.clone()), cb);
2108                 }
2109
2110                 _ => {}
2111             }
2112             if let Some(substs) = ty.substs() {
2113                 walk_substs(db, type_, &substs, cb);
2114             }
2115         }
2116
2117         walk_type(db, self, &mut cb);
2118     }
2119 }
2120
2121 // FIXME: closures
2122 #[derive(Debug)]
2123 pub struct Callable {
2124     ty: Type,
2125     sig: CallableSig,
2126     def: Option<CallableDefId>,
2127     pub(crate) is_bound_method: bool,
2128 }
2129
2130 pub enum CallableKind {
2131     Function(Function),
2132     TupleStruct(Struct),
2133     TupleEnumVariant(Variant),
2134     Closure,
2135 }
2136
2137 impl Callable {
2138     pub fn kind(&self) -> CallableKind {
2139         match self.def {
2140             Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2141             Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2142             Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2143             None => CallableKind::Closure,
2144         }
2145     }
2146     pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2147         let func = match self.def {
2148             Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2149             _ => return None,
2150         };
2151         let src = func.lookup(db.upcast()).source(db.upcast());
2152         let param_list = src.value.param_list()?;
2153         param_list.self_param()
2154     }
2155     pub fn n_params(&self) -> usize {
2156         self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2157     }
2158     pub fn params(
2159         &self,
2160         db: &dyn HirDatabase,
2161     ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2162         let types = self
2163             .sig
2164             .params()
2165             .iter()
2166             .skip(if self.is_bound_method { 1 } else { 0 })
2167             .map(|ty| self.ty.derived(ty.clone()));
2168         let patterns = match self.def {
2169             Some(CallableDefId::FunctionId(func)) => {
2170                 let src = func.lookup(db.upcast()).source(db.upcast());
2171                 src.value.param_list().map(|param_list| {
2172                     param_list
2173                         .self_param()
2174                         .map(|it| Some(Either::Left(it)))
2175                         .filter(|_| !self.is_bound_method)
2176                         .into_iter()
2177                         .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2178                 })
2179             }
2180             _ => None,
2181         };
2182         patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2183     }
2184     pub fn return_type(&self) -> Type {
2185         self.ty.derived(self.sig.ret().clone())
2186     }
2187 }
2188
2189 /// For IDE only
2190 #[derive(Debug, PartialEq, Eq, Hash)]
2191 pub enum ScopeDef {
2192     ModuleDef(ModuleDef),
2193     MacroDef(MacroDef),
2194     GenericParam(GenericParam),
2195     ImplSelfType(Impl),
2196     AdtSelfType(Adt),
2197     Local(Local),
2198     Unknown,
2199 }
2200
2201 impl ScopeDef {
2202     pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2203         let mut items = ArrayVec::new();
2204
2205         match (def.take_types(), def.take_values()) {
2206             (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2207             (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2208             (Some(m1), Some(m2)) => {
2209                 // Some items, like unit structs and enum variants, are
2210                 // returned as both a type and a value. Here we want
2211                 // to de-duplicate them.
2212                 if m1 != m2 {
2213                     items.push(ScopeDef::ModuleDef(m1.into()));
2214                     items.push(ScopeDef::ModuleDef(m2.into()));
2215                 } else {
2216                     items.push(ScopeDef::ModuleDef(m1.into()));
2217                 }
2218             }
2219             (None, None) => {}
2220         };
2221
2222         if let Some(macro_def_id) = def.take_macros() {
2223             items.push(ScopeDef::MacroDef(macro_def_id.into()));
2224         }
2225
2226         if items.is_empty() {
2227             items.push(ScopeDef::Unknown);
2228         }
2229
2230         items
2231     }
2232 }
2233
2234 impl From<ItemInNs> for ScopeDef {
2235     fn from(item: ItemInNs) -> Self {
2236         match item {
2237             ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2238             ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2239             ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2240         }
2241     }
2242 }
2243
2244 pub trait HasVisibility {
2245     fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2246     fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2247         let vis = self.visibility(db);
2248         vis.is_visible_from(db.upcast(), module.id)
2249     }
2250 }