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