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