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