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