]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/lib.rs
Use hir formatter more
[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 impl HasVisibility for Struct {
576     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
577         db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
578     }
579 }
580
581 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
582 pub struct Union {
583     pub(crate) id: UnionId,
584 }
585
586 impl Union {
587     pub fn name(self, db: &dyn HirDatabase) -> Name {
588         db.union_data(self.id).name.clone()
589     }
590
591     pub fn module(self, db: &dyn HirDatabase) -> Module {
592         Module { id: self.id.lookup(db.upcast()).container }
593     }
594
595     pub fn ty(self, db: &dyn HirDatabase) -> Type {
596         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
597     }
598
599     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
600         db.union_data(self.id)
601             .variant_data
602             .fields()
603             .iter()
604             .map(|(id, _)| Field { parent: self.into(), id })
605             .collect()
606     }
607
608     fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
609         db.union_data(self.id).variant_data.clone()
610     }
611 }
612
613 impl HasVisibility for Union {
614     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
615         db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
616     }
617 }
618
619 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
620 pub struct Enum {
621     pub(crate) id: EnumId,
622 }
623
624 impl Enum {
625     pub fn module(self, db: &dyn HirDatabase) -> Module {
626         Module { id: self.id.lookup(db.upcast()).container }
627     }
628
629     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
630         Some(self.module(db).krate())
631     }
632
633     pub fn name(self, db: &dyn HirDatabase) -> Name {
634         db.enum_data(self.id).name.clone()
635     }
636
637     pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
638         db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
639     }
640
641     pub fn ty(self, db: &dyn HirDatabase) -> Type {
642         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
643     }
644 }
645
646 impl HasVisibility for Enum {
647     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
648         db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
649     }
650 }
651
652 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
653 pub struct Variant {
654     pub(crate) parent: Enum,
655     pub(crate) id: LocalEnumVariantId,
656 }
657
658 impl Variant {
659     pub fn module(self, db: &dyn HirDatabase) -> Module {
660         self.parent.module(db)
661     }
662     pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
663         self.parent
664     }
665
666     pub fn name(self, db: &dyn HirDatabase) -> Name {
667         db.enum_data(self.parent.id).variants[self.id].name.clone()
668     }
669
670     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
671         self.variant_data(db)
672             .fields()
673             .iter()
674             .map(|(id, _)| Field { parent: self.into(), id })
675             .collect()
676     }
677
678     pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
679         self.variant_data(db).kind()
680     }
681
682     pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
683         db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
684     }
685 }
686
687 /// A Data Type
688 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
689 pub enum Adt {
690     Struct(Struct),
691     Union(Union),
692     Enum(Enum),
693 }
694 impl_from!(Struct, Union, Enum for Adt);
695
696 impl Adt {
697     pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
698         let subst = db.generic_defaults(self.into());
699         subst.iter().any(|ty| ty.value.is_unknown())
700     }
701
702     /// Turns this ADT into a type. Any type parameters of the ADT will be
703     /// turned into unknown types, which is good for e.g. finding the most
704     /// general set of completions, but will not look very nice when printed.
705     pub fn ty(self, db: &dyn HirDatabase) -> Type {
706         let id = AdtId::from(self);
707         Type::from_def(db, id.module(db.upcast()).krate(), id)
708     }
709
710     pub fn module(self, db: &dyn HirDatabase) -> Module {
711         match self {
712             Adt::Struct(s) => s.module(db),
713             Adt::Union(s) => s.module(db),
714             Adt::Enum(e) => e.module(db),
715         }
716     }
717
718     pub fn krate(self, db: &dyn HirDatabase) -> Crate {
719         self.module(db).krate()
720     }
721
722     pub fn name(self, db: &dyn HirDatabase) -> Name {
723         match self {
724             Adt::Struct(s) => s.name(db),
725             Adt::Union(u) => u.name(db),
726             Adt::Enum(e) => e.name(db),
727         }
728     }
729 }
730
731 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
732 pub enum VariantDef {
733     Struct(Struct),
734     Union(Union),
735     Variant(Variant),
736 }
737 impl_from!(Struct, Union, Variant for VariantDef);
738
739 impl VariantDef {
740     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
741         match self {
742             VariantDef::Struct(it) => it.fields(db),
743             VariantDef::Union(it) => it.fields(db),
744             VariantDef::Variant(it) => it.fields(db),
745         }
746     }
747
748     pub fn module(self, db: &dyn HirDatabase) -> Module {
749         match self {
750             VariantDef::Struct(it) => it.module(db),
751             VariantDef::Union(it) => it.module(db),
752             VariantDef::Variant(it) => it.module(db),
753         }
754     }
755
756     pub fn name(&self, db: &dyn HirDatabase) -> Name {
757         match self {
758             VariantDef::Struct(s) => s.name(db),
759             VariantDef::Union(u) => u.name(db),
760             VariantDef::Variant(e) => e.name(db),
761         }
762     }
763
764     pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
765         match self {
766             VariantDef::Struct(it) => it.variant_data(db),
767             VariantDef::Union(it) => it.variant_data(db),
768             VariantDef::Variant(it) => it.variant_data(db),
769         }
770     }
771 }
772
773 /// The defs which have a body.
774 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
775 pub enum DefWithBody {
776     Function(Function),
777     Static(Static),
778     Const(Const),
779 }
780 impl_from!(Function, Const, Static for DefWithBody);
781
782 impl DefWithBody {
783     pub fn module(self, db: &dyn HirDatabase) -> Module {
784         match self {
785             DefWithBody::Const(c) => c.module(db),
786             DefWithBody::Function(f) => f.module(db),
787             DefWithBody::Static(s) => s.module(db),
788         }
789     }
790
791     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
792         match self {
793             DefWithBody::Function(f) => Some(f.name(db)),
794             DefWithBody::Static(s) => s.name(db),
795             DefWithBody::Const(c) => c.name(db),
796         }
797     }
798 }
799
800 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
801 pub struct Function {
802     pub(crate) id: FunctionId,
803 }
804
805 impl Function {
806     pub fn module(self, db: &dyn HirDatabase) -> Module {
807         self.id.lookup(db.upcast()).module(db.upcast()).into()
808     }
809
810     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
811         Some(self.module(db).krate())
812     }
813
814     pub fn name(self, db: &dyn HirDatabase) -> Name {
815         db.function_data(self.id).name.clone()
816     }
817
818     /// Get this function's return type
819     pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
820         let resolver = self.id.resolver(db.upcast());
821         let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
822         let ret_type = &db.function_data(self.id).ret_type;
823         let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
824         let ty = ctx.lower_ty(ret_type);
825         Type::new_with_resolver_inner(db, krate, &resolver, ty)
826     }
827
828     pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
829         if !db.function_data(self.id).has_self_param {
830             return None;
831         }
832         Some(SelfParam { func: self.id })
833     }
834
835     pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
836         let resolver = self.id.resolver(db.upcast());
837         let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
838         let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
839         let environment = db.trait_environment(self.id.into());
840         db.function_data(self.id)
841             .params
842             .iter()
843             .enumerate()
844             .map(|(idx, type_ref)| {
845                 let ty = Type {
846                     krate,
847                     ty: InEnvironment {
848                         value: ctx.lower_ty(type_ref),
849                         environment: environment.clone(),
850                     },
851                 };
852                 Param { func: self, ty, idx }
853             })
854             .collect()
855     }
856     pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
857         if self.self_param(db).is_none() {
858             return None;
859         }
860         let mut res = self.assoc_fn_params(db);
861         res.remove(0);
862         Some(res)
863     }
864
865     pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
866         db.function_data(self.id).qualifier.is_unsafe
867     }
868
869     pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
870         let krate = self.module(db).id.krate();
871         hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
872         hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
873         hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
874     }
875
876     /// Whether this function declaration has a definition.
877     ///
878     /// This is false in the case of required (not provided) trait methods.
879     pub fn has_body(self, db: &dyn HirDatabase) -> bool {
880         db.function_data(self.id).has_body
881     }
882
883     /// A textual representation of the HIR of this function for debugging purposes.
884     pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
885         let body = db.body(self.id.into());
886
887         let mut result = String::new();
888         format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
889         for (id, expr) in body.exprs.iter() {
890             format_to!(result, "{:?}: {:?}\n", id, expr);
891         }
892
893         result
894     }
895 }
896
897 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
898 pub enum Access {
899     Shared,
900     Exclusive,
901     Owned,
902 }
903
904 impl From<hir_ty::Mutability> for Access {
905     fn from(mutability: hir_ty::Mutability) -> Access {
906         match mutability {
907             hir_ty::Mutability::Not => Access::Shared,
908             hir_ty::Mutability::Mut => Access::Exclusive,
909         }
910     }
911 }
912
913 #[derive(Debug)]
914 pub struct Param {
915     func: Function,
916     /// The index in parameter list, including self parameter.
917     idx: usize,
918     ty: Type,
919 }
920
921 impl Param {
922     pub fn ty(&self) -> &Type {
923         &self.ty
924     }
925
926     pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
927         let params = self.func.source(db)?.value.param_list()?;
928         if params.self_param().is_some() {
929             params.params().nth(self.idx.checked_sub(1)?)?.pat()
930         } else {
931             params.params().nth(self.idx)?.pat()
932         }
933     }
934 }
935
936 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
937 pub struct SelfParam {
938     func: FunctionId,
939 }
940
941 impl SelfParam {
942     pub fn access(self, db: &dyn HirDatabase) -> Access {
943         let func_data = db.function_data(self.func);
944         func_data
945             .params
946             .first()
947             .map(|param| match *param {
948                 TypeRef::Reference(.., mutability) => match mutability {
949                     hir_def::type_ref::Mutability::Shared => Access::Shared,
950                     hir_def::type_ref::Mutability::Mut => Access::Exclusive,
951                 },
952                 _ => Access::Owned,
953             })
954             .unwrap_or(Access::Owned)
955     }
956 }
957
958 impl HasVisibility for Function {
959     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
960         let function_data = db.function_data(self.id);
961         let visibility = &function_data.visibility;
962         visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
963     }
964 }
965
966 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
967 pub struct Const {
968     pub(crate) id: ConstId,
969 }
970
971 impl Const {
972     pub fn module(self, db: &dyn HirDatabase) -> Module {
973         Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
974     }
975
976     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
977         Some(self.module(db).krate())
978     }
979
980     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
981         db.const_data(self.id).name.clone()
982     }
983
984     pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
985         db.const_data(self.id).type_ref.clone()
986     }
987 }
988
989 impl HasVisibility for Const {
990     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
991         let function_data = db.const_data(self.id);
992         let visibility = &function_data.visibility;
993         visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
994     }
995 }
996
997 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
998 pub struct Static {
999     pub(crate) id: StaticId,
1000 }
1001
1002 impl Static {
1003     pub fn module(self, db: &dyn HirDatabase) -> Module {
1004         Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1005     }
1006
1007     pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1008         Some(self.module(db).krate())
1009     }
1010
1011     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1012         db.static_data(self.id).name.clone()
1013     }
1014
1015     pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1016         db.static_data(self.id).mutable
1017     }
1018 }
1019
1020 impl HasVisibility for Static {
1021     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1022         db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1023     }
1024 }
1025
1026 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1027 pub struct Trait {
1028     pub(crate) id: TraitId,
1029 }
1030
1031 impl Trait {
1032     pub fn module(self, db: &dyn HirDatabase) -> Module {
1033         Module { id: self.id.lookup(db.upcast()).container }
1034     }
1035
1036     pub fn name(self, db: &dyn HirDatabase) -> Name {
1037         db.trait_data(self.id).name.clone()
1038     }
1039
1040     pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1041         db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1042     }
1043
1044     pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1045         db.trait_data(self.id).is_auto
1046     }
1047 }
1048
1049 impl HasVisibility for Trait {
1050     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1051         db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1052     }
1053 }
1054
1055 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1056 pub struct TypeAlias {
1057     pub(crate) id: TypeAliasId,
1058 }
1059
1060 impl TypeAlias {
1061     pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1062         let subst = db.generic_defaults(self.id.into());
1063         subst.iter().any(|ty| ty.value.is_unknown())
1064     }
1065
1066     pub fn module(self, db: &dyn HirDatabase) -> Module {
1067         Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1068     }
1069
1070     pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1071         self.module(db).krate()
1072     }
1073
1074     pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1075         db.type_alias_data(self.id).type_ref.clone()
1076     }
1077
1078     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1079         Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1080     }
1081
1082     pub fn name(self, db: &dyn HirDatabase) -> Name {
1083         db.type_alias_data(self.id).name.clone()
1084     }
1085 }
1086
1087 impl HasVisibility for TypeAlias {
1088     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1089         let function_data = db.type_alias_data(self.id);
1090         let visibility = &function_data.visibility;
1091         visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1092     }
1093 }
1094
1095 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1096 pub struct BuiltinType {
1097     pub(crate) inner: hir_def::builtin_type::BuiltinType,
1098 }
1099
1100 impl BuiltinType {
1101     pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1102         let resolver = module.id.resolver(db.upcast());
1103         Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1104             .expect("crate not present in resolver")
1105     }
1106
1107     pub fn name(self) -> Name {
1108         self.inner.as_name()
1109     }
1110 }
1111
1112 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1113 pub struct MacroDef {
1114     pub(crate) id: MacroDefId,
1115 }
1116
1117 impl MacroDef {
1118     /// FIXME: right now, this just returns the root module of the crate that
1119     /// defines this macro. The reasons for this is that macros are expanded
1120     /// early, in `hir_expand`, where modules simply do not exist yet.
1121     pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1122         let krate = self.id.krate;
1123         let def_map = db.crate_def_map(krate);
1124         let module_id = def_map.root();
1125         Some(Module { id: def_map.module_id(module_id) })
1126     }
1127
1128     /// XXX: this parses the file
1129     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1130         self.source(db)?.value.name().map(|it| it.as_name())
1131     }
1132
1133     /// Indicate it is a proc-macro
1134     pub fn is_proc_macro(&self) -> bool {
1135         matches!(self.id.kind, MacroDefKind::ProcMacro(_))
1136     }
1137
1138     /// Indicate it is a derive macro
1139     pub fn is_derive_macro(&self) -> bool {
1140         matches!(self.id.kind, MacroDefKind::ProcMacro(_) | MacroDefKind::BuiltInDerive(_))
1141     }
1142 }
1143
1144 /// Invariant: `inner.as_assoc_item(db).is_some()`
1145 /// We do not actively enforce this invariant.
1146 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1147 pub enum AssocItem {
1148     Function(Function),
1149     Const(Const),
1150     TypeAlias(TypeAlias),
1151 }
1152 #[derive(Debug)]
1153 pub enum AssocItemContainer {
1154     Trait(Trait),
1155     Impl(Impl),
1156 }
1157 pub trait AsAssocItem {
1158     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1159 }
1160
1161 impl AsAssocItem for Function {
1162     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1163         as_assoc_item(db, AssocItem::Function, self.id)
1164     }
1165 }
1166 impl AsAssocItem for Const {
1167     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1168         as_assoc_item(db, AssocItem::Const, self.id)
1169     }
1170 }
1171 impl AsAssocItem for TypeAlias {
1172     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1173         as_assoc_item(db, AssocItem::TypeAlias, self.id)
1174     }
1175 }
1176 impl AsAssocItem for ModuleDef {
1177     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1178         match self {
1179             ModuleDef::Function(it) => it.as_assoc_item(db),
1180             ModuleDef::Const(it) => it.as_assoc_item(db),
1181             ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1182             _ => None,
1183         }
1184     }
1185 }
1186 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1187 where
1188     ID: Lookup<Data = AssocItemLoc<AST>>,
1189     DEF: From<ID>,
1190     CTOR: FnOnce(DEF) -> AssocItem,
1191     AST: ItemTreeNode,
1192 {
1193     match id.lookup(db.upcast()).container {
1194         AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1195         AssocContainerId::ModuleId(_) => None,
1196     }
1197 }
1198
1199 impl AssocItem {
1200     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1201         match self {
1202             AssocItem::Function(it) => Some(it.name(db)),
1203             AssocItem::Const(it) => it.name(db),
1204             AssocItem::TypeAlias(it) => Some(it.name(db)),
1205         }
1206     }
1207     pub fn module(self, db: &dyn HirDatabase) -> Module {
1208         match self {
1209             AssocItem::Function(f) => f.module(db),
1210             AssocItem::Const(c) => c.module(db),
1211             AssocItem::TypeAlias(t) => t.module(db),
1212         }
1213     }
1214     pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1215         let container = match self {
1216             AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1217             AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1218             AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1219         };
1220         match container {
1221             AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1222             AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1223             AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1224         }
1225     }
1226
1227     pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1228         match self.container(db) {
1229             AssocItemContainer::Trait(t) => Some(t),
1230             _ => None,
1231         }
1232     }
1233 }
1234
1235 impl HasVisibility for AssocItem {
1236     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1237         match self {
1238             AssocItem::Function(f) => f.visibility(db),
1239             AssocItem::Const(c) => c.visibility(db),
1240             AssocItem::TypeAlias(t) => t.visibility(db),
1241         }
1242     }
1243 }
1244
1245 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1246 pub enum GenericDef {
1247     Function(Function),
1248     Adt(Adt),
1249     Trait(Trait),
1250     TypeAlias(TypeAlias),
1251     Impl(Impl),
1252     // enum variants cannot have generics themselves, but their parent enums
1253     // can, and this makes some code easier to write
1254     Variant(Variant),
1255     // consts can have type parameters from their parents (i.e. associated consts of traits)
1256     Const(Const),
1257 }
1258 impl_from!(
1259     Function,
1260     Adt(Struct, Enum, Union),
1261     Trait,
1262     TypeAlias,
1263     Impl,
1264     Variant,
1265     Const
1266     for GenericDef
1267 );
1268
1269 impl GenericDef {
1270     pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1271         let generics = db.generic_params(self.into());
1272         let ty_params = generics
1273             .types
1274             .iter()
1275             .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1276             .map(GenericParam::TypeParam);
1277         let lt_params = generics
1278             .lifetimes
1279             .iter()
1280             .map(|(local_id, _)| LifetimeParam {
1281                 id: LifetimeParamId { parent: self.into(), local_id },
1282             })
1283             .map(GenericParam::LifetimeParam);
1284         let const_params = generics
1285             .consts
1286             .iter()
1287             .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1288             .map(GenericParam::ConstParam);
1289         ty_params.chain(lt_params).chain(const_params).collect()
1290     }
1291
1292     pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1293         let generics = db.generic_params(self.into());
1294         generics
1295             .types
1296             .iter()
1297             .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1298             .collect()
1299     }
1300 }
1301
1302 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1303 pub struct Local {
1304     pub(crate) parent: DefWithBodyId,
1305     pub(crate) pat_id: PatId,
1306 }
1307
1308 impl Local {
1309     pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1310         let src = self.source(db);
1311         match src.value {
1312             Either::Left(bind_pat) => {
1313                 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1314             }
1315             Either::Right(_self_param) => true,
1316         }
1317     }
1318
1319     // FIXME: why is this an option? It shouldn't be?
1320     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1321         let body = db.body(self.parent.into());
1322         match &body[self.pat_id] {
1323             Pat::Bind { name, .. } => Some(name.clone()),
1324             _ => None,
1325         }
1326     }
1327
1328     pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1329         self.name(db) == Some(name![self])
1330     }
1331
1332     pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1333         let body = db.body(self.parent.into());
1334         matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1335     }
1336
1337     pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1338         self.parent.into()
1339     }
1340
1341     pub fn module(self, db: &dyn HirDatabase) -> Module {
1342         self.parent(db).module(db)
1343     }
1344
1345     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1346         let def = DefWithBodyId::from(self.parent);
1347         let infer = db.infer(def);
1348         let ty = infer[self.pat_id].clone();
1349         let krate = def.module(db.upcast()).krate();
1350         Type::new(db, krate, def, ty)
1351     }
1352
1353     pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1354         let (_body, source_map) = db.body_with_source_map(self.parent.into());
1355         let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1356         let root = src.file_syntax(db.upcast());
1357         src.map(|ast| {
1358             ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1359         })
1360     }
1361 }
1362
1363 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1364 pub struct Label {
1365     pub(crate) parent: DefWithBodyId,
1366     pub(crate) label_id: LabelId,
1367 }
1368
1369 impl Label {
1370     pub fn module(self, db: &dyn HirDatabase) -> Module {
1371         self.parent(db).module(db)
1372     }
1373
1374     pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1375         self.parent.into()
1376     }
1377
1378     pub fn name(self, db: &dyn HirDatabase) -> Name {
1379         let body = db.body(self.parent.into());
1380         body[self.label_id].name.clone()
1381     }
1382
1383     pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1384         let (_body, source_map) = db.body_with_source_map(self.parent.into());
1385         let src = source_map.label_syntax(self.label_id);
1386         let root = src.file_syntax(db.upcast());
1387         src.map(|ast| ast.to_node(&root))
1388     }
1389 }
1390
1391 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1392 pub enum GenericParam {
1393     TypeParam(TypeParam),
1394     LifetimeParam(LifetimeParam),
1395     ConstParam(ConstParam),
1396 }
1397 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1398
1399 impl GenericParam {
1400     pub fn module(self, db: &dyn HirDatabase) -> Module {
1401         match self {
1402             GenericParam::TypeParam(it) => it.module(db),
1403             GenericParam::LifetimeParam(it) => it.module(db),
1404             GenericParam::ConstParam(it) => it.module(db),
1405         }
1406     }
1407
1408     pub fn name(self, db: &dyn HirDatabase) -> Name {
1409         match self {
1410             GenericParam::TypeParam(it) => it.name(db),
1411             GenericParam::LifetimeParam(it) => it.name(db),
1412             GenericParam::ConstParam(it) => it.name(db),
1413         }
1414     }
1415 }
1416
1417 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1418 pub struct TypeParam {
1419     pub(crate) id: TypeParamId,
1420 }
1421
1422 impl TypeParam {
1423     pub fn name(self, db: &dyn HirDatabase) -> Name {
1424         let params = db.generic_params(self.id.parent);
1425         params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1426     }
1427
1428     pub fn module(self, db: &dyn HirDatabase) -> Module {
1429         self.id.parent.module(db.upcast()).into()
1430     }
1431
1432     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1433         let resolver = self.id.parent.resolver(db.upcast());
1434         let krate = self.id.parent.module(db.upcast()).krate();
1435         let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1436         Type::new_with_resolver_inner(db, krate, &resolver, ty)
1437     }
1438
1439     pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1440         db.generic_predicates_for_param(self.id)
1441             .into_iter()
1442             .filter_map(|pred| match &pred.value {
1443                 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1444                     Some(Trait::from(trait_ref.trait_))
1445                 }
1446                 _ => None,
1447             })
1448             .collect()
1449     }
1450
1451     pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1452         let params = db.generic_defaults(self.id.parent);
1453         let local_idx = hir_ty::param_idx(db, self.id)?;
1454         let resolver = self.id.parent.resolver(db.upcast());
1455         let krate = self.id.parent.module(db.upcast()).krate();
1456         let ty = params.get(local_idx)?.clone();
1457         let subst = Substs::type_params(db, self.id.parent);
1458         let ty = ty.subst(&subst.prefix(local_idx));
1459         Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1460     }
1461 }
1462
1463 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1464 pub struct LifetimeParam {
1465     pub(crate) id: LifetimeParamId,
1466 }
1467
1468 impl LifetimeParam {
1469     pub fn name(self, db: &dyn HirDatabase) -> Name {
1470         let params = db.generic_params(self.id.parent);
1471         params.lifetimes[self.id.local_id].name.clone()
1472     }
1473
1474     pub fn module(self, db: &dyn HirDatabase) -> Module {
1475         self.id.parent.module(db.upcast()).into()
1476     }
1477
1478     pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1479         self.id.parent.into()
1480     }
1481 }
1482
1483 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1484 pub struct ConstParam {
1485     pub(crate) id: ConstParamId,
1486 }
1487
1488 impl ConstParam {
1489     pub fn name(self, db: &dyn HirDatabase) -> Name {
1490         let params = db.generic_params(self.id.parent);
1491         params.consts[self.id.local_id].name.clone()
1492     }
1493
1494     pub fn module(self, db: &dyn HirDatabase) -> Module {
1495         self.id.parent.module(db.upcast()).into()
1496     }
1497
1498     pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1499         self.id.parent.into()
1500     }
1501
1502     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1503         let def = self.id.parent;
1504         let krate = def.module(db.upcast()).krate();
1505         Type::new(db, krate, def, db.const_param_ty(self.id))
1506     }
1507 }
1508
1509 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1510 pub struct Impl {
1511     pub(crate) id: ImplId,
1512 }
1513
1514 impl Impl {
1515     pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1516         let inherent = db.inherent_impls_in_crate(krate.id);
1517         let trait_ = db.trait_impls_in_crate(krate.id);
1518
1519         inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1520     }
1521
1522     pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty }: Type) -> Vec<Impl> {
1523         let def_crates = match ty.value.def_crates(db, krate) {
1524             Some(def_crates) => def_crates,
1525             None => return Vec::new(),
1526         };
1527
1528         let filter = |impl_def: &Impl| {
1529             let target_ty = impl_def.target_ty(db);
1530             let rref = target_ty.remove_ref();
1531             ty.value.equals_ctor(rref.as_ref().map_or(&target_ty.ty.value, |it| &it.ty.value))
1532         };
1533
1534         let mut all = Vec::new();
1535         def_crates.into_iter().for_each(|id| {
1536             all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
1537         });
1538         let fp = TyFingerprint::for_impl(&ty.value);
1539         for id in db.crate_graph().iter() {
1540             match fp {
1541                 Some(fp) => all.extend(
1542                     db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
1543                 ),
1544                 None => all
1545                     .extend(db.trait_impls_in_crate(id).all_impls().map(Self::from).filter(filter)),
1546             }
1547         }
1548         all
1549     }
1550
1551     pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1552         let krate = trait_.module(db).krate();
1553         let mut all = Vec::new();
1554         for Crate { id } in krate.reverse_dependencies(db).into_iter().chain(Some(krate)) {
1555             let impls = db.trait_impls_in_crate(id);
1556             all.extend(impls.for_trait(trait_.id).map(Self::from))
1557         }
1558         all
1559     }
1560
1561     // FIXME: the return type is wrong. This should be a hir version of
1562     // `TraitRef` (ie, resolved `TypeRef`).
1563     pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1564         db.impl_data(self.id).target_trait.clone()
1565     }
1566
1567     pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1568         let impl_data = db.impl_data(self.id);
1569         let resolver = self.id.resolver(db.upcast());
1570         let krate = self.id.lookup(db.upcast()).container.krate();
1571         let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1572         let ty = ctx.lower_ty(&impl_data.target_type);
1573         Type::new_with_resolver_inner(db, krate, &resolver, ty)
1574     }
1575
1576     pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1577         db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1578     }
1579
1580     pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1581         db.impl_data(self.id).is_negative
1582     }
1583
1584     pub fn module(self, db: &dyn HirDatabase) -> Module {
1585         self.id.lookup(db.upcast()).container.into()
1586     }
1587
1588     pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1589         Crate { id: self.module(db).id.krate() }
1590     }
1591
1592     pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1593         let src = self.source(db)?;
1594         let item = src.file_id.is_builtin_derive(db.upcast())?;
1595         let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1596
1597         // FIXME: handle `cfg_attr`
1598         let attr = item
1599             .value
1600             .attrs()
1601             .filter_map(|it| {
1602                 let path = ModPath::from_src(it.path()?, &hygenic)?;
1603                 if path.as_ident()?.to_string() == "derive" {
1604                     Some(it)
1605                 } else {
1606                     None
1607                 }
1608             })
1609             .last()?;
1610
1611         Some(item.with_value(attr))
1612     }
1613 }
1614
1615 #[derive(Clone, PartialEq, Eq, Debug)]
1616 pub struct Type {
1617     krate: CrateId,
1618     ty: InEnvironment<Ty>,
1619 }
1620
1621 impl Type {
1622     pub(crate) fn new_with_resolver(
1623         db: &dyn HirDatabase,
1624         resolver: &Resolver,
1625         ty: Ty,
1626     ) -> Option<Type> {
1627         let krate = resolver.krate()?;
1628         Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1629     }
1630     pub(crate) fn new_with_resolver_inner(
1631         db: &dyn HirDatabase,
1632         krate: CrateId,
1633         resolver: &Resolver,
1634         ty: Ty,
1635     ) -> Type {
1636         let environment =
1637             resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1638         Type { krate, ty: InEnvironment { value: ty, environment } }
1639     }
1640
1641     fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1642         let resolver = lexical_env.resolver(db.upcast());
1643         let environment =
1644             resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1645         Type { krate, ty: InEnvironment { value: ty, environment } }
1646     }
1647
1648     fn from_def(
1649         db: &dyn HirDatabase,
1650         krate: CrateId,
1651         def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1652     ) -> Type {
1653         let substs = Substs::build_for_def(db, def).fill_with_unknown().build();
1654         let ty = db.ty(def.into()).subst(&substs);
1655         Type::new(db, krate, def, ty)
1656     }
1657
1658     pub fn is_unit(&self) -> bool {
1659         matches!(self.ty.value.interned(&Interner), TyKind::Tuple(0, ..))
1660     }
1661     pub fn is_bool(&self) -> bool {
1662         matches!(self.ty.value.interned(&Interner), TyKind::Scalar(Scalar::Bool))
1663     }
1664
1665     pub fn is_mutable_reference(&self) -> bool {
1666         matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1667     }
1668
1669     pub fn remove_ref(&self) -> Option<Type> {
1670         match &self.ty.value.interned(&Interner) {
1671             TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
1672             _ => None,
1673         }
1674     }
1675
1676     pub fn is_unknown(&self) -> bool {
1677         self.ty.value.is_unknown()
1678     }
1679
1680     /// Checks that particular type `ty` implements `std::future::Future`.
1681     /// This function is used in `.await` syntax completion.
1682     pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1683         // No special case for the type of async block, since Chalk can figure it out.
1684
1685         let krate = self.krate;
1686
1687         let std_future_trait =
1688             db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1689         let std_future_trait = match std_future_trait {
1690             Some(it) => it,
1691             None => return false,
1692         };
1693
1694         let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1695         method_resolution::implements_trait(
1696             &canonical_ty,
1697             db,
1698             self.ty.environment.clone(),
1699             krate,
1700             std_future_trait,
1701         )
1702     }
1703
1704     /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1705     ///
1706     /// This function can be used to check if a particular type is callable, since FnOnce is a
1707     /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1708     pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1709         let krate = self.krate;
1710
1711         let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1712             Some(it) => it,
1713             None => return false,
1714         };
1715
1716         let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1717         method_resolution::implements_trait_unique(
1718             &canonical_ty,
1719             db,
1720             self.ty.environment.clone(),
1721             krate,
1722             fnonce_trait,
1723         )
1724     }
1725
1726     pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1727         let trait_ref = hir_ty::TraitRef {
1728             trait_: trait_.id,
1729             substs: Substs::build_for_def(db, trait_.id)
1730                 .push(self.ty.value.clone())
1731                 .fill(args.iter().map(|t| t.ty.value.clone()))
1732                 .build(),
1733         };
1734
1735         let goal = Canonical {
1736             value: hir_ty::InEnvironment::new(
1737                 self.ty.environment.clone(),
1738                 hir_ty::Obligation::Trait(trait_ref),
1739             ),
1740             kinds: Arc::new([]),
1741         };
1742
1743         db.trait_solve(self.krate, goal).is_some()
1744     }
1745
1746     pub fn normalize_trait_assoc_type(
1747         &self,
1748         db: &dyn HirDatabase,
1749         trait_: Trait,
1750         args: &[Type],
1751         alias: TypeAlias,
1752     ) -> Option<Type> {
1753         let subst = Substs::build_for_def(db, trait_.id)
1754             .push(self.ty.value.clone())
1755             .fill(args.iter().map(|t| t.ty.value.clone()))
1756             .build();
1757         let predicate = ProjectionPredicate {
1758             projection_ty: ProjectionTy {
1759                 associated_ty_id: to_assoc_type_id(alias.id),
1760                 substitution: subst,
1761             },
1762             ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner),
1763         };
1764         let goal = Canonical {
1765             value: InEnvironment::new(
1766                 self.ty.environment.clone(),
1767                 Obligation::Projection(predicate),
1768             ),
1769             kinds: Arc::new([TyVariableKind::General]),
1770         };
1771
1772         match db.trait_solve(self.krate, goal)? {
1773             Solution::Unique(SolutionVariables(subst)) => {
1774                 subst.value.first().map(|ty| self.derived(ty.clone()))
1775             }
1776             Solution::Ambig(_) => None,
1777         }
1778     }
1779
1780     pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1781         let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1782         let copy_trait = match lang_item {
1783             Some(LangItemTarget::TraitId(it)) => it,
1784             _ => return false,
1785         };
1786         self.impls_trait(db, copy_trait.into(), &[])
1787     }
1788
1789     pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1790         let def = self.ty.value.callable_def(db);
1791
1792         let sig = self.ty.value.callable_sig(db)?;
1793         Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1794     }
1795
1796     pub fn is_closure(&self) -> bool {
1797         matches!(&self.ty.value.interned(&Interner), TyKind::Closure { .. })
1798     }
1799
1800     pub fn is_fn(&self) -> bool {
1801         matches!(&self.ty.value.interned(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1802     }
1803
1804     pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1805         let adt_id = match self.ty.value.interned(&Interner) {
1806             &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1807             _ => return false,
1808         };
1809
1810         let adt = adt_id.into();
1811         match adt {
1812             Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1813             _ => false,
1814         }
1815     }
1816
1817     pub fn is_raw_ptr(&self) -> bool {
1818         matches!(&self.ty.value.interned(&Interner), TyKind::Raw(..))
1819     }
1820
1821     pub fn contains_unknown(&self) -> bool {
1822         return go(&self.ty.value);
1823
1824         fn go(ty: &Ty) -> bool {
1825             match ty.interned(&Interner) {
1826                 TyKind::Unknown => true,
1827
1828                 TyKind::Adt(_, substs)
1829                 | TyKind::AssociatedType(_, substs)
1830                 | TyKind::Tuple(_, substs)
1831                 | TyKind::OpaqueType(_, substs)
1832                 | TyKind::FnDef(_, substs)
1833                 | TyKind::Closure(_, substs) => substs.iter().any(go),
1834
1835                 TyKind::Array(ty) | TyKind::Slice(ty) | TyKind::Raw(_, ty) | TyKind::Ref(_, ty) => {
1836                     go(ty)
1837                 }
1838
1839                 TyKind::Scalar(_)
1840                 | TyKind::Str
1841                 | TyKind::Never
1842                 | TyKind::Placeholder(_)
1843                 | TyKind::BoundVar(_)
1844                 | TyKind::InferenceVar(_, _)
1845                 | TyKind::Dyn(_)
1846                 | TyKind::Function(_)
1847                 | TyKind::Alias(_)
1848                 | TyKind::ForeignType(_) => false,
1849             }
1850         }
1851     }
1852
1853     pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1854         let (variant_id, substs) = match self.ty.value.interned(&Interner) {
1855             &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1856             &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1857             _ => return Vec::new(),
1858         };
1859
1860         db.field_types(variant_id)
1861             .iter()
1862             .map(|(local_id, ty)| {
1863                 let def = Field { parent: variant_id.into(), id: local_id };
1864                 let ty = ty.clone().subst(substs);
1865                 (def, self.derived(ty))
1866             })
1867             .collect()
1868     }
1869
1870     pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1871         if let TyKind::Tuple(_, substs) = &self.ty.value.interned(&Interner) {
1872             substs.iter().map(|ty| self.derived(ty.clone())).collect()
1873         } else {
1874             Vec::new()
1875         }
1876     }
1877
1878     pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1879         // There should be no inference vars in types passed here
1880         // FIXME check that?
1881         let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1882         let environment = self.ty.environment.clone();
1883         let ty = InEnvironment { value: canonical, environment };
1884         autoderef(db, Some(self.krate), ty)
1885             .map(|canonical| canonical.value)
1886             .map(move |ty| self.derived(ty))
1887     }
1888
1889     // This would be nicer if it just returned an iterator, but that runs into
1890     // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1891     pub fn iterate_assoc_items<T>(
1892         self,
1893         db: &dyn HirDatabase,
1894         krate: Crate,
1895         mut callback: impl FnMut(AssocItem) -> Option<T>,
1896     ) -> Option<T> {
1897         for krate in self.ty.value.def_crates(db, krate.id)? {
1898             let impls = db.inherent_impls_in_crate(krate);
1899
1900             for impl_def in impls.for_self_ty(&self.ty.value) {
1901                 for &item in db.impl_data(*impl_def).items.iter() {
1902                     if let Some(result) = callback(item.into()) {
1903                         return Some(result);
1904                     }
1905                 }
1906             }
1907         }
1908         None
1909     }
1910
1911     pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1912         self.ty
1913             .value
1914             .strip_references()
1915             .substs()
1916             .into_iter()
1917             .flat_map(|substs| substs.iter())
1918             .map(move |ty| self.derived(ty.clone()))
1919     }
1920
1921     pub fn iterate_method_candidates<T>(
1922         &self,
1923         db: &dyn HirDatabase,
1924         krate: Crate,
1925         traits_in_scope: &FxHashSet<TraitId>,
1926         name: Option<&Name>,
1927         mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1928     ) -> Option<T> {
1929         // There should be no inference vars in types passed here
1930         // FIXME check that?
1931         // FIXME replace Unknown by bound vars here
1932         let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1933
1934         let env = self.ty.environment.clone();
1935         let krate = krate.id;
1936
1937         method_resolution::iterate_method_candidates(
1938             &canonical,
1939             db,
1940             env,
1941             krate,
1942             traits_in_scope,
1943             name,
1944             method_resolution::LookupMode::MethodCall,
1945             |ty, it| match it {
1946                 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1947                 _ => None,
1948             },
1949         )
1950     }
1951
1952     pub fn iterate_path_candidates<T>(
1953         &self,
1954         db: &dyn HirDatabase,
1955         krate: Crate,
1956         traits_in_scope: &FxHashSet<TraitId>,
1957         name: Option<&Name>,
1958         mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1959     ) -> Option<T> {
1960         // There should be no inference vars in types passed here
1961         // FIXME check that?
1962         // FIXME replace Unknown by bound vars here
1963         let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1964
1965         let env = self.ty.environment.clone();
1966         let krate = krate.id;
1967
1968         method_resolution::iterate_method_candidates(
1969             &canonical,
1970             db,
1971             env,
1972             krate,
1973             traits_in_scope,
1974             name,
1975             method_resolution::LookupMode::Path,
1976             |ty, it| callback(ty, it.into()),
1977         )
1978     }
1979
1980     pub fn as_adt(&self) -> Option<Adt> {
1981         let (adt, _subst) = self.ty.value.as_adt()?;
1982         Some(adt.into())
1983     }
1984
1985     pub fn as_dyn_trait(&self) -> Option<Trait> {
1986         self.ty.value.dyn_trait().map(Into::into)
1987     }
1988
1989     pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
1990         self.ty.value.impl_trait_bounds(db).map(|it| {
1991             it.into_iter()
1992                 .filter_map(|pred| match pred {
1993                     hir_ty::GenericPredicate::Implemented(trait_ref) => {
1994                         Some(Trait::from(trait_ref.trait_))
1995                     }
1996                     _ => None,
1997                 })
1998                 .collect()
1999         })
2000     }
2001
2002     pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2003         self.ty.value.associated_type_parent_trait(db).map(Into::into)
2004     }
2005
2006     fn derived(&self, ty: Ty) -> Type {
2007         Type {
2008             krate: self.krate,
2009             ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
2010         }
2011     }
2012
2013     pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2014         // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2015         // We need a different order here.
2016
2017         fn walk_substs(
2018             db: &dyn HirDatabase,
2019             type_: &Type,
2020             substs: &Substs,
2021             cb: &mut impl FnMut(Type),
2022         ) {
2023             for ty in substs.iter() {
2024                 walk_type(db, &type_.derived(ty.clone()), cb);
2025             }
2026         }
2027
2028         fn walk_bounds(
2029             db: &dyn HirDatabase,
2030             type_: &Type,
2031             bounds: &[GenericPredicate],
2032             cb: &mut impl FnMut(Type),
2033         ) {
2034             for pred in bounds {
2035                 match pred {
2036                     GenericPredicate::Implemented(trait_ref) => {
2037                         cb(type_.clone());
2038                         walk_substs(db, type_, &trait_ref.substs, cb);
2039                     }
2040                     _ => (),
2041                 }
2042             }
2043         }
2044
2045         fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2046             let ty = type_.ty.value.strip_references();
2047             match ty.interned(&Interner) {
2048                 TyKind::Adt(..) => {
2049                     cb(type_.derived(ty.clone()));
2050                 }
2051                 TyKind::AssociatedType(..) => {
2052                     if let Some(_) = ty.associated_type_parent_trait(db) {
2053                         cb(type_.derived(ty.clone()));
2054                     }
2055                 }
2056                 TyKind::OpaqueType(..) => {
2057                     if let Some(bounds) = ty.impl_trait_bounds(db) {
2058                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2059                     }
2060                 }
2061                 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2062                     if let Some(bounds) = ty.impl_trait_bounds(db) {
2063                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2064                     }
2065
2066                     walk_substs(db, type_, &opaque_ty.substitution, cb);
2067                 }
2068                 TyKind::Placeholder(_) => {
2069                     if let Some(bounds) = ty.impl_trait_bounds(db) {
2070                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2071                     }
2072                 }
2073                 TyKind::Dyn(bounds) => {
2074                     walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
2075                 }
2076
2077                 TyKind::Ref(_, ty) | TyKind::Raw(_, ty) | TyKind::Array(ty) | TyKind::Slice(ty) => {
2078                     walk_type(db, &type_.derived(ty.clone()), cb);
2079                 }
2080
2081                 _ => {}
2082             }
2083             if let Some(substs) = ty.substs() {
2084                 walk_substs(db, type_, &substs, cb);
2085             }
2086         }
2087
2088         walk_type(db, self, &mut cb);
2089     }
2090 }
2091
2092 // FIXME: closures
2093 #[derive(Debug)]
2094 pub struct Callable {
2095     ty: Type,
2096     sig: CallableSig,
2097     def: Option<CallableDefId>,
2098     pub(crate) is_bound_method: bool,
2099 }
2100
2101 pub enum CallableKind {
2102     Function(Function),
2103     TupleStruct(Struct),
2104     TupleEnumVariant(Variant),
2105     Closure,
2106 }
2107
2108 impl Callable {
2109     pub fn kind(&self) -> CallableKind {
2110         match self.def {
2111             Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2112             Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2113             Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2114             None => CallableKind::Closure,
2115         }
2116     }
2117     pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2118         let func = match self.def {
2119             Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2120             _ => return None,
2121         };
2122         let src = func.lookup(db.upcast()).source(db.upcast());
2123         let param_list = src.value.param_list()?;
2124         param_list.self_param()
2125     }
2126     pub fn n_params(&self) -> usize {
2127         self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2128     }
2129     pub fn params(
2130         &self,
2131         db: &dyn HirDatabase,
2132     ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2133         let types = self
2134             .sig
2135             .params()
2136             .iter()
2137             .skip(if self.is_bound_method { 1 } else { 0 })
2138             .map(|ty| self.ty.derived(ty.clone()));
2139         let patterns = match self.def {
2140             Some(CallableDefId::FunctionId(func)) => {
2141                 let src = func.lookup(db.upcast()).source(db.upcast());
2142                 src.value.param_list().map(|param_list| {
2143                     param_list
2144                         .self_param()
2145                         .map(|it| Some(Either::Left(it)))
2146                         .filter(|_| !self.is_bound_method)
2147                         .into_iter()
2148                         .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2149                 })
2150             }
2151             _ => None,
2152         };
2153         patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2154     }
2155     pub fn return_type(&self) -> Type {
2156         self.ty.derived(self.sig.ret().clone())
2157     }
2158 }
2159
2160 /// For IDE only
2161 #[derive(Debug, PartialEq, Eq, Hash)]
2162 pub enum ScopeDef {
2163     ModuleDef(ModuleDef),
2164     MacroDef(MacroDef),
2165     GenericParam(GenericParam),
2166     ImplSelfType(Impl),
2167     AdtSelfType(Adt),
2168     Local(Local),
2169     Unknown,
2170 }
2171
2172 impl ScopeDef {
2173     pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2174         let mut items = ArrayVec::new();
2175
2176         match (def.take_types(), def.take_values()) {
2177             (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2178             (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2179             (Some(m1), Some(m2)) => {
2180                 // Some items, like unit structs and enum variants, are
2181                 // returned as both a type and a value. Here we want
2182                 // to de-duplicate them.
2183                 if m1 != m2 {
2184                     items.push(ScopeDef::ModuleDef(m1.into()));
2185                     items.push(ScopeDef::ModuleDef(m2.into()));
2186                 } else {
2187                     items.push(ScopeDef::ModuleDef(m1.into()));
2188                 }
2189             }
2190             (None, None) => {}
2191         };
2192
2193         if let Some(macro_def_id) = def.take_macros() {
2194             items.push(ScopeDef::MacroDef(macro_def_id.into()));
2195         }
2196
2197         if items.is_empty() {
2198             items.push(ScopeDef::Unknown);
2199         }
2200
2201         items
2202     }
2203 }
2204
2205 impl From<ItemInNs> for ScopeDef {
2206     fn from(item: ItemInNs) -> Self {
2207         match item {
2208             ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2209             ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2210             ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2211         }
2212     }
2213 }
2214
2215 pub trait HasVisibility {
2216     fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2217     fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2218         let vis = self.visibility(db);
2219         vis.is_visible_from(db.upcast(), module.id)
2220     }
2221 }