aboutsummaryrefslogtreecommitdiff
path: root/crates/hir/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/hir/src/lib.rs')
-rw-r--r--crates/hir/src/lib.rs129
1 files changed, 93 insertions, 36 deletions
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index c5161dadd..12dd5fb38 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -29,6 +29,8 @@ mod has_source;
29pub mod diagnostics; 29pub mod diagnostics;
30pub mod db; 30pub mod db;
31 31
32mod display;
33
32use std::{iter, sync::Arc}; 34use std::{iter, sync::Arc};
33 35
34use arrayvec::ArrayVec; 36use arrayvec::ArrayVec;
@@ -50,14 +52,15 @@ use hir_def::{
50use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind}; 52use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
51use hir_ty::{ 53use hir_ty::{
52 autoderef, 54 autoderef,
53 display::{write_bounds_like_dyn_trait_with_prefix, HirDisplayError, HirFormatter},
54 method_resolution::{self, TyFingerprint}, 55 method_resolution::{self, TyFingerprint},
56 primitive::UintTy,
55 to_assoc_type_id, 57 to_assoc_type_id,
56 traits::{FnTrait, Solution, SolutionVariables}, 58 traits::{FnTrait, Solution, SolutionVariables},
57 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate, 59 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate,
58 InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, Ty, 60 InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substitution,
59 TyDefId, TyKind, TyVariableKind, 61 Ty, TyDefId, TyKind, TyVariableKind,
60}; 62};
63use itertools::Itertools;
61use rustc_hash::FxHashSet; 64use rustc_hash::FxHashSet;
62use stdx::{format_to, impl_from}; 65use stdx::{format_to, impl_from};
63use syntax::{ 66use syntax::{
@@ -139,7 +142,6 @@ impl Crate {
139 .collect() 142 .collect()
140 } 143 }
141 144
142 // FIXME: add `transitive_reverse_dependencies`.
143 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> { 145 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
144 let crate_graph = db.crate_graph(); 146 let crate_graph = db.crate_graph();
145 crate_graph 147 crate_graph
@@ -151,6 +153,14 @@ impl Crate {
151 .collect() 153 .collect()
152 } 154 }
153 155
156 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
157 db.crate_graph()
158 .transitive_reverse_dependencies(self.id)
159 .into_iter()
160 .map(|id| Crate { id })
161 .collect()
162 }
163
154 pub fn root_module(self, db: &dyn HirDatabase) -> Module { 164 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
155 let def_map = db.crate_def_map(self.id); 165 let def_map = db.crate_def_map(self.id);
156 Module { id: def_map.module_id(def_map.root()) } 166 Module { id: def_map.module_id(def_map.root()) }
@@ -508,7 +518,7 @@ impl Field {
508 VariantDef::Union(it) => it.id.into(), 518 VariantDef::Union(it) => it.id.into(),
509 VariantDef::Variant(it) => it.parent.id.into(), 519 VariantDef::Variant(it) => it.parent.id.into(),
510 }; 520 };
511 let substs = Substs::type_params(db, generic_def_id); 521 let substs = Substitution::type_params(db, generic_def_id);
512 let ty = db.field_types(var_id)[self.id].clone().subst(&substs); 522 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
513 Type::new(db, self.parent.module(db).id.krate(), var_id, ty) 523 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
514 } 524 }
@@ -571,6 +581,12 @@ impl Struct {
571 } 581 }
572} 582}
573 583
584impl HasVisibility for Struct {
585 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
586 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
587 }
588}
589
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 590#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
575pub struct Union { 591pub struct Union {
576 pub(crate) id: UnionId, 592 pub(crate) id: UnionId,
@@ -603,6 +619,12 @@ impl Union {
603 } 619 }
604} 620}
605 621
622impl HasVisibility for Union {
623 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
624 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
625 }
626}
627
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 628#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
607pub struct Enum { 629pub struct Enum {
608 pub(crate) id: EnumId, 630 pub(crate) id: EnumId,
@@ -630,6 +652,12 @@ impl Enum {
630 } 652 }
631} 653}
632 654
655impl HasVisibility for Enum {
656 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
657 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
658 }
659}
660
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 661#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
634pub struct Variant { 662pub struct Variant {
635 pub(crate) parent: Enum, 663 pub(crate) parent: Enum,
@@ -821,7 +849,8 @@ impl Function {
821 db.function_data(self.id) 849 db.function_data(self.id)
822 .params 850 .params
823 .iter() 851 .iter()
824 .map(|type_ref| { 852 .enumerate()
853 .map(|(idx, type_ref)| {
825 let ty = Type { 854 let ty = Type {
826 krate, 855 krate,
827 ty: InEnvironment { 856 ty: InEnvironment {
@@ -829,7 +858,7 @@ impl Function {
829 environment: environment.clone(), 858 environment: environment.clone(),
830 }, 859 },
831 }; 860 };
832 Param { ty } 861 Param { func: self, ty, idx }
833 }) 862 })
834 .collect() 863 .collect()
835 } 864 }
@@ -843,7 +872,7 @@ impl Function {
843 } 872 }
844 873
845 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool { 874 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
846 db.function_data(self.id).is_unsafe 875 db.function_data(self.id).qualifier.is_unsafe
847 } 876 }
848 877
849 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { 878 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
@@ -892,6 +921,9 @@ impl From<hir_ty::Mutability> for Access {
892 921
893#[derive(Debug)] 922#[derive(Debug)]
894pub struct Param { 923pub struct Param {
924 func: Function,
925 /// The index in parameter list, including self parameter.
926 idx: usize,
895 ty: Type, 927 ty: Type,
896} 928}
897 929
@@ -899,6 +931,15 @@ impl Param {
899 pub fn ty(&self) -> &Type { 931 pub fn ty(&self) -> &Type {
900 &self.ty 932 &self.ty
901 } 933 }
934
935 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
936 let params = self.func.source(db)?.value.param_list()?;
937 if params.self_param().is_some() {
938 params.params().nth(self.idx.checked_sub(1)?)?.pat()
939 } else {
940 params.params().nth(self.idx)?.pat()
941 }
942 }
902} 943}
903 944
904#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 945#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -921,6 +962,14 @@ impl SelfParam {
921 }) 962 })
922 .unwrap_or(Access::Owned) 963 .unwrap_or(Access::Owned)
923 } 964 }
965
966 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
967 match self.access(db) {
968 Access::Shared => "&self",
969 Access::Exclusive => "&mut self",
970 Access::Owned => "self",
971 }
972 }
924} 973}
925 974
926impl HasVisibility for Function { 975impl HasVisibility for Function {
@@ -948,6 +997,10 @@ impl Const {
948 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { 997 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
949 db.const_data(self.id).name.clone() 998 db.const_data(self.id).name.clone()
950 } 999 }
1000
1001 pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
1002 db.const_data(self.id).type_ref.clone()
1003 }
951} 1004}
952 1005
953impl HasVisibility for Const { 1006impl HasVisibility for Const {
@@ -981,6 +1034,12 @@ impl Static {
981 } 1034 }
982} 1035}
983 1036
1037impl HasVisibility for Static {
1038 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1039 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1040 }
1041}
1042
984#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 1043#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
985pub struct Trait { 1044pub struct Trait {
986 pub(crate) id: TraitId, 1045 pub(crate) id: TraitId,
@@ -1000,7 +1059,13 @@ impl Trait {
1000 } 1059 }
1001 1060
1002 pub fn is_auto(self, db: &dyn HirDatabase) -> bool { 1061 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1003 db.trait_data(self.id).auto 1062 db.trait_data(self.id).is_auto
1063 }
1064}
1065
1066impl HasVisibility for Trait {
1067 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1068 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1004 } 1069 }
1005} 1070}
1006 1071
@@ -1406,25 +1471,12 @@ impl TypeParam {
1406 let resolver = self.id.parent.resolver(db.upcast()); 1471 let resolver = self.id.parent.resolver(db.upcast());
1407 let krate = self.id.parent.module(db.upcast()).krate(); 1472 let krate = self.id.parent.module(db.upcast()).krate();
1408 let ty = params.get(local_idx)?.clone(); 1473 let ty = params.get(local_idx)?.clone();
1409 let subst = Substs::type_params(db, self.id.parent); 1474 let subst = Substitution::type_params(db, self.id.parent);
1410 let ty = ty.subst(&subst.prefix(local_idx)); 1475 let ty = ty.subst(&subst.prefix(local_idx));
1411 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty)) 1476 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1412 } 1477 }
1413} 1478}
1414 1479
1415impl HirDisplay for TypeParam {
1416 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1417 write!(f, "{}", self.name(f.db))?;
1418 let bounds = f.db.generic_predicates_for_param(self.id);
1419 let substs = Substs::type_params(f.db, self.id.parent);
1420 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
1421 if !(predicates.is_empty() || f.omit_verbose_types()) {
1422 write_bounds_like_dyn_trait_with_prefix(":", &predicates, f)?;
1423 }
1424 Ok(())
1425 }
1426}
1427
1428#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] 1480#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1429pub struct LifetimeParam { 1481pub struct LifetimeParam {
1430 pub(crate) id: LifetimeParamId, 1482 pub(crate) id: LifetimeParamId,
@@ -1497,11 +1549,17 @@ impl Impl {
1497 }; 1549 };
1498 1550
1499 let mut all = Vec::new(); 1551 let mut all = Vec::new();
1500 def_crates.into_iter().for_each(|id| { 1552 def_crates.iter().for_each(|&id| {
1501 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter)) 1553 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
1502 }); 1554 });
1503 let fp = TyFingerprint::for_impl(&ty.value); 1555 let fp = TyFingerprint::for_impl(&ty.value);
1504 for id in db.crate_graph().iter() { 1556 for id in def_crates
1557 .iter()
1558 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1559 .map(|Crate { id }| id)
1560 .chain(def_crates.iter().copied())
1561 .unique()
1562 {
1505 match fp { 1563 match fp {
1506 Some(fp) => all.extend( 1564 Some(fp) => all.extend(
1507 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter), 1565 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
@@ -1516,7 +1574,8 @@ impl Impl {
1516 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> { 1574 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1517 let krate = trait_.module(db).krate(); 1575 let krate = trait_.module(db).krate();
1518 let mut all = Vec::new(); 1576 let mut all = Vec::new();
1519 for Crate { id } in krate.reverse_dependencies(db).into_iter().chain(Some(krate)) { 1577 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter().chain(Some(krate))
1578 {
1520 let impls = db.trait_impls_in_crate(id); 1579 let impls = db.trait_impls_in_crate(id);
1521 all.extend(impls.for_trait(trait_.id).map(Self::from)) 1580 all.extend(impls.for_trait(trait_.id).map(Self::from))
1522 } 1581 }
@@ -1615,7 +1674,7 @@ impl Type {
1615 krate: CrateId, 1674 krate: CrateId,
1616 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>, 1675 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1617 ) -> Type { 1676 ) -> Type {
1618 let substs = Substs::build_for_def(db, def).fill_with_unknown().build(); 1677 let substs = Substitution::build_for_def(db, def).fill_with_unknown().build();
1619 let ty = db.ty(def.into()).subst(&substs); 1678 let ty = db.ty(def.into()).subst(&substs);
1620 Type::new(db, krate, def, ty) 1679 Type::new(db, krate, def, ty)
1621 } 1680 }
@@ -1631,6 +1690,10 @@ impl Type {
1631 matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..)) 1690 matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1632 } 1691 }
1633 1692
1693 pub fn is_usize(&self) -> bool {
1694 matches!(self.ty.value.interned(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1695 }
1696
1634 pub fn remove_ref(&self) -> Option<Type> { 1697 pub fn remove_ref(&self) -> Option<Type> {
1635 match &self.ty.value.interned(&Interner) { 1698 match &self.ty.value.interned(&Interner) {
1636 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())), 1699 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
@@ -1691,7 +1754,7 @@ impl Type {
1691 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool { 1754 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1692 let trait_ref = hir_ty::TraitRef { 1755 let trait_ref = hir_ty::TraitRef {
1693 trait_: trait_.id, 1756 trait_: trait_.id,
1694 substs: Substs::build_for_def(db, trait_.id) 1757 substs: Substitution::build_for_def(db, trait_.id)
1695 .push(self.ty.value.clone()) 1758 .push(self.ty.value.clone())
1696 .fill(args.iter().map(|t| t.ty.value.clone())) 1759 .fill(args.iter().map(|t| t.ty.value.clone()))
1697 .build(), 1760 .build(),
@@ -1715,7 +1778,7 @@ impl Type {
1715 args: &[Type], 1778 args: &[Type],
1716 alias: TypeAlias, 1779 alias: TypeAlias,
1717 ) -> Option<Type> { 1780 ) -> Option<Type> {
1718 let subst = Substs::build_for_def(db, trait_.id) 1781 let subst = Substitution::build_for_def(db, trait_.id)
1719 .push(self.ty.value.clone()) 1782 .push(self.ty.value.clone())
1720 .fill(args.iter().map(|t| t.ty.value.clone())) 1783 .fill(args.iter().map(|t| t.ty.value.clone()))
1721 .build(); 1784 .build();
@@ -1982,7 +2045,7 @@ impl Type {
1982 fn walk_substs( 2045 fn walk_substs(
1983 db: &dyn HirDatabase, 2046 db: &dyn HirDatabase,
1984 type_: &Type, 2047 type_: &Type,
1985 substs: &Substs, 2048 substs: &Substitution,
1986 cb: &mut impl FnMut(Type), 2049 cb: &mut impl FnMut(Type),
1987 ) { 2050 ) {
1988 for ty in substs.iter() { 2051 for ty in substs.iter() {
@@ -2054,12 +2117,6 @@ impl Type {
2054 } 2117 }
2055} 2118}
2056 2119
2057impl HirDisplay for Type {
2058 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
2059 self.ty.value.hir_fmt(f)
2060 }
2061}
2062
2063// FIXME: closures 2120// FIXME: closures
2064#[derive(Debug)] 2121#[derive(Debug)]
2065pub struct Callable { 2122pub struct Callable {