Skip to content

Commit 5efac03

Browse files
authored
Rollup merge of rust-lang#54717 - ljedrz:cleanup_ty_p1, r=davidtwco
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
2 parents 6b24de1 + 7ad21a8 commit 5efac03

File tree

10 files changed

+375
-388
lines changed

10 files changed

+375
-388
lines changed

src/librustc/ty/codec.rs

+14-14
Original file line numberDiff line numberDiff line change
@@ -178,19 +178,19 @@ pub fn decode_predicates<'a, 'tcx, D>(decoder: &mut D)
178178
Ok(ty::GenericPredicates {
179179
parent: Decodable::decode(decoder)?,
180180
predicates: (0..decoder.read_usize()?).map(|_| {
181-
// Handle shorthands first, if we have an usize > 0x80.
182-
let predicate = if decoder.positioned_at_shorthand() {
183-
let pos = decoder.read_usize()?;
184-
assert!(pos >= SHORTHAND_OFFSET);
185-
let shorthand = pos - SHORTHAND_OFFSET;
186-
187-
decoder.with_position(shorthand, ty::Predicate::decode)
188-
} else {
189-
ty::Predicate::decode(decoder)
190-
}?;
191-
Ok((predicate, Decodable::decode(decoder)?))
192-
})
193-
.collect::<Result<Vec<_>, _>>()?,
181+
// Handle shorthands first, if we have an usize > 0x80.
182+
let predicate = if decoder.positioned_at_shorthand() {
183+
let pos = decoder.read_usize()?;
184+
assert!(pos >= SHORTHAND_OFFSET);
185+
let shorthand = pos - SHORTHAND_OFFSET;
186+
187+
decoder.with_position(shorthand, ty::Predicate::decode)
188+
} else {
189+
ty::Predicate::decode(decoder)
190+
}?;
191+
Ok((predicate, Decodable::decode(decoder)?))
192+
})
193+
.collect::<Result<Vec<_>, _>>()?,
194194
})
195195
}
196196

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

268268
#[inline]
269269
pub fn decode_allocation<'a, 'tcx, D>(decoder: &mut D)
270-
-> Result<&'tcx Allocation, D::Error>
270+
-> Result<&'tcx Allocation, D::Error>
271271
where D: TyDecoder<'a, 'tcx>,
272272
'tcx: 'a,
273273
{

src/librustc/ty/context.rs

+20-24
Original file line numberDiff line numberDiff line change
@@ -190,8 +190,8 @@ impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
190190
// types/regions in the global interner
191191
if local as *const _ as usize == global as *const _ as usize {
192192
bug!("Attempted to intern `{:?}` which contains \
193-
inference types/regions in the global type context",
194-
&ty_struct);
193+
inference types/regions in the global type context",
194+
&ty_struct);
195195
}
196196

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

273273
bug!("node {} with HirId::owner {:?} cannot be placed in \
274274
TypeckTables with local_id_root {:?}",
275-
tcx.hir.node_to_string(node_id),
276-
DefId::local(hir_id.owner),
277-
local_id_root)
275+
tcx.hir.node_to_string(node_id),
276+
DefId::local(hir_id.owner),
277+
local_id_root)
278278
});
279279
}
280280
} else {
@@ -540,16 +540,13 @@ impl<'tcx> TypeckTables<'tcx> {
540540
}
541541

542542
pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
543-
match self.node_id_to_type_opt(id) {
544-
Some(ty) => ty,
545-
None => {
546-
bug!("node_id_to_type: no type for node `{}`",
547-
tls::with(|tcx| {
548-
let id = tcx.hir.hir_to_node_id(id);
549-
tcx.hir.node_to_string(id)
550-
}))
551-
}
552-
}
543+
self.node_id_to_type_opt(id).unwrap_or_else(||
544+
bug!("node_id_to_type: no type for node `{}`",
545+
tls::with(|tcx| {
546+
let id = tcx.hir.hir_to_node_id(id);
547+
tcx.hir.node_to_string(id)
548+
}))
549+
)
553550
}
554551

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

