2006: Improvements around `Arc<[T]>` r=matklad a=sinkuu

First commit tries to avoid cloning `Arc<[T]>` to a temporary `Vec` for mutating it, if there are no other strong references. Second commit utilizes [`FromIterator for Arc<[T]>`](https://doc.rust-lang.org/std/sync/struct.Arc.html#impl-FromIterator%3CT%3E) instead of `.collect::<Vec<_>>().into()` to avoid allocation in `From<Vec<T>> for Arc<[T]>`.

Co-authored-by: Shotaro Yamada <sinkuu@sinkuu.xyz>
This commit is contained in:
bors[bot] 2019-10-14 13:14:18 +00:00 committed by GitHub
commit e182825170
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 49 additions and 50 deletions

View File

@ -51,6 +51,7 @@ mod lang_item;
mod generics;
mod resolve;
pub mod diagnostics;
mod util;
mod code_model;

View File

@ -17,8 +17,8 @@ use std::sync::Arc;
use std::{fmt, iter, mem};
use crate::{
db::HirDatabase, expr::ExprId, type_ref::Mutability, Adt, Crate, DefWithBody, GenericParams,
HasGenericParams, Name, Trait, TypeAlias,
db::HirDatabase, expr::ExprId, type_ref::Mutability, util::make_mut_slice, Adt, Crate,
DefWithBody, GenericParams, HasGenericParams, Name, Trait, TypeAlias,
};
use display::{HirDisplay, HirFormatter};
@ -308,12 +308,9 @@ impl Substs {
}
pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
// Without an Arc::make_mut_slice, we can't avoid the clone here:
let mut v: Vec<_> = self.0.iter().cloned().collect();
for t in &mut v {
for t in make_mut_slice(&mut self.0) {
t.walk_mut(f);
}
self.0 = v.into();
}
pub fn as_single(&self) -> &Ty {
@ -330,8 +327,7 @@ impl Substs {
.params_including_parent()
.into_iter()
.map(|p| Ty::Param { idx: p.idx, name: p.name.clone() })
.collect::<Vec<_>>()
.into(),
.collect(),
)
}
@ -342,8 +338,7 @@ impl Substs {
.params_including_parent()
.into_iter()
.map(|p| Ty::Bound(p.idx))
.collect::<Vec<_>>()
.into(),
.collect(),
)
}
@ -541,12 +536,9 @@ impl TypeWalk for FnSig {
}
fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
// Without an Arc::make_mut_slice, we can't avoid the clone here:
let mut v: Vec<_> = self.params_and_return.iter().cloned().collect();
for t in &mut v {
for t in make_mut_slice(&mut self.params_and_return) {
t.walk_mut(f);
}
self.params_and_return = v.into();
}
}
@ -756,11 +748,9 @@ impl TypeWalk for Ty {
p_ty.parameters.walk_mut(f);
}
Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
let mut v: Vec<_> = predicates.iter().cloned().collect();
for p in &mut v {
for p in make_mut_slice(predicates) {
p.walk_mut(f);
}
*predicates = v.into();
}
Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
}

View File

