Skip to content

Commit f6c35c6

Browse files
committed
Auto merge of #43932 - eddyb:const-scoping, r=<try>
Forward-compatibly deny drops in constants if they *could* actually run. This is part of #40036, specifically the checks for user-defined destructor invocations on locals which *may not* have been moved away, the motivating example being: ```rust const FOO: i32 = (HasDrop {...}, 0).1; ``` The evaluation of constant MIR will continue to create `'static` slots for more locals than is necessary (if `Storage{Live,Dead}` statements are ignored), but it shouldn't be misusable. r? @nikomatsakis
2 parents a7e0018 + cdfe8d7 commit f6c35c6

File tree

4 files changed

+133
-32
lines changed

4 files changed

+133
-32
lines changed

src/librustc/middle/region.rs

+50-26
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,9 @@ pub struct RegionMaps {
221221
/// table, the appropriate cleanup scope is the innermost
222222
/// enclosing statement, conditional expression, or repeating
223223
/// block (see `terminating_scopes`).
224-
rvalue_scopes: NodeMap<CodeExtent>,
224+
/// In constants, None is used to indicate that certain expressions
225+
/// escape into 'static and should have no local cleanup scope.
226+
rvalue_scopes: NodeMap<Option<CodeExtent>>,
225227

226228
/// Encodes the hierarchy of fn bodies. Every fn body (including
227229
/// closures) forms its own distinct region hierarchy, rooted in
@@ -356,9 +358,11 @@ impl<'tcx> RegionMaps {
356358
self.var_map.insert(var, lifetime);
357359
}
358360

359-
fn record_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
361+
fn record_rvalue_scope(&mut self, var: ast::NodeId, lifetime: Option<CodeExtent>) {
360362
debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
361-
assert!(var != lifetime.node_id());
363+
if let Some(lifetime) = lifetime {
364+
assert!(var != lifetime.node_id());
365+
}
362366
self.rvalue_scopes.insert(var, lifetime);
363367
}
364368

@@ -387,7 +391,7 @@ impl<'tcx> RegionMaps {
387391
// check for a designated rvalue scope
388392
if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
389393
debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
390-
return Some(s);
394+
return s;
391395
}
392396

393397
// else, locate the innermost terminating scope
@@ -801,16 +805,11 @@ fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr:
801805
}
802806

803807
fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
804-
local: &'tcx hir::Local) {
805-
debug!("resolve_local(local.id={:?},local.init={:?})",
806-
local.id,local.init.is_some());
808+
pat: Option<&'tcx hir::Pat>,
809+
init: Option<&'tcx hir::Expr>) {
810+
debug!("resolve_local(pat={:?}, init={:?})", pat, init);
807811

808-
// For convenience in trans, associate with the local-id the var
809-
// scope that will be used for any bindings declared in this
810-
// pattern.
811812
let blk_scope = visitor.cx.var_parent;
812-
let blk_scope = blk_scope.expect("locals must be within a block");
813-
visitor.region_maps.record_var_scope(local.id, blk_scope);
814813

815814
// As an exception to the normal rules governing temporary
816815
// lifetimes, initializers in a let have a temporary lifetime
@@ -870,15 +869,22 @@ fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
870869
//
871870
// FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
872871