688685
pub fn pat_adjustments_mut(&mut self)
689-
-> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
686+
-> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
690687
LocalTableInContextMut {
691688
local_id_root: self.local_id_root,
692689
data: &mut self.pat_adjustments,
@@ -1199,8 +1196,8 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
11991196
let hir_id = hir.node_to_hir_id(k);
12001197
let map = trait_map.entry(hir_id.owner).or_default();
12011198
Lrc::get_mut(map).unwrap()
1202-
.insert(hir_id.local_id,
1203-
Lrc::new(StableVec::new(v)));
1199+
.insert(hir_id.local_id,
1200+
Lrc::new(StableVec::new(v)));
12041201
}
12051202

12061203
let gcx = &GlobalCtxt {
@@ -2188,7 +2185,6 @@ macro_rules! sty_debug_print {
21882185
};
21892186
$(let mut $variant = total;)*
21902187

2191-
21922188
for &Interned(t) in tcx.interners.type_.borrow().iter() {
21932189
let variant = match t.sty {
21942190
ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
@@ -2207,7 +2203,7 @@ macro_rules! sty_debug_print {
22072203
}
22082204
println!("Ty interner total ty region both");
22092205
$(println!(" {:18}: {uses:6} {usespc:4.1}%, \
2210-
{ty:4.1}% {region:5.1}% {both:4.1}%",
2206+
{ty:4.1}% {region:5.1}% {both:4.1}%",
22112207
stringify!($variant),
22122208
uses = $variant.total,
22132209
usespc = $variant.total as f64 * 100.0 / total.total as f64,
@@ -2216,7 +2212,7 @@ macro_rules! sty_debug_print {
22162212
both = $variant.both_infer as f64 * 100.0 / total.total as f64);
22172213
)*
22182214
println!(" total {uses:6} \
2219-
{ty:4.1}% {region:5.1}% {both:4.1}%",
2215+
{ty:4.1}% {region:5.1}% {both:4.1}%",
22202216
uses = total.total,
22212217
ty = total.ty_infer as f64 * 100.0 / total.total as f64,
22222218
region = total.region_infer as f64 * 100.0 / total.total as f64,
@@ -2653,7 +2649,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
26532649
}
26542650

26552651
pub fn mk_closure(self, closure_id: DefId, closure_substs: ClosureSubsts<'tcx>)
2656-
-> Ty<'tcx> {
2652+
-> Ty<'tcx> {
26572653
self.mk_ty(Closure(closure_id, closure_substs))
26582654
}
26592655

@@ -2686,8 +2682,8 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
26862682
}
26872683

26882684
pub fn mk_ty_param(self,
2689-
index: u32,
2690-
name: InternedString) -> Ty<'tcx> {
2685+
index: u32,
2686+
name: InternedString) -> Ty<'tcx> {
26912687
self.mk_ty(Param(ParamTy { idx: index, name: name }))
26922688
}
26932689

src/librustc/ty/error.rs

+53-53
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
use hir::def_id::DefId;
1212
use ty::{self, BoundRegion, Region, Ty, TyCtxt};
13+
use std::borrow::Cow;
1314
use std::fmt;
1415
use rustc_target::spec::abi;
1516
use syntax::ast;
@@ -71,7 +72,7 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
7172
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7273
use self::TypeError::*;
7374
fn report_maybe_different(f: &mut fmt::Formatter<'_>,
74-
expected: String, found: String) -> fmt::Result {
75+
expected: &str, found: &str) -> fmt::Result {
7576
// A naive approach to making sure that we're not reporting silly errors such as:
7677
// (expected closure, found closure).
7778
if expected == found {
@@ -126,15 +127,15 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
126127
br)
127128
}
128129
Sorts(values) => ty::tls::with(|tcx| {
129-
report_maybe_different(f, values.expected.sort_string(tcx),
130-
values.found.sort_string(tcx))
130+
report_maybe_different(f, &values.expected.sort_string(tcx),
131+
&values.found.sort_string(tcx))
131132
}),
132133
Traits(values) => ty::tls::with(|tcx| {
133134
report_maybe_different(f,
134-
format!("trait `{}`",
135-
tcx.item_path_str(values.expected)),
136-
format!("trait `{}`",
137-
tcx.item_path_str(values.found)))
135+
&format!("trait `{}`",
136+
tcx.item_path_str(values.expected)),
137+
&format!("trait `{}`",
138+
tcx.item_path_str(values.found)))
138139
}),
139140
IntMismatch(ref values) => {
140141
write!(f, "expected `{:?}`, found `{:?}`",
@@ -162,8 +163,8 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
162163
values.found)
163164
},
164165
ExistentialMismatch(ref values) => {
165-
report_maybe_different(f, format!("trait `{}`", values.expected),
166-
format!("trait `{}`", values.found))
166+
report_maybe_different(f, &format!("trait `{}`", values.expected),
167+
&format!("trait `{}`", values.found))
167168
}
168169
OldStyleLUB(ref err) => {
169170
write!(f, "{}", err)
@@ -173,22 +174,22 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
173174
}
174175

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

