From 455945f24b12689340d5085ed795aa3bfdab9d34 Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Sat, 28 Sep 2019 15:59:19 +0100 Subject: [PATCH 1/2] Remove HIR based const qualification --- src/librustc/middle/expr_use_visitor.rs | 15 +- src/librustc/middle/mem_categorization.rs | 66 +-- src/librustc/query/mod.rs | 14 +- src/librustc/ty/query/mod.rs | 2 +- src/librustc_interface/passes.rs | 3 +- src/librustc_metadata/cstore_impl.rs | 3 - src/librustc_metadata/decoder.rs | 8 - src/librustc_metadata/encoder.rs | 22 +- src/librustc_metadata/schema.rs | 1 - src/librustc_passes/lib.rs | 2 - src/librustc_passes/rvalue_promotion.rs | 658 ---------------------- src/librustc_typeck/check/dropck.rs | 84 +-- src/librustc_typeck/check/regionck.rs | 54 +- src/librustc_typeck/check/upvar.rs | 8 +- src/test/ui/issues/issue-17252.stderr | 6 +- src/test/ui/issues/issue-23302-1.stderr | 4 +- src/test/ui/issues/issue-23302-2.stderr | 4 +- src/test/ui/issues/issue-23302-3.stderr | 22 +- src/test/ui/issues/issue-36163.stderr | 6 +- 19 files changed, 66 insertions(+), 916 deletions(-) delete mode 100644 src/librustc_passes/rvalue_promotion.rs diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 45b660f5c67f6..d8b84fd473744 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -20,7 +20,6 @@ use crate::ty::{self, DefIdTree, TyCtxt, adjustment}; use crate::hir::{self, PatKind}; use std::rc::Rc; use syntax_pos::Span; -use crate::util::nodemap::ItemLocalSet; /////////////////////////////////////////////////////////////////////////// // The Delegate trait @@ -261,9 +260,6 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`) /// - `region_scope_tree` --- region scope tree for the code being analyzed /// - `tables` --- typeck results for the code being analyzed - /// - `rvalue_promotable_map` --- if you care about rvalue promotion, then provide - /// the map here (it can be computed with `tcx.rvalue_promotable_map(def_id)`). - /// `None` means that rvalues will be given more conservative lifetimes. /// /// See also `with_infer`, which is used *during* typeck. pub fn new( @@ -273,15 +269,13 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { param_env: ty::ParamEnv<'tcx>, region_scope_tree: &'a region::ScopeTree, tables: &'a ty::TypeckTables<'tcx>, - rvalue_promotable_map: Option<&'tcx ItemLocalSet>, ) -> Self { ExprUseVisitor { mc: mc::MemCategorizationContext::new(tcx, param_env, body_owner, region_scope_tree, - tables, - rvalue_promotable_map), + tables), delegate, param_env, } @@ -317,16 +311,9 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { let param_ty = return_if_err!(self.mc.pat_ty_adjusted(¶m.pat)); debug!("consume_body: param_ty = {:?}", param_ty); - let fn_body_scope_r = - self.tcx().mk_region(ty::ReScope( - region::Scope { - id: body.value.hir_id.local_id, - data: region::ScopeData::Node - })); let param_cmt = Rc::new(self.mc.cat_rvalue( param.hir_id, param.pat.span, - fn_body_scope_r, // Parameters live only as long as the fn body. param_ty)); self.walk_irrefutable_pat(param_cmt, ¶m.pat); diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 3f5f54c94638e..edfcc30a749cf 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -79,12 +79,11 @@ use std::fmt; use std::hash::{Hash, Hasher}; use rustc_data_structures::fx::FxIndexMap; use std::rc::Rc; -use crate::util::nodemap::ItemLocalSet; #[derive(Clone, Debug, PartialEq)] pub enum Categorization<'tcx> { - Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope - ThreadLocal(ty::Region<'tcx>), // value that cannot move, but still restricted in scope + Rvalue, // temporary val + ThreadLocal, // value that cannot move, but still restricted in scope StaticItem, Upvar(Upvar), // upvar referenced by closure env Local(hir::HirId), // local variable @@ -219,7 +218,6 @@ pub struct MemCategorizationContext<'a, 'tcx> { pub upvars: Option<&'tcx FxIndexMap>, pub region_scope_tree: &'a region::ScopeTree, pub tables: &'a ty::TypeckTables<'tcx>, - rvalue_promotable_map: Option<&'tcx ItemLocalSet>, infcx: Option<&'a InferCtxt<'a, 'tcx>>, } @@ -335,7 +333,6 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { body_owner: DefId, region_scope_tree: &'a region::ScopeTree, tables: &'a ty::TypeckTables<'tcx>, - rvalue_promotable_map: Option<&'tcx ItemLocalSet>, ) -> MemCategorizationContext<'a, 'tcx> { MemCategorizationContext { tcx, @@ -343,7 +340,6 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { upvars: tcx.upvars(body_owner), region_scope_tree, tables, - rvalue_promotable_map, infcx: None, param_env, } @@ -369,19 +365,12 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { ) -> MemCategorizationContext<'a, 'tcx> { let tcx = infcx.tcx; - // Subtle: we can't do rvalue promotion analysis until the - // typeck phase is complete, which means that you can't trust - // the rvalue lifetimes that result, but that's ok, since we - // don't need to know those during type inference. - let rvalue_promotable_map = None; - MemCategorizationContext { tcx, body_owner, upvars: tcx.upvars(body_owner), region_scope_tree, tables, - rvalue_promotable_map, infcx: Some(infcx), param_env, } @@ -664,8 +653,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { .any(|attr| attr.check_name(sym::thread_local)); let cat = if is_thread_local { - let re = self.temporary_scope(hir_id.local_id); - Categorization::ThreadLocal(re) + Categorization::ThreadLocal } else { Categorization::StaticItem }; @@ -876,16 +864,6 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { ret } - /// Returns the lifetime of a temporary created by expr with id `id`. - /// This could be `'static` if `id` is part of a constant expression. - pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> { - let scope = self.region_scope_tree.temporary_scope(id); - self.tcx.mk_region(match scope { - Some(scope) => ty::ReScope(scope), - None => ty::ReStatic - }) - } - pub fn cat_rvalue_node(&self, hir_id: hir::HirId, span: Span, @@ -894,28 +872,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})", hir_id, span, expr_ty); - let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id)) - .unwrap_or(false); - - debug!("cat_rvalue_node: promotable = {:?}", promotable); - - // Always promote `[T; 0]` (even when e.g., borrowed mutably). - let promotable = match expr_ty.kind { - ty::Array(_, len) if len.try_eval_usize(self.tcx, self.param_env) == Some(0) => true, - _ => promotable, - }; - - debug!("cat_rvalue_node: promotable = {:?} (2)", promotable); - - // Compute maximum lifetime of this rvalue. This is 'static if - // we can promote to a constant, otherwise equal to enclosing temp - // lifetime. - let re = if promotable { - self.tcx.lifetimes.re_static - } else { - self.temporary_scope(hir_id.local_id) - }; - let ret = self.cat_rvalue(hir_id, span, re, expr_ty); + let ret = self.cat_rvalue(hir_id, span, expr_ty); debug!("cat_rvalue_node ret {:?}", ret); ret } @@ -923,12 +880,11 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { pub fn cat_rvalue(&self, cmt_hir_id: hir::HirId, span: Span, - temp_scope: ty::Region<'tcx>, expr_ty: Ty<'tcx>) -> cmt_<'tcx> { let ret = cmt_ { hir_id: cmt_hir_id, span:span, - cat:Categorization::Rvalue(temp_scope), + cat:Categorization::Rvalue, mutbl:McDeclared, ty:expr_ty, note: NoteNone @@ -1376,9 +1332,9 @@ impl<'tcx> cmt_<'tcx> { //! determines how long the value in `self` remains live. match self.cat { - Categorization::Rvalue(..) | + Categorization::Rvalue | Categorization::StaticItem | - Categorization::ThreadLocal(..) | + Categorization::ThreadLocal | Categorization::Local(..) | Categorization::Deref(_, UnsafePtr(..)) | Categorization::Deref(_, BorrowedPtr(..)) | @@ -1409,8 +1365,8 @@ impl<'tcx> cmt_<'tcx> { b.freely_aliasable() } - Categorization::Rvalue(..) | - Categorization::ThreadLocal(..) | + Categorization::Rvalue | + Categorization::ThreadLocal | Categorization::Local(..) | Categorization::Upvar(..) | Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but... @@ -1457,10 +1413,10 @@ impl<'tcx> cmt_<'tcx> { Categorization::StaticItem => { "static item".into() } - Categorization::ThreadLocal(..) => { + Categorization::ThreadLocal => { "thread-local static item".into() } - Categorization::Rvalue(..) => { + Categorization::Rvalue => { "non-place".into() } Categorization::Local(vid) => { diff --git a/src/librustc/query/mod.rs b/src/librustc/query/mod.rs index e463810b7af5f..c95652f274e36 100644 --- a/src/librustc/query/mod.rs +++ b/src/librustc/query/mod.rs @@ -94,6 +94,7 @@ rustc_queries! { /// of the MIR qualify_consts pass. The actual meaning of /// the value isn't known except to the pass itself. query mir_const_qualif(key: DefId) -> (u8, &'tcx BitSet) { + desc { |tcx| "const checking `{}`", tcx.def_path_str(key) } cache_on_disk_if { key.is_local() } } @@ -530,19 +531,6 @@ rustc_queries! { TypeChecking { query trait_of_item(_: DefId) -> Option {} - query const_is_rvalue_promotable_to_static(key: DefId) -> bool { - desc { |tcx| - "const checking if rvalue is promotable to static `{}`", - tcx.def_path_str(key) - } - cache_on_disk_if { true } - } - query rvalue_promotable_map(key: DefId) -> &'tcx ItemLocalSet { - desc { |tcx| - "checking which parts of `{}` are promotable to static", - tcx.def_path_str(key) - } - } } Codegen { diff --git a/src/librustc/ty/query/mod.rs b/src/librustc/ty/query/mod.rs index 863721a5b4b79..4279ca8c3daf6 100644 --- a/src/librustc/ty/query/mod.rs +++ b/src/librustc/ty/query/mod.rs @@ -37,7 +37,7 @@ use crate::ty::{self, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt, AdtSizedConst use crate::ty::steal::Steal; use crate::ty::util::NeedsDrop; use crate::ty::subst::SubstsRef; -use crate::util::nodemap::{DefIdSet, DefIdMap, ItemLocalSet}; +use crate::util::nodemap::{DefIdSet, DefIdMap}; use crate::util::common::ErrorReported; use crate::util::profiling::ProfileCategory::*; diff --git a/src/librustc_interface/passes.rs b/src/librustc_interface/passes.rs index 8474bae5a71d2..5f6c4629b090c 100644 --- a/src/librustc_interface/passes.rs +++ b/src/librustc_interface/passes.rs @@ -916,9 +916,8 @@ fn analysis(tcx: TyCtxt<'_>, cnum: CrateNum) -> Result<()> { time(sess, "misc checking 2", || { parallel!({ - time(sess, "rvalue promotion + match checking", || { + time(sess, "match checking", || { tcx.par_body_owners(|def_id| { - tcx.ensure().const_is_rvalue_promotable_to_static(def_id); tcx.ensure().check_match(def_id); }); }); diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index edb6f594fdd0d..0f80540b11ea3 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -154,9 +154,6 @@ provide! { <'tcx> tcx, def_id, other, cdata, rendered_const => { cdata.get_rendered_const(def_id.index) } impl_parent => { cdata.get_parent_impl(def_id.index) } trait_of_item => { cdata.get_trait_of_item(def_id.index) } - const_is_rvalue_promotable_to_static => { - cdata.const_is_rvalue_promotable_to_static(def_id.index) - } is_mir_available => { cdata.is_item_mir_available(def_id.index) } dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) } diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index 9fcc310154599..da0c7493b5c68 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -915,14 +915,6 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool { - match self.entry(id).kind { - EntryKind::AssocConst(_, data, _) | - EntryKind::Const(data, _) => data.ast_promotable, - _ => bug!(), - } - } - pub fn is_item_mir_available(&self, id: DefIndex) -> bool { !self.is_proc_macro(id) && self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some() diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index a86bc283cedc6..4ed6954d8fb3a 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -861,18 +861,11 @@ impl EncodeContext<'tcx> { let kind = match trait_item.kind { ty::AssocKind::Const => { - let const_qualif = - if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.kind { - self.const_qualif(0, body) - } else { - ConstQualif { mir: 0, ast_promotable: false } - }; - let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item)); let rendered_const = self.lazy(RenderedConst(rendered)); - EntryKind::AssocConst(container, const_qualif, rendered_const) + EntryKind::AssocConst(container, ConstQualif { mir: 0 }, rendered_const) } ty::AssocKind::Method => { let fn_data = if let hir::TraitItemKind::Method(method_sig, m) = &ast_item.kind { @@ -946,13 +939,6 @@ impl EncodeContext<'tcx> { !self.tcx.sess.opts.output_types.should_codegen() } - fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif { - let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id); - let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id); - - ConstQualif { mir, ast_promotable } - } - fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> { debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); let tcx = self.tcx; @@ -974,7 +960,7 @@ impl EncodeContext<'tcx> { let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0; EntryKind::AssocConst(container, - self.const_qualif(mir, body_id), + ConstQualif { mir }, self.encode_rendered_const_for_body(body_id)) } else { bug!() @@ -1123,7 +1109,7 @@ impl EncodeContext<'tcx> { hir::ItemKind::Const(_, body_id) => { let mir = tcx.at(item.span).mir_const_qualif(def_id).0; EntryKind::Const( - self.const_qualif(mir, body_id), + ConstQualif { mir }, self.encode_rendered_const_for_body(body_id) ) } @@ -1475,7 +1461,7 @@ impl EncodeContext<'tcx> { let mir = tcx.mir_const_qualif(def_id).0; Entry { - kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data), + kind: EntryKind::Const(ConstQualif { mir }, const_data), visibility: self.lazy(ty::Visibility::Public), span: self.lazy(tcx.def_span(def_id)), attributes: Lazy::empty(), diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs index 2069adea021b8..4fe9c466cb6da 100644 --- a/src/librustc_metadata/schema.rs +++ b/src/librustc_metadata/schema.rs @@ -274,7 +274,6 @@ pub enum EntryKind<'tcx> { #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct ConstQualif { pub mir: u8, - pub ast_promotable: bool, } /// Contains a constant which has been rendered to a String. diff --git a/src/librustc_passes/lib.rs b/src/librustc_passes/lib.rs index 4e29706714f3d..6c7958fb365dd 100644 --- a/src/librustc_passes/lib.rs +++ b/src/librustc_passes/lib.rs @@ -19,12 +19,10 @@ use rustc::ty::query::Providers; pub mod error_codes; pub mod ast_validation; -pub mod rvalue_promotion; pub mod hir_stats; pub mod layout_test; pub mod loops; pub fn provide(providers: &mut Providers<'_>) { - rvalue_promotion::provide(providers); loops::provide(providers); } diff --git a/src/librustc_passes/rvalue_promotion.rs b/src/librustc_passes/rvalue_promotion.rs deleted file mode 100644 index a93ca7847d68a..0000000000000 --- a/src/librustc_passes/rvalue_promotion.rs +++ /dev/null @@ -1,658 +0,0 @@ -// Verifies that the types and values of const and static items -// are safe. The rules enforced by this module are: -// -// - For each *mutable* static item, it checks that its **type**: -// - doesn't have a destructor -// - doesn't own a box -// -// - For each *immutable* static item, it checks that its **value**: -// - doesn't own a box -// - doesn't contain a struct literal or a call to an enum variant / struct constructor where -// - the type of the struct/enum has a dtor -// -// Rules Enforced Elsewhere: -// - It's not possible to take the address of a static item with unsafe interior. This is enforced -// by borrowck::gather_loans - -use rustc::ty::cast::CastTy; -use rustc::hir::def::{Res, DefKind, CtorKind}; -use rustc::hir::def_id::DefId; -use rustc::middle::expr_use_visitor as euv; -use rustc::middle::mem_categorization as mc; -use rustc::middle::mem_categorization::Categorization; -use rustc::ty::{self, Ty, TyCtxt}; -use rustc::ty::query::Providers; -use rustc::ty::subst::{InternalSubsts, SubstsRef}; -use rustc::util::nodemap::{ItemLocalSet, HirIdSet}; -use rustc::hir; -use syntax::symbol::sym; -use syntax_pos::{Span, DUMMY_SP}; -use log::debug; -use Promotability::*; -use std::ops::{BitAnd, BitAndAssign, BitOr}; - -pub fn provide(providers: &mut Providers<'_>) { - *providers = Providers { - rvalue_promotable_map, - const_is_rvalue_promotable_to_static, - ..*providers - }; -} - -fn const_is_rvalue_promotable_to_static(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - assert!(def_id.is_local()); - - let hir_id = tcx.hir().as_local_hir_id(def_id) - .expect("rvalue_promotable_map invoked with non-local def-id"); - let body_id = tcx.hir().body_owned_by(hir_id); - tcx.rvalue_promotable_map(def_id).contains(&body_id.hir_id.local_id) -} - -fn rvalue_promotable_map(tcx: TyCtxt<'_>, def_id: DefId) -> &ItemLocalSet { - let outer_def_id = tcx.closure_base_def_id(def_id); - if outer_def_id != def_id { - return tcx.rvalue_promotable_map(outer_def_id); - } - - let mut visitor = CheckCrateVisitor { - tcx, - tables: &ty::TypeckTables::empty(None), - in_fn: false, - in_static: false, - mut_rvalue_borrows: Default::default(), - param_env: ty::ParamEnv::empty(), - identity_substs: InternalSubsts::empty(), - result: ItemLocalSet::default(), - }; - - // `def_id` should be a `Body` owner - let hir_id = tcx.hir().as_local_hir_id(def_id) - .expect("rvalue_promotable_map invoked with non-local def-id"); - let body_id = tcx.hir().body_owned_by(hir_id); - let _ = visitor.check_nested_body(body_id); - - tcx.arena.alloc(visitor.result) -} - -struct CheckCrateVisitor<'a, 'tcx> { - tcx: TyCtxt<'tcx>, - in_fn: bool, - in_static: bool, - mut_rvalue_borrows: HirIdSet, - param_env: ty::ParamEnv<'tcx>, - identity_substs: SubstsRef<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, - result: ItemLocalSet, -} - -#[must_use] -#[derive(Debug, Clone, Copy, PartialEq)] -enum Promotability { - Promotable, - NotPromotable -} - -impl BitAnd for Promotability { - type Output = Self; - - fn bitand(self, rhs: Self) -> Self { - match (self, rhs) { - (Promotable, Promotable) => Promotable, - _ => NotPromotable, - } - } -} - -impl BitAndAssign for Promotability { - fn bitand_assign(&mut self, rhs: Self) { - *self = *self & rhs - } -} - -impl BitOr for Promotability { - type Output = Self; - - fn bitor(self, rhs: Self) -> Self { - match (self, rhs) { - (NotPromotable, NotPromotable) => NotPromotable, - _ => Promotable, - } - } -} - -impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> { - // Returns true iff all the values of the type are promotable. - fn type_promotability(&mut self, ty: Ty<'tcx>) -> Promotability { - debug!("type_promotability({})", ty); - - if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) && - !ty.needs_drop(self.tcx, self.param_env) { - Promotable - } else { - NotPromotable - } - } - - fn handle_const_fn_call( - &mut self, - def_id: DefId, - ) -> Promotability { - if self.tcx.is_promotable_const_fn(def_id) { - Promotable - } else { - NotPromotable - } - } - - /// While the `ExprUseVisitor` walks, we will identify which - /// expressions are borrowed, and insert their IDs into this - /// table. Actually, we insert the "borrow-id", which is normally - /// the ID of the expression being borrowed: but in the case of - /// `ref mut` borrows, the `id` of the pattern is - /// inserted. Therefore, later we remove that entry from the table - /// and transfer it over to the value being matched. This will - /// then prevent said value from being promoted. - fn remove_mut_rvalue_borrow(&mut self, pat: &hir::Pat) -> bool { - let mut any_removed = false; - pat.walk(|p| { - any_removed |= self.mut_rvalue_borrows.remove(&p.hir_id); - true - }); - any_removed - } -} - -impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> { - fn check_nested_body(&mut self, body_id: hir::BodyId) -> Promotability { - let item_id = self.tcx.hir().body_owner(body_id); - let item_def_id = self.tcx.hir().local_def_id(item_id); - - let outer_in_fn = self.in_fn; - let outer_tables = self.tables; - let outer_param_env = self.param_env; - let outer_identity_substs = self.identity_substs; - - self.in_fn = false; - self.in_static = false; - - match self.tcx.hir().body_owner_kind(item_id) { - hir::BodyOwnerKind::Closure | - hir::BodyOwnerKind::Fn => self.in_fn = true, - hir::BodyOwnerKind::Static(_) => self.in_static = true, - _ => {} - }; - - - self.tables = self.tcx.typeck_tables_of(item_def_id); - self.param_env = self.tcx.param_env(item_def_id); - self.identity_substs = InternalSubsts::identity_for_item(self.tcx, item_def_id); - - let body = self.tcx.hir().body(body_id); - - let tcx = self.tcx; - let param_env = self.param_env; - let region_scope_tree = self.tcx.region_scope_tree(item_def_id); - let tables = self.tables; - euv::ExprUseVisitor::new( - self, - tcx, - item_def_id, - param_env, - ®ion_scope_tree, - tables, - None, - ).consume_body(body); - - let body_promotable = self.check_expr(&body.value); - self.in_fn = outer_in_fn; - self.tables = outer_tables; - self.param_env = outer_param_env; - self.identity_substs = outer_identity_substs; - body_promotable - } - - fn check_stmt(&mut self, stmt: &'tcx hir::Stmt) -> Promotability { - match stmt.kind { - hir::StmtKind::Local(ref local) => { - if self.remove_mut_rvalue_borrow(&local.pat) { - if let Some(init) = &local.init { - self.mut_rvalue_borrows.insert(init.hir_id); - } - } - - if let Some(ref expr) = local.init { - let _ = self.check_expr(&expr); - } - NotPromotable - } - // Item statements are allowed - hir::StmtKind::Item(..) => Promotable, - hir::StmtKind::Expr(ref box_expr) | - hir::StmtKind::Semi(ref box_expr) => { - let _ = self.check_expr(box_expr); - NotPromotable - } - } - } - - fn check_expr(&mut self, ex: &'tcx hir::Expr) -> Promotability { - let node_ty = self.tables.node_type(ex.hir_id); - let mut outer = check_expr_kind(self, ex, node_ty); - outer &= check_adjustments(self, ex); - - // Handle borrows on (or inside the autorefs of) this expression. - if self.mut_rvalue_borrows.remove(&ex.hir_id) { - outer = NotPromotable - } - - if outer == Promotable { - self.result.insert(ex.hir_id.local_id); - } - outer - } - - fn check_block(&mut self, block: &'tcx hir::Block) -> Promotability { - let mut iter_result = Promotable; - for index in block.stmts.iter() { - iter_result &= self.check_stmt(index); - } - match block.expr { - Some(ref box_expr) => iter_result & self.check_expr(&*box_expr), - None => iter_result, - } - } -} - -/// This function is used to enforce the constraints on -/// const/static items. It walks through the *value* -/// of the item walking down the expression and evaluating -/// every nested expression. If the expression is not part -/// of a const/static item, it is qualified for promotion -/// instead of producing errors. -fn check_expr_kind<'a, 'tcx>( - v: &mut CheckCrateVisitor<'a, 'tcx>, - e: &'tcx hir::Expr, node_ty: Ty<'tcx>) -> Promotability { - - let ty_result = match node_ty.kind { - ty::Adt(def, _) if def.has_dtor(v.tcx) => { - NotPromotable - } - _ => Promotable - }; - - let kind_result = match e.kind { - hir::ExprKind::Box(ref expr) => { - let _ = v.check_expr(&expr); - NotPromotable - } - hir::ExprKind::Unary(op, ref expr) => { - let expr_promotability = v.check_expr(expr); - if v.tables.is_method_call(e) || op == hir::UnDeref { - return NotPromotable; - } - expr_promotability - } - hir::ExprKind::Binary(op, ref lhs, ref rhs) => { - let lefty = v.check_expr(lhs); - let righty = v.check_expr(rhs); - if v.tables.is_method_call(e) { - return NotPromotable; - } - match v.tables.node_type(lhs.hir_id).kind { - ty::RawPtr(_) | ty::FnPtr(..) => { - assert!(op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne || - op.node == hir::BinOpKind::Le || op.node == hir::BinOpKind::Lt || - op.node == hir::BinOpKind::Ge || op.node == hir::BinOpKind::Gt); - - NotPromotable - } - _ => lefty & righty - } - } - hir::ExprKind::Cast(ref from, _) => { - let expr_promotability = v.check_expr(from); - debug!("checking const cast(id={})", from.hir_id); - let cast_in = CastTy::from_ty(v.tables.expr_ty(from)); - let cast_out = CastTy::from_ty(v.tables.expr_ty(e)); - match (cast_in, cast_out) { - (Some(CastTy::FnPtr), Some(CastTy::Int(_))) | - (Some(CastTy::Ptr(_)), Some(CastTy::Int(_))) => NotPromotable, - (_, _) => expr_promotability - } - } - hir::ExprKind::Path(ref qpath) => { - let res = v.tables.qpath_res(qpath, e.hir_id); - match res { - Res::Def(DefKind::Ctor(..), _) - | Res::Def(DefKind::Fn, _) - | Res::Def(DefKind::Method, _) - | Res::SelfCtor(..) => - Promotable, - - // References to a static that are themselves within a static - // are inherently promotable with the exception - // of "#[thread_local]" statics, which may not - // outlive the current function - Res::Def(DefKind::Static, did) => { - - if v.in_static { - for attr in &v.tcx.get_attrs(did)[..] { - if attr.check_name(sym::thread_local) { - debug!("reference to `Static(id={:?})` is unpromotable \ - due to a `#[thread_local]` attribute", did); - return NotPromotable; - } - } - Promotable - } else { - debug!("reference to `Static(id={:?})` is unpromotable as it is not \ - referenced from a static", did); - NotPromotable - } - } - - Res::Def(DefKind::Const, did) | - Res::Def(DefKind::AssocConst, did) => { - let promotable = if v.tcx.trait_of_item(did).is_some() { - // Don't peek inside trait associated constants. - NotPromotable - } else if v.tcx.at(e.span).const_is_rvalue_promotable_to_static(did) { - Promotable - } else { - NotPromotable - }; - // Just in case the type is more specific than the definition, - // e.g., impl associated const with type parameters, check it. - // Also, trait associated consts are relaxed by this. - promotable | v.type_promotability(node_ty) - } - _ => NotPromotable - } - } - hir::ExprKind::Call(ref callee, ref hirvec) => { - let mut call_result = v.check_expr(callee); - for index in hirvec.iter() { - call_result &= v.check_expr(index); - } - let mut callee = &**callee; - loop { - callee = match callee.kind { - hir::ExprKind::Block(ref block, _) => match block.expr { - Some(ref tail) => &tail, - None => break - }, - _ => break - }; - } - // The callee is an arbitrary expression, it doesn't necessarily have a definition. - let def = if let hir::ExprKind::Path(ref qpath) = callee.kind { - v.tables.qpath_res(qpath, callee.hir_id) - } else { - Res::Err - }; - let def_result = match def { - Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | - Res::SelfCtor(..) => Promotable, - Res::Def(DefKind::Fn, did) => v.handle_const_fn_call(did), - Res::Def(DefKind::Method, did) => { - match v.tcx.associated_item(did).container { - ty::ImplContainer(_) => v.handle_const_fn_call(did), - ty::TraitContainer(_) => NotPromotable, - } - } - _ => NotPromotable, - }; - def_result & call_result - } - hir::ExprKind::MethodCall(ref _pathsegment, ref _span, ref hirvec) => { - let mut method_call_result = Promotable; - for index in hirvec.iter() { - method_call_result &= v.check_expr(index); - } - if let Some(def_id) = v.tables.type_dependent_def_id(e.hir_id) { - match v.tcx.associated_item(def_id).container { - ty::ImplContainer(_) => method_call_result & v.handle_const_fn_call(def_id), - ty::TraitContainer(_) => NotPromotable, - } - } else { - v.tcx.sess.delay_span_bug(e.span, "no type-dependent def for method call"); - NotPromotable - } - } - hir::ExprKind::Struct(ref _qpath, ref hirvec, ref option_expr) => { - let mut struct_result = Promotable; - for index in hirvec.iter() { - struct_result &= v.check_expr(&index.expr); - } - if let Some(ref expr) = *option_expr { - struct_result &= v.check_expr(&expr); - } - if let ty::Adt(adt, ..) = v.tables.expr_ty(e).kind { - // unsafe_cell_type doesn't necessarily exist with no_core - if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() { - return NotPromotable; - } - } - struct_result - } - - hir::ExprKind::Lit(_) | - hir::ExprKind::Err => Promotable, - - hir::ExprKind::AddrOf(_, ref expr) | - hir::ExprKind::Repeat(ref expr, _) | - hir::ExprKind::Type(ref expr, _) | - hir::ExprKind::DropTemps(ref expr) => { - v.check_expr(&expr) - } - - hir::ExprKind::Closure(_capture_clause, ref _box_fn_decl, - body_id, _span, _option_generator_movability) => { - let nested_body_promotable = v.check_nested_body(body_id); - // Paths in constant contexts cannot refer to local variables, - // as there are none, and thus closures can't have upvars there. - let closure_def_id = v.tcx.hir().local_def_id(e.hir_id); - if !v.tcx.upvars(closure_def_id).map_or(true, |v| v.is_empty()) { - NotPromotable - } else { - nested_body_promotable - } - } - - hir::ExprKind::Field(ref expr, _ident) => { - let expr_promotability = v.check_expr(&expr); - if let Some(def) = v.tables.expr_ty(expr).ty_adt_def() { - if def.is_union() { - return NotPromotable; - } - } - expr_promotability - } - - hir::ExprKind::Block(ref box_block, ref _option_label) => { - v.check_block(box_block) - } - - hir::ExprKind::Index(ref lhs, ref rhs) => { - let lefty = v.check_expr(lhs); - let righty = v.check_expr(rhs); - if v.tables.is_method_call(e) { - return NotPromotable; - } - lefty & righty - } - - hir::ExprKind::Array(ref hirvec) => { - let mut array_result = Promotable; - for index in hirvec.iter() { - array_result &= v.check_expr(index); - } - array_result - } - - hir::ExprKind::Tup(ref hirvec) => { - let mut tup_result = Promotable; - for index in hirvec.iter() { - tup_result &= v.check_expr(index); - } - tup_result - } - - // Conditional control flow (possible to implement). - hir::ExprKind::Match(ref expr, ref arms, ref _match_source) => { - // Compute the most demanding borrow from all the arms' - // patterns and set that on the discriminator. - if arms.iter().fold(false, |_, arm| v.remove_mut_rvalue_borrow(&arm.pat)) { - v.mut_rvalue_borrows.insert(expr.hir_id); - } - - let _ = v.check_expr(expr); - for index in arms.iter() { - let _ = v.check_expr(&*index.body); - if let Some(hir::Guard::If(ref expr)) = index.guard { - let _ = v.check_expr(&expr); - } - } - NotPromotable - } - - hir::ExprKind::Loop(ref box_block, ref _option_label, ref _loop_source) => { - let _ = v.check_block(box_block); - NotPromotable - } - - // More control flow (also not very meaningful). - hir::ExprKind::Break(_, ref option_expr) | hir::ExprKind::Ret(ref option_expr) => { - if let Some(ref expr) = *option_expr { - let _ = v.check_expr(&expr); - } - NotPromotable - } - - hir::ExprKind::Continue(_) => { - NotPromotable - } - - // Generator expressions - hir::ExprKind::Yield(ref expr, _) => { - let _ = v.check_expr(&expr); - NotPromotable - } - - // Expressions with side-effects. - hir::ExprKind::AssignOp(_, ref lhs, ref rhs) | hir::ExprKind::Assign(ref lhs, ref rhs) => { - let _ = v.check_expr(lhs); - let _ = v.check_expr(rhs); - NotPromotable - } - - hir::ExprKind::InlineAsm(ref _inline_asm, ref hirvec_lhs, ref hirvec_rhs) => { - for index in hirvec_lhs.iter().chain(hirvec_rhs.iter()) { - let _ = v.check_expr(index); - } - NotPromotable - } - }; - ty_result & kind_result -} - -/// Checks the adjustments of an expression. -fn check_adjustments<'a, 'tcx>( - v: &mut CheckCrateVisitor<'a, 'tcx>, - e: &hir::Expr) -> Promotability { - use rustc::ty::adjustment::*; - - let mut adjustments = v.tables.expr_adjustments(e).iter().peekable(); - while let Some(adjustment) = adjustments.next() { - match adjustment.kind { - Adjust::NeverToAny | - Adjust::Pointer(_) | - Adjust::Borrow(_) => {} - - Adjust::Deref(_) => { - if let Some(next_adjustment) = adjustments.peek() { - if let Adjust::Borrow(_) = next_adjustment.kind { - continue; - } - } - return NotPromotable; - } - } - } - Promotable -} - -impl<'a, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'tcx> { - fn consume(&mut self, - _consume_id: hir::HirId, - _consume_span: Span, - _cmt: &mc::cmt_<'_>, - _mode: euv::ConsumeMode) {} - - fn borrow(&mut self, - borrow_id: hir::HirId, - _borrow_span: Span, - cmt: &mc::cmt_<'tcx>, - _loan_region: ty::Region<'tcx>, - bk: ty::BorrowKind, - loan_cause: euv::LoanCause) { - debug!( - "borrow(borrow_id={:?}, cmt={:?}, bk={:?}, loan_cause={:?})", - borrow_id, - cmt, - bk, - loan_cause, - ); - - // Kind of hacky, but we allow Unsafe coercions in constants. - // These occur when we convert a &T or *T to a *U, as well as - // when making a thin pointer (e.g., `*T`) into a fat pointer - // (e.g., `*Trait`). - if let euv::LoanCause::AutoUnsafe = loan_cause { - return; - } - - let mut cur = cmt; - loop { - match cur.cat { - Categorization::ThreadLocal(..) | - Categorization::Rvalue(..) => { - if loan_cause == euv::MatchDiscriminant { - // Ignore the dummy immutable borrow created by EUV. - break; - } - if bk.to_mutbl_lossy() == hir::MutMutable { - self.mut_rvalue_borrows.insert(borrow_id); - } - break; - } - Categorization::StaticItem => { - break; - } - Categorization::Deref(ref cmt, _) | - Categorization::Downcast(ref cmt, _) | - Categorization::Interior(ref cmt, _) => { - cur = cmt; - } - - Categorization::Upvar(..) | - Categorization::Local(..) => break, - } - } - } - - fn decl_without_init(&mut self, _id: hir::HirId, _span: Span) {} - fn mutate(&mut self, - _assignment_id: hir::HirId, - _assignment_span: Span, - _assignee_cmt: &mc::cmt_<'_>, - _mode: euv::MutateMode) { - } - - fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_<'_>, _: euv::MatchMode) {} - - fn consume_pat(&mut self, - _consume_pat: &hir::Pat, - _cmt: &mc::cmt_<'_>, - _mode: euv::ConsumeMode) {} -} diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs index cb03af46f3dbb..d46ac4a39a337 100644 --- a/src/librustc_typeck/check/dropck.rs +++ b/src/librustc_typeck/check/dropck.rs @@ -3,10 +3,10 @@ use crate::check::regionck::RegionCtxt; use crate::hir; use crate::hir::def_id::DefId; use rustc::infer::outlives::env::OutlivesEnvironment; -use rustc::infer::{self, InferOk, SuppressRegionErrors}; +use rustc::infer::{InferOk, SuppressRegionErrors}; use rustc::middle::region; use rustc::traits::{ObligationCause, TraitEngine, TraitEngineExt}; -use rustc::ty::subst::{Subst, SubstsRef, GenericArgKind}; +use rustc::ty::subst::{Subst, SubstsRef}; use rustc::ty::{self, Ty, TyCtxt}; use crate::util::common::ErrorReported; @@ -233,87 +233,21 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( result } -/// This function confirms that the type -/// expression `typ` conforms to the "Drop Check Rule" from the Sound -/// Generic Drop RFC (#769). -/// -/// ---- -/// -/// The simplified (*) Drop Check Rule is the following: -/// -/// Let `v` be some value (either temporary or named) and 'a be some -/// lifetime (scope). If the type of `v` owns data of type `D`, where -/// -/// * (1.) `D` has a lifetime- or type-parametric Drop implementation, -/// (where that `Drop` implementation does not opt-out of -/// this check via the `may_dangle` -/// attribute), and -/// * (2.) the structure of `D` can reach a reference of type `&'a _`, -/// -/// then 'a must strictly outlive the scope of v. -/// -/// ---- -/// -/// This function is meant to by applied to the type for every -/// expression in the program. -/// -/// ---- -/// -/// (*) The qualifier "simplified" is attached to the above -/// definition of the Drop Check Rule, because it is a simplification -/// of the original Drop Check rule, which attempted to prove that -/// some `Drop` implementations could not possibly access data even if -/// it was technically reachable, due to parametricity. -/// -/// However, (1.) parametricity on its own turned out to be a -/// necessary but insufficient condition, and (2.) future changes to -/// the language are expected to make it impossible to ensure that a -/// `Drop` implementation is actually parametric with respect to any -/// particular type parameter. (In particular, impl specialization is -/// expected to break the needed parametricity property beyond -/// repair.) -/// -/// Therefore, we have scaled back Drop-Check to a more conservative -/// rule that does not attempt to deduce whether a `Drop` -/// implementation could not possible access data of a given lifetime; -/// instead Drop-Check now simply assumes that if a destructor has -/// access (direct or indirect) to a lifetime parameter, then that -/// lifetime must be forced to outlive that destructor's dynamic -/// extent. We then provide the `may_dangle` -/// attribute as a way for destructor implementations to opt-out of -/// this conservative assumption (and thus assume the obligation of -/// ensuring that they do not access data nor invoke methods of -/// values that have been previously dropped). -pub fn check_safety_of_destructor_if_necessary<'a, 'tcx>( +/// This function is not only checking that the dropck obligations are met for +/// the given type, but it's also currently preventing non-regular recursion in +/// types from causing stack overflows (dropck_no_diverge_on_nonregular_*.rs). +crate fn check_drop_obligations<'a, 'tcx>( rcx: &mut RegionCtxt<'a, 'tcx>, ty: Ty<'tcx>, span: Span, body_id: hir::HirId, - scope: region::Scope, ) -> Result<(), ErrorReported> { - debug!("check_safety_of_destructor_if_necessary typ: {:?} scope: {:?}", - ty, scope); + debug!("check_drop_obligations typ: {:?}", ty); - let parent_scope = match rcx.region_scope_tree.opt_encl_scope(scope) { - Some(parent_scope) => parent_scope, - // If no enclosing scope, then it must be the root scope - // which cannot be outlived. - None => return Ok(()), - }; - let parent_scope = rcx.tcx.mk_region(ty::ReScope(parent_scope)); - let origin = || infer::SubregionOrigin::SafeDestructor(span); let cause = &ObligationCause::misc(span, body_id); let infer_ok = rcx.infcx.at(cause, rcx.fcx.param_env).dropck_outlives(ty); debug!("dropck_outlives = {:#?}", infer_ok); - let kinds = rcx.fcx.register_infer_ok_obligations(infer_ok); - for kind in kinds { - match kind.unpack() { - GenericArgKind::Lifetime(r) => rcx.sub_regions(origin(), parent_scope, r), - GenericArgKind::Type(ty) => rcx.type_must_outlive(origin(), ty, parent_scope), - GenericArgKind::Const(_) => { - // Generic consts don't add constraints. - } - } - } + rcx.fcx.register_infer_ok_obligations(infer_ok); + Ok(()) } diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index 90407780a302d..2f9091282b707 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -347,13 +347,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { ); self.outlives_environment .save_implied_bounds(body_id.hir_id); - self.link_fn_params( - region::Scope { - id: body.value.hir_id.local_id, - data: region::ScopeData::Node, - }, - &body.params, - ); + self.link_fn_params(&body.params); self.visit_body(body); self.visit_region_obligations(body_id.hir_id); @@ -430,8 +424,8 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { let typ = self.resolve_node_type(hir_id); let body_id = self.body_id; - let _ = dropck::check_safety_of_destructor_if_necessary( - self, typ, span, body_id, var_scope, + let _ = dropck::check_drop_obligations( + self, typ, span, body_id, ); }) } @@ -928,29 +922,15 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { } fn check_safety_of_rvalue_destructor_if_necessary(&mut self, cmt: &mc::cmt_<'tcx>, span: Span) { - if let Categorization::Rvalue(region) = cmt.cat { - match *region { - ty::ReScope(rvalue_scope) => { - let typ = self.resolve_type(cmt.ty); - let body_id = self.body_id; - let _ = dropck::check_safety_of_destructor_if_necessary( - self, - typ, - span, - body_id, - rvalue_scope, - ); - } - ty::ReStatic => {} - _ => { - span_bug!( - span, - "unexpected rvalue region in rvalue \ - destructor safety checking: `{:?}`", - region - ); - } - } + if let Categorization::Rvalue = cmt.cat { + let typ = self.resolve_type(cmt.ty); + let body_id = self.body_id; + let _ = dropck::check_drop_obligations( + self, + typ, + span, + body_id, + ); } } @@ -1074,13 +1054,11 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { /// Computes the guarantors for any ref bindings in a match and /// then ensures that the lifetime of the resulting pointer is /// linked to the lifetime of its guarantor (if any). - fn link_fn_params(&self, body_scope: region::Scope, params: &[hir::Param]) { - debug!("regionck::link_fn_params(body_scope={:?})", body_scope); + fn link_fn_params(&self, params: &[hir::Param]) { for param in params { let param_ty = self.node_ty(param.hir_id); - let re_scope = self.tcx.mk_region(ty::ReScope(body_scope)); let param_cmt = self.with_mc(|mc| { - Rc::new(mc.cat_rvalue(param.hir_id, param.pat.span, re_scope, param_ty)) + Rc::new(mc.cat_rvalue(param.hir_id, param.pat.span, param_ty)) }); debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param); self.link_pattern(param_cmt, ¶m.pat); @@ -1222,8 +1200,8 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { | Categorization::StaticItem | Categorization::Upvar(..) | Categorization::Local(..) - | Categorization::ThreadLocal(..) - | Categorization::Rvalue(..) => { + | Categorization::ThreadLocal + | Categorization::Rvalue => { // These are all "base cases" with independent lifetimes // that are not subject to inference return; diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 71ea938a8039b..4156e8ae12afa 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -408,8 +408,8 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { Categorization::Deref(_, mc::UnsafePtr(..)) | Categorization::StaticItem - | Categorization::ThreadLocal(..) - | Categorization::Rvalue(..) + | Categorization::ThreadLocal + | Categorization::Rvalue | Categorization::Local(_) | Categorization::Upvar(..) => { return; @@ -439,8 +439,8 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { Categorization::Deref(_, mc::UnsafePtr(..)) | Categorization::StaticItem - | Categorization::ThreadLocal(..) - | Categorization::Rvalue(..) + | Categorization::ThreadLocal + | Categorization::Rvalue | Categorization::Local(_) | Categorization::Upvar(..) => {} } diff --git a/src/test/ui/issues/issue-17252.stderr b/src/test/ui/issues/issue-17252.stderr index da3e2e763af58..8fd67b19d6a5a 100644 --- a/src/test/ui/issues/issue-17252.stderr +++ b/src/test/ui/issues/issue-17252.stderr @@ -1,11 +1,11 @@ -error[E0391]: cycle detected when processing `FOO` +error[E0391]: cycle detected when const checking `FOO` --> $DIR/issue-17252.rs:1:20 | LL | const FOO: usize = FOO; | ^^^ | - = note: ...which again requires processing `FOO`, completing the cycle -note: cycle used when processing `main::{{constant}}#0` + = note: ...which again requires const checking `FOO`, completing the cycle +note: cycle used when const checking `main::{{constant}}#0` --> $DIR/issue-17252.rs:4:18 | LL | let _x: [u8; FOO]; // caused stack overflow prior to fix diff --git a/src/test/ui/issues/issue-23302-1.stderr b/src/test/ui/issues/issue-23302-1.stderr index bbdb13a95007b..f2457774326dd 100644 --- a/src/test/ui/issues/issue-23302-1.stderr +++ b/src/test/ui/issues/issue-23302-1.stderr @@ -1,10 +1,10 @@ -error[E0391]: cycle detected when processing `X::A::{{constant}}#0` +error[E0391]: cycle detected when const checking `X::A::{{constant}}#0` --> $DIR/issue-23302-1.rs:4:9 | LL | A = X::A as isize, | ^^^^^^^^^^^^^ | - = note: ...which again requires processing `X::A::{{constant}}#0`, completing the cycle + = note: ...which again requires const checking `X::A::{{constant}}#0`, completing the cycle note: cycle used when processing `X::A::{{constant}}#0` --> $DIR/issue-23302-1.rs:4:9 | diff --git a/src/test/ui/issues/issue-23302-2.stderr b/src/test/ui/issues/issue-23302-2.stderr index 03afd82211a7e..c121c17b904ea 100644 --- a/src/test/ui/issues/issue-23302-2.stderr +++ b/src/test/ui/issues/issue-23302-2.stderr @@ -1,10 +1,10 @@ -error[E0391]: cycle detected when processing `Y::A::{{constant}}#0` +error[E0391]: cycle detected when const checking `Y::A::{{constant}}#0` --> $DIR/issue-23302-2.rs:4:9 | LL | A = Y::B as isize, | ^^^^^^^^^^^^^ | - = note: ...which again requires processing `Y::A::{{constant}}#0`, completing the cycle + = note: ...which again requires const checking `Y::A::{{constant}}#0`, completing the cycle note: cycle used when processing `Y::A::{{constant}}#0` --> $DIR/issue-23302-2.rs:4:9 | diff --git a/src/test/ui/issues/issue-23302-3.stderr b/src/test/ui/issues/issue-23302-3.stderr index a7d643987f710..0229469f04140 100644 --- a/src/test/ui/issues/issue-23302-3.stderr +++ b/src/test/ui/issues/issue-23302-3.stderr @@ -1,26 +1,20 @@ -error[E0391]: cycle detected when const checking if rvalue is promotable to static `A` - --> $DIR/issue-23302-3.rs:1:1 - | -LL | const A: i32 = B; - | ^^^^^^^^^^^^^^^^^ - | -note: ...which requires checking which parts of `A` are promotable to static... +error[E0391]: cycle detected when const checking `A` --> $DIR/issue-23302-3.rs:1:16 | LL | const A: i32 = B; | ^ -note: ...which requires const checking if rvalue is promotable to static `B`... - --> $DIR/issue-23302-3.rs:3:1 | -LL | const B: i32 = A; - | ^^^^^^^^^^^^^^^^^ -note: ...which requires checking which parts of `B` are promotable to static... +note: ...which requires const checking `B`... --> $DIR/issue-23302-3.rs:3:16 | LL | const B: i32 = A; | ^ - = note: ...which again requires const checking if rvalue is promotable to static `A`, completing the cycle - = note: cycle used when running analysis passes on this crate + = note: ...which again requires const checking `A`, completing the cycle +note: cycle used when processing `A` + --> $DIR/issue-23302-3.rs:1:1 + | +LL | const A: i32 = B; + | ^^^^^^^^^^^^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-36163.stderr b/src/test/ui/issues/issue-36163.stderr index 50e8cf6e88c58..3866243914b89 100644 --- a/src/test/ui/issues/issue-36163.stderr +++ b/src/test/ui/issues/issue-36163.stderr @@ -1,15 +1,15 @@ -error[E0391]: cycle detected when processing `Foo::B::{{constant}}#0` +error[E0391]: cycle detected when const checking `Foo::B::{{constant}}#0` --> $DIR/issue-36163.rs:4:9 | LL | B = A, | ^ | -note: ...which requires processing `A`... +note: ...which requires const checking `A`... --> $DIR/issue-36163.rs:1:18 | LL | const A: isize = Foo::B as isize; | ^^^^^^^^^^^^^^^ - = note: ...which again requires processing `Foo::B::{{constant}}#0`, completing the cycle + = note: ...which again requires const checking `Foo::B::{{constant}}#0`, completing the cycle note: cycle used when processing `Foo::B::{{constant}}#0` --> $DIR/issue-36163.rs:4:9 | From b4ad612697b7dccbf83562010fcfaa36023324cd Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Sat, 28 Sep 2019 16:12:33 +0100 Subject: [PATCH 2/2] Remove unused parts of ExprUseVisitor --- src/librustc/middle/expr_use_visitor.rs | 458 ++++-------------------- src/librustc_typeck/check/upvar.rs | 53 +-- 2 files changed, 83 insertions(+), 428 deletions(-) diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index d8b84fd473744..bb7ac5d8dbe1a 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -2,20 +2,16 @@ //! normal visitor, which just walks the entire body in one shot, the //! `ExprUseVisitor` determines how expressions are being used. -pub use self::LoanCause::*; pub use self::ConsumeMode::*; -pub use self::MoveReason::*; -pub use self::MatchMode::*; -use self::TrackMatchMode::*; use self::OverloadedCallType::*; -use crate::hir::def::{CtorOf, Res, DefKind}; +use crate::hir::def::Res; use crate::hir::def_id::DefId; use crate::hir::ptr::P; use crate::infer::InferCtxt; use crate::middle::mem_categorization as mc; use crate::middle::region; -use crate::ty::{self, DefIdTree, TyCtxt, adjustment}; +use crate::ty::{self, TyCtxt, adjustment}; use crate::hir::{self, PatKind}; use std::rc::Rc; @@ -29,161 +25,19 @@ use syntax_pos::Span; pub trait Delegate<'tcx> { // The value found at `cmt` is either copied or moved, depending // on mode. - fn consume(&mut self, - consume_id: hir::HirId, - consume_span: Span, - cmt: &mc::cmt_<'tcx>, - mode: ConsumeMode); - - // The value found at `cmt` has been determined to match the - // pattern binding `matched_pat`, and its subparts are being - // copied or moved depending on `mode`. Note that `matched_pat` - // is called on all variant/structs in the pattern (i.e., the - // interior nodes of the pattern's tree structure) while - // consume_pat is called on the binding identifiers in the pattern - // (which are leaves of the pattern's tree structure). - // - // Note that variants/structs and identifiers are disjoint; thus - // `matched_pat` and `consume_pat` are never both called on the - // same input pattern structure (though of `consume_pat` can be - // called on a subpart of an input passed to `matched_pat). - fn matched_pat(&mut self, - matched_pat: &hir::Pat, - cmt: &mc::cmt_<'tcx>, - mode: MatchMode); - - // The value found at `cmt` is either copied or moved via the - // pattern binding `consume_pat`, depending on mode. - fn consume_pat(&mut self, - consume_pat: &hir::Pat, - cmt: &mc::cmt_<'tcx>, - mode: ConsumeMode); - - // The value found at `borrow` is being borrowed at the point - // `borrow_id` for the region `loan_region` with kind `bk`. - fn borrow(&mut self, - borrow_id: hir::HirId, - borrow_span: Span, - cmt: &mc::cmt_<'tcx>, - loan_region: ty::Region<'tcx>, - bk: ty::BorrowKind, - loan_cause: LoanCause); - - // The local variable `id` is declared but not initialized. - fn decl_without_init(&mut self, - id: hir::HirId, - span: Span); + fn consume(&mut self, cmt: &mc::cmt_<'tcx>, mode: ConsumeMode); - // The path at `cmt` is being assigned to. - fn mutate(&mut self, - assignment_id: hir::HirId, - assignment_span: Span, - assignee_cmt: &mc::cmt_<'tcx>, - mode: MutateMode); - - // A nested closure or generator - only one layer deep. - fn nested_body(&mut self, _body_id: hir::BodyId) {} -} + // The value found at `cmt` is being borrowed with kind `bk`. + fn borrow(&mut self, cmt: &mc::cmt_<'tcx>, bk: ty::BorrowKind); -#[derive(Copy, Clone, PartialEq, Debug)] -pub enum LoanCause { - ClosureCapture(Span), - AddrOf, - AutoRef, - AutoUnsafe, - RefBinding, - OverloadedOperator, - ClosureInvocation, - ForLoop, - MatchDiscriminant + // The path at `cmt` is being assigned to. + fn mutate(&mut self, assignee_cmt: &mc::cmt_<'tcx>); } #[derive(Copy, Clone, PartialEq, Debug)] pub enum ConsumeMode { Copy, // reference to x where x has a type that copies - Move(MoveReason), // reference to x where x has a type that moves -} - -#[derive(Copy, Clone, PartialEq, Debug)] -pub enum MoveReason { - DirectRefMove, - PatBindingMove, - CaptureMove, -} - -#[derive(Copy, Clone, PartialEq, Debug)] -pub enum MatchMode { - NonBindingMatch, - BorrowingMatch, - CopyingMatch, - MovingMatch, -} - -#[derive(Copy, Clone, PartialEq, Debug)] -enum TrackMatchMode { - Unknown, - Definite(MatchMode), - Conflicting, -} - -impl TrackMatchMode { - // Builds up the whole match mode for a pattern from its constituent - // parts. The lattice looks like this: - // - // Conflicting - // / \ - // / \ - // Borrowing Moving - // \ / - // \ / - // Copying - // | - // NonBinding - // | - // Unknown - // - // examples: - // - // * `(_, some_int)` pattern is Copying, since - // NonBinding + Copying => Copying - // - // * `(some_int, some_box)` pattern is Moving, since - // Copying + Moving => Moving - // - // * `(ref x, some_box)` pattern is Conflicting, since - // Borrowing + Moving => Conflicting - // - // Note that the `Unknown` and `Conflicting` states are - // represented separately from the other more interesting - // `Definite` states, which simplifies logic here somewhat. - fn lub(&mut self, mode: MatchMode) { - *self = match (*self, mode) { - // Note that clause order below is very significant. - (Unknown, new) => Definite(new), - (Definite(old), new) if old == new => Definite(old), - - (Definite(old), NonBindingMatch) => Definite(old), - (Definite(NonBindingMatch), new) => Definite(new), - - (Definite(old), CopyingMatch) => Definite(old), - (Definite(CopyingMatch), new) => Definite(new), - - (Definite(_), _) => Conflicting, - (Conflicting, _) => *self, - }; - } - - fn match_mode(&self) -> MatchMode { - match *self { - Unknown => NonBindingMatch, - Definite(mode) => mode, - Conflicting => { - // Conservatively return MovingMatch to let the - // compiler continue to make progress. - MovingMatch - } - } - } + Move, // reference to x where x has a type that moves } #[derive(Copy, Clone, PartialEq, Debug)] @@ -326,15 +180,11 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.mc.tcx } - fn delegate_consume(&mut self, - consume_id: hir::HirId, - consume_span: Span, - cmt: &mc::cmt_<'tcx>) { - debug!("delegate_consume(consume_id={}, cmt={:?})", - consume_id, cmt); + fn delegate_consume(&mut self, cmt: &mc::cmt_<'tcx>) { + debug!("delegate_consume(cmt={:?})", cmt); - let mode = copy_or_move(&self.mc, self.param_env, cmt, DirectRefMove); - self.delegate.consume(consume_id, consume_span, cmt, mode); + let mode = copy_or_move(&self.mc, self.param_env, cmt); + self.delegate.consume(cmt, mode); } fn consume_exprs(&mut self, exprs: &[hir::Expr]) { @@ -347,30 +197,21 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { debug!("consume_expr(expr={:?})", expr); let cmt = return_if_err!(self.mc.cat_expr(expr)); - self.delegate_consume(expr.hir_id, expr.span, &cmt); + self.delegate_consume(&cmt); self.walk_expr(expr); } - fn mutate_expr(&mut self, - span: Span, - assignment_expr: &hir::Expr, - expr: &hir::Expr, - mode: MutateMode) { + fn mutate_expr(&mut self, expr: &hir::Expr) { let cmt = return_if_err!(self.mc.cat_expr(expr)); - self.delegate.mutate(assignment_expr.hir_id, span, &cmt, mode); + self.delegate.mutate(&cmt); self.walk_expr(expr); } - fn borrow_expr(&mut self, - expr: &hir::Expr, - r: ty::Region<'tcx>, - bk: ty::BorrowKind, - cause: LoanCause) { - debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})", - expr, r, bk); + fn borrow_expr(&mut self, expr: &hir::Expr, bk: ty::BorrowKind) { + debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk); let cmt = return_if_err!(self.mc.cat_expr(expr)); - self.delegate.borrow(expr.hir_id, expr.span, &cmt, r, bk, cause); + self.delegate.borrow(&cmt, bk); self.walk_expr(expr) } @@ -388,24 +229,24 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { hir::ExprKind::Path(_) => { } hir::ExprKind::Type(ref subexpr, _) => { - self.walk_expr(&subexpr) + self.walk_expr(subexpr) } 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 - self.select_from_expr(&base); + self.select_from_expr(base); } hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs] - self.select_from_expr(&lhs); - self.consume_expr(&rhs); + self.select_from_expr(lhs); + self.consume_expr(rhs); } hir::ExprKind::Call(ref callee, ref args) => { // callee(args) - self.walk_callee(expr, &callee); + self.walk_callee(expr, callee); self.consume_exprs(args); } @@ -423,14 +264,11 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { hir::ExprKind::Match(ref discr, ref arms, _) => { let discr_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&discr))); - let r = self.tcx().lifetimes.re_empty; - self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant); + self.borrow_expr(&discr, ty::ImmBorrow); // treatment of the discriminant is handled while walking the arms. for arm in arms { - let mode = self.arm_move_mode(discr_cmt.clone(), arm); - let mode = mode.match_mode(); - self.walk_arm(discr_cmt.clone(), arm, mode); + self.walk_arm(discr_cmt.clone(), arm); } } @@ -441,11 +279,8 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { hir::ExprKind::AddrOf(m, ref base) => { // &base // make sure that the thing we are pointing out stays valid // for the lifetime `scope_r` of the resulting ptr: - let expr_ty = return_if_err!(self.mc.expr_ty(expr)); - if let ty::Ref(r, _, _) = expr_ty.kind { - let bk = ty::BorrowKind::from_mutbl(m); - self.borrow_expr(&base, r, bk, AddrOf); - } + let bk = ty::BorrowKind::from_mutbl(m); + self.borrow_expr(&base, bk); } hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => { @@ -453,16 +288,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { if o.is_indirect { self.consume_expr(output); } else { - self.mutate_expr( - output.span, - expr, - output, - if o.is_rw { - MutateMode::WriteAndRead - } else { - MutateMode::JustWrite - }, - ); + self.mutate_expr(output); } } self.consume_exprs(inputs); @@ -473,65 +299,64 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { hir::ExprKind::Err => {} hir::ExprKind::Loop(ref blk, _, _) => { - self.walk_block(&blk); + self.walk_block(blk); } hir::ExprKind::Unary(_, ref lhs) => { - self.consume_expr(&lhs); + self.consume_expr(lhs); } hir::ExprKind::Binary(_, ref lhs, ref rhs) => { - self.consume_expr(&lhs); - self.consume_expr(&rhs); + self.consume_expr(lhs); + self.consume_expr(rhs); } hir::ExprKind::Block(ref blk, _) => { - self.walk_block(&blk); + self.walk_block(blk); } hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => { if let Some(ref expr) = *opt_expr { - self.consume_expr(&expr); + self.consume_expr(expr); } } hir::ExprKind::Assign(ref lhs, ref rhs) => { - self.mutate_expr(expr.span, expr, &lhs, MutateMode::JustWrite); - self.consume_expr(&rhs); + self.mutate_expr(lhs); + self.consume_expr(rhs); } hir::ExprKind::Cast(ref base, _) => { - self.consume_expr(&base); + self.consume_expr(base); } hir::ExprKind::DropTemps(ref expr) => { - self.consume_expr(&expr); + self.consume_expr(expr); } hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => { if self.mc.tables.is_method_call(expr) { self.consume_expr(lhs); } else { - self.mutate_expr(expr.span, expr, &lhs, MutateMode::WriteAndRead); + self.mutate_expr(lhs); } - self.consume_expr(&rhs); + self.consume_expr(rhs); } hir::ExprKind::Repeat(ref base, _) => { - self.consume_expr(&base); + self.consume_expr(base); } - hir::ExprKind::Closure(_, _, body_id, fn_decl_span, _) => { - self.delegate.nested_body(body_id); + hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => { self.walk_captures(expr, fn_decl_span); } hir::ExprKind::Box(ref base) => { - self.consume_expr(&base); + self.consume_expr(base); } hir::ExprKind::Yield(ref value, _) => { - self.consume_expr(&value); + self.consume_expr(value); } } } @@ -547,24 +372,12 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { ty::Error => { } _ => { if let Some(def_id) = self.mc.tables.type_dependent_def_id(call.hir_id) { - let call_scope = region::Scope { - id: call.hir_id.local_id, - data: region::ScopeData::Node - }; match OverloadedCallType::from_method_id(self.tcx(), def_id) { FnMutOverloadedCall => { - let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope)); - self.borrow_expr(callee, - call_scope_r, - ty::MutBorrow, - ClosureInvocation); + self.borrow_expr(callee, ty::MutBorrow); } FnOverloadedCall => { - let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope)); - self.borrow_expr(callee, - call_scope_r, - ty::ImmBorrow, - ClosureInvocation); + self.borrow_expr(callee, ty::ImmBorrow); } FnOnceOverloadedCall => self.consume_expr(callee), } @@ -595,22 +408,14 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } fn walk_local(&mut self, local: &hir::Local) { - match local.init { - None => { - local.pat.each_binding(|_, hir_id, span, _| { - self.delegate.decl_without_init(hir_id, span); - }) - } - - Some(ref expr) => { - // Variable declarations with - // initializers are considered - // "assigns", which is handled by - // `walk_pat`: - self.walk_expr(&expr); - let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr))); - self.walk_irrefutable_pat(init_cmt, &local.pat); - } + if let Some(ref expr) = local.init { + // Variable declarations with + // initializers are considered + // "assigns", which is handled by + // `walk_pat`: + self.walk_expr(&expr); + let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr))); + self.walk_irrefutable_pat(init_cmt, &local.pat); } } @@ -660,7 +465,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { with_field.ident, with_field.ty(self.tcx(), substs) ); - self.delegate_consume(with_expr.hir_id, with_expr.span, &cmt_field); + self.delegate_consume(&cmt_field); } } } @@ -695,7 +500,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { adjustment::Adjust::Pointer(_) => { // Creating a closure/fn-pointer or unsizing consumes // the input and stores it into the resulting rvalue. - self.delegate_consume(expr.hir_id, expr.span, &cmt); + self.delegate_consume(&cmt); } adjustment::Adjust::Deref(None) => {} @@ -707,7 +512,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // this is an autoref of `x`. adjustment::Adjust::Deref(Some(ref deref)) => { let bk = ty::BorrowKind::from_mutbl(deref.mutbl); - self.delegate.borrow(expr.hir_id, expr.span, &cmt, deref.region, bk, AutoRef); + self.delegate.borrow(&cmt, bk); } adjustment::Adjust::Borrow(ref autoref) => { @@ -731,13 +536,8 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { autoref); match *autoref { - adjustment::AutoBorrow::Ref(r, m) => { - self.delegate.borrow(expr.hir_id, - expr.span, - cmt_base, - r, - ty::BorrowKind::from_mutbl(m.into()), - AutoRef); + adjustment::AutoBorrow::Ref(_, m) => { + self.delegate.borrow(cmt_base, ty::BorrowKind::from_mutbl(m.into())); } adjustment::AutoBorrow::RawPtr(m) => { @@ -745,33 +545,14 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { expr.hir_id, cmt_base); - // Converting from a &T to *T (or &mut T to *mut T) is - // treated as borrowing it for the enclosing temporary - // scope. - let r = self.tcx().mk_region(ty::ReScope( - region::Scope { - id: expr.hir_id.local_id, - data: region::ScopeData::Node - })); - - self.delegate.borrow(expr.hir_id, - expr.span, - cmt_base, - r, - ty::BorrowKind::from_mutbl(m), - AutoUnsafe); + + self.delegate.borrow(cmt_base, ty::BorrowKind::from_mutbl(m)); } } } - fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode { - let mut mode = Unknown; - self.determine_pat_move_mode(discr_cmt.clone(), &arm.pat, &mut mode); - mode - } - - fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) { - self.walk_pat(discr_cmt.clone(), &arm.pat, mode); + fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) { + self.walk_pat(discr_cmt.clone(), &arm.pat); if let Some(hir::Guard::If(ref e)) = arm.guard { self.consume_expr(e) @@ -783,44 +564,12 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or /// let binding, and *not* a match arm or nested pat.) fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) { - let mut mode = Unknown; - self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode); - let mode = mode.match_mode(); - self.walk_pat(cmt_discr, pat, mode); + self.walk_pat(cmt_discr, pat); } - /// Identifies any bindings within `pat` and accumulates within - /// `mode` whether the overall pattern/match structure is a move, - /// copy, or borrow. - fn determine_pat_move_mode(&mut self, - cmt_discr: mc::cmt<'tcx>, - pat: &hir::Pat, - mode: &mut TrackMatchMode) { - debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, pat); - - return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| { - if let PatKind::Binding(..) = pat.kind { - let bm = *self.mc.tables.pat_binding_modes() - .get(pat.hir_id) - .expect("missing binding mode"); - match bm { - ty::BindByReference(..) => - mode.lub(BorrowingMatch), - ty::BindByValue(..) => { - match copy_or_move(&self.mc, self.param_env, &cmt_pat, PatBindingMove) { - Copy => mode.lub(CopyingMatch), - Move(..) => mode.lub(MovingMatch), - } - } - } - } - })); - } - /// The core driver for walking a pattern; `match_mode` must be - /// established up front, e.g., via `determine_pat_move_mode` (see - /// also `walk_irrefutable_pat` for patterns that stand alone). - fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) { + /// The core driver for walking a pattern + fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) { debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat); let tcx = self.tcx(); @@ -828,10 +577,9 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| { if let PatKind::Binding(_, canonical_id, ..) = pat.kind { debug!( - "walk_pat: binding cmt_pat={:?} pat={:?} match_mode={:?}", + "walk_pat: binding cmt_pat={:?} pat={:?}", cmt_pat, pat, - match_mode, ); if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) { debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm); @@ -844,21 +592,19 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // binding being produced. let def = Res::Local(canonical_id); if let Ok(ref binding_cmt) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) { - delegate.mutate(pat.hir_id, pat.span, binding_cmt, MutateMode::Init); + delegate.mutate(binding_cmt); } // It is also a borrow or copy/move of the value being matched. match bm { ty::BindByReference(m) => { - if let ty::Ref(r, _, _) = pat_ty.kind { - let bk = ty::BorrowKind::from_mutbl(m); - delegate.borrow(pat.hir_id, pat.span, &cmt_pat, r, bk, RefBinding); - } + let bk = ty::BorrowKind::from_mutbl(m); + delegate.borrow(&cmt_pat, bk); } ty::BindByValue(..) => { - let mode = copy_or_move(mc, param_env, &cmt_pat, PatBindingMove); + let mode = copy_or_move(mc, param_env, &cmt_pat); debug!("walk_pat binding consuming pat"); - delegate.consume_pat(pat, &cmt_pat, mode); + delegate.consume(&cmt_pat, mode); } } } else { @@ -866,45 +612,6 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } } })); - - // Do a second pass over the pattern, calling `matched_pat` on - // the interior nodes (enum variants and structs), as opposed - // to the above loop's visit of than the bindings that form - // the leaves of the pattern tree structure. - return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| { - let qpath = match pat.kind { - PatKind::Path(ref qpath) | - PatKind::TupleStruct(ref qpath, ..) | - PatKind::Struct(ref qpath, ..) => qpath, - _ => return - }; - let res = mc.tables.qpath_res(qpath, pat.hir_id); - match res { - Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => { - let variant_did = mc.tcx.parent(variant_ctor_did).unwrap(); - let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did); - - debug!("variantctor downcast_cmt={:?} pat={:?}", downcast_cmt, pat); - delegate.matched_pat(pat, &downcast_cmt, match_mode); - } - Res::Def(DefKind::Variant, variant_did) => { - let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did); - - debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat); - delegate.matched_pat(pat, &downcast_cmt, match_mode); - } - Res::Def(DefKind::Struct, _) - | Res::Def(DefKind::Ctor(..), _) - | Res::Def(DefKind::Union, _) - | Res::Def(DefKind::TyAlias, _) - | Res::Def(DefKind::AssocTy, _) - | Res::SelfTy(..) => { - debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat); - delegate.matched_pat(pat, &cmt_pat, match_mode); - } - _ => {} - } - })); } fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) { @@ -912,7 +619,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id); if let Some(upvars) = self.tcx().upvars(closure_def_id) { - for (&var_id, upvar) in upvars.iter() { + for &var_id in upvars.keys() { let upvar_id = ty::UpvarId { var_path: ty::UpvarPath { hir_id: var_id }, closure_expr_id: closure_def_id.to_local(), @@ -923,19 +630,11 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { var_id)); match upvar_capture { ty::UpvarCapture::ByValue => { - let mode = copy_or_move(&self.mc, - self.param_env, - &cmt_var, - CaptureMove); - self.delegate.consume(closure_expr.hir_id, upvar.span, &cmt_var, mode); + let mode = copy_or_move(&self.mc, self.param_env, &cmt_var); + self.delegate.consume(&cmt_var, mode); } ty::UpvarCapture::ByRef(upvar_borrow) => { - self.delegate.borrow(closure_expr.hir_id, - fn_decl_span, - &cmt_var, - upvar_borrow.region, - upvar_borrow.kind, - ClosureCapture(upvar.span)); + self.delegate.borrow(&cmt_var, upvar_borrow.kind); } } } @@ -958,10 +657,9 @@ fn copy_or_move<'a, 'tcx>( mc: &mc::MemCategorizationContext<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, cmt: &mc::cmt_<'tcx>, - move_reason: MoveReason, ) -> ConsumeMode { if !mc.type_is_copy_modulo_regions(param_env, cmt.ty, cmt.span) { - Move(move_reason) + Move } else { Copy } diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 4156e8ae12afa..c0fdd743286dd 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -321,7 +321,7 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { euv::Copy => { return; } - euv::Move(_) => {} + euv::Move => {} } let tcx = self.fcx.tcx; @@ -582,48 +582,13 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { } impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> { - fn consume( - &mut self, - _consume_id: hir::HirId, - _consume_span: Span, - cmt: &mc::cmt_<'tcx>, - mode: euv::ConsumeMode, - ) { + fn consume(&mut self, cmt: &mc::cmt_<'tcx>,mode: euv::ConsumeMode) { debug!("consume(cmt={:?},mode={:?})", cmt, mode); self.adjust_upvar_borrow_kind_for_consume(cmt, mode); } - fn matched_pat( - &mut self, - _matched_pat: &hir::Pat, - _cmt: &mc::cmt_<'tcx>, - _mode: euv::MatchMode, - ) { - } - - fn consume_pat( - &mut self, - _consume_pat: &hir::Pat, - cmt: &mc::cmt_<'tcx>, - mode: euv::ConsumeMode, - ) { - debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode); - self.adjust_upvar_borrow_kind_for_consume(cmt, mode); - } - - fn borrow( - &mut self, - borrow_id: hir::HirId, - _borrow_span: Span, - cmt: &mc::cmt_<'tcx>, - _loan_region: ty::Region<'tcx>, - bk: ty::BorrowKind, - _loan_cause: euv::LoanCause, - ) { - debug!( - "borrow(borrow_id={}, cmt={:?}, bk={:?})", - borrow_id, cmt, bk - ); + fn borrow(&mut self, cmt: &mc::cmt_<'tcx>, bk: ty::BorrowKind) { + debug!("borrow(cmt={:?}, bk={:?})", cmt, bk); match bk { ty::ImmBorrow => {} @@ -636,15 +601,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> { } } - fn decl_without_init(&mut self, _id: hir::HirId, _span: Span) {} - - fn mutate( - &mut self, - _assignment_id: hir::HirId, - _assignment_span: Span, - assignee_cmt: &mc::cmt_<'tcx>, - _mode: euv::MutateMode, - ) { + fn mutate(&mut self, assignee_cmt: &mc::cmt_<'tcx>) { debug!("mutate(assignee_cmt={:?})", assignee_cmt); self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);