]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir/src/code_model.rs
Remove imports from hir
[rust.git] / crates / ra_hir / src / code_model.rs
1 //! FIXME: write short doc here
2 use std::sync::Arc;
3
4 use either::Either;
5 use hir_def::{
6     adt::VariantData,
7     builtin_type::BuiltinType,
8     docs::Documentation,
9     expr::{BindingAnnotation, Pat, PatId},
10     nameres::ModuleSource,
11     per_ns::PerNs,
12     resolver::HasResolver,
13     type_ref::{Mutability, TypeRef},
14     AdtId, ConstId, DefWithBodyId, EnumId, FunctionId, HasModule, ImplId, LocalEnumVariantId,
15     LocalModuleId, LocalStructFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
16     TypeParamId, UnionId,
17 };
18 use hir_expand::{
19     diagnostics::DiagnosticSink,
20     name::{name, AsName},
21     MacroDefId,
22 };
23 use hir_ty::{
24     autoderef, display::HirFormatter, expr::ExprValidator, ApplicationTy, Canonical, InEnvironment,
25     TraitEnvironment, Ty, TyDefId, TypeCtor, TypeWalk,
26 };
27 use ra_db::{CrateId, Edition, FileId};
28 use ra_syntax::ast;
29
30 use crate::{
31     db::{DefDatabase, HirDatabase},
32     CallableDef, HirDisplay, InFile, Name,
33 };
34
35 /// hir::Crate describes a single crate. It's the main interface with which
36 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
37 /// root module.
38 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39 pub struct Crate {
40     pub(crate) id: CrateId,
41 }
42
43 #[derive(Debug)]
44 pub struct CrateDependency {
45     pub krate: Crate,
46     pub name: Name,
47 }
48
49 impl Crate {
50     pub fn dependencies(self, db: &impl DefDatabase) -> Vec<CrateDependency> {
51         db.crate_graph()
52             .dependencies(self.id)
53             .map(|dep| {
54                 let krate = Crate { id: dep.crate_id() };
55                 let name = dep.as_name();
56                 CrateDependency { krate, name }
57             })
58             .collect()
59     }
60
61     // FIXME: add `transitive_reverse_dependencies`.
62     pub fn reverse_dependencies(self, db: &impl DefDatabase) -> Vec<Crate> {
63         let crate_graph = db.crate_graph();
64         crate_graph
65             .iter()
66             .filter(|&krate| crate_graph.dependencies(krate).any(|it| it.crate_id == self.id))
67             .map(|id| Crate { id })
68             .collect()
69     }
70
71     pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> {
72         let module_id = db.crate_def_map(self.id).root;
73         Some(Module::new(self, module_id))
74     }
75
76     pub fn root_file(self, db: &impl DefDatabase) -> FileId {
77         db.crate_graph().crate_root(self.id)
78     }
79
80     pub fn edition(self, db: &impl DefDatabase) -> Edition {
81         let crate_graph = db.crate_graph();
82         crate_graph.edition(self.id)
83     }
84
85     pub fn all(db: &impl DefDatabase) -> Vec<Crate> {
86         db.crate_graph().iter().map(|id| Crate { id }).collect()
87     }
88 }
89
90 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
91 pub struct Module {
92     pub(crate) id: ModuleId,
93 }
94
95 /// The defs which can be visible in the module.
96 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
97 pub enum ModuleDef {
98     Module(Module),
99     Function(Function),
100     Adt(Adt),
101     // Can't be directly declared, but can be imported.
102     EnumVariant(EnumVariant),
103     Const(Const),
104     Static(Static),
105     Trait(Trait),
106     TypeAlias(TypeAlias),
107     BuiltinType(BuiltinType),
108 }
109 impl_froms!(
110     ModuleDef: Module,
111     Function,
112     Adt(Struct, Enum, Union),
113     EnumVariant,
114     Const,
115     Static,
116     Trait,
117     TypeAlias,
118     BuiltinType
119 );
120
121 pub use hir_def::attr::Attrs;
122
123 impl Module {
124     pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module {
125         Module { id: ModuleId { krate: krate.id, local_id: crate_module_id } }
126     }
127
128     /// Name of this module.
129     pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
130         let def_map = db.crate_def_map(self.id.krate);
131         let parent = def_map[self.id.local_id].parent?;
132         def_map[parent].children.iter().find_map(|(name, module_id)| {
133             if *module_id == self.id.local_id {
134                 Some(name.clone())
135             } else {
136                 None
137             }
138         })
139     }
140
141     /// Returns the crate this module is part of.
142     pub fn krate(self) -> Crate {
143         Crate { id: self.id.krate }
144     }
145
146     /// Topmost parent of this module. Every module has a `crate_root`, but some
147     /// might be missing `krate`. This can happen if a module's file is not included
148     /// in the module tree of any target in `Cargo.toml`.
149     pub fn crate_root(self, db: &impl DefDatabase) -> Module {
150         let def_map = db.crate_def_map(self.id.krate);
151         self.with_module_id(def_map.root)
152     }
153
154     /// Iterates over all child modules.
155     pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> {
156         let def_map = db.crate_def_map(self.id.krate);
157         let children = def_map[self.id.local_id]
158             .children
159             .iter()
160             .map(|(_, module_id)| self.with_module_id(*module_id))
161             .collect::<Vec<_>>();
162         children.into_iter()
163     }
164
165     /// Finds a parent module.
166     pub fn parent(self, db: &impl DefDatabase) -> Option<Module> {
167         let def_map = db.crate_def_map(self.id.krate);
168         let parent_id = def_map[self.id.local_id].parent?;
169         Some(self.with_module_id(parent_id))
170     }
171
172     pub fn path_to_root(self, db: &impl HirDatabase) -> Vec<Module> {
173         let mut res = vec![self];
174         let mut curr = self;
175         while let Some(next) = curr.parent(db) {
176             res.push(next);
177             curr = next
178         }
179         res
180     }
181
182     /// Returns a `ModuleScope`: a set of items, visible in this module.
183     pub fn scope(self, db: &impl HirDatabase) -> Vec<(Name, ScopeDef)> {
184         db.crate_def_map(self.id.krate)[self.id.local_id]
185             .scope
186             .entries()
187             .map(|(name, res)| (name.clone(), res.def.into()))
188             .collect()
189     }
190
191     pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) {
192         db.crate_def_map(self.id.krate).add_diagnostics(db, self.id.local_id, sink);
193         for decl in self.declarations(db) {
194             match decl {
195                 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
196                 crate::ModuleDef::Module(m) => {
197                     // Only add diagnostics from inline modules
198                     if let ModuleSource::Module(_) = m.definition_source(db).value {
199                         m.diagnostics(db, sink)
200                     }
201                 }
202                 _ => (),
203             }
204         }
205
206         for impl_block in self.impl_blocks(db) {
207             for item in impl_block.items(db) {
208                 if let AssocItem::Function(f) = item {
209                     f.diagnostics(db, sink);
210                 }
211             }
212         }
213     }
214
215     pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> {
216         let def_map = db.crate_def_map(self.id.krate);
217         def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
218     }
219
220     pub fn impl_blocks(self, db: &impl DefDatabase) -> Vec<ImplBlock> {
221         let def_map = db.crate_def_map(self.id.krate);
222         def_map[self.id.local_id].scope.impls().map(ImplBlock::from).collect()
223     }
224
225     pub(crate) fn with_module_id(self, module_id: LocalModuleId) -> Module {
226         Module::new(self.krate(), module_id)
227     }
228 }
229
230 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231 pub struct StructField {
232     pub(crate) parent: VariantDef,
233     pub(crate) id: LocalStructFieldId,
234 }
235
236 #[derive(Debug, PartialEq, Eq)]
237 pub enum FieldSource {
238     Named(ast::RecordFieldDef),
239     Pos(ast::TupleFieldDef),
240 }
241
242 impl StructField {
243     pub fn name(&self, db: &impl HirDatabase) -> Name {
244         self.parent.variant_data(db).fields()[self.id].name.clone()
245     }
246
247     pub fn ty(&self, db: &impl HirDatabase) -> Type {
248         let var_id = self.parent.into();
249         let ty = db.field_types(var_id)[self.id].clone();
250         Type::new(db, self.parent.module(db).id.krate.into(), var_id, ty)
251     }
252
253     pub fn parent_def(&self, _db: &impl HirDatabase) -> VariantDef {
254         self.parent
255     }
256 }
257
258 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
259 pub struct Struct {
260     pub(crate) id: StructId,
261 }
262
263 impl Struct {
264     pub fn module(self, db: &impl DefDatabase) -> Module {
265         Module { id: self.id.lookup(db).container.module(db) }
266     }
267
268     pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
269         Some(self.module(db).krate())
270     }
271
272     pub fn name(self, db: &impl DefDatabase) -> Name {
273         db.struct_data(self.id.into()).name.clone()
274     }
275
276     pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
277         db.struct_data(self.id.into())
278             .variant_data
279             .fields()
280             .iter()
281             .map(|(id, _)| StructField { parent: self.into(), id })
282             .collect()
283     }
284
285     pub fn ty(self, db: &impl HirDatabase) -> Type {
286         Type::from_def(db, self.id.lookup(db).container.module(db).krate, self.id)
287     }
288
289     fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {
290         db.struct_data(self.id.into()).variant_data.clone()
291     }
292 }
293
294 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295 pub struct Union {
296     pub(crate) id: UnionId,
297 }
298
299 impl Union {
300     pub fn name(self, db: &impl DefDatabase) -> Name {
301         db.union_data(self.id).name.clone()
302     }
303
304     pub fn module(self, db: &impl DefDatabase) -> Module {
305         Module { id: self.id.lookup(db).container.module(db) }
306     }
307
308     pub fn ty(self, db: &impl HirDatabase) -> Type {
309         Type::from_def(db, self.id.lookup(db).container.module(db).krate, self.id)
310     }
311
312     pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
313         db.union_data(self.id)
314             .variant_data
315             .fields()
316             .iter()
317             .map(|(id, _)| StructField { parent: self.into(), id })
318             .collect()
319     }
320
321     fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {
322         db.union_data(self.id).variant_data.clone()
323     }
324 }
325
326 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
327 pub struct Enum {
328     pub(crate) id: EnumId,
329 }
330
331 impl Enum {
332     pub fn module(self, db: &impl DefDatabase) -> Module {
333         Module { id: self.id.lookup(db).container.module(db) }
334     }
335
336     pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
337         Some(self.module(db).krate())
338     }
339
340     pub fn name(self, db: &impl DefDatabase) -> Name {
341         db.enum_data(self.id).name.clone()
342     }
343
344     pub fn variants(self, db: &impl DefDatabase) -> Vec<EnumVariant> {
345         db.enum_data(self.id)
346             .variants
347             .iter()
348             .map(|(id, _)| EnumVariant { parent: self, id })
349             .collect()
350     }
351
352     pub fn ty(self, db: &impl HirDatabase) -> Type {
353         Type::from_def(db, self.id.lookup(db).container.module(db).krate, self.id)
354     }
355 }
356
357 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
358 pub struct EnumVariant {
359     pub(crate) parent: Enum,
360     pub(crate) id: LocalEnumVariantId,
361 }
362
363 impl EnumVariant {
364     pub fn module(self, db: &impl HirDatabase) -> Module {
365         self.parent.module(db)
366     }
367     pub fn parent_enum(self, _db: &impl DefDatabase) -> Enum {
368         self.parent
369     }
370
371     pub fn name(self, db: &impl DefDatabase) -> Name {
372         db.enum_data(self.parent.id).variants[self.id].name.clone()
373     }
374
375     pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
376         self.variant_data(db)
377             .fields()
378             .iter()
379             .map(|(id, _)| StructField { parent: self.into(), id })
380             .collect()
381     }
382
383     pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {
384         db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
385     }
386 }
387
388 /// A Data Type
389 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
390 pub enum Adt {
391     Struct(Struct),
392     Union(Union),
393     Enum(Enum),
394 }
395 impl_froms!(Adt: Struct, Union, Enum);
396
397 impl Adt {
398     pub fn has_non_default_type_params(self, db: &impl HirDatabase) -> bool {
399         let subst = db.generic_defaults(self.into());
400         subst.iter().any(|ty| ty == &Ty::Unknown)
401     }
402     pub fn ty(self, db: &impl HirDatabase) -> Type {
403         let id = AdtId::from(self);
404         Type::from_def(db, id.module(db).krate, id)
405     }
406
407     pub fn module(self, db: &impl DefDatabase) -> Module {
408         match self {
409             Adt::Struct(s) => s.module(db),
410             Adt::Union(s) => s.module(db),
411             Adt::Enum(e) => e.module(db),
412         }
413     }
414
415     pub fn krate(self, db: &impl HirDatabase) -> Option<Crate> {
416         Some(self.module(db).krate())
417     }
418 }
419
420 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
421 pub enum VariantDef {
422     Struct(Struct),
423     Union(Union),
424     EnumVariant(EnumVariant),
425 }
426 impl_froms!(VariantDef: Struct, Union, EnumVariant);
427
428 impl VariantDef {
429     pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
430         match self {
431             VariantDef::Struct(it) => it.fields(db),
432             VariantDef::Union(it) => it.fields(db),
433             VariantDef::EnumVariant(it) => it.fields(db),
434         }
435     }
436
437     pub fn module(self, db: &impl HirDatabase) -> Module {
438         match self {
439             VariantDef::Struct(it) => it.module(db),
440             VariantDef::Union(it) => it.module(db),
441             VariantDef::EnumVariant(it) => it.module(db),
442         }
443     }
444
445     pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {
446         match self {
447             VariantDef::Struct(it) => it.variant_data(db),
448             VariantDef::Union(it) => it.variant_data(db),
449             VariantDef::EnumVariant(it) => it.variant_data(db),
450         }
451     }
452 }
453
454 /// The defs which have a body.
455 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
456 pub enum DefWithBody {
457     Function(Function),
458     Static(Static),
459     Const(Const),
460 }
461
462 impl_froms!(DefWithBody: Function, Const, Static);
463
464 impl DefWithBody {
465     pub fn module(self, db: &impl HirDatabase) -> Module {
466         match self {
467             DefWithBody::Const(c) => c.module(db),
468             DefWithBody::Function(f) => f.module(db),
469             DefWithBody::Static(s) => s.module(db),
470         }
471     }
472 }
473
474 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
475 pub struct Function {
476     pub(crate) id: FunctionId,
477 }
478
479 impl Function {
480     pub fn module(self, db: &impl DefDatabase) -> Module {
481         self.id.lookup(db).module(db).into()
482     }
483
484     pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
485         Some(self.module(db).krate())
486     }
487
488     pub fn name(self, db: &impl HirDatabase) -> Name {
489         db.function_data(self.id).name.clone()
490     }
491
492     pub fn has_self_param(self, db: &impl HirDatabase) -> bool {
493         db.function_data(self.id).has_self_param
494     }
495
496     pub fn params(self, db: &impl HirDatabase) -> Vec<TypeRef> {
497         db.function_data(self.id).params.clone()
498     }
499
500     pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) {
501         let infer = db.infer(self.id.into());
502         infer.add_diagnostics(db, self.id, sink);
503         let mut validator = ExprValidator::new(self.id, infer, sink);
504         validator.validate_body(db);
505     }
506 }
507
508 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
509 pub struct Const {
510     pub(crate) id: ConstId,
511 }
512
513 impl Const {
514     pub fn module(self, db: &impl DefDatabase) -> Module {
515         Module { id: self.id.lookup(db).module(db) }
516     }
517
518     pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
519         Some(self.module(db).krate())
520     }
521
522     pub fn name(self, db: &impl HirDatabase) -> Option<Name> {
523         db.const_data(self.id).name.clone()
524     }
525 }
526
527 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
528 pub struct Static {
529     pub(crate) id: StaticId,
530 }
531
532 impl Static {
533     pub fn module(self, db: &impl DefDatabase) -> Module {
534         Module { id: self.id.lookup(db).module(db) }
535     }
536
537     pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
538         Some(self.module(db).krate())
539     }
540 }
541
542 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
543 pub struct Trait {
544     pub(crate) id: TraitId,
545 }
546
547 impl Trait {
548     pub fn module(self, db: &impl DefDatabase) -> Module {
549         Module { id: self.id.lookup(db).container.module(db) }
550     }
551
552     pub fn name(self, db: &impl DefDatabase) -> Name {
553         db.trait_data(self.id).name.clone()
554     }
555
556     pub fn items(self, db: &impl DefDatabase) -> Vec<AssocItem> {
557         db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
558     }
559
560     pub fn is_auto(self, db: &impl DefDatabase) -> bool {
561         db.trait_data(self.id).auto
562     }
563 }
564
565 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
566 pub struct TypeAlias {
567     pub(crate) id: TypeAliasId,
568 }
569
570 impl TypeAlias {
571     pub fn has_non_default_type_params(self, db: &impl HirDatabase) -> bool {
572         let subst = db.generic_defaults(self.id.into());
573         subst.iter().any(|ty| ty == &Ty::Unknown)
574     }
575
576     pub fn module(self, db: &impl DefDatabase) -> Module {
577         Module { id: self.id.lookup(db).module(db) }
578     }
579
580     pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
581         Some(self.module(db).krate())
582     }
583
584     pub fn type_ref(self, db: &impl DefDatabase) -> Option<TypeRef> {
585         db.type_alias_data(self.id).type_ref.clone()
586     }
587
588     pub fn ty(self, db: &impl HirDatabase) -> Type {
589         Type::from_def(db, self.id.lookup(db).module(db).krate, self.id)
590     }
591
592     pub fn name(self, db: &impl DefDatabase) -> Name {
593         db.type_alias_data(self.id).name.clone()
594     }
595 }
596
597 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
598 pub struct MacroDef {
599     pub(crate) id: MacroDefId,
600 }
601
602 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
603 pub enum AssocItem {
604     Function(Function),
605     Const(Const),
606     TypeAlias(TypeAlias),
607 }
608 // FIXME: not every function, ... is actually an assoc item. maybe we should make
609 // sure that you can only turn actual assoc items into AssocItems. This would
610 // require not implementing From, and instead having some checked way of
611 // casting them, and somehow making the constructors private, which would be annoying.
612 impl_froms!(AssocItem: Function, Const, TypeAlias);
613
614 impl AssocItem {
615     pub fn module(self, db: &impl DefDatabase) -> Module {
616         match self {
617             AssocItem::Function(f) => f.module(db),
618             AssocItem::Const(c) => c.module(db),
619             AssocItem::TypeAlias(t) => t.module(db),
620         }
621     }
622 }
623
624 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
625 pub enum GenericDef {
626     Function(Function),
627     Adt(Adt),
628     Trait(Trait),
629     TypeAlias(TypeAlias),
630     ImplBlock(ImplBlock),
631     // enum variants cannot have generics themselves, but their parent enums
632     // can, and this makes some code easier to write
633     EnumVariant(EnumVariant),
634     // consts can have type parameters from their parents (i.e. associated consts of traits)
635     Const(Const),
636 }
637 impl_froms!(
638     GenericDef: Function,
639     Adt(Struct, Enum, Union),
640     Trait,
641     TypeAlias,
642     ImplBlock,
643     EnumVariant,
644     Const
645 );
646
647 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
648 pub struct Local {
649     pub(crate) parent: DefWithBody,
650     pub(crate) pat_id: PatId,
651 }
652
653 impl Local {
654     pub fn name(self, db: &impl HirDatabase) -> Option<Name> {
655         let body = db.body(self.parent.into());
656         match &body[self.pat_id] {
657             Pat::Bind { name, .. } => Some(name.clone()),
658             _ => None,
659         }
660     }
661
662     pub fn is_self(self, db: &impl HirDatabase) -> bool {
663         self.name(db) == Some(name![self])
664     }
665
666     pub fn is_mut(self, db: &impl HirDatabase) -> bool {
667         let body = db.body(self.parent.into());
668         match &body[self.pat_id] {
669             Pat::Bind { mode, .. } => match mode {
670                 BindingAnnotation::Mutable | BindingAnnotation::RefMut => true,
671                 _ => false,
672             },
673             _ => false,
674         }
675     }
676
677     pub fn parent(self, _db: &impl HirDatabase) -> DefWithBody {
678         self.parent
679     }
680
681     pub fn module(self, db: &impl HirDatabase) -> Module {
682         self.parent.module(db)
683     }
684
685     pub fn ty(self, db: &impl HirDatabase) -> Type {
686         let def = DefWithBodyId::from(self.parent);
687         let infer = db.infer(def);
688         let ty = infer[self.pat_id].clone();
689         let resolver = def.resolver(db);
690         let krate = def.module(db).krate;
691         let environment = TraitEnvironment::lower(db, &resolver);
692         Type { krate, ty: InEnvironment { value: ty, environment } }
693     }
694
695     pub fn source(self, db: &impl HirDatabase) -> InFile<Either<ast::BindPat, ast::SelfParam>> {
696         let (_body, source_map) = db.body_with_source_map(self.parent.into());
697         let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
698         let root = src.file_syntax(db);
699         src.map(|ast| {
700             ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
701         })
702     }
703 }
704
705 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
706 pub struct TypeParam {
707     pub(crate) id: TypeParamId,
708 }
709
710 impl TypeParam {
711     pub fn name(self, db: &impl HirDatabase) -> Name {
712         let params = db.generic_params(self.id.parent);
713         params.types[self.id.local_id].name.clone()
714     }
715
716     pub fn module(self, db: &impl HirDatabase) -> Module {
717         self.id.parent.module(db).into()
718     }
719 }
720
721 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
722 pub struct ImplBlock {
723     pub(crate) id: ImplId,
724 }
725
726 impl ImplBlock {
727     pub fn all_in_crate(db: &impl HirDatabase, krate: Crate) -> Vec<ImplBlock> {
728         let impls = db.impls_in_crate(krate.id);
729         impls.all_impls().map(Self::from).collect()
730     }
731     pub fn for_trait(db: &impl HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplBlock> {
732         let impls = db.impls_in_crate(krate.id);
733         impls.lookup_impl_blocks_for_trait(trait_.id).map(Self::from).collect()
734     }
735
736     pub fn target_trait(&self, db: &impl DefDatabase) -> Option<TypeRef> {
737         db.impl_data(self.id).target_trait.clone()
738     }
739
740     pub fn target_type(&self, db: &impl DefDatabase) -> TypeRef {
741         db.impl_data(self.id).target_type.clone()
742     }
743
744     pub fn target_ty(&self, db: &impl HirDatabase) -> Type {
745         let impl_data = db.impl_data(self.id);
746         let resolver = self.id.resolver(db);
747         let environment = TraitEnvironment::lower(db, &resolver);
748         let ty = Ty::from_hir(db, &resolver, &impl_data.target_type);
749         Type {
750             krate: self.id.lookup(db).container.module(db).krate,
751             ty: InEnvironment { value: ty, environment },
752         }
753     }
754
755     pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> {
756         db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
757     }
758
759     pub fn is_negative(&self, db: &impl DefDatabase) -> bool {
760         db.impl_data(self.id).is_negative
761     }
762
763     pub fn module(&self, db: &impl DefDatabase) -> Module {
764         self.id.lookup(db).container.module(db).into()
765     }
766
767     pub fn krate(&self, db: &impl DefDatabase) -> Crate {
768         Crate { id: self.module(db).id.krate }
769     }
770 }
771
772 #[derive(Clone, PartialEq, Eq, Debug)]
773 pub struct Type {
774     pub(crate) krate: CrateId,
775     pub(crate) ty: InEnvironment<Ty>,
776 }
777
778 impl Type {
779     fn new(db: &impl HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
780         let resolver = lexical_env.resolver(db);
781         let environment = TraitEnvironment::lower(db, &resolver);
782         Type { krate, ty: InEnvironment { value: ty, environment } }
783     }
784
785     fn from_def(
786         db: &impl HirDatabase,
787         krate: CrateId,
788         def: impl HasResolver + Into<TyDefId>,
789     ) -> Type {
790         let ty = db.ty(def.into());
791         Type::new(db, krate, def, ty)
792     }
793
794     pub fn is_bool(&self) -> bool {
795         match &self.ty.value {
796             Ty::Apply(a_ty) => match a_ty.ctor {
797                 TypeCtor::Bool => true,
798                 _ => false,
799             },
800             _ => false,
801         }
802     }
803
804     pub fn is_mutable_reference(&self) -> bool {
805         match &self.ty.value {
806             Ty::Apply(a_ty) => match a_ty.ctor {
807                 TypeCtor::Ref(Mutability::Mut) => true,
808                 _ => false,
809             },
810             _ => false,
811         }
812     }
813
814     pub fn is_unknown(&self) -> bool {
815         match &self.ty.value {
816             Ty::Unknown => true,
817             _ => false,
818         }
819     }
820
821     // FIXME: this method is broken, as it doesn't take closures into account.
822     pub fn as_callable(&self) -> Option<CallableDef> {
823         Some(self.ty.value.as_callable()?.0)
824     }
825
826     pub fn contains_unknown(&self) -> bool {
827         return go(&self.ty.value);
828
829         fn go(ty: &Ty) -> bool {
830             match ty {
831                 Ty::Unknown => true,
832                 Ty::Apply(a_ty) => a_ty.parameters.iter().any(go),
833                 _ => false,
834             }
835         }
836     }
837
838     pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> {
839         if let Ty::Apply(a_ty) = &self.ty.value {
840             match a_ty.ctor {
841                 TypeCtor::Adt(AdtId::StructId(s)) => {
842                     let var_def = s.into();
843                     return db
844                         .field_types(var_def)
845                         .iter()
846                         .map(|(local_id, ty)| {
847                             let def = StructField { parent: var_def.into(), id: local_id };
848                             let ty = ty.clone().subst(&a_ty.parameters);
849                             (def, self.derived(ty))
850                         })
851                         .collect();
852                 }
853                 _ => {}
854             }
855         };
856         Vec::new()
857     }
858
859     pub fn tuple_fields(&self, _db: &impl HirDatabase) -> Vec<Type> {
860         let mut res = Vec::new();
861         if let Ty::Apply(a_ty) = &self.ty.value {
862             match a_ty.ctor {
863                 TypeCtor::Tuple { .. } => {
864                     for ty in a_ty.parameters.iter() {
865                         let ty = ty.clone().subst(&a_ty.parameters);
866                         res.push(self.derived(ty));
867                     }
868                 }
869                 _ => {}
870             }
871         };
872         res
873     }
874
875     pub fn variant_fields(
876         &self,
877         db: &impl HirDatabase,
878         def: VariantDef,
879     ) -> Vec<(StructField, Type)> {
880         // FIXME: check that ty and def match
881         match &self.ty.value {
882             Ty::Apply(a_ty) => {
883                 let field_types = db.field_types(def.into());
884                 def.fields(db)
885                     .into_iter()
886                     .map(|it| {
887                         let ty = field_types[it.id].clone().subst(&a_ty.parameters);
888                         (it, self.derived(ty))
889                     })
890                     .collect()
891             }
892             _ => Vec::new(),
893         }
894     }
895
896     pub fn autoderef<'a>(&'a self, db: &'a impl HirDatabase) -> impl Iterator<Item = Type> + 'a {
897         // There should be no inference vars in types passed here
898         // FIXME check that?
899         let canonical = Canonical { value: self.ty.value.clone(), num_vars: 0 };
900         let environment = self.ty.environment.clone();
901         let ty = InEnvironment { value: canonical, environment: environment.clone() };
902         autoderef(db, Some(self.krate), ty)
903             .map(|canonical| canonical.value)
904             .map(move |ty| self.derived(ty))
905     }
906
907     // This would be nicer if it just returned an iterator, but that runs into
908     // lifetime problems, because we need to borrow temp `CrateImplBlocks`.
909     pub fn iterate_impl_items<T>(
910         self,
911         db: &impl HirDatabase,
912         krate: Crate,
913         mut callback: impl FnMut(AssocItem) -> Option<T>,
914     ) -> Option<T> {
915         for krate in self.ty.value.def_crates(db, krate.id)? {
916             let impls = db.impls_in_crate(krate);
917
918             for impl_block in impls.lookup_impl_blocks(&self.ty.value) {
919                 for &item in db.impl_data(impl_block).items.iter() {
920                     if let Some(result) = callback(item.into()) {
921                         return Some(result);
922                     }
923                 }
924             }
925         }
926         None
927     }
928
929     pub fn as_adt(&self) -> Option<Adt> {
930         let (adt, _subst) = self.ty.value.as_adt()?;
931         Some(adt.into())
932     }
933
934     // FIXME: provide required accessors such that it becomes implementable from outside.
935     pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
936         match (&self.ty.value, &other.ty.value) {
937             (Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor
938             {
939                 TypeCtor::Ref(..) => match parameters.as_single() {
940                     Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor,
941                     _ => false,
942                 },
943                 _ => a_original_ty.ctor == *ctor,
944             },
945             _ => false,
946         }
947     }
948
949     fn derived(&self, ty: Ty) -> Type {
950         Type {
951             krate: self.krate,
952             ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
953         }
954     }
955 }
956
957 impl HirDisplay for Type {
958     fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> std::fmt::Result {
959         self.ty.value.hir_fmt(f)
960     }
961 }
962
963 /// For IDE only
964 pub enum ScopeDef {
965     ModuleDef(ModuleDef),
966     MacroDef(MacroDef),
967     GenericParam(TypeParam),
968     ImplSelfType(ImplBlock),
969     AdtSelfType(Adt),
970     Local(Local),
971     Unknown,
972 }
973
974 impl From<PerNs> for ScopeDef {
975     fn from(def: PerNs) -> Self {
976         def.take_types()
977             .or_else(|| def.take_values())
978             .map(|module_def_id| ScopeDef::ModuleDef(module_def_id.into()))
979             .or_else(|| {
980                 def.take_macros().map(|macro_def_id| ScopeDef::MacroDef(macro_def_id.into()))
981             })
982             .unwrap_or(ScopeDef::Unknown)
983     }
984 }
985
986 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
987 pub enum AttrDef {
988     Module(Module),
989     StructField(StructField),
990     Adt(Adt),
991     Function(Function),
992     EnumVariant(EnumVariant),
993     Static(Static),
994     Const(Const),
995     Trait(Trait),
996     TypeAlias(TypeAlias),
997     MacroDef(MacroDef),
998 }
999
1000 impl_froms!(
1001     AttrDef: Module,
1002     StructField,
1003     Adt(Struct, Enum, Union),
1004     EnumVariant,
1005     Static,
1006     Const,
1007     Function,
1008     Trait,
1009     TypeAlias,
1010     MacroDef
1011 );
1012
1013 pub trait HasAttrs {
1014     fn attrs(self, db: &impl DefDatabase) -> Attrs;
1015 }
1016
1017 impl<T: Into<AttrDef>> HasAttrs for T {
1018     fn attrs(self, db: &impl DefDatabase) -> Attrs {
1019         let def: AttrDef = self.into();
1020         db.attrs(def.into())
1021     }
1022 }
1023
1024 pub trait Docs {
1025     fn docs(&self, db: &impl HirDatabase) -> Option<Documentation>;
1026 }
1027 impl<T: Into<AttrDef> + Copy> Docs for T {
1028     fn docs(&self, db: &impl HirDatabase) -> Option<Documentation> {
1029         let def: AttrDef = (*self).into();
1030         db.documentation(def.into())
1031     }
1032 }