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