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