aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/cfg/src/cfg_expr.rs2
-rw-r--r--crates/hir/src/lib.rs89
-rw-r--r--crates/hir_def/src/attr.rs48
-rw-r--r--crates/hir_def/src/item_tree.rs12
-rw-r--r--crates/hir_def/src/lib.rs10
-rw-r--r--crates/hir_def/src/nameres/tests/diagnostics.rs3
-rw-r--r--crates/hir_def/src/test_db.rs9
-rw-r--r--crates/hir_expand/src/db.rs2
-rw-r--r--crates/hir_ty/src/autoderef.rs12
-rw-r--r--crates/hir_ty/src/db.rs23
-rw-r--r--crates/hir_ty/src/diagnostics/expr.rs21
-rw-r--r--crates/hir_ty/src/diagnostics/match_check.rs8
-rw-r--r--crates/hir_ty/src/diagnostics/unsafe_check.rs6
-rw-r--r--crates/hir_ty/src/display.rs186
-rw-r--r--crates/hir_ty/src/infer.rs70
-rw-r--r--crates/hir_ty/src/infer/coerce.rs38
-rw-r--r--crates/hir_ty/src/infer/expr.rs247
-rw-r--r--crates/hir_ty/src/infer/pat.rs41
-rw-r--r--crates/hir_ty/src/infer/path.rs18
-rw-r--r--crates/hir_ty/src/infer/unify.rs105
-rw-r--r--crates/hir_ty/src/lib.rs381
-rw-r--r--crates/hir_ty/src/lower.rs705
-rw-r--r--crates/hir_ty/src/method_resolution.rs88
-rw-r--r--crates/hir_ty/src/op.rs66
-rw-r--r--crates/hir_ty/src/tests.rs10
-rw-r--r--crates/hir_ty/src/traits.rs38
-rw-r--r--crates/hir_ty/src/traits/chalk.rs85
-rw-r--r--crates/hir_ty/src/traits/chalk/interner.rs2
-rw-r--r--crates/hir_ty/src/traits/chalk/mapping.rs238
-rw-r--r--crates/hir_ty/src/traits/chalk/tls.rs9
-rw-r--r--crates/ide/src/lib.rs9
-rw-r--r--crates/ide/src/runnables.rs344
-rw-r--r--crates/ide_assists/src/handlers/apply_demorgan.rs87
-rw-r--r--crates/ide_db/src/search.rs4
-rw-r--r--crates/mbe/src/expander.rs4
-rw-r--r--crates/mbe/src/expander/matcher.rs266
-rw-r--r--crates/mbe/src/expander/transcriber.rs19
-rw-r--r--crates/rust-analyzer/build.rs5
-rw-r--r--crates/rust-analyzer/src/cli/analysis_stats.rs6
-rw-r--r--crates/rust-analyzer/src/handlers.rs30
-rw-r--r--crates/rust-analyzer/src/lsp_ext.rs13
-rw-r--r--crates/rust-analyzer/src/main_loop.rs1
-rw-r--r--crates/rust-analyzer/src/to_proto.rs8
-rw-r--r--crates/tt/src/lib.rs47
44 files changed, 2075 insertions, 1340 deletions
diff --git a/crates/cfg/src/cfg_expr.rs b/crates/cfg/src/cfg_expr.rs
index 42327f1e1..069fc01d0 100644
--- a/crates/cfg/src/cfg_expr.rs
+++ b/crates/cfg/src/cfg_expr.rs
@@ -49,7 +49,7 @@ impl fmt::Display for CfgAtom {
49 } 49 }
50} 50}
51 51
52#[derive(Debug, Clone, PartialEq, Eq)] 52#[derive(Debug, Clone, PartialEq, Eq, Hash)]
53pub enum CfgExpr { 53pub enum CfgExpr {
54 Invalid, 54 Invalid,
55 Atom(CfgAtom), 55 Atom(CfgAtom),
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 58adc8fd3..10b8171be 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -51,11 +51,11 @@ use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
51use hir_ty::{ 51use hir_ty::{
52 autoderef, 52 autoderef,
53 display::{write_bounds_like_dyn_trait_with_prefix, HirDisplayError, HirFormatter}, 53 display::{write_bounds_like_dyn_trait_with_prefix, HirDisplayError, HirFormatter},
54 method_resolution, 54 method_resolution, to_assoc_type_id,
55 traits::{FnTrait, Solution, SolutionVariables}, 55 traits::{FnTrait, Solution, SolutionVariables},
56 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate, 56 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate,
57 InEnvironment, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, TraitEnvironment, 57 InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, Ty,
58 Ty, TyDefId, TyVariableKind, 58 TyDefId, TyKind, TyVariableKind,
59}; 59};
60use rustc_hash::FxHashSet; 60use rustc_hash::FxHashSet;
61use stdx::{format_to, impl_from}; 61use stdx::{format_to, impl_from};
@@ -677,7 +677,7 @@ impl_from!(Struct, Union, Enum for Adt);
677impl Adt { 677impl Adt {
678 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool { 678 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
679 let subst = db.generic_defaults(self.into()); 679 let subst = db.generic_defaults(self.into());
680 subst.iter().any(|ty| &ty.value == &Ty::Unknown) 680 subst.iter().any(|ty| ty.value.is_unknown())
681 } 681 }
682 682
683 /// Turns this ADT into a type. Any type parameters of the ADT will be 683 /// Turns this ADT into a type. Any type parameters of the ADT will be
@@ -802,7 +802,7 @@ impl Function {
802 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate(); 802 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
803 let ret_type = &db.function_data(self.id).ret_type; 803 let ret_type = &db.function_data(self.id).ret_type;
804 let ctx = hir_ty::TyLoweringContext::new(db, &resolver); 804 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
805 let ty = Ty::from_hir_ext(&ctx, ret_type).0; 805 let ty = ctx.lower_ty(ret_type);
806 Type::new_with_resolver_inner(db, krate, &resolver, ty) 806 Type::new_with_resolver_inner(db, krate, &resolver, ty)
807 } 807 }
808 808
@@ -817,7 +817,7 @@ impl Function {
817 let resolver = self.id.resolver(db.upcast()); 817 let resolver = self.id.resolver(db.upcast());
818 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate(); 818 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
819 let ctx = hir_ty::TyLoweringContext::new(db, &resolver); 819 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
820 let environment = TraitEnvironment::lower(db, &resolver); 820 let environment = db.trait_environment(self.id.into());
821 db.function_data(self.id) 821 db.function_data(self.id)
822 .params 822 .params
823 .iter() 823 .iter()
@@ -825,7 +825,7 @@ impl Function {
825 let ty = Type { 825 let ty = Type {
826 krate, 826 krate,
827 ty: InEnvironment { 827 ty: InEnvironment {
828 value: Ty::from_hir_ext(&ctx, type_ref).0, 828 value: ctx.lower_ty(type_ref),
829 environment: environment.clone(), 829 environment: environment.clone(),
830 }, 830 },
831 }; 831 };
@@ -1012,7 +1012,7 @@ pub struct TypeAlias {
1012impl TypeAlias { 1012impl TypeAlias {
1013 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool { 1013 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1014 let subst = db.generic_defaults(self.id.into()); 1014 let subst = db.generic_defaults(self.id.into());
1015 subst.iter().any(|ty| &ty.value == &Ty::Unknown) 1015 subst.iter().any(|ty| ty.value.is_unknown())
1016 } 1016 }
1017 1017
1018 pub fn module(self, db: &dyn HirDatabase) -> Module { 1018 pub fn module(self, db: &dyn HirDatabase) -> Module {
@@ -1384,7 +1384,7 @@ impl TypeParam {
1384 pub fn ty(self, db: &dyn HirDatabase) -> Type { 1384 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1385 let resolver = self.id.parent.resolver(db.upcast()); 1385 let resolver = self.id.parent.resolver(db.upcast());
1386 let krate = self.id.parent.module(db.upcast()).krate(); 1386 let krate = self.id.parent.module(db.upcast()).krate();
1387 let ty = Ty::Placeholder(self.id); 1387 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1388 Type::new_with_resolver_inner(db, krate, &resolver, ty) 1388 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1389 } 1389 }
1390 1390
@@ -1499,7 +1499,7 @@ impl Impl {
1499 let resolver = self.id.resolver(db.upcast()); 1499 let resolver = self.id.resolver(db.upcast());
1500 let krate = self.id.lookup(db.upcast()).container.krate(); 1500 let krate = self.id.lookup(db.upcast()).container.krate();
1501 let ctx = hir_ty::TyLoweringContext::new(db, &resolver); 1501 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1502 let ty = Ty::from_hir(&ctx, &impl_data.target_type); 1502 let ty = ctx.lower_ty(&impl_data.target_type);
1503 Type::new_with_resolver_inner(db, krate, &resolver, ty) 1503 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1504 } 1504 }
1505 1505
@@ -1563,13 +1563,15 @@ impl Type {
1563 resolver: &Resolver, 1563 resolver: &Resolver,
1564 ty: Ty, 1564 ty: Ty,
1565 ) -> Type { 1565 ) -> Type {
1566 let environment = TraitEnvironment::lower(db, &resolver); 1566 let environment =
1567 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1567 Type { krate, ty: InEnvironment { value: ty, environment } } 1568 Type { krate, ty: InEnvironment { value: ty, environment } }
1568 } 1569 }
1569 1570
1570 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type { 1571 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1571 let resolver = lexical_env.resolver(db.upcast()); 1572 let resolver = lexical_env.resolver(db.upcast());
1572 let environment = TraitEnvironment::lower(db, &resolver); 1573 let environment =
1574 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1573 Type { krate, ty: InEnvironment { value: ty, environment } } 1575 Type { krate, ty: InEnvironment { value: ty, environment } }
1574 } 1576 }
1575 1577
@@ -1584,25 +1586,25 @@ impl Type {
1584 } 1586 }
1585 1587
1586 pub fn is_unit(&self) -> bool { 1588 pub fn is_unit(&self) -> bool {
1587 matches!(self.ty.value, Ty::Tuple(0, ..)) 1589 matches!(self.ty.value.interned(&Interner), TyKind::Tuple(0, ..))
1588 } 1590 }
1589 pub fn is_bool(&self) -> bool { 1591 pub fn is_bool(&self) -> bool {
1590 matches!(self.ty.value, Ty::Scalar(Scalar::Bool)) 1592 matches!(self.ty.value.interned(&Interner), TyKind::Scalar(Scalar::Bool))
1591 } 1593 }
1592 1594
1593 pub fn is_mutable_reference(&self) -> bool { 1595 pub fn is_mutable_reference(&self) -> bool {
1594 matches!(self.ty.value, Ty::Ref(hir_ty::Mutability::Mut, ..)) 1596 matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1595 } 1597 }
1596 1598
1597 pub fn remove_ref(&self) -> Option<Type> { 1599 pub fn remove_ref(&self) -> Option<Type> {
1598 match &self.ty.value { 1600 match &self.ty.value.interned(&Interner) {
1599 Ty::Ref(.., substs) => Some(self.derived(substs[0].clone())), 1601 TyKind::Ref(.., substs) => Some(self.derived(substs[0].clone())),
1600 _ => None, 1602 _ => None,
1601 } 1603 }
1602 } 1604 }
1603 1605
1604 pub fn is_unknown(&self) -> bool { 1606 pub fn is_unknown(&self) -> bool {
1605 matches!(self.ty.value, Ty::Unknown) 1607 self.ty.value.is_unknown()
1606 } 1608 }
1607 1609
1608 /// Checks that particular type `ty` implements `std::future::Future`. 1610 /// Checks that particular type `ty` implements `std::future::Future`.
@@ -1683,8 +1685,11 @@ impl Type {
1683 .fill(args.iter().map(|t| t.ty.value.clone())) 1685 .fill(args.iter().map(|t| t.ty.value.clone()))
1684 .build(); 1686 .build();
1685 let predicate = ProjectionPredicate { 1687 let predicate = ProjectionPredicate {
1686 projection_ty: ProjectionTy { associated_ty: alias.id, parameters: subst }, 1688 projection_ty: ProjectionTy {
1687 ty: Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)), 1689 associated_ty: to_assoc_type_id(alias.id),
1690 parameters: subst,
1691 },
1692 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner),
1688 }; 1693 };
1689 let goal = Canonical { 1694 let goal = Canonical {
1690 value: InEnvironment::new( 1695 value: InEnvironment::new(
@@ -1712,26 +1717,23 @@ impl Type {
1712 } 1717 }
1713 1718
1714 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> { 1719 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1715 let def = match self.ty.value { 1720 let def = self.ty.value.callable_def(db);
1716 Ty::FnDef(def, _) => Some(def),
1717 _ => None,
1718 };
1719 1721
1720 let sig = self.ty.value.callable_sig(db)?; 1722 let sig = self.ty.value.callable_sig(db)?;
1721 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false }) 1723 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1722 } 1724 }
1723 1725
1724 pub fn is_closure(&self) -> bool { 1726 pub fn is_closure(&self) -> bool {
1725 matches!(&self.ty.value, Ty::Closure { .. }) 1727 matches!(&self.ty.value.interned(&Interner), TyKind::Closure { .. })
1726 } 1728 }
1727 1729
1728 pub fn is_fn(&self) -> bool { 1730 pub fn is_fn(&self) -> bool {
1729 matches!(&self.ty.value, Ty::FnDef(..) | Ty::Function { .. }) 1731 matches!(&self.ty.value.interned(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1730 } 1732 }
1731 1733
1732 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool { 1734 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1733 let adt_id = match self.ty.value { 1735 let adt_id = match self.ty.value.interned(&Interner) {
1734 Ty::Adt(hir_ty::AdtId(adt_id), ..) => adt_id, 1736 &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1735 _ => return false, 1737 _ => return false,
1736 }; 1738 };
1737 1739
@@ -1743,24 +1745,25 @@ impl Type {
1743 } 1745 }
1744 1746
1745 pub fn is_raw_ptr(&self) -> bool { 1747 pub fn is_raw_ptr(&self) -> bool {
1746 matches!(&self.ty.value, Ty::Raw(..)) 1748 matches!(&self.ty.value.interned(&Interner), TyKind::Raw(..))
1747 } 1749 }
1748 1750
1749 pub fn contains_unknown(&self) -> bool { 1751 pub fn contains_unknown(&self) -> bool {
1750 return go(&self.ty.value); 1752 return go(&self.ty.value);
1751 1753
1752 fn go(ty: &Ty) -> bool { 1754 fn go(ty: &Ty) -> bool {
1753 match ty { 1755 if ty.is_unknown() {
1754 Ty::Unknown => true, 1756 true
1755 _ => ty.substs().map_or(false, |substs| substs.iter().any(go)), 1757 } else {
1758 ty.substs().map_or(false, |substs| substs.iter().any(go))
1756 } 1759 }
1757 } 1760 }
1758 } 1761 }
1759 1762
1760 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> { 1763 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1761 let (variant_id, substs) = match self.ty.value { 1764 let (variant_id, substs) = match self.ty.value.interned(&Interner) {
1762 Ty::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs), 1765 &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1763 Ty::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs), 1766 &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1764 _ => return Vec::new(), 1767 _ => return Vec::new(),
1765 }; 1768 };
1766 1769
@@ -1775,7 +1778,7 @@ impl Type {
1775 } 1778 }
1776 1779
1777 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> { 1780 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1778 if let Ty::Tuple(_, substs) = &self.ty.value { 1781 if let TyKind::Tuple(_, substs) = &self.ty.value.interned(&Interner) {
1779 substs.iter().map(|ty| self.derived(ty.clone())).collect() 1782 substs.iter().map(|ty| self.derived(ty.clone())).collect()
1780 } else { 1783 } else {
1781 Vec::new() 1784 Vec::new()
@@ -1957,33 +1960,33 @@ impl Type {
1957 1960
1958 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) { 1961 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
1959 let ty = type_.ty.value.strip_references(); 1962 let ty = type_.ty.value.strip_references();
1960 match ty { 1963 match ty.interned(&Interner) {
1961 Ty::Adt(..) => { 1964 TyKind::Adt(..) => {
1962 cb(type_.derived(ty.clone())); 1965 cb(type_.derived(ty.clone()));
1963 } 1966 }
1964 Ty::AssociatedType(..) => { 1967 TyKind::AssociatedType(..) => {
1965 if let Some(_) = ty.associated_type_parent_trait(db) { 1968 if let Some(_) = ty.associated_type_parent_trait(db) {
1966 cb(type_.derived(ty.clone())); 1969 cb(type_.derived(ty.clone()));
1967 } 1970 }
1968 } 1971 }
1969 Ty::OpaqueType(..) => { 1972 TyKind::OpaqueType(..) => {
1970 if let Some(bounds) = ty.impl_trait_bounds(db) { 1973 if let Some(bounds) = ty.impl_trait_bounds(db) {
1971 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb); 1974 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1972 } 1975 }
1973 } 1976 }
1974 Ty::Alias(AliasTy::Opaque(opaque_ty)) => { 1977 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
1975 if let Some(bounds) = ty.impl_trait_bounds(db) { 1978 if let Some(bounds) = ty.impl_trait_bounds(db) {
1976 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb); 1979 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1977 } 1980 }
1978 1981
1979 walk_substs(db, type_, &opaque_ty.parameters, cb); 1982 walk_substs(db, type_, &opaque_ty.parameters, cb);
1980 } 1983 }
1981 Ty::Placeholder(_) => { 1984 TyKind::Placeholder(_) => {
1982 if let Some(bounds) = ty.impl_trait_bounds(db) { 1985 if let Some(bounds) = ty.impl_trait_bounds(db) {
1983 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb); 1986 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1984 } 1987 }
1985 } 1988 }
1986 Ty::Dyn(bounds) => { 1989 TyKind::Dyn(bounds) => {
1987 walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb); 1990 walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
1988 } 1991 }
1989 1992
diff --git a/crates/hir_def/src/attr.rs b/crates/hir_def/src/attr.rs
index 97cdbbb9e..7b41b148c 100644
--- a/crates/hir_def/src/attr.rs
+++ b/crates/hir_def/src/attr.rs
@@ -9,6 +9,7 @@ use hir_expand::{hygiene::Hygiene, name::AsName, AstId, InFile};
9use itertools::Itertools; 9use itertools::Itertools;
10use la_arena::ArenaMap; 10use la_arena::ArenaMap;
11use mbe::ast_to_token_tree; 11use mbe::ast_to_token_tree;
12use smallvec::{smallvec, SmallVec};
12use syntax::{ 13use syntax::{
13 ast::{self, AstNode, AttrsOwner}, 14 ast::{self, AstNode, AttrsOwner},
14 match_ast, AstToken, SmolStr, SyntaxNode, 15 match_ast, AstToken, SmolStr, SyntaxNode,
@@ -134,53 +135,42 @@ impl RawAttrs {
134 let crate_graph = db.crate_graph(); 135 let crate_graph = db.crate_graph();
135 let new_attrs = self 136 let new_attrs = self
136 .iter() 137 .iter()
137 .filter_map(|attr| { 138 .flat_map(|attr| -> SmallVec<[_; 1]> {
138 let attr = attr.clone(); 139 let attr = attr.clone();
139 let is_cfg_attr = 140 let is_cfg_attr =
140 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]); 141 attr.path.as_ident().map_or(false, |name| *name == hir_expand::name![cfg_attr]);
141 if !is_cfg_attr { 142 if !is_cfg_attr {
142 return Some(attr); 143 return smallvec![attr];
143 } 144 }
144 145
145 let subtree = match &attr.input { 146 let subtree = match &attr.input {
146 Some(AttrInput::TokenTree(it)) => it, 147 Some(AttrInput::TokenTree(it)) => it,
147 _ => return Some(attr), 148 _ => return smallvec![attr],
148 }; 149 };
149 150
150 // Input subtree is: `(cfg, attr)` 151 // Input subtree is: `(cfg, $(attr),+)`
151 // Split it up into a `cfg` and an `attr` subtree. 152 // Split it up into a `cfg` subtree and the `attr` subtrees.
152 // FIXME: There should be a common API for this. 153 // FIXME: There should be a common API for this.
153 let mut saw_comma = false; 154 let mut parts = subtree.token_trees.split(
154 let (mut cfg, attr): (Vec<_>, Vec<_>) = 155 |tt| matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ','),
155 subtree.clone().token_trees.into_iter().partition(|tree| { 156 );
156 if saw_comma { 157 let cfg = parts.next().unwrap();
157 return false; 158 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg.to_vec() };
158 }
159
160 match tree {
161 tt::TokenTree::Leaf(tt::Leaf::Punct(p)) if p.char == ',' => {
162 saw_comma = true;
163 }
164 _ => {}
165 }
166
167 true
168 });
169 cfg.pop(); // `,` ends up in here
170
171 let attr = Subtree { delimiter: None, token_trees: attr };
172 let cfg = Subtree { delimiter: subtree.delimiter, token_trees: cfg };
173 let cfg = CfgExpr::parse(&cfg); 159 let cfg = CfgExpr::parse(&cfg);
160 let attrs = parts.filter(|a| !a.is_empty()).filter_map(|attr| {
161 let tree = Subtree { delimiter: None, token_trees: attr.to_vec() };
162 let attr = ast::Attr::parse(&format!("#[{}]", tree)).ok()?;
163 let hygiene = Hygiene::new_unhygienic(); // FIXME
164 Attr::from_src(attr, &hygiene)
165 });
174 166
175 let cfg_options = &crate_graph[krate].cfg_options; 167 let cfg_options = &crate_graph[krate].cfg_options;
176 if cfg_options.check(&cfg) == Some(false) { 168 if cfg_options.check(&cfg) == Some(false) {
177 None 169 smallvec![]
178 } else { 170 } else {
179 cov_mark::hit!(cfg_attr_active); 171 cov_mark::hit!(cfg_attr_active);
180 172
181 let attr = ast::Attr::parse(&format!("#[{}]", attr)).ok()?; 173 attrs.collect()
182 let hygiene = Hygiene::new_unhygienic(); // FIXME
183 Attr::from_src(attr, &hygiene)
184 } 174 }
185 }) 175 })
186 .collect(); 176 .collect();
diff --git a/crates/hir_def/src/item_tree.rs b/crates/hir_def/src/item_tree.rs
index 6bb334573..09bcb10dc 100644
--- a/crates/hir_def/src/item_tree.rs
+++ b/crates/hir_def/src/item_tree.rs
@@ -209,18 +209,6 @@ impl ItemTree {
209 } 209 }
210 } 210 }
211 211
212 pub fn source<S: ItemTreeNode>(&self, db: &dyn DefDatabase, of: ItemTreeId<S>) -> S::Source {
213 // This unwrap cannot fail, since it has either succeeded above, or resulted in an empty
214 // ItemTree (in which case there is no valid `FileItemTreeId` to call this method with).
215 let root =
216 db.parse_or_expand(of.file_id).expect("parse_or_expand failed on constructed ItemTree");
217
218 let id = self[of.value].ast_id();
219 let map = db.ast_id_map(of.file_id);
220 let ptr = map.get(id);
221 ptr.to_node(&root)
222 }
223
224 fn data(&self) -> &ItemTreeData { 212 fn data(&self) -> &ItemTreeData {
225 self.data.as_ref().expect("attempted to access data of empty ItemTree") 213 self.data.as_ref().expect("attempted to access data of empty ItemTree")
226 } 214 }
diff --git a/crates/hir_def/src/lib.rs b/crates/hir_def/src/lib.rs
index 6d11c5be4..c6655c5fb 100644
--- a/crates/hir_def/src/lib.rs
+++ b/crates/hir_def/src/lib.rs
@@ -341,6 +341,16 @@ pub enum DefWithBodyId {
341 341
342impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId); 342impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
343 343
344impl DefWithBodyId {
345 pub fn as_generic_def_id(self) -> Option<GenericDefId> {
346 match self {
347 DefWithBodyId::FunctionId(f) => Some(f.into()),
348 DefWithBodyId::StaticId(_) => None,
349 DefWithBodyId::ConstId(c) => Some(c.into()),
350 }
351 }
352}
353
344#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] 354#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
345pub enum AssocItemId { 355pub enum AssocItemId {
346 FunctionId(FunctionId), 356 FunctionId(FunctionId),
diff --git a/crates/hir_def/src/nameres/tests/diagnostics.rs b/crates/hir_def/src/nameres/tests/diagnostics.rs
index d5ef8ceb5..1b8e885b0 100644
--- a/crates/hir_def/src/nameres/tests/diagnostics.rs
+++ b/crates/hir_def/src/nameres/tests/diagnostics.rs
@@ -149,6 +149,9 @@ fn inactive_via_cfg_attr() {
149 #[cfg_attr(not(never), cfg(not(no)))] fn f() {} 149 #[cfg_attr(not(never), cfg(not(no)))] fn f() {}
150 150
151 #[cfg_attr(never, cfg(no))] fn g() {} 151 #[cfg_attr(never, cfg(no))] fn g() {}
152
153 #[cfg_attr(not(never), inline, cfg(no))] fn h() {}
154 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: no is disabled
152 "#, 155 "#,
153 ); 156 );
154} 157}
diff --git a/crates/hir_def/src/test_db.rs b/crates/hir_def/src/test_db.rs
index eda982c85..10977761c 100644
--- a/crates/hir_def/src/test_db.rs
+++ b/crates/hir_def/src/test_db.rs
@@ -15,7 +15,7 @@ use rustc_hash::FxHashSet;
15use syntax::{algo, ast, AstNode, TextRange, TextSize}; 15use syntax::{algo, ast, AstNode, TextRange, TextSize};
16use test_utils::extract_annotations; 16use test_utils::extract_annotations;
17 17
18use crate::{db::DefDatabase, nameres::DefMap, Lookup, ModuleDefId, ModuleId}; 18use crate::{db::DefDatabase, nameres::DefMap, src::HasSource, Lookup, ModuleDefId, ModuleId};
19 19
20#[salsa::database( 20#[salsa::database(
21 base_db::SourceDatabaseExtStorage, 21 base_db::SourceDatabaseExtStorage,
@@ -115,14 +115,9 @@ impl TestDB {
115 if file_id != position.file_id.into() { 115 if file_id != position.file_id.into() {
116 continue; 116 continue;
117 } 117 }
118 let root = self.parse_or_expand(file_id).unwrap();
119 let ast_map = self.ast_id_map(file_id);
120 let item_tree = self.item_tree(file_id);
121 for decl in module.scope.declarations() { 118 for decl in module.scope.declarations() {
122 if let ModuleDefId::FunctionId(it) = decl { 119 if let ModuleDefId::FunctionId(it) = decl {
123 let ast = 120 let range = it.lookup(self).source(self).value.syntax().text_range();
124 ast_map.get(item_tree[it.lookup(self).id.value].ast_id).to_node(&root);
125 let range = ast.syntax().text_range();
126 121
127 if !range.contains(position.offset) { 122 if !range.contains(position.offset) {
128 continue; 123 continue;
diff --git a/crates/hir_expand/src/db.rs b/crates/hir_expand/src/db.rs
index cb6e23320..9086e6c17 100644
--- a/crates/hir_expand/src/db.rs
+++ b/crates/hir_expand/src/db.rs
@@ -340,6 +340,8 @@ fn parse_macro_with_arg(
340 None => return ExpandResult { value: None, err: result.err }, 340 None => return ExpandResult { value: None, err: result.err },
341 }; 341 };
342 342
343 log::debug!("expanded = {}", tt.as_debug_string());
344
343 let fragment_kind = to_fragment_kind(db, macro_call_id); 345 let fragment_kind = to_fragment_kind(db, macro_call_id);
344 346
345 let (parse, rev_token_map) = match mbe::token_tree_to_syntax_node(&tt, fragment_kind) { 347 let (parse, rev_token_map) = match mbe::token_tree_to_syntax_node(&tt, fragment_kind) {
diff --git a/crates/hir_ty/src/autoderef.rs b/crates/hir_ty/src/autoderef.rs
index be1fd1f13..d739d5d60 100644
--- a/crates/hir_ty/src/autoderef.rs
+++ b/crates/hir_ty/src/autoderef.rs
@@ -12,9 +12,10 @@ use log::{info, warn};
12 12
13use crate::{ 13use crate::{
14 db::HirDatabase, 14 db::HirDatabase,
15 to_assoc_type_id,
15 traits::{InEnvironment, Solution}, 16 traits::{InEnvironment, Solution},
16 utils::generics, 17 utils::generics,
17 BoundVar, Canonical, DebruijnIndex, Obligation, Substs, TraitRef, Ty, 18 BoundVar, Canonical, DebruijnIndex, Interner, Obligation, Substs, TraitRef, Ty, TyKind,
18}; 19};
19 20
20const AUTODEREF_RECURSION_LIMIT: usize = 10; 21const AUTODEREF_RECURSION_LIMIT: usize = 10;
@@ -81,8 +82,9 @@ fn deref_by_trait(
81 82
82 // Now do the assoc type projection 83 // Now do the assoc type projection
83 let projection = super::traits::ProjectionPredicate { 84 let projection = super::traits::ProjectionPredicate {
84 ty: Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, ty.value.kinds.len())), 85 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, ty.value.kinds.len()))
85 projection_ty: super::ProjectionTy { associated_ty: target, parameters }, 86 .intern(&Interner),
87 projection_ty: super::ProjectionTy { associated_ty: to_assoc_type_id(target), parameters },
86 }; 88 };
87 89
88 let obligation = super::Obligation::Projection(projection); 90 let obligation = super::Obligation::Projection(projection);
@@ -114,8 +116,8 @@ fn deref_by_trait(
114 // new variables in that case 116 // new variables in that case
115 117
116 for i in 1..vars.0.kinds.len() { 118 for i in 1..vars.0.kinds.len() {
117 if vars.0.value[i - 1] 119 if vars.0.value[i - 1].interned(&Interner)
118 != Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i - 1)) 120 != &TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i - 1))
119 { 121 {
120 warn!("complex solution for derefing {:?}: {:?}, ignoring", ty.value, solution); 122 warn!("complex solution for derefing {:?}: {:?}, ignoring", ty.value, solution);
121 return None; 123 return None;
diff --git a/crates/hir_ty/src/db.rs b/crates/hir_ty/src/db.rs
index 06714409f..74a048672 100644
--- a/crates/hir_ty/src/db.rs
+++ b/crates/hir_ty/src/db.rs
@@ -12,7 +12,7 @@ use la_arena::ArenaMap;
12use crate::{ 12use crate::{
13 method_resolution::{InherentImpls, TraitImpls}, 13 method_resolution::{InherentImpls, TraitImpls},
14 traits::chalk, 14 traits::chalk,
15 Binders, CallableDefId, GenericPredicate, InferenceResult, OpaqueTyId, PolyFnSig, 15 Binders, CallableDefId, FnDefId, GenericPredicate, ImplTraitId, InferenceResult, PolyFnSig,
16 ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId, 16 ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId,
17}; 17};
18use hir_expand::name::Name; 18use hir_expand::name::Name;
@@ -65,6 +65,9 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
65 #[salsa::invoke(crate::lower::generic_predicates_query)] 65 #[salsa::invoke(crate::lower::generic_predicates_query)]
66 fn generic_predicates(&self, def: GenericDefId) -> Arc<[Binders<GenericPredicate>]>; 66 fn generic_predicates(&self, def: GenericDefId) -> Arc<[Binders<GenericPredicate>]>;
67 67
68 #[salsa::invoke(crate::lower::trait_environment_query)]
69 fn trait_environment(&self, def: GenericDefId) -> Arc<crate::TraitEnvironment>;
70
68 #[salsa::invoke(crate::lower::generic_defaults_query)] 71 #[salsa::invoke(crate::lower::generic_defaults_query)]
69 fn generic_defaults(&self, def: GenericDefId) -> Arc<[Binders<Ty>]>; 72 fn generic_defaults(&self, def: GenericDefId) -> Arc<[Binders<Ty>]>;
70 73
@@ -81,11 +84,11 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
81 #[salsa::interned] 84 #[salsa::interned]
82 fn intern_callable_def(&self, callable_def: CallableDefId) -> InternedCallableDefId; 85 fn intern_callable_def(&self, callable_def: CallableDefId) -> InternedCallableDefId;
83 #[salsa::interned] 86 #[salsa::interned]
84 fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId; 87 fn intern_type_param_id(&self, param_id: TypeParamId) -> InternedTypeParamId;
85 #[salsa::interned] 88 #[salsa::interned]
86 fn intern_impl_trait_id(&self, id: OpaqueTyId) -> InternedOpaqueTyId; 89 fn intern_impl_trait_id(&self, id: ImplTraitId) -> InternedOpaqueTyId;
87 #[salsa::interned] 90 #[salsa::interned]
88 fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> ClosureId; 91 fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> InternedClosureId;
89 92
90 #[salsa::invoke(chalk::associated_ty_data_query)] 93 #[salsa::invoke(chalk::associated_ty_data_query)]
91 fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>; 94 fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>;
@@ -100,10 +103,10 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
100 fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>; 103 fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>;
101 104
102 #[salsa::invoke(crate::traits::chalk::fn_def_datum_query)] 105 #[salsa::invoke(crate::traits::chalk::fn_def_datum_query)]
103 fn fn_def_datum(&self, krate: CrateId, fn_def_id: chalk::FnDefId) -> Arc<chalk::FnDefDatum>; 106 fn fn_def_datum(&self, krate: CrateId, fn_def_id: FnDefId) -> Arc<chalk::FnDefDatum>;
104 107
105 #[salsa::invoke(crate::traits::chalk::fn_def_variance_query)] 108 #[salsa::invoke(crate::traits::chalk::fn_def_variance_query)]
106 fn fn_def_variance(&self, krate: CrateId, fn_def_id: chalk::FnDefId) -> chalk::Variances; 109 fn fn_def_variance(&self, krate: CrateId, fn_def_id: FnDefId) -> chalk::Variances;
107 110
108 #[salsa::invoke(crate::traits::chalk::adt_variance_query)] 111 #[salsa::invoke(crate::traits::chalk::adt_variance_query)]
109 fn adt_variance(&self, krate: CrateId, adt_id: chalk::AdtId) -> chalk::Variances; 112 fn adt_variance(&self, krate: CrateId, adt_id: chalk::AdtId) -> chalk::Variances;
@@ -149,16 +152,16 @@ fn hir_database_is_object_safe() {
149} 152}
150 153
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub struct GlobalTypeParamId(salsa::InternId); 155pub struct InternedTypeParamId(salsa::InternId);
153impl_intern_key!(GlobalTypeParamId); 156impl_intern_key!(InternedTypeParamId);
154 157
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
156pub struct InternedOpaqueTyId(salsa::InternId); 159pub struct InternedOpaqueTyId(salsa::InternId);
157impl_intern_key!(InternedOpaqueTyId); 160impl_intern_key!(InternedOpaqueTyId);
158 161
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160pub struct ClosureId(salsa::InternId); 163pub struct InternedClosureId(salsa::InternId);
161impl_intern_key!(ClosureId); 164impl_intern_key!(InternedClosureId);
162 165
163/// This exists just for Chalk, because Chalk just has a single `FnDefId` where 166/// This exists just for Chalk, because Chalk just has a single `FnDefId` where
164/// we have different IDs for struct and enum variant constructors. 167/// we have different IDs for struct and enum variant constructors.
diff --git a/crates/hir_ty/src/diagnostics/expr.rs b/crates/hir_ty/src/diagnostics/expr.rs
index 2751cd304..b2bfd68d4 100644
--- a/crates/hir_ty/src/diagnostics/expr.rs
+++ b/crates/hir_ty/src/diagnostics/expr.rs
@@ -15,7 +15,7 @@ use crate::{
15 MissingPatFields, RemoveThisSemicolon, 15 MissingPatFields, RemoveThisSemicolon,
16 }, 16 },
17 utils::variant_data, 17 utils::variant_data,
18 AdtId, InferenceResult, Ty, 18 AdtId, InferenceResult, Interner, Ty, TyKind,
19}; 19};
20 20
21pub(crate) use hir_def::{ 21pub(crate) use hir_def::{
@@ -289,11 +289,10 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
289 let (body, source_map): (Arc<Body>, Arc<BodySourceMap>) = 289 let (body, source_map): (Arc<Body>, Arc<BodySourceMap>) =
290 db.body_with_source_map(self.owner.into()); 290 db.body_with_source_map(self.owner.into());
291 291
292 let match_expr_ty = match infer.type_of_expr.get(match_expr) { 292 let match_expr_ty = if infer.type_of_expr[match_expr].is_unknown() {
293 // If we can't resolve the type of the match expression 293 return;
294 // we cannot perform exhaustiveness checks. 294 } else {
295 None | Some(Ty::Unknown) => return, 295 &infer.type_of_expr[match_expr]
296 Some(ty) => ty,
297 }; 296 };
298 297
299 let cx = MatchCheckCtx { match_expr, body, infer: infer.clone(), db }; 298 let cx = MatchCheckCtx { match_expr, body, infer: infer.clone(), db };
@@ -379,14 +378,14 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
379 _ => return, 378 _ => return,
380 }; 379 };
381 380
382 let (params, required) = match mismatch.expected { 381 let (params, required) = match mismatch.expected.interned(&Interner) {
383 Ty::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters) 382 TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters)
384 if enum_id == core_result_enum => 383 if *enum_id == core_result_enum =>
385 { 384 {
386 (parameters, "Ok".to_string()) 385 (parameters, "Ok".to_string())
387 } 386 }
388 Ty::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters) 387 TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters)
389 if enum_id == core_option_enum => 388 if *enum_id == core_option_enum =>
390 { 389 {
391 (parameters, "Some".to_string()) 390 (parameters, "Some".to_string())
392 } 391 }
diff --git a/crates/hir_ty/src/diagnostics/match_check.rs b/crates/hir_ty/src/diagnostics/match_check.rs
index 04d39c571..5a5cdcbf3 100644
--- a/crates/hir_ty/src/diagnostics/match_check.rs
+++ b/crates/hir_ty/src/diagnostics/match_check.rs
@@ -227,7 +227,7 @@ use hir_def::{
227use la_arena::Idx; 227use la_arena::Idx;
228use smallvec::{smallvec, SmallVec}; 228use smallvec::{smallvec, SmallVec};
229 229
230use crate::{db::HirDatabase, AdtId, InferenceResult, Ty}; 230use crate::{db::HirDatabase, AdtId, InferenceResult, Interner, TyKind};
231 231
232#[derive(Debug, Clone, Copy)] 232#[derive(Debug, Clone, Copy)]
233/// Either a pattern from the source code being analyzed, represented as 233/// Either a pattern from the source code being analyzed, represented as
@@ -626,13 +626,13 @@ pub(super) fn is_useful(
626 // - enum with no variants 626 // - enum with no variants
627 // - `!` type 627 // - `!` type
628 // In those cases, no match arm is useful. 628 // In those cases, no match arm is useful.
629 match cx.infer[cx.match_expr].strip_references() { 629 match cx.infer[cx.match_expr].strip_references().interned(&Interner) {
630 Ty::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ..) => { 630 TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ..) => {
631 if cx.db.enum_data(*enum_id).variants.is_empty() { 631 if cx.db.enum_data(*enum_id).variants.is_empty() {
632 return Ok(Usefulness::NotUseful); 632 return Ok(Usefulness::NotUseful);
633 } 633 }
634 } 634 }
635 Ty::Never => return Ok(Usefulness::NotUseful), 635 TyKind::Never => return Ok(Usefulness::NotUseful),
636 _ => (), 636 _ => (),
637 } 637 }
638 638
diff --git a/crates/hir_ty/src/diagnostics/unsafe_check.rs b/crates/hir_ty/src/diagnostics/unsafe_check.rs
index e77a20fea..20bb64827 100644
--- a/crates/hir_ty/src/diagnostics/unsafe_check.rs
+++ b/crates/hir_ty/src/diagnostics/unsafe_check.rs
@@ -11,7 +11,7 @@ use hir_def::{
11}; 11};
12use hir_expand::diagnostics::DiagnosticSink; 12use hir_expand::diagnostics::DiagnosticSink;
13 13
14use crate::{db::HirDatabase, diagnostics::MissingUnsafe, InferenceResult, Ty}; 14use crate::{db::HirDatabase, diagnostics::MissingUnsafe, InferenceResult, Interner, TyKind};
15 15
16pub(super) struct UnsafeValidator<'a, 'b: 'a> { 16pub(super) struct UnsafeValidator<'a, 'b: 'a> {
17 owner: DefWithBodyId, 17 owner: DefWithBodyId,
@@ -85,7 +85,7 @@ fn walk_unsafe(
85 let expr = &body.exprs[current]; 85 let expr = &body.exprs[current];
86 match expr { 86 match expr {
87 &Expr::Call { callee, .. } => { 87 &Expr::Call { callee, .. } => {
88 if let Some(func) = infer[callee].as_fn_def() { 88 if let Some(func) = infer[callee].as_fn_def(db) {
89 if db.function_data(func).is_unsafe { 89 if db.function_data(func).is_unsafe {
90 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block }); 90 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block });
91 } 91 }
@@ -110,7 +110,7 @@ fn walk_unsafe(
110 } 110 }
111 } 111 }
112 Expr::UnaryOp { expr, op: UnaryOp::Deref } => { 112 Expr::UnaryOp { expr, op: UnaryOp::Deref } => {
113 if let Ty::Raw(..) = &infer[*expr] { 113 if let TyKind::Raw(..) = &infer[*expr].interned(&Interner) {
114 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block }); 114 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block });
115 } 115 }
116 } 116 }
diff --git a/crates/hir_ty/src/display.rs b/crates/hir_ty/src/display.rs
index ab51cb0a6..e6473586b 100644
--- a/crates/hir_ty/src/display.rs
+++ b/crates/hir_ty/src/display.rs
@@ -11,9 +11,10 @@ use hir_def::{
11use hir_expand::name::Name; 11use hir_expand::name::Name;
12 12
13use crate::{ 13use crate::{
14 db::HirDatabase, primitive, utils::generics, AdtId, AliasTy, CallableDefId, CallableSig, 14 db::HirDatabase, from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, primitive,
15 GenericPredicate, Lifetime, Obligation, OpaqueTy, OpaqueTyId, ProjectionTy, Scalar, Substs, 15 to_assoc_type_id, traits::chalk::from_chalk, utils::generics, AdtId, AliasTy, CallableDefId,
16 TraitRef, Ty, 16 CallableSig, GenericPredicate, ImplTraitId, Interner, Lifetime, Obligation, OpaqueTy,
17 ProjectionTy, Scalar, Substs, TraitRef, Ty, TyKind,
17}; 18};
18 19
19pub struct HirFormatter<'a> { 20pub struct HirFormatter<'a> {
@@ -256,7 +257,7 @@ impl HirDisplay for ProjectionTy {
256 f.write_joined(&self.parameters[1..], ", ")?; 257 f.write_joined(&self.parameters[1..], ", ")?;
257 write!(f, ">")?; 258 write!(f, ">")?;
258 } 259 }
259 write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?; 260 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty)).name)?;
260 Ok(()) 261 Ok(())
261 } 262 }
262} 263}
@@ -267,32 +268,32 @@ impl HirDisplay for Ty {
267 return write!(f, "{}", TYPE_HINT_TRUNCATION); 268 return write!(f, "{}", TYPE_HINT_TRUNCATION);
268 } 269 }
269 270
270 match self { 271 match self.interned(&Interner) {
271 Ty::Never => write!(f, "!")?, 272 TyKind::Never => write!(f, "!")?,
272 Ty::Str => write!(f, "str")?, 273 TyKind::Str => write!(f, "str")?,
273 Ty::Scalar(Scalar::Bool) => write!(f, "bool")?, 274 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
274 Ty::Scalar(Scalar::Char) => write!(f, "char")?, 275 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
275 &Ty::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?, 276 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
276 &Ty::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?, 277 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
277 &Ty::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?, 278 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
278 Ty::Slice(parameters) => { 279 TyKind::Slice(parameters) => {
279 let t = parameters.as_single(); 280 let t = parameters.as_single();
280 write!(f, "[")?; 281 write!(f, "[")?;
281 t.hir_fmt(f)?; 282 t.hir_fmt(f)?;
282 write!(f, "]")?; 283 write!(f, "]")?;
283 } 284 }
284 Ty::Array(parameters) => { 285 TyKind::Array(parameters) => {
285 let t = parameters.as_single(); 286 let t = parameters.as_single();
286 write!(f, "[")?; 287 write!(f, "[")?;
287 t.hir_fmt(f)?; 288 t.hir_fmt(f)?;
288 write!(f, "; _]")?; 289 write!(f, "; _]")?;
289 } 290 }
290 Ty::Raw(m, parameters) | Ty::Ref(m, parameters) => { 291 TyKind::Raw(m, parameters) | TyKind::Ref(m, parameters) => {
291 let t = parameters.as_single(); 292 let t = parameters.as_single();
292 let ty_display = 293 let ty_display =
293 t.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target); 294 t.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
294 295
295 if matches!(self, Ty::Raw(..)) { 296 if matches!(self.interned(&Interner), TyKind::Raw(..)) {
296 write!( 297 write!(
297 f, 298 f,
298 "*{}", 299 "*{}",
@@ -312,22 +313,26 @@ impl HirDisplay for Ty {
312 )?; 313 )?;
313 } 314 }
314 315
316 // FIXME: all this just to decide whether to use parentheses...
315 let datas; 317 let datas;
316 let predicates = match t { 318 let predicates = match t.interned(&Interner) {
317 Ty::Dyn(predicates) if predicates.len() > 1 => { 319 TyKind::Dyn(predicates) if predicates.len() > 1 => {
318 Cow::Borrowed(predicates.as_ref()) 320 Cow::Borrowed(predicates.as_ref())
319 } 321 }
320 &Ty::Alias(AliasTy::Opaque(OpaqueTy { 322 &TyKind::Alias(AliasTy::Opaque(OpaqueTy { opaque_ty_id, ref parameters })) => {
321 opaque_ty_id: OpaqueTyId::ReturnTypeImplTrait(func, idx), 323 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
322 ref parameters, 324 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
323 })) => { 325 datas =
324 datas = 326 f.db.return_type_impl_traits(func)
325 f.db.return_type_impl_traits(func).expect("impl trait id without data"); 327 .expect("impl trait id without data");
326 let data = (*datas) 328 let data = (*datas)
327 .as_ref() 329 .as_ref()
328 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone()); 330 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
329 let bounds = data.subst(parameters); 331 let bounds = data.subst(parameters);
330 Cow::Owned(bounds.value) 332 Cow::Owned(bounds.value)
333 } else {
334 Cow::Borrowed(&[][..])
335 }
331 } 336 }
332 _ => Cow::Borrowed(&[][..]), 337 _ => Cow::Borrowed(&[][..]),
333 }; 338 };
@@ -347,7 +352,7 @@ impl HirDisplay for Ty {
347 write!(f, "{}", ty_display)?; 352 write!(f, "{}", ty_display)?;
348 } 353 }
349 } 354 }
350 Ty::Tuple(_, substs) => { 355 TyKind::Tuple(_, substs) => {
351 if substs.len() == 1 { 356 if substs.len() == 1 {
352 write!(f, "(")?; 357 write!(f, "(")?;
353 substs[0].hir_fmt(f)?; 358 substs[0].hir_fmt(f)?;
@@ -358,12 +363,12 @@ impl HirDisplay for Ty {
358 write!(f, ")")?; 363 write!(f, ")")?;
359 } 364 }
360 } 365 }
361 Ty::Function(fn_ptr) => { 366 TyKind::Function(fn_ptr) => {
362 let sig = CallableSig::from_fn_ptr(fn_ptr); 367 let sig = CallableSig::from_fn_ptr(fn_ptr);
363 sig.hir_fmt(f)?; 368 sig.hir_fmt(f)?;
364 } 369 }
365 Ty::FnDef(def, parameters) => { 370 TyKind::FnDef(def, parameters) => {
366 let def = *def; 371 let def = from_chalk(f.db, *def);
367 let sig = f.db.callable_item_signature(def).subst(parameters); 372 let sig = f.db.callable_item_signature(def).subst(parameters);
368 match def { 373 match def {
369 CallableDefId::FunctionId(ff) => { 374 CallableDefId::FunctionId(ff) => {
@@ -401,7 +406,7 @@ impl HirDisplay for Ty {
401 write!(f, " -> {}", ret_display)?; 406 write!(f, " -> {}", ret_display)?;
402 } 407 }
403 } 408 }
404 Ty::Adt(AdtId(def_id), parameters) => { 409 TyKind::Adt(AdtId(def_id), parameters) => {
405 match f.display_target { 410 match f.display_target {
406 DisplayTarget::Diagnostics | DisplayTarget::Test => { 411 DisplayTarget::Diagnostics | DisplayTarget::Test => {
407 let name = match *def_id { 412 let name = match *def_id {
@@ -427,37 +432,39 @@ impl HirDisplay for Ty {
427 } 432 }
428 433
429 if parameters.len() > 0 { 434 if parameters.len() > 0 {
430 let parameters_to_write = 435 let parameters_to_write = if f.display_target.is_source_code()
431 if f.display_target.is_source_code() || f.omit_verbose_types() { 436 || f.omit_verbose_types()
432 match self 437 {
433 .as_generic_def() 438 match self
434 .map(|generic_def_id| f.db.generic_defaults(generic_def_id)) 439 .as_generic_def(f.db)
435 .filter(|defaults| !defaults.is_empty()) 440 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
436 { 441 .filter(|defaults| !defaults.is_empty())
437 None => parameters.0.as_ref(), 442 {
438 Some(default_parameters) => { 443 None => parameters.0.as_ref(),
439 let mut default_from = 0; 444 Some(default_parameters) => {
440 for (i, parameter) in parameters.iter().enumerate() { 445 let mut default_from = 0;
441 match (parameter, default_parameters.get(i)) { 446 for (i, parameter) in parameters.iter().enumerate() {
442 (&Ty::Unknown, _) | (_, None) => { 447 match (parameter.interned(&Interner), default_parameters.get(i))
448 {
449 (&TyKind::Unknown, _) | (_, None) => {
450 default_from = i + 1;
451 }
452 (_, Some(default_parameter)) => {
453 let actual_default = default_parameter
454 .clone()
455 .subst(&parameters.prefix(i));
456 if parameter != &actual_default {
443 default_from = i + 1; 457 default_from = i + 1;
444 } 458 }
445 (_, Some(default_parameter)) => {
446 let actual_default = default_parameter
447 .clone()
448 .subst(&parameters.prefix(i));
449 if parameter != &actual_default {
450 default_from = i + 1;
451 }
452 }
453 } 459 }
454 } 460 }
455 &parameters.0[0..default_from]
456 } 461 }
462 &parameters.0[0..default_from]
457 } 463 }
458 } else { 464 }
459 parameters.0.as_ref() 465 } else {
460 }; 466 parameters.0.as_ref()
467 };
461 if !parameters_to_write.is_empty() { 468 if !parameters_to_write.is_empty() {
462 write!(f, "<")?; 469 write!(f, "<")?;
463 f.write_joined(parameters_to_write, ", ")?; 470 f.write_joined(parameters_to_write, ", ")?;
@@ -465,13 +472,14 @@ impl HirDisplay for Ty {
465 } 472 }
466 } 473 }
467 } 474 }
468 Ty::AssociatedType(type_alias, parameters) => { 475 TyKind::AssociatedType(assoc_type_id, parameters) => {
476 let type_alias = from_assoc_type_id(*assoc_type_id);
469 let trait_ = match type_alias.lookup(f.db.upcast()).container { 477 let trait_ = match type_alias.lookup(f.db.upcast()).container {
470 AssocContainerId::TraitId(it) => it, 478 AssocContainerId::TraitId(it) => it,
471 _ => panic!("not an associated type"), 479 _ => panic!("not an associated type"),
472 }; 480 };
473 let trait_ = f.db.trait_data(trait_); 481 let trait_ = f.db.trait_data(trait_);
474 let type_alias_data = f.db.type_alias_data(*type_alias); 482 let type_alias_data = f.db.type_alias_data(type_alias);
475 483
476 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types) 484 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
477 if f.display_target.is_test() { 485 if f.display_target.is_test() {
@@ -482,19 +490,22 @@ impl HirDisplay for Ty {
482 write!(f, ">")?; 490 write!(f, ">")?;
483 } 491 }
484 } else { 492 } else {
485 let projection_ty = 493 let projection_ty = ProjectionTy {
486 ProjectionTy { associated_ty: *type_alias, parameters: parameters.clone() }; 494 associated_ty: to_assoc_type_id(type_alias),
495 parameters: parameters.clone(),
496 };
487 497
488 projection_ty.hir_fmt(f)?; 498 projection_ty.hir_fmt(f)?;
489 } 499 }
490 } 500 }
491 Ty::ForeignType(type_alias) => { 501 TyKind::ForeignType(type_alias) => {
492 let type_alias = f.db.type_alias_data(*type_alias); 502 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
493 write!(f, "{}", type_alias.name)?; 503 write!(f, "{}", type_alias.name)?;
494 } 504 }
495 Ty::OpaqueType(opaque_ty_id, parameters) => { 505 TyKind::OpaqueType(opaque_ty_id, parameters) => {
496 match opaque_ty_id { 506 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
497 &OpaqueTyId::ReturnTypeImplTrait(func, idx) => { 507 match impl_trait_id {
508 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
498 let datas = 509 let datas =
499 f.db.return_type_impl_traits(func).expect("impl trait id without data"); 510 f.db.return_type_impl_traits(func).expect("impl trait id without data");
500 let data = (*datas) 511 let data = (*datas)
@@ -504,14 +515,14 @@ impl HirDisplay for Ty {
504 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?; 515 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?;
505 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution 516 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
506 } 517 }
507 OpaqueTyId::AsyncBlockTypeImplTrait(..) => { 518 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
508 write!(f, "impl Future<Output = ")?; 519 write!(f, "impl Future<Output = ")?;
509 parameters[0].hir_fmt(f)?; 520 parameters[0].hir_fmt(f)?;
510 write!(f, ">")?; 521 write!(f, ">")?;
511 } 522 }
512 } 523 }
513 } 524 }
514 Ty::Closure(.., substs) => { 525 TyKind::Closure(.., substs) => {
515 let sig = substs[0].callable_sig(f.db); 526 let sig = substs[0].callable_sig(f.db);
516 if let Some(sig) = sig { 527 if let Some(sig) = sig {
517 if sig.params().is_empty() { 528 if sig.params().is_empty() {
@@ -535,7 +546,8 @@ impl HirDisplay for Ty {
535 write!(f, "{{closure}}")?; 546 write!(f, "{{closure}}")?;
536 } 547 }
537 } 548 }
538 Ty::Placeholder(id) => { 549 TyKind::Placeholder(idx) => {
550 let id = from_placeholder_idx(f.db, *idx);
539 let generics = generics(f.db.upcast(), id.parent); 551 let generics = generics(f.db.upcast(), id.parent);
540 let param_data = &generics.params.types[id.local_id]; 552 let param_data = &generics.params.types[id.local_id];
541 match param_data.provenance { 553 match param_data.provenance {
@@ -543,8 +555,8 @@ impl HirDisplay for Ty {
543 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))? 555 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
544 } 556 }
545 TypeParamProvenance::ArgumentImplTrait => { 557 TypeParamProvenance::ArgumentImplTrait => {
546 let bounds = f.db.generic_predicates_for_param(*id); 558 let bounds = f.db.generic_predicates_for_param(id);
547 let substs = Substs::type_params_for_generics(&generics); 559 let substs = Substs::type_params_for_generics(f.db, &generics);
548 write_bounds_like_dyn_trait_with_prefix( 560 write_bounds_like_dyn_trait_with_prefix(
549 "impl", 561 "impl",
550 &bounds.iter().map(|b| b.clone().subst(&substs)).collect::<Vec<_>>(), 562 &bounds.iter().map(|b| b.clone().subst(&substs)).collect::<Vec<_>>(),
@@ -553,14 +565,15 @@ impl HirDisplay for Ty {
553 } 565 }
554 } 566 }
555 } 567 }
556 Ty::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index)?, 568 TyKind::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index)?,
557 Ty::Dyn(predicates) => { 569 TyKind::Dyn(predicates) => {
558 write_bounds_like_dyn_trait_with_prefix("dyn", predicates, f)?; 570 write_bounds_like_dyn_trait_with_prefix("dyn", predicates, f)?;
559 } 571 }
560 Ty::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?, 572 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
561 Ty::Alias(AliasTy::Opaque(opaque_ty)) => { 573 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
562 match opaque_ty.opaque_ty_id { 574 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
563 OpaqueTyId::ReturnTypeImplTrait(func, idx) => { 575 match impl_trait_id {
576 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
564 let datas = 577 let datas =
565 f.db.return_type_impl_traits(func).expect("impl trait id without data"); 578 f.db.return_type_impl_traits(func).expect("impl trait id without data");
566 let data = (*datas) 579 let data = (*datas)
@@ -569,12 +582,12 @@ impl HirDisplay for Ty {
569 let bounds = data.subst(&opaque_ty.parameters); 582 let bounds = data.subst(&opaque_ty.parameters);
570 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?; 583 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?;
571 } 584 }
572 OpaqueTyId::AsyncBlockTypeImplTrait(..) => { 585 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
573 write!(f, "{{async block}}")?; 586 write!(f, "{{async block}}")?;
574 } 587 }
575 }; 588 };
576 } 589 }
577 Ty::Unknown => { 590 TyKind::Unknown => {
578 if f.display_target.is_source_code() { 591 if f.display_target.is_source_code() {
579 return Err(HirDisplayError::DisplaySourceCodeError( 592 return Err(HirDisplayError::DisplaySourceCodeError(
580 DisplaySourceCodeError::UnknownType, 593 DisplaySourceCodeError::UnknownType,
@@ -582,7 +595,7 @@ impl HirDisplay for Ty {
582 } 595 }
583 write!(f, "{{unknown}}")?; 596 write!(f, "{{unknown}}")?;
584 } 597 }
585 Ty::InferenceVar(..) => write!(f, "_")?, 598 TyKind::InferenceVar(..) => write!(f, "_")?,
586 } 599 }
587 Ok(()) 600 Ok(())
588 } 601 }
@@ -695,7 +708,9 @@ fn write_bounds_like_dyn_trait(
695 write!(f, "<")?; 708 write!(f, "<")?;
696 angle_open = true; 709 angle_open = true;
697 } 710 }
698 let type_alias = f.db.type_alias_data(projection_pred.projection_ty.associated_ty); 711 let type_alias = f.db.type_alias_data(from_assoc_type_id(
712 projection_pred.projection_ty.associated_ty,
713 ));
699 write!(f, "{} = ", type_alias.name)?; 714 write!(f, "{} = ", type_alias.name)?;
700 projection_pred.ty.hir_fmt(f)?; 715 projection_pred.ty.hir_fmt(f)?;
701 } 716 }
@@ -766,7 +781,10 @@ impl HirDisplay for GenericPredicate {
766 write!( 781 write!(
767 f, 782 f,
768 ">::{} = ", 783 ">::{} = ",
769 f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name, 784 f.db.type_alias_data(from_assoc_type_id(
785 projection_pred.projection_ty.associated_ty
786 ))
787 .name,
770 )?; 788 )?;
771 projection_pred.ty.hir_fmt(f)?; 789 projection_pred.ty.hir_fmt(f)?;
772 } 790 }
diff --git a/crates/hir_ty/src/infer.rs b/crates/hir_ty/src/infer.rs
index 4d771a91e..8cf59821f 100644
--- a/crates/hir_ty/src/infer.rs
+++ b/crates/hir_ty/src/infer.rs
@@ -41,7 +41,8 @@ use super::{
41 InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeWalk, 41 InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeWalk,
42}; 42};
43use crate::{ 43use crate::{
44 db::HirDatabase, infer::diagnostics::InferenceDiagnostic, lower::ImplTraitLoweringMode, AliasTy, 44 db::HirDatabase, infer::diagnostics::InferenceDiagnostic, lower::ImplTraitLoweringMode,
45 to_assoc_type_id, AliasTy, Interner, TyKind,
45}; 46};
46 47
47pub(crate) use unify::unify; 48pub(crate) use unify::unify;
@@ -169,7 +170,7 @@ impl Index<ExprId> for InferenceResult {
169 type Output = Ty; 170 type Output = Ty;
170 171
171 fn index(&self, expr: ExprId) -> &Ty { 172 fn index(&self, expr: ExprId) -> &Ty {
172 self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown) 173 self.type_of_expr.get(expr).unwrap_or(&Ty(TyKind::Unknown))
173 } 174 }
174} 175}
175 176
@@ -177,7 +178,7 @@ impl Index<PatId> for InferenceResult {
177 type Output = Ty; 178 type Output = Ty;
178 179
179 fn index(&self, pat: PatId) -> &Ty { 180 fn index(&self, pat: PatId) -> &Ty {
180 self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown) 181 self.type_of_pat.get(pat).unwrap_or(&Ty(TyKind::Unknown))
181 } 182 }
182} 183}
183 184
@@ -226,8 +227,10 @@ impl<'a> InferenceContext<'a> {
226 result: InferenceResult::default(), 227 result: InferenceResult::default(),
227 table: unify::InferenceTable::new(), 228 table: unify::InferenceTable::new(),
228 obligations: Vec::default(), 229 obligations: Vec::default(),
229 return_ty: Ty::Unknown, // set in collect_fn_signature 230 return_ty: TyKind::Unknown.intern(&Interner), // set in collect_fn_signature
230 trait_env: TraitEnvironment::lower(db, &resolver), 231 trait_env: owner
232 .as_generic_def_id()
233 .map_or_else(Default::default, |d| db.trait_environment(d)),
231 db, 234 db,
232 owner, 235 owner,
233 body: db.body(owner), 236 body: db.body(owner),
@@ -237,15 +240,19 @@ impl<'a> InferenceContext<'a> {
237 } 240 }
238 } 241 }
239 242
243 fn err_ty(&self) -> Ty {
244 TyKind::Unknown.intern(&Interner)
245 }
246
240 fn resolve_all(mut self) -> InferenceResult { 247 fn resolve_all(mut self) -> InferenceResult {
241 // FIXME resolve obligations as well (use Guidance if necessary) 248 // FIXME resolve obligations as well (use Guidance if necessary)
242 let mut result = std::mem::take(&mut self.result); 249 let mut result = std::mem::take(&mut self.result);
243 for ty in result.type_of_expr.values_mut() { 250 for ty in result.type_of_expr.values_mut() {
244 let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown)); 251 let resolved = self.table.resolve_ty_completely(ty.clone());
245 *ty = resolved; 252 *ty = resolved;
246 } 253 }
247 for ty in result.type_of_pat.values_mut() { 254 for ty in result.type_of_pat.values_mut() {
248 let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown)); 255 let resolved = self.table.resolve_ty_completely(ty.clone());
249 *ty = resolved; 256 *ty = resolved;
250 } 257 }
251 result 258 result
@@ -287,7 +294,7 @@ impl<'a> InferenceContext<'a> {
287 // FIXME use right resolver for block 294 // FIXME use right resolver for block
288 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver) 295 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
289 .with_impl_trait_mode(impl_trait_mode); 296 .with_impl_trait_mode(impl_trait_mode);
290 let ty = Ty::from_hir(&ctx, type_ref); 297 let ty = ctx.lower_ty(type_ref);
291 let ty = self.insert_type_vars(ty); 298 let ty = self.insert_type_vars(ty);
292 self.normalize_associated_types_in(ty) 299 self.normalize_associated_types_in(ty)
293 } 300 }
@@ -298,8 +305,8 @@ impl<'a> InferenceContext<'a> {
298 305
299 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. 306 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
300 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty { 307 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
301 match ty { 308 match ty.interned(&Interner) {
302 Ty::Unknown => self.table.new_type_var(), 309 TyKind::Unknown => self.table.new_type_var(),
303 _ => ty, 310 _ => ty,
304 } 311 }
305 } 312 }
@@ -377,13 +384,16 @@ impl<'a> InferenceContext<'a> {
377 let trait_ref = TraitRef { trait_, substs: substs.clone() }; 384 let trait_ref = TraitRef { trait_, substs: substs.clone() };
378 let projection = ProjectionPredicate { 385 let projection = ProjectionPredicate {
379 ty: ty.clone(), 386 ty: ty.clone(),
380 projection_ty: ProjectionTy { associated_ty: res_assoc_ty, parameters: substs }, 387 projection_ty: ProjectionTy {
388 associated_ty: to_assoc_type_id(res_assoc_ty),
389 parameters: substs,
390 },
381 }; 391 };
382 self.obligations.push(Obligation::Trait(trait_ref)); 392 self.obligations.push(Obligation::Trait(trait_ref));
383 self.obligations.push(Obligation::Projection(projection)); 393 self.obligations.push(Obligation::Projection(projection));
384 self.resolve_ty_as_possible(ty) 394 self.resolve_ty_as_possible(ty)
385 } 395 }
386 None => Ty::Unknown, 396 None => self.err_ty(),
387 } 397 }
388 } 398 }
389 399
@@ -395,8 +405,10 @@ impl<'a> InferenceContext<'a> {
395 /// to do it as well. 405 /// to do it as well.
396 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { 406 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
397 let ty = self.resolve_ty_as_possible(ty); 407 let ty = self.resolve_ty_as_possible(ty);
398 ty.fold(&mut |ty| match ty { 408 ty.fold(&mut |ty| match ty.interned(&Interner) {
399 Ty::Alias(AliasTy::Projection(proj_ty)) => self.normalize_projection_ty(proj_ty), 409 TyKind::Alias(AliasTy::Projection(proj_ty)) => {
410 self.normalize_projection_ty(proj_ty.clone())
411 }
400 _ => ty, 412 _ => ty,
401 }) 413 })
402 } 414 }
@@ -412,7 +424,7 @@ impl<'a> InferenceContext<'a> {
412 fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) { 424 fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) {
413 let path = match path { 425 let path = match path {
414 Some(path) => path, 426 Some(path) => path,
415 None => return (Ty::Unknown, None), 427 None => return (self.err_ty(), None),
416 }; 428 };
417 let resolver = &self.resolver; 429 let resolver = &self.resolver;
418 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 430 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
@@ -421,30 +433,30 @@ impl<'a> InferenceContext<'a> {
421 let (resolution, unresolved) = 433 let (resolution, unresolved) =
422 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) { 434 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
423 Some(it) => it, 435 Some(it) => it,
424 None => return (Ty::Unknown, None), 436 None => return (self.err_ty(), None),
425 }; 437 };
426 return match resolution { 438 return match resolution {
427 TypeNs::AdtId(AdtId::StructId(strukt)) => { 439 TypeNs::AdtId(AdtId::StructId(strukt)) => {
428 let substs = Ty::substs_from_path(&ctx, path, strukt.into(), true); 440 let substs = ctx.substs_from_path(path, strukt.into(), true);
429 let ty = self.db.ty(strukt.into()); 441 let ty = self.db.ty(strukt.into());
430 let ty = self.insert_type_vars(ty.subst(&substs)); 442 let ty = self.insert_type_vars(ty.subst(&substs));
431 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved) 443 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
432 } 444 }
433 TypeNs::AdtId(AdtId::UnionId(u)) => { 445 TypeNs::AdtId(AdtId::UnionId(u)) => {
434 let substs = Ty::substs_from_path(&ctx, path, u.into(), true); 446 let substs = ctx.substs_from_path(path, u.into(), true);
435 let ty = self.db.ty(u.into()); 447 let ty = self.db.ty(u.into());
436 let ty = self.insert_type_vars(ty.subst(&substs)); 448 let ty = self.insert_type_vars(ty.subst(&substs));
437 forbid_unresolved_segments((ty, Some(u.into())), unresolved) 449 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
438 } 450 }
439 TypeNs::EnumVariantId(var) => { 451 TypeNs::EnumVariantId(var) => {
440 let substs = Ty::substs_from_path(&ctx, path, var.into(), true); 452 let substs = ctx.substs_from_path(path, var.into(), true);
441 let ty = self.db.ty(var.parent.into()); 453 let ty = self.db.ty(var.parent.into());
442 let ty = self.insert_type_vars(ty.subst(&substs)); 454 let ty = self.insert_type_vars(ty.subst(&substs));
443 forbid_unresolved_segments((ty, Some(var.into())), unresolved) 455 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
444 } 456 }
445 TypeNs::SelfType(impl_id) => { 457 TypeNs::SelfType(impl_id) => {
446 let generics = crate::utils::generics(self.db.upcast(), impl_id.into()); 458 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
447 let substs = Substs::type_params_for_generics(&generics); 459 let substs = Substs::type_params_for_generics(self.db, &generics);
448 let ty = self.db.impl_self_ty(impl_id).subst(&substs); 460 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
449 match unresolved { 461 match unresolved {
450 None => { 462 None => {
@@ -462,11 +474,11 @@ impl<'a> InferenceContext<'a> {
462 } 474 }
463 } 475 }
464 // FIXME potentially resolve assoc type 476 // FIXME potentially resolve assoc type
465 (Ty::Unknown, None) 477 (self.err_ty(), None)
466 } 478 }
467 Some(_) => { 479 Some(_) => {
468 // FIXME diagnostic 480 // FIXME diagnostic
469 (Ty::Unknown, None) 481 (self.err_ty(), None)
470 } 482 }
471 } 483 }
472 } 484 }
@@ -480,15 +492,15 @@ impl<'a> InferenceContext<'a> {
480 } 492 }
481 TypeNs::AdtSelfType(_) => { 493 TypeNs::AdtSelfType(_) => {
482 // FIXME this could happen in array size expressions, once we're checking them 494 // FIXME this could happen in array size expressions, once we're checking them
483 (Ty::Unknown, None) 495 (self.err_ty(), None)
484 } 496 }
485 TypeNs::GenericParam(_) => { 497 TypeNs::GenericParam(_) => {
486 // FIXME potentially resolve assoc type 498 // FIXME potentially resolve assoc type
487 (Ty::Unknown, None) 499 (self.err_ty(), None)
488 } 500 }
489 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => { 501 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
490 // FIXME diagnostic 502 // FIXME diagnostic
491 (Ty::Unknown, None) 503 (self.err_ty(), None)
492 } 504 }
493 }; 505 };
494 506
@@ -500,7 +512,7 @@ impl<'a> InferenceContext<'a> {
500 result 512 result
501 } else { 513 } else {
502 // FIXME diagnostic 514 // FIXME diagnostic
503 (Ty::Unknown, None) 515 (TyKind::Unknown.intern(&Interner), None)
504 } 516 }
505 } 517 }
506 518
@@ -529,7 +541,7 @@ impl<'a> InferenceContext<'a> {
529 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver) 541 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
530 .with_impl_trait_mode(ImplTraitLoweringMode::Param); 542 .with_impl_trait_mode(ImplTraitLoweringMode::Param);
531 let param_tys = 543 let param_tys =
532 data.params.iter().map(|type_ref| Ty::from_hir(&ctx, type_ref)).collect::<Vec<_>>(); 544 data.params.iter().map(|type_ref| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
533 for (ty, pat) in param_tys.into_iter().zip(body.params.iter()) { 545 for (ty, pat) in param_tys.into_iter().zip(body.params.iter()) {
534 let ty = self.insert_type_vars(ty); 546 let ty = self.insert_type_vars(ty);
535 let ty = self.normalize_associated_types_in(ty); 547 let ty = self.normalize_associated_types_in(ty);
@@ -711,12 +723,12 @@ impl Expectation {
711 723
712 /// This expresses no expectation on the type. 724 /// This expresses no expectation on the type.
713 fn none() -> Self { 725 fn none() -> Self {
714 Expectation { ty: Ty::Unknown, rvalue_hint: false } 726 Expectation { ty: TyKind::Unknown.intern(&Interner), rvalue_hint: false }
715 } 727 }
716 728
717 fn coercion_target(&self) -> &Ty { 729 fn coercion_target(&self) -> &Ty {
718 if self.rvalue_hint { 730 if self.rvalue_hint {
719 &Ty::Unknown 731 &Ty(TyKind::Unknown)
720 } else { 732 } else {
721 &self.ty 733 &self.ty
722 } 734 }
diff --git a/crates/hir_ty/src/infer/coerce.rs b/crates/hir_ty/src/infer/coerce.rs
index 7e8846f27..36670043a 100644
--- a/crates/hir_ty/src/infer/coerce.rs
+++ b/crates/hir_ty/src/infer/coerce.rs
@@ -7,7 +7,7 @@
7use chalk_ir::{Mutability, TyVariableKind}; 7use chalk_ir::{Mutability, TyVariableKind};
8use hir_def::lang_item::LangItemTarget; 8use hir_def::lang_item::LangItemTarget;
9 9
10use crate::{autoderef, traits::Solution, Obligation, Substs, TraitRef, Ty}; 10use crate::{autoderef, traits::Solution, Interner, Obligation, Substs, TraitRef, Ty, TyKind};
11 11
12use super::{InEnvironment, InferenceContext}; 12use super::{InEnvironment, InferenceContext};
13 13
@@ -33,7 +33,9 @@ impl<'a> InferenceContext<'a> {
33 } else if self.coerce(ty2, ty1) { 33 } else if self.coerce(ty2, ty1) {
34 ty1.clone() 34 ty1.clone()
35 } else { 35 } else {
36 if let (Ty::FnDef(..), Ty::FnDef(..)) = (ty1, ty2) { 36 if let (TyKind::FnDef(..), TyKind::FnDef(..)) =
37 (ty1.interned(&Interner), ty2.interned(&Interner))
38 {
37 cov_mark::hit!(coerce_fn_reification); 39 cov_mark::hit!(coerce_fn_reification);
38 // Special case: two function types. Try to coerce both to 40 // Special case: two function types. Try to coerce both to
39 // pointers to have a chance at getting a match. See 41 // pointers to have a chance at getting a match. See
@@ -51,13 +53,13 @@ impl<'a> InferenceContext<'a> {
51 } 53 }
52 54
53 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { 55 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool {
54 match (&from_ty, to_ty) { 56 match (from_ty.interned(&Interner), to_ty.interned(&Interner)) {
55 // Never type will make type variable to fallback to Never Type instead of Unknown. 57 // Never type will make type variable to fallback to Never Type instead of Unknown.
56 (Ty::Never, Ty::InferenceVar(tv, TyVariableKind::General)) => { 58 (TyKind::Never, TyKind::InferenceVar(tv, TyVariableKind::General)) => {
57 self.table.type_variable_table.set_diverging(*tv, true); 59 self.table.type_variable_table.set_diverging(*tv, true);
58 return true; 60 return true;
59 } 61 }
60 (Ty::Never, _) => return true, 62 (TyKind::Never, _) => return true,
61 63
62 // Trivial cases, this should go after `never` check to 64 // Trivial cases, this should go after `never` check to
63 // avoid infer result type to be never 65 // avoid infer result type to be never
@@ -69,33 +71,33 @@ impl<'a> InferenceContext<'a> {
69 } 71 }
70 72
71 // Pointer weakening and function to pointer 73 // Pointer weakening and function to pointer
72 match (&mut from_ty, to_ty) { 74 match (&mut from_ty.0, to_ty.interned(&Interner)) {
73 // `*mut T` -> `*const T` 75 // `*mut T` -> `*const T`
74 // `&mut T` -> `&T` 76 // `&mut T` -> `&T`
75 (Ty::Raw(m1, ..), Ty::Raw(m2 @ Mutability::Not, ..)) 77 (TyKind::Raw(m1, ..), TyKind::Raw(m2 @ Mutability::Not, ..))
76 | (Ty::Ref(m1, ..), Ty::Ref(m2 @ Mutability::Not, ..)) => { 78 | (TyKind::Ref(m1, ..), TyKind::Ref(m2 @ Mutability::Not, ..)) => {
77 *m1 = *m2; 79 *m1 = *m2;
78 } 80 }
79 // `&T` -> `*const T` 81 // `&T` -> `*const T`
80 // `&mut T` -> `*mut T`/`*const T` 82 // `&mut T` -> `*mut T`/`*const T`
81 (Ty::Ref(.., substs), &Ty::Raw(m2 @ Mutability::Not, ..)) 83 (TyKind::Ref(.., substs), &TyKind::Raw(m2 @ Mutability::Not, ..))
82 | (Ty::Ref(Mutability::Mut, substs), &Ty::Raw(m2, ..)) => { 84 | (TyKind::Ref(Mutability::Mut, substs), &TyKind::Raw(m2, ..)) => {
83 from_ty = Ty::Raw(m2, substs.clone()); 85 from_ty = TyKind::Raw(m2, substs.clone()).intern(&Interner);
84 } 86 }
85 87
86 // Illegal mutability conversion 88 // Illegal mutability conversion
87 (Ty::Raw(Mutability::Not, ..), Ty::Raw(Mutability::Mut, ..)) 89 (TyKind::Raw(Mutability::Not, ..), TyKind::Raw(Mutability::Mut, ..))
88 | (Ty::Ref(Mutability::Not, ..), Ty::Ref(Mutability::Mut, ..)) => return false, 90 | (TyKind::Ref(Mutability::Not, ..), TyKind::Ref(Mutability::Mut, ..)) => return false,
89 91
90 // `{function_type}` -> `fn()` 92 // `{function_type}` -> `fn()`
91 (Ty::FnDef(..), Ty::Function { .. }) => match from_ty.callable_sig(self.db) { 93 (TyKind::FnDef(..), TyKind::Function { .. }) => match from_ty.callable_sig(self.db) {
92 None => return false, 94 None => return false,
93 Some(sig) => { 95 Some(sig) => {
94 from_ty = Ty::fn_ptr(sig); 96 from_ty = Ty::fn_ptr(sig);
95 } 97 }
96 }, 98 },
97 99
98 (Ty::Closure(.., substs), Ty::Function { .. }) => { 100 (TyKind::Closure(.., substs), TyKind::Function { .. }) => {
99 from_ty = substs[0].clone(); 101 from_ty = substs[0].clone();
100 } 102 }
101 103
@@ -107,9 +109,11 @@ impl<'a> InferenceContext<'a> {
107 } 109 }
108 110
109 // Auto Deref if cannot coerce 111 // Auto Deref if cannot coerce
110 match (&from_ty, to_ty) { 112 match (from_ty.interned(&Interner), to_ty.interned(&Interner)) {
111 // FIXME: DerefMut 113 // FIXME: DerefMut
112 (Ty::Ref(_, st1), Ty::Ref(_, st2)) => self.unify_autoderef_behind_ref(&st1[0], &st2[0]), 114 (TyKind::Ref(_, st1), TyKind::Ref(_, st2)) => {
115 self.unify_autoderef_behind_ref(&st1[0], &st2[0])
116 }
113 117
114 // Otherwise, normal unify 118 // Otherwise, normal unify
115 _ => self.unify(&from_ty, to_ty), 119 _ => self.unify(&from_ty, to_ty),
diff --git a/crates/hir_ty/src/infer/expr.rs b/crates/hir_ty/src/infer/expr.rs
index 262177ffb..eee3e6ec5 100644
--- a/crates/hir_ty/src/infer/expr.rs
+++ b/crates/hir_ty/src/infer/expr.rs
@@ -18,10 +18,11 @@ use crate::{
18 lower::lower_to_chalk_mutability, 18 lower::lower_to_chalk_mutability,
19 method_resolution, op, 19 method_resolution, op,
20 primitive::{self, UintTy}, 20 primitive::{self, UintTy},
21 traits::{FnTrait, InEnvironment}, 21 to_assoc_type_id,
22 traits::{chalk::from_chalk, FnTrait, InEnvironment},
22 utils::{generics, variant_data, Generics}, 23 utils::{generics, variant_data, Generics},
23 AdtId, Binders, CallableDefId, FnPointer, FnSig, Obligation, OpaqueTyId, Rawness, Scalar, 24 AdtId, Binders, CallableDefId, FnPointer, FnSig, Interner, Obligation, Rawness, Scalar, Substs,
24 Substs, TraitRef, Ty, 25 TraitRef, Ty, TyKind,
25}; 26};
26 27
27use super::{ 28use super::{
@@ -57,7 +58,7 @@ impl<'a> InferenceContext<'a> {
57 // Return actual type when type mismatch. 58 // Return actual type when type mismatch.
58 // This is needed for diagnostic when return type mismatch. 59 // This is needed for diagnostic when return type mismatch.
59 ty 60 ty
60 } else if expected.coercion_target() == &Ty::Unknown { 61 } else if expected.coercion_target().is_unknown() {
61 ty 62 ty
62 } else { 63 } else {
63 expected.ty.clone() 64 expected.ty.clone()
@@ -84,7 +85,7 @@ impl<'a> InferenceContext<'a> {
84 arg_tys.push(arg); 85 arg_tys.push(arg);
85 } 86 }
86 let parameters = param_builder.build(); 87 let parameters = param_builder.build();
87 let arg_ty = Ty::Tuple(num_args, parameters); 88 let arg_ty = TyKind::Tuple(num_args, parameters).intern(&Interner);
88 let substs = 89 let substs =
89 Substs::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build(); 90 Substs::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build();
90 91
@@ -97,8 +98,10 @@ impl<'a> InferenceContext<'a> {
97 }); 98 });
98 if self.db.trait_solve(krate, goal.value).is_some() { 99 if self.db.trait_solve(krate, goal.value).is_some() {
99 self.obligations.push(implements_fn_trait); 100 self.obligations.push(implements_fn_trait);
100 let output_proj_ty = 101 let output_proj_ty = crate::ProjectionTy {
101 crate::ProjectionTy { associated_ty: output_assoc_type, parameters: substs }; 102 associated_ty: to_assoc_type_id(output_assoc_type),
103 parameters: substs,
104 };
102 let return_ty = self.normalize_projection_ty(output_proj_ty); 105 let return_ty = self.normalize_projection_ty(output_proj_ty);
103 Some((arg_tys, return_ty)) 106 Some((arg_tys, return_ty))
104 } else { 107 } else {
@@ -116,10 +119,13 @@ impl<'a> InferenceContext<'a> {
116 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { 119 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
117 let body = Arc::clone(&self.body); // avoid borrow checker problem 120 let body = Arc::clone(&self.body); // avoid borrow checker problem
118 let ty = match &body[tgt_expr] { 121 let ty = match &body[tgt_expr] {
119 Expr::Missing => Ty::Unknown, 122 Expr::Missing => self.err_ty(),
120 Expr::If { condition, then_branch, else_branch } => { 123 Expr::If { condition, then_branch, else_branch } => {
121 // if let is desugared to match, so this is always simple if 124 // if let is desugared to match, so this is always simple if
122 self.infer_expr(*condition, &Expectation::has_type(Ty::Scalar(Scalar::Bool))); 125 self.infer_expr(
126 *condition,
127 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
128 );
123 129
124 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe); 130 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
125 let mut both_arms_diverge = Diverges::Always; 131 let mut both_arms_diverge = Diverges::Always;
@@ -167,14 +173,15 @@ impl<'a> InferenceContext<'a> {
167 Expr::TryBlock { body } => { 173 Expr::TryBlock { body } => {
168 let _inner = self.infer_expr(*body, expected); 174 let _inner = self.infer_expr(*body, expected);
169 // FIXME should be std::result::Result<{inner}, _> 175 // FIXME should be std::result::Result<{inner}, _>
170 Ty::Unknown 176 self.err_ty()
171 } 177 }
172 Expr::Async { body } => { 178 Expr::Async { body } => {
173 // Use the first type parameter as the output type of future. 179 // Use the first type parameter as the output type of future.
174 // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType> 180 // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
175 let inner_ty = self.infer_expr(*body, &Expectation::none()); 181 let inner_ty = self.infer_expr(*body, &Expectation::none());
176 let opaque_ty_id = OpaqueTyId::AsyncBlockTypeImplTrait(self.owner, *body); 182 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
177 Ty::OpaqueType(opaque_ty_id, Substs::single(inner_ty)) 183 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
184 TyKind::OpaqueType(opaque_ty_id, Substs::single(inner_ty)).intern(&Interner)
178 } 185 }
179 Expr::Loop { body, label } => { 186 Expr::Loop { body, label } => {
180 self.breakables.push(BreakableContext { 187 self.breakables.push(BreakableContext {
@@ -192,17 +199,20 @@ impl<'a> InferenceContext<'a> {
192 if ctxt.may_break { 199 if ctxt.may_break {
193 ctxt.break_ty 200 ctxt.break_ty
194 } else { 201 } else {
195 Ty::Never 202 TyKind::Never.intern(&Interner)
196 } 203 }
197 } 204 }
198 Expr::While { condition, body, label } => { 205 Expr::While { condition, body, label } => {
199 self.breakables.push(BreakableContext { 206 self.breakables.push(BreakableContext {
200 may_break: false, 207 may_break: false,
201 break_ty: Ty::Unknown, 208 break_ty: self.err_ty(),
202 label: label.map(|label| self.body[label].name.clone()), 209 label: label.map(|label| self.body[label].name.clone()),
203 }); 210 });
204 // while let is desugared to a match loop, so this is always simple while 211 // while let is desugared to a match loop, so this is always simple while
205 self.infer_expr(*condition, &Expectation::has_type(Ty::Scalar(Scalar::Bool))); 212 self.infer_expr(
213 *condition,
214 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
215 );
206 self.infer_expr(*body, &Expectation::has_type(Ty::unit())); 216 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
207 let _ctxt = self.breakables.pop().expect("breakable stack broken"); 217 let _ctxt = self.breakables.pop().expect("breakable stack broken");
208 // the body may not run, so it diverging doesn't mean we diverge 218 // the body may not run, so it diverging doesn't mean we diverge
@@ -214,7 +224,7 @@ impl<'a> InferenceContext<'a> {
214 224
215 self.breakables.push(BreakableContext { 225 self.breakables.push(BreakableContext {
216 may_break: false, 226 may_break: false,
217 break_ty: Ty::Unknown, 227 break_ty: self.err_ty(),
218 label: label.map(|label| self.body[label].name.clone()), 228 label: label.map(|label| self.body[label].name.clone()),
219 }); 229 });
220 let pat_ty = 230 let pat_ty =
@@ -249,12 +259,15 @@ impl<'a> InferenceContext<'a> {
249 None => self.table.new_type_var(), 259 None => self.table.new_type_var(),
250 }; 260 };
251 sig_tys.push(ret_ty.clone()); 261 sig_tys.push(ret_ty.clone());
252 let sig_ty = Ty::Function(FnPointer { 262 let sig_ty = TyKind::Function(FnPointer {
253 num_args: sig_tys.len() - 1, 263 num_args: sig_tys.len() - 1,
254 sig: FnSig { variadic: false }, 264 sig: FnSig { variadic: false },
255 substs: Substs(sig_tys.clone().into()), 265 substs: Substs(sig_tys.clone().into()),
256 }); 266 })
257 let closure_ty = Ty::Closure(self.owner, tgt_expr, Substs::single(sig_ty)); 267 .intern(&Interner);
268 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
269 let closure_ty =
270 TyKind::Closure(closure_id, Substs::single(sig_ty)).intern(&Interner);
258 271
259 // Eagerly try to relate the closure type with the expected 272 // Eagerly try to relate the closure type with the expected
260 // type, otherwise we often won't have enough information to 273 // type, otherwise we often won't have enough information to
@@ -295,7 +308,7 @@ impl<'a> InferenceContext<'a> {
295 args.len(), 308 args.len(),
296 ) 309 )
297 }) 310 })
298 .unwrap_or((Vec::new(), Ty::Unknown)); 311 .unwrap_or((Vec::new(), self.err_ty()));
299 self.register_obligations_for_call(&callee_ty); 312 self.register_obligations_for_call(&callee_ty);
300 self.check_call_arguments(args, &param_tys); 313 self.check_call_arguments(args, &param_tys);
301 self.normalize_associated_types_in(ret_ty) 314 self.normalize_associated_types_in(ret_ty)
@@ -305,8 +318,11 @@ impl<'a> InferenceContext<'a> {
305 Expr::Match { expr, arms } => { 318 Expr::Match { expr, arms } => {
306 let input_ty = self.infer_expr(*expr, &Expectation::none()); 319 let input_ty = self.infer_expr(*expr, &Expectation::none());
307 320
308 let mut result_ty = 321 let mut result_ty = if arms.is_empty() {
309 if arms.is_empty() { Ty::Never } else { self.table.new_type_var() }; 322 TyKind::Never.intern(&Interner)
323 } else {
324 self.table.new_type_var()
325 };
310 326
311 let matchee_diverges = self.diverges; 327 let matchee_diverges = self.diverges;
312 let mut all_arms_diverge = Diverges::Always; 328 let mut all_arms_diverge = Diverges::Always;
@@ -317,7 +333,7 @@ impl<'a> InferenceContext<'a> {
317 if let Some(guard_expr) = arm.guard { 333 if let Some(guard_expr) = arm.guard {
318 self.infer_expr( 334 self.infer_expr(
319 guard_expr, 335 guard_expr,
320 &Expectation::has_type(Ty::Scalar(Scalar::Bool)), 336 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
321 ); 337 );
322 } 338 }
323 339
@@ -333,9 +349,9 @@ impl<'a> InferenceContext<'a> {
333 Expr::Path(p) => { 349 Expr::Path(p) => {
334 // FIXME this could be more efficient... 350 // FIXME this could be more efficient...
335 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr); 351 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
336 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) 352 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(self.err_ty())
337 } 353 }
338 Expr::Continue { .. } => Ty::Never, 354 Expr::Continue { .. } => TyKind::Never.intern(&Interner),
339 Expr::Break { expr, label } => { 355 Expr::Break { expr, label } => {
340 let val_ty = if let Some(expr) = expr { 356 let val_ty = if let Some(expr) = expr {
341 self.infer_expr(*expr, &Expectation::none()) 357 self.infer_expr(*expr, &Expectation::none())
@@ -347,7 +363,7 @@ impl<'a> InferenceContext<'a> {
347 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) { 363 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
348 ctxt.break_ty.clone() 364 ctxt.break_ty.clone()
349 } else { 365 } else {
350 Ty::Unknown 366 self.err_ty()
351 }; 367 };
352 368
353 let merged_type = self.coerce_merge_branch(&last_ty, &val_ty); 369 let merged_type = self.coerce_merge_branch(&last_ty, &val_ty);
@@ -360,7 +376,7 @@ impl<'a> InferenceContext<'a> {
360 expr: tgt_expr, 376 expr: tgt_expr,
361 }); 377 });
362 } 378 }
363 Ty::Never 379 TyKind::Never.intern(&Interner)
364 } 380 }
365 Expr::Return { expr } => { 381 Expr::Return { expr } => {
366 if let Some(expr) = expr { 382 if let Some(expr) = expr {
@@ -369,14 +385,14 @@ impl<'a> InferenceContext<'a> {
369 let unit = Ty::unit(); 385 let unit = Ty::unit();
370 self.coerce(&unit, &self.return_ty.clone()); 386 self.coerce(&unit, &self.return_ty.clone());
371 } 387 }
372 Ty::Never 388 TyKind::Never.intern(&Interner)
373 } 389 }
374 Expr::Yield { expr } => { 390 Expr::Yield { expr } => {
375 // FIXME: track yield type for coercion 391 // FIXME: track yield type for coercion
376 if let Some(expr) = expr { 392 if let Some(expr) = expr {
377 self.infer_expr(*expr, &Expectation::none()); 393 self.infer_expr(*expr, &Expectation::none());
378 } 394 }
379 Ty::Never 395 TyKind::Never.intern(&Interner)
380 } 396 }
381 Expr::RecordLit { path, fields, spread } => { 397 Expr::RecordLit { path, fields, spread } => {
382 let (ty, def_id) = self.resolve_variant(path.as_ref()); 398 let (ty, def_id) = self.resolve_variant(path.as_ref());
@@ -404,8 +420,9 @@ impl<'a> InferenceContext<'a> {
404 if let Some(field_def) = field_def { 420 if let Some(field_def) = field_def {
405 self.result.record_field_resolutions.insert(field.expr, field_def); 421 self.result.record_field_resolutions.insert(field.expr, field_def);
406 } 422 }
407 let field_ty = field_def 423 let field_ty = field_def.map_or(self.err_ty(), |it| {
408 .map_or(Ty::Unknown, |it| field_types[it.local_id].clone().subst(&substs)); 424 field_types[it.local_id].clone().subst(&substs)
425 });
409 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); 426 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
410 } 427 }
411 if let Some(expr) = spread { 428 if let Some(expr) = spread {
@@ -424,27 +441,33 @@ impl<'a> InferenceContext<'a> {
424 environment: self.trait_env.clone(), 441 environment: self.trait_env.clone(),
425 }, 442 },
426 ) 443 )
427 .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { 444 .find_map(|derefed_ty| {
428 Ty::Tuple(_, substs) => { 445 match canonicalized.decanonicalize_ty(derefed_ty.value).interned(&Interner) {
429 name.as_tuple_index().and_then(|idx| substs.0.get(idx).cloned()) 446 TyKind::Tuple(_, substs) => {
430 } 447 name.as_tuple_index().and_then(|idx| substs.0.get(idx).cloned())
431 Ty::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => { 448 }
432 self.db.struct_data(s).variant_data.field(name).map(|local_id| { 449 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
433 let field = FieldId { parent: s.into(), local_id }; 450 self.db.struct_data(*s).variant_data.field(name).map(|local_id| {
434 self.write_field_resolution(tgt_expr, field); 451 let field = FieldId { parent: (*s).into(), local_id };
435 self.db.field_types(s.into())[field.local_id].clone().subst(&parameters) 452 self.write_field_resolution(tgt_expr, field);
436 }) 453 self.db.field_types((*s).into())[field.local_id]
437 } 454 .clone()
438 Ty::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => { 455 .subst(&parameters)
439 self.db.union_data(u).variant_data.field(name).map(|local_id| { 456 })
440 let field = FieldId { parent: u.into(), local_id }; 457 }
441 self.write_field_resolution(tgt_expr, field); 458 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
442 self.db.field_types(u.into())[field.local_id].clone().subst(&parameters) 459 self.db.union_data(*u).variant_data.field(name).map(|local_id| {
443 }) 460 let field = FieldId { parent: (*u).into(), local_id };
461 self.write_field_resolution(tgt_expr, field);
462 self.db.field_types((*u).into())[field.local_id]
463 .clone()
464 .subst(&parameters)
465 })
466 }
467 _ => None,
444 } 468 }
445 _ => None,
446 }) 469 })
447 .unwrap_or(Ty::Unknown); 470 .unwrap_or(self.err_ty());
448 let ty = self.insert_type_vars(ty); 471 let ty = self.insert_type_vars(ty);
449 self.normalize_associated_types_in(ty) 472 self.normalize_associated_types_in(ty)
450 } 473 }
@@ -481,9 +504,10 @@ impl<'a> InferenceContext<'a> {
481 }; 504 };
482 let inner_ty = self.infer_expr_inner(*expr, &expectation); 505 let inner_ty = self.infer_expr_inner(*expr, &expectation);
483 match rawness { 506 match rawness {
484 Rawness::RawPtr => Ty::Raw(mutability, Substs::single(inner_ty)), 507 Rawness::RawPtr => TyKind::Raw(mutability, Substs::single(inner_ty)),
485 Rawness::Ref => Ty::Ref(mutability, Substs::single(inner_ty)), 508 Rawness::Ref => TyKind::Ref(mutability, Substs::single(inner_ty)),
486 } 509 }
510 .intern(&Interner)
487 } 511 }
488 Expr::Box { expr } => { 512 Expr::Box { expr } => {
489 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); 513 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
@@ -499,7 +523,7 @@ impl<'a> InferenceContext<'a> {
499 sb = sb.fill(repeat_with(|| self.table.new_type_var())); 523 sb = sb.fill(repeat_with(|| self.table.new_type_var()));
500 Ty::adt_ty(box_, sb.build()) 524 Ty::adt_ty(box_, sb.build())
501 } else { 525 } else {
502 Ty::Unknown 526 self.err_ty()
503 } 527 }
504 } 528 }
505 Expr::UnaryOp { expr, op } => { 529 Expr::UnaryOp { expr, op } => {
@@ -519,31 +543,31 @@ impl<'a> InferenceContext<'a> {
519 Some(derefed_ty) => { 543 Some(derefed_ty) => {
520 canonicalized.decanonicalize_ty(derefed_ty.value) 544 canonicalized.decanonicalize_ty(derefed_ty.value)
521 } 545 }
522 None => Ty::Unknown, 546 None => self.err_ty(),
523 } 547 }
524 } 548 }
525 None => Ty::Unknown, 549 None => self.err_ty(),
526 }, 550 },
527 UnaryOp::Neg => { 551 UnaryOp::Neg => {
528 match &inner_ty { 552 match inner_ty.interned(&Interner) {
529 // Fast path for builtins 553 // Fast path for builtins
530 Ty::Scalar(Scalar::Int(_)) 554 TyKind::Scalar(Scalar::Int(_))
531 | Ty::Scalar(Scalar::Uint(_)) 555 | TyKind::Scalar(Scalar::Uint(_))
532 | Ty::Scalar(Scalar::Float(_)) 556 | TyKind::Scalar(Scalar::Float(_))
533 | Ty::InferenceVar(_, TyVariableKind::Integer) 557 | TyKind::InferenceVar(_, TyVariableKind::Integer)
534 | Ty::InferenceVar(_, TyVariableKind::Float) => inner_ty, 558 | TyKind::InferenceVar(_, TyVariableKind::Float) => inner_ty,
535 // Otherwise we resolve via the std::ops::Neg trait 559 // Otherwise we resolve via the std::ops::Neg trait
536 _ => self 560 _ => self
537 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()), 561 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
538 } 562 }
539 } 563 }
540 UnaryOp::Not => { 564 UnaryOp::Not => {
541 match &inner_ty { 565 match inner_ty.interned(&Interner) {
542 // Fast path for builtins 566 // Fast path for builtins
543 Ty::Scalar(Scalar::Bool) 567 TyKind::Scalar(Scalar::Bool)
544 | Ty::Scalar(Scalar::Int(_)) 568 | TyKind::Scalar(Scalar::Int(_))
545 | Ty::Scalar(Scalar::Uint(_)) 569 | TyKind::Scalar(Scalar::Uint(_))
546 | Ty::InferenceVar(_, TyVariableKind::Integer) => inner_ty, 570 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
547 // Otherwise we resolve via the std::ops::Not trait 571 // Otherwise we resolve via the std::ops::Not trait
548 _ => self 572 _ => self
549 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()), 573 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
@@ -554,7 +578,9 @@ impl<'a> InferenceContext<'a> {
554 Expr::BinaryOp { lhs, rhs, op } => match op { 578 Expr::BinaryOp { lhs, rhs, op } => match op {
555 Some(op) => { 579 Some(op) => {
556 let lhs_expectation = match op { 580 let lhs_expectation = match op {
557 BinaryOp::LogicOp(..) => Expectation::has_type(Ty::Scalar(Scalar::Bool)), 581 BinaryOp::LogicOp(..) => {
582 Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner))
583 }
558 _ => Expectation::none(), 584 _ => Expectation::none(),
559 }; 585 };
560 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); 586 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
@@ -563,7 +589,7 @@ impl<'a> InferenceContext<'a> {
563 589
564 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone()); 590 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
565 591
566 if ret == Ty::Unknown { 592 if ret.is_unknown() {
567 cov_mark::hit!(infer_expr_inner_binary_operator_overload); 593 cov_mark::hit!(infer_expr_inner_binary_operator_overload);
568 594
569 self.resolve_associated_type_with_params( 595 self.resolve_associated_type_with_params(
@@ -575,7 +601,7 @@ impl<'a> InferenceContext<'a> {
575 ret 601 ret
576 } 602 }
577 } 603 }
578 _ => Ty::Unknown, 604 _ => self.err_ty(),
579 }, 605 },
580 Expr::Range { lhs, rhs, range_type } => { 606 Expr::Range { lhs, rhs, range_type } => {
581 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none())); 607 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
@@ -586,33 +612,33 @@ impl<'a> InferenceContext<'a> {
586 match (range_type, lhs_ty, rhs_ty) { 612 match (range_type, lhs_ty, rhs_ty) {
587 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() { 613 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
588 Some(adt) => Ty::adt_ty(adt, Substs::empty()), 614 Some(adt) => Ty::adt_ty(adt, Substs::empty()),
589 None => Ty::Unknown, 615 None => self.err_ty(),
590 }, 616 },
591 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() { 617 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
592 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 618 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
593 None => Ty::Unknown, 619 None => self.err_ty(),
594 }, 620 },
595 (RangeOp::Inclusive, None, Some(ty)) => { 621 (RangeOp::Inclusive, None, Some(ty)) => {
596 match self.resolve_range_to_inclusive() { 622 match self.resolve_range_to_inclusive() {
597 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 623 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
598 None => Ty::Unknown, 624 None => self.err_ty(),
599 } 625 }
600 } 626 }
601 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() { 627 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
602 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 628 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
603 None => Ty::Unknown, 629 None => self.err_ty(),
604 }, 630 },
605 (RangeOp::Inclusive, Some(_), Some(ty)) => { 631 (RangeOp::Inclusive, Some(_), Some(ty)) => {
606 match self.resolve_range_inclusive() { 632 match self.resolve_range_inclusive() {
607 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 633 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
608 None => Ty::Unknown, 634 None => self.err_ty(),
609 } 635 }
610 } 636 }
611 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() { 637 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
612 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 638 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
613 None => Ty::Unknown, 639 None => self.err_ty(),
614 }, 640 },
615 (RangeOp::Inclusive, _, None) => Ty::Unknown, 641 (RangeOp::Inclusive, _, None) => self.err_ty(),
616 } 642 }
617 } 643 }
618 Expr::Index { base, index } => { 644 Expr::Index { base, index } => {
@@ -631,19 +657,19 @@ impl<'a> InferenceContext<'a> {
631 index_trait, 657 index_trait,
632 ); 658 );
633 let self_ty = 659 let self_ty =
634 self_ty.map_or(Ty::Unknown, |t| canonicalized.decanonicalize_ty(t.value)); 660 self_ty.map_or(self.err_ty(), |t| canonicalized.decanonicalize_ty(t.value));
635 self.resolve_associated_type_with_params( 661 self.resolve_associated_type_with_params(
636 self_ty, 662 self_ty,
637 self.resolve_ops_index_output(), 663 self.resolve_ops_index_output(),
638 &[index_ty], 664 &[index_ty],
639 ) 665 )
640 } else { 666 } else {
641 Ty::Unknown 667 self.err_ty()
642 } 668 }
643 } 669 }
644 Expr::Tuple { exprs } => { 670 Expr::Tuple { exprs } => {
645 let mut tys = match &expected.ty { 671 let mut tys = match expected.ty.interned(&Interner) {
646 Ty::Tuple(_, substs) => substs 672 TyKind::Tuple(_, substs) => substs
647 .iter() 673 .iter()
648 .cloned() 674 .cloned()
649 .chain(repeat_with(|| self.table.new_type_var())) 675 .chain(repeat_with(|| self.table.new_type_var()))
@@ -656,11 +682,11 @@ impl<'a> InferenceContext<'a> {
656 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); 682 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
657 } 683 }
658 684
659 Ty::Tuple(tys.len(), Substs(tys.into())) 685 TyKind::Tuple(tys.len(), Substs(tys.into())).intern(&Interner)
660 } 686 }
661 Expr::Array(array) => { 687 Expr::Array(array) => {
662 let elem_ty = match &expected.ty { 688 let elem_ty = match expected.ty.interned(&Interner) {
663 Ty::Array(st) | Ty::Slice(st) => st.as_single().clone(), 689 TyKind::Array(st) | TyKind::Slice(st) => st.as_single().clone(),
664 _ => self.table.new_type_var(), 690 _ => self.table.new_type_var(),
665 }; 691 };
666 692
@@ -677,43 +703,51 @@ impl<'a> InferenceContext<'a> {
677 ); 703 );
678 self.infer_expr( 704 self.infer_expr(
679 *repeat, 705 *repeat,
680 &Expectation::has_type(Ty::Scalar(Scalar::Uint(UintTy::Usize))), 706 &Expectation::has_type(
707 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner),
708 ),
681 ); 709 );
682 } 710 }
683 } 711 }
684 712
685 Ty::Array(Substs::single(elem_ty)) 713 TyKind::Array(Substs::single(elem_ty)).intern(&Interner)
686 } 714 }
687 Expr::Literal(lit) => match lit { 715 Expr::Literal(lit) => match lit {
688 Literal::Bool(..) => Ty::Scalar(Scalar::Bool), 716 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
689 Literal::String(..) => Ty::Ref(Mutability::Not, Substs::single(Ty::Str)), 717 Literal::String(..) => {
718 TyKind::Ref(Mutability::Not, Substs::single(TyKind::Str.intern(&Interner)))
719 .intern(&Interner)
720 }
690 Literal::ByteString(..) => { 721 Literal::ByteString(..) => {
691 let byte_type = Ty::Scalar(Scalar::Uint(UintTy::U8)); 722 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(&Interner);
692 let array_type = Ty::Array(Substs::single(byte_type)); 723 let array_type = TyKind::Array(Substs::single(byte_type)).intern(&Interner);
693 Ty::Ref(Mutability::Not, Substs::single(array_type)) 724 TyKind::Ref(Mutability::Not, Substs::single(array_type)).intern(&Interner)
694 } 725 }
695 Literal::Char(..) => Ty::Scalar(Scalar::Char), 726 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(&Interner),
696 Literal::Int(_v, ty) => match ty { 727 Literal::Int(_v, ty) => match ty {
697 Some(int_ty) => { 728 Some(int_ty) => {
698 Ty::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty))) 729 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
730 .intern(&Interner)
699 } 731 }
700 None => self.table.new_integer_var(), 732 None => self.table.new_integer_var(),
701 }, 733 },
702 Literal::Uint(_v, ty) => match ty { 734 Literal::Uint(_v, ty) => match ty {
703 Some(int_ty) => { 735 Some(int_ty) => {
704 Ty::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty))) 736 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
737 .intern(&Interner)
705 } 738 }
706 None => self.table.new_integer_var(), 739 None => self.table.new_integer_var(),
707 }, 740 },
708 Literal::Float(_v, ty) => match ty { 741 Literal::Float(_v, ty) => match ty {
709 Some(float_ty) => { 742 Some(float_ty) => {
710 Ty::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty))) 743 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
744 .intern(&Interner)
711 } 745 }
712 None => self.table.new_float_var(), 746 None => self.table.new_float_var(),
713 }, 747 },
714 }, 748 },
715 }; 749 };
716 // use a new type variable if we got Ty::Unknown here 750 // use a new type variable if we got unknown here
717 let ty = self.insert_type_vars_shallow(ty); 751 let ty = self.insert_type_vars_shallow(ty);
718 let ty = self.resolve_ty_as_possible(ty); 752 let ty = self.resolve_ty_as_possible(ty);
719 self.write_expr_ty(tgt_expr, ty.clone()); 753 self.write_expr_ty(tgt_expr, ty.clone());
@@ -730,7 +764,7 @@ impl<'a> InferenceContext<'a> {
730 match stmt { 764 match stmt {
731 Statement::Let { pat, type_ref, initializer } => { 765 Statement::Let { pat, type_ref, initializer } => {
732 let decl_ty = 766 let decl_ty =
733 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); 767 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(self.err_ty());
734 768
735 // Always use the declared type when specified 769 // Always use the declared type when specified
736 let mut ty = decl_ty.clone(); 770 let mut ty = decl_ty.clone();
@@ -738,7 +772,7 @@ impl<'a> InferenceContext<'a> {
738 if let Some(expr) = initializer { 772 if let Some(expr) = initializer {
739 let actual_ty = 773 let actual_ty =
740 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); 774 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
741 if decl_ty == Ty::Unknown { 775 if decl_ty.is_unknown() {
742 ty = actual_ty; 776 ty = actual_ty;
743 } 777 }
744 } 778 }
@@ -802,7 +836,7 @@ impl<'a> InferenceContext<'a> {
802 self.write_method_resolution(tgt_expr, func); 836 self.write_method_resolution(tgt_expr, func);
803 (ty, self.db.value_ty(func.into()), Some(generics(self.db.upcast(), func.into()))) 837 (ty, self.db.value_ty(func.into()), Some(generics(self.db.upcast(), func.into())))
804 } 838 }
805 None => (receiver_ty, Binders::new(0, Ty::Unknown), None), 839 None => (receiver_ty, Binders::new(0, self.err_ty()), None),
806 }; 840 };
807 let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); 841 let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty);
808 let method_ty = method_ty.subst(&substs); 842 let method_ty = method_ty.subst(&substs);
@@ -813,15 +847,17 @@ impl<'a> InferenceContext<'a> {
813 if !sig.params().is_empty() { 847 if !sig.params().is_empty() {
814 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) 848 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
815 } else { 849 } else {
816 (Ty::Unknown, Vec::new(), sig.ret().clone()) 850 (self.err_ty(), Vec::new(), sig.ret().clone())
817 } 851 }
818 } 852 }
819 None => (Ty::Unknown, Vec::new(), Ty::Unknown), 853 None => (self.err_ty(), Vec::new(), self.err_ty()),
820 }; 854 };
821 // Apply autoref so the below unification works correctly 855 // Apply autoref so the below unification works correctly
822 // FIXME: return correct autorefs from lookup_method 856 // FIXME: return correct autorefs from lookup_method
823 let actual_receiver_ty = match expected_receiver_ty.as_reference() { 857 let actual_receiver_ty = match expected_receiver_ty.as_reference() {
824 Some((_, mutability)) => Ty::Ref(mutability, Substs::single(derefed_receiver_ty)), 858 Some((_, mutability)) => {
859 TyKind::Ref(mutability, Substs::single(derefed_receiver_ty)).intern(&Interner)
860 }
825 _ => derefed_receiver_ty, 861 _ => derefed_receiver_ty,
826 }; 862 };
827 self.unify(&expected_receiver_ty, &actual_receiver_ty); 863 self.unify(&expected_receiver_ty, &actual_receiver_ty);
@@ -837,7 +873,7 @@ impl<'a> InferenceContext<'a> {
837 // that we have more information about the types of arguments when we 873 // that we have more information about the types of arguments when we
838 // type-check the functions. This isn't really the right way to do this. 874 // type-check the functions. This isn't really the right way to do this.
839 for &check_closures in &[false, true] { 875 for &check_closures in &[false, true] {
840 let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); 876 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
841 for (&arg, param_ty) in args.iter().zip(param_iter) { 877 for (&arg, param_ty) in args.iter().zip(param_iter) {
842 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. }); 878 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
843 if is_closure != check_closures { 879 if is_closure != check_closures {
@@ -867,7 +903,7 @@ impl<'a> InferenceContext<'a> {
867 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf { 903 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
868 substs.push(receiver_ty.clone()); 904 substs.push(receiver_ty.clone());
869 } else { 905 } else {
870 substs.push(Ty::Unknown); 906 substs.push(self.err_ty());
871 } 907 }
872 } 908 }
873 } 909 }
@@ -891,14 +927,15 @@ impl<'a> InferenceContext<'a> {
891 }; 927 };
892 let supplied_params = substs.len(); 928 let supplied_params = substs.len();
893 for _ in supplied_params..total_len { 929 for _ in supplied_params..total_len {
894 substs.push(Ty::Unknown); 930 substs.push(self.err_ty());
895 } 931 }
896 assert_eq!(substs.len(), total_len); 932 assert_eq!(substs.len(), total_len);
897 Substs(substs.into()) 933 Substs(substs.into())
898 } 934 }
899 935
900 fn register_obligations_for_call(&mut self, callable_ty: &Ty) { 936 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
901 if let &Ty::FnDef(def, ref parameters) = callable_ty { 937 if let TyKind::FnDef(fn_def, parameters) = callable_ty.interned(&Interner) {
938 let def: CallableDefId = from_chalk(self.db, *fn_def);
902 let generic_predicates = self.db.generic_predicates(def.into()); 939 let generic_predicates = self.db.generic_predicates(def.into());
903 for predicate in generic_predicates.iter() { 940 for predicate in generic_predicates.iter() {
904 let predicate = predicate.clone().subst(parameters); 941 let predicate = predicate.clone().subst(parameters);
diff --git a/crates/hir_ty/src/infer/pat.rs b/crates/hir_ty/src/infer/pat.rs
index a0ac8d80f..a16755cda 100644
--- a/crates/hir_ty/src/infer/pat.rs
+++ b/crates/hir_ty/src/infer/pat.rs
@@ -12,7 +12,7 @@ use hir_def::{
12use hir_expand::name::Name; 12use hir_expand::name::Name;
13 13
14use super::{BindingMode, Expectation, InferenceContext}; 14use super::{BindingMode, Expectation, InferenceContext};
15use crate::{lower::lower_to_chalk_mutability, utils::variant_data, Substs, Ty}; 15use crate::{lower::lower_to_chalk_mutability, utils::variant_data, Interner, Substs, Ty, TyKind};
16 16
17impl<'a> InferenceContext<'a> { 17impl<'a> InferenceContext<'a> {
18 fn infer_tuple_struct_pat( 18 fn infer_tuple_struct_pat(
@@ -46,7 +46,7 @@ impl<'a> InferenceContext<'a> {
46 let expected_ty = var_data 46 let expected_ty = var_data
47 .as_ref() 47 .as_ref()
48 .and_then(|d| d.field(&Name::new_tuple_field(i))) 48 .and_then(|d| d.field(&Name::new_tuple_field(i)))
49 .map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs)); 49 .map_or(self.err_ty(), |field| field_tys[field].clone().subst(&substs));
50 let expected_ty = self.normalize_associated_types_in(expected_ty); 50 let expected_ty = self.normalize_associated_types_in(expected_ty);
51 self.infer_pat(subpat, &expected_ty, default_bm); 51 self.infer_pat(subpat, &expected_ty, default_bm);
52 } 52 }
@@ -80,8 +80,8 @@ impl<'a> InferenceContext<'a> {
80 self.result.record_pat_field_resolutions.insert(subpat.pat, field_def); 80 self.result.record_pat_field_resolutions.insert(subpat.pat, field_def);
81 } 81 }
82 82
83 let expected_ty = 83 let expected_ty = matching_field
84 matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs)); 84 .map_or(self.err_ty(), |field| field_tys[field].clone().subst(&substs));
85 let expected_ty = self.normalize_associated_types_in(expected_ty); 85 let expected_ty = self.normalize_associated_types_in(expected_ty);
86 self.infer_pat(subpat.pat, &expected_ty, default_bm); 86 self.infer_pat(subpat.pat, &expected_ty, default_bm);
87 } 87 }
@@ -129,7 +129,8 @@ impl<'a> InferenceContext<'a> {
129 None => (&args[..], &[][..]), 129 None => (&args[..], &[][..]),
130 }; 130 };
131 let n_uncovered_patterns = expectations.len().saturating_sub(args.len()); 131 let n_uncovered_patterns = expectations.len().saturating_sub(args.len());
132 let mut expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); 132 let err_ty = self.err_ty();
133 let mut expectations_iter = expectations.iter().chain(repeat(&err_ty));
133 let mut infer_pat = |(&pat, ty)| self.infer_pat(pat, ty, default_bm); 134 let mut infer_pat = |(&pat, ty)| self.infer_pat(pat, ty, default_bm);
134 135
135 let mut inner_tys = Vec::with_capacity(n_uncovered_patterns + args.len()); 136 let mut inner_tys = Vec::with_capacity(n_uncovered_patterns + args.len());
@@ -137,7 +138,7 @@ impl<'a> InferenceContext<'a> {
137 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned()); 138 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned());
138 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat)); 139 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat));
139 140
140 Ty::Tuple(inner_tys.len(), Substs(inner_tys.into())) 141 TyKind::Tuple(inner_tys.len(), Substs(inner_tys.into())).intern(&Interner)
141 } 142 }
142 Pat::Or(ref pats) => { 143 Pat::Or(ref pats) => {
143 if let Some((first_pat, rest)) = pats.split_first() { 144 if let Some((first_pat, rest)) = pats.split_first() {
@@ -147,7 +148,7 @@ impl<'a> InferenceContext<'a> {
147 } 148 }
148 ty 149 ty
149 } else { 150 } else {
150 Ty::Unknown 151 self.err_ty()
151 } 152 }
152 } 153 }
153 Pat::Ref { pat, mutability } => { 154 Pat::Ref { pat, mutability } => {
@@ -159,10 +160,10 @@ impl<'a> InferenceContext<'a> {
159 } 160 }
160 inner_ty 161 inner_ty
161 } 162 }
162 _ => &Ty::Unknown, 163 _ => &Ty(TyKind::Unknown),
163 }; 164 };
164 let subty = self.infer_pat(*pat, expectation, default_bm); 165 let subty = self.infer_pat(*pat, expectation, default_bm);
165 Ty::Ref(mutability, Substs::single(subty)) 166 TyKind::Ref(mutability, Substs::single(subty)).intern(&Interner)
166 } 167 }
167 Pat::TupleStruct { path: p, args: subpats, ellipsis } => self.infer_tuple_struct_pat( 168 Pat::TupleStruct { path: p, args: subpats, ellipsis } => self.infer_tuple_struct_pat(
168 p.as_ref(), 169 p.as_ref(),
@@ -178,7 +179,7 @@ impl<'a> InferenceContext<'a> {
178 Pat::Path(path) => { 179 Pat::Path(path) => {
179 // FIXME use correct resolver for the surrounding expression 180 // FIXME use correct resolver for the surrounding expression
180 let resolver = self.resolver.clone(); 181 let resolver = self.resolver.clone();
181 self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) 182 self.infer_path(&resolver, &path, pat.into()).unwrap_or(self.err_ty())
182 } 183 }
183 Pat::Bind { mode, name: _, subpat } => { 184 Pat::Bind { mode, name: _, subpat } => {
184 let mode = if mode == &BindingAnnotation::Unannotated { 185 let mode = if mode == &BindingAnnotation::Unannotated {
@@ -195,7 +196,7 @@ impl<'a> InferenceContext<'a> {
195 196
196 let bound_ty = match mode { 197 let bound_ty = match mode {
197 BindingMode::Ref(mutability) => { 198 BindingMode::Ref(mutability) => {
198 Ty::Ref(mutability, Substs::single(inner_ty.clone())) 199 TyKind::Ref(mutability, Substs::single(inner_ty.clone())).intern(&Interner)
199 } 200 }
200 BindingMode::Move => inner_ty.clone(), 201 BindingMode::Move => inner_ty.clone(),
201 }; 202 };
@@ -204,17 +205,17 @@ impl<'a> InferenceContext<'a> {
204 return inner_ty; 205 return inner_ty;
205 } 206 }
206 Pat::Slice { prefix, slice, suffix } => { 207 Pat::Slice { prefix, slice, suffix } => {
207 let (container_ty, elem_ty): (fn(_) -> _, _) = match &expected { 208 let (container_ty, elem_ty): (fn(_) -> _, _) = match expected.interned(&Interner) {
208 Ty::Array(st) => (Ty::Array, st.as_single().clone()), 209 TyKind::Array(st) => (TyKind::Array, st.as_single().clone()),
209 Ty::Slice(st) => (Ty::Slice, st.as_single().clone()), 210 TyKind::Slice(st) => (TyKind::Slice, st.as_single().clone()),
210 _ => (Ty::Slice, Ty::Unknown), 211 _ => (TyKind::Slice, self.err_ty()),
211 }; 212 };
212 213
213 for pat_id in prefix.iter().chain(suffix) { 214 for pat_id in prefix.iter().chain(suffix) {
214 self.infer_pat(*pat_id, &elem_ty, default_bm); 215 self.infer_pat(*pat_id, &elem_ty, default_bm);
215 } 216 }
216 217
217 let pat_ty = container_ty(Substs::single(elem_ty)); 218 let pat_ty = container_ty(Substs::single(elem_ty)).intern(&Interner);
218 if let Some(slice_pat_id) = slice { 219 if let Some(slice_pat_id) = slice {
219 self.infer_pat(*slice_pat_id, &pat_ty, default_bm); 220 self.infer_pat(*slice_pat_id, &pat_ty, default_bm);
220 } 221 }
@@ -232,20 +233,20 @@ impl<'a> InferenceContext<'a> {
232 Some(box_adt) => { 233 Some(box_adt) => {
233 let inner_expected = match expected.as_adt() { 234 let inner_expected = match expected.as_adt() {
234 Some((adt, substs)) if adt == box_adt => substs.as_single(), 235 Some((adt, substs)) if adt == box_adt => substs.as_single(),
235 _ => &Ty::Unknown, 236 _ => &Ty(TyKind::Unknown),
236 }; 237 };
237 238
238 let inner_ty = self.infer_pat(*inner, inner_expected, default_bm); 239 let inner_ty = self.infer_pat(*inner, inner_expected, default_bm);
239 Ty::adt_ty(box_adt, Substs::single(inner_ty)) 240 Ty::adt_ty(box_adt, Substs::single(inner_ty))
240 } 241 }
241 None => Ty::Unknown, 242 None => self.err_ty(),
242 }, 243 },
243 Pat::ConstBlock(expr) => { 244 Pat::ConstBlock(expr) => {
244 self.infer_expr(*expr, &Expectation::has_type(expected.clone())) 245 self.infer_expr(*expr, &Expectation::has_type(expected.clone()))
245 } 246 }
246 Pat::Missing => Ty::Unknown, 247 Pat::Missing => self.err_ty(),
247 }; 248 };
248 // use a new type variable if we got Ty::Unknown here 249 // use a new type variable if we got error type here
249 let ty = self.insert_type_vars_shallow(ty); 250 let ty = self.insert_type_vars_shallow(ty);
250 if !self.unify(&ty, expected) { 251 if !self.unify(&ty, expected) {
251 // FIXME record mismatch, we need to change the type of self.type_mismatches for that 252 // FIXME record mismatch, we need to change the type of self.type_mismatches for that
diff --git a/crates/hir_ty/src/infer/path.rs b/crates/hir_ty/src/infer/path.rs
index ae3554bac..af108fb6c 100644
--- a/crates/hir_ty/src/infer/path.rs
+++ b/crates/hir_ty/src/infer/path.rs
@@ -9,7 +9,7 @@ use hir_def::{
9}; 9};
10use hir_expand::name::Name; 10use hir_expand::name::Name;
11 11
12use crate::{method_resolution, Substs, Ty, ValueTyDefId}; 12use crate::{method_resolution, Interner, Substs, Ty, TyKind, ValueTyDefId};
13 13
14use super::{ExprOrPatId, InferenceContext, TraitRef}; 14use super::{ExprOrPatId, InferenceContext, TraitRef};
15 15
@@ -40,7 +40,7 @@ impl<'a> InferenceContext<'a> {
40 let ty = self.make_ty(type_ref); 40 let ty = self.make_ty(type_ref);
41 let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1); 41 let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1);
42 let ctx = crate::lower::TyLoweringContext::new(self.db, &resolver); 42 let ctx = crate::lower::TyLoweringContext::new(self.db, &resolver);
43 let (ty, _) = Ty::from_type_relative_path(&ctx, ty, None, remaining_segments_for_ty); 43 let (ty, _) = ctx.lower_ty_relative_path(ty, None, remaining_segments_for_ty);
44 self.resolve_ty_assoc_item( 44 self.resolve_ty_assoc_item(
45 ty, 45 ty,
46 &path.segments().last().expect("path had at least one segment").name, 46 &path.segments().last().expect("path had at least one segment").name,
@@ -79,7 +79,7 @@ impl<'a> InferenceContext<'a> {
79 } 79 }
80 ValueNs::ImplSelf(impl_id) => { 80 ValueNs::ImplSelf(impl_id) => {
81 let generics = crate::utils::generics(self.db.upcast(), impl_id.into()); 81 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
82 let substs = Substs::type_params_for_generics(&generics); 82 let substs = Substs::type_params_for_generics(self.db, &generics);
83 let ty = self.db.impl_self_ty(impl_id).subst(&substs); 83 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
84 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() { 84 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() {
85 let ty = self.db.value_ty(struct_id.into()).subst(&substs); 85 let ty = self.db.value_ty(struct_id.into()).subst(&substs);
@@ -96,7 +96,7 @@ impl<'a> InferenceContext<'a> {
96 // self_subst is just for the parent 96 // self_subst is just for the parent
97 let parent_substs = self_subst.unwrap_or_else(Substs::empty); 97 let parent_substs = self_subst.unwrap_or_else(Substs::empty);
98 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 98 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
99 let substs = Ty::substs_from_path(&ctx, path, typable, true); 99 let substs = ctx.substs_from_path(path, typable, true);
100 let full_substs = Substs::builder(substs.len()) 100 let full_substs = Substs::builder(substs.len())
101 .use_parent_substs(&parent_substs) 101 .use_parent_substs(&parent_substs)
102 .fill(substs.0[parent_substs.len()..].iter().cloned()) 102 .fill(substs.0[parent_substs.len()..].iter().cloned())
@@ -126,7 +126,8 @@ impl<'a> InferenceContext<'a> {
126 let segment = 126 let segment =
127 remaining_segments.last().expect("there should be at least one segment here"); 127 remaining_segments.last().expect("there should be at least one segment here");
128 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 128 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
129 let trait_ref = TraitRef::from_resolved_path(&ctx, trait_, resolved_segment, None); 129 let trait_ref =
130 ctx.lower_trait_ref_from_resolved_path(trait_, resolved_segment, None);
130 self.resolve_trait_assoc_item(trait_ref, segment, id) 131 self.resolve_trait_assoc_item(trait_ref, segment, id)
131 } 132 }
132 (def, _) => { 133 (def, _) => {
@@ -137,14 +138,13 @@ impl<'a> InferenceContext<'a> {
137 let remaining_segments_for_ty = 138 let remaining_segments_for_ty =
138 remaining_segments.take(remaining_segments.len() - 1); 139 remaining_segments.take(remaining_segments.len() - 1);
139 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 140 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
140 let (ty, _) = Ty::from_partly_resolved_hir_path( 141 let (ty, _) = ctx.lower_partly_resolved_path(
141 &ctx,
142 def, 142 def,
143 resolved_segment, 143 resolved_segment,
144 remaining_segments_for_ty, 144 remaining_segments_for_ty,
145 true, 145 true,
146 ); 146 );
147 if let Ty::Unknown = ty { 147 if let TyKind::Unknown = ty.interned(&Interner) {
148 return None; 148 return None;
149 } 149 }
150 150
@@ -209,7 +209,7 @@ impl<'a> InferenceContext<'a> {
209 name: &Name, 209 name: &Name,
210 id: ExprOrPatId, 210 id: ExprOrPatId,
211 ) -> Option<(ValueNs, Option<Substs>)> { 211 ) -> Option<(ValueNs, Option<Substs>)> {
212 if let Ty::Unknown = ty { 212 if let TyKind::Unknown = ty.interned(&Interner) {
213 return None; 213 return None;
214 } 214 }
215 215
diff --git a/crates/hir_ty/src/infer/unify.rs b/crates/hir_ty/src/infer/unify.rs
index 54fcfed10..16d89ed1b 100644
--- a/crates/hir_ty/src/infer/unify.rs
+++ b/crates/hir_ty/src/infer/unify.rs
@@ -7,8 +7,8 @@ use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
7 7
8use super::{InferenceContext, Obligation}; 8use super::{InferenceContext, Obligation};
9use crate::{ 9use crate::{
10 BoundVar, Canonical, DebruijnIndex, GenericPredicate, InEnvironment, InferenceVar, Scalar, 10 BoundVar, Canonical, DebruijnIndex, GenericPredicate, InEnvironment, InferenceVar, Interner,
11 Substs, Ty, TypeWalk, 11 Scalar, Substs, Ty, TyKind, TypeWalk,
12}; 12};
13 13
14impl<'a> InferenceContext<'a> { 14impl<'a> InferenceContext<'a> {
@@ -49,8 +49,8 @@ impl<'a, 'b> Canonicalizer<'a, 'b> {
49 49
50 fn do_canonicalize<T: TypeWalk>(&mut self, t: T, binders: DebruijnIndex) -> T { 50 fn do_canonicalize<T: TypeWalk>(&mut self, t: T, binders: DebruijnIndex) -> T {
51 t.fold_binders( 51 t.fold_binders(
52 &mut |ty, binders| match ty { 52 &mut |ty, binders| match ty.interned(&Interner) {
53 Ty::InferenceVar(var, kind) => { 53 &TyKind::InferenceVar(var, kind) => {
54 let inner = var.to_inner(); 54 let inner = var.to_inner();
55 if self.var_stack.contains(&inner) { 55 if self.var_stack.contains(&inner) {
56 // recursive type 56 // recursive type
@@ -66,7 +66,7 @@ impl<'a, 'b> Canonicalizer<'a, 'b> {
66 } else { 66 } else {
67 let root = self.ctx.table.var_unification_table.find(inner); 67 let root = self.ctx.table.var_unification_table.find(inner);
68 let position = self.add(InferenceVar::from_inner(root), kind); 68 let position = self.add(InferenceVar::from_inner(root), kind);
69 Ty::BoundVar(BoundVar::new(binders, position)) 69 TyKind::BoundVar(BoundVar::new(binders, position)).intern(&Interner)
70 } 70 }
71 } 71 }
72 _ => ty, 72 _ => ty,
@@ -108,10 +108,10 @@ impl<T> Canonicalized<T> {
108 pub(super) fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { 108 pub(super) fn decanonicalize_ty(&self, mut ty: Ty) -> Ty {
109 ty.walk_mut_binders( 109 ty.walk_mut_binders(
110 &mut |ty, binders| { 110 &mut |ty, binders| {
111 if let &mut Ty::BoundVar(bound) = ty { 111 if let &mut TyKind::BoundVar(bound) = &mut ty.0 {
112 if bound.debruijn >= binders { 112 if bound.debruijn >= binders {
113 let (v, k) = self.free_vars[bound.index]; 113 let (v, k) = self.free_vars[bound.index];
114 *ty = Ty::InferenceVar(v, k); 114 *ty = TyKind::InferenceVar(v, k).intern(&Interner);
115 } 115 }
116 } 116 }
117 }, 117 },
@@ -142,7 +142,7 @@ impl<T> Canonicalized<T> {
142 // eagerly replace projections in the type; we may be getting types 142 // eagerly replace projections in the type; we may be getting types
143 // e.g. from where clauses where this hasn't happened yet 143 // e.g. from where clauses where this hasn't happened yet
144 let ty = ctx.normalize_associated_types_in(ty.clone().subst_bound_vars(&new_vars)); 144 let ty = ctx.normalize_associated_types_in(ty.clone().subst_bound_vars(&new_vars));
145 ctx.table.unify(&Ty::InferenceVar(v, k), &ty); 145 ctx.table.unify(&TyKind::InferenceVar(v, k).intern(&Interner), &ty);
146 } 146 }
147 } 147 }
148} 148}
@@ -166,7 +166,10 @@ pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> {
166 // (kind of hacky) 166 // (kind of hacky)
167 for (i, var) in vars.iter().enumerate() { 167 for (i, var) in vars.iter().enumerate() {
168 if &*table.resolve_ty_shallow(var) == var { 168 if &*table.resolve_ty_shallow(var) == var {
169 table.unify(var, &Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i))); 169 table.unify(
170 var,
171 &TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i)).intern(&Interner),
172 );
170 } 173 }
171 } 174 }
172 Some( 175 Some(
@@ -196,11 +199,12 @@ impl TypeVariableTable {
196 199
197 fn fallback_value(&self, iv: InferenceVar, kind: TyVariableKind) -> Ty { 200 fn fallback_value(&self, iv: InferenceVar, kind: TyVariableKind) -> Ty {
198 match kind { 201 match kind {
199 _ if self.inner[iv.to_inner().0 as usize].diverging => Ty::Never, 202 _ if self.inner[iv.to_inner().0 as usize].diverging => TyKind::Never,
200 TyVariableKind::General => Ty::Unknown, 203 TyVariableKind::General => TyKind::Unknown,
201 TyVariableKind::Integer => Ty::Scalar(Scalar::Int(IntTy::I32)), 204 TyVariableKind::Integer => TyKind::Scalar(Scalar::Int(IntTy::I32)),
202 TyVariableKind::Float => Ty::Scalar(Scalar::Float(FloatTy::F64)), 205 TyVariableKind::Float => TyKind::Scalar(Scalar::Float(FloatTy::F64)),
203 } 206 }
207 .intern(&Interner)
204 } 208 }
205} 209}
206 210
@@ -227,7 +231,7 @@ impl InferenceTable {
227 self.type_variable_table.push(TypeVariableData { diverging }); 231 self.type_variable_table.push(TypeVariableData { diverging });
228 let key = self.var_unification_table.new_key(TypeVarValue::Unknown); 232 let key = self.var_unification_table.new_key(TypeVarValue::Unknown);
229 assert_eq!(key.0 as usize, self.type_variable_table.inner.len() - 1); 233 assert_eq!(key.0 as usize, self.type_variable_table.inner.len() - 1);
230 Ty::InferenceVar(InferenceVar::from_inner(key), kind) 234 TyKind::InferenceVar(InferenceVar::from_inner(key), kind).intern(&Interner)
231 } 235 }
232 236
233 pub(crate) fn new_type_var(&mut self) -> Ty { 237 pub(crate) fn new_type_var(&mut self) -> Ty {
@@ -290,12 +294,12 @@ impl InferenceTable {
290 } 294 }
291 295
292 pub(super) fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { 296 pub(super) fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool {
293 match (ty1, ty2) { 297 match (ty1.interned(&Interner), ty2.interned(&Interner)) {
294 (Ty::Unknown, _) | (_, Ty::Unknown) => true, 298 (TyKind::Unknown, _) | (_, TyKind::Unknown) => true,
295 299
296 (Ty::Placeholder(p1), Ty::Placeholder(p2)) if *p1 == *p2 => true, 300 (TyKind::Placeholder(p1), TyKind::Placeholder(p2)) if *p1 == *p2 => true,
297 301
298 (Ty::Dyn(dyn1), Ty::Dyn(dyn2)) if dyn1.len() == dyn2.len() => { 302 (TyKind::Dyn(dyn1), TyKind::Dyn(dyn2)) if dyn1.len() == dyn2.len() => {
299 for (pred1, pred2) in dyn1.iter().zip(dyn2.iter()) { 303 for (pred1, pred2) in dyn1.iter().zip(dyn2.iter()) {
300 if !self.unify_preds(pred1, pred2, depth + 1) { 304 if !self.unify_preds(pred1, pred2, depth + 1) {
301 return false; 305 return false;
@@ -305,16 +309,16 @@ impl InferenceTable {
305 } 309 }
306 310
307 ( 311 (
308 Ty::InferenceVar(tv1, TyVariableKind::General), 312 TyKind::InferenceVar(tv1, TyVariableKind::General),
309 Ty::InferenceVar(tv2, TyVariableKind::General), 313 TyKind::InferenceVar(tv2, TyVariableKind::General),
310 ) 314 )
311 | ( 315 | (
312 Ty::InferenceVar(tv1, TyVariableKind::Integer), 316 TyKind::InferenceVar(tv1, TyVariableKind::Integer),
313 Ty::InferenceVar(tv2, TyVariableKind::Integer), 317 TyKind::InferenceVar(tv2, TyVariableKind::Integer),
314 ) 318 )
315 | ( 319 | (
316 Ty::InferenceVar(tv1, TyVariableKind::Float), 320 TyKind::InferenceVar(tv1, TyVariableKind::Float),
317 Ty::InferenceVar(tv2, TyVariableKind::Float), 321 TyKind::InferenceVar(tv2, TyVariableKind::Float),
318 ) if self.type_variable_table.is_diverging(*tv1) 322 ) if self.type_variable_table.is_diverging(*tv1)
319 == self.type_variable_table.is_diverging(*tv2) => 323 == self.type_variable_table.is_diverging(*tv2) =>
320 { 324 {
@@ -326,24 +330,37 @@ impl InferenceTable {
326 // The order of MaybeNeverTypeVar matters here. 330 // The order of MaybeNeverTypeVar matters here.
327 // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. 331 // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar.
328 // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. 332 // Unifying MaybeNeverTypeVar and other concrete type will let the former become it.
329 (Ty::InferenceVar(tv, TyVariableKind::General), other) 333 (TyKind::InferenceVar(tv, TyVariableKind::General), other)
330 | (other, Ty::InferenceVar(tv, TyVariableKind::General)) 334 | (other, TyKind::InferenceVar(tv, TyVariableKind::General))
331 | (Ty::InferenceVar(tv, TyVariableKind::Integer), other @ Ty::Scalar(Scalar::Int(_)))
332 | (other @ Ty::Scalar(Scalar::Int(_)), Ty::InferenceVar(tv, TyVariableKind::Integer))
333 | ( 335 | (
334 Ty::InferenceVar(tv, TyVariableKind::Integer), 336 TyKind::InferenceVar(tv, TyVariableKind::Integer),
335 other @ Ty::Scalar(Scalar::Uint(_)), 337 other @ TyKind::Scalar(Scalar::Int(_)),
336 ) 338 )
337 | ( 339 | (
338 other @ Ty::Scalar(Scalar::Uint(_)), 340 other @ TyKind::Scalar(Scalar::Int(_)),
339 Ty::InferenceVar(tv, TyVariableKind::Integer), 341 TyKind::InferenceVar(tv, TyVariableKind::Integer),
340 ) 342 )
341 | (Ty::InferenceVar(tv, TyVariableKind::Float), other @ Ty::Scalar(Scalar::Float(_))) 343 | (
342 | (other @ Ty::Scalar(Scalar::Float(_)), Ty::InferenceVar(tv, TyVariableKind::Float)) => 344 TyKind::InferenceVar(tv, TyVariableKind::Integer),
343 { 345 other @ TyKind::Scalar(Scalar::Uint(_)),
346 )
347 | (
348 other @ TyKind::Scalar(Scalar::Uint(_)),
349 TyKind::InferenceVar(tv, TyVariableKind::Integer),
350 )
351 | (
352 TyKind::InferenceVar(tv, TyVariableKind::Float),
353 other @ TyKind::Scalar(Scalar::Float(_)),
354 )
355 | (
356 other @ TyKind::Scalar(Scalar::Float(_)),
357 TyKind::InferenceVar(tv, TyVariableKind::Float),
358 ) => {
344 // the type var is unknown since we tried to resolve it 359 // the type var is unknown since we tried to resolve it
345 self.var_unification_table 360 self.var_unification_table.union_value(
346 .union_value(tv.to_inner(), TypeVarValue::Known(other.clone())); 361 tv.to_inner(),
362 TypeVarValue::Known(other.clone().intern(&Interner)),
363 );
347 true 364 true
348 } 365 }
349 366
@@ -387,8 +404,8 @@ impl InferenceTable {
387 if i > 0 { 404 if i > 0 {
388 cov_mark::hit!(type_var_resolves_to_int_var); 405 cov_mark::hit!(type_var_resolves_to_int_var);
389 } 406 }
390 match &*ty { 407 match &ty.0 {
391 Ty::InferenceVar(tv, _) => { 408 TyKind::InferenceVar(tv, _) => {
392 let inner = tv.to_inner(); 409 let inner = tv.to_inner();
393 match self.var_unification_table.inlined_probe_value(inner).known() { 410 match self.var_unification_table.inlined_probe_value(inner).known() {
394 Some(known_ty) => { 411 Some(known_ty) => {
@@ -410,8 +427,8 @@ impl InferenceTable {
410 /// be resolved as far as possible, i.e. contain no type variables with 427 /// be resolved as far as possible, i.e. contain no type variables with
411 /// known type. 428 /// known type.
412 fn resolve_ty_as_possible_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { 429 fn resolve_ty_as_possible_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
413 ty.fold(&mut |ty| match ty { 430 ty.fold(&mut |ty| match ty.interned(&Interner) {
414 Ty::InferenceVar(tv, kind) => { 431 &TyKind::InferenceVar(tv, kind) => {
415 let inner = tv.to_inner(); 432 let inner = tv.to_inner();
416 if tv_stack.contains(&inner) { 433 if tv_stack.contains(&inner) {
417 cov_mark::hit!(type_var_cycles_resolve_as_possible); 434 cov_mark::hit!(type_var_cycles_resolve_as_possible);
@@ -435,10 +452,10 @@ impl InferenceTable {
435 } 452 }
436 453
437 /// Resolves the type completely; type variables without known type are 454 /// Resolves the type completely; type variables without known type are
438 /// replaced by Ty::Unknown. 455 /// replaced by TyKind::Unknown.
439 fn resolve_ty_completely_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { 456 fn resolve_ty_completely_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
440 ty.fold(&mut |ty| match ty { 457 ty.fold(&mut |ty| match ty.interned(&Interner) {
441 Ty::InferenceVar(tv, kind) => { 458 &TyKind::InferenceVar(tv, kind) => {
442 let inner = tv.to_inner(); 459 let inner = tv.to_inner();
443 if tv_stack.contains(&inner) { 460 if tv_stack.contains(&inner) {
444 cov_mark::hit!(type_var_cycles_resolve_completely); 461 cov_mark::hit!(type_var_cycles_resolve_completely);
diff --git a/crates/hir_ty/src/lib.rs b/crates/hir_ty/src/lib.rs
index e77f24e4e..d6ff968f0 100644
--- a/crates/hir_ty/src/lib.rs
+++ b/crates/hir_ty/src/lib.rs
@@ -27,9 +27,8 @@ use std::{iter, mem, ops::Deref, sync::Arc};
27 27
28use base_db::salsa; 28use base_db::salsa;
29use hir_def::{ 29use hir_def::{
30 builtin_type::BuiltinType, expr::ExprId, type_ref::Rawness, AssocContainerId, DefWithBodyId, 30 builtin_type::BuiltinType, expr::ExprId, type_ref::Rawness, AssocContainerId, FunctionId,
31 FunctionId, GenericDefId, HasModule, LifetimeParamId, Lookup, TraitId, TypeAliasId, 31 GenericDefId, HasModule, LifetimeParamId, Lookup, TraitId, TypeAliasId, TypeParamId,
32 TypeParamId,
33}; 32};
34use itertools::Itertools; 33use itertools::Itertools;
35 34
@@ -49,7 +48,14 @@ pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironmen
49 48
50pub use chalk_ir::{AdtId, BoundVar, DebruijnIndex, Mutability, Scalar, TyVariableKind}; 49pub use chalk_ir::{AdtId, BoundVar, DebruijnIndex, Mutability, Scalar, TyVariableKind};
51 50
52pub(crate) use crate::traits::chalk::Interner; 51pub use crate::traits::chalk::Interner;
52
53pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
54pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
55pub type FnDefId = chalk_ir::FnDefId<Interner>;
56pub type ClosureId = chalk_ir::ClosureId<Interner>;
57pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
58pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
53 59
54#[derive(Clone, PartialEq, Eq, Debug, Hash)] 60#[derive(Clone, PartialEq, Eq, Debug, Hash)]
55pub enum Lifetime { 61pub enum Lifetime {
@@ -68,7 +74,7 @@ pub struct OpaqueTy {
68/// trait and all its parameters are fully known. 74/// trait and all its parameters are fully known.
69#[derive(Clone, PartialEq, Eq, Debug, Hash)] 75#[derive(Clone, PartialEq, Eq, Debug, Hash)]
70pub struct ProjectionTy { 76pub struct ProjectionTy {
71 pub associated_ty: TypeAliasId, 77 pub associated_ty: AssocTypeId,
72 pub parameters: Substs, 78 pub parameters: Substs,
73} 79}
74 80
@@ -78,7 +84,7 @@ impl ProjectionTy {
78 } 84 }
79 85
80 fn trait_(&self, db: &dyn HirDatabase) -> TraitId { 86 fn trait_(&self, db: &dyn HirDatabase) -> TraitId {
81 match self.associated_ty.lookup(db.upcast()).container { 87 match from_assoc_type_id(self.associated_ty).lookup(db.upcast()).container {
82 AssocContainerId::TraitId(it) => it, 88 AssocContainerId::TraitId(it) => it,
83 _ => panic!("projection ty without parent trait"), 89 _ => panic!("projection ty without parent trait"),
84 } 90 }
@@ -131,7 +137,7 @@ pub enum AliasTy {
131/// 137///
132/// This should be cheap to clone. 138/// This should be cheap to clone.
133#[derive(Clone, PartialEq, Eq, Debug, Hash)] 139#[derive(Clone, PartialEq, Eq, Debug, Hash)]
134pub enum Ty { 140pub enum TyKind {
135 /// Structures, enumerations and unions. 141 /// Structures, enumerations and unions.
136 Adt(AdtId<Interner>, Substs), 142 Adt(AdtId<Interner>, Substs),
137 143
@@ -139,7 +145,7 @@ pub enum Ty {
139 /// when we have tried to normalize a projection like `T::Item` but 145 /// when we have tried to normalize a projection like `T::Item` but
140 /// couldn't find a better representation. In that case, we generate 146 /// couldn't find a better representation. In that case, we generate
141 /// an **application type** like `(Iterator::Item)<T>`. 147 /// an **application type** like `(Iterator::Item)<T>`.
142 AssociatedType(TypeAliasId, Substs), 148 AssociatedType(AssocTypeId, Substs),
143 149
144 /// a scalar type like `bool` or `u32` 150 /// a scalar type like `bool` or `u32`
145 Scalar(Scalar), 151 Scalar(Scalar),
@@ -179,7 +185,7 @@ pub enum Ty {
179 /// fn foo() -> i32 { 1 } 185 /// fn foo() -> i32 { 1 }
180 /// let bar = foo; // bar: fn() -> i32 {foo} 186 /// let bar = foo; // bar: fn() -> i32 {foo}
181 /// ``` 187 /// ```
182 FnDef(CallableDefId, Substs), 188 FnDef(FnDefId, Substs),
183 189
184 /// The pointee of a string slice. Written as `str`. 190 /// The pointee of a string slice. Written as `str`.
185 Str, 191 Str,
@@ -191,10 +197,10 @@ pub enum Ty {
191 /// 197 ///
192 /// The closure signature is stored in a `FnPtr` type in the first type 198 /// The closure signature is stored in a `FnPtr` type in the first type
193 /// parameter. 199 /// parameter.
194 Closure(DefWithBodyId, ExprId, Substs), 200 Closure(ClosureId, Substs),
195 201
196 /// Represents a foreign type declared in external blocks. 202 /// Represents a foreign type declared in external blocks.
197 ForeignType(TypeAliasId), 203 ForeignType(ForeignDefId),
198 204
199 /// A pointer to a function. Written as `fn() -> i32`. 205 /// A pointer to a function. Written as `fn() -> i32`.
200 /// 206 ///
@@ -216,7 +222,7 @@ pub enum Ty {
216 /// {}` when we're type-checking the body of that function. In this 222 /// {}` when we're type-checking the body of that function. In this
217 /// situation, we know this stands for *some* type, but don't know the exact 223 /// situation, we know this stands for *some* type, but don't know the exact
218 /// type. 224 /// type.
219 Placeholder(TypeParamId), 225 Placeholder(PlaceholderIndex),
220 226
221 /// A bound type variable. This is used in various places: when representing 227 /// A bound type variable. This is used in various places: when representing
222 /// some polymorphic type like the type of function `fn f<T>`, the type 228 /// some polymorphic type like the type of function `fn f<T>`, the type
@@ -244,6 +250,21 @@ pub enum Ty {
244 Unknown, 250 Unknown,
245} 251}
246 252
253#[derive(Clone, PartialEq, Eq, Debug, Hash)]
254pub struct Ty(TyKind);
255
256impl TyKind {
257 pub fn intern(self, _interner: &Interner) -> Ty {
258 Ty(self)
259 }
260}
261
262impl Ty {
263 pub fn interned(&self, _interner: &Interner) -> &TyKind {
264 &self.0
265 }
266}
267
247/// A list of substitutions for generic parameters. 268/// A list of substitutions for generic parameters.
248#[derive(Clone, PartialEq, Eq, Debug, Hash)] 269#[derive(Clone, PartialEq, Eq, Debug, Hash)]
249pub struct Substs(Arc<[Ty]>); 270pub struct Substs(Arc<[Ty]>);
@@ -291,14 +312,22 @@ impl Substs {
291 } 312 }
292 313
293 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). 314 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
294 pub(crate) fn type_params_for_generics(generic_params: &Generics) -> Substs { 315 pub(crate) fn type_params_for_generics(
295 Substs(generic_params.iter().map(|(id, _)| Ty::Placeholder(id)).collect()) 316 db: &dyn HirDatabase,
317 generic_params: &Generics,
318 ) -> Substs {
319 Substs(
320 generic_params
321 .iter()
322 .map(|(id, _)| TyKind::Placeholder(to_placeholder_idx(db, id)).intern(&Interner))
323 .collect(),
324 )
296 } 325 }
297 326
298 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). 327 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
299 pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substs { 328 pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substs {
300 let params = generics(db.upcast(), def.into()); 329 let params = generics(db.upcast(), def.into());
301 Substs::type_params_for_generics(&params) 330 Substs::type_params_for_generics(db, &params)
302 } 331 }
303 332
304 /// Return Substs that replace each parameter by a bound variable. 333 /// Return Substs that replace each parameter by a bound variable.
@@ -307,7 +336,7 @@ impl Substs {
307 generic_params 336 generic_params
308 .iter() 337 .iter()
309 .enumerate() 338 .enumerate()
310 .map(|(idx, _)| Ty::BoundVar(BoundVar::new(debruijn, idx))) 339 .map(|(idx, _)| TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(&Interner))
311 .collect(), 340 .collect(),
312 ) 341 )
313 } 342 }
@@ -355,11 +384,14 @@ impl SubstsBuilder {
355 } 384 }
356 385
357 pub fn fill_with_bound_vars(self, debruijn: DebruijnIndex, starting_from: usize) -> Self { 386 pub fn fill_with_bound_vars(self, debruijn: DebruijnIndex, starting_from: usize) -> Self {
358 self.fill((starting_from..).map(|idx| Ty::BoundVar(BoundVar::new(debruijn, idx)))) 387 self.fill(
388 (starting_from..)
389 .map(|idx| TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(&Interner)),
390 )
359 } 391 }
360 392
361 pub fn fill_with_unknown(self) -> Self { 393 pub fn fill_with_unknown(self) -> Self {
362 self.fill(iter::repeat(Ty::Unknown)) 394 self.fill(iter::repeat(TyKind::Unknown.intern(&Interner)))
363 } 395 }
364 396
365 pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self { 397 pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self {
@@ -601,45 +633,52 @@ impl TypeWalk for CallableSig {
601 633
602impl Ty { 634impl Ty {
603 pub fn unit() -> Self { 635 pub fn unit() -> Self {
604 Ty::Tuple(0, Substs::empty()) 636 TyKind::Tuple(0, Substs::empty()).intern(&Interner)
605 } 637 }
606 638
607 pub fn adt_ty(adt: hir_def::AdtId, substs: Substs) -> Ty { 639 pub fn adt_ty(adt: hir_def::AdtId, substs: Substs) -> Ty {
608 Ty::Adt(AdtId(adt), substs) 640 TyKind::Adt(AdtId(adt), substs).intern(&Interner)
609 } 641 }
610 642
611 pub fn fn_ptr(sig: CallableSig) -> Self { 643 pub fn fn_ptr(sig: CallableSig) -> Self {
612 Ty::Function(FnPointer { 644 TyKind::Function(FnPointer {
613 num_args: sig.params().len(), 645 num_args: sig.params().len(),
614 sig: FnSig { variadic: sig.is_varargs }, 646 sig: FnSig { variadic: sig.is_varargs },
615 substs: Substs(sig.params_and_return), 647 substs: Substs(sig.params_and_return),
616 }) 648 })
649 .intern(&Interner)
617 } 650 }
618 651
619 pub fn builtin(builtin: BuiltinType) -> Self { 652 pub fn builtin(builtin: BuiltinType) -> Self {
620 match builtin { 653 match builtin {
621 BuiltinType::Char => Ty::Scalar(Scalar::Char), 654 BuiltinType::Char => TyKind::Scalar(Scalar::Char).intern(&Interner),
622 BuiltinType::Bool => Ty::Scalar(Scalar::Bool), 655 BuiltinType::Bool => TyKind::Scalar(Scalar::Bool).intern(&Interner),
623 BuiltinType::Str => Ty::Str, 656 BuiltinType::Str => TyKind::Str.intern(&Interner),
624 BuiltinType::Int(t) => Ty::Scalar(Scalar::Int(primitive::int_ty_from_builtin(t))), 657 BuiltinType::Int(t) => {
625 BuiltinType::Uint(t) => Ty::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(t))), 658 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(t))).intern(&Interner)
626 BuiltinType::Float(t) => Ty::Scalar(Scalar::Float(primitive::float_ty_from_builtin(t))), 659 }
660 BuiltinType::Uint(t) => {
661 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(t))).intern(&Interner)
662 }
663 BuiltinType::Float(t) => {
664 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(t))).intern(&Interner)
665 }
627 } 666 }
628 } 667 }
629 668
630 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> { 669 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> {
631 match self { 670 match self.interned(&Interner) {
632 Ty::Ref(mutability, parameters) => Some((parameters.as_single(), *mutability)), 671 TyKind::Ref(mutability, parameters) => Some((parameters.as_single(), *mutability)),
633 _ => None, 672 _ => None,
634 } 673 }
635 } 674 }
636 675
637 pub fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> { 676 pub fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> {
638 match self { 677 match self.interned(&Interner) {
639 Ty::Ref(mutability, parameters) => { 678 TyKind::Ref(mutability, parameters) => {
640 Some((parameters.as_single(), Rawness::Ref, *mutability)) 679 Some((parameters.as_single(), Rawness::Ref, *mutability))
641 } 680 }
642 Ty::Raw(mutability, parameters) => { 681 TyKind::Raw(mutability, parameters) => {
643 Some((parameters.as_single(), Rawness::RawPtr, *mutability)) 682 Some((parameters.as_single(), Rawness::RawPtr, *mutability))
644 } 683 }
645 _ => None, 684 _ => None,
@@ -649,7 +688,7 @@ impl Ty {
649 pub fn strip_references(&self) -> &Ty { 688 pub fn strip_references(&self) -> &Ty {
650 let mut t: &Ty = self; 689 let mut t: &Ty = self;
651 690
652 while let Ty::Ref(_mutability, parameters) = t { 691 while let TyKind::Ref(_mutability, parameters) = t.interned(&Interner) {
653 t = parameters.as_single(); 692 t = parameters.as_single();
654 } 693 }
655 694
@@ -657,65 +696,71 @@ impl Ty {
657 } 696 }
658 697
659 pub fn as_adt(&self) -> Option<(hir_def::AdtId, &Substs)> { 698 pub fn as_adt(&self) -> Option<(hir_def::AdtId, &Substs)> {
660 match self { 699 match self.interned(&Interner) {
661 Ty::Adt(AdtId(adt), parameters) => Some((*adt, parameters)), 700 TyKind::Adt(AdtId(adt), parameters) => Some((*adt, parameters)),
662 _ => None, 701 _ => None,
663 } 702 }
664 } 703 }
665 704
666 pub fn as_tuple(&self) -> Option<&Substs> { 705 pub fn as_tuple(&self) -> Option<&Substs> {
667 match self { 706 match self.interned(&Interner) {
668 Ty::Tuple(_, substs) => Some(substs), 707 TyKind::Tuple(_, substs) => Some(substs),
669 _ => None, 708 _ => None,
670 } 709 }
671 } 710 }
672 711
673 pub fn as_generic_def(&self) -> Option<GenericDefId> { 712 pub fn as_generic_def(&self, db: &dyn HirDatabase) -> Option<GenericDefId> {
674 match *self { 713 match *self.interned(&Interner) {
675 Ty::Adt(AdtId(adt), ..) => Some(adt.into()), 714 TyKind::Adt(AdtId(adt), ..) => Some(adt.into()),
676 Ty::FnDef(callable, ..) => Some(callable.into()), 715 TyKind::FnDef(callable, ..) => {
677 Ty::AssociatedType(type_alias, ..) => Some(type_alias.into()), 716 Some(db.lookup_intern_callable_def(callable.into()).into())
678 Ty::ForeignType(type_alias, ..) => Some(type_alias.into()), 717 }
718 TyKind::AssociatedType(type_alias, ..) => Some(from_assoc_type_id(type_alias).into()),
719 TyKind::ForeignType(type_alias, ..) => Some(from_foreign_def_id(type_alias).into()),
679 _ => None, 720 _ => None,
680 } 721 }
681 } 722 }
682 723
683 pub fn is_never(&self) -> bool { 724 pub fn is_never(&self) -> bool {
684 matches!(self, Ty::Never) 725 matches!(self.interned(&Interner), TyKind::Never)
685 } 726 }
686 727
687 pub fn is_unknown(&self) -> bool { 728 pub fn is_unknown(&self) -> bool {
688 matches!(self, Ty::Unknown) 729 matches!(self.interned(&Interner), TyKind::Unknown)
689 } 730 }
690 731
691 pub fn equals_ctor(&self, other: &Ty) -> bool { 732 pub fn equals_ctor(&self, other: &Ty) -> bool {
692 match (self, other) { 733 match (self.interned(&Interner), other.interned(&Interner)) {
693 (Ty::Adt(adt, ..), Ty::Adt(adt2, ..)) => adt == adt2, 734 (TyKind::Adt(adt, ..), TyKind::Adt(adt2, ..)) => adt == adt2,
694 (Ty::Slice(_), Ty::Slice(_)) | (Ty::Array(_), Ty::Array(_)) => true, 735 (TyKind::Slice(_), TyKind::Slice(_)) | (TyKind::Array(_), TyKind::Array(_)) => true,
695 (Ty::FnDef(def_id, ..), Ty::FnDef(def_id2, ..)) => def_id == def_id2, 736 (TyKind::FnDef(def_id, ..), TyKind::FnDef(def_id2, ..)) => def_id == def_id2,
696 (Ty::OpaqueType(ty_id, ..), Ty::OpaqueType(ty_id2, ..)) => ty_id == ty_id2, 737 (TyKind::OpaqueType(ty_id, ..), TyKind::OpaqueType(ty_id2, ..)) => ty_id == ty_id2,
697 (Ty::AssociatedType(ty_id, ..), Ty::AssociatedType(ty_id2, ..)) 738 (TyKind::AssociatedType(ty_id, ..), TyKind::AssociatedType(ty_id2, ..)) => {
698 | (Ty::ForeignType(ty_id, ..), Ty::ForeignType(ty_id2, ..)) => ty_id == ty_id2, 739 ty_id == ty_id2
699 (Ty::Closure(def, expr, _), Ty::Closure(def2, expr2, _)) => { 740 }
700 expr == expr2 && def == def2 741 (TyKind::ForeignType(ty_id, ..), TyKind::ForeignType(ty_id2, ..)) => ty_id == ty_id2,
742 (TyKind::Closure(id1, _), TyKind::Closure(id2, _)) => id1 == id2,
743 (TyKind::Ref(mutability, ..), TyKind::Ref(mutability2, ..))
744 | (TyKind::Raw(mutability, ..), TyKind::Raw(mutability2, ..)) => {
745 mutability == mutability2
701 } 746 }
702 (Ty::Ref(mutability, ..), Ty::Ref(mutability2, ..))
703 | (Ty::Raw(mutability, ..), Ty::Raw(mutability2, ..)) => mutability == mutability2,
704 ( 747 (
705 Ty::Function(FnPointer { num_args, sig, .. }), 748 TyKind::Function(FnPointer { num_args, sig, .. }),
706 Ty::Function(FnPointer { num_args: num_args2, sig: sig2, .. }), 749 TyKind::Function(FnPointer { num_args: num_args2, sig: sig2, .. }),
707 ) => num_args == num_args2 && sig == sig2, 750 ) => num_args == num_args2 && sig == sig2,
708 (Ty::Tuple(cardinality, _), Ty::Tuple(cardinality2, _)) => cardinality == cardinality2, 751 (TyKind::Tuple(cardinality, _), TyKind::Tuple(cardinality2, _)) => {
709 (Ty::Str, Ty::Str) | (Ty::Never, Ty::Never) => true, 752 cardinality == cardinality2
710 (Ty::Scalar(scalar), Ty::Scalar(scalar2)) => scalar == scalar2, 753 }
754 (TyKind::Str, TyKind::Str) | (TyKind::Never, TyKind::Never) => true,
755 (TyKind::Scalar(scalar), TyKind::Scalar(scalar2)) => scalar == scalar2,
711 _ => false, 756 _ => false,
712 } 757 }
713 } 758 }
714 759
715 /// If this is a `dyn Trait` type, this returns the `Trait` part. 760 /// If this is a `dyn Trait` type, this returns the `Trait` part.
716 pub fn dyn_trait_ref(&self) -> Option<&TraitRef> { 761 pub fn dyn_trait_ref(&self) -> Option<&TraitRef> {
717 match self { 762 match self.interned(&Interner) {
718 Ty::Dyn(bounds) => bounds.get(0).and_then(|b| match b { 763 TyKind::Dyn(bounds) => bounds.get(0).and_then(|b| match b {
719 GenericPredicate::Implemented(trait_ref) => Some(trait_ref), 764 GenericPredicate::Implemented(trait_ref) => Some(trait_ref),
720 _ => None, 765 _ => None,
721 }), 766 }),
@@ -729,28 +774,37 @@ impl Ty {
729 } 774 }
730 775
731 fn builtin_deref(&self) -> Option<Ty> { 776 fn builtin_deref(&self) -> Option<Ty> {
732 match self { 777 match self.interned(&Interner) {
733 Ty::Ref(.., parameters) => Some(Ty::clone(parameters.as_single())), 778 TyKind::Ref(.., parameters) => Some(Ty::clone(parameters.as_single())),
734 Ty::Raw(.., parameters) => Some(Ty::clone(parameters.as_single())), 779 TyKind::Raw(.., parameters) => Some(Ty::clone(parameters.as_single())),
735 _ => None, 780 _ => None,
736 } 781 }
737 } 782 }
738 783
739 pub fn as_fn_def(&self) -> Option<FunctionId> { 784 pub fn callable_def(&self, db: &dyn HirDatabase) -> Option<CallableDefId> {
740 match self { 785 match self.interned(&Interner) {
741 &Ty::FnDef(CallableDefId::FunctionId(func), ..) => Some(func), 786 &TyKind::FnDef(def, ..) => Some(db.lookup_intern_callable_def(def.into())),
742 _ => None, 787 _ => None,
743 } 788 }
744 } 789 }
745 790
791 pub fn as_fn_def(&self, db: &dyn HirDatabase) -> Option<FunctionId> {
792 if let Some(CallableDefId::FunctionId(func)) = self.callable_def(db) {
793 Some(func)
794 } else {
795 None
796 }
797 }
798
746 pub fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig> { 799 pub fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig> {
747 match self { 800 match self.interned(&Interner) {
748 Ty::Function(fn_ptr) => Some(CallableSig::from_fn_ptr(fn_ptr)), 801 TyKind::Function(fn_ptr) => Some(CallableSig::from_fn_ptr(fn_ptr)),
749 Ty::FnDef(def, parameters) => { 802 TyKind::FnDef(def, parameters) => {
750 let sig = db.callable_item_signature(*def); 803 let callable_def = db.lookup_intern_callable_def((*def).into());
804 let sig = db.callable_item_signature(callable_def);
751 Some(sig.subst(&parameters)) 805 Some(sig.subst(&parameters))
752 } 806 }
753 Ty::Closure(.., substs) => { 807 TyKind::Closure(.., substs) => {
754 let sig_param = &substs[0]; 808 let sig_param = &substs[0];
755 sig_param.callable_sig(db) 809 sig_param.callable_sig(db)
756 } 810 }
@@ -763,18 +817,18 @@ impl Ty {
763 /// `self` is `Option<_>` and the substs contain `u32`, we'll have 817 /// `self` is `Option<_>` and the substs contain `u32`, we'll have
764 /// `Option<u32>` afterwards.) 818 /// `Option<u32>` afterwards.)
765 pub fn apply_substs(mut self, new_substs: Substs) -> Ty { 819 pub fn apply_substs(mut self, new_substs: Substs) -> Ty {
766 match &mut self { 820 match &mut self.0 {
767 Ty::Adt(_, substs) 821 TyKind::Adt(_, substs)
768 | Ty::Slice(substs) 822 | TyKind::Slice(substs)
769 | Ty::Array(substs) 823 | TyKind::Array(substs)
770 | Ty::Raw(_, substs) 824 | TyKind::Raw(_, substs)
771 | Ty::Ref(_, substs) 825 | TyKind::Ref(_, substs)
772 | Ty::FnDef(_, substs) 826 | TyKind::FnDef(_, substs)
773 | Ty::Function(FnPointer { substs, .. }) 827 | TyKind::Function(FnPointer { substs, .. })
774 | Ty::Tuple(_, substs) 828 | TyKind::Tuple(_, substs)
775 | Ty::OpaqueType(_, substs) 829 | TyKind::OpaqueType(_, substs)
776 | Ty::AssociatedType(_, substs) 830 | TyKind::AssociatedType(_, substs)
777 | Ty::Closure(.., substs) => { 831 | TyKind::Closure(.., substs) => {
778 assert_eq!(substs.len(), new_substs.len()); 832 assert_eq!(substs.len(), new_substs.len());
779 *substs = new_substs; 833 *substs = new_substs;
780 } 834 }
@@ -786,44 +840,44 @@ impl Ty {
786 /// Returns the type parameters of this type if it has some (i.e. is an ADT 840 /// Returns the type parameters of this type if it has some (i.e. is an ADT
787 /// or function); so if `self` is `Option<u32>`, this returns the `u32`. 841 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
788 pub fn substs(&self) -> Option<&Substs> { 842 pub fn substs(&self) -> Option<&Substs> {
789 match self { 843 match self.interned(&Interner) {
790 Ty::Adt(_, substs) 844 TyKind::Adt(_, substs)
791 | Ty::Slice(substs) 845 | TyKind::Slice(substs)
792 | Ty::Array(substs) 846 | TyKind::Array(substs)
793 | Ty::Raw(_, substs) 847 | TyKind::Raw(_, substs)
794 | Ty::Ref(_, substs) 848 | TyKind::Ref(_, substs)
795 | Ty::FnDef(_, substs) 849 | TyKind::FnDef(_, substs)
796 | Ty::Function(FnPointer { substs, .. }) 850 | TyKind::Function(FnPointer { substs, .. })
797 | Ty::Tuple(_, substs) 851 | TyKind::Tuple(_, substs)
798 | Ty::OpaqueType(_, substs) 852 | TyKind::OpaqueType(_, substs)
799 | Ty::AssociatedType(_, substs) 853 | TyKind::AssociatedType(_, substs)
800 | Ty::Closure(.., substs) => Some(substs), 854 | TyKind::Closure(.., substs) => Some(substs),
801 _ => None, 855 _ => None,
802 } 856 }
803 } 857 }
804 858
805 pub fn substs_mut(&mut self) -> Option<&mut Substs> { 859 pub fn substs_mut(&mut self) -> Option<&mut Substs> {
806 match self { 860 match &mut self.0 {
807 Ty::Adt(_, substs) 861 TyKind::Adt(_, substs)
808 | Ty::Slice(substs) 862 | TyKind::Slice(substs)
809 | Ty::Array(substs) 863 | TyKind::Array(substs)
810 | Ty::Raw(_, substs) 864 | TyKind::Raw(_, substs)
811 | Ty::Ref(_, substs) 865 | TyKind::Ref(_, substs)
812 | Ty::FnDef(_, substs) 866 | TyKind::FnDef(_, substs)
813 | Ty::Function(FnPointer { substs, .. }) 867 | TyKind::Function(FnPointer { substs, .. })
814 | Ty::Tuple(_, substs) 868 | TyKind::Tuple(_, substs)
815 | Ty::OpaqueType(_, substs) 869 | TyKind::OpaqueType(_, substs)
816 | Ty::AssociatedType(_, substs) 870 | TyKind::AssociatedType(_, substs)
817 | Ty::Closure(.., substs) => Some(substs), 871 | TyKind::Closure(.., substs) => Some(substs),
818 _ => None, 872 _ => None,
819 } 873 }
820 } 874 }
821 875
822 pub fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<GenericPredicate>> { 876 pub fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<GenericPredicate>> {
823 match self { 877 match self.interned(&Interner) {
824 Ty::OpaqueType(opaque_ty_id, ..) => { 878 TyKind::OpaqueType(opaque_ty_id, ..) => {
825 match opaque_ty_id { 879 match db.lookup_intern_impl_trait_id((*opaque_ty_id).into()) {
826 OpaqueTyId::AsyncBlockTypeImplTrait(def, _expr) => { 880 ImplTraitId::AsyncBlockTypeImplTrait(def, _expr) => {
827 let krate = def.module(db.upcast()).krate(); 881 let krate = def.module(db.upcast()).krate();
828 if let Some(future_trait) = db 882 if let Some(future_trait) = db
829 .lang_item(krate, "future_trait".into()) 883 .lang_item(krate, "future_trait".into())
@@ -841,12 +895,13 @@ impl Ty {
841 None 895 None
842 } 896 }
843 } 897 }
844 OpaqueTyId::ReturnTypeImplTrait(..) => None, 898 ImplTraitId::ReturnTypeImplTrait(..) => None,
845 } 899 }
846 } 900 }
847 Ty::Alias(AliasTy::Opaque(opaque_ty)) => { 901 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
848 let predicates = match opaque_ty.opaque_ty_id { 902 let predicates = match db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into())
849 OpaqueTyId::ReturnTypeImplTrait(func, idx) => { 903 {
904 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
850 db.return_type_impl_traits(func).map(|it| { 905 db.return_type_impl_traits(func).map(|it| {
851 let data = (*it) 906 let data = (*it)
852 .as_ref() 907 .as_ref()
@@ -855,18 +910,19 @@ impl Ty {
855 }) 910 })
856 } 911 }
857 // It always has an parameter for Future::Output type. 912 // It always has an parameter for Future::Output type.
858 OpaqueTyId::AsyncBlockTypeImplTrait(..) => unreachable!(), 913 ImplTraitId::AsyncBlockTypeImplTrait(..) => unreachable!(),
859 }; 914 };
860 915
861 predicates.map(|it| it.value) 916 predicates.map(|it| it.value)
862 } 917 }
863 Ty::Placeholder(id) => { 918 TyKind::Placeholder(idx) => {
919 let id = from_placeholder_idx(db, *idx);
864 let generic_params = db.generic_params(id.parent); 920 let generic_params = db.generic_params(id.parent);
865 let param_data = &generic_params.types[id.local_id]; 921 let param_data = &generic_params.types[id.local_id];
866 match param_data.provenance { 922 match param_data.provenance {
867 hir_def::generics::TypeParamProvenance::ArgumentImplTrait => { 923 hir_def::generics::TypeParamProvenance::ArgumentImplTrait => {
868 let predicates = db 924 let predicates = db
869 .generic_predicates_for_param(*id) 925 .generic_predicates_for_param(id)
870 .into_iter() 926 .into_iter()
871 .map(|pred| pred.value.clone()) 927 .map(|pred| pred.value.clone())
872 .collect_vec(); 928 .collect_vec();
@@ -881,15 +937,16 @@ impl Ty {
881 } 937 }
882 938
883 pub fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId> { 939 pub fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId> {
884 match self { 940 match self.interned(&Interner) {
885 Ty::AssociatedType(type_alias_id, ..) => { 941 TyKind::AssociatedType(id, ..) => {
886 match type_alias_id.lookup(db.upcast()).container { 942 match from_assoc_type_id(*id).lookup(db.upcast()).container {
887 AssocContainerId::TraitId(trait_id) => Some(trait_id), 943 AssocContainerId::TraitId(trait_id) => Some(trait_id),
888 _ => None, 944 _ => None,
889 } 945 }
890 } 946 }
891 Ty::Alias(AliasTy::Projection(projection_ty)) => { 947 TyKind::Alias(AliasTy::Projection(projection_ty)) => {
892 match projection_ty.associated_ty.lookup(db.upcast()).container { 948 match from_assoc_type_id(projection_ty.associated_ty).lookup(db.upcast()).container
949 {
893 AssocContainerId::TraitId(trait_id) => Some(trait_id), 950 AssocContainerId::TraitId(trait_id) => Some(trait_id),
894 _ => None, 951 _ => None,
895 } 952 }
@@ -908,13 +965,13 @@ pub trait TypeWalk {
908 } 965 }
909 /// Walk the type, counting entered binders. 966 /// Walk the type, counting entered binders.
910 /// 967 ///
911 /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers 968 /// `TyKind::Bound` variables use DeBruijn indexing, which means that 0 refers
912 /// to the innermost binder, 1 to the next, etc.. So when we want to 969 /// to the innermost binder, 1 to the next, etc.. So when we want to
913 /// substitute a certain bound variable, we can't just walk the whole type 970 /// substitute a certain bound variable, we can't just walk the whole type
914 /// and blindly replace each instance of a certain index; when we 'enter' 971 /// and blindly replace each instance of a certain index; when we 'enter'
915 /// things that introduce new bound variables, we have to keep track of 972 /// things that introduce new bound variables, we have to keep track of
916 /// that. Currently, the only thing that introduces bound variables on our 973 /// that. Currently, the only thing that introduces bound variables on our
917 /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound 974 /// side are `TyKind::Dyn` and `TyKind::Opaque`, which each introduce a bound
918 /// variable for the self type. 975 /// variable for the self type.
919 fn walk_mut_binders( 976 fn walk_mut_binders(
920 &mut self, 977 &mut self,
@@ -932,7 +989,7 @@ pub trait TypeWalk {
932 { 989 {
933 self.walk_mut_binders( 990 self.walk_mut_binders(
934 &mut |ty_mut, binders| { 991 &mut |ty_mut, binders| {
935 let ty = mem::replace(ty_mut, Ty::Unknown); 992 let ty = mem::replace(ty_mut, Ty(TyKind::Unknown));
936 *ty_mut = f(ty, binders); 993 *ty_mut = f(ty, binders);
937 }, 994 },
938 binders, 995 binders,
@@ -945,13 +1002,13 @@ pub trait TypeWalk {
945 Self: Sized, 1002 Self: Sized,
946 { 1003 {
947 self.walk_mut(&mut |ty_mut| { 1004 self.walk_mut(&mut |ty_mut| {
948 let ty = mem::replace(ty_mut, Ty::Unknown); 1005 let ty = mem::replace(ty_mut, Ty(TyKind::Unknown));
949 *ty_mut = f(ty); 1006 *ty_mut = f(ty);
950 }); 1007 });
951 self 1008 self
952 } 1009 }
953 1010
954 /// Substitutes `Ty::Bound` vars with the given substitution. 1011 /// Substitutes `TyKind::Bound` vars with the given substitution.
955 fn subst_bound_vars(self, substs: &Substs) -> Self 1012 fn subst_bound_vars(self, substs: &Substs) -> Self
956 where 1013 where
957 Self: Sized, 1014 Self: Sized,
@@ -959,14 +1016,14 @@ pub trait TypeWalk {
959 self.subst_bound_vars_at_depth(substs, DebruijnIndex::INNERMOST) 1016 self.subst_bound_vars_at_depth(substs, DebruijnIndex::INNERMOST)
960 } 1017 }
961 1018
962 /// Substitutes `Ty::Bound` vars with the given substitution. 1019 /// Substitutes `TyKind::Bound` vars with the given substitution.
963 fn subst_bound_vars_at_depth(mut self, substs: &Substs, depth: DebruijnIndex) -> Self 1020 fn subst_bound_vars_at_depth(mut self, substs: &Substs, depth: DebruijnIndex) -> Self
964 where 1021 where
965 Self: Sized, 1022 Self: Sized,
966 { 1023 {
967 self.walk_mut_binders( 1024 self.walk_mut_binders(
968 &mut |ty, binders| { 1025 &mut |ty, binders| {
969 if let &mut Ty::BoundVar(bound) = ty { 1026 if let &mut TyKind::BoundVar(bound) = &mut ty.0 {
970 if bound.debruijn >= binders { 1027 if bound.debruijn >= binders {
971 *ty = substs.0[bound.index].clone().shift_bound_vars(binders); 1028 *ty = substs.0[bound.index].clone().shift_bound_vars(binders);
972 } 1029 }
@@ -977,17 +1034,17 @@ pub trait TypeWalk {
977 self 1034 self
978 } 1035 }
979 1036
980 /// Shifts up debruijn indices of `Ty::Bound` vars by `n`. 1037 /// Shifts up debruijn indices of `TyKind::Bound` vars by `n`.
981 fn shift_bound_vars(self, n: DebruijnIndex) -> Self 1038 fn shift_bound_vars(self, n: DebruijnIndex) -> Self
982 where 1039 where
983 Self: Sized, 1040 Self: Sized,
984 { 1041 {
985 self.fold_binders( 1042 self.fold_binders(
986 &mut |ty, binders| match ty { 1043 &mut |ty, binders| match &ty.0 {
987 Ty::BoundVar(bound) if bound.debruijn >= binders => { 1044 TyKind::BoundVar(bound) if bound.debruijn >= binders => {
988 Ty::BoundVar(bound.shifted_in_from(n)) 1045 TyKind::BoundVar(bound.shifted_in_from(n)).intern(&Interner)
989 } 1046 }
990 ty => ty, 1047 _ => ty,
991 }, 1048 },
992 DebruijnIndex::INNERMOST, 1049 DebruijnIndex::INNERMOST,
993 ) 1050 )
@@ -996,18 +1053,18 @@ pub trait TypeWalk {
996 1053
997impl TypeWalk for Ty { 1054impl TypeWalk for Ty {
998 fn walk(&self, f: &mut impl FnMut(&Ty)) { 1055 fn walk(&self, f: &mut impl FnMut(&Ty)) {
999 match self { 1056 match self.interned(&Interner) {
1000 Ty::Alias(AliasTy::Projection(p_ty)) => { 1057 TyKind::Alias(AliasTy::Projection(p_ty)) => {
1001 for t in p_ty.parameters.iter() { 1058 for t in p_ty.parameters.iter() {
1002 t.walk(f); 1059 t.walk(f);
1003 } 1060 }
1004 } 1061 }
1005 Ty::Alias(AliasTy::Opaque(o_ty)) => { 1062 TyKind::Alias(AliasTy::Opaque(o_ty)) => {
1006 for t in o_ty.parameters.iter() { 1063 for t in o_ty.parameters.iter() {
1007 t.walk(f); 1064 t.walk(f);
1008 } 1065 }
1009 } 1066 }
1010 Ty::Dyn(predicates) => { 1067 TyKind::Dyn(predicates) => {
1011 for p in predicates.iter() { 1068 for p in predicates.iter() {
1012 p.walk(f); 1069 p.walk(f);
1013 } 1070 }
@@ -1028,16 +1085,16 @@ impl TypeWalk for Ty {
1028 f: &mut impl FnMut(&mut Ty, DebruijnIndex), 1085 f: &mut impl FnMut(&mut Ty, DebruijnIndex),
1029 binders: DebruijnIndex, 1086 binders: DebruijnIndex,
1030 ) { 1087 ) {
1031 match self { 1088 match &mut self.0 {
1032 Ty::Alias(AliasTy::Projection(p_ty)) => { 1089 TyKind::Alias(AliasTy::Projection(p_ty)) => {
1033 p_ty.parameters.walk_mut_binders(f, binders); 1090 p_ty.parameters.walk_mut_binders(f, binders);
1034 } 1091 }
1035 Ty::Dyn(predicates) => { 1092 TyKind::Dyn(predicates) => {
1036 for p in make_mut_slice(predicates) { 1093 for p in make_mut_slice(predicates) {
1037 p.walk_mut_binders(f, binders.shifted_in()); 1094 p.walk_mut_binders(f, binders.shifted_in());
1038 } 1095 }
1039 } 1096 }
1040 Ty::Alias(AliasTy::Opaque(o_ty)) => { 1097 TyKind::Alias(AliasTy::Opaque(o_ty)) => {
1041 o_ty.parameters.walk_mut_binders(f, binders); 1098 o_ty.parameters.walk_mut_binders(f, binders);
1042 } 1099 }
1043 _ => { 1100 _ => {
@@ -1068,7 +1125,7 @@ impl<T: TypeWalk> TypeWalk for Vec<T> {
1068} 1125}
1069 1126
1070#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] 1127#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1071pub enum OpaqueTyId { 1128pub enum ImplTraitId {
1072 ReturnTypeImplTrait(hir_def::FunctionId, u16), 1129 ReturnTypeImplTrait(hir_def::FunctionId, u16),
1073 AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId), 1130 AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
1074} 1131}
@@ -1082,3 +1139,33 @@ pub struct ReturnTypeImplTraits {
1082pub(crate) struct ReturnTypeImplTrait { 1139pub(crate) struct ReturnTypeImplTrait {
1083 pub(crate) bounds: Binders<Vec<GenericPredicate>>, 1140 pub(crate) bounds: Binders<Vec<GenericPredicate>>,
1084} 1141}
1142
1143pub fn to_foreign_def_id(id: TypeAliasId) -> ForeignDefId {
1144 chalk_ir::ForeignDefId(salsa::InternKey::as_intern_id(&id))
1145}
1146
1147pub fn from_foreign_def_id(id: ForeignDefId) -> TypeAliasId {
1148 salsa::InternKey::from_intern_id(id.0)
1149}
1150
1151pub fn to_assoc_type_id(id: TypeAliasId) -> AssocTypeId {
1152 chalk_ir::AssocTypeId(salsa::InternKey::as_intern_id(&id))
1153}
1154
1155pub fn from_assoc_type_id(id: AssocTypeId) -> TypeAliasId {
1156 salsa::InternKey::from_intern_id(id.0)
1157}
1158
1159pub fn from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> TypeParamId {
1160 assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
1161 let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
1162 db.lookup_intern_type_param_id(interned_id)
1163}
1164
1165pub fn to_placeholder_idx(db: &dyn HirDatabase, id: TypeParamId) -> PlaceholderIndex {
1166 let interned_id = db.intern_type_param_id(id);
1167 PlaceholderIndex {
1168 ui: chalk_ir::UniverseIndex::ROOT,
1169 idx: salsa::InternKey::as_intern_id(&interned_id).as_usize(),
1170 }
1171}
diff --git a/crates/hir_ty/src/lower.rs b/crates/hir_ty/src/lower.rs
index 5fa83567b..c32dca9d7 100644
--- a/crates/hir_ty/src/lower.rs
+++ b/crates/hir_ty/src/lower.rs
@@ -8,7 +8,7 @@
8use std::{iter, sync::Arc}; 8use std::{iter, sync::Arc};
9 9
10use base_db::CrateId; 10use base_db::CrateId;
11use chalk_ir::Mutability; 11use chalk_ir::{cast::Cast, Mutability};
12use hir_def::{ 12use hir_def::{
13 adt::StructKind, 13 adt::StructKind,
14 builtin_type::BuiltinType, 14 builtin_type::BuiltinType,
@@ -27,13 +27,15 @@ use stdx::impl_from;
27 27
28use crate::{ 28use crate::{
29 db::HirDatabase, 29 db::HirDatabase,
30 to_assoc_type_id, to_placeholder_idx,
31 traits::chalk::{Interner, ToChalk},
30 utils::{ 32 utils::{
31 all_super_trait_refs, associated_type_by_name_including_super_traits, generics, 33 all_super_trait_refs, associated_type_by_name_including_super_traits, generics,
32 make_mut_slice, variant_data, 34 make_mut_slice, variant_data,
33 }, 35 },
34 AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, FnPointer, FnSig, GenericPredicate, 36 AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, FnPointer, FnSig, GenericPredicate,
35 OpaqueTy, OpaqueTyId, PolyFnSig, ProjectionPredicate, ProjectionTy, ReturnTypeImplTrait, 37 ImplTraitId, OpaqueTy, PolyFnSig, ProjectionPredicate, ProjectionTy, ReturnTypeImplTrait,
36 ReturnTypeImplTraits, Substs, TraitEnvironment, TraitRef, Ty, TypeWalk, 38 ReturnTypeImplTraits, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeWalk,
37}; 39};
38 40
39#[derive(Debug)] 41#[derive(Debug)]
@@ -138,69 +140,71 @@ pub enum TypeParamLoweringMode {
138 Variable, 140 Variable,
139} 141}
140 142
141impl Ty { 143impl<'a> TyLoweringContext<'a> {
142 pub fn from_hir(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> Self { 144 pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty {
143 Ty::from_hir_ext(ctx, type_ref).0 145 self.lower_ty_ext(type_ref).0
144 } 146 }
145 pub fn from_hir_ext(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> (Self, Option<TypeNs>) { 147
148 fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
146 let mut res = None; 149 let mut res = None;
147 let ty = match type_ref { 150 let ty = match type_ref {
148 TypeRef::Never => Ty::Never, 151 TypeRef::Never => TyKind::Never.intern(&Interner),
149 TypeRef::Tuple(inner) => { 152 TypeRef::Tuple(inner) => {
150 let inner_tys: Arc<[Ty]> = inner.iter().map(|tr| Ty::from_hir(ctx, tr)).collect(); 153 let inner_tys: Arc<[Ty]> = inner.iter().map(|tr| self.lower_ty(tr)).collect();
151 Ty::Tuple(inner_tys.len(), Substs(inner_tys)) 154 TyKind::Tuple(inner_tys.len(), Substs(inner_tys)).intern(&Interner)
152 } 155 }
153 TypeRef::Path(path) => { 156 TypeRef::Path(path) => {
154 let (ty, res_) = Ty::from_hir_path(ctx, path); 157 let (ty, res_) = self.lower_path(path);
155 res = res_; 158 res = res_;
156 ty 159 ty
157 } 160 }
158 TypeRef::RawPtr(inner, mutability) => { 161 TypeRef::RawPtr(inner, mutability) => {
159 let inner_ty = Ty::from_hir(ctx, inner); 162 let inner_ty = self.lower_ty(inner);
160 Ty::Raw(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty)) 163 TyKind::Raw(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty))
164 .intern(&Interner)
161 } 165 }
162 TypeRef::Array(inner) => { 166 TypeRef::Array(inner) => {
163 let inner_ty = Ty::from_hir(ctx, inner); 167 let inner_ty = self.lower_ty(inner);
164 Ty::Array(Substs::single(inner_ty)) 168 TyKind::Array(Substs::single(inner_ty)).intern(&Interner)
165 } 169 }
166 TypeRef::Slice(inner) => { 170 TypeRef::Slice(inner) => {
167 let inner_ty = Ty::from_hir(ctx, inner); 171 let inner_ty = self.lower_ty(inner);
168 Ty::Slice(Substs::single(inner_ty)) 172 TyKind::Slice(Substs::single(inner_ty)).intern(&Interner)
169 } 173 }
170 TypeRef::Reference(inner, _, mutability) => { 174 TypeRef::Reference(inner, _, mutability) => {
171 let inner_ty = Ty::from_hir(ctx, inner); 175 let inner_ty = self.lower_ty(inner);
172 Ty::Ref(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty)) 176 TyKind::Ref(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty))
177 .intern(&Interner)
173 } 178 }
174 TypeRef::Placeholder => Ty::Unknown, 179 TypeRef::Placeholder => TyKind::Unknown.intern(&Interner),
175 TypeRef::Fn(params, is_varargs) => { 180 TypeRef::Fn(params, is_varargs) => {
176 let substs = Substs(params.iter().map(|tr| Ty::from_hir(ctx, tr)).collect()); 181 let substs = Substs(params.iter().map(|tr| self.lower_ty(tr)).collect());
177 Ty::Function(FnPointer { 182 TyKind::Function(FnPointer {
178 num_args: substs.len() - 1, 183 num_args: substs.len() - 1,
179 sig: FnSig { variadic: *is_varargs }, 184 sig: FnSig { variadic: *is_varargs },
180 substs, 185 substs,
181 }) 186 })
187 .intern(&Interner)
182 } 188 }
183 TypeRef::DynTrait(bounds) => { 189 TypeRef::DynTrait(bounds) => {
184 let self_ty = Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)); 190 let self_ty =
185 let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| { 191 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
186 bounds 192 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
187 .iter() 193 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
188 .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
189 .collect()
190 }); 194 });
191 Ty::Dyn(predicates) 195 TyKind::Dyn(predicates).intern(&Interner)
192 } 196 }
193 TypeRef::ImplTrait(bounds) => { 197 TypeRef::ImplTrait(bounds) => {
194 match ctx.impl_trait_mode { 198 match self.impl_trait_mode {
195 ImplTraitLoweringMode::Opaque => { 199 ImplTraitLoweringMode::Opaque => {
196 let idx = ctx.impl_trait_counter.get(); 200 let idx = self.impl_trait_counter.get();
197 ctx.impl_trait_counter.set(idx + 1); 201 self.impl_trait_counter.set(idx + 1);
198 202
199 assert!(idx as usize == ctx.opaque_type_data.borrow().len()); 203 assert!(idx as usize == self.opaque_type_data.borrow().len());
200 // this dance is to make sure the data is in the right 204 // this dance is to make sure the data is in the right
201 // place even if we encounter more opaque types while 205 // place even if we encounter more opaque types while
202 // lowering the bounds 206 // lowering the bounds
203 ctx.opaque_type_data 207 self.opaque_type_data
204 .borrow_mut() 208 .borrow_mut()
205 .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) }); 209 .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) });
206 // We don't want to lower the bounds inside the binders 210 // We don't want to lower the bounds inside the binders
@@ -212,65 +216,67 @@ impl Ty {
212 // other, but separately. So if the `T` refers to a type 216 // other, but separately. So if the `T` refers to a type
213 // parameter of the outer function, it's just one binder 217 // parameter of the outer function, it's just one binder
214 // away instead of two. 218 // away instead of two.
215 let actual_opaque_type_data = ctx 219 let actual_opaque_type_data = self
216 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| { 220 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
217 ReturnTypeImplTrait::from_hir(ctx, &bounds) 221 ctx.lower_impl_trait(&bounds)
218 }); 222 });
219 ctx.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data; 223 self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
220 224
221 let func = match ctx.resolver.generic_def() { 225 let func = match self.resolver.generic_def() {
222 Some(GenericDefId::FunctionId(f)) => f, 226 Some(GenericDefId::FunctionId(f)) => f,
223 _ => panic!("opaque impl trait lowering in non-function"), 227 _ => panic!("opaque impl trait lowering in non-function"),
224 }; 228 };
225 let impl_trait_id = OpaqueTyId::ReturnTypeImplTrait(func, idx); 229 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
226 let generics = generics(ctx.db.upcast(), func.into()); 230 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
227 let parameters = Substs::bound_vars(&generics, ctx.in_binders); 231 let generics = generics(self.db.upcast(), func.into());
228 Ty::Alias(AliasTy::Opaque(OpaqueTy { 232 let parameters = Substs::bound_vars(&generics, self.in_binders);
229 opaque_ty_id: impl_trait_id, 233 TyKind::Alias(AliasTy::Opaque(OpaqueTy { opaque_ty_id, parameters }))
230 parameters, 234 .intern(&Interner)
231 }))
232 } 235 }
233 ImplTraitLoweringMode::Param => { 236 ImplTraitLoweringMode::Param => {
234 let idx = ctx.impl_trait_counter.get(); 237 let idx = self.impl_trait_counter.get();
235 // FIXME we're probably doing something wrong here 238 // FIXME we're probably doing something wrong here
236 ctx.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16); 239 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
237 if let Some(def) = ctx.resolver.generic_def() { 240 if let Some(def) = self.resolver.generic_def() {
238 let generics = generics(ctx.db.upcast(), def); 241 let generics = generics(self.db.upcast(), def);
239 let param = generics 242 let param = generics
240 .iter() 243 .iter()
241 .filter(|(_, data)| { 244 .filter(|(_, data)| {
242 data.provenance == TypeParamProvenance::ArgumentImplTrait 245 data.provenance == TypeParamProvenance::ArgumentImplTrait
243 }) 246 })
244 .nth(idx as usize) 247 .nth(idx as usize)
245 .map_or(Ty::Unknown, |(id, _)| Ty::Placeholder(id)); 248 .map_or(TyKind::Unknown, |(id, _)| {
246 param 249 TyKind::Placeholder(to_placeholder_idx(self.db, id))
250 });
251 param.intern(&Interner)
247 } else { 252 } else {
248 Ty::Unknown 253 TyKind::Unknown.intern(&Interner)
249 } 254 }
250 } 255 }
251 ImplTraitLoweringMode::Variable => { 256 ImplTraitLoweringMode::Variable => {
252 let idx = ctx.impl_trait_counter.get(); 257 let idx = self.impl_trait_counter.get();
253 // FIXME we're probably doing something wrong here 258 // FIXME we're probably doing something wrong here
254 ctx.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16); 259 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
255 let (parent_params, self_params, list_params, _impl_trait_params) = 260 let (parent_params, self_params, list_params, _impl_trait_params) =
256 if let Some(def) = ctx.resolver.generic_def() { 261 if let Some(def) = self.resolver.generic_def() {
257 let generics = generics(ctx.db.upcast(), def); 262 let generics = generics(self.db.upcast(), def);
258 generics.provenance_split() 263 generics.provenance_split()
259 } else { 264 } else {
260 (0, 0, 0, 0) 265 (0, 0, 0, 0)
261 }; 266 };
262 Ty::BoundVar(BoundVar::new( 267 TyKind::BoundVar(BoundVar::new(
263 ctx.in_binders, 268 self.in_binders,
264 idx as usize + parent_params + self_params + list_params, 269 idx as usize + parent_params + self_params + list_params,
265 )) 270 ))
271 .intern(&Interner)
266 } 272 }
267 ImplTraitLoweringMode::Disallowed => { 273 ImplTraitLoweringMode::Disallowed => {
268 // FIXME: report error 274 // FIXME: report error
269 Ty::Unknown 275 TyKind::Unknown.intern(&Interner)
270 } 276 }
271 } 277 }
272 } 278 }
273 TypeRef::Error => Ty::Unknown, 279 TypeRef::Error => TyKind::Unknown.intern(&Interner),
274 }; 280 };
275 (ty, res) 281 (ty, res)
276 } 282 }
@@ -278,7 +284,7 @@ impl Ty {
278 /// This is only for `generic_predicates_for_param`, where we can't just 284 /// This is only for `generic_predicates_for_param`, where we can't just
279 /// lower the self types of the predicates since that could lead to cycles. 285 /// lower the self types of the predicates since that could lead to cycles.
280 /// So we just check here if the `type_ref` resolves to a generic param, and which. 286 /// So we just check here if the `type_ref` resolves to a generic param, and which.
281 fn from_hir_only_param(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> Option<TypeParamId> { 287 fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
282 let path = match type_ref { 288 let path = match type_ref {
283 TypeRef::Path(path) => path, 289 TypeRef::Path(path) => path,
284 _ => return None, 290 _ => return None,
@@ -290,7 +296,7 @@ impl Ty {
290 return None; 296 return None;
291 } 297 }
292 let resolution = 298 let resolution =
293 match ctx.resolver.resolve_path_in_type_ns(ctx.db.upcast(), path.mod_path()) { 299 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
294 Some((it, None)) => it, 300 Some((it, None)) => it,
295 _ => return None, 301 _ => return None,
296 }; 302 };
@@ -301,8 +307,8 @@ impl Ty {
301 } 307 }
302 } 308 }
303 309
304 pub(crate) fn from_type_relative_path( 310 pub(crate) fn lower_ty_relative_path(
305 ctx: &TyLoweringContext<'_>, 311 &self,
306 ty: Ty, 312 ty: Ty,
307 // We need the original resolution to lower `Self::AssocTy` correctly 313 // We need the original resolution to lower `Self::AssocTy` correctly
308 res: Option<TypeNs>, 314 res: Option<TypeNs>,
@@ -311,17 +317,17 @@ impl Ty {
311 if remaining_segments.len() == 1 { 317 if remaining_segments.len() == 1 {
312 // resolve unselected assoc types 318 // resolve unselected assoc types
313 let segment = remaining_segments.first().unwrap(); 319 let segment = remaining_segments.first().unwrap();
314 (Ty::select_associated_type(ctx, res, segment), None) 320 (self.select_associated_type(res, segment), None)
315 } else if remaining_segments.len() > 1 { 321 } else if remaining_segments.len() > 1 {
316 // FIXME report error (ambiguous associated type) 322 // FIXME report error (ambiguous associated type)
317 (Ty::Unknown, None) 323 (TyKind::Unknown.intern(&Interner), None)
318 } else { 324 } else {
319 (ty, res) 325 (ty, res)
320 } 326 }
321 } 327 }
322 328
323 pub(crate) fn from_partly_resolved_hir_path( 329 pub(crate) fn lower_partly_resolved_path(
324 ctx: &TyLoweringContext<'_>, 330 &self,
325 resolution: TypeNs, 331 resolution: TypeNs,
326 resolved_segment: PathSegment<'_>, 332 resolved_segment: PathSegment<'_>,
327 remaining_segments: PathSegments<'_>, 333 remaining_segments: PathSegments<'_>,
@@ -331,103 +337,109 @@ impl Ty {
331 TypeNs::TraitId(trait_) => { 337 TypeNs::TraitId(trait_) => {
332 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there 338 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
333 let self_ty = if remaining_segments.len() == 0 { 339 let self_ty = if remaining_segments.len() == 0 {
334 Some(Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))) 340 Some(
341 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
342 .intern(&Interner),
343 )
335 } else { 344 } else {
336 None 345 None
337 }; 346 };
338 let trait_ref = 347 let trait_ref =
339 TraitRef::from_resolved_path(ctx, trait_, resolved_segment, self_ty); 348 self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
340 let ty = if remaining_segments.len() == 1 { 349 let ty = if remaining_segments.len() == 1 {
341 let segment = remaining_segments.first().unwrap(); 350 let segment = remaining_segments.first().unwrap();
342 let found = associated_type_by_name_including_super_traits( 351 let found = associated_type_by_name_including_super_traits(
343 ctx.db, 352 self.db,
344 trait_ref, 353 trait_ref,
345 &segment.name, 354 &segment.name,
346 ); 355 );
347 match found { 356 match found {
348 Some((super_trait_ref, associated_ty)) => { 357 Some((super_trait_ref, associated_ty)) => {
349 // FIXME handle type parameters on the segment 358 // FIXME handle type parameters on the segment
350 Ty::Alias(AliasTy::Projection(ProjectionTy { 359 TyKind::Alias(AliasTy::Projection(ProjectionTy {
351 associated_ty, 360 associated_ty: to_assoc_type_id(associated_ty),
352 parameters: super_trait_ref.substs, 361 parameters: super_trait_ref.substs,
353 })) 362 }))
363 .intern(&Interner)
354 } 364 }
355 None => { 365 None => {
356 // FIXME: report error (associated type not found) 366 // FIXME: report error (associated type not found)
357 Ty::Unknown 367 TyKind::Unknown.intern(&Interner)
358 } 368 }
359 } 369 }
360 } else if remaining_segments.len() > 1 { 370 } else if remaining_segments.len() > 1 {
361 // FIXME report error (ambiguous associated type) 371 // FIXME report error (ambiguous associated type)
362 Ty::Unknown 372 TyKind::Unknown.intern(&Interner)
363 } else { 373 } else {
364 Ty::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)])) 374 TyKind::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)]))
375 .intern(&Interner)
365 }; 376 };
366 return (ty, None); 377 return (ty, None);
367 } 378 }
368 TypeNs::GenericParam(param_id) => { 379 TypeNs::GenericParam(param_id) => {
369 let generics = generics( 380 let generics = generics(
370 ctx.db.upcast(), 381 self.db.upcast(),
371 ctx.resolver.generic_def().expect("generics in scope"), 382 self.resolver.generic_def().expect("generics in scope"),
372 ); 383 );
373 match ctx.type_param_mode { 384 match self.type_param_mode {
374 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id), 385 TypeParamLoweringMode::Placeholder => {
386 TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
387 }
375 TypeParamLoweringMode::Variable => { 388 TypeParamLoweringMode::Variable => {
376 let idx = generics.param_idx(param_id).expect("matching generics"); 389 let idx = generics.param_idx(param_id).expect("matching generics");
377 Ty::BoundVar(BoundVar::new(ctx.in_binders, idx)) 390 TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
378 } 391 }
379 } 392 }
393 .intern(&Interner)
380 } 394 }
381 TypeNs::SelfType(impl_id) => { 395 TypeNs::SelfType(impl_id) => {
382 let generics = generics(ctx.db.upcast(), impl_id.into()); 396 let generics = generics(self.db.upcast(), impl_id.into());
383 let substs = match ctx.type_param_mode { 397 let substs = match self.type_param_mode {
384 TypeParamLoweringMode::Placeholder => { 398 TypeParamLoweringMode::Placeholder => {
385 Substs::type_params_for_generics(&generics) 399 Substs::type_params_for_generics(self.db, &generics)
386 } 400 }
387 TypeParamLoweringMode::Variable => { 401 TypeParamLoweringMode::Variable => {
388 Substs::bound_vars(&generics, ctx.in_binders) 402 Substs::bound_vars(&generics, self.in_binders)
389 } 403 }
390 }; 404 };
391 ctx.db.impl_self_ty(impl_id).subst(&substs) 405 self.db.impl_self_ty(impl_id).subst(&substs)
392 } 406 }
393 TypeNs::AdtSelfType(adt) => { 407 TypeNs::AdtSelfType(adt) => {
394 let generics = generics(ctx.db.upcast(), adt.into()); 408 let generics = generics(self.db.upcast(), adt.into());
395 let substs = match ctx.type_param_mode { 409 let substs = match self.type_param_mode {
396 TypeParamLoweringMode::Placeholder => { 410 TypeParamLoweringMode::Placeholder => {
397 Substs::type_params_for_generics(&generics) 411 Substs::type_params_for_generics(self.db, &generics)
398 } 412 }
399 TypeParamLoweringMode::Variable => { 413 TypeParamLoweringMode::Variable => {
400 Substs::bound_vars(&generics, ctx.in_binders) 414 Substs::bound_vars(&generics, self.in_binders)
401 } 415 }
402 }; 416 };
403 ctx.db.ty(adt.into()).subst(&substs) 417 self.db.ty(adt.into()).subst(&substs)
404 } 418 }
405 419
406 TypeNs::AdtId(it) => { 420 TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
407 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args)
408 }
409 TypeNs::BuiltinType(it) => { 421 TypeNs::BuiltinType(it) => {
410 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args) 422 self.lower_path_inner(resolved_segment, it.into(), infer_args)
411 } 423 }
412 TypeNs::TypeAliasId(it) => { 424 TypeNs::TypeAliasId(it) => {
413 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args) 425 self.lower_path_inner(resolved_segment, it.into(), infer_args)
414 } 426 }
415 // FIXME: report error 427 // FIXME: report error
416 TypeNs::EnumVariantId(_) => return (Ty::Unknown, None), 428 TypeNs::EnumVariantId(_) => return (TyKind::Unknown.intern(&Interner), None),
417 }; 429 };
418 Ty::from_type_relative_path(ctx, ty, Some(resolution), remaining_segments) 430 self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
419 } 431 }
420 432
421 pub(crate) fn from_hir_path(ctx: &TyLoweringContext<'_>, path: &Path) -> (Ty, Option<TypeNs>) { 433 pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
422 // Resolve the path (in type namespace) 434 // Resolve the path (in type namespace)
423 if let Some(type_ref) = path.type_anchor() { 435 if let Some(type_ref) = path.type_anchor() {
424 let (ty, res) = Ty::from_hir_ext(ctx, &type_ref); 436 let (ty, res) = self.lower_ty_ext(&type_ref);
425 return Ty::from_type_relative_path(ctx, ty, res, path.segments()); 437 return self.lower_ty_relative_path(ty, res, path.segments());
426 } 438 }
427 let (resolution, remaining_index) = 439 let (resolution, remaining_index) =
428 match ctx.resolver.resolve_path_in_type_ns(ctx.db.upcast(), path.mod_path()) { 440 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
429 Some(it) => it, 441 Some(it) => it,
430 None => return (Ty::Unknown, None), 442 None => return (TyKind::Unknown.intern(&Interner), None),
431 }; 443 };
432 let (resolved_segment, remaining_segments) = match remaining_index { 444 let (resolved_segment, remaining_segments) = match remaining_index {
433 None => ( 445 None => (
@@ -436,31 +448,23 @@ impl Ty {
436 ), 448 ),
437 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)), 449 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
438 }; 450 };
439 Ty::from_partly_resolved_hir_path( 451 self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
440 ctx,
441 resolution,
442 resolved_segment,
443 remaining_segments,
444 false,
445 )
446 } 452 }
447 453
448 fn select_associated_type( 454 fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
449 ctx: &TyLoweringContext<'_>,
450 res: Option<TypeNs>,
451 segment: PathSegment<'_>,
452 ) -> Ty {
453 if let Some(res) = res { 455 if let Some(res) = res {
454 let ty = 456 let ty = associated_type_shorthand_candidates(
455 associated_type_shorthand_candidates(ctx.db, res, move |name, t, associated_ty| { 457 self.db,
458 res,
459 move |name, t, associated_ty| {
456 if name == segment.name { 460 if name == segment.name {
457 let substs = match ctx.type_param_mode { 461 let substs = match self.type_param_mode {
458 TypeParamLoweringMode::Placeholder => { 462 TypeParamLoweringMode::Placeholder => {
459 // if we're lowering to placeholders, we have to put 463 // if we're lowering to placeholders, we have to put
460 // them in now 464 // them in now
461 let s = Substs::type_params( 465 let s = Substs::type_params(
462 ctx.db, 466 self.db,
463 ctx.resolver.generic_def().expect( 467 self.resolver.generic_def().expect(
464 "there should be generics if there's a generic param", 468 "there should be generics if there's a generic param",
465 ), 469 ),
466 ); 470 );
@@ -470,25 +474,29 @@ impl Ty {
470 }; 474 };
471 // We need to shift in the bound vars, since 475 // We need to shift in the bound vars, since
472 // associated_type_shorthand_candidates does not do that 476 // associated_type_shorthand_candidates does not do that
473 let substs = substs.shift_bound_vars(ctx.in_binders); 477 let substs = substs.shift_bound_vars(self.in_binders);
474 // FIXME handle type parameters on the segment 478 // FIXME handle type parameters on the segment
475 return Some(Ty::Alias(AliasTy::Projection(ProjectionTy { 479 return Some(
476 associated_ty, 480 TyKind::Alias(AliasTy::Projection(ProjectionTy {
477 parameters: substs, 481 associated_ty: to_assoc_type_id(associated_ty),
478 }))); 482 parameters: substs,
483 }))
484 .intern(&Interner),
485 );
479 } 486 }
480 487
481 None 488 None
482 }); 489 },
490 );
483 491
484 ty.unwrap_or(Ty::Unknown) 492 ty.unwrap_or(TyKind::Unknown.intern(&Interner))
485 } else { 493 } else {
486 Ty::Unknown 494 TyKind::Unknown.intern(&Interner)
487 } 495 }
488 } 496 }
489 497
490 fn from_hir_path_inner( 498 fn lower_path_inner(
491 ctx: &TyLoweringContext<'_>, 499 &self,
492 segment: PathSegment<'_>, 500 segment: PathSegment<'_>,
493 typeable: TyDefId, 501 typeable: TyDefId,
494 infer_args: bool, 502 infer_args: bool,
@@ -498,14 +506,14 @@ impl Ty {
498 TyDefId::AdtId(it) => Some(it.into()), 506 TyDefId::AdtId(it) => Some(it.into()),
499 TyDefId::TypeAliasId(it) => Some(it.into()), 507 TyDefId::TypeAliasId(it) => Some(it.into()),
500 }; 508 };
501 let substs = substs_from_path_segment(ctx, segment, generic_def, infer_args); 509 let substs = self.substs_from_path_segment(segment, generic_def, infer_args);
502 ctx.db.ty(typeable).subst(&substs) 510 self.db.ty(typeable).subst(&substs)
503 } 511 }
504 512
505 /// Collect generic arguments from a path into a `Substs`. See also 513 /// Collect generic arguments from a path into a `Substs`. See also
506 /// `create_substs_for_ast_path` and `def_to_ty` in rustc. 514 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
507 pub(super) fn substs_from_path( 515 pub(super) fn substs_from_path(
508 ctx: &TyLoweringContext<'_>, 516 &self,
509 path: &Path, 517 path: &Path,
510 // Note that we don't call `db.value_type(resolved)` here, 518 // Note that we don't call `db.value_type(resolved)` here,
511 // `ValueTyDefId` is just a convenient way to pass generics and 519 // `ValueTyDefId` is just a convenient way to pass generics and
@@ -535,169 +543,161 @@ impl Ty {
535 (segment, Some(var.parent.into())) 543 (segment, Some(var.parent.into()))
536 } 544 }
537 }; 545 };
538 substs_from_path_segment(ctx, segment, generic_def, infer_args) 546 self.substs_from_path_segment(segment, generic_def, infer_args)
539 } 547 }
540}
541 548
542fn substs_from_path_segment( 549 fn substs_from_path_segment(
543 ctx: &TyLoweringContext<'_>, 550 &self,
544 segment: PathSegment<'_>, 551 segment: PathSegment<'_>,
545 def_generic: Option<GenericDefId>, 552 def_generic: Option<GenericDefId>,
546 infer_args: bool, 553 infer_args: bool,
547) -> Substs { 554 ) -> Substs {
548 let mut substs = Vec::new(); 555 let mut substs = Vec::new();
549 let def_generics = def_generic.map(|def| generics(ctx.db.upcast(), def)); 556 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
550 557
551 let (parent_params, self_params, type_params, impl_trait_params) = 558 let (parent_params, self_params, type_params, impl_trait_params) =
552 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split()); 559 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
553 let total_len = parent_params + self_params + type_params + impl_trait_params; 560 let total_len = parent_params + self_params + type_params + impl_trait_params;
554 561
555 substs.extend(iter::repeat(Ty::Unknown).take(parent_params)); 562 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(parent_params));
556 563
557 let mut had_explicit_type_args = false; 564 let mut had_explicit_type_args = false;
558 565
559 if let Some(generic_args) = &segment.args_and_bindings { 566 if let Some(generic_args) = &segment.args_and_bindings {
560 if !generic_args.has_self_type { 567 if !generic_args.has_self_type {
561 substs.extend(iter::repeat(Ty::Unknown).take(self_params)); 568 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(self_params));
562 } 569 }
563 let expected_num = 570 let expected_num =
564 if generic_args.has_self_type { self_params + type_params } else { type_params }; 571 if generic_args.has_self_type { self_params + type_params } else { type_params };
565 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 }; 572 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
566 // if args are provided, it should be all of them, but we can't rely on that 573 // if args are provided, it should be all of them, but we can't rely on that
567 for arg in generic_args 574 for arg in generic_args
568 .args 575 .args
569 .iter() 576 .iter()
570 .filter(|arg| matches!(arg, GenericArg::Type(_))) 577 .filter(|arg| matches!(arg, GenericArg::Type(_)))
571 .skip(skip) 578 .skip(skip)
572 .take(expected_num) 579 .take(expected_num)
573 { 580 {
574 match arg { 581 match arg {
575 GenericArg::Type(type_ref) => { 582 GenericArg::Type(type_ref) => {
576 had_explicit_type_args = true; 583 had_explicit_type_args = true;
577 let ty = Ty::from_hir(ctx, type_ref); 584 let ty = self.lower_ty(type_ref);
578 substs.push(ty); 585 substs.push(ty);
586 }
587 GenericArg::Lifetime(_) => {}
579 } 588 }
580 GenericArg::Lifetime(_) => {}
581 } 589 }
582 } 590 }
583 }
584 591
585 // handle defaults. In expression or pattern path segments without 592 // handle defaults. In expression or pattern path segments without
586 // explicitly specified type arguments, missing type arguments are inferred 593 // explicitly specified type arguments, missing type arguments are inferred
587 // (i.e. defaults aren't used). 594 // (i.e. defaults aren't used).
588 if !infer_args || had_explicit_type_args { 595 if !infer_args || had_explicit_type_args {
589 if let Some(def_generic) = def_generic { 596 if let Some(def_generic) = def_generic {
590 let defaults = ctx.db.generic_defaults(def_generic); 597 let defaults = self.db.generic_defaults(def_generic);
591 assert_eq!(total_len, defaults.len()); 598 assert_eq!(total_len, defaults.len());
592 599
593 for default_ty in defaults.iter().skip(substs.len()) { 600 for default_ty in defaults.iter().skip(substs.len()) {
594 // each default can depend on the previous parameters 601 // each default can depend on the previous parameters
595 let substs_so_far = Substs(substs.clone().into()); 602 let substs_so_far = Substs(substs.clone().into());
596 substs.push(default_ty.clone().subst(&substs_so_far)); 603 substs.push(default_ty.clone().subst(&substs_so_far));
604 }
597 } 605 }
598 } 606 }
599 }
600 607
601 // add placeholders for args that were not provided 608 // add placeholders for args that were not provided
602 // FIXME: emit diagnostics in contexts where this is not allowed 609 // FIXME: emit diagnostics in contexts where this is not allowed
603 for _ in substs.len()..total_len { 610 for _ in substs.len()..total_len {
604 substs.push(Ty::Unknown); 611 substs.push(TyKind::Unknown.intern(&Interner));
605 } 612 }
606 assert_eq!(substs.len(), total_len); 613 assert_eq!(substs.len(), total_len);
607 614
608 Substs(substs.into()) 615 Substs(substs.into())
609} 616 }
610 617
611impl TraitRef { 618 fn lower_trait_ref_from_path(
612 fn from_path( 619 &self,
613 ctx: &TyLoweringContext<'_>,
614 path: &Path, 620 path: &Path,
615 explicit_self_ty: Option<Ty>, 621 explicit_self_ty: Option<Ty>,
616 ) -> Option<Self> { 622 ) -> Option<TraitRef> {
617 let resolved = 623 let resolved =
618 match ctx.resolver.resolve_path_in_type_ns_fully(ctx.db.upcast(), path.mod_path())? { 624 match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
619 TypeNs::TraitId(tr) => tr, 625 TypeNs::TraitId(tr) => tr,
620 _ => return None, 626 _ => return None,
621 }; 627 };
622 let segment = path.segments().last().expect("path should have at least one segment"); 628 let segment = path.segments().last().expect("path should have at least one segment");
623 Some(TraitRef::from_resolved_path(ctx, resolved, segment, explicit_self_ty)) 629 Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
624 } 630 }
625 631
626 pub(crate) fn from_resolved_path( 632 pub(crate) fn lower_trait_ref_from_resolved_path(
627 ctx: &TyLoweringContext<'_>, 633 &self,
628 resolved: TraitId, 634 resolved: TraitId,
629 segment: PathSegment<'_>, 635 segment: PathSegment<'_>,
630 explicit_self_ty: Option<Ty>, 636 explicit_self_ty: Option<Ty>,
631 ) -> Self { 637 ) -> TraitRef {
632 let mut substs = TraitRef::substs_from_path(ctx, segment, resolved); 638 let mut substs = self.trait_ref_substs_from_path(segment, resolved);
633 if let Some(self_ty) = explicit_self_ty { 639 if let Some(self_ty) = explicit_self_ty {
634 make_mut_slice(&mut substs.0)[0] = self_ty; 640 make_mut_slice(&mut substs.0)[0] = self_ty;
635 } 641 }
636 TraitRef { trait_: resolved, substs } 642 TraitRef { trait_: resolved, substs }
637 } 643 }
638 644
639 fn from_hir( 645 fn lower_trait_ref(
640 ctx: &TyLoweringContext<'_>, 646 &self,
641 type_ref: &TypeRef, 647 type_ref: &TypeRef,
642 explicit_self_ty: Option<Ty>, 648 explicit_self_ty: Option<Ty>,
643 ) -> Option<Self> { 649 ) -> Option<TraitRef> {
644 let path = match type_ref { 650 let path = match type_ref {
645 TypeRef::Path(path) => path, 651 TypeRef::Path(path) => path,
646 _ => return None, 652 _ => return None,
647 }; 653 };
648 TraitRef::from_path(ctx, path, explicit_self_ty) 654 self.lower_trait_ref_from_path(path, explicit_self_ty)
649 } 655 }
650 656
651 fn substs_from_path( 657 fn trait_ref_substs_from_path(&self, segment: PathSegment<'_>, resolved: TraitId) -> Substs {
652 ctx: &TyLoweringContext<'_>, 658 self.substs_from_path_segment(segment, Some(resolved.into()), false)
653 segment: PathSegment<'_>,
654 resolved: TraitId,
655 ) -> Substs {
656 substs_from_path_segment(ctx, segment, Some(resolved.into()), false)
657 } 659 }
658}
659 660
660impl GenericPredicate { 661 pub(crate) fn lower_where_predicate(
661 pub(crate) fn from_where_predicate<'a>( 662 &'a self,
662 ctx: &'a TyLoweringContext<'a>,
663 where_predicate: &'a WherePredicate, 663 where_predicate: &'a WherePredicate,
664 ) -> impl Iterator<Item = GenericPredicate> + 'a { 664 ) -> impl Iterator<Item = GenericPredicate> + 'a {
665 match where_predicate { 665 match where_predicate {
666 WherePredicate::ForLifetime { target, bound, .. } 666 WherePredicate::ForLifetime { target, bound, .. }
667 | WherePredicate::TypeBound { target, bound } => { 667 | WherePredicate::TypeBound { target, bound } => {
668 let self_ty = match target { 668 let self_ty = match target {
669 WherePredicateTypeTarget::TypeRef(type_ref) => Ty::from_hir(ctx, type_ref), 669 WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
670 WherePredicateTypeTarget::TypeParam(param_id) => { 670 WherePredicateTypeTarget::TypeParam(param_id) => {
671 let generic_def = ctx.resolver.generic_def().expect("generics in scope"); 671 let generic_def = self.resolver.generic_def().expect("generics in scope");
672 let generics = generics(ctx.db.upcast(), generic_def); 672 let generics = generics(self.db.upcast(), generic_def);
673 let param_id = 673 let param_id =
674 hir_def::TypeParamId { parent: generic_def, local_id: *param_id }; 674 hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
675 match ctx.type_param_mode { 675 let placeholder = to_placeholder_idx(self.db, param_id);
676 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id), 676 match self.type_param_mode {
677 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
677 TypeParamLoweringMode::Variable => { 678 TypeParamLoweringMode::Variable => {
678 let idx = generics.param_idx(param_id).expect("matching generics"); 679 let idx = generics.param_idx(param_id).expect("matching generics");
679 Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx)) 680 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
680 } 681 }
681 } 682 }
683 .intern(&Interner)
682 } 684 }
683 }; 685 };
684 GenericPredicate::from_type_bound(ctx, bound, self_ty) 686 self.lower_type_bound(bound, self_ty).collect::<Vec<_>>().into_iter()
685 .collect::<Vec<_>>()
686 .into_iter()
687 } 687 }
688 WherePredicate::Lifetime { .. } => vec![].into_iter(), 688 WherePredicate::Lifetime { .. } => vec![].into_iter(),
689 } 689 }
690 } 690 }
691 691
692 pub(crate) fn from_type_bound<'a>( 692 pub(crate) fn lower_type_bound(
693 ctx: &'a TyLoweringContext<'a>, 693 &'a self,
694 bound: &'a TypeBound, 694 bound: &'a TypeBound,
695 self_ty: Ty, 695 self_ty: Ty,
696 ) -> impl Iterator<Item = GenericPredicate> + 'a { 696 ) -> impl Iterator<Item = GenericPredicate> + 'a {
697 let mut bindings = None; 697 let mut bindings = None;
698 let trait_ref = match bound { 698 let trait_ref = match bound {
699 TypeBound::Path(path) => { 699 TypeBound::Path(path) => {
700 bindings = TraitRef::from_path(ctx, path, Some(self_ty)); 700 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
701 Some( 701 Some(
702 bindings.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented), 702 bindings.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented),
703 ) 703 )
@@ -708,64 +708,62 @@ impl GenericPredicate {
708 trait_ref.into_iter().chain( 708 trait_ref.into_iter().chain(
709 bindings 709 bindings
710 .into_iter() 710 .into_iter()
711 .flat_map(move |tr| assoc_type_bindings_from_type_bound(ctx, bound, tr)), 711 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
712 ) 712 )
713 } 713 }
714}
715 714
716fn assoc_type_bindings_from_type_bound<'a>( 715 fn assoc_type_bindings_from_type_bound(
717 ctx: &'a TyLoweringContext<'a>, 716 &'a self,
718 bound: &'a TypeBound, 717 bound: &'a TypeBound,
719 trait_ref: TraitRef, 718 trait_ref: TraitRef,
720) -> impl Iterator<Item = GenericPredicate> + 'a { 719 ) -> impl Iterator<Item = GenericPredicate> + 'a {
721 let last_segment = match bound { 720 let last_segment = match bound {
722 TypeBound::Path(path) => path.segments().last(), 721 TypeBound::Path(path) => path.segments().last(),
723 TypeBound::Error | TypeBound::Lifetime(_) => None, 722 TypeBound::Error | TypeBound::Lifetime(_) => None,
724 }; 723 };
725 last_segment 724 last_segment
726 .into_iter() 725 .into_iter()
727 .flat_map(|segment| segment.args_and_bindings.into_iter()) 726 .flat_map(|segment| segment.args_and_bindings.into_iter())
728 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) 727 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
729 .flat_map(move |binding| { 728 .flat_map(move |binding| {
730 let found = associated_type_by_name_including_super_traits( 729 let found = associated_type_by_name_including_super_traits(
731 ctx.db, 730 self.db,
732 trait_ref.clone(), 731 trait_ref.clone(),
733 &binding.name, 732 &binding.name,
734 ); 733 );
735 let (super_trait_ref, associated_ty) = match found { 734 let (super_trait_ref, associated_ty) = match found {
736 None => return SmallVec::<[GenericPredicate; 1]>::new(), 735 None => return SmallVec::<[GenericPredicate; 1]>::new(),
737 Some(t) => t, 736 Some(t) => t,
738 }; 737 };
739 let projection_ty = ProjectionTy { associated_ty, parameters: super_trait_ref.substs }; 738 let projection_ty = ProjectionTy {
740 let mut preds = SmallVec::with_capacity( 739 associated_ty: to_assoc_type_id(associated_ty),
741 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(), 740 parameters: super_trait_ref.substs,
742 ); 741 };
743 if let Some(type_ref) = &binding.type_ref { 742 let mut preds = SmallVec::with_capacity(
744 let ty = Ty::from_hir(ctx, type_ref); 743 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
745 let projection_predicate = 744 );
746 ProjectionPredicate { projection_ty: projection_ty.clone(), ty }; 745 if let Some(type_ref) = &binding.type_ref {
747 preds.push(GenericPredicate::Projection(projection_predicate)); 746 let ty = self.lower_ty(type_ref);
748 } 747 let projection_predicate =
749 for bound in &binding.bounds { 748 ProjectionPredicate { projection_ty: projection_ty.clone(), ty };
750 preds.extend(GenericPredicate::from_type_bound( 749 preds.push(GenericPredicate::Projection(projection_predicate));
751 ctx, 750 }
752 bound, 751 for bound in &binding.bounds {
753 Ty::Alias(AliasTy::Projection(projection_ty.clone())), 752 preds.extend(self.lower_type_bound(
754 )); 753 bound,
755 } 754 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
756 preds 755 ));
757 }) 756 }
758} 757 preds
758 })
759 }
759 760
760impl ReturnTypeImplTrait { 761 fn lower_impl_trait(&self, bounds: &[TypeBound]) -> ReturnTypeImplTrait {
761 fn from_hir(ctx: &TyLoweringContext, bounds: &[TypeBound]) -> Self {
762 cov_mark::hit!(lower_rpit); 762 cov_mark::hit!(lower_rpit);
763 let self_ty = Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)); 763 let self_ty =
764 let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| { 764 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
765 bounds 765 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
766 .iter() 766 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
767 .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
768 .collect()
769 }); 767 });
770 ReturnTypeImplTrait { bounds: Binders::new(1, predicates) } 768 ReturnTypeImplTrait { bounds: Binders::new(1, predicates) }
771 } 769 }
@@ -861,7 +859,7 @@ pub(crate) fn field_types_query(
861 let ctx = 859 let ctx =
862 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 860 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
863 for (field_id, field_data) in var_data.fields().iter() { 861 for (field_id, field_data) in var_data.fields().iter() {
864 res.insert(field_id, Binders::new(generics.len(), Ty::from_hir(&ctx, &field_data.type_ref))) 862 res.insert(field_id, Binders::new(generics.len(), ctx.lower_ty(&field_data.type_ref)))
865 } 863 }
866 Arc::new(res) 864 Arc::new(res)
867} 865}
@@ -889,16 +887,13 @@ pub(crate) fn generic_predicates_for_param_query(
889 WherePredicate::ForLifetime { target, .. } 887 WherePredicate::ForLifetime { target, .. }
890 | WherePredicate::TypeBound { target, .. } => match target { 888 | WherePredicate::TypeBound { target, .. } => match target {
891 WherePredicateTypeTarget::TypeRef(type_ref) => { 889 WherePredicateTypeTarget::TypeRef(type_ref) => {
892 Ty::from_hir_only_param(&ctx, type_ref) == Some(param_id) 890 ctx.lower_ty_only_param(type_ref) == Some(param_id)
893 } 891 }
894 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id, 892 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
895 }, 893 },
896 WherePredicate::Lifetime { .. } => false, 894 WherePredicate::Lifetime { .. } => false,
897 }) 895 })
898 .flat_map(|pred| { 896 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
899 GenericPredicate::from_where_predicate(&ctx, pred)
900 .map(|p| Binders::new(generics.len(), p))
901 })
902 .collect() 897 .collect()
903} 898}
904 899
@@ -910,41 +905,55 @@ pub(crate) fn generic_predicates_for_param_recover(
910 Arc::new([]) 905 Arc::new([])
911} 906}
912 907
913impl TraitEnvironment { 908pub(crate) fn trait_environment_query(
914 pub fn lower(db: &dyn HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> { 909 db: &dyn HirDatabase,
915 let ctx = TyLoweringContext::new(db, &resolver) 910 def: GenericDefId,
916 .with_type_param_mode(TypeParamLoweringMode::Placeholder); 911) -> Arc<TraitEnvironment> {
917 let mut predicates = resolver 912 let resolver = def.resolver(db.upcast());
918 .where_predicates_in_scope() 913 let ctx = TyLoweringContext::new(db, &resolver)
919 .flat_map(|pred| GenericPredicate::from_where_predicate(&ctx, pred)) 914 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
920 .collect::<Vec<_>>(); 915 let mut traits_in_scope = Vec::new();
921 916 let mut clauses = Vec::new();
922 if let Some(def) = resolver.generic_def() { 917 for pred in resolver.where_predicates_in_scope() {
923 let container: Option<AssocContainerId> = match def { 918 for pred in ctx.lower_where_predicate(pred) {
924 // FIXME: is there a function for this? 919 if pred.is_error() {
925 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container), 920 continue;
926 GenericDefId::AdtId(_) => None,
927 GenericDefId::TraitId(_) => None,
928 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
929 GenericDefId::ImplId(_) => None,
930 GenericDefId::EnumVariantId(_) => None,
931 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
932 };
933 if let Some(AssocContainerId::TraitId(trait_id)) = container {
934 // add `Self: Trait<T1, T2, ...>` to the environment in trait
935 // function default implementations (and hypothetical code
936 // inside consts or type aliases)
937 cov_mark::hit!(trait_self_implements_self);
938 let substs = Substs::type_params(db, trait_id);
939 let trait_ref = TraitRef { trait_: trait_id, substs };
940 let pred = GenericPredicate::Implemented(trait_ref);
941
942 predicates.push(pred);
943 } 921 }
922 if let GenericPredicate::Implemented(tr) = &pred {
923 traits_in_scope.push((tr.self_ty().clone(), tr.trait_));
924 }
925 let program_clause: chalk_ir::ProgramClause<Interner> =
926 pred.clone().to_chalk(db).cast(&Interner);
927 clauses.push(program_clause.into_from_env_clause(&Interner));
944 } 928 }
929 }
945 930
946 Arc::new(TraitEnvironment { predicates }) 931 let container: Option<AssocContainerId> = match def {
932 // FIXME: is there a function for this?
933 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
934 GenericDefId::AdtId(_) => None,
935 GenericDefId::TraitId(_) => None,
936 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
937 GenericDefId::ImplId(_) => None,
938 GenericDefId::EnumVariantId(_) => None,
939 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
940 };
941 if let Some(AssocContainerId::TraitId(trait_id)) = container {
942 // add `Self: Trait<T1, T2, ...>` to the environment in trait
943 // function default implementations (and hypothetical code
944 // inside consts or type aliases)
945 cov_mark::hit!(trait_self_implements_self);
946 let substs = Substs::type_params(db, trait_id);
947 let trait_ref = TraitRef { trait_: trait_id, substs };
948 let pred = GenericPredicate::Implemented(trait_ref);
949 let program_clause: chalk_ir::ProgramClause<Interner> =
950 pred.clone().to_chalk(db).cast(&Interner);
951 clauses.push(program_clause.into_from_env_clause(&Interner));
947 } 952 }
953
954 let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
955
956 Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
948} 957}
949 958
950/// Resolve the where clause(s) of an item with generics. 959/// Resolve the where clause(s) of an item with generics.
@@ -958,10 +967,7 @@ pub(crate) fn generic_predicates_query(
958 let generics = generics(db.upcast(), def); 967 let generics = generics(db.upcast(), def);
959 resolver 968 resolver
960 .where_predicates_in_scope() 969 .where_predicates_in_scope()
961 .flat_map(|pred| { 970 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
962 GenericPredicate::from_where_predicate(&ctx, pred)
963 .map(|p| Binders::new(generics.len(), p))
964 })
965 .collect() 971 .collect()
966} 972}
967 973
@@ -979,17 +985,18 @@ pub(crate) fn generic_defaults_query(
979 .iter() 985 .iter()
980 .enumerate() 986 .enumerate()
981 .map(|(idx, (_, p))| { 987 .map(|(idx, (_, p))| {
982 let mut ty = p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(&ctx, t)); 988 let mut ty =
989 p.default.as_ref().map_or(TyKind::Unknown.intern(&Interner), |t| ctx.lower_ty(t));
983 990
984 // Each default can only refer to previous parameters. 991 // Each default can only refer to previous parameters.
985 ty.walk_mut_binders( 992 ty.walk_mut_binders(
986 &mut |ty, binders| match ty { 993 &mut |ty, binders| match &mut ty.0 {
987 Ty::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => { 994 TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
988 if *index >= idx { 995 if *index >= idx {
989 // type variable default referring to parameter coming 996 // type variable default referring to parameter coming
990 // after it. This is forbidden (FIXME: report 997 // after it. This is forbidden (FIXME: report
991 // diagnostic) 998 // diagnostic)
992 *ty = Ty::Unknown; 999 *ty = TyKind::Unknown.intern(&Interner);
993 } 1000 }
994 } 1001 }
995 _ => {} 1002 _ => {}
@@ -1010,11 +1017,11 @@ fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1010 let ctx_params = TyLoweringContext::new(db, &resolver) 1017 let ctx_params = TyLoweringContext::new(db, &resolver)
1011 .with_impl_trait_mode(ImplTraitLoweringMode::Variable) 1018 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1012 .with_type_param_mode(TypeParamLoweringMode::Variable); 1019 .with_type_param_mode(TypeParamLoweringMode::Variable);
1013 let params = data.params.iter().map(|tr| Ty::from_hir(&ctx_params, tr)).collect::<Vec<_>>(); 1020 let params = data.params.iter().map(|tr| (&ctx_params).lower_ty(tr)).collect::<Vec<_>>();
1014 let ctx_ret = TyLoweringContext::new(db, &resolver) 1021 let ctx_ret = TyLoweringContext::new(db, &resolver)
1015 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) 1022 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1016 .with_type_param_mode(TypeParamLoweringMode::Variable); 1023 .with_type_param_mode(TypeParamLoweringMode::Variable);
1017 let ret = Ty::from_hir(&ctx_ret, &data.ret_type); 1024 let ret = (&ctx_ret).lower_ty(&data.ret_type);
1018 let generics = generics(db.upcast(), def.into()); 1025 let generics = generics(db.upcast(), def.into());
1019 let num_binders = generics.len(); 1026 let num_binders = generics.len();
1020 Binders::new(num_binders, CallableSig::from_params_and_return(params, ret, data.is_varargs)) 1027 Binders::new(num_binders, CallableSig::from_params_and_return(params, ret, data.is_varargs))
@@ -1025,7 +1032,10 @@ fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1025fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> { 1032fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1026 let generics = generics(db.upcast(), def.into()); 1033 let generics = generics(db.upcast(), def.into());
1027 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1034 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1028 Binders::new(substs.len(), Ty::FnDef(def.into(), substs)) 1035 Binders::new(
1036 substs.len(),
1037 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1038 )
1029} 1039}
1030 1040
1031/// Build the declared type of a const. 1041/// Build the declared type of a const.
@@ -1036,7 +1046,7 @@ fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1036 let ctx = 1046 let ctx =
1037 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 1047 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1038 1048
1039 Binders::new(generics.len(), Ty::from_hir(&ctx, &data.type_ref)) 1049 Binders::new(generics.len(), ctx.lower_ty(&data.type_ref))
1040} 1050}
1041 1051
1042/// Build the declared type of a static. 1052/// Build the declared type of a static.
@@ -1045,7 +1055,7 @@ fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1045 let resolver = def.resolver(db.upcast()); 1055 let resolver = def.resolver(db.upcast());
1046 let ctx = TyLoweringContext::new(db, &resolver); 1056 let ctx = TyLoweringContext::new(db, &resolver);
1047 1057
1048 Binders::new(0, Ty::from_hir(&ctx, &data.type_ref)) 1058 Binders::new(0, ctx.lower_ty(&data.type_ref))
1049} 1059}
1050 1060
1051fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig { 1061fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
@@ -1054,8 +1064,7 @@ fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnS
1054 let resolver = def.resolver(db.upcast()); 1064 let resolver = def.resolver(db.upcast());
1055 let ctx = 1065 let ctx =
1056 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 1066 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1057 let params = 1067 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1058 fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
1059 let ret = type_for_adt(db, def.into()); 1068 let ret = type_for_adt(db, def.into());
1060 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false)) 1069 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1061} 1070}
@@ -1068,7 +1077,10 @@ fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<T
1068 } 1077 }
1069 let generics = generics(db.upcast(), def.into()); 1078 let generics = generics(db.upcast(), def.into());
1070 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1079 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1071 Binders::new(substs.len(), Ty::FnDef(def.into(), substs)) 1080 Binders::new(
1081 substs.len(),
1082 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1083 )
1072} 1084}
1073 1085
1074fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig { 1086fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
@@ -1078,8 +1090,7 @@ fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId)
1078 let resolver = def.parent.resolver(db.upcast()); 1090 let resolver = def.parent.resolver(db.upcast());
1079 let ctx = 1091 let ctx =
1080 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 1092 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1081 let params = 1093 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1082 fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
1083 let ret = type_for_adt(db, def.parent.into()); 1094 let ret = type_for_adt(db, def.parent.into());
1084 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false)) 1095 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1085} 1096}
@@ -1093,7 +1104,10 @@ fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -
1093 } 1104 }
1094 let generics = generics(db.upcast(), def.parent.into()); 1105 let generics = generics(db.upcast(), def.parent.into());
1095 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1106 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1096 Binders::new(substs.len(), Ty::FnDef(def.into(), substs)) 1107 Binders::new(
1108 substs.len(),
1109 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1110 )
1097} 1111}
1098 1112
1099fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> { 1113fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
@@ -1108,11 +1122,11 @@ fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1108 let ctx = 1122 let ctx =
1109 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 1123 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1110 if db.type_alias_data(t).is_extern { 1124 if db.type_alias_data(t).is_extern {
1111 Binders::new(0, Ty::ForeignType(t)) 1125 Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner))
1112 } else { 1126 } else {
1113 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1127 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1114 let type_ref = &db.type_alias_data(t).type_ref; 1128 let type_ref = &db.type_alias_data(t).type_ref;
1115 let inner = Ty::from_hir(&ctx, type_ref.as_ref().unwrap_or(&TypeRef::Error)); 1129 let inner = ctx.lower_ty(type_ref.as_ref().unwrap_or(&TypeRef::Error));
1116 Binders::new(substs.len(), inner) 1130 Binders::new(substs.len(), inner)
1117 } 1131 }
1118} 1132}
@@ -1184,7 +1198,7 @@ pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId)
1184 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(), 1198 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
1185 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(), 1199 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
1186 }; 1200 };
1187 Binders::new(num_binders, Ty::Unknown) 1201 Binders::new(num_binders, TyKind::Unknown.intern(&Interner))
1188} 1202}
1189 1203
1190pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> { 1204pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
@@ -1204,7 +1218,7 @@ pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binde
1204 let generics = generics(db.upcast(), impl_id.into()); 1218 let generics = generics(db.upcast(), impl_id.into());
1205 let ctx = 1219 let ctx =
1206 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 1220 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1207 Binders::new(generics.len(), Ty::from_hir(&ctx, &impl_data.target_type)) 1221 Binders::new(generics.len(), ctx.lower_ty(&impl_data.target_type))
1208} 1222}
1209 1223
1210pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty { 1224pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
@@ -1213,7 +1227,7 @@ pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> T
1213 let resolver = def.parent.resolver(db.upcast()); 1227 let resolver = def.parent.resolver(db.upcast());
1214 let ctx = TyLoweringContext::new(db, &resolver); 1228 let ctx = TyLoweringContext::new(db, &resolver);
1215 1229
1216 Ty::from_hir(&ctx, &data.ty) 1230 ctx.lower_ty(&data.ty)
1217} 1231}
1218 1232
1219pub(crate) fn impl_self_ty_recover( 1233pub(crate) fn impl_self_ty_recover(
@@ -1222,7 +1236,7 @@ pub(crate) fn impl_self_ty_recover(
1222 impl_id: &ImplId, 1236 impl_id: &ImplId,
1223) -> Binders<Ty> { 1237) -> Binders<Ty> {
1224 let generics = generics(db.upcast(), (*impl_id).into()); 1238 let generics = generics(db.upcast(), (*impl_id).into());
1225 Binders::new(generics.len(), Ty::Unknown) 1239 Binders::new(generics.len(), TyKind::Unknown.intern(&Interner))
1226} 1240}
1227 1241
1228pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> { 1242pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
@@ -1232,10 +1246,7 @@ pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<
1232 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 1246 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1233 let self_ty = db.impl_self_ty(impl_id); 1247 let self_ty = db.impl_self_ty(impl_id);
1234 let target_trait = impl_data.target_trait.as_ref()?; 1248 let target_trait = impl_data.target_trait.as_ref()?;
1235 Some(Binders::new( 1249 Some(Binders::new(self_ty.num_binders, ctx.lower_trait_ref(target_trait, Some(self_ty.value))?))
1236 self_ty.num_binders,
1237 TraitRef::from_hir(&ctx, target_trait, Some(self_ty.value))?,
1238 ))
1239} 1250}
1240 1251
1241pub(crate) fn return_type_impl_traits( 1252pub(crate) fn return_type_impl_traits(
@@ -1248,7 +1259,7 @@ pub(crate) fn return_type_impl_traits(
1248 let ctx_ret = TyLoweringContext::new(db, &resolver) 1259 let ctx_ret = TyLoweringContext::new(db, &resolver)
1249 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) 1260 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1250 .with_type_param_mode(TypeParamLoweringMode::Variable); 1261 .with_type_param_mode(TypeParamLoweringMode::Variable);
1251 let _ret = Ty::from_hir(&ctx_ret, &data.ret_type); 1262 let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1252 let generics = generics(db.upcast(), def.into()); 1263 let generics = generics(db.upcast(), def.into());
1253 let num_binders = generics.len(); 1264 let num_binders = generics.len();
1254 let return_type_impl_traits = 1265 let return_type_impl_traits =
diff --git a/crates/hir_ty/src/method_resolution.rs b/crates/hir_ty/src/method_resolution.rs
index ccc12c075..c7055bee5 100644
--- a/crates/hir_ty/src/method_resolution.rs
+++ b/crates/hir_ty/src/method_resolution.rs
@@ -9,7 +9,7 @@ use base_db::CrateId;
9use chalk_ir::Mutability; 9use chalk_ir::Mutability;
10use hir_def::{ 10use hir_def::{
11 lang_item::LangItemTarget, AssocContainerId, AssocItemId, FunctionId, GenericDefId, HasModule, 11 lang_item::LangItemTarget, AssocContainerId, AssocItemId, FunctionId, GenericDefId, HasModule,
12 ImplId, Lookup, ModuleId, TraitId, TypeAliasId, 12 ImplId, Lookup, ModuleId, TraitId,
13}; 13};
14use hir_expand::name::Name; 14use hir_expand::name::Name;
15use rustc_hash::{FxHashMap, FxHashSet}; 15use rustc_hash::{FxHashMap, FxHashSet};
@@ -17,10 +17,11 @@ use rustc_hash::{FxHashMap, FxHashSet};
17use crate::{ 17use crate::{
18 autoderef, 18 autoderef,
19 db::HirDatabase, 19 db::HirDatabase,
20 from_foreign_def_id,
20 primitive::{self, FloatTy, IntTy, UintTy}, 21 primitive::{self, FloatTy, IntTy, UintTy},
21 utils::all_super_traits, 22 utils::all_super_traits,
22 AdtId, Canonical, DebruijnIndex, FnPointer, FnSig, InEnvironment, Scalar, Substs, 23 AdtId, Canonical, DebruijnIndex, FnPointer, FnSig, ForeignDefId, InEnvironment, Interner,
23 TraitEnvironment, TraitRef, Ty, TypeWalk, 24 Scalar, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeWalk,
24}; 25};
25 26
26/// This is used as a key for indexing impls. 27/// This is used as a key for indexing impls.
@@ -35,7 +36,7 @@ pub enum TyFingerprint {
35 Adt(hir_def::AdtId), 36 Adt(hir_def::AdtId),
36 Dyn(TraitId), 37 Dyn(TraitId),
37 Tuple(usize), 38 Tuple(usize),
38 ForeignType(TypeAliasId), 39 ForeignType(ForeignDefId),
39 FnPtr(usize, FnSig), 40 FnPtr(usize, FnSig),
40} 41}
41 42
@@ -44,18 +45,20 @@ impl TyFingerprint {
44 /// have impls: if we have some `struct S`, we can have an `impl S`, but not 45 /// have impls: if we have some `struct S`, we can have an `impl S`, but not
45 /// `impl &S`. Hence, this will return `None` for reference types and such. 46 /// `impl &S`. Hence, this will return `None` for reference types and such.
46 pub(crate) fn for_impl(ty: &Ty) -> Option<TyFingerprint> { 47 pub(crate) fn for_impl(ty: &Ty) -> Option<TyFingerprint> {
47 let fp = match ty { 48 let fp = match *ty.interned(&Interner) {
48 &Ty::Str => TyFingerprint::Str, 49 TyKind::Str => TyFingerprint::Str,
49 &Ty::Never => TyFingerprint::Never, 50 TyKind::Never => TyFingerprint::Never,
50 &Ty::Slice(..) => TyFingerprint::Slice, 51 TyKind::Slice(..) => TyFingerprint::Slice,
51 &Ty::Array(..) => TyFingerprint::Array, 52 TyKind::Array(..) => TyFingerprint::Array,
52 &Ty::Scalar(scalar) => TyFingerprint::Scalar(scalar), 53 TyKind::Scalar(scalar) => TyFingerprint::Scalar(scalar),
53 &Ty::Adt(AdtId(adt), _) => TyFingerprint::Adt(adt), 54 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(adt),
54 &Ty::Tuple(cardinality, _) => TyFingerprint::Tuple(cardinality), 55 TyKind::Tuple(cardinality, _) => TyFingerprint::Tuple(cardinality),
55 &Ty::Raw(mutability, ..) => TyFingerprint::RawPtr(mutability), 56 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(mutability),
56 &Ty::ForeignType(alias_id, ..) => TyFingerprint::ForeignType(alias_id), 57 TyKind::ForeignType(alias_id, ..) => TyFingerprint::ForeignType(alias_id),
57 &Ty::Function(FnPointer { num_args, sig, .. }) => TyFingerprint::FnPtr(num_args, sig), 58 TyKind::Function(FnPointer { num_args, sig, .. }) => {
58 Ty::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?, 59 TyFingerprint::FnPtr(num_args, sig)
60 }
61 TyKind::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?,
59 _ => return None, 62 _ => return None,
60 }; 63 };
61 Some(fp) 64 Some(fp)
@@ -230,31 +233,33 @@ impl Ty {
230 233
231 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect()); 234 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
232 235
233 let lang_item_targets = match self { 236 let lang_item_targets = match self.interned(&Interner) {
234 Ty::Adt(AdtId(def_id), _) => { 237 TyKind::Adt(AdtId(def_id), _) => {
235 return mod_to_crate_ids(def_id.module(db.upcast())); 238 return mod_to_crate_ids(def_id.module(db.upcast()));
236 } 239 }
237 Ty::ForeignType(type_alias_id) => { 240 TyKind::ForeignType(id) => {
238 return mod_to_crate_ids(type_alias_id.lookup(db.upcast()).module(db.upcast())); 241 return mod_to_crate_ids(
242 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
243 );
239 } 244 }
240 Ty::Scalar(Scalar::Bool) => lang_item_crate!("bool"), 245 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
241 Ty::Scalar(Scalar::Char) => lang_item_crate!("char"), 246 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
242 Ty::Scalar(Scalar::Float(f)) => match f { 247 TyKind::Scalar(Scalar::Float(f)) => match f {
243 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime) 248 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
244 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"), 249 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
245 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"), 250 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
246 }, 251 },
247 &Ty::Scalar(Scalar::Int(t)) => { 252 &TyKind::Scalar(Scalar::Int(t)) => {
248 lang_item_crate!(primitive::int_ty_to_string(t)) 253 lang_item_crate!(primitive::int_ty_to_string(t))
249 } 254 }
250 &Ty::Scalar(Scalar::Uint(t)) => { 255 &TyKind::Scalar(Scalar::Uint(t)) => {
251 lang_item_crate!(primitive::uint_ty_to_string(t)) 256 lang_item_crate!(primitive::uint_ty_to_string(t))
252 } 257 }
253 Ty::Str => lang_item_crate!("str_alloc", "str"), 258 TyKind::Str => lang_item_crate!("str_alloc", "str"),
254 Ty::Slice(_) => lang_item_crate!("slice_alloc", "slice"), 259 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
255 Ty::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"), 260 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
256 Ty::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"), 261 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
257 Ty::Dyn(_) => { 262 TyKind::Dyn(_) => {
258 return self.dyn_trait().and_then(|trait_| { 263 return self.dyn_trait().and_then(|trait_| {
259 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast())) 264 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
260 }); 265 });
@@ -430,7 +435,8 @@ fn iterate_method_candidates_with_autoref(
430 } 435 }
431 let refed = Canonical { 436 let refed = Canonical {
432 kinds: deref_chain[0].kinds.clone(), 437 kinds: deref_chain[0].kinds.clone(),
433 value: Ty::Ref(Mutability::Not, Substs::single(deref_chain[0].value.clone())), 438 value: TyKind::Ref(Mutability::Not, Substs::single(deref_chain[0].value.clone()))
439 .intern(&Interner),
434 }; 440 };
435 if iterate_method_candidates_by_receiver( 441 if iterate_method_candidates_by_receiver(
436 &refed, 442 &refed,
@@ -446,7 +452,8 @@ fn iterate_method_candidates_with_autoref(
446 } 452 }
447 let ref_muted = Canonical { 453 let ref_muted = Canonical {
448 kinds: deref_chain[0].kinds.clone(), 454 kinds: deref_chain[0].kinds.clone(),
449 value: Ty::Ref(Mutability::Mut, Substs::single(deref_chain[0].value.clone())), 455 value: TyKind::Ref(Mutability::Mut, Substs::single(deref_chain[0].value.clone()))
456 .intern(&Interner),
450 }; 457 };
451 if iterate_method_candidates_by_receiver( 458 if iterate_method_candidates_by_receiver(
452 &ref_muted, 459 &ref_muted,
@@ -526,10 +533,9 @@ fn iterate_trait_method_candidates(
526 // if ty is `dyn Trait`, the trait doesn't need to be in scope 533 // if ty is `dyn Trait`, the trait doesn't need to be in scope
527 let inherent_trait = 534 let inherent_trait =
528 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t)); 535 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
529 let env_traits = if let Ty::Placeholder(_) = self_ty.value { 536 let env_traits = if let TyKind::Placeholder(_) = self_ty.value.interned(&Interner) {
530 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope 537 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
531 env.trait_predicates_for_self_ty(&self_ty.value) 538 env.traits_in_scope_from_clauses(&self_ty.value)
532 .map(|tr| tr.trait_)
533 .flat_map(|t| all_super_traits(db.upcast(), t)) 539 .flat_map(|t| all_super_traits(db.upcast(), t))
534 .collect() 540 .collect()
535 } else { 541 } else {
@@ -680,13 +686,13 @@ pub(crate) fn inherent_impl_substs(
680} 686}
681 687
682/// This replaces any 'free' Bound vars in `s` (i.e. those with indices past 688/// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
683/// num_vars_to_keep) by `Ty::Unknown`. 689/// num_vars_to_keep) by `TyKind::Unknown`.
684fn fallback_bound_vars(s: Substs, num_vars_to_keep: usize) -> Substs { 690fn fallback_bound_vars(s: Substs, num_vars_to_keep: usize) -> Substs {
685 s.fold_binders( 691 s.fold_binders(
686 &mut |ty, binders| { 692 &mut |ty, binders| {
687 if let Ty::BoundVar(bound) = &ty { 693 if let TyKind::BoundVar(bound) = ty.interned(&Interner) {
688 if bound.index >= num_vars_to_keep && bound.debruijn >= binders { 694 if bound.index >= num_vars_to_keep && bound.debruijn >= binders {
689 Ty::Unknown 695 TyKind::Unknown.intern(&Interner)
690 } else { 696 } else {
691 ty 697 ty
692 } 698 }
@@ -773,9 +779,11 @@ fn autoderef_method_receiver(
773) -> Vec<Canonical<Ty>> { 779) -> Vec<Canonical<Ty>> {
774 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect(); 780 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
775 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!) 781 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
776 if let Some(Ty::Array(parameters)) = deref_chain.last().map(|ty| &ty.value) { 782 if let Some(TyKind::Array(parameters)) =
783 deref_chain.last().map(|ty| ty.value.interned(&Interner))
784 {
777 let kinds = deref_chain.last().unwrap().kinds.clone(); 785 let kinds = deref_chain.last().unwrap().kinds.clone();
778 let unsized_ty = Ty::Slice(parameters.clone()); 786 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
779 deref_chain.push(Canonical { value: unsized_ty, kinds }) 787 deref_chain.push(Canonical { value: unsized_ty, kinds })
780 } 788 }
781 deref_chain 789 deref_chain
diff --git a/crates/hir_ty/src/op.rs b/crates/hir_ty/src/op.rs
index bb9b8bbfc..527c5cbbd 100644
--- a/crates/hir_ty/src/op.rs
+++ b/crates/hir_ty/src/op.rs
@@ -2,51 +2,55 @@
2use chalk_ir::TyVariableKind; 2use chalk_ir::TyVariableKind;
3use hir_def::expr::{ArithOp, BinaryOp, CmpOp}; 3use hir_def::expr::{ArithOp, BinaryOp, CmpOp};
4 4
5use crate::{Scalar, Ty}; 5use crate::{Interner, Scalar, Ty, TyKind};
6 6
7pub(super) fn binary_op_return_ty(op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Ty { 7pub(super) fn binary_op_return_ty(op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Ty {
8 match op { 8 match op {
9 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => Ty::Scalar(Scalar::Bool), 9 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
10 BinaryOp::Assignment { .. } => Ty::unit(), 10 BinaryOp::Assignment { .. } => Ty::unit(),
11 BinaryOp::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => match lhs_ty { 11 BinaryOp::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => {
12 Ty::Scalar(Scalar::Int(_)) 12 match lhs_ty.interned(&Interner) {
13 | Ty::Scalar(Scalar::Uint(_)) 13 TyKind::Scalar(Scalar::Int(_))
14 | Ty::Scalar(Scalar::Float(_)) => lhs_ty, 14 | TyKind::Scalar(Scalar::Uint(_))
15 Ty::InferenceVar(_, TyVariableKind::Integer) 15 | TyKind::Scalar(Scalar::Float(_)) => lhs_ty,
16 | Ty::InferenceVar(_, TyVariableKind::Float) => lhs_ty, 16 TyKind::InferenceVar(_, TyVariableKind::Integer)
17 _ => Ty::Unknown, 17 | TyKind::InferenceVar(_, TyVariableKind::Float) => lhs_ty,
18 }, 18 _ => TyKind::Unknown.intern(&Interner),
19 BinaryOp::ArithOp(_) => match rhs_ty { 19 }
20 Ty::Scalar(Scalar::Int(_)) 20 }
21 | Ty::Scalar(Scalar::Uint(_)) 21 BinaryOp::ArithOp(_) => match rhs_ty.interned(&Interner) {
22 | Ty::Scalar(Scalar::Float(_)) => rhs_ty, 22 TyKind::Scalar(Scalar::Int(_))
23 Ty::InferenceVar(_, TyVariableKind::Integer) 23 | TyKind::Scalar(Scalar::Uint(_))
24 | Ty::InferenceVar(_, TyVariableKind::Float) => rhs_ty, 24 | TyKind::Scalar(Scalar::Float(_)) => rhs_ty,
25 _ => Ty::Unknown, 25 TyKind::InferenceVar(_, TyVariableKind::Integer)
26 | TyKind::InferenceVar(_, TyVariableKind::Float) => rhs_ty,
27 _ => TyKind::Unknown.intern(&Interner),
26 }, 28 },
27 } 29 }
28} 30}
29 31
30pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty { 32pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty {
31 match op { 33 match op {
32 BinaryOp::LogicOp(..) => Ty::Scalar(Scalar::Bool), 34 BinaryOp::LogicOp(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
33 BinaryOp::Assignment { op: None } => lhs_ty, 35 BinaryOp::Assignment { op: None } => lhs_ty,
34 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match lhs_ty { 36 BinaryOp::CmpOp(CmpOp::Eq { .. }) => match lhs_ty.interned(&Interner) {
35 Ty::Scalar(_) | Ty::Str => lhs_ty, 37 TyKind::Scalar(_) | TyKind::Str => lhs_ty,
36 Ty::InferenceVar(_, TyVariableKind::Integer) 38 TyKind::InferenceVar(_, TyVariableKind::Integer)
37 | Ty::InferenceVar(_, TyVariableKind::Float) => lhs_ty, 39 | TyKind::InferenceVar(_, TyVariableKind::Float) => lhs_ty,
38 _ => Ty::Unknown, 40 _ => TyKind::Unknown.intern(&Interner),
39 }, 41 },
40 BinaryOp::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => Ty::Unknown, 42 BinaryOp::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => {
43 TyKind::Unknown.intern(&Interner)
44 }
41 BinaryOp::CmpOp(CmpOp::Ord { .. }) 45 BinaryOp::CmpOp(CmpOp::Ord { .. })
42 | BinaryOp::Assignment { op: Some(_) } 46 | BinaryOp::Assignment { op: Some(_) }
43 | BinaryOp::ArithOp(_) => match lhs_ty { 47 | BinaryOp::ArithOp(_) => match lhs_ty.interned(&Interner) {
44 Ty::Scalar(Scalar::Int(_)) 48 TyKind::Scalar(Scalar::Int(_))
45 | Ty::Scalar(Scalar::Uint(_)) 49 | TyKind::Scalar(Scalar::Uint(_))
46 | Ty::Scalar(Scalar::Float(_)) => lhs_ty, 50 | TyKind::Scalar(Scalar::Float(_)) => lhs_ty,
47 Ty::InferenceVar(_, TyVariableKind::Integer) 51 TyKind::InferenceVar(_, TyVariableKind::Integer)
48 | Ty::InferenceVar(_, TyVariableKind::Float) => lhs_ty, 52 | TyKind::InferenceVar(_, TyVariableKind::Float) => lhs_ty,
49 _ => Ty::Unknown, 53 _ => TyKind::Unknown.intern(&Interner),
50 }, 54 },
51 } 55 }
52} 56}
diff --git a/crates/hir_ty/src/tests.rs b/crates/hir_ty/src/tests.rs
index fc770ea60..0a4141e69 100644
--- a/crates/hir_ty/src/tests.rs
+++ b/crates/hir_ty/src/tests.rs
@@ -19,6 +19,7 @@ use hir_def::{
19 item_scope::ItemScope, 19 item_scope::ItemScope,
20 keys, 20 keys,
21 nameres::DefMap, 21 nameres::DefMap,
22 src::HasSource,
22 AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId, 23 AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId,
23}; 24};
24use hir_expand::{db::AstDatabase, InFile}; 25use hir_expand::{db::AstDatabase, InFile};
@@ -195,18 +196,15 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
195 defs.sort_by_key(|def| match def { 196 defs.sort_by_key(|def| match def {
196 DefWithBodyId::FunctionId(it) => { 197 DefWithBodyId::FunctionId(it) => {
197 let loc = it.lookup(&db); 198 let loc = it.lookup(&db);
198 let tree = db.item_tree(loc.id.file_id); 199 loc.source(&db).value.syntax().text_range().start()
199 tree.source(&db, loc.id).syntax().text_range().start()
200 } 200 }
201 DefWithBodyId::ConstId(it) => { 201 DefWithBodyId::ConstId(it) => {
202 let loc = it.lookup(&db); 202 let loc = it.lookup(&db);
203 let tree = db.item_tree(loc.id.file_id); 203 loc.source(&db).value.syntax().text_range().start()
204 tree.source(&db, loc.id).syntax().text_range().start()
205 } 204 }
206 DefWithBodyId::StaticId(it) => { 205 DefWithBodyId::StaticId(it) => {
207 let loc = it.lookup(&db); 206 let loc = it.lookup(&db);
208 let tree = db.item_tree(loc.id.file_id); 207 loc.source(&db).value.syntax().text_range().start()
209 tree.source(&db, loc.id).syntax().text_range().start()
210 } 208 }
211 }); 209 });
212 for def in defs { 210 for def in defs {
diff --git a/crates/hir_ty/src/traits.rs b/crates/hir_ty/src/traits.rs
index e4cdb6d53..edfafdff8 100644
--- a/crates/hir_ty/src/traits.rs
+++ b/crates/hir_ty/src/traits.rs
@@ -10,7 +10,9 @@ use stdx::panic_context;
10 10
11use crate::{db::HirDatabase, DebruijnIndex, Substs}; 11use crate::{db::HirDatabase, DebruijnIndex, Substs};
12 12
13use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TypeWalk}; 13use super::{
14 Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TyKind, TypeWalk,
15};
14 16
15use self::chalk::{from_chalk, Interner, ToChalk}; 17use self::chalk::{from_chalk, Interner, ToChalk};
16 18
@@ -38,26 +40,38 @@ fn create_chalk_solver() -> chalk_recursive::RecursiveSolver<Interner> {
38/// fn foo<T: Default>(t: T) {} 40/// fn foo<T: Default>(t: T) {}
39/// ``` 41/// ```
40/// we assume that `T: Default`. 42/// we assume that `T: Default`.
41#[derive(Clone, Debug, PartialEq, Eq, Hash)] 43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
42pub struct TraitEnvironment { 44pub struct TraitEnvironment {
43 pub predicates: Vec<GenericPredicate>, 45 // When we're using Chalk's Ty we can make this a BTreeMap since it's Ord,
46 // but for now it's too annoying...
47 pub(crate) traits_from_clauses: Vec<(Ty, TraitId)>,
48 pub(crate) env: chalk_ir::Environment<Interner>,
44} 49}
45 50
46impl TraitEnvironment { 51impl TraitEnvironment {
47 /// Returns trait refs with the given self type which are supposed to hold 52 pub(crate) fn traits_in_scope_from_clauses<'a>(
48 /// in this trait env. E.g. if we are in `foo<T: SomeTrait>()`, this will
49 /// find that `T: SomeTrait` if we call it for `T`.
50 pub(crate) fn trait_predicates_for_self_ty<'a>(
51 &'a self, 53 &'a self,
52 ty: &'a Ty, 54 ty: &'a Ty,
53 ) -> impl Iterator<Item = &'a TraitRef> + 'a { 55 ) -> impl Iterator<Item = TraitId> + 'a {
54 self.predicates.iter().filter_map(move |pred| match pred { 56 self.traits_from_clauses.iter().filter_map(move |(self_ty, trait_id)| {
55 GenericPredicate::Implemented(tr) if tr.self_ty() == ty => Some(tr), 57 if self_ty == ty {
56 _ => None, 58 Some(*trait_id)
59 } else {
60 None
61 }
57 }) 62 })
58 } 63 }
59} 64}
60 65
66impl Default for TraitEnvironment {
67 fn default() -> Self {
68 TraitEnvironment {
69 traits_from_clauses: Vec::new(),
70 env: chalk_ir::Environment::new(&Interner),
71 }
72 }
73}
74
61/// Something (usually a goal), along with an environment. 75/// Something (usually a goal), along with an environment.
62#[derive(Clone, Debug, PartialEq, Eq, Hash)] 76#[derive(Clone, Debug, PartialEq, Eq, Hash)]
63pub struct InEnvironment<T> { 77pub struct InEnvironment<T> {
@@ -129,7 +143,7 @@ pub(crate) fn trait_solve_query(
129 log::info!("trait_solve_query({})", goal.value.value.display(db)); 143 log::info!("trait_solve_query({})", goal.value.value.display(db));
130 144
131 if let Obligation::Projection(pred) = &goal.value.value { 145 if let Obligation::Projection(pred) = &goal.value.value {
132 if let Ty::BoundVar(_) = &pred.projection_ty.parameters[0] { 146 if let TyKind::BoundVar(_) = &pred.projection_ty.parameters[0].interned(&Interner) {
133 // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible 147 // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible
134 return Some(Solution::Ambig(Guidance::Unknown)); 148 return Some(Solution::Ambig(Guidance::Unknown));
135 } 149 }
diff --git a/crates/hir_ty/src/traits/chalk.rs b/crates/hir_ty/src/traits/chalk.rs
index 565672b6b..ef1e6b2df 100644
--- a/crates/hir_ty/src/traits/chalk.rs
+++ b/crates/hir_ty/src/traits/chalk.rs
@@ -17,29 +17,31 @@ use super::ChalkContext;
17use crate::{ 17use crate::{
18 db::HirDatabase, 18 db::HirDatabase,
19 display::HirDisplay, 19 display::HirDisplay,
20 from_assoc_type_id,
20 method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS}, 21 method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS},
22 to_assoc_type_id,
21 utils::generics, 23 utils::generics,
22 BoundVar, CallableDefId, CallableSig, DebruijnIndex, GenericPredicate, ProjectionPredicate, 24 BoundVar, CallableDefId, CallableSig, DebruijnIndex, FnDefId, GenericPredicate,
23 ProjectionTy, Substs, TraitRef, Ty, 25 ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TyKind,
24}; 26};
25use mapping::{ 27use mapping::{
26 convert_where_clauses, generic_predicate_to_inline_bound, make_binders, TypeAliasAsAssocType, 28 convert_where_clauses, generic_predicate_to_inline_bound, make_binders, TypeAliasAsValue,
27 TypeAliasAsValue,
28}; 29};
29 30
31pub use self::interner::Interner;
30pub(crate) use self::interner::*; 32pub(crate) use self::interner::*;
31 33
32pub(super) mod tls; 34pub(super) mod tls;
33mod interner; 35mod interner;
34mod mapping; 36mod mapping;
35 37
36pub(super) trait ToChalk { 38pub(crate) trait ToChalk {
37 type Chalk; 39 type Chalk;
38 fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk; 40 fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk;
39 fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self; 41 fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self;
40} 42}
41 43
42pub(super) fn from_chalk<T, ChalkT>(db: &dyn HirDatabase, chalk: ChalkT) -> T 44pub(crate) fn from_chalk<T, ChalkT>(db: &dyn HirDatabase, chalk: ChalkT) -> T
43where 45where
44 T: ToChalk<Chalk = ChalkT>, 46 T: ToChalk<Chalk = ChalkT>,
45{ 47{
@@ -90,7 +92,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
90 ty: &Ty, 92 ty: &Ty,
91 binders: &CanonicalVarKinds<Interner>, 93 binders: &CanonicalVarKinds<Interner>,
92 ) -> Option<chalk_ir::TyVariableKind> { 94 ) -> Option<chalk_ir::TyVariableKind> {
93 if let Ty::BoundVar(bv) = ty { 95 if let TyKind::BoundVar(bv) = ty.interned(&Interner) {
94 let binders = binders.as_slice(&Interner); 96 let binders = binders.as_slice(&Interner);
95 if bv.debruijn == DebruijnIndex::INNERMOST { 97 if bv.debruijn == DebruijnIndex::INNERMOST {
96 if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind { 98 if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind {
@@ -175,10 +177,9 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
175 } 177 }
176 178
177 fn opaque_ty_data(&self, id: chalk_ir::OpaqueTyId<Interner>) -> Arc<OpaqueTyDatum> { 179 fn opaque_ty_data(&self, id: chalk_ir::OpaqueTyId<Interner>) -> Arc<OpaqueTyDatum> {
178 let interned_id = crate::db::InternedOpaqueTyId::from(id); 180 let full_id = self.db.lookup_intern_impl_trait_id(id.into());
179 let full_id = self.db.lookup_intern_impl_trait_id(interned_id);
180 let bound = match full_id { 181 let bound = match full_id {
181 crate::OpaqueTyId::ReturnTypeImplTrait(func, idx) => { 182 crate::ImplTraitId::ReturnTypeImplTrait(func, idx) => {
182 let datas = self 183 let datas = self
183 .db 184 .db
184 .return_type_impl_traits(func) 185 .return_type_impl_traits(func)
@@ -200,7 +201,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
200 let num_vars = datas.num_binders; 201 let num_vars = datas.num_binders;
201 make_binders(bound, num_vars) 202 make_binders(bound, num_vars)
202 } 203 }
203 crate::OpaqueTyId::AsyncBlockTypeImplTrait(..) => { 204 crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => {
204 if let Some((future_trait, future_output)) = self 205 if let Some((future_trait, future_output)) = self
205 .db 206 .db
206 .lang_item(self.krate, "future_trait".into()) 207 .lang_item(self.krate, "future_trait".into())
@@ -220,21 +221,25 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
220 let impl_bound = GenericPredicate::Implemented(TraitRef { 221 let impl_bound = GenericPredicate::Implemented(TraitRef {
221 trait_: future_trait, 222 trait_: future_trait,
222 // Self type as the first parameter. 223 // Self type as the first parameter.
223 substs: Substs::single(Ty::BoundVar(BoundVar { 224 substs: Substs::single(
224 debruijn: DebruijnIndex::INNERMOST, 225 TyKind::BoundVar(BoundVar {
225 index: 0, 226 debruijn: DebruijnIndex::INNERMOST,
226 })), 227 index: 0,
228 })
229 .intern(&Interner),
230 ),
227 }); 231 });
228 let proj_bound = GenericPredicate::Projection(ProjectionPredicate { 232 let proj_bound = GenericPredicate::Projection(ProjectionPredicate {
229 // The parameter of the opaque type. 233 // The parameter of the opaque type.
230 ty: Ty::BoundVar(BoundVar { debruijn: DebruijnIndex::ONE, index: 0 }), 234 ty: TyKind::BoundVar(BoundVar { debruijn: DebruijnIndex::ONE, index: 0 })
235 .intern(&Interner),
231 projection_ty: ProjectionTy { 236 projection_ty: ProjectionTy {
232 associated_ty: future_output, 237 associated_ty: to_assoc_type_id(future_output),
233 // Self type as the first parameter. 238 // Self type as the first parameter.
234 parameters: Substs::single(Ty::BoundVar(BoundVar::new( 239 parameters: Substs::single(
235 DebruijnIndex::INNERMOST, 240 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
236 0, 241 .intern(&Interner),
237 ))), 242 ),
238 }, 243 },
239 }); 244 });
240 let bound = OpaqueTyDatumBound { 245 let bound = OpaqueTyDatumBound {
@@ -263,7 +268,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
263 268
264 fn hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner> { 269 fn hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner> {
265 // FIXME: actually provide the hidden type; it is relevant for auto traits 270 // FIXME: actually provide the hidden type; it is relevant for auto traits
266 Ty::Unknown.to_chalk(self.db) 271 TyKind::Unknown.intern(&Interner).to_chalk(self.db)
267 } 272 }
268 273
269 fn is_object_safe(&self, _trait_id: chalk_ir::TraitId<Interner>) -> bool { 274 fn is_object_safe(&self, _trait_id: chalk_ir::TraitId<Interner>) -> bool {
@@ -378,7 +383,7 @@ pub(crate) fn associated_ty_data_query(
378 id: AssocTypeId, 383 id: AssocTypeId,
379) -> Arc<AssociatedTyDatum> { 384) -> Arc<AssociatedTyDatum> {
380 debug!("associated_ty_data {:?}", id); 385 debug!("associated_ty_data {:?}", id);
381 let type_alias: TypeAliasId = from_chalk::<TypeAliasAsAssocType, _>(db, id).0; 386 let type_alias: TypeAliasId = from_assoc_type_id(id);
382 let trait_ = match type_alias.lookup(db.upcast()).container { 387 let trait_ = match type_alias.lookup(db.upcast()).container {
383 AssocContainerId::TraitId(t) => t, 388 AssocContainerId::TraitId(t) => t,
384 _ => panic!("associated type not in trait"), 389 _ => panic!("associated type not in trait"),
@@ -391,11 +396,12 @@ pub(crate) fn associated_ty_data_query(
391 let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast()); 396 let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast());
392 let ctx = crate::TyLoweringContext::new(db, &resolver) 397 let ctx = crate::TyLoweringContext::new(db, &resolver)
393 .with_type_param_mode(crate::lower::TypeParamLoweringMode::Variable); 398 .with_type_param_mode(crate::lower::TypeParamLoweringMode::Variable);
394 let self_ty = Ty::BoundVar(crate::BoundVar::new(crate::DebruijnIndex::INNERMOST, 0)); 399 let self_ty =
400 TyKind::BoundVar(BoundVar::new(crate::DebruijnIndex::INNERMOST, 0)).intern(&Interner);
395 let bounds = type_alias_data 401 let bounds = type_alias_data
396 .bounds 402 .bounds
397 .iter() 403 .iter()
398 .flat_map(|bound| GenericPredicate::from_type_bound(&ctx, bound, self_ty.clone())) 404 .flat_map(|bound| ctx.lower_type_bound(bound, self_ty.clone()))
399 .filter_map(|pred| generic_predicate_to_inline_bound(db, &pred, &self_ty)) 405 .filter_map(|pred| generic_predicate_to_inline_bound(db, &pred, &self_ty))
400 .map(|bound| make_binders(bound.shifted_in(&Interner), 0)) 406 .map(|bound| make_binders(bound.shifted_in(&Interner), 0))
401 .collect(); 407 .collect();
@@ -432,10 +438,8 @@ pub(crate) fn trait_datum_query(
432 fundamental: false, 438 fundamental: false,
433 }; 439 };
434 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars); 440 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
435 let associated_ty_ids = trait_data 441 let associated_ty_ids =
436 .associated_types() 442 trait_data.associated_types().map(|type_alias| to_assoc_type_id(type_alias)).collect();
437 .map(|type_alias| TypeAliasAsAssocType(type_alias).to_chalk(db))
438 .collect();
439 let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses }; 443 let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses };
440 let well_known = 444 let well_known =
441 lang_attr(db.upcast(), trait_).and_then(|name| well_known_trait_from_lang_attr(&name)); 445 lang_attr(db.upcast(), trait_).and_then(|name| well_known_trait_from_lang_attr(&name));
@@ -487,19 +491,14 @@ pub(crate) fn struct_datum_query(
487 struct_id: AdtId, 491 struct_id: AdtId,
488) -> Arc<StructDatum> { 492) -> Arc<StructDatum> {
489 debug!("struct_datum {:?}", struct_id); 493 debug!("struct_datum {:?}", struct_id);
490 let type_ctor = Ty::Adt(struct_id, Substs::empty());
491 let chalk_ir::AdtId(adt_id) = struct_id; 494 let chalk_ir::AdtId(adt_id) = struct_id;
492 debug!("struct {:?} = {:?}", struct_id, type_ctor);
493 let num_params = generics(db.upcast(), adt_id.into()).len(); 495 let num_params = generics(db.upcast(), adt_id.into()).len();
494 let upstream = adt_id.module(db.upcast()).krate() != krate; 496 let upstream = adt_id.module(db.upcast()).krate() != krate;
495 let where_clauses = type_ctor 497 let where_clauses = {
496 .as_generic_def() 498 let generic_params = generics(db.upcast(), adt_id.into());
497 .map(|generic_def| { 499 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
498 let generic_params = generics(db.upcast(), generic_def); 500 convert_where_clauses(db, adt_id.into(), &bound_vars)
499 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 501 };
500 convert_where_clauses(db, generic_def, &bound_vars)
501 })
502 .unwrap_or_else(Vec::new);
503 let flags = rust_ir::AdtFlags { 502 let flags = rust_ir::AdtFlags {
504 upstream, 503 upstream,
505 // FIXME set fundamental and phantom_data flags correctly 504 // FIXME set fundamental and phantom_data flags correctly
@@ -622,7 +621,7 @@ fn type_alias_associated_ty_value(
622 let value_bound = rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) }; 621 let value_bound = rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) };
623 let value = rust_ir::AssociatedTyValue { 622 let value = rust_ir::AssociatedTyValue {
624 impl_id: impl_id.to_chalk(db), 623 impl_id: impl_id.to_chalk(db),
625 associated_ty_id: TypeAliasAsAssocType(assoc_ty).to_chalk(db), 624 associated_ty_id: to_assoc_type_id(assoc_ty),
626 value: make_binders(value_bound, ty.num_binders), 625 value: make_binders(value_bound, ty.num_binders),
627 }; 626 };
628 Arc::new(value) 627 Arc::new(value)
@@ -716,14 +715,14 @@ impl From<crate::db::InternedOpaqueTyId> for OpaqueTyId {
716 } 715 }
717} 716}
718 717
719impl From<chalk_ir::ClosureId<Interner>> for crate::db::ClosureId { 718impl From<chalk_ir::ClosureId<Interner>> for crate::db::InternedClosureId {
720 fn from(id: chalk_ir::ClosureId<Interner>) -> Self { 719 fn from(id: chalk_ir::ClosureId<Interner>) -> Self {
721 Self::from_intern_id(id.0) 720 Self::from_intern_id(id.0)
722 } 721 }
723} 722}
724 723
725impl From<crate::db::ClosureId> for chalk_ir::ClosureId<Interner> { 724impl From<crate::db::InternedClosureId> for chalk_ir::ClosureId<Interner> {
726 fn from(id: crate::db::ClosureId) -> Self { 725 fn from(id: crate::db::InternedClosureId) -> Self {
727 chalk_ir::ClosureId(id.as_intern_id()) 726 chalk_ir::ClosureId(id.as_intern_id())
728 } 727 }
729} 728}
diff --git a/crates/hir_ty/src/traits/chalk/interner.rs b/crates/hir_ty/src/traits/chalk/interner.rs
index 54bd1c724..1dc3f497d 100644
--- a/crates/hir_ty/src/traits/chalk/interner.rs
+++ b/crates/hir_ty/src/traits/chalk/interner.rs
@@ -12,7 +12,6 @@ pub struct Interner;
12 12
13pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>; 13pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
14pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>; 14pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;
15pub(crate) type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
16pub(crate) type TraitId = chalk_ir::TraitId<Interner>; 15pub(crate) type TraitId = chalk_ir::TraitId<Interner>;
17pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>; 16pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>;
18pub(crate) type AdtId = chalk_ir::AdtId<Interner>; 17pub(crate) type AdtId = chalk_ir::AdtId<Interner>;
@@ -21,7 +20,6 @@ pub(crate) type ImplId = chalk_ir::ImplId<Interner>;
21pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>; 20pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>;
22pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>; 21pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>;
23pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>; 22pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>;
24pub(crate) type FnDefId = chalk_ir::FnDefId<Interner>;
25pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>; 23pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>;
26pub(crate) type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>; 24pub(crate) type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
27pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>; 25pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>;
diff --git a/crates/hir_ty/src/traits/chalk/mapping.rs b/crates/hir_ty/src/traits/chalk/mapping.rs
index 3a08b67e9..2a66a2310 100644
--- a/crates/hir_ty/src/traits/chalk/mapping.rs
+++ b/crates/hir_ty/src/traits/chalk/mapping.rs
@@ -3,10 +3,7 @@
3//! Chalk (in both directions); plus some helper functions for more specialized 3//! Chalk (in both directions); plus some helper functions for more specialized
4//! conversions. 4//! conversions.
5 5
6use chalk_ir::{ 6use chalk_ir::{cast::Cast, fold::shift::Shift, interner::HasInterner, LifetimeData};
7 cast::Cast, fold::shift::Shift, interner::HasInterner, LifetimeData, PlaceholderIndex,
8 UniverseIndex,
9};
10use chalk_solve::rust_ir; 7use chalk_solve::rust_ir;
11 8
12use base_db::salsa::InternKey; 9use base_db::salsa::InternKey;
@@ -14,10 +11,11 @@ use hir_def::{AssocContainerId, GenericDefId, Lookup, TypeAliasId};
14 11
15use crate::{ 12use crate::{
16 db::HirDatabase, 13 db::HirDatabase,
14 from_assoc_type_id,
17 primitive::UintTy, 15 primitive::UintTy,
18 traits::{Canonical, Obligation}, 16 traits::{Canonical, Obligation},
19 AliasTy, CallableDefId, FnPointer, FnSig, GenericPredicate, InEnvironment, OpaqueTy, 17 AliasTy, CallableDefId, FnPointer, FnSig, GenericPredicate, InEnvironment, OpaqueTy,
20 OpaqueTyId, ProjectionPredicate, ProjectionTy, Scalar, Substs, TraitEnvironment, TraitRef, Ty, 18 ProjectionPredicate, ProjectionTy, Scalar, Substs, TraitRef, Ty,
21}; 19};
22 20
23use super::interner::*; 21use super::interner::*;
@@ -26,10 +24,10 @@ use super::*;
26impl ToChalk for Ty { 24impl ToChalk for Ty {
27 type Chalk = chalk_ir::Ty<Interner>; 25 type Chalk = chalk_ir::Ty<Interner>;
28 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Ty<Interner> { 26 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Ty<Interner> {
29 match self { 27 match self.0 {
30 Ty::Ref(m, parameters) => ref_to_chalk(db, m, parameters), 28 TyKind::Ref(m, parameters) => ref_to_chalk(db, m, parameters),
31 Ty::Array(parameters) => array_to_chalk(db, parameters), 29 TyKind::Array(parameters) => array_to_chalk(db, parameters),
32 Ty::Function(FnPointer { sig: FnSig { variadic }, substs, .. }) => { 30 TyKind::Function(FnPointer { sig: FnSig { variadic }, substs, .. }) => {
33 let substitution = chalk_ir::FnSubst(substs.to_chalk(db).shifted_in(&Interner)); 31 let substitution = chalk_ir::FnSubst(substs.to_chalk(db).shifted_in(&Interner));
34 chalk_ir::TyKind::Function(chalk_ir::FnPointer { 32 chalk_ir::TyKind::Function(chalk_ir::FnPointer {
35 num_binders: 0, 33 num_binders: 0,
@@ -38,58 +36,49 @@ impl ToChalk for Ty {
38 }) 36 })
39 .intern(&Interner) 37 .intern(&Interner)
40 } 38 }
41 Ty::AssociatedType(type_alias, substs) => { 39 TyKind::AssociatedType(assoc_type_id, substs) => {
42 let assoc_type = TypeAliasAsAssocType(type_alias);
43 let assoc_type_id = assoc_type.to_chalk(db);
44 let substitution = substs.to_chalk(db); 40 let substitution = substs.to_chalk(db);
45 chalk_ir::TyKind::AssociatedType(assoc_type_id, substitution).intern(&Interner) 41 chalk_ir::TyKind::AssociatedType(assoc_type_id, substitution).intern(&Interner)
46 } 42 }
47 43
48 Ty::OpaqueType(impl_trait_id, substs) => { 44 TyKind::OpaqueType(id, substs) => {
49 let id = impl_trait_id.to_chalk(db);
50 let substitution = substs.to_chalk(db); 45 let substitution = substs.to_chalk(db);
51 chalk_ir::TyKind::OpaqueType(id, substitution).intern(&Interner) 46 chalk_ir::TyKind::OpaqueType(id, substitution).intern(&Interner)
52 } 47 }
53 48
54 Ty::ForeignType(type_alias) => { 49 TyKind::ForeignType(id) => chalk_ir::TyKind::Foreign(id).intern(&Interner),
55 let foreign_type = TypeAliasAsForeignType(type_alias);
56 let foreign_type_id = foreign_type.to_chalk(db);
57 chalk_ir::TyKind::Foreign(foreign_type_id).intern(&Interner)
58 }
59 50
60 Ty::Scalar(scalar) => chalk_ir::TyKind::Scalar(scalar).intern(&Interner), 51 TyKind::Scalar(scalar) => chalk_ir::TyKind::Scalar(scalar).intern(&Interner),
61 52
62 Ty::Tuple(cardinality, substs) => { 53 TyKind::Tuple(cardinality, substs) => {
63 let substitution = substs.to_chalk(db); 54 let substitution = substs.to_chalk(db);
64 chalk_ir::TyKind::Tuple(cardinality.into(), substitution).intern(&Interner) 55 chalk_ir::TyKind::Tuple(cardinality.into(), substitution).intern(&Interner)
65 } 56 }
66 Ty::Raw(mutability, substs) => { 57 TyKind::Raw(mutability, substs) => {
67 let ty = substs[0].clone().to_chalk(db); 58 let ty = substs[0].clone().to_chalk(db);
68 chalk_ir::TyKind::Raw(mutability, ty).intern(&Interner) 59 chalk_ir::TyKind::Raw(mutability, ty).intern(&Interner)
69 } 60 }
70 Ty::Slice(substs) => { 61 TyKind::Slice(substs) => {
71 chalk_ir::TyKind::Slice(substs[0].clone().to_chalk(db)).intern(&Interner) 62 chalk_ir::TyKind::Slice(substs[0].clone().to_chalk(db)).intern(&Interner)
72 } 63 }
73 Ty::Str => chalk_ir::TyKind::Str.intern(&Interner), 64 TyKind::Str => chalk_ir::TyKind::Str.intern(&Interner),
74 Ty::FnDef(callable_def, substs) => { 65 TyKind::FnDef(id, substs) => {
75 let id = callable_def.to_chalk(db);
76 let substitution = substs.to_chalk(db); 66 let substitution = substs.to_chalk(db);
77 chalk_ir::TyKind::FnDef(id, substitution).intern(&Interner) 67 chalk_ir::TyKind::FnDef(id, substitution).intern(&Interner)
78 } 68 }
79 Ty::Never => chalk_ir::TyKind::Never.intern(&Interner), 69 TyKind::Never => chalk_ir::TyKind::Never.intern(&Interner),
80 70
81 Ty::Closure(def, expr, substs) => { 71 TyKind::Closure(closure_id, substs) => {
82 let closure_id = db.intern_closure((def, expr));
83 let substitution = substs.to_chalk(db); 72 let substitution = substs.to_chalk(db);
84 chalk_ir::TyKind::Closure(closure_id.into(), substitution).intern(&Interner) 73 chalk_ir::TyKind::Closure(closure_id, substitution).intern(&Interner)
85 } 74 }
86 75
87 Ty::Adt(adt_id, substs) => { 76 TyKind::Adt(adt_id, substs) => {
88 let substitution = substs.to_chalk(db); 77 let substitution = substs.to_chalk(db);
89 chalk_ir::TyKind::Adt(adt_id, substitution).intern(&Interner) 78 chalk_ir::TyKind::Adt(adt_id, substitution).intern(&Interner)
90 } 79 }
91 Ty::Alias(AliasTy::Projection(proj_ty)) => { 80 TyKind::Alias(AliasTy::Projection(proj_ty)) => {
92 let associated_ty_id = TypeAliasAsAssocType(proj_ty.associated_ty).to_chalk(db); 81 let associated_ty_id = proj_ty.associated_ty;
93 let substitution = proj_ty.parameters.to_chalk(db); 82 let substitution = proj_ty.parameters.to_chalk(db);
94 chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy { 83 chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
95 associated_ty_id, 84 associated_ty_id,
@@ -98,17 +87,10 @@ impl ToChalk for Ty {
98 .cast(&Interner) 87 .cast(&Interner)
99 .intern(&Interner) 88 .intern(&Interner)
100 } 89 }
101 Ty::Placeholder(id) => { 90 TyKind::Placeholder(idx) => idx.to_ty::<Interner>(&Interner),
102 let interned_id = db.intern_type_param_id(id); 91 TyKind::BoundVar(idx) => chalk_ir::TyKind::BoundVar(idx).intern(&Interner),
103 PlaceholderIndex { 92 TyKind::InferenceVar(..) => panic!("uncanonicalized infer ty"),
104 ui: UniverseIndex::ROOT, 93 TyKind::Dyn(predicates) => {
105 idx: interned_id.as_intern_id().as_usize(),
106 }
107 .to_ty::<Interner>(&Interner)
108 }
109 Ty::BoundVar(idx) => chalk_ir::TyKind::BoundVar(idx).intern(&Interner),
110 Ty::InferenceVar(..) => panic!("uncanonicalized infer ty"),
111 Ty::Dyn(predicates) => {
112 let where_clauses = chalk_ir::QuantifiedWhereClauses::from_iter( 94 let where_clauses = chalk_ir::QuantifiedWhereClauses::from_iter(
113 &Interner, 95 &Interner,
114 predicates.iter().filter(|p| !p.is_error()).cloned().map(|p| p.to_chalk(db)), 96 predicates.iter().filter(|p| !p.is_error()).cloned().map(|p| p.to_chalk(db)),
@@ -119,8 +101,8 @@ impl ToChalk for Ty {
119 }; 101 };
120 chalk_ir::TyKind::Dyn(bounded_ty).intern(&Interner) 102 chalk_ir::TyKind::Dyn(bounded_ty).intern(&Interner)
121 } 103 }
122 Ty::Alias(AliasTy::Opaque(opaque_ty)) => { 104 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
123 let opaque_ty_id = opaque_ty.opaque_ty_id.to_chalk(db); 105 let opaque_ty_id = opaque_ty.opaque_ty_id;
124 let substitution = opaque_ty.parameters.to_chalk(db); 106 let substitution = opaque_ty.parameters.to_chalk(db);
125 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy { 107 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy {
126 opaque_ty_id, 108 opaque_ty_id,
@@ -128,30 +110,23 @@ impl ToChalk for Ty {
128 })) 110 }))
129 .intern(&Interner) 111 .intern(&Interner)
130 } 112 }
131 Ty::Unknown => chalk_ir::TyKind::Error.intern(&Interner), 113 TyKind::Unknown => chalk_ir::TyKind::Error.intern(&Interner),
132 } 114 }
133 } 115 }
134 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self { 116 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self {
135 match chalk.data(&Interner).kind.clone() { 117 match chalk.data(&Interner).kind.clone() {
136 chalk_ir::TyKind::Error => Ty::Unknown, 118 chalk_ir::TyKind::Error => TyKind::Unknown,
137 chalk_ir::TyKind::Array(ty, _size) => Ty::Array(Substs::single(from_chalk(db, ty))), 119 chalk_ir::TyKind::Array(ty, _size) => TyKind::Array(Substs::single(from_chalk(db, ty))),
138 chalk_ir::TyKind::Placeholder(idx) => { 120 chalk_ir::TyKind::Placeholder(idx) => TyKind::Placeholder(idx),
139 assert_eq!(idx.ui, UniverseIndex::ROOT);
140 let interned_id = crate::db::GlobalTypeParamId::from_intern_id(
141 crate::salsa::InternId::from(idx.idx),
142 );
143 Ty::Placeholder(db.lookup_intern_type_param_id(interned_id))
144 }
145 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Projection(proj)) => { 121 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Projection(proj)) => {
146 let associated_ty = 122 let associated_ty = proj.associated_ty_id;
147 from_chalk::<TypeAliasAsAssocType, _>(db, proj.associated_ty_id).0;
148 let parameters = from_chalk(db, proj.substitution); 123 let parameters = from_chalk(db, proj.substitution);
149 Ty::Alias(AliasTy::Projection(ProjectionTy { associated_ty, parameters })) 124 TyKind::Alias(AliasTy::Projection(ProjectionTy { associated_ty, parameters }))
150 } 125 }
151 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(opaque_ty)) => { 126 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(opaque_ty)) => {
152 let impl_trait_id = from_chalk(db, opaque_ty.opaque_ty_id); 127 let opaque_ty_id = opaque_ty.opaque_ty_id;
153 let parameters = from_chalk(db, opaque_ty.substitution); 128 let parameters = from_chalk(db, opaque_ty.substitution);
154 Ty::Alias(AliasTy::Opaque(OpaqueTy { opaque_ty_id: impl_trait_id, parameters })) 129 TyKind::Alias(AliasTy::Opaque(OpaqueTy { opaque_ty_id, parameters }))
155 } 130 }
156 chalk_ir::TyKind::Function(chalk_ir::FnPointer { 131 chalk_ir::TyKind::Function(chalk_ir::FnPointer {
157 num_binders, 132 num_binders,
@@ -164,14 +139,14 @@ impl ToChalk for Ty {
164 db, 139 db,
165 substitution.0.shifted_out(&Interner).expect("fn ptr should have no binders"), 140 substitution.0.shifted_out(&Interner).expect("fn ptr should have no binders"),
166 ); 141 );
167 Ty::Function(FnPointer { 142 TyKind::Function(FnPointer {
168 num_args: (substs.len() - 1), 143 num_args: (substs.len() - 1),
169 sig: FnSig { variadic }, 144 sig: FnSig { variadic },
170 substs, 145 substs,
171 }) 146 })
172 } 147 }
173 chalk_ir::TyKind::BoundVar(idx) => Ty::BoundVar(idx), 148 chalk_ir::TyKind::BoundVar(idx) => TyKind::BoundVar(idx),
174 chalk_ir::TyKind::InferenceVar(_iv, _kind) => Ty::Unknown, 149 chalk_ir::TyKind::InferenceVar(_iv, _kind) => TyKind::Unknown,
175 chalk_ir::TyKind::Dyn(where_clauses) => { 150 chalk_ir::TyKind::Dyn(where_clauses) => {
176 assert_eq!(where_clauses.bounds.binders.len(&Interner), 1); 151 assert_eq!(where_clauses.bounds.binders.len(&Interner), 1);
177 let predicates = where_clauses 152 let predicates = where_clauses
@@ -180,49 +155,43 @@ impl ToChalk for Ty {
180 .iter(&Interner) 155 .iter(&Interner)
181 .map(|c| from_chalk(db, c.clone())) 156 .map(|c| from_chalk(db, c.clone()))
182 .collect(); 157 .collect();
183 Ty::Dyn(predicates) 158 TyKind::Dyn(predicates)
184 } 159 }
185 160
186 chalk_ir::TyKind::Adt(adt_id, subst) => Ty::Adt(adt_id, from_chalk(db, subst)), 161 chalk_ir::TyKind::Adt(adt_id, subst) => TyKind::Adt(adt_id, from_chalk(db, subst)),
187 chalk_ir::TyKind::AssociatedType(type_id, subst) => Ty::AssociatedType( 162 chalk_ir::TyKind::AssociatedType(type_id, subst) => {
188 from_chalk::<TypeAliasAsAssocType, _>(db, type_id).0, 163 TyKind::AssociatedType(type_id, from_chalk(db, subst))
189 from_chalk(db, subst), 164 }
190 ),
191 165
192 chalk_ir::TyKind::OpaqueType(opaque_type_id, subst) => { 166 chalk_ir::TyKind::OpaqueType(opaque_type_id, subst) => {
193 Ty::OpaqueType(from_chalk(db, opaque_type_id), from_chalk(db, subst)) 167 TyKind::OpaqueType(opaque_type_id, from_chalk(db, subst))
194 } 168 }
195 169
196 chalk_ir::TyKind::Scalar(scalar) => Ty::Scalar(scalar), 170 chalk_ir::TyKind::Scalar(scalar) => TyKind::Scalar(scalar),
197 chalk_ir::TyKind::Tuple(cardinality, subst) => { 171 chalk_ir::TyKind::Tuple(cardinality, subst) => {
198 Ty::Tuple(cardinality, from_chalk(db, subst)) 172 TyKind::Tuple(cardinality, from_chalk(db, subst))
199 } 173 }
200 chalk_ir::TyKind::Raw(mutability, ty) => { 174 chalk_ir::TyKind::Raw(mutability, ty) => {
201 Ty::Raw(mutability, Substs::single(from_chalk(db, ty))) 175 TyKind::Raw(mutability, Substs::single(from_chalk(db, ty)))
202 } 176 }
203 chalk_ir::TyKind::Slice(ty) => Ty::Slice(Substs::single(from_chalk(db, ty))), 177 chalk_ir::TyKind::Slice(ty) => TyKind::Slice(Substs::single(from_chalk(db, ty))),
204 chalk_ir::TyKind::Ref(mutability, _lifetime, ty) => { 178 chalk_ir::TyKind::Ref(mutability, _lifetime, ty) => {
205 Ty::Ref(mutability, Substs::single(from_chalk(db, ty))) 179 TyKind::Ref(mutability, Substs::single(from_chalk(db, ty)))
206 } 180 }
207 chalk_ir::TyKind::Str => Ty::Str, 181 chalk_ir::TyKind::Str => TyKind::Str,
208 chalk_ir::TyKind::Never => Ty::Never, 182 chalk_ir::TyKind::Never => TyKind::Never,
209 183
210 chalk_ir::TyKind::FnDef(fn_def_id, subst) => { 184 chalk_ir::TyKind::FnDef(fn_def_id, subst) => {
211 Ty::FnDef(from_chalk(db, fn_def_id), from_chalk(db, subst)) 185 TyKind::FnDef(fn_def_id, from_chalk(db, subst))
212 } 186 }
213 187
214 chalk_ir::TyKind::Closure(id, subst) => { 188 chalk_ir::TyKind::Closure(id, subst) => TyKind::Closure(id, from_chalk(db, subst)),
215 let id: crate::db::ClosureId = id.into();
216 let (def, expr) = db.lookup_intern_closure(id);
217 Ty::Closure(def, expr, from_chalk(db, subst))
218 }
219 189
220 chalk_ir::TyKind::Foreign(foreign_def_id) => { 190 chalk_ir::TyKind::Foreign(foreign_def_id) => TyKind::ForeignType(foreign_def_id),
221 Ty::ForeignType(from_chalk::<TypeAliasAsForeignType, _>(db, foreign_def_id).0)
222 }
223 chalk_ir::TyKind::Generator(_, _) => unimplemented!(), // FIXME 191 chalk_ir::TyKind::Generator(_, _) => unimplemented!(), // FIXME
224 chalk_ir::TyKind::GeneratorWitness(_, _) => unimplemented!(), // FIXME 192 chalk_ir::TyKind::GeneratorWitness(_, _) => unimplemented!(), // FIXME
225 } 193 }
194 .intern(&Interner)
226 } 195 }
227} 196}
228 197
@@ -298,21 +267,6 @@ impl ToChalk for hir_def::TraitId {
298 } 267 }
299} 268}
300 269
301impl ToChalk for OpaqueTyId {
302 type Chalk = chalk_ir::OpaqueTyId<Interner>;
303
304 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::OpaqueTyId<Interner> {
305 db.intern_impl_trait_id(self).into()
306 }
307
308 fn from_chalk(
309 db: &dyn HirDatabase,
310 opaque_ty_id: chalk_ir::OpaqueTyId<Interner>,
311 ) -> OpaqueTyId {
312 db.lookup_intern_impl_trait_id(opaque_ty_id.into())
313 }
314}
315
316impl ToChalk for hir_def::ImplId { 270impl ToChalk for hir_def::ImplId {
317 type Chalk = ImplId; 271 type Chalk = ImplId;
318 272
@@ -337,34 +291,6 @@ impl ToChalk for CallableDefId {
337 } 291 }
338} 292}
339 293
340pub(crate) struct TypeAliasAsAssocType(pub(crate) TypeAliasId);
341
342impl ToChalk for TypeAliasAsAssocType {
343 type Chalk = AssocTypeId;
344
345 fn to_chalk(self, _db: &dyn HirDatabase) -> AssocTypeId {
346 chalk_ir::AssocTypeId(self.0.as_intern_id())
347 }
348
349 fn from_chalk(_db: &dyn HirDatabase, assoc_type_id: AssocTypeId) -> TypeAliasAsAssocType {
350 TypeAliasAsAssocType(InternKey::from_intern_id(assoc_type_id.0))
351 }
352}
353
354pub(crate) struct TypeAliasAsForeignType(pub(crate) TypeAliasId);
355
356impl ToChalk for TypeAliasAsForeignType {
357 type Chalk = ForeignDefId;
358
359 fn to_chalk(self, _db: &dyn HirDatabase) -> ForeignDefId {
360 chalk_ir::ForeignDefId(self.0.as_intern_id())
361 }
362
363 fn from_chalk(_db: &dyn HirDatabase, foreign_def_id: ForeignDefId) -> TypeAliasAsForeignType {
364 TypeAliasAsForeignType(InternKey::from_intern_id(foreign_def_id.0))
365 }
366}
367
368pub(crate) struct TypeAliasAsValue(pub(crate) TypeAliasId); 294pub(crate) struct TypeAliasAsValue(pub(crate) TypeAliasId);
369 295
370impl ToChalk for TypeAliasAsValue { 296impl ToChalk for TypeAliasAsValue {
@@ -446,7 +372,7 @@ impl ToChalk for ProjectionTy {
446 372
447 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::ProjectionTy<Interner> { 373 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::ProjectionTy<Interner> {
448 chalk_ir::ProjectionTy { 374 chalk_ir::ProjectionTy {
449 associated_ty_id: TypeAliasAsAssocType(self.associated_ty).to_chalk(db), 375 associated_ty_id: self.associated_ty,
450 substitution: self.parameters.to_chalk(db), 376 substitution: self.parameters.to_chalk(db),
451 } 377 }
452 } 378 }
@@ -456,11 +382,7 @@ impl ToChalk for ProjectionTy {
456 projection_ty: chalk_ir::ProjectionTy<Interner>, 382 projection_ty: chalk_ir::ProjectionTy<Interner>,
457 ) -> ProjectionTy { 383 ) -> ProjectionTy {
458 ProjectionTy { 384 ProjectionTy {
459 associated_ty: from_chalk::<TypeAliasAsAssocType, _>( 385 associated_ty: projection_ty.associated_ty_id,
460 db,
461 projection_ty.associated_ty_id,
462 )
463 .0,
464 parameters: from_chalk(db, projection_ty.substitution), 386 parameters: from_chalk(db, projection_ty.substitution),
465 } 387 }
466 } 388 }
@@ -536,31 +458,6 @@ where
536 } 458 }
537} 459}
538 460
539impl ToChalk for Arc<TraitEnvironment> {
540 type Chalk = chalk_ir::Environment<Interner>;
541
542 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Environment<Interner> {
543 let mut clauses = Vec::new();
544 for pred in &self.predicates {
545 if pred.is_error() {
546 // for env, we just ignore errors
547 continue;
548 }
549 let program_clause: chalk_ir::ProgramClause<Interner> =
550 pred.clone().to_chalk(db).cast(&Interner);
551 clauses.push(program_clause.into_from_env_clause(&Interner));
552 }
553 chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses)
554 }
555
556 fn from_chalk(
557 _db: &dyn HirDatabase,
558 _env: chalk_ir::Environment<Interner>,
559 ) -> Arc<TraitEnvironment> {
560 unimplemented!()
561 }
562}
563
564impl<T: ToChalk> ToChalk for InEnvironment<T> 461impl<T: ToChalk> ToChalk for InEnvironment<T>
565where 462where
566 T::Chalk: chalk_ir::interner::HasInterner<Interner = Interner>, 463 T::Chalk: chalk_ir::interner::HasInterner<Interner = Interner>,
@@ -569,19 +466,16 @@ where
569 466
570 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> { 467 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> {
571 chalk_ir::InEnvironment { 468 chalk_ir::InEnvironment {
572 environment: self.environment.to_chalk(db), 469 environment: self.environment.env.clone(),
573 goal: self.value.to_chalk(db), 470 goal: self.value.to_chalk(db),
574 } 471 }
575 } 472 }
576 473
577 fn from_chalk( 474 fn from_chalk(
578 db: &dyn HirDatabase, 475 _db: &dyn HirDatabase,
579 in_env: chalk_ir::InEnvironment<T::Chalk>, 476 _in_env: chalk_ir::InEnvironment<T::Chalk>,
580 ) -> InEnvironment<T> { 477 ) -> InEnvironment<T> {
581 InEnvironment { 478 unimplemented!()
582 environment: from_chalk(db, in_env.environment),
583 value: from_chalk(db, in_env.goal),
584 }
585 } 479 }
586} 480}
587 481
@@ -642,7 +536,10 @@ pub(super) fn generic_predicate_to_inline_bound(
642 if &proj.projection_ty.parameters[0] != self_ty { 536 if &proj.projection_ty.parameters[0] != self_ty {
643 return None; 537 return None;
644 } 538 }
645 let trait_ = match proj.projection_ty.associated_ty.lookup(db.upcast()).container { 539 let trait_ = match from_assoc_type_id(proj.projection_ty.associated_ty)
540 .lookup(db.upcast())
541 .container
542 {
646 AssocContainerId::TraitId(t) => t, 543 AssocContainerId::TraitId(t) => t,
647 _ => panic!("associated type not in trait"), 544 _ => panic!("associated type not in trait"),
648 }; 545 };
@@ -653,8 +550,7 @@ pub(super) fn generic_predicate_to_inline_bound(
653 let alias_eq_bound = rust_ir::AliasEqBound { 550 let alias_eq_bound = rust_ir::AliasEqBound {
654 value: proj.ty.clone().to_chalk(db), 551 value: proj.ty.clone().to_chalk(db),
655 trait_bound: rust_ir::TraitBound { trait_id: trait_.to_chalk(db), args_no_self }, 552 trait_bound: rust_ir::TraitBound { trait_id: trait_.to_chalk(db), args_no_self },
656 associated_ty_id: TypeAliasAsAssocType(proj.projection_ty.associated_ty) 553 associated_ty_id: proj.projection_ty.associated_ty,
657 .to_chalk(db),
658 parameters: Vec::new(), // FIXME we don't support generic associated types yet 554 parameters: Vec::new(), // FIXME we don't support generic associated types yet
659 }; 555 };
660 Some(rust_ir::InlineBound::AliasEqBound(alias_eq_bound)) 556 Some(rust_ir::InlineBound::AliasEqBound(alias_eq_bound))
diff --git a/crates/hir_ty/src/traits/chalk/tls.rs b/crates/hir_ty/src/traits/chalk/tls.rs
index 75b16172e..8892a63a9 100644
--- a/crates/hir_ty/src/traits/chalk/tls.rs
+++ b/crates/hir_ty/src/traits/chalk/tls.rs
@@ -4,8 +4,8 @@ use std::fmt;
4use chalk_ir::{AliasTy, GenericArg, Goal, Goals, Lifetime, ProgramClauseImplication}; 4use chalk_ir::{AliasTy, GenericArg, Goal, Goals, Lifetime, ProgramClauseImplication};
5use itertools::Itertools; 5use itertools::Itertools;
6 6
7use super::{from_chalk, Interner, TypeAliasAsAssocType}; 7use super::{from_chalk, Interner};
8use crate::{db::HirDatabase, CallableDefId}; 8use crate::{db::HirDatabase, from_assoc_type_id, CallableDefId};
9use hir_def::{AdtId, AssocContainerId, Lookup, TypeAliasId}; 9use hir_def::{AdtId, AssocContainerId, Lookup, TypeAliasId};
10 10
11pub(crate) use unsafe_tls::{set_current_program, with_current_program}; 11pub(crate) use unsafe_tls::{set_current_program, with_current_program};
@@ -41,7 +41,7 @@ impl DebugContext<'_> {
41 id: super::AssocTypeId, 41 id: super::AssocTypeId,
42 fmt: &mut fmt::Formatter<'_>, 42 fmt: &mut fmt::Formatter<'_>,
43 ) -> Result<(), fmt::Error> { 43 ) -> Result<(), fmt::Error> {
44 let type_alias: TypeAliasId = from_chalk::<TypeAliasAsAssocType, _>(self.0, id).0; 44 let type_alias: TypeAliasId = from_assoc_type_id(id);
45 let type_alias_data = self.0.type_alias_data(type_alias); 45 let type_alias_data = self.0.type_alias_data(type_alias);
46 let trait_ = match type_alias.lookup(self.0.upcast()).container { 46 let trait_ = match type_alias.lookup(self.0.upcast()).container {
47 AssocContainerId::TraitId(t) => t, 47 AssocContainerId::TraitId(t) => t,
@@ -75,8 +75,7 @@ impl DebugContext<'_> {
75 projection_ty: &chalk_ir::ProjectionTy<Interner>, 75 projection_ty: &chalk_ir::ProjectionTy<Interner>,
76 fmt: &mut fmt::Formatter<'_>, 76 fmt: &mut fmt::Formatter<'_>,
77 ) -> Result<(), fmt::Error> { 77 ) -> Result<(), fmt::Error> {
78 let type_alias: TypeAliasId = 78 let type_alias = from_assoc_type_id(projection_ty.associated_ty_id);
79 from_chalk::<TypeAliasAsAssocType, _>(self.0, projection_ty.associated_ty_id).0;
80 let type_alias_data = self.0.type_alias_data(type_alias); 79 let type_alias_data = self.0.type_alias_data(type_alias);
81 let trait_ = match type_alias.lookup(self.0.upcast()).container { 80 let trait_ = match type_alias.lookup(self.0.upcast()).container {
82 AssocContainerId::TraitId(t) => t, 81 AssocContainerId::TraitId(t) => t,
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs
index 0a493d2f3..a8b169e87 100644
--- a/crates/ide/src/lib.rs
+++ b/crates/ide/src/lib.rs
@@ -447,6 +447,15 @@ impl Analysis {
447 self.with_db(|db| runnables::runnables(db, file_id)) 447 self.with_db(|db| runnables::runnables(db, file_id))
448 } 448 }
449 449
450 /// Returns the set of tests for the given file position.
451 pub fn related_tests(
452 &self,
453 position: FilePosition,
454 search_scope: Option<SearchScope>,
455 ) -> Cancelable<Vec<Runnable>> {
456 self.with_db(|db| runnables::related_tests(db, position, search_scope))
457 }
458
450 /// Computes syntax highlighting for the given file 459 /// Computes syntax highlighting for the given file
451 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> { 460 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> {
452 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false)) 461 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs
index 280565563..faa91541e 100644
--- a/crates/ide/src/runnables.rs
+++ b/crates/ide/src/runnables.rs
@@ -1,10 +1,17 @@
1use std::fmt; 1use std::fmt;
2 2
3use ast::NameOwner;
3use cfg::CfgExpr; 4use cfg::CfgExpr;
4use hir::{AsAssocItem, HasAttrs, HasSource, Semantics}; 5use hir::{AsAssocItem, HasAttrs, HasSource, Semantics};
5use ide_assists::utils::test_related_attribute; 6use ide_assists::utils::test_related_attribute;
6use ide_db::{defs::Definition, RootDatabase, SymbolKind}; 7use ide_db::{
8 base_db::{FilePosition, FileRange},
9 defs::Definition,
10 search::SearchScope,
11 RootDatabase, SymbolKind,
12};
7use itertools::Itertools; 13use itertools::Itertools;
14use rustc_hash::FxHashSet;
8use syntax::{ 15use syntax::{
9 ast::{self, AstNode, AttrsOwner}, 16 ast::{self, AstNode, AttrsOwner},
10 match_ast, SyntaxNode, 17 match_ast, SyntaxNode,
@@ -12,17 +19,17 @@ use syntax::{
12 19
13use crate::{ 20use crate::{
14 display::{ToNav, TryToNav}, 21 display::{ToNav, TryToNav},
15 FileId, NavigationTarget, 22 references, FileId, NavigationTarget,
16}; 23};
17 24
18#[derive(Debug, Clone)] 25#[derive(Debug, Clone, Hash, PartialEq, Eq)]
19pub struct Runnable { 26pub struct Runnable {
20 pub nav: NavigationTarget, 27 pub nav: NavigationTarget,
21 pub kind: RunnableKind, 28 pub kind: RunnableKind,
22 pub cfg: Option<CfgExpr>, 29 pub cfg: Option<CfgExpr>,
23} 30}
24 31
25#[derive(Debug, Clone)] 32#[derive(Debug, Clone, Hash, PartialEq, Eq)]
26pub enum TestId { 33pub enum TestId {
27 Name(String), 34 Name(String),
28 Path(String), 35 Path(String),
@@ -37,7 +44,7 @@ impl fmt::Display for TestId {
37 } 44 }
38} 45}
39 46
40#[derive(Debug, Clone)] 47#[derive(Debug, Clone, Hash, PartialEq, Eq)]
41pub enum RunnableKind { 48pub enum RunnableKind {
42 Test { test_id: TestId, attr: TestAttr }, 49 Test { test_id: TestId, attr: TestAttr },
43 TestMod { path: String }, 50 TestMod { path: String },
@@ -105,6 +112,105 @@ pub(crate) fn runnables(db: &RootDatabase, file_id: FileId) -> Vec<Runnable> {
105 res 112 res
106} 113}
107 114
115// Feature: Related Tests
116//
117// Provides a sneak peek of all tests where the current item is used.
118//
119// The simplest way to use this feature is via the context menu:
120// - Right-click on the selected item. The context menu opens.
121// - Select **Peek related tests**
122//
123// |===
124// | Editor | Action Name
125//
126// | VS Code | **Rust Analyzer: Peek related tests**
127// |===
128pub(crate) fn related_tests(
129 db: &RootDatabase,
130 position: FilePosition,
131 search_scope: Option<SearchScope>,
132) -> Vec<Runnable> {
133 let sema = Semantics::new(db);
134 let mut res: FxHashSet<Runnable> = FxHashSet::default();
135
136 find_related_tests(&sema, position, search_scope, &mut res);
137
138 res.into_iter().collect_vec()
139}
140
141fn find_related_tests(
142 sema: &Semantics<RootDatabase>,
143 position: FilePosition,
144 search_scope: Option<SearchScope>,
145 tests: &mut FxHashSet<Runnable>,
146) {
147 if let Some(refs) = references::find_all_refs(&sema, position, search_scope) {
148 for (file_id, refs) in refs.references {
149 let file = sema.parse(file_id);
150 let file = file.syntax();
151 let functions = refs.iter().filter_map(|(range, _)| {
152 let token = file.token_at_offset(range.start()).next()?;
153 let token = sema.descend_into_macros(token);
154 let syntax = token.parent();
155 syntax.ancestors().find_map(ast::Fn::cast)
156 });
157
158 for fn_def in functions {
159 if let Some(runnable) = as_test_runnable(&sema, &fn_def) {
160 // direct test
161 tests.insert(runnable);
162 } else if let Some(module) = parent_test_module(&sema, &fn_def) {
163 // indirect test
164 find_related_tests_in_module(sema, &fn_def, &module, tests);
165 }
166 }
167 }
168 }
169}
170
171fn find_related_tests_in_module(
172 sema: &Semantics<RootDatabase>,
173 fn_def: &ast::Fn,
174 parent_module: &hir::Module,
175 tests: &mut FxHashSet<Runnable>,
176) {
177 if let Some(fn_name) = fn_def.name() {
178 let mod_source = parent_module.definition_source(sema.db);
179 let range = match mod_source.value {
180 hir::ModuleSource::Module(m) => m.syntax().text_range(),
181 hir::ModuleSource::BlockExpr(b) => b.syntax().text_range(),
182 hir::ModuleSource::SourceFile(f) => f.syntax().text_range(),
183 };
184
185 let file_id = mod_source.file_id.original_file(sema.db);
186 let mod_scope = SearchScope::file_range(FileRange { file_id, range });
187 let fn_pos = FilePosition { file_id, offset: fn_name.syntax().text_range().start() };
188 find_related_tests(sema, fn_pos, Some(mod_scope), tests)
189 }
190}
191
192fn as_test_runnable(sema: &Semantics<RootDatabase>, fn_def: &ast::Fn) -> Option<Runnable> {
193 if test_related_attribute(&fn_def).is_some() {
194 let function = sema.to_def(fn_def)?;
195 runnable_fn(sema, function)
196 } else {
197 None
198 }
199}
200
201fn parent_test_module(sema: &Semantics<RootDatabase>, fn_def: &ast::Fn) -> Option<hir::Module> {
202 fn_def.syntax().ancestors().find_map(|node| {
203 let module = ast::Module::cast(node)?;
204 let module = sema.to_def(&module)?;
205
206 if has_test_function_or_multiple_test_submodules(sema, &module) {
207 Some(module)
208 } else {
209 None
210 }
211 })
212}
213
108fn runnables_mod(sema: &Semantics<RootDatabase>, acc: &mut Vec<Runnable>, module: hir::Module) { 214fn runnables_mod(sema: &Semantics<RootDatabase>, acc: &mut Vec<Runnable>, module: hir::Module) {
109 acc.extend(module.declarations(sema.db).into_iter().filter_map(|def| { 215 acc.extend(module.declarations(sema.db).into_iter().filter_map(|def| {
110 let runnable = match def { 216 let runnable = match def {
@@ -256,7 +362,7 @@ fn module_def_doctest(sema: &Semantics<RootDatabase>, def: hir::ModuleDef) -> Op
256 Some(res) 362 Some(res)
257} 363}
258 364
259#[derive(Debug, Copy, Clone)] 365#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
260pub struct TestAttr { 366pub struct TestAttr {
261 pub ignore: bool, 367 pub ignore: bool,
262} 368}
@@ -349,6 +455,12 @@ mod tests {
349 ); 455 );
350 } 456 }
351 457
458 fn check_tests(ra_fixture: &str, expect: Expect) {
459 let (analysis, position) = fixture::position(ra_fixture);
460 let tests = analysis.related_tests(position, None).unwrap();
461 expect.assert_debug_eq(&tests);
462 }
463
352 #[test] 464 #[test]
353 fn test_runnables() { 465 fn test_runnables() {
354 check( 466 check(
@@ -1074,4 +1186,224 @@ mod tests {
1074 "#]], 1186 "#]],
1075 ); 1187 );
1076 } 1188 }
1189
1190 #[test]
1191 fn find_no_tests() {
1192 check_tests(
1193 r#"
1194//- /lib.rs
1195fn foo$0() { };
1196"#,
1197 expect![[r#"
1198 []
1199 "#]],
1200 );
1201 }
1202
1203 #[test]
1204 fn find_direct_fn_test() {
1205 check_tests(
1206 r#"
1207//- /lib.rs
1208fn foo$0() { };
1209
1210mod tests {
1211 #[test]
1212 fn foo_test() {
1213 super::foo()
1214 }
1215}
1216"#,
1217 expect![[r#"
1218 [
1219 Runnable {
1220 nav: NavigationTarget {
1221 file_id: FileId(
1222 0,
1223 ),
1224 full_range: 31..85,
1225 focus_range: 46..54,
1226 name: "foo_test",
1227 kind: Function,
1228 },
1229 kind: Test {
1230 test_id: Path(
1231 "tests::foo_test",
1232 ),
1233 attr: TestAttr {
1234 ignore: false,
1235 },
1236 },
1237 cfg: None,
1238 },
1239 ]
1240 "#]],
1241 );
1242 }
1243
1244 #[test]
1245 fn find_direct_struct_test() {
1246 check_tests(
1247 r#"
1248//- /lib.rs
1249struct Fo$0o;
1250fn foo(arg: &Foo) { };
1251
1252mod tests {
1253 use super::*;
1254
1255 #[test]
1256 fn foo_test() {
1257 foo(Foo);
1258 }
1259}
1260"#,
1261 expect![[r#"
1262 [
1263 Runnable {
1264 nav: NavigationTarget {
1265 file_id: FileId(
1266 0,
1267 ),
1268 full_range: 71..122,
1269 focus_range: 86..94,
1270 name: "foo_test",
1271 kind: Function,
1272 },
1273 kind: Test {
1274 test_id: Path(
1275 "tests::foo_test",
1276 ),
1277 attr: TestAttr {
1278 ignore: false,
1279 },
1280 },
1281 cfg: None,
1282 },
1283 ]
1284 "#]],
1285 );
1286 }
1287
1288 #[test]
1289 fn find_indirect_fn_test() {
1290 check_tests(
1291 r#"
1292//- /lib.rs
1293fn foo$0() { };
1294
1295mod tests {
1296 use super::foo;
1297
1298 fn check1() {
1299 check2()
1300 }
1301
1302 fn check2() {
1303 foo()
1304 }
1305
1306 #[test]
1307 fn foo_test() {
1308 check1()
1309 }
1310}
1311"#,
1312 expect![[r#"
1313 [
1314 Runnable {
1315 nav: NavigationTarget {
1316 file_id: FileId(
1317 0,
1318 ),
1319 full_range: 133..183,
1320 focus_range: 148..156,
1321 name: "foo_test",
1322 kind: Function,
1323 },
1324 kind: Test {
1325 test_id: Path(
1326 "tests::foo_test",
1327 ),
1328 attr: TestAttr {
1329 ignore: false,
1330 },
1331 },
1332 cfg: None,
1333 },
1334 ]
1335 "#]],
1336 );
1337 }
1338
1339 #[test]
1340 fn tests_are_unique() {
1341 check_tests(
1342 r#"
1343//- /lib.rs
1344fn foo$0() { };
1345
1346mod tests {
1347 use super::foo;
1348
1349 #[test]
1350 fn foo_test() {
1351 foo();
1352 foo();
1353 }
1354
1355 #[test]
1356 fn foo2_test() {
1357 foo();
1358 foo();
1359 }
1360
1361}
1362"#,
1363 expect![[r#"
1364 [
1365 Runnable {
1366 nav: NavigationTarget {
1367 file_id: FileId(
1368 0,
1369 ),
1370 full_range: 52..115,
1371 focus_range: 67..75,
1372 name: "foo_test",
1373 kind: Function,
1374 },
1375 kind: Test {
1376 test_id: Path(
1377 "tests::foo_test",
1378 ),
1379 attr: TestAttr {
1380 ignore: false,
1381 },
1382 },
1383 cfg: None,
1384 },
1385 Runnable {
1386 nav: NavigationTarget {
1387 file_id: FileId(
1388 0,
1389 ),
1390 full_range: 121..185,
1391 focus_range: 136..145,
1392 name: "foo2_test",
1393 kind: Function,
1394 },
1395 kind: Test {
1396 test_id: Path(
1397 "tests::foo2_test",
1398 ),
1399 attr: TestAttr {
1400 ignore: false,
1401 },
1402 },
1403 cfg: None,
1404 },
1405 ]
1406 "#]],
1407 );
1408 }
1077} 1409}
diff --git a/crates/ide_assists/src/handlers/apply_demorgan.rs b/crates/ide_assists/src/handlers/apply_demorgan.rs
index a1c339603..5c936a510 100644
--- a/crates/ide_assists/src/handlers/apply_demorgan.rs
+++ b/crates/ide_assists/src/handlers/apply_demorgan.rs
@@ -1,3 +1,5 @@
1use std::collections::VecDeque;
2
1use syntax::ast::{self, AstNode}; 3use syntax::ast::{self, AstNode};
2 4
3use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKind, Assists}; 5use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKind, Assists};
@@ -30,19 +32,52 @@ pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext) -> Option<(
30 return None; 32 return None;
31 } 33 }
32 34
33 let lhs = expr.lhs()?; 35 let mut expr = expr;
34 let lhs_range = lhs.syntax().text_range(); 36
35 let not_lhs = invert_boolean_expression(&ctx.sema, lhs); 37 // Walk up the tree while we have the same binary operator
38 while let Some(parent_expr) = expr.syntax().parent().and_then(ast::BinExpr::cast) {
39 if let Some(parent_op) = expr.op_kind() {
40 if parent_op == op {
41 expr = parent_expr
42 }
43 }
44 }
45
46 let mut expr_stack = vec![expr.clone()];
47 let mut terms = Vec::new();
48 let mut op_ranges = Vec::new();
49
50 // Find all the children with the same binary operator
51 while let Some(expr) = expr_stack.pop() {
52 let mut traverse_bin_expr_arm = |expr| {
53 if let ast::Expr::BinExpr(bin_expr) = expr {
54 if let Some(expr_op) = bin_expr.op_kind() {
55 if expr_op == op {
56 expr_stack.push(bin_expr);
57 } else {
58 terms.push(ast::Expr::BinExpr(bin_expr));
59 }
60 } else {
61 terms.push(ast::Expr::BinExpr(bin_expr));
62 }
63 } else {
64 terms.push(expr);
65 }
66 };
36 67
37 let rhs = expr.rhs()?; 68 op_ranges.extend(expr.op_token().map(|t| t.text_range()));
38 let rhs_range = rhs.syntax().text_range(); 69 traverse_bin_expr_arm(expr.lhs()?);
39 let not_rhs = invert_boolean_expression(&ctx.sema, rhs); 70 traverse_bin_expr_arm(expr.rhs()?);
71 }
40 72
41 acc.add( 73 acc.add(
42 AssistId("apply_demorgan", AssistKind::RefactorRewrite), 74 AssistId("apply_demorgan", AssistKind::RefactorRewrite),
43 "Apply De Morgan's law", 75 "Apply De Morgan's law",
44 op_range, 76 op_range,
45 |edit| { 77 |edit| {
78 terms.sort_by_key(|t| t.syntax().text_range().start());
79 let mut terms = VecDeque::from(terms);
80
46 let paren_expr = expr.syntax().parent().and_then(|parent| ast::ParenExpr::cast(parent)); 81 let paren_expr = expr.syntax().parent().and_then(|parent| ast::ParenExpr::cast(parent));
47 82
48 let neg_expr = paren_expr 83 let neg_expr = paren_expr
@@ -57,11 +92,18 @@ pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext) -> Option<(
57 } 92 }
58 }); 93 });
59 94
60 edit.replace(op_range, opposite_op); 95 for op_range in op_ranges {
96 edit.replace(op_range, opposite_op);
97 }
61 98
62 if let Some(paren_expr) = paren_expr { 99 if let Some(paren_expr) = paren_expr {
63 edit.replace(lhs_range, not_lhs.syntax().text()); 100 for term in terms {
64 edit.replace(rhs_range, not_rhs.syntax().text()); 101 let range = term.syntax().text_range();
102 let not_term = invert_boolean_expression(&ctx.sema, term);
103
104 edit.replace(range, not_term.syntax().text());
105 }
106
65 if let Some(neg_expr) = neg_expr { 107 if let Some(neg_expr) = neg_expr {
66 cov_mark::hit!(demorgan_double_negation); 108 cov_mark::hit!(demorgan_double_negation);
67 edit.replace(neg_expr.op_token().unwrap().text_range(), ""); 109 edit.replace(neg_expr.op_token().unwrap().text_range(), "");
@@ -70,8 +112,25 @@ pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext) -> Option<(
70 edit.replace(paren_expr.l_paren_token().unwrap().text_range(), "!("); 112 edit.replace(paren_expr.l_paren_token().unwrap().text_range(), "!(");
71 } 113 }
72 } else { 114 } else {
73 edit.replace(lhs_range, format!("!({}", not_lhs.syntax().text())); 115 if let Some(lhs) = terms.pop_front() {
74 edit.replace(rhs_range, format!("{})", not_rhs.syntax().text())); 116 let lhs_range = lhs.syntax().text_range();
117 let not_lhs = invert_boolean_expression(&ctx.sema, lhs);
118
119 edit.replace(lhs_range, format!("!({}", not_lhs.syntax().text()));
120 }
121
122 if let Some(rhs) = terms.pop_back() {
123 let rhs_range = rhs.syntax().text_range();
124 let not_rhs = invert_boolean_expression(&ctx.sema, rhs);
125
126 edit.replace(rhs_range, format!("{})", not_rhs.syntax().text()));
127 }
128
129 for term in terms {
130 let term_range = term.syntax().text_range();
131 let not_term = invert_boolean_expression(&ctx.sema, term);
132 edit.replace(term_range, not_term.syntax().text());
133 }
75 } 134 }
76 }, 135 },
77 ) 136 )
@@ -180,6 +239,12 @@ fn f() {
180 } 239 }
181 240
182 #[test] 241 #[test]
242 fn demorgan_multiple_terms() {
243 check_assist(apply_demorgan, "fn f() { x ||$0 y || z }", "fn f() { !(!x && !y && !z) }");
244 check_assist(apply_demorgan, "fn f() { x || y ||$0 z }", "fn f() { !(!x && !y && !z) }");
245 }
246
247 #[test]
183 fn demorgan_doesnt_apply_with_cursor_not_on_op() { 248 fn demorgan_doesnt_apply_with_cursor_not_on_op() {
184 check_assist_not_applicable(apply_demorgan, "fn f() { $0 !x || !x }") 249 check_assist_not_applicable(apply_demorgan, "fn f() { $0 !x || !x }")
185 } 250 }
diff --git a/crates/ide_db/src/search.rs b/crates/ide_db/src/search.rs
index ddcfbd3f3..fa18703e1 100644
--- a/crates/ide_db/src/search.rs
+++ b/crates/ide_db/src/search.rs
@@ -86,6 +86,10 @@ impl SearchScope {
86 SearchScope::new(std::iter::once((file, None)).collect()) 86 SearchScope::new(std::iter::once((file, None)).collect())
87 } 87 }
88 88
89 pub fn file_range(range: FileRange) -> SearchScope {
90 SearchScope::new(std::iter::once((range.file_id, Some(range.range))).collect())
91 }
92
89 pub fn files(files: &[FileId]) -> SearchScope { 93 pub fn files(files: &[FileId]) -> SearchScope {
90 SearchScope::new(files.iter().map(|f| (*f, None)).collect()) 94 SearchScope::new(files.iter().map(|f| (*f, None)).collect())
91 } 95 }
diff --git a/crates/mbe/src/expander.rs b/crates/mbe/src/expander.rs
index 2efff8f52..3197c834c 100644
--- a/crates/mbe/src/expander.rs
+++ b/crates/mbe/src/expander.rs
@@ -5,7 +5,7 @@
5mod matcher; 5mod matcher;
6mod transcriber; 6mod transcriber;
7 7
8use smallvec::SmallVec; 8use rustc_hash::FxHashMap;
9use syntax::SmolStr; 9use syntax::SmolStr;
10 10
11use crate::{ExpandError, ExpandResult}; 11use crate::{ExpandError, ExpandResult};
@@ -96,7 +96,7 @@ pub(crate) fn expand_rules(
96/// many is not a plain `usize`, but an `&[usize]`. 96/// many is not a plain `usize`, but an `&[usize]`.
97#[derive(Debug, Default, Clone, PartialEq, Eq)] 97#[derive(Debug, Default, Clone, PartialEq, Eq)]
98struct Bindings { 98struct Bindings {
99 inner: SmallVec<[(SmolStr, Binding); 4]>, 99 inner: FxHashMap<SmolStr, Binding>,
100} 100}
101 101
102#[derive(Debug, Clone, PartialEq, Eq)] 102#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/crates/mbe/src/expander/matcher.rs b/crates/mbe/src/expander/matcher.rs
index 9d3d28055..2c69e8968 100644
--- a/crates/mbe/src/expander/matcher.rs
+++ b/crates/mbe/src/expander/matcher.rs
@@ -59,6 +59,8 @@
59//! eof: [a $( a )* a b ·] 59//! eof: [a $( a )* a b ·]
60//! ``` 60//! ```
61 61
62use std::rc::Rc;
63
62use crate::{ 64use crate::{
63 expander::{Binding, Bindings, Fragment}, 65 expander::{Binding, Bindings, Fragment},
64 parser::{Op, OpDelimited, OpDelimitedIter, RepeatKind, Separator}, 66 parser::{Op, OpDelimited, OpDelimitedIter, RepeatKind, Separator},
@@ -76,43 +78,15 @@ impl Bindings {
76 // FIXME: Do we have a better way to represent an empty token ? 78 // FIXME: Do we have a better way to represent an empty token ?
77 // Insert an empty subtree for empty token 79 // Insert an empty subtree for empty token
78 let tt = tt::Subtree::default().into(); 80 let tt = tt::Subtree::default().into();
79 self.inner.push((name.clone(), Binding::Fragment(Fragment::Tokens(tt)))); 81 self.inner.insert(name.clone(), Binding::Fragment(Fragment::Tokens(tt)));
80 } 82 }
81 83
82 fn push_empty(&mut self, name: &SmolStr) { 84 fn push_empty(&mut self, name: &SmolStr) {
83 self.inner.push((name.clone(), Binding::Empty)); 85 self.inner.insert(name.clone(), Binding::Empty);
84 }
85
86 fn push_nested(&mut self, idx: usize, nested: Bindings) -> Result<(), ExpandError> {
87 for (key, value) in nested.inner {
88 if self.get_mut(&key).is_none() {
89 self.inner.push((key.clone(), Binding::Nested(Vec::new())));
90 }
91 match self.get_mut(&key) {
92 Some(Binding::Nested(it)) => {
93 // insert empty nested bindings before this one
94 while it.len() < idx {
95 it.push(Binding::Nested(vec![]));
96 }
97 it.push(value);
98 }
99 _ => {
100 return Err(ExpandError::BindingError(format!(
101 "could not find binding `{}`",
102 key
103 )));
104 }
105 }
106 }
107 Ok(())
108 }
109
110 fn get_mut(&mut self, name: &str) -> Option<&mut Binding> {
111 self.inner.iter_mut().find_map(|(n, b)| if n == name { Some(b) } else { None })
112 } 86 }
113 87
114 fn bindings(&self) -> impl Iterator<Item = &Binding> { 88 fn bindings(&self) -> impl Iterator<Item = &Binding> {
115 self.inner.iter().map(|(_, b)| b) 89 self.inner.values()
116 } 90 }
117} 91}
118 92
@@ -163,6 +137,181 @@ pub(super) fn match_(pattern: &MetaTemplate, input: &tt::Subtree) -> Match {
163} 137}
164 138
165#[derive(Debug, Clone)] 139#[derive(Debug, Clone)]
140enum BindingKind {
141 Empty(SmolStr),
142 Optional(SmolStr),
143 Fragment(SmolStr, Fragment),
144 Nested(usize, usize),
145}
146
147#[derive(Debug, Clone)]
148struct BindingsIdx(usize, usize);
149
150#[derive(Debug, Clone)]
151enum LinkNode<T> {
152 Node(T),
153 Parent { idx: usize, len: usize },
154}
155
156#[derive(Default)]
157struct BindingsBuilder {
158 nodes: Vec<Vec<LinkNode<Rc<BindingKind>>>>,
159 nested: Vec<Vec<LinkNode<usize>>>,
160}
161
162impl BindingsBuilder {
163 fn alloc(&mut self) -> BindingsIdx {
164 let idx = self.nodes.len();
165 self.nodes.push(Vec::new());
166 let nidx = self.nested.len();
167 self.nested.push(Vec::new());
168 BindingsIdx(idx, nidx)
169 }
170
171 fn copy(&mut self, bindings: &BindingsIdx) -> BindingsIdx {
172 let idx = copy_parent(bindings.0, &mut self.nodes);
173 let nidx = copy_parent(bindings.1, &mut self.nested);
174 return BindingsIdx(idx, nidx);
175
176 fn copy_parent<T>(idx: usize, target: &mut Vec<Vec<LinkNode<T>>>) -> usize
177 where
178 T: Clone,
179 {
180 let new_idx = target.len();
181 let len = target[idx].len();
182 if len < 4 {
183 target.push(target[idx].clone())
184 } else {
185 target.push(vec![LinkNode::Parent { idx, len }]);
186 }
187 new_idx
188 }
189 }
190
191 fn push_empty(&mut self, idx: &mut BindingsIdx, var: &SmolStr) {
192 self.nodes[idx.0].push(LinkNode::Node(Rc::new(BindingKind::Empty(var.clone()))));
193 }
194
195 fn push_optional(&mut self, idx: &mut BindingsIdx, var: &SmolStr) {
196 self.nodes[idx.0].push(LinkNode::Node(Rc::new(BindingKind::Optional(var.clone()))));
197 }
198
199 fn push_fragment(&mut self, idx: &mut BindingsIdx, var: &SmolStr, fragment: Fragment) {
200 self.nodes[idx.0]
201 .push(LinkNode::Node(Rc::new(BindingKind::Fragment(var.clone(), fragment))));
202 }
203
204 fn push_nested(&mut self, parent: &mut BindingsIdx, child: &BindingsIdx) {
205 let BindingsIdx(idx, nidx) = self.copy(&child);
206 self.nodes[parent.0].push(LinkNode::Node(Rc::new(BindingKind::Nested(idx, nidx))));
207 }
208
209 fn push_default(&mut self, idx: &mut BindingsIdx) {
210 self.nested[idx.1].push(LinkNode::Node(idx.0));
211 let new_idx = self.nodes.len();
212 self.nodes.push(Vec::new());
213 idx.0 = new_idx;
214 }
215
216 fn build(self, idx: &BindingsIdx) -> Bindings {
217 let mut bindings = Bindings::default();
218 self.build_inner(&mut bindings, &self.nodes[idx.0]);
219 bindings
220 }
221
222 fn build_inner(&self, bindings: &mut Bindings, link_nodes: &Vec<LinkNode<Rc<BindingKind>>>) {
223 let mut nodes = Vec::new();
224 self.collect_nodes(&link_nodes, &mut nodes);
225
226 for cmd in nodes {
227 match &**cmd {
228 BindingKind::Empty(name) => {
229 bindings.push_empty(name);
230 }
231 BindingKind::Optional(name) => {
232 bindings.push_optional(name);
233 }
234 BindingKind::Fragment(name, fragment) => {
235 bindings.inner.insert(name.clone(), Binding::Fragment(fragment.clone()));
236 }
237 BindingKind::Nested(idx, nested_idx) => {
238 let mut nested_nodes = Vec::new();
239 self.collect_nested(*idx, *nested_idx, &mut nested_nodes);
240
241 for (idx, iter) in nested_nodes.into_iter().enumerate() {
242 for (key, value) in &iter.inner {
243 let bindings = bindings
244 .inner
245 .entry(key.clone())
246 .or_insert_with(|| Binding::Nested(Vec::new()));
247
248 if let Binding::Nested(it) = bindings {
249 // insert empty nested bindings before this one
250 while it.len() < idx {
251 it.push(Binding::Nested(Vec::new()));
252 }
253 it.push(value.clone());
254 }
255 }
256 }
257 }
258 }
259 }
260 }
261
262 fn collect_nested_ref<'a>(
263 &'a self,
264 id: usize,
265 len: usize,
266 nested_refs: &mut Vec<&'a Vec<LinkNode<Rc<BindingKind>>>>,
267 ) {
268 self.nested[id].iter().take(len).for_each(|it| match it {
269 LinkNode::Node(id) => nested_refs.push(&self.nodes[*id]),
270 LinkNode::Parent { idx, len } => self.collect_nested_ref(*idx, *len, nested_refs),
271 });
272 }
273
274 fn collect_nested(&self, idx: usize, nested_idx: usize, nested: &mut Vec<Bindings>) {
275 let last = &self.nodes[idx];
276 let mut nested_refs = Vec::new();
277 self.nested[nested_idx].iter().for_each(|it| match *it {
278 LinkNode::Node(idx) => nested_refs.push(&self.nodes[idx]),
279 LinkNode::Parent { idx, len } => self.collect_nested_ref(idx, len, &mut nested_refs),
280 });
281 nested_refs.push(last);
282
283 nested_refs.into_iter().for_each(|iter| {
284 let mut child_bindings = Bindings::default();
285 self.build_inner(&mut child_bindings, &iter);
286 nested.push(child_bindings)
287 })
288 }
289
290 fn collect_nodes_ref<'a>(
291 &'a self,
292 id: usize,
293 len: usize,
294 nodes: &mut Vec<&'a Rc<BindingKind>>,
295 ) {
296 self.nodes[id].iter().take(len).for_each(|it| match it {
297 LinkNode::Node(it) => nodes.push(it),
298 LinkNode::Parent { idx, len } => self.collect_nodes_ref(*idx, *len, nodes),
299 });
300 }
301
302 fn collect_nodes<'a>(
303 &'a self,
304 link_nodes: &'a Vec<LinkNode<Rc<BindingKind>>>,
305 nodes: &mut Vec<&'a Rc<BindingKind>>,
306 ) {
307 link_nodes.into_iter().for_each(|it| match it {
308 LinkNode::Node(it) => nodes.push(it),
309 LinkNode::Parent { idx, len } => self.collect_nodes_ref(*idx, *len, nodes),
310 });
311 }
312}
313
314#[derive(Debug, Clone)]
166struct MatchState<'t> { 315struct MatchState<'t> {
167 /// The position of the "dot" in this matcher 316 /// The position of the "dot" in this matcher
168 dot: OpDelimitedIter<'t>, 317 dot: OpDelimitedIter<'t>,
@@ -187,7 +336,7 @@ struct MatchState<'t> {
187 sep_parsed: Option<usize>, 336 sep_parsed: Option<usize>,
188 337
189 /// Matched meta variables bindings 338 /// Matched meta variables bindings
190 bindings: SmallVec<[Bindings; 4]>, 339 bindings: BindingsIdx,
191 340
192 /// Cached result of meta variable parsing 341 /// Cached result of meta variable parsing
193 meta_result: Option<(TtIter<'t>, ExpandResult<Option<Fragment>>)>, 342 meta_result: Option<(TtIter<'t>, ExpandResult<Option<Fragment>>)>,
@@ -218,6 +367,7 @@ fn match_loop_inner<'t>(
218 src: TtIter<'t>, 367 src: TtIter<'t>,
219 stack: &[TtIter<'t>], 368 stack: &[TtIter<'t>],
220 res: &mut Match, 369 res: &mut Match,
370 bindings_builder: &mut BindingsBuilder,
221 cur_items: &mut SmallVec<[MatchState<'t>; 1]>, 371 cur_items: &mut SmallVec<[MatchState<'t>; 1]>,
222 bb_items: &mut SmallVec<[MatchState<'t>; 1]>, 372 bb_items: &mut SmallVec<[MatchState<'t>; 1]>,
223 next_items: &mut Vec<MatchState<'t>>, 373 next_items: &mut Vec<MatchState<'t>>,
@@ -251,12 +401,10 @@ fn match_loop_inner<'t>(
251 if item.sep_parsed.is_none() { 401 if item.sep_parsed.is_none() {
252 // Get the `up` matcher 402 // Get the `up` matcher
253 let mut new_pos = *item.up.clone().unwrap(); 403 let mut new_pos = *item.up.clone().unwrap();
404 new_pos.bindings = bindings_builder.copy(&new_pos.bindings);
254 // Add matches from this repetition to the `matches` of `up` 405 // Add matches from this repetition to the `matches` of `up`
255 if let Some(bindings) = new_pos.bindings.last_mut() { 406 bindings_builder.push_nested(&mut new_pos.bindings, &item.bindings);
256 for (i, b) in item.bindings.iter_mut().enumerate() { 407
257 bindings.push_nested(i, b.clone()).unwrap();
258 }
259 }
260 // Move the "dot" past the repetition in `up` 408 // Move the "dot" past the repetition in `up`
261 new_pos.dot.next(); 409 new_pos.dot.next();
262 new_pos.is_error = new_pos.is_error || item.is_error; 410 new_pos.is_error = new_pos.is_error || item.is_error;
@@ -280,7 +428,7 @@ fn match_loop_inner<'t>(
280 else if item.sep_kind != Some(RepeatKind::ZeroOrOne) { 428 else if item.sep_kind != Some(RepeatKind::ZeroOrOne) {
281 item.dot = item.dot.reset(); 429 item.dot = item.dot.reset();
282 item.sep_parsed = None; 430 item.sep_parsed = None;
283 item.bindings.push(Bindings::default()); 431 bindings_builder.push_default(&mut item.bindings);
284 cur_items.push(item); 432 cur_items.push(item);
285 } 433 }
286 } else { 434 } else {
@@ -298,12 +446,12 @@ fn match_loop_inner<'t>(
298 OpDelimited::Op(Op::Repeat { tokens, kind, separator }) => { 446 OpDelimited::Op(Op::Repeat { tokens, kind, separator }) => {
299 if matches!(kind, RepeatKind::ZeroOrMore | RepeatKind::ZeroOrOne) { 447 if matches!(kind, RepeatKind::ZeroOrMore | RepeatKind::ZeroOrOne) {
300 let mut new_item = item.clone(); 448 let mut new_item = item.clone();
449 new_item.bindings = bindings_builder.copy(&new_item.bindings);
301 new_item.dot.next(); 450 new_item.dot.next();
302 let mut vars = Vec::new(); 451 let mut vars = Vec::new();
303 let bindings = new_item.bindings.last_mut().unwrap();
304 collect_vars(&mut vars, tokens); 452 collect_vars(&mut vars, tokens);
305 for var in vars { 453 for var in vars {
306 bindings.push_empty(&var); 454 bindings_builder.push_empty(&mut new_item.bindings, &var);
307 } 455 }
308 cur_items.push(new_item); 456 cur_items.push(new_item);
309 } 457 }
@@ -314,7 +462,7 @@ fn match_loop_inner<'t>(
314 sep: separator.clone(), 462 sep: separator.clone(),
315 sep_kind: Some(*kind), 463 sep_kind: Some(*kind),
316 sep_parsed: None, 464 sep_parsed: None,
317 bindings: smallvec![Bindings::default()], 465 bindings: bindings_builder.alloc(),
318 meta_result: None, 466 meta_result: None,
319 is_error: false, 467 is_error: false,
320 }) 468 })
@@ -339,7 +487,7 @@ fn match_loop_inner<'t>(
339 item.meta_result = Some((fork, match_res)); 487 item.meta_result = Some((fork, match_res));
340 try_push!(bb_items, item); 488 try_push!(bb_items, item);
341 } else { 489 } else {
342 item.bindings.last_mut().unwrap().push_optional(name); 490 bindings_builder.push_optional(&mut item.bindings, &name);
343 item.dot.next(); 491 item.dot.next();
344 cur_items.push(item); 492 cur_items.push(item);
345 } 493 }
@@ -348,11 +496,11 @@ fn match_loop_inner<'t>(
348 res.add_err(err); 496 res.add_err(err);
349 match match_res.value { 497 match match_res.value {
350 Some(fragment) => { 498 Some(fragment) => {
351 item.bindings 499 bindings_builder.push_fragment(
352 .last_mut() 500 &mut item.bindings,
353 .unwrap() 501 &name,
354 .inner 502 fragment,
355 .push((name.clone(), Binding::Fragment(fragment))); 503 );
356 } 504 }
357 _ => {} 505 _ => {}
358 } 506 }
@@ -394,6 +542,8 @@ fn match_loop(pattern: &MetaTemplate, src: &tt::Subtree) -> Match {
394 let mut res = Match::default(); 542 let mut res = Match::default();
395 let mut error_reover_item = None; 543 let mut error_reover_item = None;
396 544
545 let mut bindings_builder = BindingsBuilder::default();
546
397 let mut cur_items = smallvec![MatchState { 547 let mut cur_items = smallvec![MatchState {
398 dot: pattern.iter_delimited(None), 548 dot: pattern.iter_delimited(None),
399 stack: Default::default(), 549 stack: Default::default(),
@@ -401,7 +551,7 @@ fn match_loop(pattern: &MetaTemplate, src: &tt::Subtree) -> Match {
401 sep: None, 551 sep: None,
402 sep_kind: None, 552 sep_kind: None,
403 sep_parsed: None, 553 sep_parsed: None,
404 bindings: smallvec![Bindings::default()], 554 bindings: bindings_builder.alloc(),
405 is_error: false, 555 is_error: false,
406 meta_result: None, 556 meta_result: None,
407 }]; 557 }];
@@ -419,6 +569,7 @@ fn match_loop(pattern: &MetaTemplate, src: &tt::Subtree) -> Match {
419 src.clone(), 569 src.clone(),
420 &stack, 570 &stack,
421 &mut res, 571 &mut res,
572 &mut bindings_builder,
422 &mut cur_items, 573 &mut cur_items,
423 &mut bb_items, 574 &mut bb_items,
424 &mut next_items, 575 &mut next_items,
@@ -428,9 +579,9 @@ fn match_loop(pattern: &MetaTemplate, src: &tt::Subtree) -> Match {
428 stdx::always!(cur_items.is_empty()); 579 stdx::always!(cur_items.is_empty());
429 580
430 if error_items.len() > 0 { 581 if error_items.len() > 0 {
431 error_reover_item = error_items.pop(); 582 error_reover_item = error_items.pop().map(|it| it.bindings);
432 } else if eof_items.len() > 0 { 583 } else if eof_items.len() > 0 {
433 error_reover_item = Some(eof_items[0].clone()); 584 error_reover_item = Some(eof_items[0].bindings.clone());
434 } 585 }
435 586
436 // We need to do some post processing after the `match_loop_inner`. 587 // We need to do some post processing after the `match_loop_inner`.
@@ -440,11 +591,11 @@ fn match_loop(pattern: &MetaTemplate, src: &tt::Subtree) -> Match {
440 if eof_items.len() == 1 { 591 if eof_items.len() == 1 {
441 // remove all errors, because it is the correct answer ! 592 // remove all errors, because it is the correct answer !
442 res = Match::default(); 593 res = Match::default();
443 res.bindings = eof_items[0].bindings[0].clone(); 594 res.bindings = bindings_builder.build(&eof_items[0].bindings);
444 } else { 595 } else {
445 // Error recovery 596 // Error recovery
446 if error_reover_item.is_some() { 597 if error_reover_item.is_some() {
447 res.bindings = error_reover_item.unwrap().bindings[0].clone(); 598 res.bindings = bindings_builder.build(&error_reover_item.unwrap());
448 } 599 }
449 res.add_err(ExpandError::UnexpectedToken); 600 res.add_err(ExpandError::UnexpectedToken);
450 } 601 }
@@ -467,8 +618,8 @@ fn match_loop(pattern: &MetaTemplate, src: &tt::Subtree) -> Match {
467 } 618 }
468 res.add_err(err!("leftover tokens")); 619 res.add_err(err!("leftover tokens"));
469 620
470 if let Some(mut error_reover_item) = error_reover_item { 621 if let Some(error_reover_item) = error_reover_item {
471 res.bindings = error_reover_item.bindings.remove(0); 622 res.bindings = bindings_builder.build(&error_reover_item);
472 } 623 }
473 return res; 624 return res;
474 } 625 }
@@ -494,12 +645,13 @@ fn match_loop(pattern: &MetaTemplate, src: &tt::Subtree) -> Match {
494 645
495 if let Some(OpDelimited::Op(Op::Var { name, .. })) = item.dot.peek() { 646 if let Some(OpDelimited::Op(Op::Var { name, .. })) = item.dot.peek() {
496 let (iter, match_res) = item.meta_result.take().unwrap(); 647 let (iter, match_res) = item.meta_result.take().unwrap();
497 let bindings = item.bindings.last_mut().unwrap();
498 match match_res.value { 648 match match_res.value {
499 Some(fragment) => { 649 Some(fragment) => {
500 bindings.inner.push((name.clone(), Binding::Fragment(fragment))); 650 bindings_builder.push_fragment(&mut item.bindings, &name, fragment);
651 }
652 None if match_res.err.is_none() => {
653 bindings_builder.push_optional(&mut item.bindings, &name);
501 } 654 }
502 None if match_res.err.is_none() => bindings.push_optional(name),
503 _ => {} 655 _ => {}
504 } 656 }
505 if let Some(err) = match_res.err { 657 if let Some(err) = match_res.err {
diff --git a/crates/mbe/src/expander/transcriber.rs b/crates/mbe/src/expander/transcriber.rs
index ad9953a7d..dd7fa97d7 100644
--- a/crates/mbe/src/expander/transcriber.rs
+++ b/crates/mbe/src/expander/transcriber.rs
@@ -2,7 +2,7 @@
2//! `$ident => foo`, interpolates variables in the template, to get `fn foo() {}` 2//! `$ident => foo`, interpolates variables in the template, to get `fn foo() {}`
3 3
4use syntax::SmolStr; 4use syntax::SmolStr;
5use tt::Delimiter; 5use tt::{Delimiter, Subtree};
6 6
7use super::ExpandResult; 7use super::ExpandResult;
8use crate::{ 8use crate::{
@@ -13,17 +13,13 @@ use crate::{
13 13
14impl Bindings { 14impl Bindings {
15 fn contains(&self, name: &str) -> bool { 15 fn contains(&self, name: &str) -> bool {
16 self.inner.iter().any(|(n, _)| n == name) 16 self.inner.contains_key(name)
17 } 17 }
18 18
19 fn get(&self, name: &str, nesting: &mut [NestingState]) -> Result<&Fragment, ExpandError> { 19 fn get(&self, name: &str, nesting: &mut [NestingState]) -> Result<&Fragment, ExpandError> {
20 let mut b: &Binding = self 20 let mut b: &Binding = self.inner.get(name).ok_or_else(|| {
21 .inner 21 ExpandError::BindingError(format!("could not find binding `{}`", name))
22 .iter() 22 })?;
23 .find_map(|(n, b)| if n == name { Some(b) } else { None })
24 .ok_or_else(|| {
25 ExpandError::BindingError(format!("could not find binding `{}`", name))
26 })?;
27 for nesting_state in nesting.iter_mut() { 23 for nesting_state in nesting.iter_mut() {
28 nesting_state.hit = true; 24 nesting_state.hit = true;
29 b = match b { 25 b = match b {
@@ -179,7 +175,10 @@ fn expand_repeat(
179 counter += 1; 175 counter += 1;
180 if counter == limit { 176 if counter == limit {
181 log::warn!("expand_tt in repeat pattern exceed limit => {:#?}\n{:#?}", template, ctx); 177 log::warn!("expand_tt in repeat pattern exceed limit => {:#?}\n{:#?}", template, ctx);
182 break; 178 return ExpandResult {
179 value: Fragment::Tokens(Subtree::default().into()),
180 err: Some(ExpandError::Other("Expand exceed limit".to_string())),
181 };
183 } 182 }
184 183
185 if e.is_some() { 184 if e.is_some() {
diff --git a/crates/rust-analyzer/build.rs b/crates/rust-analyzer/build.rs
index 5ae76ba30..999dc5928 100644
--- a/crates/rust-analyzer/build.rs
+++ b/crates/rust-analyzer/build.rs
@@ -39,8 +39,7 @@ fn set_rerun() {
39} 39}
40 40
41fn rev() -> Option<String> { 41fn rev() -> Option<String> {
42 let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().ok()?; 42 let output = Command::new("git").args(&["describe", "--tags"]).output().ok()?;
43 let stdout = String::from_utf8(output.stdout).ok()?; 43 let stdout = String::from_utf8(output.stdout).ok()?;
44 let short_hash = stdout.get(0..7)?; 44 Some(stdout)
45 Some(short_hash.to_owned())
46} 45}
diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs
index ad0759bda..c81c1d26e 100644
--- a/crates/rust-analyzer/src/cli/analysis_stats.rs
+++ b/crates/rust-analyzer/src/cli/analysis_stats.rs
@@ -12,7 +12,7 @@ use hir::{
12 AssocItem, Crate, HasSource, HirDisplay, ModuleDef, 12 AssocItem, Crate, HasSource, HirDisplay, ModuleDef,
13}; 13};
14use hir_def::FunctionId; 14use hir_def::FunctionId;
15use hir_ty::{Ty, TypeWalk}; 15use hir_ty::TypeWalk;
16use ide_db::base_db::{ 16use ide_db::base_db::{
17 salsa::{self, ParallelDatabase}, 17 salsa::{self, ParallelDatabase},
18 SourceDatabaseExt, 18 SourceDatabaseExt,
@@ -187,12 +187,12 @@ impl AnalysisStatsCmd {
187 for (expr_id, _) in body.exprs.iter() { 187 for (expr_id, _) in body.exprs.iter() {
188 let ty = &inference_result[expr_id]; 188 let ty = &inference_result[expr_id];
189 num_exprs += 1; 189 num_exprs += 1;
190 if let Ty::Unknown = ty { 190 if ty.is_unknown() {
191 num_exprs_unknown += 1; 191 num_exprs_unknown += 1;
192 } else { 192 } else {
193 let mut is_partially_unknown = false; 193 let mut is_partially_unknown = false;
194 ty.walk(&mut |ty| { 194 ty.walk(&mut |ty| {
195 if let Ty::Unknown = ty { 195 if ty.is_unknown() {
196 is_partially_unknown = true; 196 is_partially_unknown = true;
197 } 197 }
198 }); 198 });
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs
index 6cc433cb8..706a39dab 100644
--- a/crates/rust-analyzer/src/handlers.rs
+++ b/crates/rust-analyzer/src/handlers.rs
@@ -555,7 +555,7 @@ pub(crate) fn handle_runnables(
555 if should_skip_target(&runnable, cargo_spec.as_ref()) { 555 if should_skip_target(&runnable, cargo_spec.as_ref()) {
556 continue; 556 continue;
557 } 557 }
558 let mut runnable = to_proto::runnable(&snap, file_id, runnable)?; 558 let mut runnable = to_proto::runnable(&snap, runnable)?;
559 if expect_test { 559 if expect_test {
560 runnable.label = format!("{} + expect", runnable.label); 560 runnable.label = format!("{} + expect", runnable.label);
561 runnable.args.expect_test = Some(true); 561 runnable.args.expect_test = Some(true);
@@ -607,6 +607,24 @@ pub(crate) fn handle_runnables(
607 Ok(res) 607 Ok(res)
608} 608}
609 609
610pub(crate) fn handle_related_tests(
611 snap: GlobalStateSnapshot,
612 params: lsp_types::TextDocumentPositionParams,
613) -> Result<Vec<lsp_ext::TestInfo>> {
614 let _p = profile::span("handle_related_tests");
615 let position = from_proto::file_position(&snap, params)?;
616
617 let tests = snap.analysis.related_tests(position, None)?;
618 let mut res = Vec::new();
619 for it in tests {
620 if let Ok(runnable) = to_proto::runnable(&snap, it) {
621 res.push(lsp_ext::TestInfo { runnable })
622 }
623 }
624
625 Ok(res)
626}
627
610pub(crate) fn handle_completion( 628pub(crate) fn handle_completion(
611 snap: GlobalStateSnapshot, 629 snap: GlobalStateSnapshot,
612 params: lsp_types::CompletionParams, 630 params: lsp_types::CompletionParams,
@@ -772,7 +790,7 @@ pub(crate) fn handle_hover(
772 contents: HoverContents::Markup(to_proto::markup_content(info.info.markup)), 790 contents: HoverContents::Markup(to_proto::markup_content(info.info.markup)),
773 range: Some(range), 791 range: Some(range),
774 }, 792 },
775 actions: prepare_hover_actions(&snap, position.file_id, &info.info.actions), 793 actions: prepare_hover_actions(&snap, &info.info.actions),
776 }; 794 };
777 795
778 Ok(Some(hover)) 796 Ok(Some(hover))
@@ -1440,17 +1458,16 @@ fn show_impl_command_link(
1440 1458
1441fn runnable_action_links( 1459fn runnable_action_links(
1442 snap: &GlobalStateSnapshot, 1460 snap: &GlobalStateSnapshot,
1443 file_id: FileId,
1444 runnable: Runnable, 1461 runnable: Runnable,
1445) -> Option<lsp_ext::CommandLinkGroup> { 1462) -> Option<lsp_ext::CommandLinkGroup> {
1446 let cargo_spec = CargoTargetSpec::for_file(&snap, file_id).ok()?; 1463 let cargo_spec = CargoTargetSpec::for_file(&snap, runnable.nav.file_id).ok()?;
1447 let hover_config = snap.config.hover(); 1464 let hover_config = snap.config.hover();
1448 if !hover_config.runnable() || should_skip_target(&runnable, cargo_spec.as_ref()) { 1465 if !hover_config.runnable() || should_skip_target(&runnable, cargo_spec.as_ref()) {
1449 return None; 1466 return None;
1450 } 1467 }
1451 1468
1452 let action: &'static _ = runnable.action(); 1469 let action: &'static _ = runnable.action();
1453 to_proto::runnable(snap, file_id, runnable).ok().map(|r| { 1470 to_proto::runnable(snap, runnable).ok().map(|r| {
1454 let mut group = lsp_ext::CommandLinkGroup::default(); 1471 let mut group = lsp_ext::CommandLinkGroup::default();
1455 1472
1456 if hover_config.run { 1473 if hover_config.run {
@@ -1489,7 +1506,6 @@ fn goto_type_action_links(
1489 1506
1490fn prepare_hover_actions( 1507fn prepare_hover_actions(
1491 snap: &GlobalStateSnapshot, 1508 snap: &GlobalStateSnapshot,
1492 file_id: FileId,
1493 actions: &[HoverAction], 1509 actions: &[HoverAction],
1494) -> Vec<lsp_ext::CommandLinkGroup> { 1510) -> Vec<lsp_ext::CommandLinkGroup> {
1495 if snap.config.hover().none() || !snap.config.hover_actions() { 1511 if snap.config.hover().none() || !snap.config.hover_actions() {
@@ -1500,7 +1516,7 @@ fn prepare_hover_actions(
1500 .iter() 1516 .iter()
1501 .filter_map(|it| match it { 1517 .filter_map(|it| match it {
1502 HoverAction::Implementation(position) => show_impl_command_link(snap, position), 1518 HoverAction::Implementation(position) => show_impl_command_link(snap, position),
1503 HoverAction::Runnable(r) => runnable_action_links(snap, file_id, r.clone()), 1519 HoverAction::Runnable(r) => runnable_action_links(snap, r.clone()),
1504 HoverAction::GoToType(targets) => goto_type_action_links(snap, targets), 1520 HoverAction::GoToType(targets) => goto_type_action_links(snap, targets),
1505 }) 1521 })
1506 .collect() 1522 .collect()
diff --git a/crates/rust-analyzer/src/lsp_ext.rs b/crates/rust-analyzer/src/lsp_ext.rs
index 0d2c8f7ff..efcdcd1d9 100644
--- a/crates/rust-analyzer/src/lsp_ext.rs
+++ b/crates/rust-analyzer/src/lsp_ext.rs
@@ -177,6 +177,19 @@ pub struct CargoRunnable {
177 pub expect_test: Option<bool>, 177 pub expect_test: Option<bool>,
178} 178}
179 179
180pub enum RelatedTests {}
181
182impl Request for RelatedTests {
183 type Params = lsp_types::TextDocumentPositionParams;
184 type Result = Vec<TestInfo>;
185 const METHOD: &'static str = "rust-analyzer/relatedTests";
186}
187
188#[derive(Debug, Deserialize, Serialize)]
189pub struct TestInfo {
190 pub runnable: Runnable,
191}
192
180pub enum InlayHints {} 193pub enum InlayHints {}
181 194
182impl Request for InlayHints { 195impl Request for InlayHints {
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index f0cb309e4..984790d35 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -500,6 +500,7 @@ impl GlobalState {
500 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro) 500 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
501 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module) 501 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
502 .on::<lsp_ext::Runnables>(handlers::handle_runnables) 502 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
503 .on::<lsp_ext::RelatedTests>(handlers::handle_related_tests)
503 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints) 504 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
504 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action) 505 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
505 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve) 506 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs
index 1a8cdadad..5736875d3 100644
--- a/crates/rust-analyzer/src/to_proto.rs
+++ b/crates/rust-analyzer/src/to_proto.rs
@@ -484,7 +484,8 @@ pub(crate) fn folding_range(
484 let kind = match fold.kind { 484 let kind = match fold.kind {
485 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment), 485 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
486 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports), 486 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
487 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList | FoldKind::Region => None, 487 FoldKind::Region => Some(lsp_types::FoldingRangeKind::Region),
488 FoldKind::Mods | FoldKind::Block | FoldKind::ArgList => None,
488 }; 489 };
489 490
490 let range = range(line_index, fold.range); 491 let range = range(line_index, fold.range);
@@ -838,11 +839,10 @@ pub(crate) fn resolved_code_action(
838 839
839pub(crate) fn runnable( 840pub(crate) fn runnable(
840 snap: &GlobalStateSnapshot, 841 snap: &GlobalStateSnapshot,
841 file_id: FileId,
842 runnable: Runnable, 842 runnable: Runnable,
843) -> Result<lsp_ext::Runnable> { 843) -> Result<lsp_ext::Runnable> {
844 let config = snap.config.runnables(); 844 let config = snap.config.runnables();
845 let spec = CargoTargetSpec::for_file(snap, file_id)?; 845 let spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id)?;
846 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone()); 846 let workspace_root = spec.as_ref().map(|it| it.workspace_root.clone());
847 let target = spec.as_ref().map(|s| s.target.clone()); 847 let target = spec.as_ref().map(|s| s.target.clone());
848 let (cargo_args, executable_args) = 848 let (cargo_args, executable_args) =
@@ -875,7 +875,7 @@ pub(crate) fn code_lens(
875 let annotation_range = range(&line_index, annotation.range); 875 let annotation_range = range(&line_index, annotation.range);
876 876
877 let action = run.action(); 877 let action = run.action();
878 let r = runnable(&snap, run.nav.file_id, run)?; 878 let r = runnable(&snap, run)?;
879 879
880 let command = if debug { 880 let command = if debug {
881 command::debug_single(&r) 881 command::debug_single(&r)
diff --git a/crates/tt/src/lib.rs b/crates/tt/src/lib.rs
index 8301dc28a..9d9a01e30 100644
--- a/crates/tt/src/lib.rs
+++ b/crates/tt/src/lib.rs
@@ -227,6 +227,53 @@ impl Subtree {
227 } 227 }
228} 228}
229 229
230impl Subtree {
231 /// A simple line string used for debugging
232 pub fn as_debug_string(&self) -> String {
233 let delim = match self.delimiter_kind() {
234 Some(DelimiterKind::Brace) => ("{", "}"),
235 Some(DelimiterKind::Bracket) => ("[", "]"),
236 Some(DelimiterKind::Parenthesis) => ("(", ")"),
237 None => (" ", " "),
238 };
239
240 let mut res = String::new();
241 res.push_str(delim.0);
242 let mut iter = self.token_trees.iter();
243 let mut last = None;
244 while let Some(child) = iter.next() {
245 let s = match child {
246 TokenTree::Leaf(it) => {
247 let s = match it {
248 Leaf::Literal(it) => it.text.to_string(),
249 Leaf::Punct(it) => it.char.to_string(),
250 Leaf::Ident(it) => it.text.to_string(),
251 };
252 match (it, last) {
253 (Leaf::Ident(_), Some(&TokenTree::Leaf(Leaf::Ident(_)))) => {
254 " ".to_string() + &s
255 }
256 (Leaf::Punct(_), Some(&TokenTree::Leaf(Leaf::Punct(punct)))) => {
257 if punct.spacing == Spacing::Alone {
258 " ".to_string() + &s
259 } else {
260 s
261 }
262 }
263 _ => s,
264 }
265 }
266 TokenTree::Subtree(it) => it.as_debug_string(),
267 };
268 res.push_str(&s);
269 last = Some(child);
270 }
271
272 res.push_str(delim.1);
273 res
274 }
275}
276
230pub mod buffer; 277pub mod buffer;
231 278
232#[derive(Debug, PartialEq, Eq, Clone)] 279#[derive(Debug, PartialEq, Eq, Clone)]