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