Skip to content

Commit

Permalink
Rollup merge of rust-lang#54717 - ljedrz:cleanup_ty_p1, r=davidtwco
Browse files Browse the repository at this point in the history
Cleanup rustc/ty part 1

Part 2 will follow soon; I wouldn't want these changes to rot too quickly.

- improve stack shifting and remove related allocations
- move a faster early return up
- improve allocations
- use Cow<str> where applicable
- simplify common patterns
- whitespace fixes
  • Loading branch information
pietroalbini authored Oct 5, 2018
2 parents 6b24de1 + 7ad21a8 commit 5efac03
Show file tree
Hide file tree
Showing 10 changed files with 375 additions and 388 deletions.
28 changes: 14 additions & 14 deletions src/librustc/ty/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,19 +178,19 @@ pub fn decode_predicates<'a, 'tcx, D>(decoder: &mut D)
Ok(ty::GenericPredicates {
parent: Decodable::decode(decoder)?,
predicates: (0..decoder.read_usize()?).map(|_| {
// Handle shorthands first, if we have an usize > 0x80.
let predicate = if decoder.positioned_at_shorthand() {
let pos = decoder.read_usize()?;
assert!(pos >= SHORTHAND_OFFSET);
let shorthand = pos - SHORTHAND_OFFSET;

decoder.with_position(shorthand, ty::Predicate::decode)
} else {
ty::Predicate::decode(decoder)
}?;
Ok((predicate, Decodable::decode(decoder)?))
})
.collect::<Result<Vec<_>, _>>()?,
// Handle shorthands first, if we have an usize > 0x80.
let predicate = if decoder.positioned_at_shorthand() {
let pos = decoder.read_usize()?;
assert!(pos >= SHORTHAND_OFFSET);
let shorthand = pos - SHORTHAND_OFFSET;

decoder.with_position(shorthand, ty::Predicate::decode)
} else {
ty::Predicate::decode(decoder)
}?;
Ok((predicate, Decodable::decode(decoder)?))
})
.collect::<Result<Vec<_>, _>>()?,
})
}

Expand Down Expand Up @@ -267,7 +267,7 @@ pub fn decode_const<'a, 'tcx, D>(decoder: &mut D)

#[inline]
pub fn decode_allocation<'a, 'tcx, D>(decoder: &mut D)
-> Result<&'tcx Allocation, D::Error>
-> Result<&'tcx Allocation, D::Error>
where D: TyDecoder<'a, 'tcx>,
'tcx: 'a,
{
Expand Down
44 changes: 20 additions & 24 deletions src/librustc/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,8 @@ impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
// types/regions in the global interner
if local as *const _ as usize == global as *const _ as usize {
bug!("Attempted to intern `{:?}` which contains \
inference types/regions in the global type context",
&ty_struct);
inference types/regions in the global type context",
&ty_struct);
}

// Don't be &mut TyS.
Expand Down Expand Up @@ -272,9 +272,9 @@ fn validate_hir_id_for_typeck_tables(local_id_root: Option<DefId>,

bug!("node {} with HirId::owner {:?} cannot be placed in \
TypeckTables with local_id_root {:?}",
tcx.hir.node_to_string(node_id),
DefId::local(hir_id.owner),
local_id_root)
tcx.hir.node_to_string(node_id),
DefId::local(hir_id.owner),
local_id_root)
});
}
} else {
Expand Down Expand Up @@ -540,16 +540,13 @@ impl<'tcx> TypeckTables<'tcx> {
}

pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
match self.node_id_to_type_opt(id) {
Some(ty) => ty,
None => {
bug!("node_id_to_type: no type for node `{}`",
tls::with(|tcx| {
let id = tcx.hir.hir_to_node_id(id);
tcx.hir.node_to_string(id)
}))
}
}
self.node_id_to_type_opt(id).unwrap_or_else(||
bug!("node_id_to_type: no type for node `{}`",
tls::with(|tcx| {
let id = tcx.hir.hir_to_node_id(id);
tcx.hir.node_to_string(id)
}))
)
}

pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
Expand Down Expand Up @@ -686,7 +683,7 @@ impl<'tcx> TypeckTables<'tcx> {
}

pub fn pat_adjustments_mut(&mut self)
-> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
-> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
LocalTableInContextMut {
local_id_root: self.local_id_root,
data: &mut self.pat_adjustments,
Expand Down Expand Up @@ -1199,8 +1196,8 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
let hir_id = hir.node_to_hir_id(k);
let map = trait_map.entry(hir_id.owner).or_default();
Lrc::get_mut(map).unwrap()
.insert(hir_id.local_id,
Lrc::new(StableVec::new(v)));
.insert(hir_id.local_id,
Lrc::new(StableVec::new(v)));
}

