Skip to content

Commit e402e75

Browse files
committed
auto merge of #14350 : zwarich/rust/let-suggestion, r=pcwalton
2 parents 8d50d6a + 516a177 commit e402e75

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/librustc/middle/borrowck/mod.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -689,11 +689,16 @@ impl<'a> BorrowckCtxt<'a> {
689689
"reference must be valid for ",
690690
sub_scope,
691691
"...");
692+
let suggestion = if is_statement_scope(self.tcx, super_scope) {
693+
"; consider using a `let` binding to increase its lifetime"
694+
} else {
695+
""
696+
};
692697
note_and_explain_region(
693698
self.tcx,
694699
"...but borrowed value is only valid for ",
695700
super_scope,
696-
"");
701+
suggestion);
697702
}
698703

699704
err_borrowed_pointer_too_short(loan_scope, ptr_scope, _) => {
@@ -779,6 +784,18 @@ impl<'a> BorrowckCtxt<'a> {
779784
}
780785
}
781786

787+
fn is_statement_scope(tcx: &ty::ctxt, region: ty::Region) -> bool {
788+
match region {
789+
ty::ReScope(node_id) => {
790+
match tcx.map.find(node_id) {
791+
Some(ast_map::NodeStmt(_)) => true,
792+
_ => false
793+
}
794+
}
795+
_ => false
796+
}
797+
}
798+
782799
impl DataFlowOperator for LoanDataFlowOperator {
783800
#[inline]
784801
fn initial_value(&self) -> bool {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Copyright 2014 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+
fn f() {
12+
let x = [1].iter(); //~ ERROR borrowed value does not live long enough
13+
//~^^ NOTE reference must be valid for the block
14+
//~^^ NOTE consider using a `let` binding to increase its lifetime
15+
}
16+
17+
fn main() {
18+
f();
19+
}
20+

0 commit comments

Comments
 (0)