@ -6,6 +6,7 @@ use crate::ty::{
Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty,
TypeWalk,
};
use crate::util::make_mut_slice;
impl<'a, D: HirDatabase> InferenceContext<'a, D> {
pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D>
@ -74,10 +75,11 @@ where
})
}
fn do_canonicalize_trait_ref(&mut self, trait_ref: TraitRef) -> TraitRef {
let substs =
trait_ref.substs.iter().map(|ty| self.do_canonicalize_ty(ty.clone())).collect();
TraitRef { trait_: trait_ref.trait_, substs: Substs(substs) }
fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef {
for ty in make_mut_slice(&mut trait_ref.substs.0) {
*ty = self.do_canonicalize_ty(ty.clone());
}
trait_ref
}
fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> {
@ -87,10 +89,11 @@ where
}
}
fn do_canonicalize_projection_ty(&mut self, projection_ty: ProjectionTy) -> ProjectionTy {
let params =
projection_ty.parameters.iter().map(|ty| self.do_canonicalize_ty(ty.clone())).collect();
ProjectionTy { associated_ty: projection_ty.associated_ty, parameters: Substs(params) }
fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy {
for ty in make_mut_slice(&mut projection_ty.parameters.0) {
*ty = self.do_canonicalize_ty(ty.clone());
}
projection_ty
}
fn do_canonicalize_projection_predicate(

View File

@ -22,6 +22,7 @@ use crate::{
resolve::{Resolver, TypeNs},
ty::Adt,
type_ref::{TypeBound, TypeRef},
util::make_mut_slice,
BuiltinType, Const, Enum, EnumVariant, Function, ModuleDef, Path, Static, Struct, StructField,
Trait, TypeAlias, Union,
};
@ -31,11 +32,11 @@ impl Ty {
match type_ref {
TypeRef::Never => Ty::simple(TypeCtor::Never),
TypeRef::Tuple(inner) => {
let inner_tys =
inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect::<Vec<_>>();
let inner_tys: Arc<[Ty]> =
inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect();
Ty::apply(
TypeCtor::Tuple { cardinality: inner_tys.len() as u16 },
Substs(inner_tys.into()),
Substs(inner_tys),
)
}
TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path),
@ -57,9 +58,7 @@ impl Ty {
}
TypeRef::Placeholder => Ty::Unknown,
TypeRef::Fn(params) => {
let inner_tys =
params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect::<Vec<_>>();
let sig = Substs(inner_tys.into());
let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect());
Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig)
}
TypeRef::DynTrait(bounds) => {
@ -69,8 +68,8 @@ impl Ty {
.flat_map(|b| {
GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone())
})
.collect::<Vec<_>>();
Ty::Dyn(predicates.into())
.collect();
Ty::Dyn(predicates)
}
TypeRef::ImplTrait(bounds) => {
let self_ty = Ty::Bound(0);
@ -79,8 +78,8 @@ impl Ty {
.flat_map(|b| {
GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone())
})
.collect::<Vec<_>>();
Ty::Opaque(predicates.into())
.collect();
Ty::Opaque(predicates)
}
TypeRef::Error => Ty::Unknown,
}
@ -392,10 +391,7 @@ impl TraitRef {
) -> Self {
let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved);
if let Some(self_ty) = explicit_self_ty {
// FIXME this could be nicer
let mut substs_vec = substs.0.to_vec();
substs_vec[0] = self_ty;
substs.0 = substs_vec.into();
make_mut_slice(&mut substs.0)[0] = self_ty;
}
TraitRef { trait_: resolved, substs }
}
@ -558,13 +554,12 @@ pub(crate) fn generic_predicates_for_param_query(
param_idx: u32,
) -> Arc<[GenericPredicate]> {
let resolver = def.resolver(db);
let predicates = resolver
resolver
.where_predicates_in_scope()
// we have to filter out all other predicates *first*, before attempting to lower them
.filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx))
.flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred))
.collect::<Vec<_>>();
predicates.into()
.collect()
}
pub(crate) fn trait_env(
@ -585,11 +580,10 @@ pub(crate) fn generic_predicates_query(
def: GenericDef,
) -> Arc<[GenericPredicate]> {
let resolver = def.resolver(db);
let predicates = resolver
resolver
.where_predicates_in_scope()
.flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred))
.collect::<Vec<_>>();
predicates.into()
.collect()
}
/// Resolve the default type params from generics
@ -603,9 +597,9 @@ pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDef) ->
.map(|p| {
p.default.as_ref().map_or(Ty::Unknown, |path| Ty::from_hir_path(db, &resolver, path))
})
.collect::<Vec<_>>();
.collect();
Substs(defaults.into())
Substs(defaults)
}
fn fn_sig_for_fn(db: &impl HirDatabase, def: Function) -> FnSig {

View File

@ -89,7 +89,7 @@ pub(crate) fn impls_for_trait_query(
}
let crate_impl_blocks = db.impls_in_crate(krate);
impls.extend(crate_impl_blocks.lookup_impl_blocks_for_trait(trait_));
impls.into_iter().collect::<Vec<_>>().into()
impls.into_iter().collect()
}
/// A set of clauses that we assume to be true. E.g. if we are inside this function:

View File

@ -126,8 +126,7 @@ impl ToChalk for Substs {
chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty),
chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(),
})
.collect::<Vec<_>>()
.into();
.collect();
Substs(tys)
}
}

12
crates/ra_hir/src/util.rs Normal file
View File

@ -0,0 +1,12 @@
//! Internal utility functions.
use std::sync::Arc;
/// Helper for mutating `Arc<[T]>` (i.e. `Arc::make_mut` for Arc slices).
/// The underlying values are cloned if there are other strong references.
pub(crate) fn make_mut_slice<T: Clone>(a: &mut Arc<[T]>) -> &mut [T] {
if Arc::get_mut(a).is_none() {
*a = a.iter().cloned().collect();
}
Arc::get_mut(a).unwrap()
}