873-
if let Some(ref expr) = local.init {
872+
if let Some(expr) = init {
874873
record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
875874

876-
if is_binding_pat(&local.pat) {
877-
record_rvalue_scope(visitor, &expr, blk_scope);
875+
if let Some(pat) = pat {
876+
if is_binding_pat(pat) {
877+
record_rvalue_scope(visitor, &expr, blk_scope);
878+
}
878879
}
879880
}
880881

881-
intravisit::walk_local(visitor, local);
882+
if let Some(pat) = pat {
883+
visitor.visit_pat(pat);
884+
}
885+
if let Some(expr) = init {
886+
visitor.visit_expr(expr);
887+
}
882888

883889
/// True if `pat` match the `P&` nonterminal:
884890
///
@@ -952,7 +958,7 @@ fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
952958
fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
953959
visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
954960
expr: &hir::Expr,
955-
blk_id: CodeExtent)
961+
blk_id: Option<CodeExtent>)
956962
{
957963
match expr.node {
958964
hir::ExprAddrOf(_, ref subexpr) => {
@@ -1002,7 +1008,7 @@ fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
10021008
/// Note: ET is intended to match "rvalues or lvalues based on rvalues".
10031009
fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
10041010
expr: &hir::Expr,
1005-
blk_scope: CodeExtent) {
1011+
blk_scope: Option<CodeExtent>) {
10061012
let mut expr = expr;
10071013
loop {
10081014
// Note: give all the expressions matching `ET` with the
@@ -1075,12 +1081,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
10751081

10761082
let outer_cx = self.cx;
10771083
let outer_ts = mem::replace(&mut self.terminating_scopes, NodeSet());
1078-
1079-
// Only functions have an outer terminating (drop) scope,
1080-
// while temporaries in constant initializers are 'static.
1081-
if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
1082-
self.terminating_scopes.insert(body_id.node_id);
1083-
}
1084+
self.terminating_scopes.insert(body_id.node_id);
10841085

10851086
if let Some(root_id) = self.cx.root_id {
10861087
self.region_maps.record_fn_parent(body_id.node_id, root_id);
@@ -1098,7 +1099,30 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
10981099

10991100
// The body of the every fn is a root scope.
11001101
self.cx.parent = self.cx.var_parent;
1101-
self.visit_expr(&body.value);
1102+
if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
1103+
self.visit_expr(&body.value);
1104+
} else {
1105+
// Only functions have an outer terminating (drop) scope, while
1106+
// temporaries in constant initializers may be 'static, but only
1107+
// according to rvalue lifetime semantics, using the same
1108+
// syntactical rules used for let initializers.
1109+
//
1110+
// E.g. in `let x = &f();`, the temporary holding the result from
1111+
// the `f()` call lives for the entirety of the surrounding block.
1112+
//
1113+
// Similarly, `const X: ... = &f();` would have the result of `f()`
1114+
// live for `'static`, implying (if Drop restrictions on constants
1115+
// ever get lifted) that the value *could* have a destructor, but
1116+
// it'd get leaked instead of the destructor running during the
1117+
// evaluation of `X` (if at all allowed by CTFE).
1118+
//
1119+
// However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1120+
// would *not* let the `f()` temporary escape into an outer scope
1121+
// (i.e. `'static`), which means that after `g` returns, it drops,
1122+
// and all the associated destruction scope rules apply.
1123+
self.cx.var_parent = None;
1124+
resolve_local(self, None, Some(&body.value));
1125+
}
11021126

11031127
// Restore context we had at the start.
11041128
self.cx = outer_cx;
@@ -1118,7 +1142,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
11181142
resolve_expr(self, ex);
11191143
}
11201144
fn visit_local(&mut self, l: &'tcx Local) {
1121-
resolve_local(self, l);
1145+
resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
11221146
}
11231147
}
11241148

src/librustc_mir/transform/qualify_consts.rs

+55-5
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ struct Qualifier<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
120120
return_qualif: Option<Qualif>,
121121
qualif: Qualif,
122122
const_fn_arg_vars: BitVector,
123+
local_needs_drop: IndexVec<Local, Option<Span>>,
123124
temp_promotion_state: IndexVec<Local, TempState>,
124125
promotion_candidates: Vec<Candidate>
125126
}
@@ -146,6 +147,7 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
146147
return_qualif: None,
147148
qualif: Qualif::empty(),
148149
const_fn_arg_vars: BitVector::new(mir.local_decls.len()),
150+
local_needs_drop: IndexVec::from_elem(None, &mir.local_decls),
149151
temp_promotion_state: temps,
150152
promotion_candidates: vec![]
151153
}
@@ -193,16 +195,26 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
193195
self.add(original);
194196
}
195197