let gcx = &GlobalCtxt {
Expand Down Expand Up @@ -2188,7 +2185,6 @@ macro_rules! sty_debug_print {
};
$(let mut $variant = total;)*


for &Interned(t) in tcx.interners.type_.borrow().iter() {
let variant = match t.sty {
ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
Expand All @@ -2207,7 +2203,7 @@ macro_rules! sty_debug_print {
}
println!("Ty interner total ty region both");
$(println!(" {:18}: {uses:6} {usespc:4.1}%, \
{ty:4.1}% {region:5.1}% {both:4.1}%",
{ty:4.1}% {region:5.1}% {both:4.1}%",
stringify!($variant),
uses = $variant.total,
usespc = $variant.total as f64 * 100.0 / total.total as f64,
Expand All @@ -2216,7 +2212,7 @@ macro_rules! sty_debug_print {
both = $variant.both_infer as f64 * 100.0 / total.total as f64);
)*
println!(" total {uses:6} \
{ty:4.1}% {region:5.1}% {both:4.1}%",
{ty:4.1}% {region:5.1}% {both:4.1}%",
uses = total.total,
ty = total.ty_infer as f64 * 100.0 / total.total as f64,
region = total.region_infer as f64 * 100.0 / total.total as f64,
Expand Down Expand Up @@ -2653,7 +2649,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
}

pub fn mk_closure(self, closure_id: DefId, closure_substs: ClosureSubsts<'tcx>)
-> Ty<'tcx> {
-> Ty<'tcx> {
self.mk_ty(Closure(closure_id, closure_substs))
}

Expand Down Expand Up @@ -2686,8 +2682,8 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
}

pub fn mk_ty_param(self,
index: u32,
name: InternedString) -> Ty<'tcx> {
index: u32,
name: InternedString) -> Ty<'tcx> {
self.mk_ty(Param(ParamTy { idx: index, name: name }))
}

Expand Down
106 changes: 53 additions & 53 deletions src/librustc/ty/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use hir::def_id::DefId;
use ty::{self, BoundRegion, Region, Ty, TyCtxt};
use std::borrow::Cow;
use std::fmt;
use rustc_target::spec::abi;
use syntax::ast;
Expand Down Expand Up @@ -71,7 +72,7 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::TypeError::*;
fn report_maybe_different(f: &mut fmt::Formatter<'_>,
expected: String, found: String) -> fmt::Result {
expected: &str, found: &str) -> fmt::Result {
// A naive approach to making sure that we're not reporting silly errors such as:
// (expected closure, found closure).
if expected == found {
Expand Down Expand Up @@ -126,15 +127,15 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
br)
}
Sorts(values) => ty::tls::with(|tcx| {
report_maybe_different(f, values.expected.sort_string(tcx),
values.found.sort_string(tcx))
report_maybe_different(f, &values.expected.sort_string(tcx),
&values.found.sort_string(tcx))
}),
Traits(values) => ty::tls::with(|tcx| {
report_maybe_different(f,
format!("trait `{}`",
tcx.item_path_str(values.expected)),
format!("trait `{}`",
tcx.item_path_str(values.found)))
&format!("trait `{}`",
tcx.item_path_str(values.expected)),
&format!("trait `{}`",
tcx.item_path_str(values.found)))
}),
IntMismatch(ref values) => {
write!(f, "expected `{:?}`, found `{:?}`",
Expand Down Expand Up @@ -162,8 +163,8 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
values.found)
},
ExistentialMismatch(ref values) => {
report_maybe_different(f, format!("trait `{}`", values.expected),
format!("trait `{}`", values.found))
report_maybe_different(f, &format!("trait `{}`", values.expected),
&format!("trait `{}`", values.found))
}
OldStyleLUB(ref err) => {
write!(f, "{}", err)
Expand All @@ -173,22 +174,22 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
}

impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
match self.sty {
ty::Bool | ty::Char | ty::Int(_) |
ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string(),
ty::Tuple(ref tys) if tys.is_empty() => self.to_string(),
ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),

ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)),
ty::Foreign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)),
ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)).into(),
ty::Foreign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)).into(),
ty::Array(_, n) => {
match n.assert_usize(tcx) {
Some(n) => format!("array of {} elements", n),
None => "array".to_string(),
Some(n) => format!("array of {} elements", n).into(),
None => "array".into(),
}
}
ty::Slice(_) => "slice".to_string(),
ty::RawPtr(_) => "*-ptr".to_string(),
ty::Slice(_) => "slice".into(),
ty::RawPtr(_) => "*-ptr".into(),
ty::Ref(region, ty, mutbl) => {
let tymut = ty::TypeAndMut { ty, mutbl };
let tymut_string = tymut.to_string();
Expand All @@ -199,39 +200,39 @@ impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
format!("{}reference", match mutbl {
hir::Mutability::MutMutable => "mutable ",
_ => ""
})
}).into()
} else {
format!("&{}", tymut_string)
format!("&{}", tymut_string).into()
}
}
ty::FnDef(..) => "fn item".to_string(),
ty::FnPtr(_) => "fn pointer".to_string(),
ty::FnDef(..) => "fn item".into(),
ty::FnPtr(_) => "fn pointer".into(),
ty::Dynamic(ref inner, ..) => {
inner.principal().map_or_else(|| "trait".to_string(),
|p| format!("trait {}", tcx.item_path_str(p.def_id())))
inner.principal().map_or_else(|| "trait".into(),
|p| format!("trait {}", tcx.item_path_str(p.def_id())).into())
}
ty::Closure(..) => "closure".to_string(),
ty::Generator(..) => "generator".to_string(),
ty::GeneratorWitness(..) => "generator witness".to_string(),
ty::Tuple(..) => "tuple".to_string(),
ty::Infer(ty::TyVar(_)) => "inferred type".to_string(),
ty::Infer(ty::IntVar(_)) => "integral variable".to_string(),
ty::Infer(ty::FloatVar(_)) => "floating-point variable".to_string(),
ty::Closure(..) => "closure".into(),
ty::Generator(..) => "generator".into(),
ty::GeneratorWitness(..) => "generator witness".into(),
ty::Tuple(..) => "tuple".into(),
ty::Infer(ty::TyVar(_)) => "inferred type".into(),
ty::Infer(ty::IntVar(_)) => "integral variable".into(),
ty::Infer(ty::FloatVar(_)) => "floating-point variable".into(),
ty::Infer(ty::CanonicalTy(_)) |
ty::Infer(ty::FreshTy(_)) => "fresh type".to_string(),
ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".to_string(),
ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".to_string(),
ty::Projection(_) => "associated type".to_string(),
ty::UnnormalizedProjection(_) => "non-normalized associated type".to_string(),
ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
ty::Projection(_) => "associated type".into(),
ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
ty::Param(ref p) => {
if p.is_self() {
"Self".to_string()
"Self".into()
} else {
"type parameter".to_string()
"type parameter".into()
}
}
ty::Opaque(..) => "opaque type".to_string(),
ty::Error => "type error".to_string(),
ty::Opaque(..) => "opaque type".into(),
ty::Error => "type error".into(),
}
}
}
Expand All @@ -251,20 +252,19 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
db.note("no two closures, even if identical, have the same type");
db.help("consider boxing your closure and/or using it as a trait object");
}
match (&values.found.sty, &values.expected.sty) { // Issue #53280
(ty::Infer(ty::IntVar(_)), ty::Float(_)) => {
if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
db.span_suggestion_with_applicability(
sp,
"use a float literal",
format!("{}.0", snippet),
Applicability::MachineApplicable
);
}
if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
(&values.found.sty, &values.expected.sty) // Issue #53280
{
if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
db.span_suggestion_with_applicability(
sp,
"use a float literal",
format!("{}.0", snippet),
Applicability::MachineApplicable
);
}
},
_ => {}
}
}
},
OldStyleLUB(err) => {
Expand Down
4 changes: 1 addition & 3 deletions src/librustc/ty/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,7 @@ impl FlagComputation {
let outer_exclusive_binder = computation.outer_exclusive_binder;
if outer_exclusive_binder > ty::INNERMOST {
self.add_exclusive_binder(outer_exclusive_binder.shifted_out(1));
} else {
// otherwise, this binder captures nothing
}
} // otherwise, this binder captures nothing
}

fn add_sty(&mut self, st: &ty::TyKind<'_>) {
Expand Down
19 changes: 3 additions & 16 deletions src/librustc/ty/inhabitedness/def_id_forest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,7 @@ impl<'a, 'gcx, 'tcx> DefIdForest {
tcx: TyCtxt<'a, 'gcx, 'tcx>,
id: DefId) -> bool
{
for root_id in self.root_ids.iter() {
if tcx.is_descendant_of(id, *root_id) {
return true;
}
}
false
self.root_ids.iter().any(|root_id| tcx.is_descendant_of(id, *root_id))
}

/// Calculate the intersection of a collection of forests.
Expand All @@ -92,11 +87,7 @@ impl<'a, 'gcx, 'tcx> DefIdForest {
}
ret.root_ids.extend(old_ret.drain());

for id in next_forest.root_ids {
if ret.contains(tcx, id) {
next_ret.push(id);
}
}
next_ret.extend(next_forest.root_ids.into_iter().filter(|&id| ret.contains(tcx, id)));

mem::swap(&mut next_ret, &mut ret.root_ids);
next_ret.drain();
Expand All @@ -112,11 +103,7 @@ impl<'a, 'gcx, 'tcx> DefIdForest {
let mut ret = DefIdForest::empty();
let mut next_ret = SmallVec::new();
for next_forest in iter {
for id in ret.root_ids.drain() {
if !next_forest.contains(tcx, id) {
next_ret.push(id);
}
}
next_ret.extend(ret.root_ids.drain().filter(|&id| !next_forest.contains(tcx, id)));

for id in next_forest.root_ids {
if !next_ret.contains(&id) {
Expand Down
Loading

0 comments on commit 5efac03

Please sign in to comment.