Remove HIR based const qualification
This commit is contained in:
parent
22bc9e1d9c
commit
455945f24b
19 changed files with 66 additions and 916 deletions
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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<hir::HirId, hir::Upvar>>,
|
||||
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) => {
|
||||
|
|
|
|||
|
|
@ -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<mir::Local>) {
|
||||
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<DefId> {}
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -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::*;
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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) }
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {}
|
||||
}
|
||||
|
|
@ -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(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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(..) => {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue