Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 3 additions & 20 deletions crates/hir-ty/src/builder.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! `TyBuilder`, a helper for building instances of `Ty` and related types.

use chalk_ir::{
DebruijnIndex, Scalar,
DebruijnIndex,
cast::{Cast, Caster},
};
use hir_def::{GenericDefId, GenericParamId, TraitId, builtin_type::BuiltinType};
use hir_def::{GenericDefId, GenericParamId, TraitId};
use smallvec::SmallVec;

use crate::{
Expand All @@ -18,7 +18,7 @@ use crate::{
DbInterner, EarlyBinder,
mapping::{ChalkToNextSolver, NextSolverToChalk},
},
primitive, to_chalk_trait_id,
to_chalk_trait_id,
};

#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -137,23 +137,6 @@ impl TyBuilder<()> {
TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::Usize)).intern(Interner)
}

pub(crate) fn builtin(builtin: BuiltinType) -> Ty {
match builtin {
BuiltinType::Char => TyKind::Scalar(Scalar::Char).intern(Interner),
BuiltinType::Bool => TyKind::Scalar(Scalar::Bool).intern(Interner),
BuiltinType::Str => TyKind::Str.intern(Interner),
BuiltinType::Int(t) => {
TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(t))).intern(Interner)
}
BuiltinType::Uint(t) => {
TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(t))).intern(Interner)
}
BuiltinType::Float(t) => {
TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(t))).intern(Interner)
}
}
}

