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