rust/crates/hir_ty/src/builder.rs

299 lines
10 KiB
Rust
Raw Normal View History

2021-04-04 05:55:47 -05:00
//! `TyBuilder`, a helper for building instances of `Ty` and related types.
use std::iter;
use chalk_ir::{
cast::{Cast, CastTo, Caster},
2021-04-07 14:12:42 -05:00
fold::Fold,
2021-04-04 05:55:47 -05:00
interner::HasInterner,
2021-05-02 09:20:37 -05:00
AdtId, BoundVar, DebruijnIndex, Scalar,
2021-04-04 05:55:47 -05:00
};
2022-03-09 12:50:24 -06:00
use hir_def::{
builtin_type::BuiltinType, generics::TypeOrConstParamData, ConstParamId, GenericDefId, TraitId,
TypeAliasId,
};
2021-04-04 05:55:47 -05:00
use smallvec::SmallVec;
use crate::{
2022-03-09 12:50:24 -06:00
consteval::unknown_const_as_generic, db::HirDatabase, primitive, to_assoc_type_id,
to_chalk_trait_id, utils::generics, Binders, CallableSig, ConstData, ConstValue, GenericArg,
GenericArgData, Interner, ProjectionTy, Substitution, TraitRef, Ty, TyDefId, TyExt, TyKind,
ValueTyDefId,
2021-04-04 05:55:47 -05:00
};
2022-03-09 12:50:24 -06:00
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParamKind {
Type,
Const(Ty),
}
2021-04-04 06:23:22 -05:00
/// This is a builder for `Ty` or anything that needs a `Substitution`.
2021-04-04 05:55:47 -05:00
pub struct TyBuilder<D> {
2021-04-04 06:23:22 -05:00
/// The `data` field is used to keep track of what we're building (e.g. an
/// ADT, a `TraitRef`, ...).
2021-04-04 05:55:47 -05:00
data: D,
vec: SmallVec<[GenericArg; 2]>,
2022-03-09 12:50:24 -06:00
param_kinds: SmallVec<[ParamKind; 2]>,
}
impl<A> TyBuilder<A> {
fn with_data<B>(self, data: B) -> TyBuilder<B> {
TyBuilder { data, param_kinds: self.param_kinds, vec: self.vec }
}
2021-04-04 05:55:47 -05:00
}
impl<D> TyBuilder<D> {
2022-03-09 12:50:24 -06:00
fn new(data: D, param_kinds: SmallVec<[ParamKind; 2]>) -> TyBuilder<D> {
TyBuilder { data, vec: SmallVec::with_capacity(param_kinds.len()), param_kinds }
2021-04-04 05:55:47 -05:00
}
fn build_internal(self) -> (D, Substitution) {
2022-03-09 12:50:24 -06:00
assert_eq!(self.vec.len(), self.param_kinds.len());
for (a, e) in self.vec.iter().zip(self.param_kinds.iter()) {
self.assert_match_kind(a, e);
}
2021-12-19 10:58:39 -06:00
let subst = Substitution::from_iter(Interner, self.vec);
2021-04-04 05:55:47 -05:00
(self.data, subst)
}
pub fn push(mut self, arg: impl CastTo<GenericArg>) -> Self {
2022-03-09 12:50:24 -06:00
let arg = arg.cast(Interner);
let expected_kind = &self.param_kinds[self.vec.len()];
let arg_kind = match arg.data(Interner) {
chalk_ir::GenericArgData::Ty(_) => ParamKind::Type,
chalk_ir::GenericArgData::Lifetime(_) => panic!("Got lifetime in TyBuilder::push"),
chalk_ir::GenericArgData::Const(c) => {
let c = c.data(Interner);
ParamKind::Const(c.ty.clone())
}
};
assert_eq!(*expected_kind, arg_kind);
self.vec.push(arg);
2021-04-04 05:55:47 -05:00
self
}
pub fn remaining(&self) -> usize {
2022-03-09 12:50:24 -06:00
self.param_kinds.len() - self.vec.len()
2021-04-04 05:55:47 -05:00
}
pub fn fill_with_bound_vars(self, debruijn: DebruijnIndex, starting_from: usize) -> Self {
2022-03-09 12:50:24 -06:00
// self.fill is inlined to make borrow checker happy
let mut this = self;
let other = this.param_kinds.iter().skip(this.vec.len());
let filler = (starting_from..).zip(other).map(|(idx, kind)| match kind {
ParamKind::Type => {
GenericArgData::Ty(TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(Interner))
.intern(Interner)
}
ParamKind::Const(ty) => GenericArgData::Const(
ConstData {
value: ConstValue::BoundVar(BoundVar::new(debruijn, idx)),
ty: ty.clone(),
}
.intern(Interner),
)
.intern(Interner),
});
this.vec.extend(filler.take(this.remaining()).casted(Interner));
assert_eq!(this.remaining(), 0);
this
2021-04-04 05:55:47 -05:00
}
pub fn fill_with_unknown(self) -> Self {
2022-03-09 12:50:24 -06:00
// self.fill is inlined to make borrow checker happy
let mut this = self;
let filler = this.param_kinds.iter().skip(this.vec.len()).map(|x| match x {
ParamKind::Type => GenericArgData::Ty(TyKind::Error.intern(Interner)).intern(Interner),
ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
});
this.vec.extend(filler.casted(Interner));
assert_eq!(this.remaining(), 0);
this
2021-04-04 05:55:47 -05:00
}
2022-03-09 12:50:24 -06:00
pub fn fill(mut self, filler: impl FnMut(&ParamKind) -> GenericArg) -> Self {
self.vec.extend(self.param_kinds.iter().skip(self.vec.len()).map(filler));
2021-04-04 05:55:47 -05:00
assert_eq!(self.remaining(), 0);
self
}
pub fn use_parent_substs(mut self, parent_substs: &Substitution) -> Self {
assert!(self.vec.is_empty());
2022-03-09 12:50:24 -06:00
assert!(parent_substs.len(Interner) <= self.param_kinds.len());
self.extend(parent_substs.iter(Interner).cloned());
2021-04-04 05:55:47 -05:00
self
}
2022-03-09 12:50:24 -06:00
fn extend(&mut self, it: impl Iterator<Item = GenericArg> + Clone) {
for x in it.clone().zip(self.param_kinds.iter().skip(self.vec.len())) {
self.assert_match_kind(&x.0, &x.1);
}
self.vec.extend(it);
}
fn assert_match_kind(&self, a: &chalk_ir::GenericArg<Interner>, e: &ParamKind) {
match (a.data(Interner), e) {
(chalk_ir::GenericArgData::Ty(_), ParamKind::Type)
| (chalk_ir::GenericArgData::Const(_), ParamKind::Const(_)) => (),
_ => panic!("Mismatched kinds: {:?}, {:?}, {:?}", a, self.vec, self.param_kinds),
}
}
2021-04-04 05:55:47 -05:00
}
impl TyBuilder<()> {
pub fn unit() -> Ty {
2021-12-19 10:58:39 -06:00
TyKind::Tuple(0, Substitution::empty(Interner)).intern(Interner)
2021-04-04 05:55:47 -05:00
}
pub fn fn_ptr(sig: CallableSig) -> Ty {
2021-12-19 10:58:39 -06:00
TyKind::Function(sig.to_fn_ptr()).intern(Interner)
2021-04-04 05:55:47 -05:00
}
pub fn builtin(builtin: BuiltinType) -> Ty {
match builtin {
2021-12-19 10:58:39 -06:00
BuiltinType::Char => TyKind::Scalar(Scalar::Char).intern(Interner),
BuiltinType::Bool => TyKind::Scalar(Scalar::Bool).intern(Interner),
BuiltinType::Str => TyKind::Str.intern(Interner),
2021-04-04 05:55:47 -05:00
BuiltinType::Int(t) => {
2021-12-19 10:58:39 -06:00
TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(t))).intern(Interner)
2021-04-04 05:55:47 -05:00
}
BuiltinType::Uint(t) => {
2021-12-19 10:58:39 -06:00
TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(t))).intern(Interner)
2021-04-04 05:55:47 -05:00
}
BuiltinType::Float(t) => {
2021-12-19 10:58:39 -06:00
TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(t))).intern(Interner)
2021-04-04 05:55:47 -05:00
}
}
}
2021-09-29 07:04:32 -05:00
pub fn slice(argument: Ty) -> Ty {
2021-12-19 10:58:39 -06:00
TyKind::Slice(argument).intern(Interner)
2021-09-29 07:04:32 -05:00
}
2022-03-09 12:50:24 -06:00
pub fn placeholder_subst(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substitution {
2021-04-04 06:16:16 -05:00
let params = generics(db.upcast(), def.into());
2022-03-09 12:50:24 -06:00
params.placeholder_subst(db)
2021-04-04 06:16:16 -05:00
}
2021-04-04 05:55:47 -05:00
pub fn subst_for_def(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> TyBuilder<()> {
let def = def.into();
let params = generics(db.upcast(), def);
2022-03-09 12:50:24 -06:00
TyBuilder::new(
(),
params
.iter()
.map(|(id, data)| match data {
TypeOrConstParamData::TypeParamData(_) => ParamKind::Type,
TypeOrConstParamData::ConstParamData(_) => {
ParamKind::Const(db.const_param_ty(ConstParamId::from_unchecked(id)))
}
})
.collect(),
)
2021-04-04 05:55:47 -05:00
}
pub fn build(self) -> Substitution {
let ((), subst) = self.build_internal();
subst
}
}
impl TyBuilder<hir_def::AdtId> {
2022-03-09 12:50:24 -06:00
pub fn adt(db: &dyn HirDatabase, def: hir_def::AdtId) -> TyBuilder<hir_def::AdtId> {
TyBuilder::subst_for_def(db, def).with_data(def)
2021-04-04 05:55:47 -05:00
}
pub fn fill_with_defaults(
mut self,
db: &dyn HirDatabase,
mut fallback: impl FnMut() -> Ty,
) -> Self {
let defaults = db.generic_defaults(self.data.into());
for default_ty in defaults.iter().skip(self.vec.len()) {
2022-03-09 12:50:24 -06:00
if let GenericArgData::Ty(x) = default_ty.skip_binders().data(Interner) {
if x.is_unknown() {
self.vec.push(fallback().cast(Interner));
continue;
}
};
// each default can depend on the previous parameters
let subst_so_far = Substitution::from_iter(Interner, self.vec.clone());
self.vec.push(default_ty.clone().substitute(Interner, &subst_so_far).cast(Interner));
2021-04-04 05:55:47 -05:00
}
self
}
pub fn build(self) -> Ty {
let (adt, subst) = self.build_internal();
2021-12-19 10:58:39 -06:00
TyKind::Adt(AdtId(adt), subst).intern(Interner)
2021-04-04 05:55:47 -05:00
}
}
pub struct Tuple(usize);
impl TyBuilder<Tuple> {
pub fn tuple(size: usize) -> TyBuilder<Tuple> {
2022-03-09 12:50:24 -06:00
TyBuilder::new(Tuple(size), iter::repeat(ParamKind::Type).take(size).collect())
2021-04-04 05:55:47 -05:00
}
pub fn build(self) -> Ty {
let (Tuple(size), subst) = self.build_internal();
2021-12-19 10:58:39 -06:00
TyKind::Tuple(size, subst).intern(Interner)
2021-04-04 05:55:47 -05:00
}
}
impl TyBuilder<TraitId> {
2022-03-09 12:50:24 -06:00
pub fn trait_ref(db: &dyn HirDatabase, def: TraitId) -> TyBuilder<TraitId> {
TyBuilder::subst_for_def(db, def).with_data(def)
2021-04-04 05:55:47 -05:00
}
pub fn build(self) -> TraitRef {
let (trait_id, substitution) = self.build_internal();
TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution }
}
}
impl TyBuilder<TypeAliasId> {
2022-03-09 12:50:24 -06:00
pub fn assoc_type_projection(db: &dyn HirDatabase, def: TypeAliasId) -> TyBuilder<TypeAliasId> {
TyBuilder::subst_for_def(db, def).with_data(def)
2021-04-04 05:55:47 -05:00
}
pub fn build(self) -> ProjectionTy {
let (type_alias, substitution) = self.build_internal();
ProjectionTy { associated_ty_id: to_assoc_type_id(type_alias), substitution }
}
}
2021-04-07 14:12:42 -05:00
impl<T: HasInterner<Interner = Interner> + Fold<Interner>> TyBuilder<Binders<T>> {
2021-04-04 05:55:47 -05:00
fn subst_binders(b: Binders<T>) -> Self {
2022-03-09 12:50:24 -06:00
let param_kinds = b
.binders
.iter(Interner)
.map(|x| match x {
chalk_ir::VariableKind::Ty(_) => ParamKind::Type,
chalk_ir::VariableKind::Lifetime => panic!("Got lifetime parameter"),
chalk_ir::VariableKind::Const(ty) => ParamKind::Const(ty.clone()),
})
.collect();
TyBuilder::new(b, param_kinds)
2021-04-04 05:55:47 -05:00
}
2021-04-07 14:12:42 -05:00
pub fn build(self) -> <T as Fold<Interner>>::Result {
2021-04-04 05:55:47 -05:00
let (b, subst) = self.build_internal();
2021-12-19 10:58:39 -06:00
b.substitute(Interner, &subst)
2021-04-04 05:55:47 -05:00
}
}
impl TyBuilder<Binders<Ty>> {
pub fn def_ty(db: &dyn HirDatabase, def: TyDefId) -> TyBuilder<Binders<Ty>> {
2021-06-12 22:55:55 -05:00
TyBuilder::subst_binders(db.ty(def))
2021-04-04 05:55:47 -05:00
}
pub fn impl_self_ty(db: &dyn HirDatabase, def: hir_def::ImplId) -> TyBuilder<Binders<Ty>> {
TyBuilder::subst_binders(db.impl_self_ty(def))
}
pub fn value_ty(db: &dyn HirDatabase, def: ValueTyDefId) -> TyBuilder<Binders<Ty>> {
TyBuilder::subst_binders(db.value_ty(def))
}
}