2019-11-26 08:26:08 -06:00
|
|
|
//! Helper functions for working with def, which don't need to be a separate
|
|
|
|
//! query, but can't be computed directly from `*Data` (ie, which need a `db`).
|
|
|
|
|
2023-06-06 18:42:41 -05:00
|
|
|
use std::{hash::Hash, iter};
|
2021-04-29 13:18:41 -05:00
|
|
|
|
2021-06-29 10:35:37 -05:00
|
|
|
use base_db::CrateId;
|
2023-05-26 15:58:11 -05:00
|
|
|
use chalk_ir::{
|
|
|
|
cast::Cast,
|
|
|
|
fold::{FallibleTypeFolder, Shift},
|
2023-06-03 08:54:10 -05:00
|
|
|
BoundVar, DebruijnIndex,
|
2023-05-26 15:58:11 -05:00
|
|
|
};
|
2023-02-25 06:50:27 -06:00
|
|
|
use either::Either;
|
2019-11-26 07:59:24 -06:00
|
|
|
use hir_def::{
|
|
|
|
db::DefDatabase,
|
2020-12-17 15:01:42 -06:00
|
|
|
generics::{
|
2022-06-12 07:40:37 -05:00
|
|
|
GenericParams, TypeOrConstParamData, TypeParamProvenance, WherePredicate,
|
2021-12-29 07:35:59 -06:00
|
|
|
WherePredicateTypeTarget,
|
2020-12-17 15:01:42 -06:00
|
|
|
},
|
2023-01-21 10:29:07 -06:00
|
|
|
lang_item::LangItem,
|
2019-11-26 07:59:24 -06:00
|
|
|
resolver::{HasResolver, TypeNs},
|
2021-06-14 07:36:56 -05:00
|
|
|
type_ref::{TraitBoundModifier, TypeRef},
|
2023-06-02 05:17:02 -05:00
|
|
|
ConstParamId, EnumId, EnumVariantId, FunctionId, GenericDefId, ItemContainerId,
|
2023-06-06 18:42:41 -05:00
|
|
|
LocalEnumVariantId, Lookup, OpaqueInternableThing, TraitId, TypeAliasId, TypeOrConstParamId,
|
|
|
|
TypeParamId,
|
2019-11-26 07:59:24 -06:00
|
|
|
};
|
2022-12-30 13:29:37 -06:00
|
|
|
use hir_expand::name::Name;
|
2023-01-09 12:29:28 -06:00
|
|
|
use intern::Interned;
|
2021-04-29 13:18:41 -05:00
|
|
|
use rustc_hash::FxHashSet;
|
2021-12-10 13:01:24 -06:00
|
|
|
use smallvec::{smallvec, SmallVec};
|
2023-04-28 12:14:30 -05:00
|
|
|
use stdx::never;
|
2019-11-26 07:59:24 -06:00
|
|
|
|
2021-04-29 13:18:41 -05:00
|
|
|
use crate::{
|
2023-06-02 05:17:02 -05:00
|
|
|
consteval::unknown_const,
|
|
|
|
db::HirDatabase,
|
|
|
|
layout::{Layout, TagEncoding},
|
|
|
|
mir::pad16,
|
|
|
|
ChalkTraitId, Const, ConstScalar, GenericArg, Interner, Substitution, TraitRef, TraitRefExt,
|
2023-06-03 08:54:10 -05:00
|
|
|
Ty, WhereClause,
|
2021-04-29 13:18:41 -05:00
|
|
|
};
|
2020-04-26 09:56:25 -05:00
|
|
|
|
2023-02-10 07:34:58 -06:00
|
|
|
pub(crate) fn fn_traits(
|
|
|
|
db: &dyn DefDatabase,
|
|
|
|
krate: CrateId,
|
|
|
|
) -> impl Iterator<Item = TraitId> + '_ {
|
|
|
|
[LangItem::Fn, LangItem::FnMut, LangItem::FnOnce]
|
|
|
|
.into_iter()
|
|
|
|
.filter_map(move |lang| db.lang_item(krate, lang))
|
|
|
|
.flat_map(|it| it.as_trait())
|
2021-06-29 10:35:37 -05:00
|
|
|
}
|
|
|
|
|
2023-02-10 07:34:58 -06:00
|
|
|
/// Returns an iterator over the whole super trait hierarchy (including the
|
|
|
|
/// trait itself).
|
|
|
|
pub fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> SmallVec<[TraitId; 4]> {
|
|
|
|
// we need to take care a bit here to avoid infinite loops in case of cycles
|
|
|
|
// (i.e. if we have `trait A: B; trait B: A;`)
|
|
|
|
|
|
|
|
let mut result = smallvec![trait_];
|
|
|
|
let mut i = 0;
|
|
|
|
while let Some(&t) = result.get(i) {
|
|
|
|
// yeah this is quadratic, but trait hierarchies should be flat
|
|
|
|
// enough that this doesn't matter
|
|
|
|
direct_super_traits(db, t, |tt| {
|
|
|
|
if !result.contains(&tt) {
|
|
|
|
result.push(tt);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
i += 1;
|
|
|
|
}
|
|
|
|
result
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Given a trait ref (`Self: Trait`), builds all the implied trait refs for
|
|
|
|
/// super traits. The original trait ref will be included. So the difference to
|
|
|
|
/// `all_super_traits` is that we keep track of type parameters; for example if
|
|
|
|
/// we have `Self: Trait<u32, i32>` and `Trait<T, U>: OtherTrait<U>` we'll get
|
|
|
|
/// `Self: OtherTrait<i32>`.
|
|
|
|
pub(super) fn all_super_trait_refs<T>(
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
trait_ref: TraitRef,
|
|
|
|
cb: impl FnMut(TraitRef) -> Option<T>,
|
|
|
|
) -> Option<T> {
|
|
|
|
let seen = iter::once(trait_ref.trait_id).collect();
|
2023-03-28 09:22:12 -05:00
|
|
|
SuperTraits { db, seen, stack: vec![trait_ref] }.find_map(cb)
|
2023-02-10 07:34:58 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
struct SuperTraits<'a> {
|
|
|
|
db: &'a dyn HirDatabase,
|
|
|
|
stack: Vec<TraitRef>,
|
|
|
|
seen: FxHashSet<ChalkTraitId>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> SuperTraits<'a> {
|
|
|
|
fn elaborate(&mut self, trait_ref: &TraitRef) {
|
|
|
|
direct_super_trait_refs(self.db, trait_ref, |trait_ref| {
|
|
|
|
if !self.seen.contains(&trait_ref.trait_id) {
|
|
|
|
self.stack.push(trait_ref);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Iterator for SuperTraits<'a> {
|
|
|
|
type Item = TraitRef;
|
|
|
|
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
|
|
if let Some(next) = self.stack.pop() {
|
|
|
|
self.elaborate(&next);
|
|
|
|
Some(next)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn direct_super_traits(db: &dyn DefDatabase, trait_: TraitId, cb: impl FnMut(TraitId)) {
|
2019-11-26 07:59:24 -06:00
|
|
|
let resolver = trait_.resolver(db);
|
2020-01-31 08:17:48 -06:00
|
|
|
let generic_params = db.generic_params(trait_.into());
|
|
|
|
let trait_self = generic_params.find_trait_self_param();
|
|
|
|
generic_params
|
2019-11-26 07:59:24 -06:00
|
|
|
.where_predicates
|
|
|
|
.iter()
|
2020-12-11 06:49:32 -06:00
|
|
|
.filter_map(|pred| match pred {
|
2020-12-17 15:01:42 -06:00
|
|
|
WherePredicate::ForLifetime { target, bound, .. }
|
2022-06-23 13:08:29 -05:00
|
|
|
| WherePredicate::TypeBound { target, bound } => {
|
|
|
|
let is_trait = match target {
|
|
|
|
WherePredicateTypeTarget::TypeRef(type_ref) => match &**type_ref {
|
|
|
|
TypeRef::Path(p) => p.is_self_type(),
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
WherePredicateTypeTarget::TypeOrConstParam(local_id) => {
|
|
|
|
Some(*local_id) == trait_self
|
|
|
|
}
|
|
|
|
};
|
|
|
|
match is_trait {
|
|
|
|
true => bound.as_path(),
|
|
|
|
false => None,
|
2020-12-11 06:49:32 -06:00
|
|
|
}
|
2022-06-23 13:08:29 -05:00
|
|
|
}
|
2020-12-17 15:01:42 -06:00
|
|
|
WherePredicate::Lifetime { .. } => None,
|
2019-11-26 07:59:24 -06:00
|
|
|
})
|
2022-06-23 13:08:29 -05:00
|
|
|
.filter(|(_, bound_modifier)| matches!(bound_modifier, TraitBoundModifier::None))
|
2023-03-08 11:28:52 -06:00
|
|
|
.filter_map(|(path, _)| match resolver.resolve_path_in_type_ns_fully(db, path) {
|
2019-11-26 07:59:24 -06:00
|
|
|
Some(TypeNs::TraitId(t)) => Some(t),
|
|
|
|
_ => None,
|
|
|
|
})
|
2023-02-10 07:34:58 -06:00
|
|
|
.for_each(cb);
|
2019-11-26 07:59:24 -06:00
|
|
|
}
|
|
|
|
|
2023-02-10 07:34:58 -06:00
|
|
|
fn direct_super_trait_refs(db: &dyn HirDatabase, trait_ref: &TraitRef, cb: impl FnMut(TraitRef)) {
|
2021-03-18 15:53:19 -05:00
|
|
|
let generic_params = db.generic_params(trait_ref.hir_trait_id().into());
|
2020-04-26 09:56:25 -05:00
|
|
|
let trait_self = match generic_params.find_trait_self_param() {
|
2021-12-29 07:35:59 -06:00
|
|
|
Some(p) => TypeOrConstParamId { parent: trait_ref.hir_trait_id().into(), local_id: p },
|
2023-02-10 07:34:58 -06:00
|
|
|
None => return,
|
2020-04-26 09:56:25 -05:00
|
|
|
};
|
2022-02-03 05:43:15 -06:00
|
|
|
db.generic_predicates_for_param(trait_self.parent, trait_self, None)
|
2020-04-26 09:56:25 -05:00
|
|
|
.iter()
|
|
|
|
.filter_map(|pred| {
|
2021-03-21 11:40:14 -05:00
|
|
|
pred.as_ref().filter_map(|pred| match pred.skip_binders() {
|
2021-03-24 17:07:54 -05:00
|
|
|
// FIXME: how to correctly handle higher-ranked bounds here?
|
2021-04-05 12:15:13 -05:00
|
|
|
WhereClause::Implemented(tr) => Some(
|
|
|
|
tr.clone()
|
2021-12-19 10:58:39 -06:00
|
|
|
.shifted_out_to(Interner, DebruijnIndex::ONE)
|
2021-04-05 12:15:13 -05:00
|
|
|
.expect("FIXME unexpected higher-ranked trait bound"),
|
|
|
|
),
|
2020-04-26 09:56:25 -05:00
|
|
|
_ => None,
|
|
|
|
})
|
|
|
|
})
|
2021-12-19 10:58:39 -06:00
|
|
|
.map(|pred| pred.substitute(Interner, &trait_ref.substitution))
|
2023-02-10 07:34:58 -06:00
|
|
|
.for_each(cb);
|
2020-04-26 09:56:25 -05:00
|
|
|
}
|
|
|
|
|
2019-11-26 09:02:50 -06:00
|
|
|
pub(super) fn associated_type_by_name_including_super_traits(
|
2020-06-19 09:29:38 -05:00
|
|
|
db: &dyn HirDatabase,
|
|
|
|
trait_ref: TraitRef,
|
2019-11-26 08:42:21 -06:00
|
|
|
name: &Name,
|
2020-06-19 09:29:38 -05:00
|
|
|
) -> Option<(TraitRef, TypeAliasId)> {
|
2023-02-10 07:34:58 -06:00
|
|
|
all_super_trait_refs(db, trait_ref, |t| {
|
2021-03-18 15:53:19 -05:00
|
|
|
let assoc_type = db.trait_data(t.hir_trait_id()).associated_type_by_name(name)?;
|
2020-06-19 09:29:38 -05:00
|
|
|
Some((t, assoc_type))
|
|
|
|
})
|
2019-11-26 08:42:21 -06:00
|
|
|
}
|
2019-11-27 07:25:01 -06:00
|
|
|
|
2020-03-13 10:05:46 -05:00
|
|
|
pub(crate) fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics {
|
2019-12-07 04:50:36 -06:00
|
|
|
let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def)));
|
|
|
|
Generics { def, params: db.generic_params(def), parent_generics }
|
|
|
|
}
|
|
|
|
|
2023-04-28 12:14:30 -05:00
|
|
|
/// It is a bit different from the rustc equivalent. Currently it stores:
|
|
|
|
/// - 0: the function signature, encoded as a function pointer type
|
|
|
|
/// - 1..n: generics of the parent
|
|
|
|
///
|
|
|
|
/// and it doesn't store the closure types and fields.
|
|
|
|
///
|
|
|
|
/// Codes should not assume this ordering, and should always use methods available
|
|
|
|
/// on this struct for retriving, and `TyBuilder::substs_for_closure` for creating.
|
|
|
|
pub(crate) struct ClosureSubst<'a>(pub(crate) &'a Substitution);
|
|
|
|
|
|
|
|
impl<'a> ClosureSubst<'a> {
|
|
|
|
pub(crate) fn parent_subst(&self) -> &'a [GenericArg] {
|
|
|
|
match self.0.as_slice(Interner) {
|
|
|
|
[_, x @ ..] => x,
|
|
|
|
_ => {
|
|
|
|
never!("Closure missing parameter");
|
|
|
|
&[]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn sig_ty(&self) -> &'a Ty {
|
|
|
|
match self.0.as_slice(Interner) {
|
|
|
|
[x, ..] => x.assert_ty_ref(Interner),
|
|
|
|
_ => {
|
|
|
|
unreachable!("Closure missing sig_ty parameter");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-19 09:29:38 -05:00
|
|
|
#[derive(Debug)]
|
2019-12-07 04:50:36 -06:00
|
|
|
pub(crate) struct Generics {
|
|
|
|
def: GenericDefId,
|
2021-04-04 20:50:10 -05:00
|
|
|
pub(crate) params: Interned<GenericParams>,
|
2019-12-07 04:50:36 -06:00
|
|
|
parent_generics: Option<Box<Generics>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Generics {
|
2022-12-30 03:00:42 -06:00
|
|
|
pub(crate) fn iter_id(&self) -> impl Iterator<Item = Either<TypeParamId, ConstParamId>> + '_ {
|
2022-03-09 12:50:24 -06:00
|
|
|
self.iter().map(|(id, data)| match data {
|
|
|
|
TypeOrConstParamData::TypeParamData(_) => Either::Left(TypeParamId::from_unchecked(id)),
|
|
|
|
TypeOrConstParamData::ConstParamData(_) => {
|
|
|
|
Either::Right(ConstParamId::from_unchecked(id))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
Change generic parameter/argument order
This commit "inverts" the order of generic parameters/arguments of an
item and its parent. This is to fulfill chalk's expectation on the
order of `Substitution` for generic associated types and it's one step
forward for their support (hopefully).
Although chalk doesn't put any constraint on the order of `Substitution`
for other items, it feels natural to get everything aligned rather than
special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in
parent's `Substitution` upon construction unless it's obvious that the
the item has no parent (e.g. an ADT never has parent). All users
*should* already know the parent of the item in question, and without
this, it cannot be easily reasoned about whether we're pushing the
argument for the item or for its parent.
Quick comparison of how this commit changes `Substitution`:
```rust
trait Trait<TP, const CP: usize> {
type Type<TC, const CC: usize> = ();
fn f<TC, const CC: usize>() {}
}
```
- before this commit: `[Self, TP, CP, TC, CC]` for each trait item
- after this commit: `[TC, CC, Self, TP, CP]` for each trait item
2022-10-02 07:13:21 -05:00
|
|
|
/// Iterator over types and const params of self, then parent.
|
2022-03-09 12:50:24 -06:00
|
|
|
pub(crate) fn iter<'a>(
|
|
|
|
&'a self,
|
|
|
|
) -> impl DoubleEndedIterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
|
2022-06-12 09:07:08 -05:00
|
|
|
let to_toc_id = |it: &'a Generics| {
|
|
|
|
move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p)
|
|
|
|
};
|
Change generic parameter/argument order
This commit "inverts" the order of generic parameters/arguments of an
item and its parent. This is to fulfill chalk's expectation on the
order of `Substitution` for generic associated types and it's one step
forward for their support (hopefully).
Although chalk doesn't put any constraint on the order of `Substitution`
for other items, it feels natural to get everything aligned rather than
special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in
parent's `Substitution` upon construction unless it's obvious that the
the item has no parent (e.g. an ADT never has parent). All users
*should* already know the parent of the item in question, and without
this, it cannot be easily reasoned about whether we're pushing the
argument for the item or for its parent.
Quick comparison of how this commit changes `Substitution`:
```rust
trait Trait<TP, const CP: usize> {
type Type<TC, const CC: usize> = ();
fn f<TC, const CC: usize>() {}
}
```
- before this commit: `[Self, TP, CP, TC, CC]` for each trait item
- after this commit: `[TC, CC, Self, TP, CP]` for each trait item
2022-10-02 07:13:21 -05:00
|
|
|
self.params.iter().map(to_toc_id(self)).chain(self.iter_parent())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Iterate over types and const params without parent params.
|
|
|
|
pub(crate) fn iter_self<'a>(
|
|
|
|
&'a self,
|
|
|
|
) -> impl DoubleEndedIterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
|
|
|
|
let to_toc_id = |it: &'a Generics| {
|
|
|
|
move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p)
|
|
|
|
};
|
|
|
|
self.params.iter().map(to_toc_id(self))
|
2022-03-08 10:21:35 -06:00
|
|
|
}
|
|
|
|
|
2022-03-09 12:50:24 -06:00
|
|
|
/// Iterator over types and const params of parent.
|
2022-12-30 03:00:42 -06:00
|
|
|
pub(crate) fn iter_parent(
|
|
|
|
&self,
|
|
|
|
) -> impl DoubleEndedIterator<Item = (TypeOrConstParamId, &TypeOrConstParamData)> {
|
2022-06-12 09:07:08 -05:00
|
|
|
self.parent_generics().into_iter().flat_map(|it| {
|
|
|
|
let to_toc_id =
|
|
|
|
move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p);
|
|
|
|
it.params.iter().map(to_toc_id)
|
2020-02-07 08:13:15 -06:00
|
|
|
})
|
2019-12-07 04:50:36 -06:00
|
|
|
}
|
|
|
|
|
Change generic parameter/argument order
This commit "inverts" the order of generic parameters/arguments of an
item and its parent. This is to fulfill chalk's expectation on the
order of `Substitution` for generic associated types and it's one step
forward for their support (hopefully).
Although chalk doesn't put any constraint on the order of `Substitution`
for other items, it feels natural to get everything aligned rather than
special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in
parent's `Substitution` upon construction unless it's obvious that the
the item has no parent (e.g. an ADT never has parent). All users
*should* already know the parent of the item in question, and without
this, it cannot be easily reasoned about whether we're pushing the
argument for the item or for its parent.
Quick comparison of how this commit changes `Substitution`:
```rust
trait Trait<TP, const CP: usize> {
type Type<TC, const CC: usize> = ();
fn f<TC, const CC: usize>() {}
}
```
- before this commit: `[Self, TP, CP, TC, CC]` for each trait item
- after this commit: `[TC, CC, Self, TP, CP]` for each trait item
2022-10-02 07:13:21 -05:00
|
|
|
/// Returns total number of generic parameters in scope, including those from parent.
|
2019-12-07 06:05:05 -06:00
|
|
|
pub(crate) fn len(&self) -> usize {
|
2022-06-12 09:07:08 -05:00
|
|
|
let parent = self.parent_generics().map_or(0, Generics::len);
|
2022-03-09 12:50:24 -06:00
|
|
|
let child = self.params.type_or_consts.len();
|
2022-06-12 09:07:08 -05:00
|
|
|
parent + child
|
2019-12-07 04:50:36 -06:00
|
|
|
}
|
2020-01-25 16:38:33 -06:00
|
|
|
|
Change generic parameter/argument order
This commit "inverts" the order of generic parameters/arguments of an
item and its parent. This is to fulfill chalk's expectation on the
order of `Substitution` for generic associated types and it's one step
forward for their support (hopefully).
Although chalk doesn't put any constraint on the order of `Substitution`
for other items, it feels natural to get everything aligned rather than
special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in
parent's `Substitution` upon construction unless it's obvious that the
the item has no parent (e.g. an ADT never has parent). All users
*should* already know the parent of the item in question, and without
this, it cannot be easily reasoned about whether we're pushing the
argument for the item or for its parent.
Quick comparison of how this commit changes `Substitution`:
```rust
trait Trait<TP, const CP: usize> {
type Type<TC, const CC: usize> = ();
fn f<TC, const CC: usize>() {}
}
```
- before this commit: `[Self, TP, CP, TC, CC]` for each trait item
- after this commit: `[TC, CC, Self, TP, CP]` for each trait item
2022-10-02 07:13:21 -05:00
|
|
|
/// Returns numbers of generic parameters excluding those from parent.
|
|
|
|
pub(crate) fn len_self(&self) -> usize {
|
|
|
|
self.params.type_or_consts.len()
|
|
|
|
}
|
|
|
|
|
2022-03-08 10:21:35 -06:00
|
|
|
/// (parent total, self param, type param list, const param list, impl trait)
|
|
|
|
pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize, usize) {
|
2023-02-10 07:34:58 -06:00
|
|
|
let mut self_params = 0;
|
|
|
|
let mut type_params = 0;
|
|
|
|
let mut impl_trait_params = 0;
|
|
|
|
let mut const_params = 0;
|
|
|
|
self.params.iter().for_each(|(_, data)| match data {
|
|
|
|
TypeOrConstParamData::TypeParamData(p) => match p.provenance {
|
|
|
|
TypeParamProvenance::TypeParamList => type_params += 1,
|
|
|
|
TypeParamProvenance::TraitSelf => self_params += 1,
|
|
|
|
TypeParamProvenance::ArgumentImplTrait => impl_trait_params += 1,
|
|
|
|
},
|
|
|
|
TypeOrConstParamData::ConstParamData(_) => const_params += 1,
|
|
|
|
});
|
2022-06-12 09:07:08 -05:00
|
|
|
|
|
|
|
let parent_len = self.parent_generics().map_or(0, Generics::len);
|
|
|
|
(parent_len, self_params, type_params, const_params, impl_trait_params)
|
2020-01-25 16:38:33 -06:00
|
|
|
}
|
|
|
|
|
2021-12-29 07:35:59 -06:00
|
|
|
pub(crate) fn param_idx(&self, param: TypeOrConstParamId) -> Option<usize> {
|
2020-01-31 09:52:43 -06:00
|
|
|
Some(self.find_param(param)?.0)
|
2019-12-07 04:50:36 -06:00
|
|
|
}
|
2020-01-25 16:38:33 -06:00
|
|
|
|
2021-12-29 07:35:59 -06:00
|
|
|
fn find_param(&self, param: TypeOrConstParamId) -> Option<(usize, &TypeOrConstParamData)> {
|
2019-12-07 04:50:36 -06:00
|
|
|
if param.parent == self.def {
|
2022-08-16 10:30:17 -05:00
|
|
|
let (idx, (_local_id, data)) =
|
|
|
|
self.params.iter().enumerate().find(|(_, (idx, _))| *idx == param.local_id)?;
|
Change generic parameter/argument order
This commit "inverts" the order of generic parameters/arguments of an
item and its parent. This is to fulfill chalk's expectation on the
order of `Substitution` for generic associated types and it's one step
forward for their support (hopefully).
Although chalk doesn't put any constraint on the order of `Substitution`
for other items, it feels natural to get everything aligned rather than
special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in
parent's `Substitution` upon construction unless it's obvious that the
the item has no parent (e.g. an ADT never has parent). All users
*should* already know the parent of the item in question, and without
this, it cannot be easily reasoned about whether we're pushing the
argument for the item or for its parent.
Quick comparison of how this commit changes `Substitution`:
```rust
trait Trait<TP, const CP: usize> {
type Type<TC, const CC: usize> = ();
fn f<TC, const CC: usize>() {}
}
```
- before this commit: `[Self, TP, CP, TC, CC]` for each trait item
- after this commit: `[TC, CC, Self, TP, CP]` for each trait item
2022-10-02 07:13:21 -05:00
|
|
|
Some((idx, data))
|
2020-01-31 09:52:43 -06:00
|
|
|
} else {
|
Change generic parameter/argument order
This commit "inverts" the order of generic parameters/arguments of an
item and its parent. This is to fulfill chalk's expectation on the
order of `Substitution` for generic associated types and it's one step
forward for their support (hopefully).
Although chalk doesn't put any constraint on the order of `Substitution`
for other items, it feels natural to get everything aligned rather than
special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in
parent's `Substitution` upon construction unless it's obvious that the
the item has no parent (e.g. an ADT never has parent). All users
*should* already know the parent of the item in question, and without
this, it cannot be easily reasoned about whether we're pushing the
argument for the item or for its parent.
Quick comparison of how this commit changes `Substitution`:
```rust
trait Trait<TP, const CP: usize> {
type Type<TC, const CC: usize> = ();
fn f<TC, const CC: usize>() {}
}
```
- before this commit: `[Self, TP, CP, TC, CC]` for each trait item
- after this commit: `[TC, CC, Self, TP, CP]` for each trait item
2022-10-02 07:13:21 -05:00
|
|
|
self.parent_generics()
|
|
|
|
.and_then(|g| g.find_param(param))
|
|
|
|
// Remember that parent parameters come after parameters for self.
|
|
|
|
.map(|(idx, data)| (self.len_self() + idx, data))
|
2019-12-07 04:50:36 -06:00
|
|
|
}
|
|
|
|
}
|
2021-04-04 06:07:06 -05:00
|
|
|
|
2022-10-02 04:39:42 -05:00
|
|
|
pub(crate) fn parent_generics(&self) -> Option<&Generics> {
|
|
|
|
self.parent_generics.as_deref()
|
2022-06-12 09:07:08 -05:00
|
|
|
}
|
|
|
|
|
2021-04-04 06:07:06 -05:00
|
|
|
/// Returns a Substitution that replaces each parameter by a bound variable.
|
2022-03-09 12:50:24 -06:00
|
|
|
pub(crate) fn bound_vars_subst(
|
|
|
|
&self,
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
debruijn: DebruijnIndex,
|
|
|
|
) -> Substitution {
|
2021-04-04 06:07:06 -05:00
|
|
|
Substitution::from_iter(
|
2021-12-19 10:58:39 -06:00
|
|
|
Interner,
|
2022-03-09 12:50:24 -06:00
|
|
|
self.iter_id().enumerate().map(|(idx, id)| match id {
|
2022-10-02 04:39:42 -05:00
|
|
|
Either::Left(_) => BoundVar::new(debruijn, idx).to_ty(Interner).cast(Interner),
|
|
|
|
Either::Right(id) => BoundVar::new(debruijn, idx)
|
|
|
|
.to_const(Interner, db.const_param_ty(id))
|
|
|
|
.cast(Interner),
|
2022-03-09 12:50:24 -06:00
|
|
|
}),
|
2021-04-04 06:07:06 -05:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a Substitution that replaces each parameter by itself (i.e. `Ty::Param`).
|
2022-03-09 12:50:24 -06:00
|
|
|
pub(crate) fn placeholder_subst(&self, db: &dyn HirDatabase) -> Substitution {
|
2021-04-04 06:07:06 -05:00
|
|
|
Substitution::from_iter(
|
2021-12-19 10:58:39 -06:00
|
|
|
Interner,
|
2022-03-09 12:50:24 -06:00
|
|
|
self.iter_id().map(|id| match id {
|
2022-10-02 04:39:42 -05:00
|
|
|
Either::Left(id) => {
|
|
|
|
crate::to_placeholder_idx(db, id.into()).to_ty(Interner).cast(Interner)
|
|
|
|
}
|
|
|
|
Either::Right(id) => crate::to_placeholder_idx(db, id.into())
|
|
|
|
.to_const(Interner, db.const_param_ty(id))
|
|
|
|
.cast(Interner),
|
2021-04-04 06:07:06 -05:00
|
|
|
}),
|
|
|
|
)
|
|
|
|
}
|
2019-12-07 04:50:36 -06:00
|
|
|
}
|
|
|
|
|
2020-03-13 10:05:46 -05:00
|
|
|
fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
|
2019-12-07 04:50:36 -06:00
|
|
|
let container = match def {
|
|
|
|
GenericDefId::FunctionId(it) => it.lookup(db).container,
|
|
|
|
GenericDefId::TypeAliasId(it) => it.lookup(db).container,
|
|
|
|
GenericDefId::ConstId(it) => it.lookup(db).container,
|
|
|
|
GenericDefId::EnumVariantId(it) => return Some(it.parent.into()),
|
2023-03-03 09:24:07 -06:00
|
|
|
GenericDefId::AdtId(_)
|
|
|
|
| GenericDefId::TraitId(_)
|
|
|
|
| GenericDefId::ImplId(_)
|
|
|
|
| GenericDefId::TraitAliasId(_) => return None,
|
2019-12-07 04:50:36 -06:00
|
|
|
};
|
|
|
|
|
|
|
|
match container {
|
2021-12-07 10:31:26 -06:00
|
|
|
ItemContainerId::ImplId(it) => Some(it.into()),
|
|
|
|
ItemContainerId::TraitId(it) => Some(it.into()),
|
|
|
|
ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
|
2019-12-07 04:50:36 -06:00
|
|
|
}
|
|
|
|
}
|
2022-04-07 11:33:03 -05:00
|
|
|
|
|
|
|
pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool {
|
|
|
|
let data = db.function_data(func);
|
|
|
|
if data.has_unsafe_kw() {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
match func.lookup(db.upcast()).container {
|
|
|
|
hir_def::ItemContainerId::ExternBlockId(block) => {
|
|
|
|
// Function in an `extern` block are always unsafe to call, except when it has
|
|
|
|
// `"rust-intrinsic"` ABI there are a few exceptions.
|
|
|
|
let id = block.lookup(db.upcast()).id;
|
2022-12-30 13:29:37 -06:00
|
|
|
|
|
|
|
let is_intrinsic =
|
|
|
|
id.item_tree(db.upcast())[id.value].abi.as_deref() == Some("rust-intrinsic");
|
|
|
|
|
|
|
|
if is_intrinsic {
|
|
|
|
// Intrinsics are unsafe unless they have the rustc_safe_intrinsic attribute
|
|
|
|
!data.attrs.by_key("rustc_safe_intrinsic").exists()
|
|
|
|
} else {
|
|
|
|
// Extern items are always unsafe
|
|
|
|
true
|
|
|
|
}
|
2022-04-07 11:33:03 -05:00
|
|
|
}
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
2023-04-06 07:44:38 -05:00
|
|
|
|
2023-05-26 15:58:11 -05:00
|
|
|
pub(crate) struct UnevaluatedConstEvaluatorFolder<'a> {
|
|
|
|
pub(crate) db: &'a dyn HirDatabase,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FallibleTypeFolder<Interner> for UnevaluatedConstEvaluatorFolder<'_> {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
fn as_dyn(&mut self) -> &mut dyn FallibleTypeFolder<Interner, Error = ()> {
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
fn interner(&self) -> Interner {
|
|
|
|
Interner
|
|
|
|
}
|
|
|
|
|
|
|
|
fn try_fold_const(
|
|
|
|
&mut self,
|
|
|
|
constant: Const,
|
|
|
|
_outer_binder: DebruijnIndex,
|
|
|
|
) -> Result<Const, Self::Error> {
|
|
|
|
if let chalk_ir::ConstValue::Concrete(c) = &constant.data(Interner).value {
|
|
|
|
if let ConstScalar::UnevaluatedConst(id, subst) = &c.interned {
|
|
|
|
if let Ok(eval) = self.db.const_eval(*id, subst.clone()) {
|
|
|
|
return Ok(eval);
|
|
|
|
} else {
|
|
|
|
return Ok(unknown_const(constant.data(Interner).ty.clone()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(constant)
|
|
|
|
}
|
|
|
|
}
|
2023-06-02 05:17:02 -05:00
|
|
|
|
|
|
|
pub(crate) fn detect_variant_from_bytes<'a>(
|
|
|
|
layout: &'a Layout,
|
|
|
|
db: &dyn HirDatabase,
|
|
|
|
krate: CrateId,
|
|
|
|
b: &[u8],
|
|
|
|
e: EnumId,
|
|
|
|
) -> Option<(LocalEnumVariantId, &'a Layout)> {
|
|
|
|
let (var_id, var_layout) = match &layout.variants {
|
|
|
|
hir_def::layout::Variants::Single { index } => (index.0, &*layout),
|
|
|
|
hir_def::layout::Variants::Multiple { tag, tag_encoding, variants, .. } => {
|
|
|
|
let target_data_layout = db.target_data_layout(krate)?;
|
|
|
|
let size = tag.size(&*target_data_layout).bytes_usize();
|
|
|
|
let offset = layout.fields.offset(0).bytes_usize(); // The only field on enum variants is the tag field
|
|
|
|
let tag = i128::from_le_bytes(pad16(&b[offset..offset + size], false));
|
|
|
|
match tag_encoding {
|
|
|
|
TagEncoding::Direct => {
|
|
|
|
let x = variants.iter_enumerated().find(|x| {
|
|
|
|
db.const_eval_discriminant(EnumVariantId { parent: e, local_id: x.0 .0 })
|
|
|
|
== Ok(tag)
|
|
|
|
})?;
|
|
|
|
(x.0 .0, x.1)
|
|
|
|
}
|
|
|
|
TagEncoding::Niche { untagged_variant, niche_start, .. } => {
|
|
|
|
let candidate_tag = tag.wrapping_sub(*niche_start as i128) as usize;
|
|
|
|
let variant = variants
|
|
|
|
.iter_enumerated()
|
|
|
|
.map(|(x, _)| x)
|
|
|
|
.filter(|x| x != untagged_variant)
|
|
|
|
.nth(candidate_tag)
|
|
|
|
.unwrap_or(*untagged_variant);
|
|
|
|
(variant.0, &variants[variant])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
Some((var_id, var_layout))
|
|
|
|
}
|
2023-06-06 18:42:41 -05:00
|
|
|
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
|
|
pub(crate) struct InTypeConstIdMetadata(pub(crate) Ty);
|
|
|
|
|
|
|
|
impl OpaqueInternableThing for InTypeConstIdMetadata {
|
|
|
|
fn dyn_hash(&self, mut state: &mut dyn std::hash::Hasher) {
|
|
|
|
self.hash(&mut state);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn dyn_eq(&self, other: &dyn OpaqueInternableThing) -> bool {
|
|
|
|
other.as_any().downcast_ref::<Self>().map_or(false, |x| self == x)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn dyn_clone(&self) -> Box<dyn OpaqueInternableThing> {
|
|
|
|
Box::new(self.clone())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn as_any(&self) -> &dyn std::any::Any {
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
fn box_any(&self) -> Box<dyn std::any::Any> {
|
|
|
|
Box::new(self.clone())
|
|
|
|
}
|
|
|
|
}
|