From 8ab82c147af31c1346c6e78c95722ce8bf27501b Mon Sep 17 00:00:00 2001 From: csmoe Date: Thu, 26 Sep 2019 22:23:13 +0800 Subject: [PATCH 01/17] introduce from_ref helper for replacement --- .../infer/error_reporting/need_type_info.rs | 2 +- src/librustc/infer/opaque_types/mod.rs | 4 +- src/librustc/middle/mem_categorization.rs | 2 +- src/librustc/traits/select.rs | 7 +- src/librustc/ty/sty.rs | 17 +++-- src/librustc/ty/subst.rs | 67 +++++++++++++++++++ 6 files changed, 86 insertions(+), 13 deletions(-) diff --git a/src/librustc/infer/error_reporting/need_type_info.rs b/src/librustc/infer/error_reporting/need_type_info.rs index 1df60dfc63ef3..3e4dfccf34dd5 100644 --- a/src/librustc/infer/error_reporting/need_type_info.rs +++ b/src/librustc/infer/error_reporting/need_type_info.rs @@ -220,7 +220,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let ty_msg = match local_visitor.found_ty { Some(ty::TyS { kind: ty::Closure(def_id, substs), .. }) => { - let fn_sig = substs.closure_sig(*def_id, self.tcx); + let fn_sig = ty::ClosureSubsts::from_ref(substs).closure_sig(*def_id, self.tcx); let args = closure_args(&fn_sig); let ret = fn_sig.output().skip_binder().to_string(); format!(" for the closure `fn({}) -> {}`", args, ret) diff --git a/src/librustc/infer/opaque_types/mod.rs b/src/librustc/infer/opaque_types/mod.rs index 2e19c9c24e9b5..ff7cd59720fb2 100644 --- a/src/librustc/infer/opaque_types/mod.rs +++ b/src/librustc/infer/opaque_types/mod.rs @@ -722,7 +722,7 @@ where ty::Closure(def_id, ref substs) => { // Skip lifetime parameters of the enclosing item(s) - for upvar_ty in substs.upvar_tys(def_id, self.tcx) { + for upvar_ty in ty::ClosureSubsts::from_ref(substs).upvar_tys(def_id, self.tcx) { upvar_ty.visit_with(self); } @@ -886,7 +886,7 @@ impl TypeFolder<'tcx> for ReverseMapper<'tcx> { let generics = self.tcx.generics_of(def_id); let substs = - self.tcx.mk_substs(substs.substs.iter().enumerate().map(|(index, &kind)| { + self.tcx.mk_substs(substs.iter().enumerate().map(|(index, &kind)| { if index < generics.parent_count { // Accommodate missing regions in the parent kinds... self.fold_kind_mapping_missing_regions_to_empty(kind) diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 3f5f54c94638e..5595047831cdb 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -745,7 +745,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // During upvar inference we may not know the // closure kind, just use the LATTICE_BOTTOM value. Some(infcx) => - infcx.closure_kind(closure_def_id, closure_substs) + infcx.closure_kind(closure_def_id, ty::ClosureSubsts::from_ref(closure_substs)) .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM), None => diff --git a/src/librustc/traits/select.rs b/src/librustc/traits/select.rs index e1ca9a16d965f..4d025fe73183d 100644 --- a/src/librustc/traits/select.rs +++ b/src/librustc/traits/select.rs @@ -3370,17 +3370,18 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { )?); // FIXME: chalk + if !self.tcx().sess.opts.debugging_opts.chalk { obligations.push(Obligation::new( obligation.cause.clone(), obligation.param_env, - ty::Predicate::ClosureKind(closure_def_id, substs, kind), + ty::Predicate::ClosureKind(closure_def_id, ty::ClosureSubsts::from_ref(substs.clone()), kind), )); } Ok(VtableClosureData { closure_def_id, - substs: substs.clone(), + substs: ty::ClosureSubsts::from_ref(substs), nested: obligations, }) } @@ -3869,7 +3870,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { &mut self, obligation: &TraitObligation<'tcx>, closure_def_id: DefId, - substs: ty::ClosureSubsts<'tcx>, + substs: SubstsRef<'tcx>, ) -> ty::PolyTraitRef<'tcx> { debug!( "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})", diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs index 91479751ef41d..05c6ec6f97a51 100644 --- a/src/librustc/ty/sty.rs +++ b/src/librustc/ty/sty.rs @@ -158,7 +158,7 @@ pub enum TyKind<'tcx> { /// The anonymous type of a closure. Used to represent the type of /// `|a| a`. - Closure(DefId, ClosureSubsts<'tcx>), + Closure(DefId, SubstsRef<'tcx>), /// The anonymous type of a generator. Used to represent the type of /// `|a| yield a`. @@ -317,13 +317,18 @@ pub struct ClosureSubsts<'tcx> { /// Struct returned by `split()`. Note that these are subslices of the /// parent slice and not canonical substs themselves. -struct SplitClosureSubsts<'tcx> { - closure_kind_ty: Ty<'tcx>, - closure_sig_ty: Ty<'tcx>, - upvar_kinds: &'tcx [GenericArg<'tcx>], +pub(crate) struct SplitClosureSubsts<'tcx> { + pub(crate) closure_kind_ty: Ty<'tcx>, + pub(crate) closure_sig_ty: Ty<'tcx>, + pub(crate) upvar_kinds: &'tcx [GenericArg<'tcx>], } impl<'tcx> ClosureSubsts<'tcx> { + // FIXME(csmoe): remove this method once the migration is done. + pub fn from_ref(substs: SubstsRef<'tcx>) -> Self { + Self { substs } + } + /// Divides the closure substs into their respective /// components. Single source of truth with respect to the /// ordering. @@ -2147,7 +2152,7 @@ impl<'tcx> TyS<'tcx> { Adt(_, substs) | Opaque(_, substs) => { out.extend(substs.regions()) } - Closure(_, ClosureSubsts { ref substs }) | + Closure(_, ref substs ) | Generator(_, GeneratorSubsts { ref substs }, _) => { out.extend(substs.regions()) } diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs index e5bee3cfbd06e..e17a715e9570e 100644 --- a/src/librustc/ty/subst.rs +++ b/src/librustc/ty/subst.rs @@ -5,6 +5,7 @@ use crate::infer::canonical::Canonical; use crate::ty::{self, Lift, List, Ty, TyCtxt, InferConst, ParamConst}; use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor}; use crate::mir::interpret::ConstValue; +use crate::ty::sty::SplitClosureSubsts; use rustc_serialize::{self, Encodable, Encoder, Decodable, Decoder}; use syntax_pos::{Span, DUMMY_SP}; @@ -379,6 +380,72 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { tcx.mk_substs(self.iter().take(generics.count()).cloned()) } + + /// Divides the closure substs into their respective + /// components. Single source of truth with respect to the + /// ordering. + fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'tcx> { + let generics = tcx.generics_of(def_id); + let parent_len = generics.parent_count; + SplitClosureSubsts { + closure_kind_ty: self.substs.type_at(parent_len), + closure_sig_ty: self.substs.type_at(parent_len + 1), + upvar_kinds: &self.substs[parent_len + 2..], + } + } + + #[inline] + pub fn upvar_tys( + &self, + def_id: DefId, + tcx: TyCtxt<'_>, + ) -> impl Iterator> + 'tcx { + let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx); + upvar_kinds.iter().map(|t| { + if let UnpackedKind::Type(ty) = t.unpack() { + ty + } else { + bug!("upvar should be type") + } + }) + } + + /// Returns the closure kind for this closure; may return a type + /// variable during inference. To get the closure kind during + /// inference, use `infcx.closure_kind(def_id, substs)`. + pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { + self.split(def_id, tcx).closure_kind_ty + } + + /// Returns the type representing the closure signature for this + /// closure; may contain type variables during inference. To get + /// the closure signature during inference, use + /// `infcx.fn_sig(def_id)`. + pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { + self.split(def_id, tcx).closure_sig_ty + } + + /// Returns the closure kind for this closure; only usable outside + /// of an inference context, because in that context we know that + /// there are no type variables. + /// + /// If you have an inference context, use `infcx.closure_kind()`. + pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind { + self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap() + } + + /// Extracts the signature from the closure; only usable outside + /// of an inference context, because in that context we know that + /// there are no type variables. + /// + /// If you have an inference context, use `infcx.closure_sig()`. + pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { + let ty = self.closure_sig_ty(def_id, tcx); + match ty.kind { + ty::FnPtr(sig) => sig, + _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty.kind), + } + } } impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { From eab060f4da1eeb302953b76d35278679bfeb76b0 Mon Sep 17 00:00:00 2001 From: csmoe Date: Thu, 26 Sep 2019 16:09:51 +0000 Subject: [PATCH 02/17] clean ClosureSubsts in rustc::ty --- src/librustc/ty/context.rs | 4 ++-- src/librustc/ty/flags.rs | 2 +- src/librustc/ty/instance.rs | 4 ++-- src/librustc/ty/print/obsolete.rs | 11 ++++++++--- src/librustc/ty/relate.rs | 2 +- src/librustc/ty/subst.rs | 20 ++++++++++---------- src/librustc/ty/util.rs | 2 +- src/librustc/ty/walk.rs | 2 +- 8 files changed, 26 insertions(+), 21 deletions(-) diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index 6c5d9a6dfdf22..6baf59a257734 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -29,7 +29,7 @@ use crate::traits; use crate::traits::{Clause, Clauses, GoalKind, Goal, Goals}; use crate::ty::{self, DefIdTree, Ty, TypeAndMut}; use crate::ty::{TyS, TyKind, List}; -use crate::ty::{AdtKind, AdtDef, ClosureSubsts, GeneratorSubsts, Region, Const}; +use crate::ty::{AdtKind, AdtDef, GeneratorSubsts, Region, Const}; use crate::ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate}; use crate::ty::RegionKind; use crate::ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid, ConstVid}; @@ -2482,7 +2482,7 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline] - pub fn mk_closure(self, closure_id: DefId, closure_substs: ClosureSubsts<'tcx>) + pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> { self.mk_ty(Closure(closure_id, closure_substs)) } diff --git a/src/librustc/ty/flags.rs b/src/librustc/ty/flags.rs index 6e43aa6a25d55..b513ef5a96670 100644 --- a/src/librustc/ty/flags.rs +++ b/src/librustc/ty/flags.rs @@ -106,7 +106,7 @@ impl FlagComputation { &ty::Closure(_, ref substs) => { self.add_flags(TypeFlags::HAS_TY_CLOSURE); self.add_flags(TypeFlags::HAS_FREE_LOCAL_NAMES); - self.add_substs(&substs.substs); + self.add_substs(substs); } &ty::Bound(debruijn, _) => { diff --git a/src/librustc/ty/instance.rs b/src/librustc/ty/instance.rs index 741830f205cb0..c0cd1fd0614c5 100644 --- a/src/librustc/ty/instance.rs +++ b/src/librustc/ty/instance.rs @@ -321,7 +321,7 @@ impl<'tcx> Instance<'tcx> { let actual_kind = substs.closure_kind(def_id, tcx); match needs_fn_once_adapter_shim(actual_kind, requested_kind) { - Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs), + Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs.substs), _ => Instance::new(def_id, substs.substs) } } @@ -335,7 +335,7 @@ impl<'tcx> Instance<'tcx> { pub fn fn_once_adapter_instance( tcx: TyCtxt<'tcx>, closure_did: DefId, - substs: ty::ClosureSubsts<'tcx>, + substs: ty::SubstsRef<'tcx>, ) -> Instance<'tcx> { debug!("fn_once_adapter_shim({:?}, {:?})", closure_did, diff --git a/src/librustc/ty/print/obsolete.rs b/src/librustc/ty/print/obsolete.rs index d7d43b8203f6f..6f97006c71e3b 100644 --- a/src/librustc/ty/print/obsolete.rs +++ b/src/librustc/ty/print/obsolete.rs @@ -8,7 +8,7 @@ use rustc::hir::def_id::DefId; use rustc::mir::interpret::ConstValue; use rustc::ty::subst::SubstsRef; -use rustc::ty::{self, ClosureSubsts, Const, GeneratorSubsts, Instance, Ty, TyCtxt}; +use rustc::ty::{self, Const, GeneratorSubsts, Instance, Ty, TyCtxt}; use rustc::{bug, hir}; use std::fmt::Write; use std::iter; @@ -154,8 +154,13 @@ impl DefPathBasedNames<'tcx> { self.push_type_name(sig.output(), output, debug); } } - ty::Generator(def_id, GeneratorSubsts { ref substs }, _) - | ty::Closure(def_id, ClosureSubsts { ref substs }) => { + ty::Generator(def_id, GeneratorSubsts { ref substs }, _) => { + self.push_def_path(def_id, output); + let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id)); + let substs = substs.truncate_to(self.tcx, generics); + self.push_generic_params(substs, iter::empty(), output, debug); + } + ty::Closure(def_id, substs) => { self.push_def_path(def_id, output); let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id)); let substs = substs.truncate_to(self.tcx, generics); diff --git a/src/librustc/ty/relate.rs b/src/librustc/ty/relate.rs index 2af6963f7122a..5cd89d231f939 100644 --- a/src/librustc/ty/relate.rs +++ b/src/librustc/ty/relate.rs @@ -442,7 +442,7 @@ pub fn super_relate_tys>( // the (anonymous) type of the same closure expression. So // all of their regions should be equated. let substs = relation.relate(&a_substs, &b_substs)?; - Ok(tcx.mk_closure(a_id, substs)) + Ok(tcx.mk_closure(a_id, &substs)) } (&ty::RawPtr(ref a_mt), &ty::RawPtr(ref b_mt)) => diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs index e17a715e9570e..6e00c6b29ecf1 100644 --- a/src/librustc/ty/subst.rs +++ b/src/librustc/ty/subst.rs @@ -384,22 +384,22 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { /// Divides the closure substs into their respective /// components. Single source of truth with respect to the /// ordering. - fn split(self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'tcx> { + fn split(&self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'_> { let generics = tcx.generics_of(def_id); let parent_len = generics.parent_count; SplitClosureSubsts { - closure_kind_ty: self.substs.type_at(parent_len), - closure_sig_ty: self.substs.type_at(parent_len + 1), - upvar_kinds: &self.substs[parent_len + 2..], + closure_kind_ty: self.type_at(parent_len), + closure_sig_ty: self.type_at(parent_len + 1), + upvar_kinds: &self[parent_len + 2..], } } #[inline] pub fn upvar_tys( - &self, + &'a self, def_id: DefId, tcx: TyCtxt<'_>, - ) -> impl Iterator> + 'tcx { + ) -> impl Iterator> + 'a { let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx); upvar_kinds.iter().map(|t| { if let UnpackedKind::Type(ty) = t.unpack() { @@ -413,7 +413,7 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { /// Returns the closure kind for this closure; may return a type /// variable during inference. To get the closure kind during /// inference, use `infcx.closure_kind(def_id, substs)`. - pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { + pub fn closure_kind_ty(&'a self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'a> { self.split(def_id, tcx).closure_kind_ty } @@ -421,7 +421,7 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { /// closure; may contain type variables during inference. To get /// the closure signature during inference, use /// `infcx.fn_sig(def_id)`. - pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { + pub fn closure_sig_ty(&'a self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'a> { self.split(def_id, tcx).closure_sig_ty } @@ -430,7 +430,7 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { /// there are no type variables. /// /// If you have an inference context, use `infcx.closure_kind()`. - pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind { + pub fn closure_kind(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind { self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap() } @@ -439,7 +439,7 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { /// there are no type variables. /// /// If you have an inference context, use `infcx.closure_sig()`. - pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { + pub fn closure_sig(&'a self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'a> { let ty = self.closure_sig_ty(def_id, tcx); match ty.kind { ty::FnPtr(sig) => sig, diff --git a/src/librustc/ty/util.rs b/src/librustc/ty/util.rs index c4d8e452441cb..05f0d164cc1c3 100644 --- a/src/librustc/ty/util.rs +++ b/src/librustc/ty/util.rs @@ -642,7 +642,7 @@ impl<'tcx> TyCtxt<'tcx> { /// wrapped in a binder. pub fn closure_env_ty(self, closure_def_id: DefId, - closure_substs: ty::ClosureSubsts<'tcx>) + closure_substs: SubstsRef<'tcx>) -> Option>> { let closure_ty = self.mk_closure(closure_def_id, closure_substs); diff --git a/src/librustc/ty/walk.rs b/src/librustc/ty/walk.rs index 12f0d80cd0e1c..1895ab83674eb 100644 --- a/src/librustc/ty/walk.rs +++ b/src/librustc/ty/walk.rs @@ -111,7 +111,7 @@ fn push_subtypes<'tcx>(stack: &mut TypeWalkerStack<'tcx>, parent_ty: Ty<'tcx>) { stack.extend(substs.types().rev()); } ty::Closure(_, ref substs) => { - stack.extend(substs.substs.types().rev()); + stack.extend(substs.types().rev()); } ty::Generator(_, ref substs, _) => { stack.extend(substs.substs.types().rev()); From 1f8e1d8aea495ec22fa33cefcfacbcb6ba3bad1d Mon Sep 17 00:00:00 2001 From: csmoe Date: Thu, 26 Sep 2019 16:11:23 +0000 Subject: [PATCH 03/17] remove ClosureSubsts with SubstsRef --- src/librustc/infer/opaque_types/mod.rs | 2 +- src/librustc/middle/mem_categorization.rs | 3 ++- src/librustc/mir/tcx.rs | 2 +- src/librustc/traits/select.rs | 9 ++++++--- src/librustc/ty/subst.rs | 2 +- src/librustc_codegen_ssa/mir/mod.rs | 3 ++- src/librustc_codegen_ssa/mir/rvalue.rs | 4 +++- src/librustc_codegen_utils/symbol_names/legacy.rs | 2 +- src/librustc_codegen_utils/symbol_names/v0.rs | 2 +- src/librustc_mir/borrow_check/nll/universal_regions.rs | 5 +++-- src/librustc_mir/hair/cx/expr.rs | 8 +++++--- src/librustc_mir/interpret/cast.rs | 2 +- src/librustc_mir/interpret/intrinsics/type_name.rs | 2 +- src/librustc_mir/monomorphize/collector.rs | 3 ++- src/librustc_traits/generic_types.rs | 4 +--- src/librustc_typeck/check/callee.rs | 1 + src/librustc_typeck/check/closure.rs | 1 - src/librustc_typeck/check/coercion.rs | 3 ++- src/librustc_typeck/check/upvar.rs | 3 ++- src/librustc_typeck/collect.rs | 5 +---- 20 files changed, 37 insertions(+), 29 deletions(-) diff --git a/src/librustc/infer/opaque_types/mod.rs b/src/librustc/infer/opaque_types/mod.rs index ff7cd59720fb2..8cc7dbb3c5c91 100644 --- a/src/librustc/infer/opaque_types/mod.rs +++ b/src/librustc/infer/opaque_types/mod.rs @@ -896,7 +896,7 @@ impl TypeFolder<'tcx> for ReverseMapper<'tcx> { } })); - self.tcx.mk_closure(def_id, ty::ClosureSubsts { substs }) + self.tcx.mk_closure(def_id, substs) } ty::Generator(def_id, substs, movability) => { diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 5595047831cdb..522c0e55b8594 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -745,7 +745,8 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // During upvar inference we may not know the // closure kind, just use the LATTICE_BOTTOM value. Some(infcx) => - infcx.closure_kind(closure_def_id, ty::ClosureSubsts::from_ref(closure_substs)) + infcx.closure_kind(closure_def_id, + ty::ClosureSubsts::from_ref(closure_substs)) .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM), None => diff --git a/src/librustc/mir/tcx.rs b/src/librustc/mir/tcx.rs index 26f718e858da8..44829f670faf9 100644 --- a/src/librustc/mir/tcx.rs +++ b/src/librustc/mir/tcx.rs @@ -218,7 +218,7 @@ impl<'tcx> Rvalue<'tcx> { tcx.type_of(def.did).subst(tcx, substs) } AggregateKind::Closure(did, substs) => { - tcx.mk_closure(did, substs) + tcx.mk_closure(did, &substs.substs) } AggregateKind::Generator(did, substs, movability) => { tcx.mk_generator(did, substs, movability) diff --git a/src/librustc/traits/select.rs b/src/librustc/traits/select.rs index 4d025fe73183d..3450f3fc86592 100644 --- a/src/librustc/traits/select.rs +++ b/src/librustc/traits/select.rs @@ -2051,7 +2051,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { "assemble_unboxed_candidates: kind={:?} obligation={:?}", kind, obligation ); - match self.infcx.closure_kind(closure_def_id, closure_substs) { + match self.infcx.closure_kind(closure_def_id, + ty::ClosureSubsts::from_ref(closure_substs)) { Some(closure_kind) => { debug!( "assemble_unboxed_candidates: closure_kind = {:?}", @@ -3375,7 +3376,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligations.push(Obligation::new( obligation.cause.clone(), obligation.param_env, - ty::Predicate::ClosureKind(closure_def_id, ty::ClosureSubsts::from_ref(substs.clone()), kind), + ty::Predicate::ClosureKind(closure_def_id, + ty::ClosureSubsts::from_ref(substs.clone()), kind), )); } @@ -3876,7 +3878,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})", obligation, closure_def_id, substs, ); - let closure_type = self.infcx.closure_sig(closure_def_id, substs); + let closure_type = self.infcx.closure_sig(closure_def_id, + ty::ClosureSubsts::from_ref(substs)); debug!( "closure_trait_ref_unnormalized: closure_type = {:?}", diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs index 6e00c6b29ecf1..05042ccf9a1d6 100644 --- a/src/librustc/ty/subst.rs +++ b/src/librustc/ty/subst.rs @@ -402,7 +402,7 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { ) -> impl Iterator> + 'a { let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx); upvar_kinds.iter().map(|t| { - if let UnpackedKind::Type(ty) = t.unpack() { + if let GenericArgKind::Type(ty) = t.unpack() { ty } else { bug!("upvar should be type") diff --git a/src/librustc_codegen_ssa/mir/mod.rs b/src/librustc_codegen_ssa/mir/mod.rs index 4f3a8bdb540b5..30d519c8733cc 100644 --- a/src/librustc_codegen_ssa/mir/mod.rs +++ b/src/librustc_codegen_ssa/mir/mod.rs @@ -615,7 +615,8 @@ fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( }; let (def_id, upvar_substs) = match closure_layout.ty.kind { - ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)), + ty::Closure(def_id, substs) => (def_id, + UpvarSubsts::Closure(rustc::ty::ClosureSubsts::from_ref(substs))), ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)), _ => bug!("upvar debuginfo with non-closure arg0 type `{}`", closure_layout.ty) }; diff --git a/src/librustc_codegen_ssa/mir/rvalue.rs b/src/librustc_codegen_ssa/mir/rvalue.rs index 9b69383b455cf..9cc21a28b2737 100644 --- a/src/librustc_codegen_ssa/mir/rvalue.rs +++ b/src/librustc_codegen_ssa/mir/rvalue.rs @@ -201,7 +201,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { match operand.layout.ty.kind { ty::Closure(def_id, substs) => { let instance = Instance::resolve_closure( - bx.cx().tcx(), def_id, substs, ty::ClosureKind::FnOnce); + bx.cx().tcx(), def_id, + rustc::ty::ClosureSubsts::from_ref(substs), + ty::ClosureKind::FnOnce); OperandValue::Immediate(bx.cx().get_fn(instance)) } _ => { diff --git a/src/librustc_codegen_utils/symbol_names/legacy.rs b/src/librustc_codegen_utils/symbol_names/legacy.rs index a9866c8c0b282..5bcb3b4ceb3ba 100644 --- a/src/librustc_codegen_utils/symbol_names/legacy.rs +++ b/src/librustc_codegen_utils/symbol_names/legacy.rs @@ -224,7 +224,7 @@ impl Printer<'tcx> for SymbolPrinter<'tcx> { ty::Opaque(def_id, substs) | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) | ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs }) | - ty::Closure(def_id, ty::ClosureSubsts { substs }) | + ty::Closure(def_id, substs) | ty::Generator(def_id, ty::GeneratorSubsts { substs }, _) => { self.print_def_path(def_id, substs) } diff --git a/src/librustc_codegen_utils/symbol_names/v0.rs b/src/librustc_codegen_utils/symbol_names/v0.rs index a63236305dc11..2ad699d7c6f08 100644 --- a/src/librustc_codegen_utils/symbol_names/v0.rs +++ b/src/librustc_codegen_utils/symbol_names/v0.rs @@ -414,7 +414,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { ty::Opaque(def_id, substs) | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) | ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs }) | - ty::Closure(def_id, ty::ClosureSubsts { substs }) | + ty::Closure(def_id, substs) | ty::Generator(def_id, ty::GeneratorSubsts { substs }, _) => { self = self.print_def_path(def_id, substs)?; } diff --git a/src/librustc_mir/borrow_check/nll/universal_regions.rs b/src/librustc_mir/borrow_check/nll/universal_regions.rs index 7053bdca25957..80ed90ede4dd6 100644 --- a/src/librustc_mir/borrow_check/nll/universal_regions.rs +++ b/src/librustc_mir/borrow_check/nll/universal_regions.rs @@ -509,7 +509,8 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { .replace_free_regions_with_nll_infer_vars(FR, &defining_ty); match defining_ty.kind { - ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs), + ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, + rustc::ty::ClosureSubsts::from_ref(substs)), ty::Generator(def_id, substs, movability) => { DefiningTy::Generator(def_id, substs, movability) } @@ -584,7 +585,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { assert_eq!(self.mir_def_id, def_id); let closure_sig = substs.closure_sig_ty(def_id, tcx).fn_sig(tcx); let inputs_and_output = closure_sig.inputs_and_output(); - let closure_ty = tcx.closure_env_ty(def_id, substs).unwrap(); + let closure_ty = tcx.closure_env_ty(def_id, substs.substs).unwrap(); ty::Binder::fuse( closure_ty, inputs_and_output, diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs index eed51cdab8c3c..e4d26bda40f71 100644 --- a/src/librustc_mir/hair/cx/expr.rs +++ b/src/librustc_mir/hair/cx/expr.rs @@ -506,7 +506,8 @@ fn make_mirror_unadjusted<'a, 'tcx>( hir::ExprKind::Closure(..) => { let closure_ty = cx.tables().expr_ty(expr); let (def_id, substs, movability) = match closure_ty.kind { - ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None), + ty::Closure(def_id, substs) => (def_id, + UpvarSubsts::Closure(rustc::ty::ClosureSubsts::from_ref(substs)), None), ty::Generator(def_id, substs, movability) => { (def_id, UpvarSubsts::Generator(substs), Some(movability)) } @@ -1002,7 +1003,8 @@ fn convert_var( let region = cx.tcx.mk_region(region); let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.kind { - match cx.infcx.closure_kind(closure_def_id, closure_substs).unwrap() { + match cx.infcx.closure_kind(closure_def_id, + rustc::ty::ClosureSubsts::from_ref(closure_substs)).unwrap() { ty::ClosureKind::Fn => { let ref_closure_ty = cx.tcx.mk_ref(region, ty::TypeAndMut { @@ -1011,7 +1013,7 @@ fn convert_var( }); Expr { ty: closure_ty, - temp_lifetime: temp_lifetime, + temp_lifetime, span: expr.span, kind: ExprKind::Deref { arg: Expr { diff --git a/src/librustc_mir/interpret/cast.rs b/src/librustc_mir/interpret/cast.rs index d120412c901a6..943054cc6964d 100644 --- a/src/librustc_mir/interpret/cast.rs +++ b/src/librustc_mir/interpret/cast.rs @@ -75,7 +75,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let instance = ty::Instance::resolve_closure( *self.tcx, def_id, - substs, + rustc::ty::ClosureSubsts::from_ref(substs), ty::ClosureKind::FnOnce, ); let fn_ptr = self.memory.create_fn_alloc(FnVal::Instance(instance)); diff --git a/src/librustc_mir/interpret/intrinsics/type_name.rs b/src/librustc_mir/interpret/intrinsics/type_name.rs index a8b4d65e7d4b0..dc3b7694c35c9 100644 --- a/src/librustc_mir/interpret/intrinsics/type_name.rs +++ b/src/librustc_mir/interpret/intrinsics/type_name.rs @@ -67,7 +67,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { | ty::Opaque(def_id, substs) | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) | ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs }) - | ty::Closure(def_id, ty::ClosureSubsts { substs }) + | ty::Closure(def_id, substs) | ty::Generator(def_id, ty::GeneratorSubsts { substs }, _) => self.print_def_path(def_id, substs), ty::Foreign(def_id) => self.print_def_path(def_id, &[]), diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index cc8f4759e1837..21aea5593ee4b 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -581,7 +581,8 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> { match source_ty.kind { ty::Closure(def_id, substs) => { let instance = Instance::resolve_closure( - self.tcx, def_id, substs, ty::ClosureKind::FnOnce); + self.tcx, def_id, + rustc::ty::ClosureSubsts::from_ref(substs), ty::ClosureKind::FnOnce); if should_monomorphize_locally(self.tcx, &instance) { self.output.push(create_fn_mono_item(instance)); } diff --git a/src/librustc_traits/generic_types.rs b/src/librustc_traits/generic_types.rs index e4d15a35137cc..91ca6415bdcb9 100644 --- a/src/librustc_traits/generic_types.rs +++ b/src/librustc_traits/generic_types.rs @@ -69,9 +69,7 @@ crate fn fn_def(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> { } crate fn closure(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> { - tcx.mk_closure(def_id, ty::ClosureSubsts { - substs: InternalSubsts::bound_vars_for_item(tcx, def_id), - }) + tcx.mk_closure(def_id, InternalSubsts::bound_vars_for_item(tcx, def_id)) } crate fn generator(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> { diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index 290b87388ebbe..3a16926872070 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -103,6 +103,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Check whether this is a call to a closure where we // haven't yet decided on whether the closure is fn vs // fnmut vs fnonce. If so, we have to defer further processing. + let substs = rustc::ty::ClosureSubsts::from_ref(substs); if self.closure_kind(def_id, substs).is_none() { let closure_ty = self.closure_sig(def_id, substs); let fn_sig = self diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index bdf8f3b1d4ae6..09dcce003fe27 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -132,7 +132,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return self.tcx.mk_generator(expr_def_id, substs, movability); } - let substs = ty::ClosureSubsts { substs }; let closure_type = self.tcx.mk_closure(expr_def_id, substs); debug!( diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index 564a0eac75539..c10279022bdfd 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -237,7 +237,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // Non-capturing closures are coercible to // function pointers or unsafe function pointers. // It cannot convert closures that require unsafe. - self.coerce_closure_to_fn(a, def_id_a, substs_a, b) + self.coerce_closure_to_fn(a, def_id_a, + rustc::ty::ClosureSubsts::from_ref(substs_a), b) } _ => { // Otherwise, just use unification rules. diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 71ea938a8039b..5b7c5c04e446a 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -96,7 +96,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Extract the type of the closure. let ty = self.node_ty(closure_hir_id); let (closure_def_id, substs) = match ty.kind { - ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)), + ty::Closure(def_id, substs) => (def_id, + UpvarSubsts::Closure(rustc::ty::ClosureSubsts::from_ref(substs))), ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)), ty::Error => { // #51714: skip analysis when we have already encountered type errors diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 8c3d6357f0bbf..1690ae7635f05 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1362,10 +1362,7 @@ pub fn checked_type_of(tcx: TyCtxt<'_>, def_id: DefId, fail: bool) -> Option Date: Sat, 28 Sep 2019 15:59:19 +0100 Subject: [PATCH 04/17] 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 05/17] 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); From 08a60ac6ed68628c4ccdb3fcbb6d780cadd7565a Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Sat, 21 Sep 2019 16:32:24 +0100 Subject: [PATCH 06/17] Calculate liveness for the same locals with and without -Zpolonius This fixes some test differences and also avoids overflow in issue-38591.rs. --- .../nll/type_check/liveness/local_use_map.rs | 4 + .../nll/type_check/liveness/mod.rs | 52 +++--- .../nll/type_check/liveness/polonius.rs | 11 +- .../nll/type_check/liveness/trace.rs | 37 ++++- ...wck-escaping-closure-error.polonius.stderr | 16 -- ...k-escaping-closure-error-2.polonius.stderr | 16 -- ...ref-mut-in-let-issue-46557.polonius.stderr | 59 ------- ...al-binding-from-desugaring.polonius.stderr | 16 -- ...phase-surprise-no-conflict.polonius.stderr | 148 ------------------ .../consts/promote_const_let.polonius.stderr | 29 ---- ...dropck_trait_cycle_checked.polonius.stderr | 78 --------- ...escapes-but-not-over-yield.polonius.stderr | 20 --- src/test/ui/nll/get_default.polonius.stderr | 5 +- .../loan_ends_mid_block_pair.polonius.stderr | 15 -- .../nll/polonius/polonius-smoke-test.stderr | 4 +- ...return-ref-mut-issue-46557.polonius.stderr | 15 -- ...ures-failed-recursive-fn-1.polonius.stderr | 60 ------- 17 files changed, 84 insertions(+), 501 deletions(-) delete mode 100644 src/test/ui/async-await/async-borrowck-escaping-closure-error.polonius.stderr delete mode 100644 src/test/ui/borrowck/borrowck-escaping-closure-error-2.polonius.stderr delete mode 100644 src/test/ui/borrowck/promote-ref-mut-in-let-issue-46557.polonius.stderr delete mode 100644 src/test/ui/borrowck/return-local-binding-from-desugaring.polonius.stderr delete mode 100644 src/test/ui/borrowck/two-phase-surprise-no-conflict.polonius.stderr delete mode 100644 src/test/ui/consts/promote_const_let.polonius.stderr delete mode 100644 src/test/ui/dropck/dropck_trait_cycle_checked.polonius.stderr delete mode 100644 src/test/ui/generator/ref-escapes-but-not-over-yield.polonius.stderr delete mode 100644 src/test/ui/nll/loan_ends_mid_block_pair.polonius.stderr delete mode 100644 src/test/ui/nll/return-ref-mut-issue-46557.polonius.stderr delete mode 100644 src/test/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.polonius.stderr diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs index 7689ece706695..7dee00b3eca67 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs @@ -70,6 +70,10 @@ impl LocalUseMap { appearances: IndexVec::new(), }; + if live_locals.is_empty() { + return local_use_map; + } + let mut locals_with_use_data: IndexVec = IndexVec::from_elem_n(false, body.local_decls.len()); live_locals.iter().for_each(|&local| locals_with_use_data[local] = true); diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs index 3f2ec1ba97017..a01b528833b2d 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs @@ -36,31 +36,39 @@ pub(super) fn generate<'tcx>( ) { debug!("liveness::generate"); - let live_locals: Vec = if AllFacts::enabled(typeck.tcx()) { - // If "dump facts from NLL analysis" was requested perform - // the liveness analysis for all `Local`s. This case opens - // the possibility of the variables being analyzed in `trace` - // to be *any* `Local`, not just the "live" ones, so we can't - // make any assumptions past this point as to the characteristics - // of the `live_locals`. - // FIXME: Review "live" terminology past this point, we should - // not be naming the `Local`s as live. - body.local_decls.indices().collect() + let free_regions = regions_that_outlive_free_regions( + typeck.infcx.num_region_vars(), + &typeck.borrowck_context.universal_regions, + &typeck.borrowck_context.constraints.outlives_constraints, + ); + let live_locals = compute_live_locals(typeck.tcx(), &free_regions, body); + let facts_enabled = AllFacts::enabled(typeck.tcx()); + + + let polonius_drop_used = if facts_enabled { + let mut drop_used = Vec::new(); + polonius::populate_access_facts( + typeck, + body, + location_table, + move_data, + &mut drop_used, + ); + Some(drop_used) } else { - let free_regions = { - regions_that_outlive_free_regions( - typeck.infcx.num_region_vars(), - &typeck.borrowck_context.universal_regions, - &typeck.borrowck_context.constraints.outlives_constraints, - ) - }; - compute_live_locals(typeck.tcx(), &free_regions, body) + None }; - if !live_locals.is_empty() { - trace::trace(typeck, body, elements, flow_inits, move_data, live_locals); - - polonius::populate_access_facts(typeck, body, location_table, move_data); + if !live_locals.is_empty() || facts_enabled { + trace::trace( + typeck, + body, + elements, + flow_inits, + move_data, + live_locals, + polonius_drop_used, + ); } } diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/polonius.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/polonius.rs index e37ddbda4be02..526ad7fb905bb 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/polonius.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/polonius.rs @@ -16,7 +16,7 @@ struct UseFactsExtractor<'me> { var_defined: &'me mut VarPointRelations, var_used: &'me mut VarPointRelations, location_table: &'me LocationTable, - var_drop_used: &'me mut VarPointRelations, + var_drop_used: &'me mut Vec<(Local, Location)>, move_data: &'me MoveData<'me>, path_accessed_at: &'me mut MovePathPointRelations, } @@ -39,7 +39,7 @@ impl UseFactsExtractor<'_> { fn insert_drop_use(&mut self, local: Local, location: Location) { debug!("LivenessFactsExtractor::insert_drop_use()"); - self.var_drop_used.push((local, self.location_to_index(location))); + self.var_drop_used.push((local, location)); } fn insert_path_access(&mut self, path: MovePathIndex, location: Location) { @@ -100,6 +100,7 @@ pub(super) fn populate_access_facts( body: &Body<'tcx>, location_table: &LocationTable, move_data: &MoveData<'_>, + drop_used: &mut Vec<(Local, Location)>, ) { debug!("populate_var_liveness_facts()"); @@ -107,12 +108,16 @@ pub(super) fn populate_access_facts( UseFactsExtractor { var_defined: &mut facts.var_defined, var_used: &mut facts.var_used, - var_drop_used: &mut facts.var_drop_used, + var_drop_used: drop_used, path_accessed_at: &mut facts.path_accessed_at, location_table, move_data, } .visit_body(body); + + facts.var_drop_used.extend(drop_used.iter().map(|&(local, location)| { + (local, location_table.mid_index(location)) + })); } for (local, local_decl) in body.local_decls.iter_enumerated() { diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs index 36482a7b13534..eacc4d084dbb8 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs @@ -13,7 +13,7 @@ use rustc::traits::query::type_op::outlives::DropckOutlives; use rustc::traits::query::type_op::TypeOp; use rustc::ty::{Ty, TypeFoldable}; use rustc_index::bit_set::HybridBitSet; -use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use std::rc::Rc; /// This is the heart of the liveness computation. For each variable X @@ -37,6 +37,7 @@ pub(super) fn trace( flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'tcx>>, move_data: &MoveData<'tcx>, live_locals: Vec, + polonius_drop_used: Option>, ) { debug!("trace()"); @@ -52,7 +53,13 @@ pub(super) fn trace( drop_data: FxHashMap::default(), }; - LivenessResults::new(cx).compute_for_all_locals(live_locals); + let mut results = LivenessResults::new(cx); + + if let Some(drop_used) = polonius_drop_used { + results.add_extra_drop_facts(drop_used, live_locals.iter().copied().collect()) + } + + results.compute_for_all_locals(live_locals); } /// Contextual state for the type-liveness generator. @@ -145,6 +152,32 @@ impl LivenessResults<'me, 'typeck, 'flow, 'tcx> { } } + /// Add extra drop facts needed for Polonius. + /// + /// Add facts for all locals with free regions, since regions may outlive + /// the function body only at certain nodes in the CFG. + fn add_extra_drop_facts( + &mut self, + drop_used: Vec<(Local, Location)>, + live_locals: FxHashSet, + ) { + let locations = HybridBitSet::new_empty(self.cx.elements.num_points()); + + for (local, location) in drop_used { + if !live_locals.contains(&local) { + let local_ty = self.cx.body.local_decls[local].ty; + if local_ty.has_free_regions() { + self.cx.add_drop_live_facts_for( + local, + local_ty, + &[location], + &locations, + ); + } + } + } + } + /// Clear the value of fields that are "per local variable". fn reset_local_state(&mut self) { self.defs.clear(); diff --git a/src/test/ui/async-await/async-borrowck-escaping-closure-error.polonius.stderr b/src/test/ui/async-await/async-borrowck-escaping-closure-error.polonius.stderr deleted file mode 100644 index 5f20367b6aba9..0000000000000 --- a/src/test/ui/async-await/async-borrowck-escaping-closure-error.polonius.stderr +++ /dev/null @@ -1,16 +0,0 @@ -error[E0597]: `x` does not live long enough - --> $DIR/async-borrowck-escaping-closure-error.rs:5:24 - | -LL | Box::new((async || x)()) - | -------------------^---- - | | | | - | | | borrowed value does not live long enough - | | value captured here - | borrow later used here -LL | -LL | } - | - `x` dropped here while still borrowed - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0597`. diff --git a/src/test/ui/borrowck/borrowck-escaping-closure-error-2.polonius.stderr b/src/test/ui/borrowck/borrowck-escaping-closure-error-2.polonius.stderr deleted file mode 100644 index 89af8764557ff..0000000000000 --- a/src/test/ui/borrowck/borrowck-escaping-closure-error-2.polonius.stderr +++ /dev/null @@ -1,16 +0,0 @@ -error[E0597]: `books` does not live long enough - --> $DIR/borrowck-escaping-closure-error-2.rs:11:17 - | -LL | Box::new(|| books.push(4)) - | ------------^^^^^--------- - | | | | - | | | borrowed value does not live long enough - | | value captured here - | borrow later used here -LL | -LL | } - | - `books` dropped here while still borrowed - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0597`. diff --git a/src/test/ui/borrowck/promote-ref-mut-in-let-issue-46557.polonius.stderr b/src/test/ui/borrowck/promote-ref-mut-in-let-issue-46557.polonius.stderr deleted file mode 100644 index a5b2e8762746c..0000000000000 --- a/src/test/ui/borrowck/promote-ref-mut-in-let-issue-46557.polonius.stderr +++ /dev/null @@ -1,59 +0,0 @@ -error[E0716]: temporary value dropped while borrowed - --> $DIR/promote-ref-mut-in-let-issue-46557.rs:5:21 - | -LL | let ref mut x = 1234543; - | ^^^^^^^ creates a temporary which is freed while still in use -LL | x - | - borrow later used here -LL | } - | - temporary value is freed at the end of this statement - | - = note: consider using a `let` binding to create a longer lived value - -error[E0716]: temporary value dropped while borrowed - --> $DIR/promote-ref-mut-in-let-issue-46557.rs:10:25 - | -LL | let (ref mut x, ) = (1234543, ); - | ^^^^^^^^^^^ creates a temporary which is freed while still in use -LL | x - | - borrow later used here -LL | } - | - temporary value is freed at the end of this statement - | - = note: consider using a `let` binding to create a longer lived value - -error[E0515]: cannot return value referencing temporary value - --> $DIR/promote-ref-mut-in-let-issue-46557.rs:15:5 - | -LL | match 1234543 { - | ^ ------- temporary value created here - | _____| - | | -LL | | ref mut x => x -LL | | } - | |_____^ returns a value referencing data owned by the current function - -error[E0515]: cannot return value referencing temporary value - --> $DIR/promote-ref-mut-in-let-issue-46557.rs:21:5 - | -LL | match (123443,) { - | ^ --------- temporary value created here - | _____| - | | -LL | | (ref mut x,) => x, -LL | | } - | |_____^ returns a value referencing data owned by the current function - -error[E0515]: cannot return reference to temporary value - --> $DIR/promote-ref-mut-in-let-issue-46557.rs:27:5 - | -LL | &mut 1234543 - | ^^^^^------- - | | | - | | temporary value created here - | returns a reference to data owned by the current function - -error: aborting due to 5 previous errors - -Some errors have detailed explanations: E0515, E0716. -For more information about an error, try `rustc --explain E0515`. diff --git a/src/test/ui/borrowck/return-local-binding-from-desugaring.polonius.stderr b/src/test/ui/borrowck/return-local-binding-from-desugaring.polonius.stderr deleted file mode 100644 index c818379762c9d..0000000000000 --- a/src/test/ui/borrowck/return-local-binding-from-desugaring.polonius.stderr +++ /dev/null @@ -1,16 +0,0 @@ -error[E0716]: temporary value dropped while borrowed - --> $DIR/return-local-binding-from-desugaring.rs:26:18 - | -LL | for ref x in xs { - | ^^ creates a temporary which is freed while still in use -... -LL | } - | - temporary value is freed at the end of this statement -LL | result - | ------ borrow later used here - | - = note: consider using a `let` binding to create a longer lived value - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0716`. diff --git a/src/test/ui/borrowck/two-phase-surprise-no-conflict.polonius.stderr b/src/test/ui/borrowck/two-phase-surprise-no-conflict.polonius.stderr deleted file mode 100644 index 7b246426a2333..0000000000000 --- a/src/test/ui/borrowck/two-phase-surprise-no-conflict.polonius.stderr +++ /dev/null @@ -1,148 +0,0 @@ -error[E0503]: cannot use `self.cx` because it was mutably borrowed - --> $DIR/two-phase-surprise-no-conflict.rs:21:23 - | -LL | let _mut_borrow = &mut *self; - | ---------- borrow of `*self` occurs here -LL | let _access = self.cx; - | ^^^^^^^ use of borrowed `*self` -LL | -LL | _mut_borrow; - | ----------- borrow later used here - -error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable - --> $DIR/two-phase-surprise-no-conflict.rs:57:17 - | -LL | self.hash_expr(&self.cx_mut.body(eid).value); - | ^^^^^---------^^-----------^^^^^^^^^^^^^^^^^ - | | | | - | | | immutable borrow occurs here - | | immutable borrow later used by call - | mutable borrow occurs here - -error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:119:51 - | -LL | reg.register_static(Box::new(TrivialPass::new(&mut reg.sess_mut))); - | --- --------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | | first borrow later used by call - | first mutable borrow occurs here - -error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:122:54 - | -LL | reg.register_bound(Box::new(TrivialPass::new_mut(&mut reg.sess_mut))); - | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | | first borrow later used by call - | first mutable borrow occurs here - -error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:125:53 - | -LL | reg.register_univ(Box::new(TrivialPass::new_mut(&mut reg.sess_mut))); - | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | | first borrow later used by call - | first mutable borrow occurs here - -error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:128:44 - | -LL | reg.register_ref(&TrivialPass::new_mut(&mut reg.sess_mut)); - | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | | first borrow later used by call - | first mutable borrow occurs here - -error[E0502]: cannot borrow `*reg` as mutable because it is also borrowed as immutable - --> $DIR/two-phase-surprise-no-conflict.rs:138:5 - | -LL | reg.register_bound(Box::new(CapturePass::new(®.sess_mut))); - | ^^^^--------------^^^^^^^^^^^^^^^^^^^^^^^^^^^-------------^^^ - | | | | - | | | immutable borrow occurs here - | | immutable borrow later used by call - | mutable borrow occurs here - -error[E0502]: cannot borrow `*reg` as mutable because it is also borrowed as immutable - --> $DIR/two-phase-surprise-no-conflict.rs:141:5 - | -LL | reg.register_univ(Box::new(CapturePass::new(®.sess_mut))); - | ^^^^-------------^^^^^^^^^^^^^^^^^^^^^^^^^^^-------------^^^ - | | | | - | | | immutable borrow occurs here - | | immutable borrow later used by call - | mutable borrow occurs here - -error[E0502]: cannot borrow `*reg` as mutable because it is also borrowed as immutable - --> $DIR/two-phase-surprise-no-conflict.rs:144:5 - | -LL | reg.register_ref(&CapturePass::new(®.sess_mut)); - | ^^^^------------^^^^^^^^^^^^^^^^^^^-------------^^ - | | | | - | | | immutable borrow occurs here - | | immutable borrow later used by call - | mutable borrow occurs here - -error[E0499]: cannot borrow `*reg` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:154:5 - | -LL | reg.register_bound(Box::new(CapturePass::new_mut(&mut reg.sess_mut))); - | ^^^^--------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------------^^^ - | | | | - | | | first mutable borrow occurs here - | | first borrow later used by call - | second mutable borrow occurs here - -error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:154:54 - | -LL | reg.register_bound(Box::new(CapturePass::new_mut(&mut reg.sess_mut))); - | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | | first borrow later used by call - | first mutable borrow occurs here - -error[E0499]: cannot borrow `*reg` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:158:5 - | -LL | reg.register_univ(Box::new(CapturePass::new_mut(&mut reg.sess_mut))); - | ^^^^-------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------------^^^ - | | | | - | | | first mutable borrow occurs here - | | first borrow later used by call - | second mutable borrow occurs here - -error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:158:53 - | -LL | reg.register_univ(Box::new(CapturePass::new_mut(&mut reg.sess_mut))); - | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | | first borrow later used by call - | first mutable borrow occurs here - -error[E0499]: cannot borrow `*reg` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:162:5 - | -LL | reg.register_ref(&CapturePass::new_mut(&mut reg.sess_mut)); - | ^^^^------------^^^^^^^^^^^^^^^^^^^^^^^-----------------^^ - | | | | - | | | first mutable borrow occurs here - | | first borrow later used by call - | second mutable borrow occurs here - -error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time - --> $DIR/two-phase-surprise-no-conflict.rs:162:44 - | -LL | reg.register_ref(&CapturePass::new_mut(&mut reg.sess_mut)); - | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | | first borrow later used by call - | first mutable borrow occurs here - -error: aborting due to 15 previous errors - -Some errors have detailed explanations: E0499, E0502, E0503. -For more information about an error, try `rustc --explain E0499`. diff --git a/src/test/ui/consts/promote_const_let.polonius.stderr b/src/test/ui/consts/promote_const_let.polonius.stderr deleted file mode 100644 index cf41bd7bdb1eb..0000000000000 --- a/src/test/ui/consts/promote_const_let.polonius.stderr +++ /dev/null @@ -1,29 +0,0 @@ -error[E0597]: `y` does not live long enough - --> $DIR/promote_const_let.rs:4:9 - | -LL | let x: &'static u32 = { - | - borrow later stored here -LL | let y = 42; -LL | &y - | ^^ borrowed value does not live long enough -LL | }; - | - `y` dropped here while still borrowed - -error[E0716]: temporary value dropped while borrowed - --> $DIR/promote_const_let.rs:6:28 - | -LL | let x: &'static u32 = &{ - | ____________------------____^ - | | | - | | type annotation requires that borrow lasts for `'static` -LL | | let y = 42; -LL | | y -LL | | }; - | |_____^ creates a temporary which is freed while still in use -LL | } - | - temporary value is freed at the end of this statement - -error: aborting due to 2 previous errors - -Some errors have detailed explanations: E0597, E0716. -For more information about an error, try `rustc --explain E0597`. diff --git a/src/test/ui/dropck/dropck_trait_cycle_checked.polonius.stderr b/src/test/ui/dropck/dropck_trait_cycle_checked.polonius.stderr deleted file mode 100644 index 5e93a0234259c..0000000000000 --- a/src/test/ui/dropck/dropck_trait_cycle_checked.polonius.stderr +++ /dev/null @@ -1,78 +0,0 @@ -error[E0597]: `o2` does not live long enough - --> $DIR/dropck_trait_cycle_checked.rs:111:13 - | -LL | o1.set0(&o2); - | ^^^ borrowed value does not live long enough -... -LL | } - | - - | | - | `o2` dropped here while still borrowed - | borrow might be used here, when `o1` is dropped and runs the destructor for type `std::boxed::Box>` - | - = note: values in a scope are dropped in the opposite order they are defined - -error[E0597]: `o3` does not live long enough - --> $DIR/dropck_trait_cycle_checked.rs:112:13 - | -LL | o1.set1(&o3); - | ^^^ borrowed value does not live long enough -... -LL | } - | - - | | - | `o3` dropped here while still borrowed - | borrow might be used here, when `o1` is dropped and runs the destructor for type `std::boxed::Box>` - | - = note: values in a scope are dropped in the opposite order they are defined - -error[E0597]: `o2` does not live long enough - --> $DIR/dropck_trait_cycle_checked.rs:113:13 - | -LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o2` is borrowed for `'static` -... -LL | o2.set0(&o2); - | ^^^ borrowed value does not live long enough -... -LL | } - | - `o2` dropped here while still borrowed - -error[E0597]: `o3` does not live long enough - --> $DIR/dropck_trait_cycle_checked.rs:114:13 - | -LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o3` is borrowed for `'static` -... -LL | o2.set1(&o3); - | ^^^ borrowed value does not live long enough -... -LL | } - | - `o3` dropped here while still borrowed - -error[E0597]: `o1` does not live long enough - --> $DIR/dropck_trait_cycle_checked.rs:115:13 - | -LL | o3.set0(&o1); - | ^^^ borrowed value does not live long enough -LL | o3.set1(&o2); -LL | } - | - - | | - | `o1` dropped here while still borrowed - | borrow might be used here, when `o1` is dropped and runs the destructor for type `std::boxed::Box>` - -error[E0597]: `o2` does not live long enough - --> $DIR/dropck_trait_cycle_checked.rs:116:13 - | -LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -------- cast requires that `o2` is borrowed for `'static` -... -LL | o3.set1(&o2); - | ^^^ borrowed value does not live long enough -LL | } - | - `o2` dropped here while still borrowed - -error: aborting due to 6 previous errors - -For more information about this error, try `rustc --explain E0597`. diff --git a/src/test/ui/generator/ref-escapes-but-not-over-yield.polonius.stderr b/src/test/ui/generator/ref-escapes-but-not-over-yield.polonius.stderr deleted file mode 100644 index 530bf368f676e..0000000000000 --- a/src/test/ui/generator/ref-escapes-but-not-over-yield.polonius.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error[E0597]: `b` does not live long enough - --> $DIR/ref-escapes-but-not-over-yield.rs:11:13 - | -LL | let mut b = move || { - | _________________- -LL | | yield(); -LL | | let b = 5; -LL | | a = &b; - | | ^^ borrowed value does not live long enough -LL | | -LL | | }; - | | - - | | | - | | `b` dropped here while still borrowed - | |_____... and the borrow might be used here, when that temporary is dropped and runs the destructor for generator - | a temporary with access to the borrow is created here ... - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0597`. diff --git a/src/test/ui/nll/get_default.polonius.stderr b/src/test/ui/nll/get_default.polonius.stderr index 2df6d5d61fc46..476d86cfba9c3 100644 --- a/src/test/ui/nll/get_default.polonius.stderr +++ b/src/test/ui/nll/get_default.polonius.stderr @@ -1,6 +1,9 @@ error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable --> $DIR/get_default.rs:32:17 | +LL | fn err(map: &mut Map) -> &String { + | - let's call the lifetime of this reference `'1` +LL | loop { LL | match map.get() { | --- immutable borrow occurs here LL | Some(v) => { @@ -8,7 +11,7 @@ LL | map.set(String::new()); // Both AST and MIR error here | ^^^ mutable borrow occurs here LL | LL | return v; - | - immutable borrow later used here + | - returning this value requires that `*map` is borrowed for `'1` error: aborting due to previous error diff --git a/src/test/ui/nll/loan_ends_mid_block_pair.polonius.stderr b/src/test/ui/nll/loan_ends_mid_block_pair.polonius.stderr deleted file mode 100644 index eb8442b31d7c7..0000000000000 --- a/src/test/ui/nll/loan_ends_mid_block_pair.polonius.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error[E0506]: cannot assign to `data.0` because it is borrowed - --> $DIR/loan_ends_mid_block_pair.rs:12:5 - | -LL | let c = &mut data.0; - | ----------- borrow of `data.0` occurs here -LL | capitalize(c); -LL | data.0 = 'e'; - | ^^^^^^^^^^^^ assignment to borrowed `data.0` occurs here -... -LL | capitalize(c); - | - borrow later used here - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0506`. diff --git a/src/test/ui/nll/polonius/polonius-smoke-test.stderr b/src/test/ui/nll/polonius/polonius-smoke-test.stderr index dbc5b7a019a69..1faf8e2212aab 100644 --- a/src/test/ui/nll/polonius/polonius-smoke-test.stderr +++ b/src/test/ui/nll/polonius/polonius-smoke-test.stderr @@ -17,12 +17,14 @@ LL | let w = y; error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/polonius-smoke-test.rs:19:13 | +LL | pub fn use_while_mut_fr(x: &mut i32) -> &mut i32 { + | - let's call the lifetime of this reference `'1` LL | let y = &mut *x; | ------- borrow of `*x` occurs here LL | let z = x; | ^ move out of `x` occurs here LL | y - | - borrow later used here + | - returning this value requires that `*x` is borrowed for `'1` error[E0505]: cannot move out of `s` because it is borrowed --> $DIR/polonius-smoke-test.rs:43:5 diff --git a/src/test/ui/nll/return-ref-mut-issue-46557.polonius.stderr b/src/test/ui/nll/return-ref-mut-issue-46557.polonius.stderr deleted file mode 100644 index 8e3cf59cffb44..0000000000000 --- a/src/test/ui/nll/return-ref-mut-issue-46557.polonius.stderr +++ /dev/null @@ -1,15 +0,0 @@ -error[E0716]: temporary value dropped while borrowed - --> $DIR/return-ref-mut-issue-46557.rs:4:21 - | -LL | let ref mut x = 1234543; - | ^^^^^^^ creates a temporary which is freed while still in use -LL | x - | - borrow later used here -LL | } - | - temporary value is freed at the end of this statement - | - = note: consider using a `let` binding to create a longer lived value - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0716`. diff --git a/src/test/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.polonius.stderr b/src/test/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.polonius.stderr deleted file mode 100644 index 4b906f75149af..0000000000000 --- a/src/test/ui/unboxed-closures/unboxed-closures-failed-recursive-fn-1.polonius.stderr +++ /dev/null @@ -1,60 +0,0 @@ -error[E0597]: `factorial` does not live long enough - --> $DIR/unboxed-closures-failed-recursive-fn-1.rs:15:17 - | -LL | let f = |x: u32| -> u32 { - | --------------- value captured here -LL | let g = factorial.as_ref().unwrap(); - | ^^^^^^^^^ borrowed value does not live long enough -... -LL | } - | - - | | - | `factorial` dropped here while still borrowed - | borrow might be used here, when `factorial` is dropped and runs the destructor for type `std::option::Option u32>>` - -error[E0506]: cannot assign to `factorial` because it is borrowed - --> $DIR/unboxed-closures-failed-recursive-fn-1.rs:20:5 - | -LL | let f = |x: u32| -> u32 { - | --------------- borrow of `factorial` occurs here -LL | let g = factorial.as_ref().unwrap(); - | --------- borrow occurs due to use in closure -... -LL | factorial = Some(Box::new(f)); - | ^^^^^^^^^ - | | - | assignment to borrowed `factorial` occurs here - | borrow later used here - -error[E0597]: `factorial` does not live long enough - --> $DIR/unboxed-closures-failed-recursive-fn-1.rs:28:17 - | -LL | let f = |x: u32| -> u32 { - | --------------- value captured here -LL | let g = factorial.as_ref().unwrap(); - | ^^^^^^^^^ borrowed value does not live long enough -... -LL | } - | - - | | - | `factorial` dropped here while still borrowed - | borrow might be used here, when `factorial` is dropped and runs the destructor for type `std::option::Option u32>>` - -error[E0506]: cannot assign to `factorial` because it is borrowed - --> $DIR/unboxed-closures-failed-recursive-fn-1.rs:33:5 - | -LL | let f = |x: u32| -> u32 { - | --------------- borrow of `factorial` occurs here -LL | let g = factorial.as_ref().unwrap(); - | --------- borrow occurs due to use in closure -... -LL | factorial = Some(Box::new(f)); - | ^^^^^^^^^ - | | - | assignment to borrowed `factorial` occurs here - | borrow later used here - -error: aborting due to 4 previous errors - -Some errors have detailed explanations: E0506, E0597. -For more information about an error, try `rustc --explain E0506`. From 2180c243214ebce29c45c37020e929924a8520d8 Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Tue, 24 Sep 2019 21:55:49 +0100 Subject: [PATCH 07/17] Make lifetimes in constants live at the point of use --- .../borrow_check/nll/type_check/mod.rs | 64 ++++++++++++------- .../ui/hrtb/due-to-where-clause.nll.stderr | 8 +++ src/test/ui/hrtb/due-to-where-clause.rs | 3 - src/test/ui/hrtb/due-to-where-clause.stderr | 2 +- src/test/ui/nll/promoted-liveness.rs | 8 +++ 5 files changed, 58 insertions(+), 27 deletions(-) create mode 100644 src/test/ui/hrtb/due-to-where-clause.nll.stderr create mode 100644 src/test/ui/nll/promoted-liveness.rs diff --git a/src/librustc_mir/borrow_check/nll/type_check/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/mod.rs index b24ba596d7e93..adc3381a1e762 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/mod.rs @@ -276,7 +276,17 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) { self.super_constant(constant, location); - self.sanitize_type(constant, constant.literal.ty); + let ty = self.sanitize_type(constant, constant.literal.ty); + + self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| { + let live_region_vid = + self.cx.borrowck_context.universal_regions.to_region_vid(live_region); + self.cx + .borrowck_context + .constraints + .liveness_constraints + .add_element(live_region_vid, location); + }); if let Some(annotation_index) = constant.user_ty { if let Err(terr) = self.cx.relate_type_and_user_type( @@ -528,25 +538,37 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { let parent_body = mem::replace(&mut self.body, promoted_body); + // Use new sets of constraints and closure bounds so that we can + // modify their locations. let all_facts = &mut None; let mut constraints = Default::default(); let mut closure_bounds = Default::default(); + let mut liveness_constraints = LivenessValues::new( + Rc::new(RegionValueElements::new(promoted_body)), + ); // Don't try to add borrow_region facts for the promoted MIR - mem::swap(self.cx.borrowck_context.all_facts, all_facts); - // Use a new sets of constraints and closure bounds so that we can - // modify their locations. - mem::swap( - &mut self.cx.borrowck_context.constraints.outlives_constraints, - &mut constraints - ); - mem::swap( - &mut self.cx.borrowck_context.constraints.closure_bounds_mapping, - &mut closure_bounds - ); + let mut swap_constraints = |this: &mut Self| { + mem::swap(this.cx.borrowck_context.all_facts, all_facts); + mem::swap( + &mut this.cx.borrowck_context.constraints.outlives_constraints, + &mut constraints + ); + mem::swap( + &mut this.cx.borrowck_context.constraints.closure_bounds_mapping, + &mut closure_bounds + ); + mem::swap( + &mut this.cx.borrowck_context.constraints.liveness_constraints, + &mut liveness_constraints + ); + }; + + swap_constraints(self); self.visit_body(promoted_body); + if !self.errors_reported { // if verifier failed, don't do further checks to avoid ICEs self.cx.typeck_mir(promoted_body); @@ -554,23 +576,15 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { self.body = parent_body; // Merge the outlives constraints back in, at the given location. - mem::swap(self.cx.borrowck_context.all_facts, all_facts); - mem::swap( - &mut self.cx.borrowck_context.constraints.outlives_constraints, - &mut constraints - ); - mem::swap( - &mut self.cx.borrowck_context.constraints.closure_bounds_mapping, - &mut closure_bounds - ); + swap_constraints(self); let locations = location.to_locations(); for constraint in constraints.outlives().iter() { let mut constraint = *constraint; constraint.locations = locations; if let ConstraintCategory::Return - | ConstraintCategory::UseAsConst - | ConstraintCategory::UseAsStatic = constraint.category + | ConstraintCategory::UseAsConst + | ConstraintCategory::UseAsStatic = constraint.category { // "Returning" from a promoted is an assigment to a // temporary from the user's point of view. @@ -578,6 +592,10 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { } self.cx.borrowck_context.constraints.outlives_constraints.push(constraint) } + for live_region in liveness_constraints.rows() { + self.cx.borrowck_context.constraints.liveness_constraints + .add_element(live_region, location); + } if !closure_bounds.is_empty() { let combined_bounds_mapping = closure_bounds diff --git a/src/test/ui/hrtb/due-to-where-clause.nll.stderr b/src/test/ui/hrtb/due-to-where-clause.nll.stderr new file mode 100644 index 0000000000000..e476047a7a644 --- /dev/null +++ b/src/test/ui/hrtb/due-to-where-clause.nll.stderr @@ -0,0 +1,8 @@ +error: higher-ranked subtype error + --> $DIR/due-to-where-clause.rs:2:5 + | +LL | test::(&mut 42); + | ^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/src/test/ui/hrtb/due-to-where-clause.rs b/src/test/ui/hrtb/due-to-where-clause.rs index 04e2ddd4a6090..1afd15613b51c 100644 --- a/src/test/ui/hrtb/due-to-where-clause.rs +++ b/src/test/ui/hrtb/due-to-where-clause.rs @@ -1,6 +1,3 @@ -// ignore-compare-mode-nll -// ^ This code works in nll mode. - fn main() { test::(&mut 42); //~ ERROR implementation of `Foo` is not general enough } diff --git a/src/test/ui/hrtb/due-to-where-clause.stderr b/src/test/ui/hrtb/due-to-where-clause.stderr index 9fef1e3354399..e4096ec059a6e 100644 --- a/src/test/ui/hrtb/due-to-where-clause.stderr +++ b/src/test/ui/hrtb/due-to-where-clause.stderr @@ -1,5 +1,5 @@ error: implementation of `Foo` is not general enough - --> $DIR/due-to-where-clause.rs:5:5 + --> $DIR/due-to-where-clause.rs:2:5 | LL | test::(&mut 42); | ^^^^^^^^^^^^ implementation of `Foo` is not general enough diff --git a/src/test/ui/nll/promoted-liveness.rs b/src/test/ui/nll/promoted-liveness.rs new file mode 100644 index 0000000000000..e5a8e1e5c2fcc --- /dev/null +++ b/src/test/ui/nll/promoted-liveness.rs @@ -0,0 +1,8 @@ +// Test that promoted that have larger mir bodies than their containing function +// don't cause an ICE. + +// check-pass + +fn main() { + &["0", "1", "2", "3", "4", "5", "6", "7"]; +} From 9b91bef78b15dfecc5144b0575f40a2d84ea795a Mon Sep 17 00:00:00 2001 From: csmoe Date: Thu, 26 Sep 2019 17:30:44 +0000 Subject: [PATCH 08/17] generate ClosureSubsts from SubstsRef --- .../infer/error_reporting/need_type_info.rs | 4 +- src/librustc/infer/mod.rs | 8 +- src/librustc/infer/opaque_types/mod.rs | 4 +- src/librustc/middle/mem_categorization.rs | 11 +-- src/librustc/mir/mod.rs | 4 +- src/librustc/mir/tcx.rs | 2 +- src/librustc/mir/visit.rs | 14 +--- src/librustc/traits/mod.rs | 2 +- src/librustc/traits/project.rs | 3 +- src/librustc/traits/query/dropck_outlives.rs | 1 + src/librustc/traits/select.rs | 24 +++--- src/librustc/ty/instance.rs | 12 +-- src/librustc/ty/layout.rs | 4 +- src/librustc/ty/mod.rs | 4 +- src/librustc/ty/outlives.rs | 2 +- src/librustc/ty/print/obsolete.rs | 9 +-- src/librustc/ty/print/pretty.rs | 6 +- src/librustc/ty/sty.rs | 33 ++++---- src/librustc/ty/subst.rs | 78 +++---------------- src/librustc/ty/util.rs | 6 +- src/librustc/ty/wf.rs | 2 +- .../debuginfo/metadata.rs | 4 +- src/librustc_codegen_ssa/mir/mod.rs | 2 +- src/librustc_codegen_ssa/mir/rvalue.rs | 5 +- src/librustc_metadata/encoder.rs | 2 +- src/librustc_mir/borrow_check/move_errors.rs | 3 +- .../borrow_check/nll/constraint_generation.rs | 9 +-- .../nll/region_infer/error_reporting/mod.rs | 2 +- .../error_reporting/region_name.rs | 2 +- src/librustc_mir/borrow_check/nll/renumber.rs | 14 +--- .../borrow_check/nll/type_check/mod.rs | 12 +-- .../borrow_check/nll/universal_regions.rs | 19 ++--- src/librustc_mir/hair/cx/expr.rs | 5 +- src/librustc_mir/interpret/cast.rs | 2 +- src/librustc_mir/monomorphize/collector.rs | 2 +- src/librustc_mir/shim.rs | 2 +- src/librustc_mir/util/elaborate_drops.rs | 2 +- .../chalk_context/program_clauses/builtin.rs | 5 +- src/librustc_traits/dropck_outlives.rs | 2 +- src/librustc_typeck/check/callee.rs | 4 +- src/librustc_typeck/check/closure.rs | 4 +- src/librustc_typeck/check/coercion.rs | 7 +- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/check/upvar.rs | 9 ++- src/librustc_typeck/collect.rs | 2 +- 45 files changed, 139 insertions(+), 216 deletions(-) diff --git a/src/librustc/infer/error_reporting/need_type_info.rs b/src/librustc/infer/error_reporting/need_type_info.rs index 3e4dfccf34dd5..b89731273f7e2 100644 --- a/src/librustc/infer/error_reporting/need_type_info.rs +++ b/src/librustc/infer/error_reporting/need_type_info.rs @@ -220,7 +220,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let ty_msg = match local_visitor.found_ty { Some(ty::TyS { kind: ty::Closure(def_id, substs), .. }) => { - let fn_sig = ty::ClosureSubsts::from_ref(substs).closure_sig(*def_id, self.tcx); + let fn_sig = substs.as_closure().sig(*def_id, self.tcx); let args = closure_args(&fn_sig); let ret = fn_sig.output().skip_binder().to_string(); format!(" for the closure `fn({}) -> {}`", args, ret) @@ -255,7 +255,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let suffix = match local_visitor.found_ty { Some(ty::TyS { kind: ty::Closure(def_id, substs), .. }) => { - let fn_sig = substs.closure_sig(*def_id, self.tcx); + let fn_sig = substs.as_closure().sig(*def_id, self.tcx); let ret = fn_sig.output().skip_binder().to_string(); if let Some(ExprKind::Closure(_, decl, body_id, ..)) = local_visitor.found_closure { diff --git a/src/librustc/infer/mod.rs b/src/librustc/infer/mod.rs index 750ca4e32a64e..c918df18b2d86 100644 --- a/src/librustc/infer/mod.rs +++ b/src/librustc/infer/mod.rs @@ -1481,9 +1481,9 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { pub fn closure_kind( &self, closure_def_id: DefId, - closure_substs: ty::ClosureSubsts<'tcx>, + closure_substs: SubstsRef<'tcx>, ) -> Option { - let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx); + let closure_kind_ty = closure_substs.as_closure().kind_ty(closure_def_id, self.tcx); let closure_kind_ty = self.shallow_resolve(closure_kind_ty); closure_kind_ty.to_opt_closure_kind() } @@ -1495,9 +1495,9 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { pub fn closure_sig( &self, def_id: DefId, - substs: ty::ClosureSubsts<'tcx>, + substs: SubstsRef<'tcx>, ) -> ty::PolyFnSig<'tcx> { - let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx); + let closure_sig_ty = substs.as_closure().sig_ty(def_id, self.tcx); let closure_sig_ty = self.shallow_resolve(closure_sig_ty); closure_sig_ty.fn_sig(self.tcx) } diff --git a/src/librustc/infer/opaque_types/mod.rs b/src/librustc/infer/opaque_types/mod.rs index 8cc7dbb3c5c91..e7205dd47a617 100644 --- a/src/librustc/infer/opaque_types/mod.rs +++ b/src/librustc/infer/opaque_types/mod.rs @@ -722,11 +722,11 @@ where ty::Closure(def_id, ref substs) => { // Skip lifetime parameters of the enclosing item(s) - for upvar_ty in ty::ClosureSubsts::from_ref(substs).upvar_tys(def_id, self.tcx) { + for upvar_ty in substs.as_closure().upvar_tys(def_id, self.tcx) { upvar_ty.visit_with(self); } - substs.closure_sig_ty(def_id, self.tcx).visit_with(self); + substs.as_closure().sig_ty(def_id, self.tcx).visit_with(self); } ty::Generator(def_id, ref substs, _) => { diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 522c0e55b8594..355bf97e6ed69 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -740,17 +740,18 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { let ty = self.node_ty(fn_hir_id)?; let kind = match ty.kind { ty::Generator(..) => ty::ClosureKind::FnOnce, - ty::Closure(closure_def_id, closure_substs) => { + ty::Closure(closure_def_id, substs) => { match self.infcx { // During upvar inference we may not know the // closure kind, just use the LATTICE_BOTTOM value. Some(infcx) => - infcx.closure_kind(closure_def_id, - ty::ClosureSubsts::from_ref(closure_substs)) - .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM), + infcx.closure_kind( + closure_def_id, + substs + ).unwrap_or(ty::ClosureKind::LATTICE_BOTTOM), None => - closure_substs.closure_kind(closure_def_id, self.tcx), + substs.as_closure().kind(closure_def_id, self.tcx), } } _ => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", ty), diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index 5e12c4dfe75a5..74a042d606ec9 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -15,7 +15,7 @@ use crate::ty::layout::VariantIdx; use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::subst::{Subst, SubstsRef}; use crate::ty::{ - self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt, + self, AdtDef, CanonicalUserTypeAnnotations, GeneratorSubsts, Region, Ty, TyCtxt, UserTypeAnnotationIndex, }; @@ -2188,7 +2188,7 @@ pub enum AggregateKind<'tcx> { /// active field index would identity the field `c` Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option, Option), - Closure(DefId, ClosureSubsts<'tcx>), + Closure(DefId, SubstsRef<'tcx>), Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability), } diff --git a/src/librustc/mir/tcx.rs b/src/librustc/mir/tcx.rs index 44829f670faf9..26f718e858da8 100644 --- a/src/librustc/mir/tcx.rs +++ b/src/librustc/mir/tcx.rs @@ -218,7 +218,7 @@ impl<'tcx> Rvalue<'tcx> { tcx.type_of(def.did).subst(tcx, substs) } AggregateKind::Closure(did, substs) => { - tcx.mk_closure(did, &substs.substs) + tcx.mk_closure(did, substs) } AggregateKind::Generator(did, substs, movability) => { tcx.mk_generator(did, substs, movability) diff --git a/src/librustc/mir/visit.rs b/src/librustc/mir/visit.rs index 1e3b9eb29c79d..8e68952fc706f 100644 --- a/src/librustc/mir/visit.rs +++ b/src/librustc/mir/visit.rs @@ -1,5 +1,5 @@ use crate::ty::subst::SubstsRef; -use crate::ty::{CanonicalUserTypeAnnotation, ClosureSubsts, GeneratorSubsts, Ty}; +use crate::ty::{CanonicalUserTypeAnnotation, GeneratorSubsts, Ty}; use crate::mir::*; use syntax_pos::Span; @@ -221,12 +221,6 @@ macro_rules! make_mir_visitor { self.super_substs(substs); } - fn visit_closure_substs(&mut self, - substs: & $($mutability)? ClosureSubsts<'tcx>, - _: Location) { - self.super_closure_substs(substs); - } - fn visit_generator_substs(&mut self, substs: & $($mutability)? GeneratorSubsts<'tcx>, _: Location) { @@ -618,7 +612,7 @@ macro_rules! make_mir_visitor { _, closure_substs ) => { - self.visit_closure_substs(closure_substs, location); + self.visit_substs(closure_substs, location); } AggregateKind::Generator( _, @@ -838,10 +832,6 @@ macro_rules! make_mir_visitor { _substs: & $($mutability)? GeneratorSubsts<'tcx>) { } - fn super_closure_substs(&mut self, - _substs: & $($mutability)? ClosureSubsts<'tcx>) { - } - // Convenience methods fn visit_location(&mut self, body: & $($mutability)? Body<'tcx>, location: Location) { diff --git a/src/librustc/traits/mod.rs b/src/librustc/traits/mod.rs index accbbe3643ea1..7f194c2fbbc0f 100644 --- a/src/librustc/traits/mod.rs +++ b/src/librustc/traits/mod.rs @@ -619,7 +619,7 @@ pub struct VtableGeneratorData<'tcx, N> { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)] pub struct VtableClosureData<'tcx, N> { pub closure_def_id: DefId, - pub substs: ty::ClosureSubsts<'tcx>, + pub substs: SubstsRef<'tcx>, /// Nested obligations. This can be non-empty if the closure /// signature contains associated types. pub nested: Vec diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs index 57077bcdffa72..a7bb29c699e0e 100644 --- a/src/librustc/traits/project.rs +++ b/src/librustc/traits/project.rs @@ -1334,7 +1334,8 @@ fn confirm_closure_candidate<'cx, 'tcx>( ) -> Progress<'tcx> { let tcx = selcx.tcx(); let infcx = selcx.infcx(); - let closure_sig_ty = vtable.substs.closure_sig_ty(vtable.closure_def_id, tcx); + let closure_sig_ty = vtable.substs + .as_closure().sig_ty(vtable.closure_def_id, tcx); let closure_sig = infcx.shallow_resolve(closure_sig_ty).fn_sig(tcx); let Normalized { value: closure_sig, diff --git a/src/librustc/traits/query/dropck_outlives.rs b/src/librustc/traits/query/dropck_outlives.rs index aa30541610e9b..eaf5971e4592f 100644 --- a/src/librustc/traits/query/dropck_outlives.rs +++ b/src/librustc/traits/query/dropck_outlives.rs @@ -213,6 +213,7 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { // check if *any* of those are trivial. ty::Tuple(ref tys) => tys.iter().all(|t| trivial_dropck_outlives(tcx, t.expect_ty())), ty::Closure(def_id, ref substs) => substs + .as_closure() .upvar_tys(def_id, tcx) .all(|t| trivial_dropck_outlives(tcx, t)), diff --git a/src/librustc/traits/select.rs b/src/librustc/traits/select.rs index 3450f3fc86592..9434412b020e9 100644 --- a/src/librustc/traits/select.rs +++ b/src/librustc/traits/select.rs @@ -2051,8 +2051,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { "assemble_unboxed_candidates: kind={:?} obligation={:?}", kind, obligation ); - match self.infcx.closure_kind(closure_def_id, - ty::ClosureSubsts::from_ref(closure_substs)) { + match self.infcx.closure_kind( + closure_def_id, + closure_substs + ) { Some(closure_kind) => { debug!( "assemble_unboxed_candidates: closure_kind = {:?}", @@ -2670,7 +2672,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Closure(def_id, substs) => { // (*) binder moved here Where(ty::Binder::bind( - substs.upvar_tys(def_id, self.tcx()).collect(), + substs.as_closure().upvar_tys(def_id, self.tcx()).collect(), )) } @@ -2754,7 +2756,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { tys.iter().map(|k| k.expect_ty()).collect() } - ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(), + ty::Closure(def_id, ref substs) => substs.as_closure() + .upvar_tys(def_id, self.tcx()) + .collect(), ty::Generator(def_id, ref substs, _) => { let witness = substs.witness(def_id, self.tcx()); @@ -3376,14 +3380,17 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligations.push(Obligation::new( obligation.cause.clone(), obligation.param_env, - ty::Predicate::ClosureKind(closure_def_id, - ty::ClosureSubsts::from_ref(substs.clone()), kind), + ty::Predicate::ClosureKind( + closure_def_id, + substs, + kind + ), )); } Ok(VtableClosureData { closure_def_id, - substs: ty::ClosureSubsts::from_ref(substs), + substs: substs, nested: obligations, }) } @@ -3878,8 +3885,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})", obligation, closure_def_id, substs, ); - let closure_type = self.infcx.closure_sig(closure_def_id, - ty::ClosureSubsts::from_ref(substs)); + let closure_type = self.infcx.closure_sig(closure_def_id, substs); debug!( "closure_trait_ref_unnormalized: closure_type = {:?}", diff --git a/src/librustc/ty/instance.rs b/src/librustc/ty/instance.rs index c0cd1fd0614c5..34f806b15c0c6 100644 --- a/src/librustc/ty/instance.rs +++ b/src/librustc/ty/instance.rs @@ -59,7 +59,7 @@ impl<'tcx> Instance<'tcx> { // Shims currently have type FnPtr. Not sure this should remain. ty::FnPtr(_) => ty.fn_sig(tcx), ty::Closure(def_id, substs) => { - let sig = substs.closure_sig(def_id, tcx); + let sig = substs.as_closure().sig(def_id, tcx); let env_ty = tcx.closure_env_ty(def_id, substs).unwrap(); sig.map_bound(|sig| tcx.mk_fn_sig( @@ -315,14 +315,14 @@ impl<'tcx> Instance<'tcx> { pub fn resolve_closure( tcx: TyCtxt<'tcx>, def_id: DefId, - substs: ty::ClosureSubsts<'tcx>, + substs: ty::SubstsRef<'tcx>, requested_kind: ty::ClosureKind, ) -> Instance<'tcx> { - let actual_kind = substs.closure_kind(def_id, tcx); + let actual_kind = substs.as_closure().kind(def_id, tcx); match needs_fn_once_adapter_shim(actual_kind, requested_kind) { - Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs.substs), - _ => Instance::new(def_id, substs.substs) + Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs), + _ => Instance::new(def_id, substs) } } @@ -348,7 +348,7 @@ impl<'tcx> Instance<'tcx> { let self_ty = tcx.mk_closure(closure_did, substs); - let sig = substs.closure_sig(closure_did, tcx); + let sig = substs.as_closure().sig(closure_did, tcx); let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig); assert_eq!(sig.inputs().len(), 1); let substs = tcx.mk_substs_trait(self_ty, &[sig.inputs()[0].into()]); diff --git a/src/librustc/ty/layout.rs b/src/librustc/ty/layout.rs index 6ab4f4c6112f7..d142aaeaf833e 100644 --- a/src/librustc/ty/layout.rs +++ b/src/librustc/ty/layout.rs @@ -674,7 +674,7 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { ty::Generator(def_id, substs, _) => self.generator_layout(ty, def_id, &substs)?, ty::Closure(def_id, ref substs) => { - let tys = substs.upvar_tys(def_id, tcx); + let tys = substs.as_closure().upvar_tys(def_id, tcx); univariant(&tys.map(|ty| self.layout_of(ty)).collect::, _>>()?, &ReprOptions::default(), StructKind::AlwaysSized)? @@ -2147,7 +2147,7 @@ where // Tuples, generators and closures. ty::Closure(def_id, ref substs) => { - substs.upvar_tys(def_id, tcx).nth(i).unwrap() + substs.as_closure().upvar_tys(def_id, tcx).nth(i).unwrap() } ty::Generator(def_id, ref substs, _) => { diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 731aca854a422..20c18c14ead45 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -1110,7 +1110,7 @@ pub enum Predicate<'tcx> { /// No direct syntax. May be thought of as `where T: FnFoo<...>` /// for some substitutions `...` and `T` being a closure type. /// Satisfied (or refuted) once we know the closure's kind. - ClosureKind(DefId, ClosureSubsts<'tcx>, ClosureKind), + ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind), /// `T1 <: T2` Subtype(PolySubtypePredicate<'tcx>), @@ -1457,7 +1457,7 @@ impl<'tcx> Predicate<'tcx> { WalkTysIter::None } ty::Predicate::ClosureKind(_closure_def_id, closure_substs, _kind) => { - WalkTysIter::Types(closure_substs.substs.types()) + WalkTysIter::Types(closure_substs.types()) } ty::Predicate::ConstEvaluatable(_, substs) => { WalkTysIter::Types(substs.types()) diff --git a/src/librustc/ty/outlives.rs b/src/librustc/ty/outlives.rs index 9a2e30f7f45ed..3ea767d511598 100644 --- a/src/librustc/ty/outlives.rs +++ b/src/librustc/ty/outlives.rs @@ -62,7 +62,7 @@ impl<'tcx> TyCtxt<'tcx> { // projection). match ty.kind { ty::Closure(def_id, ref substs) => { - for upvar_ty in substs.upvar_tys(def_id, *self) { + for upvar_ty in substs.as_closure().upvar_tys(def_id, *self) { self.compute_components(upvar_ty, out); } } diff --git a/src/librustc/ty/print/obsolete.rs b/src/librustc/ty/print/obsolete.rs index 6f97006c71e3b..21c018d9ee6de 100644 --- a/src/librustc/ty/print/obsolete.rs +++ b/src/librustc/ty/print/obsolete.rs @@ -154,13 +154,8 @@ impl DefPathBasedNames<'tcx> { self.push_type_name(sig.output(), output, debug); } } - ty::Generator(def_id, GeneratorSubsts { ref substs }, _) => { - self.push_def_path(def_id, output); - let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id)); - let substs = substs.truncate_to(self.tcx, generics); - self.push_generic_params(substs, iter::empty(), output, debug); - } - ty::Closure(def_id, substs) => { + ty::Generator(def_id, GeneratorSubsts { substs }, _) + | ty::Closure(def_id, substs) => { self.push_def_path(def_id, output); let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id)); let substs = substs.truncate_to(self.tcx, generics); diff --git a/src/librustc/ty/print/pretty.rs b/src/librustc/ty/print/pretty.rs index 0adb75626975f..ad4be788dae4e 100644 --- a/src/librustc/ty/print/pretty.rs +++ b/src/librustc/ty/print/pretty.rs @@ -649,7 +649,7 @@ pub trait PrettyPrinter<'tcx>: p!(in_binder(&types)); } ty::Closure(did, substs) => { - let upvar_tys = substs.upvar_tys(did, self.tcx()); + let upvar_tys = substs.as_closure().upvar_tys(did, self.tcx()); p!(write("[closure")); // FIXME(eddyb) should use `def_span`. @@ -689,8 +689,8 @@ pub trait PrettyPrinter<'tcx>: if self.tcx().sess.verbose() { p!(write( " closure_kind_ty={:?} closure_sig_ty={:?}", - substs.closure_kind_ty(did, self.tcx()), - substs.closure_sig_ty(did, self.tcx()) + substs.as_closure().kind(did, self.tcx()), + substs.as_closure().sig_ty(did, self.tcx()) )); } diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs index 05c6ec6f97a51..c3c48c4d876d3 100644 --- a/src/librustc/ty/sty.rs +++ b/src/librustc/ty/sty.rs @@ -304,8 +304,8 @@ static_assert_size!(TyKind<'_>, 24); /// type parameters is similar, but the role of CK and CS are /// different. CK represents the "yield type" and CS represents the /// "return type" of the generator. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, - Debug, RustcEncodable, RustcDecodable, HashStable)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, + RustcEncodable, RustcDecodable, HashStable)] pub struct ClosureSubsts<'tcx> { /// Lifetime and type parameters from the enclosing function, /// concatenated with the types of the upvars. @@ -317,18 +317,13 @@ pub struct ClosureSubsts<'tcx> { /// Struct returned by `split()`. Note that these are subslices of the /// parent slice and not canonical substs themselves. -pub(crate) struct SplitClosureSubsts<'tcx> { - pub(crate) closure_kind_ty: Ty<'tcx>, - pub(crate) closure_sig_ty: Ty<'tcx>, - pub(crate) upvar_kinds: &'tcx [GenericArg<'tcx>], +struct SplitClosureSubsts<'tcx> { + closure_kind_ty: Ty<'tcx>, + closure_sig_ty: Ty<'tcx>, + upvar_kinds: &'tcx [GenericArg<'tcx>], } impl<'tcx> ClosureSubsts<'tcx> { - // FIXME(csmoe): remove this method once the migration is done. - pub fn from_ref(substs: SubstsRef<'tcx>) -> Self { - Self { substs } - } - /// Divides the closure substs into their respective /// components. Single source of truth with respect to the /// ordering. @@ -361,7 +356,7 @@ impl<'tcx> ClosureSubsts<'tcx> { /// Returns the closure kind for this closure; may return a type /// variable during inference. To get the closure kind during /// inference, use `infcx.closure_kind(def_id, substs)`. - pub fn closure_kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { + pub fn kind_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { self.split(def_id, tcx).closure_kind_ty } @@ -369,7 +364,7 @@ impl<'tcx> ClosureSubsts<'tcx> { /// closure; may contain type variables during inference. To get /// the closure signature during inference, use /// `infcx.fn_sig(def_id)`. - pub fn closure_sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { + pub fn sig_ty(self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'tcx> { self.split(def_id, tcx).closure_sig_ty } @@ -378,7 +373,7 @@ impl<'tcx> ClosureSubsts<'tcx> { /// there are no type variables. /// /// If you have an inference context, use `infcx.closure_kind()`. - pub fn closure_kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind { + pub fn kind(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind { self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap() } @@ -387,8 +382,8 @@ impl<'tcx> ClosureSubsts<'tcx> { /// there are no type variables. /// /// If you have an inference context, use `infcx.closure_sig()`. - pub fn closure_sig(self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { - let ty = self.closure_sig_ty(def_id, tcx); + pub fn sig(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { + let ty = self.sig_ty(def_id, tcx); match ty.kind { ty::FnPtr(sig) => sig, _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty.kind), @@ -573,7 +568,7 @@ impl<'tcx> GeneratorSubsts<'tcx> { #[derive(Debug, Copy, Clone)] pub enum UpvarSubsts<'tcx> { - Closure(ClosureSubsts<'tcx>), + Closure(SubstsRef<'tcx>), Generator(GeneratorSubsts<'tcx>), } @@ -582,10 +577,10 @@ impl<'tcx> UpvarSubsts<'tcx> { pub fn upvar_tys( self, def_id: DefId, - tcx: TyCtxt<'_>, + tcx: TyCtxt<'tcx>, ) -> impl Iterator> + 'tcx { let upvar_kinds = match self { - UpvarSubsts::Closure(substs) => substs.split(def_id, tcx).upvar_kinds, + UpvarSubsts::Closure(substs) => substs.as_closure().split(def_id, tcx).upvar_kinds, UpvarSubsts::Generator(substs) => substs.split(def_id, tcx).upvar_kinds, }; upvar_kinds.iter().map(|t| { diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs index 05042ccf9a1d6..537192b0a2e58 100644 --- a/src/librustc/ty/subst.rs +++ b/src/librustc/ty/subst.rs @@ -5,7 +5,7 @@ use crate::infer::canonical::Canonical; use crate::ty::{self, Lift, List, Ty, TyCtxt, InferConst, ParamConst}; use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor}; use crate::mir::interpret::ConstValue; -use crate::ty::sty::SplitClosureSubsts; +use crate::ty::sty::ClosureSubsts; use rustc_serialize::{self, Encodable, Encoder, Decodable, Decoder}; use syntax_pos::{Span, DUMMY_SP}; @@ -184,6 +184,16 @@ pub type InternalSubsts<'tcx> = List>; pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; impl<'a, 'tcx> InternalSubsts<'tcx> { + /// Interpret these substitutions as the substitutions of a closure type. + /// Closure substitutions have a particular structure controlled by the + /// compiler that encodes information like the signature and closure kind; + /// see `ty::ClosureSubsts` struct for more comments. + pub fn as_closure(&'a self) -> ClosureSubsts<'a> { + ClosureSubsts { + substs: self, + } + } + /// Creates a `InternalSubsts` that maps each generic parameter to itself. pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { Self::for_item(tcx, def_id, |param, _| { @@ -380,72 +390,6 @@ impl<'a, 'tcx> InternalSubsts<'tcx> { pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { tcx.mk_substs(self.iter().take(generics.count()).cloned()) } - - /// Divides the closure substs into their respective - /// components. Single source of truth with respect to the - /// ordering. - fn split(&self, def_id: DefId, tcx: TyCtxt<'_>) -> SplitClosureSubsts<'_> { - let generics = tcx.generics_of(def_id); - let parent_len = generics.parent_count; - SplitClosureSubsts { - closure_kind_ty: self.type_at(parent_len), - closure_sig_ty: self.type_at(parent_len + 1), - upvar_kinds: &self[parent_len + 2..], - } - } - - #[inline] - pub fn upvar_tys( - &'a self, - def_id: DefId, - tcx: TyCtxt<'_>, - ) -> impl Iterator> + 'a { - let SplitClosureSubsts { upvar_kinds, .. } = self.split(def_id, tcx); - upvar_kinds.iter().map(|t| { - if let GenericArgKind::Type(ty) = t.unpack() { - ty - } else { - bug!("upvar should be type") - } - }) - } - - /// Returns the closure kind for this closure; may return a type - /// variable during inference. To get the closure kind during - /// inference, use `infcx.closure_kind(def_id, substs)`. - pub fn closure_kind_ty(&'a self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'a> { - self.split(def_id, tcx).closure_kind_ty - } - - /// Returns the type representing the closure signature for this - /// closure; may contain type variables during inference. To get - /// the closure signature during inference, use - /// `infcx.fn_sig(def_id)`. - pub fn closure_sig_ty(&'a self, def_id: DefId, tcx: TyCtxt<'_>) -> Ty<'a> { - self.split(def_id, tcx).closure_sig_ty - } - - /// Returns the closure kind for this closure; only usable outside - /// of an inference context, because in that context we know that - /// there are no type variables. - /// - /// If you have an inference context, use `infcx.closure_kind()`. - pub fn closure_kind(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::ClosureKind { - self.split(def_id, tcx).closure_kind_ty.to_opt_closure_kind().unwrap() - } - - /// Extracts the signature from the closure; only usable outside - /// of an inference context, because in that context we know that - /// there are no type variables. - /// - /// If you have an inference context, use `infcx.closure_sig()`. - pub fn closure_sig(&'a self, def_id: DefId, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'a> { - let ty = self.closure_sig_ty(def_id, tcx); - match ty.kind { - ty::FnPtr(sig) => sig, - _ => bug!("closure_sig_ty is not a fn-ptr: {:?}", ty.kind), - } - } } impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { diff --git a/src/librustc/ty/util.rs b/src/librustc/ty/util.rs index 05f0d164cc1c3..d0e95a18c59fc 100644 --- a/src/librustc/ty/util.rs +++ b/src/librustc/ty/util.rs @@ -647,7 +647,7 @@ impl<'tcx> TyCtxt<'tcx> { { let closure_ty = self.mk_closure(closure_def_id, closure_substs); let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv); - let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self); + let closure_kind_ty = closure_substs.as_closure().kind_ty(closure_def_id, self); let closure_kind = closure_kind_ty.to_opt_closure_kind()?; let env_ty = match closure_kind { ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty), @@ -1108,7 +1108,9 @@ fn needs_drop_raw<'tcx>(tcx: TyCtxt<'tcx>, query: ty::ParamEnvAnd<'tcx, Ty<'tcx> // Structural recursion. ty::Array(ty, _) | ty::Slice(ty) => needs_drop(ty), - ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop), + ty::Closure(def_id, ref substs) => { + substs.as_closure().upvar_tys(def_id, tcx).any(needs_drop) + } // Pessimistically assume that all generators will require destructors // as we don't know if a destructor is a noop or not until after the MIR diff --git a/src/librustc/ty/wf.rs b/src/librustc/ty/wf.rs index 020926e7c8de8..ecb075e30b14d 100644 --- a/src/librustc/ty/wf.rs +++ b/src/librustc/ty/wf.rs @@ -347,7 +347,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // anyway, except via auto trait matching (which // only inspects the upvar types). subtys.skip_current_subtree(); // subtree handled by compute_projection - for upvar_ty in substs.upvar_tys(def_id, self.infcx.tcx) { + for upvar_ty in substs.as_closure().upvar_tys(def_id, self.infcx.tcx) { self.compute(upvar_ty); } } diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index 544d6794e2191..e69f4b6aca19a 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -6,7 +6,7 @@ use super::utils::{debug_context, DIB, span_start, get_namespace_for_item, create_DIArray, is_node_local_to_unit}; use super::namespace::mangled_name_of_instance; use super::type_names::compute_debuginfo_type_name; -use super::{CrateDebugContext}; +use super::CrateDebugContext; use crate::abi; use crate::value::Value; use rustc_codegen_ssa::traits::*; @@ -682,7 +682,7 @@ pub fn type_metadata( } ty::Closure(def_id, substs) => { - let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx).collect(); + let upvar_tys : Vec<_> = substs.as_closure().upvar_tys(def_id, cx.tcx).collect(); let containing_scope = get_namespace_for_item(cx, def_id); prepare_tuple_metadata(cx, t, diff --git a/src/librustc_codegen_ssa/mir/mod.rs b/src/librustc_codegen_ssa/mir/mod.rs index 30d519c8733cc..378bbd0cc3856 100644 --- a/src/librustc_codegen_ssa/mir/mod.rs +++ b/src/librustc_codegen_ssa/mir/mod.rs @@ -616,7 +616,7 @@ fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( let (def_id, upvar_substs) = match closure_layout.ty.kind { ty::Closure(def_id, substs) => (def_id, - UpvarSubsts::Closure(rustc::ty::ClosureSubsts::from_ref(substs))), + UpvarSubsts::Closure(substs)), ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)), _ => bug!("upvar debuginfo with non-closure arg0 type `{}`", closure_layout.ty) }; diff --git a/src/librustc_codegen_ssa/mir/rvalue.rs b/src/librustc_codegen_ssa/mir/rvalue.rs index 9cc21a28b2737..6ffa561f3fecf 100644 --- a/src/librustc_codegen_ssa/mir/rvalue.rs +++ b/src/librustc_codegen_ssa/mir/rvalue.rs @@ -201,8 +201,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { match operand.layout.ty.kind { ty::Closure(def_id, substs) => { let instance = Instance::resolve_closure( - bx.cx().tcx(), def_id, - rustc::ty::ClosureSubsts::from_ref(substs), + bx.cx().tcx(), + def_id, + substs, ty::ClosureKind::FnOnce); OperandValue::Immediate(bx.cx().get_fn(instance)) } diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 9beeacbe72d80..598f7dcf17d31 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -1437,7 +1437,7 @@ impl EncodeContext<'tcx> { } ty::Closure(def_id, substs) => { - let sig = substs.closure_sig(def_id, self.tcx); + let sig = substs.as_closure().sig(def_id, self.tcx); let data = ClosureData { sig: self.lazy(sig) }; EntryKind::Closure(self.lazy(data)) } diff --git a/src/librustc_mir/borrow_check/move_errors.rs b/src/librustc_mir/borrow_check/move_errors.rs index bf5bddadd16f1..431361fa5a87b 100644 --- a/src/librustc_mir/borrow_check/move_errors.rs +++ b/src/librustc_mir/borrow_check/move_errors.rs @@ -341,7 +341,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { ty::Closure(def_id, closure_substs) if def_id == self.mir_def_id && upvar_field.is_some() => { - let closure_kind_ty = closure_substs.closure_kind_ty(def_id, self.infcx.tcx); + let closure_kind_ty = closure_substs + .as_closure().kind_ty(def_id, self.infcx.tcx); let closure_kind = closure_kind_ty.to_opt_closure_kind(); let capture_description = match closure_kind { Some(ty::ClosureKind::Fn) => { diff --git a/src/librustc_mir/borrow_check/nll/constraint_generation.rs b/src/librustc_mir/borrow_check/nll/constraint_generation.rs index 1e5f613aedc23..0e22ead62d1c0 100644 --- a/src/librustc_mir/borrow_check/nll/constraint_generation.rs +++ b/src/librustc_mir/borrow_check/nll/constraint_generation.rs @@ -12,7 +12,7 @@ use rustc::mir::{ SourceInfo, Statement, StatementKind, Terminator, TerminatorKind, UserTypeProjection, }; use rustc::ty::fold::TypeFoldable; -use rustc::ty::{self, ClosureSubsts, GeneratorSubsts, RegionVid, Ty}; +use rustc::ty::{self, GeneratorSubsts, RegionVid, Ty}; use rustc::ty::subst::SubstsRef; pub(super) fn generate_constraints<'cx, 'tcx>( @@ -98,13 +98,6 @@ impl<'cg, 'cx, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cg, 'cx, 'tcx> { self.super_generator_substs(substs); } - /// We sometimes have `closure_substs` within an rvalue, or within a - /// call. Make them live at the location where they appear. - fn visit_closure_substs(&mut self, substs: &ClosureSubsts<'tcx>, location: Location) { - self.add_regular_live_constraint(*substs, location); - self.super_closure_substs(substs); - } - fn visit_statement( &mut self, statement: &Statement<'tcx>, diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs index e29e9232012bc..a386d15c94284 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs @@ -800,7 +800,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { if let Some(ty::ReFree(free_region)) = self.to_error_region(fr) { if let ty::BoundRegion::BrEnv = free_region.bound_region { if let DefiningTy::Closure(def_id, substs) = self.universal_regions.defining_ty { - let closure_kind_ty = substs.closure_kind_ty(def_id, infcx.tcx); + let closure_kind_ty = substs.as_closure().kind_ty(def_id, infcx.tcx); return Some(ty::ClosureKind::FnMut) == closure_kind_ty.to_opt_closure_kind(); } } diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index 8b1ba59c6df7e..6fb976e0d84b2 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -300,7 +300,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { }; let region_name = self.synthesize_region_name(renctx); - let closure_kind_ty = substs.closure_kind_ty(def_id, tcx); + let closure_kind_ty = substs.as_closure().kind_ty(def_id, tcx); let note = match closure_kind_ty.to_opt_closure_kind() { Some(ty::ClosureKind::Fn) => { "closure implements `Fn`, so references to captured variables \ diff --git a/src/librustc_mir/borrow_check/nll/renumber.rs b/src/librustc_mir/borrow_check/nll/renumber.rs index c479c38f30c7e..48c08da76982f 100644 --- a/src/librustc_mir/borrow_check/nll/renumber.rs +++ b/src/librustc_mir/borrow_check/nll/renumber.rs @@ -1,5 +1,5 @@ use rustc::ty::subst::SubstsRef; -use rustc::ty::{self, ClosureSubsts, GeneratorSubsts, Ty, TypeFoldable}; +use rustc::ty::{self, GeneratorSubsts, Ty, TypeFoldable}; use rustc::mir::{Location, Body, Promoted}; use rustc::mir::visit::{MutVisitor, TyContext}; use rustc::infer::{InferCtxt, NLLRegionVariableOrigin}; @@ -96,16 +96,4 @@ impl<'a, 'tcx> MutVisitor<'tcx> for NLLVisitor<'a, 'tcx> { debug!("visit_generator_substs: substs={:?}", substs); } - - fn visit_closure_substs(&mut self, substs: &mut ClosureSubsts<'tcx>, location: Location) { - debug!( - "visit_closure_substs(substs={:?}, location={:?})", - substs, - location - ); - - *substs = self.renumber_regions(substs); - - debug!("visit_closure_substs: substs={:?}", substs); - } } diff --git a/src/librustc_mir/borrow_check/nll/type_check/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/mod.rs index fa326062fe2c9..698dd6d6522bf 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/mod.rs @@ -763,10 +763,10 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { ty::Adt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[VariantIdx::new(0)], substs), ty::Closure(def_id, substs) => { - return match substs.upvar_tys(def_id, tcx).nth(field.index()) { + return match substs.as_closure().upvar_tys(def_id, tcx).nth(field.index()) { Some(ty) => Ok(ty), None => Err(FieldAccessError::OutOfRange { - field_count: substs.upvar_tys(def_id, tcx).count(), + field_count: substs.as_closure().upvar_tys(def_id, tcx).count(), }), } } @@ -1934,10 +1934,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } AggregateKind::Closure(def_id, substs) => { - match substs.upvar_tys(def_id, tcx).nth(field_index) { + match substs.as_closure().upvar_tys(def_id, tcx).nth(field_index) { Some(ty) => Ok(ty), None => Err(FieldAccessError::OutOfRange { - field_count: substs.upvar_tys(def_id, tcx).count(), + field_count: substs.as_closure().upvar_tys(def_id, tcx).count(), }), } } @@ -2050,7 +2050,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => { let sig = match op.ty(body, tcx).kind { ty::Closure(def_id, substs) => { - substs.closure_sig_ty(def_id, tcx).fn_sig(tcx) + substs.as_closure().sig_ty(def_id, tcx).fn_sig(tcx) } _ => bug!(), }; @@ -2522,7 +2522,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // desugaring. A closure gets desugared to a struct, and // these extra requirements are basically like where // clauses on the struct. - AggregateKind::Closure(def_id, ty::ClosureSubsts { substs }) + AggregateKind::Closure(def_id, substs) | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => { self.prove_closure_bounds(tcx, *def_id, substs, location) } diff --git a/src/librustc_mir/borrow_check/nll/universal_regions.rs b/src/librustc_mir/borrow_check/nll/universal_regions.rs index 80ed90ede4dd6..1fa19a2f9f080 100644 --- a/src/librustc_mir/borrow_check/nll/universal_regions.rs +++ b/src/librustc_mir/borrow_check/nll/universal_regions.rs @@ -19,7 +19,7 @@ use rustc::infer::{InferCtxt, NLLRegionVariableOrigin}; use rustc::middle::lang_items; use rustc::ty::fold::TypeFoldable; use rustc::ty::subst::{InternalSubsts, SubstsRef, Subst}; -use rustc::ty::{self, ClosureSubsts, GeneratorSubsts, RegionVid, Ty, TyCtxt}; +use rustc::ty::{self, GeneratorSubsts, RegionVid, Ty, TyCtxt}; use rustc::util::nodemap::FxHashMap; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; use rustc_errors::DiagnosticBuilder; @@ -85,7 +85,7 @@ pub struct UniversalRegions<'tcx> { pub enum DefiningTy<'tcx> { /// The MIR is a closure. The signature is found via /// `ClosureSubsts::closure_sig_ty`. - Closure(DefId, ty::ClosureSubsts<'tcx>), + Closure(DefId, SubstsRef<'tcx>), /// The MIR is a generator. The signature is that generators take /// no parameters and return the result of @@ -109,7 +109,9 @@ impl<'tcx> DefiningTy<'tcx> { /// match up with the upvar order in the HIR, typesystem, and MIR. pub fn upvar_tys(self, tcx: TyCtxt<'tcx>) -> impl Iterator> + 'tcx { match self { - DefiningTy::Closure(def_id, substs) => Either::Left(substs.upvar_tys(def_id, tcx)), + DefiningTy::Closure(def_id, substs) => Either::Left( + substs.as_closure().upvar_tys(def_id, tcx) + ), DefiningTy::Generator(def_id, substs, _) => { Either::Right(Either::Left(substs.upvar_tys(def_id, tcx))) } @@ -312,7 +314,7 @@ impl<'tcx> UniversalRegions<'tcx> { err.note(&format!( "defining type: {:?} with closure substs {:#?}", def_id, - &substs.substs[..] + &substs[..] )); // FIXME: It'd be nice to print the late-bound regions @@ -509,8 +511,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { .replace_free_regions_with_nll_infer_vars(FR, &defining_ty); match defining_ty.kind { - ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, - rustc::ty::ClosureSubsts::from_ref(substs)), + ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs), ty::Generator(def_id, substs, movability) => { DefiningTy::Generator(def_id, substs, movability) } @@ -547,7 +548,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id); let identity_substs = InternalSubsts::identity_for_item(tcx, closure_base_def_id); let fr_substs = match defining_ty { - DefiningTy::Closure(_, ClosureSubsts { ref substs }) + DefiningTy::Closure(_, ref substs) | DefiningTy::Generator(_, GeneratorSubsts { ref substs }, _) => { // In the case of closures, we rely on the fact that // the first N elements in the ClosureSubsts are @@ -583,9 +584,9 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { match defining_ty { DefiningTy::Closure(def_id, substs) => { assert_eq!(self.mir_def_id, def_id); - let closure_sig = substs.closure_sig_ty(def_id, tcx).fn_sig(tcx); + let closure_sig = substs.as_closure().sig_ty(def_id, tcx).fn_sig(tcx); let inputs_and_output = closure_sig.inputs_and_output(); - let closure_ty = tcx.closure_env_ty(def_id, substs.substs).unwrap(); + let closure_ty = tcx.closure_env_ty(def_id, substs).unwrap(); ty::Binder::fuse( closure_ty, inputs_and_output, diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs index e4d26bda40f71..461cc063a475b 100644 --- a/src/librustc_mir/hair/cx/expr.rs +++ b/src/librustc_mir/hair/cx/expr.rs @@ -507,7 +507,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( let closure_ty = cx.tables().expr_ty(expr); let (def_id, substs, movability) = match closure_ty.kind { ty::Closure(def_id, substs) => (def_id, - UpvarSubsts::Closure(rustc::ty::ClosureSubsts::from_ref(substs)), None), + UpvarSubsts::Closure(substs), None), ty::Generator(def_id, substs, movability) => { (def_id, UpvarSubsts::Generator(substs), Some(movability)) } @@ -1003,8 +1003,7 @@ fn convert_var( let region = cx.tcx.mk_region(region); let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.kind { - match cx.infcx.closure_kind(closure_def_id, - rustc::ty::ClosureSubsts::from_ref(closure_substs)).unwrap() { + match cx.infcx.closure_kind(closure_def_id, closure_substs).unwrap() { ty::ClosureKind::Fn => { let ref_closure_ty = cx.tcx.mk_ref(region, ty::TypeAndMut { diff --git a/src/librustc_mir/interpret/cast.rs b/src/librustc_mir/interpret/cast.rs index 943054cc6964d..d120412c901a6 100644 --- a/src/librustc_mir/interpret/cast.rs +++ b/src/librustc_mir/interpret/cast.rs @@ -75,7 +75,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let instance = ty::Instance::resolve_closure( *self.tcx, def_id, - rustc::ty::ClosureSubsts::from_ref(substs), + substs, ty::ClosureKind::FnOnce, ); let fn_ptr = self.memory.create_fn_alloc(FnVal::Instance(instance)); diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 21aea5593ee4b..79403e3a7e85a 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -582,7 +582,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> { ty::Closure(def_id, substs) => { let instance = Instance::resolve_closure( self.tcx, def_id, - rustc::ty::ClosureSubsts::from_ref(substs), ty::ClosureKind::FnOnce); + substs, ty::ClosureKind::FnOnce); if should_monomorphize_locally(self.tcx, &instance) { self.output.push(create_fn_mono_item(instance)); } diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs index 4fae0976ffb5a..28ff1e59d5b11 100644 --- a/src/librustc_mir/shim.rs +++ b/src/librustc_mir/shim.rs @@ -320,7 +320,7 @@ fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) - ty::Closure(def_id, substs) => { builder.tuple_like_shim( dest, src, - substs.upvar_tys(def_id, tcx) + substs.as_closure().upvar_tys(def_id, tcx) ) } ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()), diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs index e1015edfa8eec..0f7199f1c4ec2 100644 --- a/src/librustc_mir/util/elaborate_drops.rs +++ b/src/librustc_mir/util/elaborate_drops.rs @@ -788,7 +788,7 @@ where let ty = self.place_ty(self.place); match ty.kind { ty::Closure(def_id, substs) => { - let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect(); + let tys : Vec<_> = substs.as_closure().upvar_tys(def_id, self.tcx()).collect(); self.open_drop_for_tuple(&tys) } // Note that `elaborate_drops` only drops the upvars of a generator, diff --git a/src/librustc_traits/chalk_context/program_clauses/builtin.rs b/src/librustc_traits/chalk_context/program_clauses/builtin.rs index 6790f14f69bbd..13bbe021ccf34 100644 --- a/src/librustc_traits/chalk_context/program_clauses/builtin.rs +++ b/src/librustc_traits/chalk_context/program_clauses/builtin.rs @@ -266,7 +266,10 @@ crate fn assemble_builtin_copy_clone_impls<'tcx>( let closure_ty = generic_types::closure(tcx, def_id); let upvar_tys: Vec<_> = match &closure_ty.kind { ty::Closure(_, substs) => { - substs.upvar_tys(def_id, tcx).map(|ty| GenericArg::from(ty)).collect() + substs.as_closure() + .upvar_tys(def_id, tcx) + .map(|ty| GenericArg::from(ty)) + .collect() }, _ => bug!(), }; diff --git a/src/librustc_traits/dropck_outlives.rs b/src/librustc_traits/dropck_outlives.rs index a36b381bed343..7db1a7413c7be 100644 --- a/src/librustc_traits/dropck_outlives.rs +++ b/src/librustc_traits/dropck_outlives.rs @@ -193,7 +193,7 @@ fn dtorck_constraint_for_ty<'tcx>( .map(|ty| dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty.expect_ty())) .collect(), - ty::Closure(def_id, substs) => substs + ty::Closure(def_id, substs) => substs.as_closure() .upvar_tys(def_id, tcx) .map(|ty| dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty)) .collect(), diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index 3a16926872070..300b730b5bbfa 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -7,6 +7,7 @@ use hir::def::Res; use hir::def_id::{DefId, LOCAL_CRATE}; use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability}; use rustc::ty::{self, Ty, TyCtxt, TypeFoldable}; +use rustc::ty::subst::SubstsRef; use rustc::{infer, traits}; use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_target::spec::abi; @@ -103,7 +104,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Check whether this is a call to a closure where we // haven't yet decided on whether the closure is fn vs // fnmut vs fnonce. If so, we have to defer further processing. - let substs = rustc::ty::ClosureSubsts::from_ref(substs); if self.closure_kind(def_id, substs).is_none() { let closure_ty = self.closure_sig(def_id, substs); let fn_sig = self @@ -481,7 +481,7 @@ pub struct DeferredCallResolution<'tcx> { adjustments: Vec>, fn_sig: ty::FnSig<'tcx>, closure_def_id: DefId, - closure_substs: ty::ClosureSubsts<'tcx>, + closure_substs: SubstsRef<'tcx>, } impl<'a, 'tcx> DeferredCallResolution<'tcx> { diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 09dcce003fe27..76c9bec1db600 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -160,14 +160,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.demand_eqtype( expr.span, sig_fn_ptr_ty, - substs.closure_sig_ty(expr_def_id, self.tcx), + substs.as_closure().sig_ty(expr_def_id, self.tcx), ); if let Some(kind) = opt_kind { self.demand_eqtype( expr.span, kind.to_ty(self.tcx), - substs.closure_kind_ty(expr_def_id, self.tcx), + substs.as_closure().kind_ty(expr_def_id, self.tcx), ); } diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index c10279022bdfd..1f8c25ae4e059 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -61,7 +61,7 @@ use rustc::traits::{self, ObligationCause, ObligationCauseCode}; use rustc::ty::adjustment::{ Adjustment, Adjust, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast }; -use rustc::ty::{self, TypeAndMut, Ty, ClosureSubsts}; +use rustc::ty::{self, TypeAndMut, Ty, subst::SubstsRef}; use rustc::ty::fold::TypeFoldable; use rustc::ty::error::TypeError; use rustc::ty::relate::RelateResult; @@ -237,8 +237,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // Non-capturing closures are coercible to // function pointers or unsafe function pointers. // It cannot convert closures that require unsafe. - self.coerce_closure_to_fn(a, def_id_a, - rustc::ty::ClosureSubsts::from_ref(substs_a), b) + self.coerce_closure_to_fn(a, def_id_a, substs_a, b) } _ => { // Otherwise, just use unification rules. @@ -728,7 +727,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { fn coerce_closure_to_fn(&self, a: Ty<'tcx>, def_id_a: DefId, - substs_a: ClosureSubsts<'tcx>, + substs_a: SubstsRef<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { //! Attempts to coerce from the type of a non-capturing closure diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index a7832b8c2cf17..c17659647207a 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4191,7 +4191,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Closure(def_id, substs) => { // We don't use `closure_sig` to account for malformed closures like // `|_: [_; continue]| {}` and instead we don't suggest anything. - let closure_sig_ty = substs.closure_sig_ty(def_id, self.tcx); + let closure_sig_ty = substs.as_closure().sig_ty(def_id, self.tcx); (def_id, match closure_sig_ty.kind { ty::FnPtr(sig) => sig, _ => return false, diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 5b7c5c04e446a..3f218e1d9fab1 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -96,8 +96,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Extract the type of the closure. let ty = self.node_ty(closure_hir_id); let (closure_def_id, substs) = match ty.kind { - ty::Closure(def_id, substs) => (def_id, - UpvarSubsts::Closure(rustc::ty::ClosureSubsts::from_ref(substs))), + ty::Closure(def_id, substs) => ( + def_id, + UpvarSubsts::Closure(substs) + ), ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)), ty::Error => { // #51714: skip analysis when we have already encountered type errors @@ -191,7 +193,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Unify the (as yet unbound) type variable in the closure // substs with the kind we inferred. let inferred_kind = delegate.current_closure_kind; - let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self.tcx); + let closure_kind_ty = closure_substs + .as_closure().kind_ty(closure_def_id, self.tcx); self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty); // If we have an origin, store it. diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 1690ae7635f05..d973106058eaf 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1855,7 +1855,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { // the signature of a closure, you should use the // `closure_sig` method on the `ClosureSubsts`: // - // closure_substs.closure_sig(def_id, tcx) + // closure_substs.sig(def_id, tcx) // // or, inside of an inference context, you can use // From 4d9b4b4769691819f7a0328d1f87fa95899ca1c4 Mon Sep 17 00:00:00 2001 From: Dylan MacKenzie Date: Wed, 2 Oct 2019 15:35:59 -0700 Subject: [PATCH 09/17] Remove `borrowck_graphviz_postflow` from test --- src/test/ui/mir-dataflow/indirect-mutation-offset.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/ui/mir-dataflow/indirect-mutation-offset.rs b/src/test/ui/mir-dataflow/indirect-mutation-offset.rs index 804b70d26527a..8087a3e139915 100644 --- a/src/test/ui/mir-dataflow/indirect-mutation-offset.rs +++ b/src/test/ui/mir-dataflow/indirect-mutation-offset.rs @@ -12,7 +12,6 @@ struct PartialInteriorMut { } #[rustc_mir(rustc_peek_indirectly_mutable,stop_after_dataflow)] -#[rustc_mir(borrowck_graphviz_postflow="indirect.dot")] const BOO: i32 = { let x = PartialInteriorMut { zst: [], From b507971119198600a9afca52f76a0a8441160152 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 29 Sep 2019 18:51:09 +0300 Subject: [PATCH 10/17] metadata: Remove `CrateMetadata::imported_name` It's entirely irrelevant to crate loading --- src/librustc_metadata/creader.rs | 2 -- src/librustc_metadata/cstore.rs | 4 ---- src/librustc_metadata/cstore_impl.rs | 3 +-- 3 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index 682835d81a62b..69e9c6eb83b74 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -207,7 +207,6 @@ impl<'a> CrateLoader<'a> { info!("register crate `extern crate {} as {}` (private_dep = {})", crate_root.name, ident, private_dep); - // Claim this crate number and cache it let cnum = self.cstore.alloc_new_crate_num(); @@ -255,7 +254,6 @@ impl<'a> CrateLoader<'a> { let cmeta = cstore::CrateMetadata { name: crate_root.name, - imported_name: ident, extern_crate: Lock::new(None), def_path_table: Lrc::new(def_path_table), trait_impls, diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs index d3619b2f5de90..ed43aad38be0a 100644 --- a/src/librustc_metadata/cstore.rs +++ b/src/librustc_metadata/cstore.rs @@ -49,10 +49,6 @@ pub struct CrateMetadata { /// Original name of the crate. pub name: Symbol, - /// Name of the crate as imported. I.e., if imported with - /// `extern crate foo as bar;` this will be `bar`. - pub imported_name: Symbol, - /// Information about the extern crate that caused this crate to /// be loaded. If this is `None`, then the crate was injected /// (e.g., by the allocator) diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index edb6f594fdd0d..b5366769fff67 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -453,8 +453,7 @@ impl cstore::CStore { } let def = data.get_macro(id.index); - let macro_full_name = data.def_path(id.index) - .to_string_friendly(|_| data.imported_name); + let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.name); let source_name = FileName::Macros(macro_full_name); let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body); From acd102aebf82718d79b215b354d002d1be74090d Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 29 Sep 2019 19:34:51 +0300 Subject: [PATCH 11/17] metadata: Do not pass crate name after renaming to `register_crate` It's entirely irrelevant to crate loading --- src/librustc_metadata/creader.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index 69e9c6eb83b74..83727d6714d74 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -191,7 +191,6 @@ impl<'a> CrateLoader<'a> { &mut self, host_lib: Option, root: &Option, - ident: Symbol, span: Span, lib: Library, dep_kind: DepKind, @@ -204,8 +203,7 @@ impl<'a> CrateLoader<'a> { .map(|e| e.is_private_dep) .unwrap_or(false); - info!("register crate `extern crate {} as {}` (private_dep = {})", - crate_root.name, ident, private_dep); + info!("register crate `{}` (private_dep = {})", crate_root.name, private_dep); // Claim this crate number and cache it let cnum = self.cstore.alloc_new_crate_num(); @@ -213,7 +211,7 @@ impl<'a> CrateLoader<'a> { // Stash paths for top-most crate locally if necessary. let crate_paths = if root.is_none() { Some(CratePaths { - ident: ident.to_string(), + ident: crate_root.name.to_string(), dylib: lib.dylib.clone().map(|p| p.0), rlib: lib.rlib.clone().map(|p| p.0), rmeta: lib.rmeta.clone().map(|p| p.0), @@ -391,7 +389,7 @@ impl<'a> CrateLoader<'a> { Ok((cnum, data)) } (LoadResult::Loaded(library), host_library) => { - Ok(self.register_crate(host_library, root, ident, span, library, dep_kind, name)) + Ok(self.register_crate(host_library, root, span, library, dep_kind, name)) } _ => panic!() } From 33c9ada8003844b6a683930fdd1442effffd3b0a Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 29 Sep 2019 20:16:23 +0300 Subject: [PATCH 12/17] metadata: Remove `locator::Context::ident` It's a crate name after renaming, so it's entirely irrelevant to crate loading --- src/librustc_metadata/creader.rs | 28 ++++++++++-------------- src/librustc_metadata/locator.rs | 21 +++++++++--------- src/test/ui/use/use-meta-mismatch.rs | 2 +- src/test/ui/use/use-meta-mismatch.stderr | 2 +- 4 files changed, 24 insertions(+), 29 deletions(-) diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index 83727d6714d74..64af9557ea49e 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -337,7 +337,6 @@ impl<'a> CrateLoader<'a> { fn resolve_crate<'b>( &'b mut self, root: &'b Option, - ident: Symbol, name: Symbol, hash: Option<&'b Svh>, extra_filename: Option<&'b str>, @@ -345,7 +344,7 @@ impl<'a> CrateLoader<'a> { path_kind: PathKind, mut dep_kind: DepKind, ) -> Result<(CrateNum, Lrc), LoadError<'b>> { - info!("resolving crate `extern crate {} as {}`", name, ident); + info!("resolving crate `{}`", name); let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) { (LoadResult::Previous(cnum), None) } else { @@ -353,7 +352,6 @@ impl<'a> CrateLoader<'a> { let mut locate_ctxt = locator::Context { sess: self.sess, span, - ident, crate_name: name, hash, extra_filename, @@ -493,16 +491,15 @@ impl<'a> CrateLoader<'a> { _ => dep.kind, }; let (local_cnum, ..) = self.resolve_crate( - root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span, + root, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span, PathKind::Dependency, dep_kind, ).unwrap_or_else(|err| err.report()); local_cnum })).collect() } - fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol) - -> ExtensionCrate { - info!("read extension crate `extern crate {} as {}`", orig_name, rename); + fn read_extension_crate(&mut self, name: Symbol, span: Span) -> ExtensionCrate { + info!("read extension crate `{}`", name); let target_triple = self.sess.opts.target_triple.clone(); let host_triple = TargetTriple::from_triple(config::host_triple()); let is_cross = target_triple != host_triple; @@ -510,8 +507,7 @@ impl<'a> CrateLoader<'a> { let mut locate_ctxt = locator::Context { sess: self.sess, span, - ident: orig_name, - crate_name: rename, + crate_name: name, hash: None, extra_filename: None, filesearch: self.sess.host_filesearch(PathKind::Crate), @@ -606,7 +602,7 @@ impl<'a> CrateLoader<'a> { span: Span, name: Symbol) -> Option<(PathBuf, CrateDisambiguator)> { - let ekrate = self.read_extension_crate(span, name, name); + let ekrate = self.read_extension_crate(name, span); if ekrate.target_only { // Need to abort before syntax expansion. @@ -699,7 +695,7 @@ impl<'a> CrateLoader<'a> { let dep_kind = DepKind::Implicit; let (cnum, data) = - self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind) + self.resolve_crate(&None, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind) .unwrap_or_else(|err| err.report()); // Sanity check the loaded crate to ensure it is indeed a panic runtime @@ -807,7 +803,7 @@ impl<'a> CrateLoader<'a> { let symbol = Symbol::intern(name); let dep_kind = DepKind::Explicit; let (_, data) = - self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP, + self.resolve_crate(&None, symbol, None, None, DUMMY_SP, PathKind::Crate, dep_kind) .unwrap_or_else(|err| err.report()); @@ -831,7 +827,7 @@ impl<'a> CrateLoader<'a> { let symbol = Symbol::intern("profiler_builtins"); let dep_kind = DepKind::Implicit; let (_, data) = - self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP, + self.resolve_crate(&None, symbol, None, None, DUMMY_SP, PathKind::Crate, dep_kind) .unwrap_or_else(|err| err.report()); @@ -1015,7 +1011,7 @@ impl<'a> CrateLoader<'a> { }; let (cnum, ..) = self.resolve_crate( - &None, item.ident.name, orig_name, None, None, + &None, orig_name, None, None, item.span, PathKind::Crate, dep_kind, ).unwrap_or_else(|err| err.report()); @@ -1044,7 +1040,7 @@ impl<'a> CrateLoader<'a> { span: Span, ) -> CrateNum { let cnum = self.resolve_crate( - &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit + &None, name, None, None, span, PathKind::Crate, DepKind::Explicit ).unwrap_or_else(|err| err.report()).0; self.update_extern_crate( @@ -1068,7 +1064,7 @@ impl<'a> CrateLoader<'a> { span: Span, ) -> Option { let cnum = self.resolve_crate( - &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit + &None, name, None, None, span, PathKind::Crate, DepKind::Explicit ).ok()?.0; self.update_extern_crate( diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index ceba7cf0fe031..f8b2777403346 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -254,7 +254,6 @@ pub struct CrateMismatch { pub struct Context<'a> { pub sess: &'a Session, pub span: Span, - pub ident: Symbol, pub crate_name: Symbol, pub hash: Option<&'a Svh>, pub extra_filename: Option<&'a str>, @@ -332,12 +331,12 @@ impl<'a> Context<'a> { self.span, E0460, "found possibly newer version of crate `{}`{}", - self.ident, + self.crate_name, add); err.note("perhaps that crate needs to be recompiled?"); let mismatches = self.rejected_via_hash.iter(); for &CrateMismatch { ref path, .. } in mismatches { - msg.push_str(&format!("\ncrate `{}`: {}", self.ident, path.display())); + msg.push_str(&format!("\ncrate `{}`: {}", self.crate_name, path.display())); } match self.root { &None => {} @@ -355,13 +354,13 @@ impl<'a> Context<'a> { E0461, "couldn't find crate `{}` \ with expected target triple {}{}", - self.ident, + self.crate_name, self.triple, add); let mismatches = self.rejected_via_triple.iter(); for &CrateMismatch { ref path, ref got } in mismatches { msg.push_str(&format!("\ncrate `{}`, target triple {}: {}", - self.ident, + self.crate_name, got, path.display())); } @@ -372,12 +371,12 @@ impl<'a> Context<'a> { self.span, E0462, "found staticlib `{}` instead of rlib or dylib{}", - self.ident, + self.crate_name, add); err.help("please recompile that crate using --crate-type lib"); let mismatches = self.rejected_via_kind.iter(); for &CrateMismatch { ref path, .. } in mismatches { - msg.push_str(&format!("\ncrate `{}`: {}", self.ident, path.display())); + msg.push_str(&format!("\ncrate `{}`: {}", self.crate_name, path.display())); } err.note(&msg); err @@ -387,14 +386,14 @@ impl<'a> Context<'a> { E0514, "found crate `{}` compiled by an incompatible version \ of rustc{}", - self.ident, + self.crate_name, add); err.help(&format!("please recompile that crate using this compiler ({})", rustc_version())); let mismatches = self.rejected_via_version.iter(); for &CrateMismatch { ref path, ref got } in mismatches { msg.push_str(&format!("\ncrate `{}` compiled by {}: {}", - self.ident, + self.crate_name, got, path.display())); } @@ -405,10 +404,10 @@ impl<'a> Context<'a> { self.span, E0463, "can't find crate for `{}`{}", - self.ident, + self.crate_name, add); - if (self.ident == sym::std || self.ident == sym::core) + if (self.crate_name == sym::std || self.crate_name == sym::core) && self.triple != TargetTriple::from_triple(config::host_triple()) { err.note(&format!("the `{}` target may not be installed", self.triple)); } diff --git a/src/test/ui/use/use-meta-mismatch.rs b/src/test/ui/use/use-meta-mismatch.rs index 459216a17e4f3..975209efb0c1b 100644 --- a/src/test/ui/use/use-meta-mismatch.rs +++ b/src/test/ui/use/use-meta-mismatch.rs @@ -1,4 +1,4 @@ -// error-pattern:can't find crate for `extra` +// error-pattern:can't find crate for `fake_crate` extern crate fake_crate as extra; diff --git a/src/test/ui/use/use-meta-mismatch.stderr b/src/test/ui/use/use-meta-mismatch.stderr index 877ac464de782..62b71fe8e12f4 100644 --- a/src/test/ui/use/use-meta-mismatch.stderr +++ b/src/test/ui/use/use-meta-mismatch.stderr @@ -1,4 +1,4 @@ -error[E0463]: can't find crate for `extra` +error[E0463]: can't find crate for `fake_crate` --> $DIR/use-meta-mismatch.rs:3:1 | LL | extern crate fake_crate as extra; From 92386a7ff37a2a7a01b187afefc51f326e923377 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sun, 29 Sep 2019 21:14:29 +0300 Subject: [PATCH 13/17] metadata: Simplify interface of `resolve_crate` --- src/librustc/middle/cstore.rs | 4 +- src/librustc_metadata/creader.rs | 92 ++++++++++++++------------------ src/librustc_metadata/locator.rs | 10 ++-- 3 files changed, 46 insertions(+), 60 deletions(-) diff --git a/src/librustc/middle/cstore.rs b/src/librustc/middle/cstore.rs index ddf6262b7382e..510787998ad07 100644 --- a/src/librustc/middle/cstore.rs +++ b/src/librustc/middle/cstore.rs @@ -148,9 +148,7 @@ pub enum ExternCrateSource { /// such ids DefId, ), - // Crate is loaded by `use`. - Use, - /// Crate is implicitly loaded by an absolute path. + /// Crate is implicitly loaded by a path resolving through extern prelude. Path, } diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index 64af9557ea49e..ea1b746dc07fe 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -2,7 +2,7 @@ use crate::cstore::{self, CStore, CrateSource, MetadataBlob}; use crate::locator::{self, CratePaths}; -use crate::schema::{CrateRoot}; +use crate::schema::{CrateRoot, CrateDep}; use rustc_data_structures::sync::{Lrc, RwLock, Lock}; use rustc::hir::def_id::CrateNum; @@ -190,7 +190,7 @@ impl<'a> CrateLoader<'a> { fn register_crate( &mut self, host_lib: Option, - root: &Option, + root: Option<&CratePaths>, span: Span, lib: Library, dep_kind: DepKind, @@ -208,19 +208,20 @@ impl<'a> CrateLoader<'a> { // Claim this crate number and cache it let cnum = self.cstore.alloc_new_crate_num(); + // Maintain a reference to the top most crate. // Stash paths for top-most crate locally if necessary. - let crate_paths = if root.is_none() { - Some(CratePaths { + let crate_paths; + let root = if let Some(root) = root { + root + } else { + crate_paths = CratePaths { ident: crate_root.name.to_string(), dylib: lib.dylib.clone().map(|p| p.0), rlib: lib.rlib.clone().map(|p| p.0), rmeta: lib.rmeta.clone().map(|p| p.0), - }) - } else { - None + }; + &crate_paths }; - // Maintain a reference to the top most crate. - let root = if root.is_some() { root } else { &crate_paths }; let Library { dylib, rlib, rmeta, metadata } = lib; let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind); @@ -336,15 +337,27 @@ impl<'a> CrateLoader<'a> { fn resolve_crate<'b>( &'b mut self, - root: &'b Option, name: Symbol, - hash: Option<&'b Svh>, - extra_filename: Option<&'b str>, span: Span, - path_kind: PathKind, + dep_kind: DepKind, + dep: Option<(&'b CratePaths, &'b CrateDep)>, + ) -> (CrateNum, Lrc) { + self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report()) + } + + fn maybe_resolve_crate<'b>( + &'b mut self, + name: Symbol, + span: Span, mut dep_kind: DepKind, + dep: Option<(&'b CratePaths, &'b CrateDep)>, ) -> Result<(CrateNum, Lrc), LoadError<'b>> { info!("resolving crate `{}`", name); + let (root, hash, extra_filename, path_kind) = match dep { + Some((root, dep)) => + (Some(root), Some(&dep.hash), Some(&dep.extra_filename[..]), PathKind::Dependency), + None => (None, None, None, PathKind::Crate), + }; let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) { (LoadResult::Previous(cnum), None) } else { @@ -463,7 +476,7 @@ impl<'a> CrateLoader<'a> { // Go through the crate metadata and load any crates that it references fn resolve_crate_deps(&mut self, - root: &Option, + root: &CratePaths, crate_root: &CrateRoot<'_>, metadata: &MetadataBlob, krate: CrateNum, @@ -478,9 +491,7 @@ impl<'a> CrateLoader<'a> { // The map from crate numbers in the crate we're resolving to local crate numbers. // We map 0 and all other holes in the map to our parent crate. The "additional" // self-dependencies should be harmless. - std::iter::once(krate).chain(crate_root.crate_deps - .decode(metadata) - .map(|dep| { + std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| { info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash, dep.extra_filename); if dep.kind == DepKind::UnexportedMacrosOnly { @@ -490,11 +501,7 @@ impl<'a> CrateLoader<'a> { DepKind::MacrosOnly => DepKind::MacrosOnly, _ => dep.kind, }; - let (local_cnum, ..) = self.resolve_crate( - root, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span, - PathKind::Dependency, dep_kind, - ).unwrap_or_else(|err| err.report()); - local_cnum + self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep))).0 })).collect() } @@ -513,7 +520,7 @@ impl<'a> CrateLoader<'a> { filesearch: self.sess.host_filesearch(PathKind::Crate), target: &self.sess.host, triple: host_triple, - root: &None, + root: None, rejected_via_hash: vec![], rejected_via_triple: vec![], rejected_via_kind: vec![], @@ -693,10 +700,7 @@ impl<'a> CrateLoader<'a> { }; info!("panic runtime not found -- loading {}", name); - let dep_kind = DepKind::Implicit; - let (cnum, data) = - self.resolve_crate(&None, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind) - .unwrap_or_else(|err| err.report()); + let (cnum, data) = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None); // Sanity check the loaded crate to ensure it is indeed a panic runtime // and the panic strategy is indeed what we thought it was. @@ -792,20 +796,15 @@ impl<'a> CrateLoader<'a> { }); if uses_std { - let name = match *sanitizer { + let name = Symbol::intern(match sanitizer { Sanitizer::Address => "rustc_asan", Sanitizer::Leak => "rustc_lsan", Sanitizer::Memory => "rustc_msan", Sanitizer::Thread => "rustc_tsan", - }; + }); info!("loading sanitizer: {}", name); - let symbol = Symbol::intern(name); - let dep_kind = DepKind::Explicit; - let (_, data) = - self.resolve_crate(&None, symbol, None, None, DUMMY_SP, - PathKind::Crate, dep_kind) - .unwrap_or_else(|err| err.report()); + let data = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None).1; // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime if !data.root.sanitizer_runtime { @@ -824,12 +823,8 @@ impl<'a> CrateLoader<'a> { { info!("loading profiler"); - let symbol = Symbol::intern("profiler_builtins"); - let dep_kind = DepKind::Implicit; - let (_, data) = - self.resolve_crate(&None, symbol, None, None, DUMMY_SP, - PathKind::Crate, dep_kind) - .unwrap_or_else(|err| err.report()); + let name = Symbol::intern("profiler_builtins"); + let data = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None).1; // Sanity check the loaded crate to ensure it is indeed a profiler runtime if !data.root.profiler_runtime { @@ -996,7 +991,7 @@ impl<'a> CrateLoader<'a> { ast::ItemKind::ExternCrate(orig_name) => { debug!("resolving extern crate stmt. ident: {} orig_name: {:?}", item.ident, orig_name); - let orig_name = match orig_name { + let name = match orig_name { Some(orig_name) => { crate::validate_crate_name(Some(self.sess), &orig_name.as_str(), Some(item.span)); @@ -1010,10 +1005,7 @@ impl<'a> CrateLoader<'a> { DepKind::Explicit }; - let (cnum, ..) = self.resolve_crate( - &None, orig_name, None, None, - item.span, PathKind::Crate, dep_kind, - ).unwrap_or_else(|err| err.report()); + let cnum = self.resolve_crate(name, item.span, dep_kind, None).0; let def_id = definitions.opt_local_def_id(item.id).unwrap(); let path_len = definitions.def_path(def_id.index).data.len(); @@ -1039,9 +1031,7 @@ impl<'a> CrateLoader<'a> { name: Symbol, span: Span, ) -> CrateNum { - let cnum = self.resolve_crate( - &None, name, None, None, span, PathKind::Crate, DepKind::Explicit - ).unwrap_or_else(|err| err.report()).0; + let cnum = self.resolve_crate(name, span, DepKind::Explicit, None).0; self.update_extern_crate( cnum, @@ -1063,9 +1053,7 @@ impl<'a> CrateLoader<'a> { name: Symbol, span: Span, ) -> Option { - let cnum = self.resolve_crate( - &None, name, None, None, span, PathKind::Crate, DepKind::Explicit - ).ok()?.0; + let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?.0; self.update_extern_crate( cnum, diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index f8b2777403346..8df236c41cfb8 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -261,7 +261,7 @@ pub struct Context<'a> { pub target: &'a Target, pub triple: TargetTriple, pub filesearch: FileSearch<'a>, - pub root: &'a Option, + pub root: Option<&'a CratePaths>, pub rejected_via_hash: Vec, pub rejected_via_triple: Vec, pub rejected_via_kind: Vec, @@ -322,8 +322,8 @@ impl<'a> Context<'a> { pub fn report_errs(self) -> ! { let add = match self.root { - &None => String::new(), - &Some(ref r) => format!(" which `{}` depends on", r.ident), + None => String::new(), + Some(r) => format!(" which `{}` depends on", r.ident), }; let mut msg = "the following crate versions were found:".to_string(); let mut err = if !self.rejected_via_hash.is_empty() { @@ -339,8 +339,8 @@ impl<'a> Context<'a> { msg.push_str(&format!("\ncrate `{}`: {}", self.crate_name, path.display())); } match self.root { - &None => {} - &Some(ref r) => { + None => {} + Some(r) => { for path in r.paths().iter() { msg.push_str(&format!("\ncrate `{}`: {}", r.ident, path.display())); } From f13adc5f9d50f66b3b86589c35e49c92af807f23 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 2 Oct 2019 02:47:36 +0300 Subject: [PATCH 14/17] metadata: Remove `CrateMetadata::host_lib` It was only used for retreiving edition, which was a bug. In case of dual proc macros the edition should be taken from the target crate version, like any other metadata. --- src/librustc_metadata/creader.rs | 1 - src/librustc_metadata/cstore.rs | 2 -- src/librustc_metadata/decoder.rs | 7 +------ 3 files changed, 1 insertion(+), 9 deletions(-) diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index ea1b746dc07fe..f2980941082f4 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -271,7 +271,6 @@ impl<'a> CrateLoader<'a> { }, private_dep, span, - host_lib, raw_proc_macros }; diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs index ed43aad38be0a..d8bbe23b8ecbc 100644 --- a/src/librustc_metadata/cstore.rs +++ b/src/librustc_metadata/cstore.rs @@ -28,7 +28,6 @@ pub use crate::cstore_impl::{provide, provide_extern}; pub type CrateNumMap = IndexVec; pub use rustc_data_structures::sync::MetadataRef; -use crate::creader::Library; use syntax_pos::Span; use proc_macro::bridge::client::ProcMacro; @@ -85,7 +84,6 @@ pub struct CrateMetadata { /// for purposes of the 'exported_private_dependencies' lint pub private_dep: bool, - pub host_lib: Option, pub span: Span, pub raw_proc_macros: Option<&'static [ProcMacro]>, diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index 9fcc310154599..6681cf3052f2b 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -543,18 +543,13 @@ impl<'a, 'tcx> CrateMetadata { name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new() ) }; - let edition = if sess.opts.debugging_opts.dual_proc_macros { - self.host_lib.as_ref().unwrap().metadata.get_root().edition - } else { - self.root.edition - }; SyntaxExtension::new( &sess.parse_sess, kind, self.get_span(id, sess), helper_attrs, - edition, + self.root.edition, Symbol::intern(name), &self.get_attributes(&self.entry(id), sess), ) From 0f96ba92b643922c02f43cf0df4d780a95375692 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 2 Oct 2019 03:15:38 +0300 Subject: [PATCH 15/17] metadata: Remove `CrateMetadata::name` It duplicates `CrateRoot::name` --- src/librustc_metadata/creader.rs | 5 ++--- src/librustc_metadata/cstore.rs | 4 ---- src/librustc_metadata/cstore_impl.rs | 6 +++--- src/librustc_metadata/decoder.rs | 2 +- 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index f2980941082f4..dcb0fb73aa72d 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -112,7 +112,7 @@ impl<'a> CrateLoader<'a> { -> Option { let mut ret = None; self.cstore.iter_crate_data(|cnum, data| { - if data.name != name { return } + if data.root.name != name { return } match hash { Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return } @@ -252,7 +252,6 @@ impl<'a> CrateLoader<'a> { }); let cmeta = cstore::CrateMetadata { - name: crate_root.name, extern_crate: Lock::new(None), def_path_table: Lrc::new(def_path_table), trait_impls, @@ -789,7 +788,7 @@ impl<'a> CrateLoader<'a> { let mut uses_std = false; self.cstore.iter_crate_data(|_, data| { - if data.name == sym::std { + if data.root.name == sym::std { uses_std = true; } }); diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs index d8bbe23b8ecbc..833c846573f63 100644 --- a/src/librustc_metadata/cstore.rs +++ b/src/librustc_metadata/cstore.rs @@ -12,7 +12,6 @@ use rustc::util::nodemap::{FxHashMap, NodeMap}; use rustc_data_structures::sync::{Lrc, RwLock, Lock}; use syntax::ast; use syntax::ext::base::SyntaxExtension; -use syntax::symbol::Symbol; use syntax_pos; pub use rustc::middle::cstore::{NativeLibrary, NativeLibraryKind, LinkagePreference}; @@ -45,9 +44,6 @@ pub struct ImportedSourceFile { } pub struct CrateMetadata { - /// Original name of the crate. - pub name: Symbol, - /// Information about the extern crate that caused this crate to /// be loaded. If this is `None`, then the crate was injected /// (e.g., by the allocator) diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index b5366769fff67..cd6b370ca3185 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -220,7 +220,7 @@ provide! { <'tcx> tcx, def_id, other, cdata, let r = *cdata.dep_kind.lock(); r } - crate_name => { cdata.name } + crate_name => { cdata.root.name } item_children => { let mut result = SmallVec::<[_; 8]>::new(); cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess); @@ -453,7 +453,7 @@ impl cstore::CStore { } let def = data.get_macro(id.index); - let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.name); + let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.root.name); let source_name = FileName::Macros(macro_full_name); let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body); @@ -503,7 +503,7 @@ impl CrateStore for cstore::CStore { fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { - self.get_crate_data(cnum).name + self.get_crate_data(cnum).root.name } fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool { diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index 6681cf3052f2b..528d937224648 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -473,7 +473,7 @@ impl<'a, 'tcx> CrateMetadata { None => { bug!("entry: id not found: {:?} in crate {:?} with number {}", item_id, - self.name, + self.root.name, self.cnum) } Some(d) => d.decode(self), From 68aadcb2ae16cc9d6845eefde3ad49b214731954 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 2 Oct 2019 22:31:11 +0300 Subject: [PATCH 16/17] metadata: Remove unused `Option` from `fn dlsym_proc_macros` --- src/librustc_metadata/creader.rs | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index dcb0fb73aa72d..042252bc13e61 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -20,7 +20,7 @@ use rustc::hir::map::Definitions; use rustc::hir::def_id::LOCAL_CRATE; use std::ops::Deref; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::{cmp, fs}; use syntax::ast; @@ -229,13 +229,14 @@ impl<'a> CrateLoader<'a> { let dependencies: Vec = cnum_map.iter().cloned().collect(); let raw_proc_macros = crate_root.proc_macro_data.map(|_| { - if self.sess.opts.debugging_opts.dual_proc_macros { - let host_lib = host_lib.as_ref().unwrap(); - self.dlsym_proc_macros(host_lib.dylib.as_ref().map(|p| p.0.clone()), - &host_lib.metadata.get_root(), span) - } else { - self.dlsym_proc_macros(dylib.clone().map(|p| p.0), &crate_root, span) - } + let temp_root; + let (dlsym_dylib, dlsym_root) = match &host_lib { + Some(host_lib) => + (&host_lib.dylib, { temp_root = host_lib.metadata.get_root(); &temp_root }), + None => (&dylib, &crate_root), + }; + let dlsym_dylib = dlsym_dylib.as_ref().expect("no dylib for a proc-macro crate"); + self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span) }); let interpret_alloc_index: Vec = crate_root.interpret_alloc_index @@ -567,17 +568,13 @@ impl<'a> CrateLoader<'a> { } fn dlsym_proc_macros(&self, - dylib: Option, - root: &CrateRoot<'_>, + path: &Path, + disambiguator: CrateDisambiguator, span: Span ) -> &'static [ProcMacro] { use std::env; use crate::dynamic_lib::DynamicLibrary; - let path = match dylib { - Some(dylib) => dylib, - None => span_bug!(span, "proc-macro crate not dylib"), - }; // Make sure the path contains a / or the linker will search for it. let path = env::current_dir().unwrap().join(path); let lib = match DynamicLibrary::open(Some(&path)) { @@ -585,7 +582,7 @@ impl<'a> CrateLoader<'a> { Err(err) => self.sess.span_fatal(span, &err), }; - let sym = self.sess.generate_proc_macro_decls_symbol(root.disambiguator); + let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator); let decls = unsafe { let sym = match lib.symbol(&sym) { Ok(f) => f, From 1cda5913146fb596b5018fb7f59b38519405e658 Mon Sep 17 00:00:00 2001 From: Dylan MacKenzie Date: Thu, 3 Oct 2019 15:51:11 -0700 Subject: [PATCH 17/17] Bless test --- src/test/ui/mir-dataflow/indirect-mutation-offset.stderr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr b/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr index 16bd17813134a..0ae9a40c96aaa 100644 --- a/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr +++ b/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr @@ -1,5 +1,5 @@ error: rustc_peek: bit not set - --> $DIR/indirect-mutation-offset.rs:35:14 + --> $DIR/indirect-mutation-offset.rs:34:14 | LL | unsafe { rustc_peek(x) }; | ^^^^^^^^^^^^^