Skip to content

Commit 62f2b49

Browse files
committed
auto merge of #5046 : sanxiyn/rust/struct-match, r=catamorphism
Previously check always succeeded because struct type was derived from the matched expression, not the matched pattern. Fix #4849.
2 parents 831840a + a29023e commit 62f2b49

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

src/librustc/middle/ty.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2823,7 +2823,7 @@ pub pure fn ty_fn_ret(fty: t) -> t {
28232823
}
28242824
}
28252825

2826-
fn is_fn_ty(fty: t) -> bool {
2826+
pub fn is_fn_ty(fty: t) -> bool {
28272827
match get(fty).sty {
28282828
ty_bare_fn(_) => true,
28292829
ty_closure(_) => true,

src/librustc/middle/typeck/check/_match.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ pub fn check_pat_variant(pcx: pat_ctxt, pat: @ast::pat, path: @ast::path,
9292
match structure_of(pcx.fcx, pat.span, expected) {
9393
ty::ty_enum(_, ref expected_substs) => {
9494
// Lookup the enum and variant def ids:
95-
let v_def = lookup_def(pcx.fcx, path.span, pat.id);
95+
let v_def = lookup_def(pcx.fcx, pat.span, pat.id);
9696
let v_def_ids = ast_util::variant_def_ids(v_def);
9797

9898
// Assign the pattern the type of the *enum*, not the variant.
@@ -125,8 +125,17 @@ pub fn check_pat_variant(pcx: pat_ctxt, pat: @ast::pat, path: @ast::path,
125125
kind_name = "variant";
126126
}
127127
ty::ty_struct(struct_def_id, ref expected_substs) => {
128+
// Lookup the struct ctor def id
129+
let s_def = lookup_def(pcx.fcx, pat.span, pat.id);
130+
let s_def_id = ast_util::def_id_of_def(s_def);
131+
128132
// Assign the pattern the type of the struct.
129-
let struct_tpt = ty::lookup_item_type(tcx, struct_def_id);
133+
let ctor_tpt = ty::lookup_item_type(tcx, s_def_id);
134+
let struct_tpt = if ty::is_fn_ty(ctor_tpt.ty) {
135+
{ty: ty::ty_fn_ret(ctor_tpt.ty), ..ctor_tpt}
136+
} else {
137+
ctor_tpt
138+
};
130139
instantiate_path(pcx.fcx, path, struct_tpt, pat.span, pat.id,
131140
pcx.block_region);
132141

src/test/compile-fail/match-struct.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// error-pattern: mismatched types
2+
3+
struct S { a: int }
4+
enum E { C(int) }
5+
6+
fn main() {
7+
match S { a: 1 } {
8+
C(_) => (),
9+
_ => ()
10+
}
11+
}

0 commit comments

Comments
 (0)