182-
ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)),
183-
ty::Foreign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)),
183+
ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)).into(),
184+
ty::Foreign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)).into(),
184185
ty::Array(_, n) => {
185186
match n.assert_usize(tcx) {
186-
Some(n) => format!("array of {} elements", n),
187-
None => "array".to_string(),
187+
Some(n) => format!("array of {} elements", n).into(),
188+
None => "array".into(),
188189
}
189190
}
190-
ty::Slice(_) => "slice".to_string(),
191-
ty::RawPtr(_) => "*-ptr".to_string(),
191+
ty::Slice(_) => "slice".into(),
192+
ty::RawPtr(_) => "*-ptr".into(),
192193
ty::Ref(region, ty, mutbl) => {
193194
let tymut = ty::TypeAndMut { ty, mutbl };
194195
let tymut_string = tymut.to_string();
@@ -199,39 +200,39 @@ impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
199200
format!("{}reference", match mutbl {
200201
hir::Mutability::MutMutable => "mutable ",
201202
_ => ""
202-
})
203+
}).into()
203204
} else {
204-
format!("&{}", tymut_string)
205+
format!("&{}", tymut_string).into()
205206
}
206207
}
207-
ty::FnDef(..) => "fn item".to_string(),
208-
ty::FnPtr(_) => "fn pointer".to_string(),
208+
ty::FnDef(..) => "fn item".into(),
209+
ty::FnPtr(_) => "fn pointer".into(),
209210
ty::Dynamic(ref inner, ..) => {
210-
inner.principal().map_or_else(|| "trait".to_string(),
211-
|p| format!("trait {}", tcx.item_path_str(p.def_id())))
211+
inner.principal().map_or_else(|| "trait".into(),
212+
|p| format!("trait {}", tcx.item_path_str(p.def_id())).into())
212213
}
213-
ty::Closure(..) => "closure".to_string(),
214-
ty::Generator(..) => "generator".to_string(),
215-
ty::GeneratorWitness(..) => "generator witness".to_string(),
216-
ty::Tuple(..) => "tuple".to_string(),
217-
ty::Infer(ty::TyVar(_)) => "inferred type".to_string(),
218-
ty::Infer(ty::IntVar(_)) => "integral variable".to_string(),
219-
ty::Infer(ty::FloatVar(_)) => "floating-point variable".to_string(),
214+
ty::Closure(..) => "closure".into(),
215+
ty::Generator(..) => "generator".into(),
216+
ty::GeneratorWitness(..) => "generator witness".into(),
217+
ty::Tuple(..) => "tuple".into(),
218+
ty::Infer(ty::TyVar(_)) => "inferred type".into(),
219+
ty::Infer(ty::IntVar(_)) => "integral variable".into(),
220+
ty::Infer(ty::FloatVar(_)) => "floating-point variable".into(),
220221
ty::Infer(ty::CanonicalTy(_)) |
221-
ty::Infer(ty::FreshTy(_)) => "fresh type".to_string(),
222-
ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".to_string(),
223-
ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".to_string(),
224-
ty::Projection(_) => "associated type".to_string(),
225-
ty::UnnormalizedProjection(_) => "non-normalized associated type".to_string(),
222+
ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
223+
ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
224+
ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
225+
ty::Projection(_) => "associated type".into(),
226+
ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
226227
ty::Param(ref p) => {
227228
if p.is_self() {
228-
"Self".to_string()
229+
"Self".into()
229230
} else {
230-
"type parameter".to_string()
231+
"type parameter".into()
231232
}
232233
}
233-
ty::Opaque(..) => "opaque type".to_string(),
234-
ty::Error => "type error".to_string(),
234+
ty::Opaque(..) => "opaque type".into(),
235+
ty::Error => "type error".into(),
235236
}
236237
}
237238
}
@@ -251,20 +252,19 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
251252
db.note("no two closures, even if identical, have the same type");
252253
db.help("consider boxing your closure and/or using it as a trait object");
253254
}
254-
match (&values.found.sty, &values.expected.sty) { // Issue #53280
255-
(ty::Infer(ty::IntVar(_)), ty::Float(_)) => {
256-
if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
257-
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
258-
db.span_suggestion_with_applicability(
259-
sp,
260-
"use a float literal",
261-
format!("{}.0", snippet),
262-
Applicability::MachineApplicable
263-
);
264-
}
255+
if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
256+
(&values.found.sty, &values.expected.sty) // Issue #53280
257+
{
258+
if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
259+
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
260+
db.span_suggestion_with_applicability(
261+
sp,
262+
"use a float literal",
263+
format!("{}.0", snippet),
264+
Applicability::MachineApplicable
265+
);
265266
}
266-
},
267-
_ => {}
267+
}
268268
}
269269
},
270270
OldStyleLUB(err) => {

src/librustc/ty/flags.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,7 @@ impl FlagComputation {
6262
let outer_exclusive_binder = computation.outer_exclusive_binder;
6363
if outer_exclusive_binder > ty::INNERMOST {
6464
self.add_exclusive_binder(outer_exclusive_binder.shifted_out(1));
65-
} else {
66-
// otherwise, this binder captures nothing
67-
}
65+
} // otherwise, this binder captures nothing
6866
}
6967

