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