Support deriving some traits for unions

This commit is contained in:
Vadim Petrochenkov 2016-08-24 21:10:19 +03:00
parent 079c390d50
commit 59ccb7b6db
3 changed files with 71 additions and 1 deletions

View file

@ -410,9 +410,18 @@ impl<'a> TraitDef<'a> {
ast::ItemKind::Enum(ref enum_def, ref generics) => {
self.expand_enum_def(cx, enum_def, &item.attrs, item.ident, generics)
}
ast::ItemKind::Union(ref struct_def, ref generics) => {
if self.supports_unions {
self.expand_struct_def(cx, &struct_def, item.ident, generics)
} else {
cx.span_err(mitem.span,
"this trait cannot be derived for unions");
return;
}
}
_ => {
cx.span_err(mitem.span,
"`derive` may only be applied to structs and enums");
"`derive` may only be applied to structs, enums and unions");
return;
}
};

View file

@ -0,0 +1,30 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Most traits cannot be derived for unions.
#![feature(untagged_unions)]
#[derive(
Clone, //~ ERROR this trait cannot be derived for unions
PartialEq, //~ ERROR this trait cannot be derived for unions
Eq, //~ ERROR this trait cannot be derived for unions
PartialOrd, //~ ERROR this trait cannot be derived for unions
Ord, //~ ERROR this trait cannot be derived for unions
Hash, //~ ERROR this trait cannot be derived for unions
Default, //~ ERROR this trait cannot be derived for unions
Debug, //~ ERROR this trait cannot be derived for unions
)]
union U {
a: u8,
b: u16,
}
fn main() {}

View file

@ -0,0 +1,31 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Some traits can be derived for unions.
#![feature(untagged_unions)]
#[derive(
Copy,
)]
union U {
a: u8,
b: u16,
}
impl Clone for U {
fn clone(&self) -> Self { *self }
}
fn main() {
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
}