Skip to content

Check for borrow of local variable introduced within static block. #18124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/librustc/middle/check_static.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,15 @@ struct GlobalChecker {
static_consumptions: NodeSet,
const_borrows: NodeSet,
static_interior_borrows: NodeSet,
static_local_borrows: NodeSet,
}

pub fn check_crate(tcx: &ty::ctxt) {
let mut checker = GlobalChecker {
static_consumptions: NodeSet::new(),
const_borrows: NodeSet::new(),
static_interior_borrows: NodeSet::new(),
static_local_borrows: NodeSet::new(),
};
{
let visitor = euv::ExprUseVisitor::new(&mut checker, tcx);
Expand Down Expand Up @@ -200,6 +202,14 @@ impl<'a, 'tcx, 'v> Visitor<'v> for CheckStaticVisitor<'a, 'tcx> {
}
}

// local variables in a block expression in a static context (i.e. being
// assigned to a static variable) cannot be borrowed.
if self.checker.static_local_borrows.remove(&e.id) {
self.tcx.sess.span_err(e.span, "cannot borrow a local variable inside \
a static block, define a separate static \
instead");
}

match e.node {
ast::ExprAddrOf(ast::MutMutable, _) => {
if self.mode != InStaticMut {
Expand Down Expand Up @@ -298,8 +308,12 @@ impl euv::Delegate for GlobalChecker {

mc::cat_downcast(..) |
mc::cat_discr(..) |
mc::cat_upvar(..) |
mc::cat_local(..) => unreachable!(),
mc::cat_upvar(..) => unreachable!(),

mc::cat_local(..) => {
self.static_local_borrows.insert(borrow_id);
break
}
}
}
}
Expand Down