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