198+
/// Check for NEEDS_DROP (from an ADT or const fn call) and
199+
/// error, unless we're in a function.
200+
fn always_deny_drop(&self) {
201+
self.deny_drop_with_feature_gate_override(false);
202+
}
203+
196204
/// Check for NEEDS_DROP (from an ADT or const fn call) and
197205
/// error, unless we're in a function, or the feature-gate
198206
/// for globals with destructors is enabled.
199207
fn deny_drop(&self) {
208+
self.deny_drop_with_feature_gate_override(true);
209+
}
210+
211+
fn deny_drop_with_feature_gate_override(&self, allow_gate: bool) {
200212
if self.mode == Mode::Fn || !self.qualif.intersects(Qualif::NEEDS_DROP) {
201213
return;
202214
}
203215

204216
// Static and const fn's allow destructors, but they're feature-gated.
205-
let msg = if self.mode != Mode::Const {
217+
let msg = if allow_gate && self.mode != Mode::Const {
206218
// Feature-gate for globals with destructors is enabled.
207219
if self.tcx.sess.features.borrow().drop_types_in_const {
208220
return;
@@ -223,15 +235,16 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
223235
let mut err =
224236
struct_span_err!(self.tcx.sess, self.span, E0493, "{}", msg);
225237

226-
if self.mode != Mode::Const {
238+
if allow_gate && self.mode != Mode::Const {
227239
help!(&mut err,
228240
"in Nightly builds, add `#![feature(drop_types_in_const)]` \
229241
to the crate attributes to enable");
230242
} else {
231243
self.find_drop_implementation_method_span()
232244
.map(|span| err.span_label(span, "destructor defined here"));
233245

234-
err.span_label(self.span, "constants cannot have destructors");
246+
err.span_label(self.span,
247+
format!("{}s cannot have destructors", self.mode));
235248
}
236249

237250
err.emit();
@@ -314,6 +327,15 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
314327
return;
315328
}
316329

330+
// When initializing a local, record whether the *value* being
331+
// stored in it needs dropping, which it may not, even if its
332+
// type does, e.g. `None::<String>`.
333+
if let Lvalue::Local(local) = *dest {
334+
if qualif.intersects(Qualif::NEEDS_DROP) {
335+
self.local_needs_drop[local] = Some(self.span);
336+
}
337+
}
338+
317339
match *dest {
318340
Lvalue::Local(index) if self.mir.local_kind(index) == LocalKind::Temp => {
319341
debug!("store to temp {:?}", index);
@@ -360,7 +382,6 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
360382

361383
let target = match mir[bb].terminator().kind {
362384
TerminatorKind::Goto { target } |
363-
// Drops are considered noops.
364385
TerminatorKind::Drop { target, .. } |
365386
TerminatorKind::Assert { target, .. } |
366387
TerminatorKind::Call { destination: Some((_, target)), .. } => {
@@ -558,11 +579,16 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
558579

559580
fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
560581
match *operand {
561-
Operand::Consume(_) => {
582+
Operand::Consume(ref lvalue) => {
562583
self.nest(|this| {
563584
this.super_operand(operand, location);
564585
this.try_consume();
565586
});
587+
588+
// Mark the consumed locals to indicate later drops are noops.
589+
if let Lvalue::Local(local) = *lvalue {
590+
self.local_needs_drop[local] = None;
591+
}
566592
}
567593
Operand::Constant(ref constant) => {
568594
if let Literal::Item { def_id, substs } = constant.literal {
@@ -864,6 +890,30 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
864890
}
865891
self.assign(dest, location);
866892
}
893+
} else if let TerminatorKind::Drop { location: ref lvalue, .. } = *kind {
894+
self.super_terminator_kind(bb, kind, location);
895+
896+
// Deny *any* live drops anywhere other than functions.
897+
if self.mode != Mode::Fn {
898+
// HACK(eddyb) Emulate a bit of dataflow analysis,
899+
// conservatively, that drop elaboration will do.
900+
let needs_drop = if let Lvalue::Local(local) = *lvalue {
901+
self.local_needs_drop[local]
902+
} else {
903+
None
904+
};
905+
906+
if let Some(span) = needs_drop {
907+
let ty = lvalue.ty(self.mir, self.tcx).to_ty(self.tcx);
908+
self.add_type(ty);
909+
910+
// Use the original assignment span to be more precise.
911+
let old_span = self.span;
912+
self.span = span;
913+
self.always_deny_drop();
914+
self.span = old_span;
915+
}
916+
}
867917
} else {
868918
// Qualify any operands inside other terminators.
869919
self.super_terminator_kind(bb, kind, location);

src/test/compile-fail/check-static-values-constraints.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,9 @@ static STATIC8: SafeStruct = SafeStruct{field1: SafeEnum::Variant1,
8686
// This example should fail because field1 in the base struct is not safe
8787
static STATIC9: SafeStruct = SafeStruct{field1: SafeEnum::Variant1,
8888
..SafeStruct{field1: SafeEnum::Variant3(WithDtor),
89+
//~^ ERROR destructors in statics are an unstable feature
90+
//~| ERROR statics are not allowed to have destructors
8991
field2: SafeEnum::Variant1}};
90-
//~^^ ERROR destructors in statics are an unstable feature
9192

9293
struct UnsafeStruct;
9394

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![feature(drop_types_in_const)]
12+
13+
struct WithDtor;
14+
15+
impl Drop for WithDtor {
16+
fn drop(&mut self) {}
17+
}
18+
19+
static FOO: Option<&'static WithDtor> = Some(&WithDtor);
20+
//~^ ERROR statics are not allowed to have destructors
21+
//~| ERROR borrowed value does not live long enoug
22+
23+
static BAR: i32 = (WithDtor, 0).1;
24+
//~^ ERROR statics are not allowed to have destructors
25+
26+
fn main () {}

0 commit comments

Comments
 (0)