pub(crate) fn unknown_subst(
db: &dyn HirDatabase,
def: impl Into<GenericDefId>,
Expand Down
48 changes: 1 addition & 47 deletions crates/hir-ty/src/chalk_db.rs
Original file line number Diff line number Diff line change
@@ -1,55 +1,9 @@
//! The implementation of `RustIrDatabase` for Chalk, which provides information
//! about the code that Chalk needs.
use hir_def::{CallableDefId, GenericDefId};

use crate::{Interner, db::HirDatabase, mapping::from_chalk};
use crate::Interner;

pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
pub(crate) type TraitId = chalk_ir::TraitId<Interner>;
pub(crate) type AdtId = chalk_ir::AdtId<Interner>;
pub(crate) type ImplId = chalk_ir::ImplId<Interner>;
pub(crate) type Variances = chalk_ir::Variances<Interner>;

impl chalk_ir::UnificationDatabase<Interner> for &dyn HirDatabase {
fn fn_def_variance(
&self,
fn_def_id: chalk_ir::FnDefId<Interner>,
) -> chalk_ir::Variances<Interner> {
HirDatabase::fn_def_variance(*self, from_chalk(*self, fn_def_id))
}

fn adt_variance(&self, adt_id: chalk_ir::AdtId<Interner>) -> chalk_ir::Variances<Interner> {
HirDatabase::adt_variance(*self, adt_id.0)
}
}

pub(crate) fn fn_def_variance_query(
db: &dyn HirDatabase,
callable_def: CallableDefId,
) -> Variances {
Variances::from_iter(
Interner,
db.variances_of(GenericDefId::from_callable(db, callable_def))
.as_deref()
.unwrap_or_default()
.iter()
.map(|v| match v {
crate::variance::Variance::Covariant => chalk_ir::Variance::Covariant,
crate::variance::Variance::Invariant => chalk_ir::Variance::Invariant,
crate::variance::Variance::Contravariant => chalk_ir::Variance::Contravariant,
crate::variance::Variance::Bivariant => chalk_ir::Variance::Invariant,
}),
)
}

pub(crate) fn adt_variance_query(db: &dyn HirDatabase, adt_id: hir_def::AdtId) -> Variances {
Variances::from_iter(
Interner,
db.variances_of(adt_id.into()).as_deref().unwrap_or_default().iter().map(|v| match v {
crate::variance::Variance::Covariant => chalk_ir::Variance::Covariant,
crate::variance::Variance::Invariant => chalk_ir::Variance::Invariant,
crate::variance::Variance::Contravariant => chalk_ir::Variance::Contravariant,
crate::variance::Variance::Bivariant => chalk_ir::Variance::Invariant,
}),
)
}
21 changes: 2 additions & 19 deletions crates/hir-ty/src/chalk_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
use hir_def::{ItemContainerId, Lookup, TraitId};

use crate::{
Binders, DynTy, Interner, ProjectionTy, Substitution, TraitRef, Ty, db::HirDatabase,
from_assoc_type_id, from_chalk_trait_id, generics::generics, to_chalk_trait_id,
Interner, ProjectionTy, Substitution, TraitRef, Ty, db::HirDatabase, from_assoc_type_id,
from_chalk_trait_id, generics::generics, to_chalk_trait_id,
};

pub(crate) trait ProjectionTyExt {
Expand Down Expand Up @@ -35,23 +35,6 @@ impl ProjectionTyExt for ProjectionTy {
}
}

pub(crate) trait DynTyExt {
fn principal(&self) -> Option<Binders<Binders<&TraitRef>>>;
}

impl DynTyExt for DynTy {
fn principal(&self) -> Option<Binders<Binders<&TraitRef>>> {
self.bounds.as_ref().filter_map(|bounds| {
bounds.interned().first().and_then(|b| {
b.as_ref().filter_map(|b| match b {
crate::WhereClause::Implemented(trait_ref) => Some(trait_ref),
_ => None,
})
})
})
}
}

pub(crate) trait TraitRefExt {
fn hir_trait_id(&self) -> TraitId;
}
Expand Down
64 changes: 12 additions & 52 deletions crates/hir-ty/src/consteval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,74 +6,28 @@ mod tests;
use base_db::Crate;
use hir_def::{
EnumVariantId, GeneralConstId, HasModule, StaticId,
expr_store::{Body, HygieneId, path::Path},
expr_store::Body,
hir::{Expr, ExprId},
resolver::{Resolver, ValueNs},
type_ref::LiteralConstRef,
};
use hir_expand::Lookup;
use rustc_type_ir::{UnevaluatedConst, inherent::IntoKind};
use stdx::never;
use rustc_type_ir::inherent::IntoKind;
use triomphe::Arc;

use crate::{
MemoryMap, TraitEnvironment,
LifetimeElisionKind, MemoryMap, TraitEnvironment, TyLoweringContext,
db::HirDatabase,
display::DisplayTarget,
generics::Generics,
infer::InferenceContext,
mir::{MirEvalError, MirLowerError},
next_solver::{
Const, ConstBytes, ConstKind, DbInterner, ErrorGuaranteed, GenericArg, GenericArgs,
ParamConst, SolverDefId, Ty, ValueConst,
SolverDefId, Ty, ValueConst,
},
};

use super::mir::{interpret_mir, lower_to_mir, pad16};

pub(crate) fn path_to_const<'a, 'g>(
db: &'a dyn HirDatabase,
resolver: &Resolver<'a>,
path: &Path,
args: impl FnOnce() -> &'g Generics,
_expected_ty: Ty<'a>,
) -> Option<Const<'a>> {
let interner = DbInterner::new_with(db, Some(resolver.krate()), None);
match resolver.resolve_path_in_value_ns_fully(db, path, HygieneId::ROOT) {
Some(ValueNs::GenericParam(p)) => {
let args = args();
match args
.type_or_const_param(p.into())
.and_then(|(idx, p)| p.const_param().map(|p| (idx, p.clone())))
{
Some((idx, _param)) => {
Some(Const::new_param(interner, ParamConst { index: idx as u32, id: p }))
}
None => {
never!(
"Generic list doesn't contain this param: {:?}, {:?}, {:?}",
args,
path,
p
);
None
}
}
}
Some(ValueNs::ConstId(c)) => {
let args = GenericArgs::new_from_iter(interner, []);
Some(Const::new(
interner,
rustc_type_ir::ConstKind::Unevaluated(UnevaluatedConst::new(
SolverDefId::ConstId(c),
args,
)),
))
}
_ => None,
}
}

