Skip to content

Commit 1fc29ef

Browse files
committed
auto merge of #14444 : huonw/rust/nice-for-errors, r=alexcrichton
Change `for` desugaring & make refutable pattern errors more precise This changes for to desugar to the `let`-based pattern match as described in #14390, and adjusts the compiler to use this information for error messages that even mention that it's in a `for` loop. Also, it makes the compiler record the exact positions of refutable parts of a pattern, to point to exactly them in error messages.
2 parents 1e2bb09 + 0df221e commit 1fc29ef

File tree

8 files changed

+140
-28
lines changed

8 files changed

+140
-28
lines changed

src/librustc/middle/check_match.rs

+43-22
Original file line numberDiff line numberDiff line change
@@ -863,9 +863,18 @@ fn default(cx: &MatchCheckCtxt, r: &[@Pat]) -> Option<Vec<@Pat> > {
863863

864864
fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {
865865
visit::walk_local(cx, loc, ());
866-
if is_refutable(cx, loc.pat) {
867-
cx.tcx.sess.span_err(loc.pat.span,
868-
"refutable pattern in local binding");
866+
867+
let name = match loc.source {
868+
LocalLet => "local",
869+
LocalFor => "`for` loop"
870+
};
871+
872+
let mut spans = vec![];
873+
find_refutable(cx, loc.pat, &mut spans);
874+
875+
for span in spans.iter() {
876+
cx.tcx.sess.span_err(*span,
877+
format!("refutable pattern in {} binding", name).as_slice());
869878
}
870879

871880
// Check legality of move bindings.
@@ -879,53 +888,65 @@ fn check_fn(cx: &mut MatchCheckCtxt,
879888
sp: Span) {
880889
visit::walk_fn(cx, kind, decl, body, sp, ());
881890
for input in decl.inputs.iter() {
882-
if is_refutable(cx, input.pat) {
883-
cx.tcx.sess.span_err(input.pat.span,
891+
let mut spans = vec![];
892+
find_refutable(cx, input.pat, &mut spans);
893+
894+
for span in spans.iter() {
895+
cx.tcx.sess.span_err(*span,
884896
"refutable pattern in function argument");
885897
}
886898
}
887899
}
888900

889-
fn is_refutable(cx: &MatchCheckCtxt, pat: &Pat) -> bool {
901+
fn find_refutable(cx: &MatchCheckCtxt, pat: &Pat, spans: &mut Vec<Span>) {
902+
macro_rules! this_pattern {
903+
() => {
904+
{
905+
spans.push(pat.span);
906+
return
907+
}
908+
}
909+
}
890910
let opt_def = cx.tcx.def_map.borrow().find_copy(&pat.id);
891911
match opt_def {
892912
Some(DefVariant(enum_id, _, _)) => {
893913
if ty::enum_variants(cx.tcx, enum_id).len() != 1u {
894-
return true;
914+
this_pattern!()
895915
}
896916
}
897-
Some(DefStatic(..)) => return true,
917+
Some(DefStatic(..)) => this_pattern!(),
898918
_ => ()
899919
}
900920

901921
match pat.node {
902922
PatUniq(sub) | PatRegion(sub) | PatIdent(_, _, Some(sub)) => {
903-
is_refutable(cx, sub)
923+
find_refutable(cx, sub, spans)
904924
}
905-
PatWild | PatWildMulti | PatIdent(_, _, None) => { false }
925+
PatWild | PatWildMulti | PatIdent(_, _, None) => {}
906926
PatLit(lit) => {
907927
match lit.node {
908928
ExprLit(lit) => {
909929
match lit.node {
910-
LitNil => false, // `()`
911-
_ => true,
930+
LitNil => {} // `()`
931+
_ => this_pattern!(),
912932
}
913933
}
914-
_ => true,
934+
_ => this_pattern!(),
915935
}
916936
}
917-
PatRange(_, _) => { true }
937+
PatRange(_, _) => { this_pattern!() }
918938
PatStruct(_, ref fields, _) => {
919-
fields.iter().any(|f| is_refutable(cx, f.pat))
920-
}
921-
PatTup(ref elts) => {
922-
elts.iter().any(|elt| is_refutable(cx, *elt))
939+
for f in fields.iter() {
940+
find_refutable(cx, f.pat, spans);
941+
}
923942
}
924-
PatEnum(_, Some(ref args)) => {
925-
args.iter().any(|a| is_refutable(cx, *a))
943+
PatTup(ref elts) | PatEnum(_, Some(ref elts))=> {
944+
for elt in elts.iter() {
945+
find_refutable(cx, *elt, spans)
946+
}
926947
}
927-
PatEnum(_,_) => { false }
928-
PatVec(..) => { true }
948+
PatEnum(_,_) => {}
949+
PatVec(..) => { this_pattern!() }
929950
}
930951
}
931952

src/libsyntax/ast.rs

+9
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,14 @@ pub enum Stmt_ {
417417
StmtMac(Mac, bool),
418418
}
419419

420+
/// Where a local declaration came from: either a true `let ... =
421+
/// ...;`, or one desugared from the pattern of a for loop.
422+
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
423+
pub enum LocalSource {
424+
LocalLet,
425+
LocalFor,
426+
}
427+
420428
// FIXME (pending discussion of #1697, #2178...): local should really be
421429
// a refinement on pat.
422430
/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
@@ -427,6 +435,7 @@ pub struct Local {
427435
pub init: Option<@Expr>,
428436
pub id: NodeId,
429437
pub span: Span,
438+
pub source: LocalSource,
430439
}
431440

432441
pub type Decl = Spanned<Decl_>;

src/libsyntax/ext/build.rs

+2
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
439439
init: Some(ex),
440440
id: ast::DUMMY_NODE_ID,
441441
span: sp,
442+
source: ast::LocalLet,
442443
};
443444
let decl = respan(sp, ast::DeclLocal(local));
444445
@respan(sp, ast::StmtDecl(@decl, ast::DUMMY_NODE_ID))
@@ -462,6 +463,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
462463
init: Some(ex),
463464
id: ast::DUMMY_NODE_ID,
464465
span: sp,
466+
source: ast::LocalLet,
465467
};
466468
let decl = respan(sp, ast::DeclLocal(local));
467469
@respan(sp, ast::StmtDecl(@decl, ast::DUMMY_NODE_ID))

src/libsyntax/ext/expand.rs

+35-5
Original file line numberDiff line numberDiff line change
@@ -147,11 +147,17 @@ pub fn expand_expr(e: @ast::Expr, fld: &mut MacroExpander) -> @ast::Expr {
147147
// ['<ident>:] loop {
148148
// match i.next() {
149149
// None => break,
150-
// Some(<src_pat>) => <src_loop_block>
150+
// Some(mut value) => {
151+
// let <src_pat> = value;
152+
// <src_loop_block>
153+
// }
151154
// }
152155
// }
153156
// }
154157
// }
158+
//
159+
// (The use of the `let` is to give better error messages
160+
// when the pattern is refutable.)
155161

156162
let local_ident = token::gensym_ident("__i"); // FIXME #13573
157163
let next_ident = fld.cx.ident_of("next");
@@ -167,11 +173,33 @@ pub fn expand_expr(e: @ast::Expr, fld: &mut MacroExpander) -> @ast::Expr {
167173
fld.cx.arm(span, vec!(none_pat), break_expr)
168174
};
169175

170-
// `Some(<src_pat>) => <src_loop_block>`
176+
// let <src_pat> = value;
177+
let value_ident = token::gensym_ident("__value");
178+
// this is careful to use src_pat.span so that error
179+
// messages point exact at that.
180+
let local = @ast::Local {
181+
ty: fld.cx.ty_infer(src_pat.span),
182+
pat: src_pat,
183+
init: Some(fld.cx.expr_ident(src_pat.span, value_ident)),
184+
id: ast::DUMMY_NODE_ID,
185+
span: src_pat.span,
186+
source: ast::LocalFor
187+
};
188+
let local = codemap::respan(src_pat.span, ast::DeclLocal(local));
189+
let local = @codemap::respan(span, ast::StmtDecl(@local, ast::DUMMY_NODE_ID));
190+
191+
// { let ...; <src_loop_block> }
192+
let block = fld.cx.block(span, vec![local],
193+
Some(fld.cx.expr_block(src_loop_block)));
194+
195+
// `Some(mut value) => { ... }`
196+
// Note the _'s in the name will stop any unused mutability warnings.
197+
let value_pat = fld.cx.pat_ident_binding_mode(span, value_ident,
198+
ast::BindByValue(ast::MutMutable));
171199
let some_arm =
172200
fld.cx.arm(span,
173-
vec!(fld.cx.pat_enum(span, some_path, vec!(src_pat))),
174-
fld.cx.expr_block(src_loop_block));
201+
vec!(fld.cx.pat_enum(span, some_path, vec!(value_pat))),
202+
fld.cx.expr_block(block));
175203

176204
// `match i.next() { ... }`
177205
let match_expr = {
@@ -669,7 +697,8 @@ fn expand_non_macro_stmt(s: &Stmt, fld: &mut MacroExpander)
669697
pat: pat,
670698
init: init,
671699
id: id,
672-
span: span
700+
span: span,
701+
source: source,
673702
} = **local;
674703
// expand the pat (it might contain exprs... #:(o)>
675704
let expanded_pat = fld.fold_pat(pat);
@@ -703,6 +732,7 @@ fn expand_non_macro_stmt(s: &Stmt, fld: &mut MacroExpander)
703732
init: new_init_opt,
704733
id: id,
705734
span: span,
735+
source: source
706736
};
707737
SmallVector::one(@Spanned {
708738
node: StmtDecl(@Spanned {

src/libsyntax/fold.rs

+1
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,7 @@ pub trait Folder {
288288
pat: self.fold_pat(l.pat),
289289
init: l.init.map(|e| self.fold_expr(e)),
290290
span: self.new_span(l.span),
291+
source: l.source,
291292
}
292293
}
293294

src/libsyntax/parse/parser.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use ast::{Ident, NormalFn, Inherited, Item, Item_, ItemStatic};
3434
use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
3535
use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
3636
use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar};
37-
use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local};
37+
use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local, LocalLet};
3838
use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
3939
use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
4040
use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
@@ -3034,6 +3034,7 @@ impl<'a> Parser<'a> {
30343034
init: init,
30353035
id: ast::DUMMY_NODE_ID,
30363036
span: mk_sp(lo, self.last_span.hi),
3037+
source: LocalLet,
30373038
}
30383039
}
30393040

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
12+
fn main() {
13+
for
14+
&1 //~ ERROR refutable pattern in `for` loop binding
15+
in [1].iter() {}
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
12+
fn func(
13+
(
14+
1, //~ ERROR refutable pattern in function argument
15+
(
16+
Some( //~ ERROR refutable pattern in function argument
17+
1), // nested, so no warning.
18+
2..3 //~ ERROR refutable pattern in function argument
19+
)
20+
): (int, (Option<int>, int))
21+
) {}
22+
23+
fn main() {
24+
let (
25+
1, //~ ERROR refutable pattern in local binding
26+
(
27+
Some( //~ ERROR refutable pattern in local binding
28+
1), // nested, so no warning.
29+
2..3 //~ ERROR refutable pattern in local binding
30+
)
31+
) = (1, (None, 2));
32+
}

0 commit comments

Comments
 (0)