Skip to content

Check type when struct is matched against enum-like pattern #5046

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
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion src/librustc/middle/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2823,7 +2823,7 @@ pub pure fn ty_fn_ret(fty: t) -> t {
}
}

fn is_fn_ty(fty: t) -> bool {
pub fn is_fn_ty(fty: t) -> bool {
match get(fty).sty {
ty_bare_fn(_) => true,
ty_closure(_) => true,
Expand Down
13 changes: 11 additions & 2 deletions src/librustc/middle/typeck/check/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ pub fn check_pat_variant(pcx: pat_ctxt, pat: @ast::pat, path: @ast::path,
match structure_of(pcx.fcx, pat.span, expected) {
ty::ty_enum(_, ref expected_substs) => {
// Lookup the enum and variant def ids:
let v_def = lookup_def(pcx.fcx, path.span, pat.id);
let v_def = lookup_def(pcx.fcx, pat.span, pat.id);
let v_def_ids = ast_util::variant_def_ids(v_def);

// Assign the pattern the type of the *enum*, not the variant.
Expand Down Expand Up @@ -125,8 +125,17 @@ pub fn check_pat_variant(pcx: pat_ctxt, pat: @ast::pat, path: @ast::path,
kind_name = "variant";
}
ty::ty_struct(struct_def_id, ref expected_substs) => {
// Lookup the struct ctor def id
let s_def = lookup_def(pcx.fcx, pat.span, pat.id);
let s_def_id = ast_util::def_id_of_def(s_def);

// Assign the pattern the type of the struct.
let struct_tpt = ty::lookup_item_type(tcx, struct_def_id);
let ctor_tpt = ty::lookup_item_type(tcx, s_def_id);
let struct_tpt = if ty::is_fn_ty(ctor_tpt.ty) {
{ty: ty::ty_fn_ret(ctor_tpt.ty), ..ctor_tpt}
} else {
ctor_tpt
};
instantiate_path(pcx.fcx, path, struct_tpt, pat.span, pat.id,
pcx.block_region);

Expand Down
11 changes: 11 additions & 0 deletions src/test/compile-fail/match-struct.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// error-pattern: mismatched types

struct S { a: int }
enum E { C(int) }

fn main() {
match S { a: 1 } {
C(_) => (),
_ => ()
}
}