pub fn unknown_const<'db>(_ty: Ty<'db>) -> Const<'db> {
Const::new(DbInterner::conjure(), rustc_type_ir::ConstKind::Error(ErrorGuaranteed))
}
Expand Down Expand Up @@ -279,8 +233,14 @@ pub(crate) fn eval_to_const<'db>(expr: ExprId, ctx: &mut InferenceContext<'_, 'd
return unknown_const(infer[expr]);
}
if let Expr::Path(p) = &ctx.body[expr] {
let resolver = &ctx.resolver;
if let Some(c) = path_to_const(ctx.db, resolver, p, || ctx.generics(), infer[expr]) {
let mut ctx = TyLoweringContext::new(
ctx.db,
&ctx.resolver,
ctx.body,
ctx.generic_def,
LifetimeElisionKind::Infer,
);
if let Some(c) = ctx.path_to_const(p) {
return c;
}
}
Expand Down
9 changes: 1 addition & 8 deletions crates/hir-ty/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use triomphe::Arc;

use crate::{
Binders, ImplTraitId, ImplTraits, InferenceResult, TraitEnvironment, Ty, TyDefId, ValueTyDefId,
chalk_db,
consteval::ConstEvalError,
dyn_compatibility::DynCompatibilityViolation,
layout::{Layout, LayoutError},
Expand Down Expand Up @@ -308,19 +307,13 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug {
#[salsa::interned]
fn intern_coroutine(&self, id: InternedCoroutine) -> InternedCoroutineId;

#[salsa::invoke(chalk_db::fn_def_variance_query)]
fn fn_def_variance(&self, fn_def_id: CallableDefId) -> chalk_db::Variances;

#[salsa::invoke(chalk_db::adt_variance_query)]
fn adt_variance(&self, adt_id: AdtId) -> chalk_db::Variances;

#[salsa::invoke(crate::variance::variances_of)]
#[salsa::cycle(
// cycle_fn = crate::variance::variances_of_cycle_fn,
// cycle_initial = crate::variance::variances_of_cycle_initial,
cycle_result = crate::variance::variances_of_cycle_initial,
)]
fn variances_of(&self, def: GenericDefId) -> Option<Arc<[crate::variance::Variance]>>;
fn variances_of(&self, def: GenericDefId) -> crate::next_solver::VariancesOf<'_>;

// next trait solver

Expand Down
6 changes: 3 additions & 3 deletions crates/hir-ty/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1062,9 +1062,9 @@ impl<'db> HirDisplay<'db> for Ty<'db> {
TyKind::Str => write!(f, "str")?,
TyKind::Bool => write!(f, "bool")?,
TyKind::Char => write!(f, "char")?,
TyKind::Float(t) => write!(f, "{}", primitive::float_ty_to_string_ns(t))?,
TyKind::Int(t) => write!(f, "{}", primitive::int_ty_to_string_ns(t))?,
TyKind::Uint(t) => write!(f, "{}", primitive::uint_ty_to_string_ns(t))?,
TyKind::Float(t) => write!(f, "{}", primitive::float_ty_to_string(t))?,
TyKind::Int(t) => write!(f, "{}", primitive::int_ty_to_string(t))?,
TyKind::Uint(t) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
TyKind::Slice(t) => {
write!(f, "[")?;
t.hir_fmt(f)?;
Expand Down
12 changes: 5 additions & 7 deletions crates/hir-ty/src/dyn_compatibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use hir_def::{
TypeAliasId, TypeOrConstParamId, TypeParamId, hir::generics::LocalTypeOrConstParamId,
lang_item::LangItem, signatures::TraitFlags,
};
use intern::Symbol;
use rustc_hash::FxHashSet;
use rustc_type_ir::{
AliasTyKind, ClauseKind, PredicatePolarity, TypeSuperVisitable as _, TypeVisitable as _,
Expand Down Expand Up @@ -441,8 +440,7 @@ fn receiver_is_dispatchable<'db>(

// Type `U`
// FIXME: That seems problematic to fake a generic param like that?
let unsized_self_ty =
crate::next_solver::Ty::new_param(interner, self_param_id, u32::MAX, Symbol::empty());
let unsized_self_ty = crate::next_solver::Ty::new_param(interner, self_param_id, u32::MAX);
// `Receiver[Self => U]`
let unsized_receiver_ty = receiver_for_self_ty(interner, func, receiver_ty, unsized_self_ty);

Expand All @@ -454,8 +452,8 @@ fn receiver_is_dispatchable<'db>(
TraitRef::new(interner, unsize_did.into(), [self_param_ty, unsized_self_ty]);

// U: Trait<Arg1, ..., ArgN>
let args = GenericArgs::for_item(interner, trait_.into(), |name, index, kind, _| {
if index == 0 { unsized_self_ty.into() } else { mk_param(interner, index, name, kind) }
let args = GenericArgs::for_item(interner, trait_.into(), |index, kind, _| {
if index == 0 { unsized_self_ty.into() } else { mk_param(interner, index, kind) }
});
let trait_predicate = TraitRef::new_from_args(interner, trait_.into(), args);

Expand Down Expand Up @@ -494,8 +492,8 @@ fn receiver_for_self_ty<'db>(
let args = crate::next_solver::GenericArgs::for_item(
interner,
SolverDefId::FunctionId(func),
|name, index, kind, _| {
if index == 0 { self_ty.into() } else { mk_param(interner, index, name, kind) }
|index, kind, _| {
if index == 0 { self_ty.into() } else { mk_param(interner, index, kind) }
},
);

Expand Down
2 changes: 1 addition & 1 deletion crates/hir-ty/src/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ impl Generics {
}

/// Returns a Substitution that replaces each parameter by itself (i.e. `Ty::Param`).
pub fn placeholder_subst(&self, db: &dyn HirDatabase) -> Substitution {
pub(crate) fn placeholder_subst(&self, db: &dyn HirDatabase) -> Substitution {
Substitution::from_iter(
Interner,
self.iter_id().enumerate().map(|(index, id)| match id {
Expand Down
18 changes: 4 additions & 14 deletions crates/hir-ty/src/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ use triomphe::Arc;
use crate::{
ImplTraitId, IncorrectGenericsLenKind, PathLoweringDiagnostic, TargetFeatures,
db::{HirDatabase, InternedClosureId, InternedOpaqueTyId},
generics::Generics,
infer::{
coerce::{CoerceMany, DynamicCoerceMany},
diagnostics::{Diagnostics, InferenceTyLoweringContext as TyLoweringContext},
Expand All @@ -72,10 +71,7 @@ use crate::{
Tys,
abi::Safety,
fold::fold_tys,
infer::{
DefineOpaqueTypes,
traits::{Obligation, ObligationCause},
},
infer::traits::{Obligation, ObligationCause},
mapping::ChalkToNextSolver,
},
traits::FnTrait,
Expand Down Expand Up @@ -763,8 +759,7 @@ pub(crate) struct InferenceContext<'body, 'db> {
/// and resolve the path via its methods. This will ensure proper error reporting.
pub(crate) resolver: Resolver<'db>,
target_features: OnceCell<(TargetFeatures, TargetFeatureIsSafeInTarget)>,
generic_def: GenericDefId,
generics: OnceCell<Generics>,
pub(crate) generic_def: GenericDefId,
table: unify::InferenceTable<'db>,
/// The traits in scope, disregarding block modules. This is used for caching purposes.
traits_in_scope: FxHashSet<TraitId>,
Expand Down Expand Up @@ -873,7 +868,6 @@ impl<'body, 'db> InferenceContext<'body, 'db> {
return_ty: types.error, // set in collect_* calls
types,
target_features: OnceCell::new(),
generics: OnceCell::new(),
table,
tuple_field_accesses_rev: Default::default(),
resume_yield_tys: None,
Expand Down Expand Up @@ -902,10 +896,6 @@ impl<'body, 'db> InferenceContext<'body, 'db> {
}
}

pub(crate) fn generics(&self) -> &Generics {
self.generics.get_or_init(|| crate::generics::generics(self.db, self.generic_def))
}

#[inline]
fn krate(&self) -> Crate {
self.resolver.krate()
Expand Down Expand Up @@ -1133,7 +1123,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> {
GenericArgs::for_item_with_defaults(
self.interner(),
va_list.into(),
|_, _, id, _| self.table.next_var_for_param(id),
|_, id, _| self.table.next_var_for_param(id),
),
),
None => self.err_ty(),
Expand Down Expand Up @@ -1676,7 +1666,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> {
.table
.infer_ctxt
.at(&ObligationCause::new(), self.table.trait_env.env)
.eq(DefineOpaqueTypes::Yes, expected, actual)
.eq(expected, actual)
.map(|infer_ok| self.table.register_infer_ok(infer_ok));
if let Err(_err) = result {
// FIXME: Emit diagnostic.
Expand Down
Loading