提交 4efdc04a 编写于 作者: B bors

Auto merge of #54756 - ljedrz:cleanup_middle, r=michaelwoerister

Cleanup rustc/middle

- improve allocations
- use `Cow<'static, str>` where applicable
- improve some patterns
- whitespace & formatting fixes
...@@ -131,12 +131,10 @@ fn handle_field_pattern_match(&mut self, lhs: &hir::Pat, def: Def, ...@@ -131,12 +131,10 @@ fn handle_field_pattern_match(&mut self, lhs: &hir::Pat, def: Def,
fn mark_live_symbols(&mut self) { fn mark_live_symbols(&mut self) {
let mut scanned = FxHashSet(); let mut scanned = FxHashSet();
while !self.worklist.is_empty() { while let Some(id) = self.worklist.pop() {
let id = self.worklist.pop().unwrap(); if !scanned.insert(id) {
if scanned.contains(&id) {
continue continue
} }
scanned.insert(id);
if let Some(ref node) = self.tcx.hir.find(id) { if let Some(ref node) = self.tcx.hir.find(id) {
self.live_symbols.insert(id); self.live_symbols.insert(id);
...@@ -212,7 +210,7 @@ fn visit_nested_body(&mut self, body: hir::BodyId) { ...@@ -212,7 +210,7 @@ fn visit_nested_body(&mut self, body: hir::BodyId) {
} }
fn visit_variant_data(&mut self, def: &'tcx hir::VariantData, _: ast::Name, fn visit_variant_data(&mut self, def: &'tcx hir::VariantData, _: ast::Name,
_: &hir::Generics, _: ast::NodeId, _: syntax_pos::Span) { _: &hir::Generics, _: ast::NodeId, _: syntax_pos::Span) {
let has_repr_c = self.repr_has_repr_c; let has_repr_c = self.repr_has_repr_c;
let inherited_pub_visibility = self.inherited_pub_visibility; let inherited_pub_visibility = self.inherited_pub_visibility;
let live_fields = def.fields().iter().filter(|f| { let live_fields = def.fields().iter().filter(|f| {
...@@ -494,8 +492,8 @@ fn symbol_is_live(&mut self, ...@@ -494,8 +492,8 @@ fn symbol_is_live(&mut self,
ctor_id: Option<ast::NodeId>) ctor_id: Option<ast::NodeId>)
-> bool { -> bool {
if self.live_symbols.contains(&id) if self.live_symbols.contains(&id)
|| ctor_id.map_or(false, || ctor_id.map_or(false, |ctor| self.live_symbols.contains(&ctor))
|ctor| self.live_symbols.contains(&ctor)) { {
return true; return true;
} }
// If it's a type whose items are live, then it's live, too. // If it's a type whose items are live, then it's live, too.
......
...@@ -163,7 +163,7 @@ fn calculate_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ...@@ -163,7 +163,7 @@ fn calculate_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
let src = tcx.used_crate_source(cnum); let src = tcx.used_crate_source(cnum);
if src.rlib.is_some() { continue } if src.rlib.is_some() { continue }
sess.err(&format!("crate `{}` required to be available in rlib format, \ sess.err(&format!("crate `{}` required to be available in rlib format, \
but was not found in this form", but was not found in this form",
tcx.crate_name(cnum))); tcx.crate_name(cnum)));
} }
return Vec::new(); return Vec::new();
...@@ -247,13 +247,13 @@ fn calculate_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ...@@ -247,13 +247,13 @@ fn calculate_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
_ => "dylib", _ => "dylib",
}; };
sess.err(&format!("crate `{}` required to be available in {} format, \ sess.err(&format!("crate `{}` required to be available in {} format, \
but was not found in this form", but was not found in this form",
tcx.crate_name(cnum), kind)); tcx.crate_name(cnum), kind));
} }
} }
} }
return ret; ret
} }
fn add_library(tcx: TyCtxt<'_, '_, '_>, fn add_library(tcx: TyCtxt<'_, '_, '_>,
......
...@@ -8,7 +8,6 @@ ...@@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
use hir::map as hir_map; use hir::map as hir_map;
use hir::def_id::{CRATE_DEF_INDEX}; use hir::def_id::{CRATE_DEF_INDEX};
use session::{config, Session}; use session::{config, Session};
...@@ -131,7 +130,7 @@ fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) { ...@@ -131,7 +130,7 @@ fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
ctxt.attr_main_fn = Some((item.id, item.span)); ctxt.attr_main_fn = Some((item.id, item.span));
} else { } else {
struct_span_err!(ctxt.session, item.span, E0137, struct_span_err!(ctxt.session, item.span, E0137,
"multiple functions with a #[main] attribute") "multiple functions with a #[main] attribute")
.span_label(item.span, "additional #[main] function") .span_label(item.span, "additional #[main] function")
.span_label(ctxt.attr_main_fn.unwrap().1, "first #[main] function") .span_label(ctxt.attr_main_fn.unwrap().1, "first #[main] function")
.emit(); .emit();
...@@ -141,11 +140,8 @@ fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) { ...@@ -141,11 +140,8 @@ fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
if ctxt.start_fn.is_none() { if ctxt.start_fn.is_none() {
ctxt.start_fn = Some((item.id, item.span)); ctxt.start_fn = Some((item.id, item.span));
} else { } else {
struct_span_err!( struct_span_err!(ctxt.session, item.span, E0138, "multiple 'start' functions")
ctxt.session, item.span, E0138, .span_label(ctxt.start_fn.unwrap().1, "previous `start` function here")
"multiple 'start' functions")
.span_label(ctxt.start_fn.unwrap().1,
"previous `start` function here")
.span_label(item.span, "multiple `start` functions") .span_label(item.span, "multiple `start` functions")
.emit(); .emit();
} }
......
...@@ -35,12 +35,8 @@ pub enum SymbolExportLevel { ...@@ -35,12 +35,8 @@ pub enum SymbolExportLevel {
impl SymbolExportLevel { impl SymbolExportLevel {
pub fn is_below_threshold(self, threshold: SymbolExportLevel) -> bool { pub fn is_below_threshold(self, threshold: SymbolExportLevel) -> bool {
if threshold == SymbolExportLevel::Rust { threshold == SymbolExportLevel::Rust // export everything from Rust dylibs
// We export everything from Rust dylibs || self == SymbolExportLevel::C
true
} else {
self == SymbolExportLevel::C
}
} }
} }
......
...@@ -321,7 +321,7 @@ pub fn consume_body(&mut self, body: &hir::Body) { ...@@ -321,7 +321,7 @@ pub fn consume_body(&mut self, body: &hir::Body) {
region::Scope { region::Scope {
id: body.value.hir_id.local_id, id: body.value.hir_id.local_id,
data: region::ScopeData::Node data: region::ScopeData::Node
})); }));
let arg_cmt = Rc::new(self.mc.cat_rvalue( let arg_cmt = Rc::new(self.mc.cat_rvalue(
arg.hir_id, arg.hir_id,
arg.pat.span, arg.pat.span,
...@@ -402,20 +402,20 @@ pub fn walk_expr(&mut self, expr: &hir::Expr) { ...@@ -402,20 +402,20 @@ pub fn walk_expr(&mut self, expr: &hir::Expr) {
self.walk_expr(&subexpr) self.walk_expr(&subexpr)
} }
hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
self.select_from_expr(&base); self.select_from_expr(&base);
} }
hir::ExprKind::Field(ref base, _) => { // base.f hir::ExprKind::Field(ref base, _) => { // base.f
self.select_from_expr(&base); self.select_from_expr(&base);
} }
hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs] hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
self.select_from_expr(&lhs); self.select_from_expr(&lhs);
self.consume_expr(&rhs); self.consume_expr(&rhs);
} }
hir::ExprKind::Call(ref callee, ref args) => { // callee(args) hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
self.walk_callee(expr, &callee); self.walk_callee(expr, &callee);
self.consume_exprs(args); self.consume_exprs(args);
} }
...@@ -801,10 +801,8 @@ fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode ...@@ -801,10 +801,8 @@ fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode
self.walk_pat(discr_cmt.clone(), &pat, mode); self.walk_pat(discr_cmt.clone(), &pat, mode);
} }
if let Some(ref guard) = arm.guard { if let Some(hir::Guard::If(ref e)) = arm.guard {
match guard { self.consume_expr(e)
hir::Guard::If(ref e) => self.consume_expr(e),
}
} }
self.consume_expr(&arm.body); self.consume_expr(&arm.body);
...@@ -826,12 +824,13 @@ fn determine_pat_move_mode(&mut self, ...@@ -826,12 +824,13 @@ fn determine_pat_move_mode(&mut self,
cmt_discr: mc::cmt<'tcx>, cmt_discr: mc::cmt<'tcx>,
pat: &hir::Pat, pat: &hir::Pat,
mode: &mut TrackMatchMode) { mode: &mut TrackMatchMode) {
debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, pat);
pat);
return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| { return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
if let PatKind::Binding(..) = pat.node { if let PatKind::Binding(..) = pat.node {
let bm = *self.mc.tables.pat_binding_modes().get(pat.hir_id) let bm = *self.mc.tables.pat_binding_modes()
.expect("missing binding mode"); .get(pat.hir_id)
.expect("missing binding mode");
match bm { match bm {
ty::BindByReference(..) => ty::BindByReference(..) =>
mode.lub(BorrowingMatch), mode.lub(BorrowingMatch),
......
...@@ -107,7 +107,7 @@ fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) { ...@@ -107,7 +107,7 @@ fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
} }
Err(LayoutError::Unknown(bad)) => { Err(LayoutError::Unknown(bad)) => {
if bad == ty { if bad == ty {
"this type's size can vary".to_string() "this type's size can vary".to_owned()
} else { } else {
format!("size can vary because of {}", bad) format!("size can vary because of {}", bad)
} }
...@@ -117,7 +117,7 @@ fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) { ...@@ -117,7 +117,7 @@ fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
}; };
struct_span_err!(self.tcx.sess, span, E0512, struct_span_err!(self.tcx.sess, span, E0512,
"transmute called with types of different sizes") "transmute called with types of different sizes")
.note(&format!("source type: {} ({})", from, skeleton_string(from, sk_from))) .note(&format!("source type: {} ({})", from, skeleton_string(from, sk_from)))
.note(&format!("target type: {} ({})", to, skeleton_string(to, sk_to))) .note(&format!("target type: {} ({})", to, skeleton_string(to, sk_to)))
.emit(); .emit();
......
...@@ -39,7 +39,6 @@ ...@@ -39,7 +39,6 @@
$( $variant:ident, $name:expr, $method:ident; )* $( $variant:ident, $name:expr, $method:ident; )*
) => { ) => {
enum_from_u32! { enum_from_u32! {
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub enum LangItem { pub enum LangItem {
...@@ -145,8 +144,8 @@ fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItemCollector<'a, 'tcx> { ...@@ -145,8 +144,8 @@ fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItemCollector<'a, 'tcx> {
fn collect_item(&mut self, item_index: usize, item_def_id: DefId) { fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
// Check for duplicates. // Check for duplicates.
match self.items.items[item_index] { if let Some(original_def_id) = self.items.items[item_index] {
Some(original_def_id) if original_def_id != item_def_id => { if original_def_id != item_def_id {
let name = LangItem::from_u32(item_index as u32).unwrap().name(); let name = LangItem::from_u32(item_index as u32).unwrap().name();
let mut err = match self.tcx.hir.span_if_local(item_def_id) { let mut err = match self.tcx.hir.span_if_local(item_def_id) {
Some(span) => struct_span_err!( Some(span) => struct_span_err!(
...@@ -161,17 +160,13 @@ fn collect_item(&mut self, item_index: usize, item_def_id: DefId) { ...@@ -161,17 +160,13 @@ fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
name)), name)),
}; };
if let Some(span) = self.tcx.hir.span_if_local(original_def_id) { if let Some(span) = self.tcx.hir.span_if_local(original_def_id) {
span_note!(&mut err, span, span_note!(&mut err, span, "first defined here.");
"first defined here.");
} else { } else {
err.note(&format!("first defined in crate `{}`.", err.note(&format!("first defined in crate `{}`.",
self.tcx.crate_name(original_def_id.krate))); self.tcx.crate_name(original_def_id.krate)));
} }
err.emit(); err.emit();
} }
_ => {
// OK.
}
} }
// Matched. // Matched.
...@@ -194,7 +189,7 @@ pub fn extract(attrs: &[ast::Attribute]) -> Option<(Symbol, Span)> { ...@@ -194,7 +189,7 @@ pub fn extract(attrs: &[ast::Attribute]) -> Option<(Symbol, Span)> {
} }
} }
return None; None
} }
pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems { pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems {
......
...@@ -128,8 +128,8 @@ fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span ...@@ -128,8 +128,8 @@ fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span
let msg = format!( let msg = format!(
"feature `{}` is declared {}, but was previously declared {}", "feature `{}` is declared {}, but was previously declared {}",
feature, feature,
if since.is_some() { "stable"} else { "unstable" }, if since.is_some() { "stable" } else { "unstable" },
if since.is_none() { "stable"} else { "unstable" }, if since.is_none() { "stable" } else { "unstable" },
); );
self.tcx.sess.struct_span_err_with_code(span, &msg, self.tcx.sess.struct_span_err_with_code(span, &msg,
DiagnosticId::Error("E0711".into())).emit(); DiagnosticId::Error("E0711".into())).emit();
......
此差异已折叠。
...@@ -371,7 +371,9 @@ fn visit_item(&mut self, item: &hir::Item) { ...@@ -371,7 +371,9 @@ fn visit_item(&mut self, item: &hir::Item) {
return return
} }
for default_method in self.tcx.provided_trait_methods(trait_def_id) { let provided_trait_methods = self.tcx.provided_trait_methods(trait_def_id);
self.worklist.reserve(provided_trait_methods.len());
for default_method in provided_trait_methods {
let node_id = self.tcx let node_id = self.tcx
.hir .hir
.as_local_node_id(default_method.def_id) .as_local_node_id(default_method.def_id)
...@@ -394,7 +396,6 @@ fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) { ...@@ -394,7 +396,6 @@ fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
#[derive(Clone)] #[derive(Clone)]
pub struct ReachableSet(pub Lrc<NodeSet>); pub struct ReachableSet(pub Lrc<NodeSet>);
fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> ReachableSet { fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> ReachableSet {
debug_assert!(crate_num == LOCAL_CRATE); debug_assert!(crate_num == LOCAL_CRATE);
......
...@@ -459,13 +459,13 @@ pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, Scope ...@@ -459,13 +459,13 @@ pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, Scope
} }
} }
pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(Scope, Scope) { pub fn each_encl_scope<E>(&self, mut e: E) where E: FnMut(Scope, Scope) {
for (&child, &parent) in &self.parent_map { for (&child, &parent) in &self.parent_map {
e(child, parent.0) e(child, parent.0)
} }
} }
pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&hir::ItemLocalId, Scope) { pub fn each_var_scope<E>(&self, mut e: E) where E: FnMut(&hir::ItemLocalId, Scope) {
for (child, &parent) in self.var_map.iter() { for (child, &parent) in self.var_map.iter() {
e(child, parent) e(child, parent)
} }
...@@ -515,10 +515,8 @@ pub fn encl_scope(&self, id: Scope) -> Scope { ...@@ -515,10 +515,8 @@ pub fn encl_scope(&self, id: Scope) -> Scope {
/// Returns the lifetime of the local variable `var_id` /// Returns the lifetime of the local variable `var_id`
pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope { pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
match self.var_map.get(&var_id) { self.var_map.get(&var_id).cloned().unwrap_or_else(||
Some(&r) => r, bug!("no enclosing scope for id {:?}", var_id))
None => { bug!("no enclosing scope for id {:?}", var_id); }
}
} }
pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> { pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
...@@ -559,8 +557,7 @@ pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind { ...@@ -559,8 +557,7 @@ pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
scope scope
} }
pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope) pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope) -> bool {
-> bool {
self.is_subscope_of(scope1, scope2) || self.is_subscope_of(scope1, scope2) ||
self.is_subscope_of(scope2, scope1) self.is_subscope_of(scope2, scope1)
} }
...@@ -584,14 +581,13 @@ pub fn is_subscope_of(&self, ...@@ -584,14 +581,13 @@ pub fn is_subscope_of(&self,
} }
} }
debug!("is_subscope_of({:?}, {:?})=true", debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope);
subscope, superscope);
return true; return true;
} }
/// Returns the id of the innermost containing body /// Returns the id of the innermost containing body
pub fn containing_body(&self, mut scope: Scope)-> Option<hir::ItemLocalId> { pub fn containing_body(&self, mut scope: Scope) -> Option<hir::ItemLocalId> {
loop { loop {
if let ScopeData::CallSite = scope.data { if let ScopeData::CallSite = scope.data {
return Some(scope.item_local_id()); return Some(scope.item_local_id());
...@@ -664,8 +660,8 @@ pub fn nearest_common_ancestor(&self, scope_a: Scope, scope_b: Scope) -> Scope { ...@@ -664,8 +660,8 @@ pub fn nearest_common_ancestor(&self, scope_a: Scope, scope_b: Scope) -> Scope {
/// Assuming that the provided region was defined within this `ScopeTree`, /// Assuming that the provided region was defined within this `ScopeTree`,
/// returns the outermost `Scope` that the region outlives. /// returns the outermost `Scope` that the region outlives.
pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
br: &ty::EarlyBoundRegion) br: &ty::EarlyBoundRegion)
-> Scope { -> Scope {
let param_owner = tcx.parent_def_id(br.def_id).unwrap(); let param_owner = tcx.parent_def_id(br.def_id).unwrap();
let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap(); let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
...@@ -828,10 +824,8 @@ fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: ...@@ -828,10 +824,8 @@ fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk:
fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) { fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
visitor.terminating_scopes.insert(arm.body.hir_id.local_id); visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
if let Some(ref g) = arm.guard { if let Some(hir::Guard::If(ref expr)) = arm.guard {
match g { visitor.terminating_scopes.insert(expr.hir_id.local_id);
hir::Guard::If(ref expr) => visitor.terminating_scopes.insert(expr.hir_id.local_id),
};
} }
intravisit::walk_arm(visitor, arm); intravisit::walk_arm(visitor, arm);
...@@ -890,11 +884,9 @@ fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: ...@@ -890,11 +884,9 @@ fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr:
// This ensures fixed size stacks. // This ensures fixed size stacks.
hir::ExprKind::Binary( hir::ExprKind::Binary(
source_map::Spanned { node: hir::BinOpKind::And, .. }, source_map::Spanned { node: hir::BinOpKind::And, .. }, _, ref r) |
_, ref r) |
hir::ExprKind::Binary( hir::ExprKind::Binary(
source_map::Spanned { node: hir::BinOpKind::Or, .. }, source_map::Spanned { node: hir::BinOpKind::Or, .. }, _, ref r) => {
_, ref r) => {
// For shortcircuiting operators, mark the RHS as a terminating // For shortcircuiting operators, mark the RHS as a terminating
// scope since it only executes conditionally. // scope since it only executes conditionally.
terminating(r.hir_id.local_id); terminating(r.hir_id.local_id);
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
use rustc::lint; use rustc::lint;
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
use session::Session; use session::Session;
use std::borrow::Cow;
use std::cell::Cell; use std::cell::Cell;
use std::mem::replace; use std::mem::replace;
use syntax::ast; use syntax::ast;
...@@ -360,17 +361,17 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) { ...@@ -360,17 +361,17 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) {
is_late_bound_map: |tcx, id| { is_late_bound_map: |tcx, id| {
let id = LocalDefId::from_def_id(DefId::local(id)); // (*) let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
tcx.resolve_lifetimes(LOCAL_CRATE) tcx.resolve_lifetimes(LOCAL_CRATE)
.late_bound .late_bound
.get(&id) .get(&id)
.cloned() .cloned()
}, },
object_lifetime_defaults_map: |tcx, id| { object_lifetime_defaults_map: |tcx, id| {
let id = LocalDefId::from_def_id(DefId::local(id)); // (*) let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
tcx.resolve_lifetimes(LOCAL_CRATE) tcx.resolve_lifetimes(LOCAL_CRATE)
.object_lifetime_defaults .object_lifetime_defaults
.get(&id) .get(&id)
.cloned() .cloned()
}, },
..*providers ..*providers
...@@ -410,8 +411,8 @@ fn resolve_lifetimes<'tcx>( ...@@ -410,8 +411,8 @@ fn resolve_lifetimes<'tcx>(
for (k, v) in named_region_map.object_lifetime_defaults { for (k, v) in named_region_map.object_lifetime_defaults {
let hir_id = tcx.hir.node_to_hir_id(k); let hir_id = tcx.hir.node_to_hir_id(k);
let map = rl.object_lifetime_defaults let map = rl.object_lifetime_defaults
.entry(hir_id.owner_local_def_id()) .entry(hir_id.owner_local_def_id())
.or_default(); .or_default();
Lrc::get_mut(map) Lrc::get_mut(map)
.unwrap() .unwrap()
.insert(hir_id.local_id, Lrc::new(v)); .insert(hir_id.local_id, Lrc::new(v));
...@@ -676,7 +677,7 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) { ...@@ -676,7 +677,7 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
lifetime.span, lifetime.span,
E0657, E0657,
"`impl Trait` can only capture lifetimes \ "`impl Trait` can only capture lifetimes \
bound at the fn or impl level" bound at the fn or impl level"
); );
self.uninsert_lifetime_on_error(lifetime, def.unwrap()); self.uninsert_lifetime_on_error(lifetime, def.unwrap());
} }
...@@ -1250,24 +1251,24 @@ fn compute_object_lifetime_defaults( ...@@ -1250,24 +1251,24 @@ fn compute_object_lifetime_defaults(
let object_lifetime_default_reprs: String = result let object_lifetime_default_reprs: String = result
.iter() .iter()
.map(|set| match *set { .map(|set| match *set {
Set1::Empty => "BaseDefault".to_string(), Set1::Empty => "BaseDefault".into(),
Set1::One(Region::Static) => "'static".to_string(), Set1::One(Region::Static) => "'static".into(),
Set1::One(Region::EarlyBound(mut i, _, _)) => { Set1::One(Region::EarlyBound(mut i, _, _)) => {
generics.params.iter().find_map(|param| match param.kind { generics.params.iter().find_map(|param| match param.kind {
GenericParamKind::Lifetime { .. } => { GenericParamKind::Lifetime { .. } => {
if i == 0 { if i == 0 {
return Some(param.name.ident().to_string()); return Some(param.name.ident().to_string().into());
}
i -= 1;
None
} }
_ => None, i -= 1;
}).unwrap() None
}
_ => None,
}).unwrap()
} }
Set1::One(_) => bug!(), Set1::One(_) => bug!(),
Set1::Many => "Ambiguous".to_string(), Set1::Many => "Ambiguous".into(),
}) })
.collect::<Vec<String>>() .collect::<Vec<Cow<'static, str>>>()
.join(","); .join(",");
tcx.sess.span_err(item.span, &object_lifetime_default_reprs); tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
} }
...@@ -1420,16 +1421,13 @@ fn check_uses_for_lifetimes_defined_by_scope(&mut self) { ...@@ -1420,16 +1421,13 @@ fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
def_ids.sort_by_key(|&def_id| self.tcx.def_path_hash(def_id)); def_ids.sort_by_key(|&def_id| self.tcx.def_path_hash(def_id));
for def_id in def_ids { for def_id in def_ids {
debug!( debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
"check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
def_id,
);
let lifetimeuseset = self.lifetime_uses.remove(&def_id); let lifetimeuseset = self.lifetime_uses.remove(&def_id);
debug!(
"check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}", debug!("check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
lifetimeuseset lifetimeuseset);
);
match lifetimeuseset { match lifetimeuseset {
Some(LifetimeUseSet::One(lifetime)) => { Some(LifetimeUseSet::One(lifetime)) => {
let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap(); let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
...@@ -1669,7 +1667,7 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) { ...@@ -1669,7 +1667,7 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
"lifetimes used in `fn` or `Fn` syntax must be \ "lifetimes used in `fn` or `Fn` syntax must be \
explicitly declared using `<...>` binders" explicitly declared using `<...>` binders"
).span_label(lifetime_ref.span, "in-band lifetime definition") ).span_label(lifetime_ref.span, "in-band lifetime definition")
.emit(); .emit();
} }
Region::Static Region::Static
...@@ -1689,7 +1687,7 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) { ...@@ -1689,7 +1687,7 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
"use of undeclared lifetime name `{}`", "use of undeclared lifetime name `{}`",
lifetime_ref lifetime_ref
).span_label(lifetime_ref.span, "undeclared lifetime") ).span_label(lifetime_ref.span, "undeclared lifetime")
.emit(); .emit();
} }
} }
...@@ -1872,18 +1870,15 @@ fn visit_fn_like_elision( ...@@ -1872,18 +1870,15 @@ fn visit_fn_like_elision(
node: hir::TraitItemKind::Method(_, ref m), node: hir::TraitItemKind::Method(_, ref m),
.. ..
}) => { }) => {
match self.tcx if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx
.hir .hir
.expect_item(self.tcx.hir.get_parent(parent)) .expect_item(self.tcx.hir.get_parent(parent))
.node .node
{ {
hir::ItemKind::Trait(.., ref trait_items) => { assoc_item_kind = trait_items
assoc_item_kind = trait_items .iter()
.iter() .find(|ti| ti.id.node_id == parent)
.find(|ti| ti.id.node_id == parent) .map(|ti| ti.kind);
.map(|ti| ti.kind);
}
_ => {}
} }
match *m { match *m {
hir::TraitMethod::Required(_) => None, hir::TraitMethod::Required(_) => None,
...@@ -1895,19 +1890,16 @@ fn visit_fn_like_elision( ...@@ -1895,19 +1890,16 @@ fn visit_fn_like_elision(
node: hir::ImplItemKind::Method(_, body), node: hir::ImplItemKind::Method(_, body),
.. ..
}) => { }) => {
match self.tcx if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx
.hir .hir
.expect_item(self.tcx.hir.get_parent(parent)) .expect_item(self.tcx.hir.get_parent(parent))
.node .node
{ {
hir::ItemKind::Impl(.., ref self_ty, ref impl_items) => { impl_self = Some(self_ty);
impl_self = Some(self_ty); assoc_item_kind = impl_items
assoc_item_kind = impl_items .iter()
.iter() .find(|ii| ii.id.node_id == parent)
.find(|ii| ii.id.node_id == parent) .map(|ii| ii.kind);
.map(|ii| ii.kind);
}
_ => {}
} }
Some(body) Some(body)
} }
...@@ -2255,9 +2247,7 @@ fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) ...@@ -2255,9 +2247,7 @@ fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime)
Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return, Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
Scope::ObjectLifetimeDefault { Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
lifetime: Some(l), ..
} => break l,
} }
}; };
self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth)); self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
...@@ -2329,13 +2319,11 @@ fn check_lifetime_params(&mut self, old_scope: ScopeRef<'_>, ...@@ -2329,13 +2319,11 @@ fn check_lifetime_params(&mut self, old_scope: ScopeRef<'_>,
lifetime_i.name.ident(), lifetime_i.name.ident(),
), ),
).help(&format!( ).help(&format!(
"you can use the `'static` lifetime directly, in place \ "you can use the `'static` lifetime directly, in place of `{}`",
of `{}`",
lifetime_i.name.ident(), lifetime_i.name.ident(),
)).emit(); )).emit();
} }
hir::LifetimeName::Param(_) hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
| hir::LifetimeName::Implicit => {
self.resolve_lifetime_ref(lt); self.resolve_lifetime_ref(lt);
} }
} }
...@@ -2492,8 +2480,6 @@ fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_ ...@@ -2492,8 +2480,6 @@ fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_
} }
} }
///////////////////////////////////////////////////////////////////////////
/// Detects late-bound lifetimes and inserts them into /// Detects late-bound lifetimes and inserts them into
/// `map.late_bound`. /// `map.late_bound`.
/// ///
...@@ -2509,10 +2495,8 @@ fn insert_late_bound_lifetimes( ...@@ -2509,10 +2495,8 @@ fn insert_late_bound_lifetimes(
decl: &hir::FnDecl, decl: &hir::FnDecl,
generics: &hir::Generics, generics: &hir::Generics,
) { ) {
debug!( debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})",
"insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics);
decl, generics
);
let mut constrained_by_input = ConstrainedCollector { let mut constrained_by_input = ConstrainedCollector {
regions: FxHashSet(), regions: FxHashSet(),
...@@ -2526,10 +2510,8 @@ fn insert_late_bound_lifetimes( ...@@ -2526,10 +2510,8 @@ fn insert_late_bound_lifetimes(
}; };
intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output); intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
debug!( debug!("insert_late_bound_lifetimes: constrained_by_input={:?}",
"insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions);
constrained_by_input.regions
);
// Walk the lifetimes that appear in where clauses. // Walk the lifetimes that appear in where clauses.
// //
...@@ -2541,15 +2523,12 @@ fn insert_late_bound_lifetimes( ...@@ -2541,15 +2523,12 @@ fn insert_late_bound_lifetimes(
appears_in_where_clause.visit_generics(generics); appears_in_where_clause.visit_generics(generics);
for param in &generics.params { for param in &generics.params {
match param.kind { if let hir::GenericParamKind::Lifetime { .. } = param.kind {
hir::GenericParamKind::Lifetime { .. } => { if !param.bounds.is_empty() {
if !param.bounds.is_empty() { // `'a: 'b` means both `'a` and `'b` are referenced
// `'a: 'b` means both `'a` and `'b` are referenced appears_in_where_clause
appears_in_where_clause .regions.insert(hir::LifetimeName::Param(param.name.modern()));
.regions.insert(hir::LifetimeName::Param(param.name.modern()));
}
} }
hir::GenericParamKind::Type { .. } => {}
} }
} }
...@@ -2661,10 +2640,10 @@ pub fn report_missing_lifetime_specifiers( ...@@ -2661,10 +2640,10 @@ pub fn report_missing_lifetime_specifiers(
if count > 1 { "s" } else { "" } if count > 1 { "s" } else { "" }
); );
let msg = if count > 1 { let msg: Cow<'static, str> = if count > 1 {
format!("expected {} lifetime parameters", count) format!("expected {} lifetime parameters", count).into()
} else { } else {
"expected lifetime parameter".to_string() "expected lifetime parameter".into()
}; };
err.span_label(span, msg); err.span_label(span, msg);
......
...@@ -164,8 +164,10 @@ fn annotate<F>(&mut self, id: NodeId, attrs: &[Attribute], ...@@ -164,8 +164,10 @@ fn annotate<F>(&mut self, id: NodeId, attrs: &[Attribute],
if let (&Some(attr::RustcDeprecation {since: dep_since, ..}), if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
&attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) { &attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
// Explicit version of iter::order::lt to handle parse errors properly // Explicit version of iter::order::lt to handle parse errors properly
for (dep_v, stab_v) in for (dep_v, stab_v) in dep_since.as_str()
dep_since.as_str().split('.').zip(stab_since.as_str().split('.')) { .split('.')
.zip(stab_since.as_str().split('.'))
{
if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) { if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
match dep_v.cmp(&stab_v) { match dep_v.cmp(&stab_v) {
Ordering::Less => { Ordering::Less => {
...@@ -523,15 +525,12 @@ fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool { ...@@ -523,15 +525,12 @@ fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
Some(Def::Method(_)) | Some(Def::Method(_)) |
Some(Def::AssociatedTy(_)) | Some(Def::AssociatedTy(_)) |
Some(Def::AssociatedConst(_)) => { Some(Def::AssociatedConst(_)) => {
match self.associated_item(def_id).container { if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container {
ty::TraitContainer(trait_def_id) => { // Trait methods do not declare visibility (even
// Trait methods do not declare visibility (even // for visibility info in cstore). Use containing
// for visibility info in cstore). Use containing // trait instead, so methods of pub traits are
// trait instead, so methods of pub traits are // themselves considered pub.
// themselves considered pub. def_id = trait_def_id;
def_id = trait_def_id;
}
_ => {}
} }
} }
_ => {} _ => {}
...@@ -561,8 +560,7 @@ fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool { ...@@ -561,8 +560,7 @@ fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
/// `id`. /// `id`.
pub fn eval_stability(self, def_id: DefId, id: Option<NodeId>, span: Span) -> EvalResult { pub fn eval_stability(self, def_id: DefId, id: Option<NodeId>, span: Span) -> EvalResult {
if span.allows_unstable() { if span.allows_unstable() {
debug!("stability: \ debug!("stability: skipping span={:?} since it is internal", span);
skipping span={:?} since it is internal", span);
return EvalResult::Allow; return EvalResult::Allow;
} }
...@@ -770,8 +768,8 @@ fn visit_item(&mut self, item: &'tcx hir::Item) { ...@@ -770,8 +768,8 @@ fn visit_item(&mut self, item: &'tcx hir::Item) {
let param_env = self.tcx.param_env(def_id); let param_env = self.tcx.param_env(def_id);
if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() { if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() {
emit_feature_err(&self.tcx.sess.parse_sess, emit_feature_err(&self.tcx.sess.parse_sess,
"untagged_unions", item.span, GateIssue::Language, "untagged_unions", item.span, GateIssue::Language,
"unions with non-`Copy` fields are unstable"); "unions with non-`Copy` fields are unstable");
} }
} }
} }
......
...@@ -113,13 +113,13 @@ fn verify<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ...@@ -113,13 +113,13 @@ fn verify<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
items.$name().is_none() { items.$name().is_none() {
if lang_items::$item == lang_items::PanicImplLangItem { if lang_items::$item == lang_items::PanicImplLangItem {
tcx.sess.err(&format!("`#[panic_handler]` function required, \ tcx.sess.err(&format!("`#[panic_handler]` function required, \
but not found")); but not found"));
} else if lang_items::$item == lang_items::OomLangItem { } else if lang_items::$item == lang_items::OomLangItem {
tcx.sess.err(&format!("`#[alloc_error_handler]` function required, \ tcx.sess.err(&format!("`#[alloc_error_handler]` function required, \
but not found")); but not found"));
} else { } else {
tcx.sess.err(&format!("language item required, but not found: `{}`", tcx.sess.err(&format!("language item required, but not found: `{}`",
stringify!($name))); stringify!($name)));
} }
} }
)* )*
......
...@@ -38,6 +38,7 @@ ...@@ -38,6 +38,7 @@
use rustc_mir::util::suggest_ref_mut; use rustc_mir::util::suggest_ref_mut;
use rustc::util::nodemap::FxHashSet; use rustc::util::nodemap::FxHashSet;
use std::borrow::Cow;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::fmt; use std::fmt;
use std::rc::Rc; use std::rc::Rc;
...@@ -808,34 +809,34 @@ fn report_bckerr(&self, err: &BckError<'a, 'tcx>) { ...@@ -808,34 +809,34 @@ fn report_bckerr(&self, err: &BckError<'a, 'tcx>) {
match err.code { match err.code {
err_mutbl => { err_mutbl => {
let descr = match err.cmt.note { let descr: Cow<'static, str> = match err.cmt.note {
mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => { mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
self.cmt_to_string(&err.cmt) self.cmt_to_cow_str(&err.cmt)
} }
_ => match opt_loan_path_is_field(&err.cmt) { _ => match opt_loan_path_is_field(&err.cmt) {
(None, true) => { (None, true) => {
format!("{} of {} binding", format!("{} of {} binding",
self.cmt_to_string(&err.cmt), self.cmt_to_cow_str(&err.cmt),
err.cmt.mutbl.to_user_str()) err.cmt.mutbl.to_user_str()).into()
} }
(None, false) => { (None, false) => {
format!("{} {}", format!("{} {}",
err.cmt.mutbl.to_user_str(), err.cmt.mutbl.to_user_str(),
self.cmt_to_string(&err.cmt)) self.cmt_to_cow_str(&err.cmt)).into()
} }
(Some(lp), true) => { (Some(lp), true) => {
format!("{} `{}` of {} binding", format!("{} `{}` of {} binding",
self.cmt_to_string(&err.cmt), self.cmt_to_cow_str(&err.cmt),
self.loan_path_to_string(&lp), self.loan_path_to_string(&lp),
err.cmt.mutbl.to_user_str()) err.cmt.mutbl.to_user_str()).into()
} }
(Some(lp), false) => { (Some(lp), false) => {
format!("{} {} `{}`", format!("{} {} `{}`",
err.cmt.mutbl.to_user_str(), err.cmt.mutbl.to_user_str(),
self.cmt_to_string(&err.cmt), self.cmt_to_cow_str(&err.cmt),
self.loan_path_to_string(&lp)) self.loan_path_to_string(&lp)).into()
} }
} }
}; };
...@@ -1058,11 +1059,11 @@ fn report_bckerr(&self, err: &BckError<'a, 'tcx>) { ...@@ -1058,11 +1059,11 @@ fn report_bckerr(&self, err: &BckError<'a, 'tcx>) {
err_borrowed_pointer_too_short(loan_scope, ptr_scope) => { err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
let descr = self.cmt_to_path_or_string(err.cmt); let descr = self.cmt_to_path_or_string(err.cmt);
let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast); let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
let descr = match opt_loan_path(&err.cmt) { let descr: Cow<'static, str> = match opt_loan_path(&err.cmt) {
Some(lp) => { Some(lp) => {
format!("`{}`", self.loan_path_to_string(&lp)) format!("`{}`", self.loan_path_to_string(&lp)).into()
} }
None => self.cmt_to_string(&err.cmt), None => self.cmt_to_cow_str(&err.cmt)
}; };
self.tcx.note_and_explain_region( self.tcx.note_and_explain_region(
&self.region_scope_tree, &self.region_scope_tree,
...@@ -1477,14 +1478,14 @@ pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String { ...@@ -1477,14 +1478,14 @@ pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String {
result result
} }
pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String { pub fn cmt_to_cow_str(&self, cmt: &mc::cmt_<'tcx>) -> Cow<'static, str> {
cmt.descriptive_string(self.tcx) cmt.descriptive_string(self.tcx)
} }
pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String { pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
match opt_loan_path(cmt) { match opt_loan_path(cmt) {
Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)), Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
None => self.cmt_to_string(cmt), None => self.cmt_to_cow_str(cmt).into_owned(),
} }
} }
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册