7068
fn add_sty(&mut self, st: &ty::TyKind<'_>) {

src/librustc/ty/inhabitedness/def_id_forest.rs

+3-16
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,7 @@ impl<'a, 'gcx, 'tcx> DefIdForest {
6666
tcx: TyCtxt<'a, 'gcx, 'tcx>,
6767
id: DefId) -> bool
6868
{
69-
for root_id in self.root_ids.iter() {
70-
if tcx.is_descendant_of(id, *root_id) {
71-
return true;
72-
}
73-
}
74-
false
69+
self.root_ids.iter().any(|root_id| tcx.is_descendant_of(id, *root_id))
7570
}
7671

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

95-
for id in next_forest.root_ids {
96-
if ret.contains(tcx, id) {
97-
next_ret.push(id);
98-
}
99-
}
90+
next_ret.extend(next_forest.root_ids.into_iter().filter(|&id| ret.contains(tcx, id)));
10091

10192
mem::swap(&mut next_ret, &mut ret.root_ids);
10293
next_ret.drain();
@@ -112,11 +103,7 @@ impl<'a, 'gcx, 'tcx> DefIdForest {
112103
let mut ret = DefIdForest::empty();
113104
let mut next_ret = SmallVec::new();
114105
for next_forest in iter {
115-
for id in ret.root_ids.drain() {
116-
if !next_forest.contains(tcx, id) {
117-
next_ret.push(id);
118-
}
119-
}
106+
next_ret.extend(ret.root_ids.drain().filter(|&id| !next_forest.contains(tcx, id)));
120107

121108
for id in next_forest.root_ids {
122109
if !next_ret.contains(&id) {

0 commit comments

Comments
 (0)