diff --git a/third_party/rust/bindgen/.cargo-checksum.json b/third_party/rust/bindgen/.cargo-checksum.json index ebe19dd44919..b50749c740fc 100644 --- a/third_party/rust/bindgen/.cargo-checksum.json +++ b/third_party/rust/bindgen/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"7bd5f5264fe47e6bcf50e68017053799b39b8cddaaef5c4690193cb25d70d413","LICENSE":"c23953d9deb0a3312dbeaf6c128a657f3591acee45067612fa68405eaa4525db","README.md":"5a1f556c6a57c0a6ccc65e19c27718e0f4b32381a8efcc80f6601b33c58c5d59","build.rs":"a9f6915c54d75f357ce32f96327bf4df53dc81a505b70831978f9dac6f43841d","src/callbacks.rs":"b24d7982332c6a35928f134184ddf4072fe4545a45546b97b9b0e0c1fbb77c08","src/clang.rs":"e9203eb5a1b432efebafcd011896e35e8c9145037bf99e7bb3709dc1b8e8e783","src/codegen/bitfield_unit.rs":"87be2d7f7774327a1608c2c4d64df869e17fb34b7efdacb4030b6794d98e40f3","src/codegen/bitfield_unit_tests.rs":"2073ac6a36e0bc9afaef5b1207966817c8fb7a1a9f6368c3b1b8f79822efbfba","src/codegen/error.rs":"2613af1d833377fd4a70719f4a09951d9d45dc9227827b9a2a938a1bcaaea2dd","src/codegen/helpers.rs":"aa0daff2061c6de31acfbd113190889e0f7ca2d2b8d4f46740bfd5832c33e4d2","src/codegen/impl_debug.rs":"f82969461d522fb758eca552ceaf189122a404cbb47fcc16008bfe52fc62aefa","src/codegen/impl_partialeq.rs":"d40d9ee2849c4d3d557b033c4d3af5e6de4a44347f67c0f016198086338811af","src/codegen/mod.rs":"9fb48eb14ef1f97e313fe13cfbc1ca96d74262f7a229f1f94011b52079d3df5b","src/codegen/struct_layout.rs":"3fa5524aff82365ce292b0cc85080514c85a6dbd31bce90f001773b995dda28e","src/extra_assertions.rs":"494534bd4f18b80d89b180c8a93733e6617edcf7deac413e9a73fd6e7bc9ced7","src/features.rs":"82511f1bb8cbd04d98f57b000903b0264237962af93a72a58220437213eba1ef","src/ir/analysis/derive.rs":"325d4c1c1e6194e743f42a2316f1501b0ef852fe309f2e9cac3434825ad235f0","src/ir/analysis/has_destructor.rs":"63644f479738df35e531d3324ff892614083c3656e0747aa34d9f20dada878ec","src/ir/analysis/has_float.rs":"76162a309e4285a806755a08c687a3e7bc894a100a63da4e88584035e215b11d","src/ir/analysis/has_type_param_in_array.rs":"fdbc0af28a144c88ea2de83e6e6da5e1ffb40e3dd63fd7a708095d085bb06f94","src/ir/analysis/has_vtable.rs":"5788372d27bdbaaf0454bc17be31a5480918bc41a8a1c4832e8c61185c07f9cd","src/ir/analysis/mod.rs":"1f218e15c19f6666512908abc853fa7ff9ca5d0fafd94f026d9e4b0ce287ec3c","src/ir/analysis/sizedness.rs":"b73865b6689d4f3546edd91909a47c329c4ae630ea97715d29bc683ae1dc17ad","src/ir/analysis/template_params.rs":"6312c008bbc80f50e72a766756c8daddea0b6eeb31ec924b83a231df931e170e","src/ir/annotations.rs":"39a5ab19f4d5dfa617577e4a0d0d2b67b5369d480c7cca4b14d172458c9843f0","src/ir/comment.rs":"c48abe01c5af0f09f583a89f1394bc6c161b40f6c8f0f600bbfe3c907b47969b","src/ir/comp.rs":"498dc771461f9f30db712dd5596fc959133ec5583e2ba6b75036b9afe9d28dcd","src/ir/context.rs":"599226eb04d337a1b1b13af91af91bdb02dbd5f26f274cbc0ebc4489eb144fc0","src/ir/derive.rs":"34f9aa76b6c9c05136bb69dcd6455397faef571a567254d2c541d50a962994db","src/ir/dot.rs":"95ed2968fc3239d87892e9f1edf1ed6dd18630d949564961765967ea1d16960c","src/ir/enum_ty.rs":"7658cf68c00b1732dfa599c2d6b6a93a82de8401142591c3afe5fcb27d901a66","src/ir/function.rs":"c2feb2e26d47aa96a74af9912ada26be077e2b0c36d46fa10167da7109590500","src/ir/int.rs":"07e0c7dbd2dd977177fae3acd2a14adf271c6cf9ff4b57cddc11d50734fd4801","src/ir/item.rs":"3bcdb69b793350e5744aec3577cdbb1e5068ece5220c38763cecd82dfb5e8f03","src/ir/item_kind.rs":"dbeae8c4fd0e5c9485d325aea040e056a1f2cd6d43fc927dee8fe1c0c59a7197","src/ir/layout.rs":"d49582081f5f86f7595afbe4845f38fb3b969a840b568f4a49b265e7d790bb5b","src/ir/mod.rs":"2eae90f207fad2e45957ec9287064992a419e3fc916aba84faff2ea25cbeb5ee","src/ir/module.rs":"c4d90bf38fe3672e01923734ccbdb7951ea929949d5f413a9c2aee12395a5094","src/ir/objc.rs":"758aa955a0c5d6ad82606c88a1f4cd1d93e666b71e82d43b18b1aaae96cf888a","src/ir/template.rs":"c0f8570b927dfd6a421fc4ce3094ec837a3ed936445225dbfac961e8e0842ae5","src/ir/traversal.rs":"ea751379a5aec02f93f8d2c61e18232776b1f000dbeae64b9a7195ba21a19dd6","src/ir/ty.rs":"952fb04cd6a71a2bca5c509aecacb42a1de0cae75824941541a38dc589f0993a","src/ir/var.rs":"8bdafb6d02f2c55ae11c28d88b19fb7a65ba8466da12ff039ae4c16c790b291e","src/lib.rs":"4ca6c5dd71ecac737b4710b4bc65435be11889375be564e9a080879387211247","src/log_stubs.rs":"6dfdd908b7c6453da416cf232893768f9480e551ca4add0858ef88bf71ee6ceb","src/main.rs":"8c96cd2a051e3f09b1b87b75cd9ed77e82e889c8309ebd3e4bc782960cf63e58","src/options.rs":"5b309b225cc51e665bd42ed3e7965a7cd73d984e4455a2d76987fc42ab271ff8","src/parse.rs":"be7d13cc84fae79ec7b3aa9e77063fa475a48d74a854423e2c72d75006a25202","src/regex_set.rs":"5cb72fc3714c0d79e9e942d003349c0775fafd7cd0c9603c65f5261883bbf9cf","src/time.rs":"3b763e6fee51d0eb01228dfe28bc28a9f692aff73b2a7b90a030902e0238fca6"},"package":"6cdac0c63ff3380328d5c427ba4ac8bca04cdd9d3a0379c6e56a43c82a364014"} \ No newline at end of file +{"files":{"Cargo.toml":"034bdf9e159572fd8c6d964d44cc4bf23d08bf39d1925468d9a911022216aa1c","LICENSE":"c23953d9deb0a3312dbeaf6c128a657f3591acee45067612fa68405eaa4525db","README.md":"5a1f556c6a57c0a6ccc65e19c27718e0f4b32381a8efcc80f6601b33c58c5d59","build.rs":"a9f6915c54d75f357ce32f96327bf4df53dc81a505b70831978f9dac6f43841d","src/callbacks.rs":"b24d7982332c6a35928f134184ddf4072fe4545a45546b97b9b0e0c1fbb77c08","src/clang.rs":"e9203eb5a1b432efebafcd011896e35e8c9145037bf99e7bb3709dc1b8e8e783","src/codegen/bitfield_unit.rs":"88b0604322dc449fc9284850eadc1f5d14b42fa747d4258bae0b6b9535f52dfd","src/codegen/bitfield_unit_tests.rs":"2073ac6a36e0bc9afaef5b1207966817c8fb7a1a9f6368c3b1b8f79822efbfba","src/codegen/error.rs":"2613af1d833377fd4a70719f4a09951d9d45dc9227827b9a2a938a1bcaaea2dd","src/codegen/helpers.rs":"fbd23e68dd51ccaddeb9761394d5df2db49baded0e2dccf6bbc52a2d6de502eb","src/codegen/impl_debug.rs":"f82969461d522fb758eca552ceaf189122a404cbb47fcc16008bfe52fc62aefa","src/codegen/impl_partialeq.rs":"d40d9ee2849c4d3d557b033c4d3af5e6de4a44347f67c0f016198086338811af","src/codegen/mod.rs":"1b2fa9bea03d2e155664ad64ee4d97c885b48e1d1bfa74d5f8bb2812685e3a8f","src/codegen/struct_layout.rs":"3fa5524aff82365ce292b0cc85080514c85a6dbd31bce90f001773b995dda28e","src/extra_assertions.rs":"494534bd4f18b80d89b180c8a93733e6617edcf7deac413e9a73fd6e7bc9ced7","src/features.rs":"c5fd7149f4a3b41fd4f89ade08505170942f4bc791bcb6a34fdddd3ae61856f8","src/ir/analysis/derive.rs":"325d4c1c1e6194e743f42a2316f1501b0ef852fe309f2e9cac3434825ad235f0","src/ir/analysis/has_destructor.rs":"63644f479738df35e531d3324ff892614083c3656e0747aa34d9f20dada878ec","src/ir/analysis/has_float.rs":"76162a309e4285a806755a08c687a3e7bc894a100a63da4e88584035e215b11d","src/ir/analysis/has_type_param_in_array.rs":"fdbc0af28a144c88ea2de83e6e6da5e1ffb40e3dd63fd7a708095d085bb06f94","src/ir/analysis/has_vtable.rs":"5788372d27bdbaaf0454bc17be31a5480918bc41a8a1c4832e8c61185c07f9cd","src/ir/analysis/mod.rs":"1f218e15c19f6666512908abc853fa7ff9ca5d0fafd94f026d9e4b0ce287ec3c","src/ir/analysis/sizedness.rs":"b73865b6689d4f3546edd91909a47c329c4ae630ea97715d29bc683ae1dc17ad","src/ir/analysis/template_params.rs":"6312c008bbc80f50e72a766756c8daddea0b6eeb31ec924b83a231df931e170e","src/ir/annotations.rs":"39a5ab19f4d5dfa617577e4a0d0d2b67b5369d480c7cca4b14d172458c9843f0","src/ir/comment.rs":"c48abe01c5af0f09f583a89f1394bc6c161b40f6c8f0f600bbfe3c907b47969b","src/ir/comp.rs":"498dc771461f9f30db712dd5596fc959133ec5583e2ba6b75036b9afe9d28dcd","src/ir/context.rs":"599226eb04d337a1b1b13af91af91bdb02dbd5f26f274cbc0ebc4489eb144fc0","src/ir/derive.rs":"34f9aa76b6c9c05136bb69dcd6455397faef571a567254d2c541d50a962994db","src/ir/dot.rs":"95ed2968fc3239d87892e9f1edf1ed6dd18630d949564961765967ea1d16960c","src/ir/enum_ty.rs":"9cc242d6b3c1866665594e8b306860ee39c0ea42d22198d46b7fded473fe3e84","src/ir/function.rs":"c2feb2e26d47aa96a74af9912ada26be077e2b0c36d46fa10167da7109590500","src/ir/int.rs":"07e0c7dbd2dd977177fae3acd2a14adf271c6cf9ff4b57cddc11d50734fd4801","src/ir/item.rs":"3bcdb69b793350e5744aec3577cdbb1e5068ece5220c38763cecd82dfb5e8f03","src/ir/item_kind.rs":"dbeae8c4fd0e5c9485d325aea040e056a1f2cd6d43fc927dee8fe1c0c59a7197","src/ir/layout.rs":"d49582081f5f86f7595afbe4845f38fb3b969a840b568f4a49b265e7d790bb5b","src/ir/mod.rs":"2eae90f207fad2e45957ec9287064992a419e3fc916aba84faff2ea25cbeb5ee","src/ir/module.rs":"c4d90bf38fe3672e01923734ccbdb7951ea929949d5f413a9c2aee12395a5094","src/ir/objc.rs":"758aa955a0c5d6ad82606c88a1f4cd1d93e666b71e82d43b18b1aaae96cf888a","src/ir/template.rs":"c0f8570b927dfd6a421fc4ce3094ec837a3ed936445225dbfac961e8e0842ae5","src/ir/traversal.rs":"ea751379a5aec02f93f8d2c61e18232776b1f000dbeae64b9a7195ba21a19dd6","src/ir/ty.rs":"952fb04cd6a71a2bca5c509aecacb42a1de0cae75824941541a38dc589f0993a","src/ir/var.rs":"8bdafb6d02f2c55ae11c28d88b19fb7a65ba8466da12ff039ae4c16c790b291e","src/lib.rs":"c70ac864de653e078fc9cfc2c808eb1cc888d83b38d003954993a166659ffe1a","src/log_stubs.rs":"6dfdd908b7c6453da416cf232893768f9480e551ca4add0858ef88bf71ee6ceb","src/main.rs":"8c96cd2a051e3f09b1b87b75cd9ed77e82e889c8309ebd3e4bc782960cf63e58","src/options.rs":"e51c06d11fb79abc1f74ce421b0fd9d0a6517f1a2e2bf81a5b2f738f92a5f182","src/parse.rs":"be7d13cc84fae79ec7b3aa9e77063fa475a48d74a854423e2c72d75006a25202","src/regex_set.rs":"5cb72fc3714c0d79e9e942d003349c0775fafd7cd0c9603c65f5261883bbf9cf","src/time.rs":"3b763e6fee51d0eb01228dfe28bc28a9f692aff73b2a7b90a030902e0238fca6"},"package":"846a1fba6535362a01487ef6b10f0275faa12e5c5d835c5c1c627aabc46ccbd6"} \ No newline at end of file diff --git a/third_party/rust/bindgen/Cargo.toml b/third_party/rust/bindgen/Cargo.toml index 11763304bbd8..3585357117a1 100644 --- a/third_party/rust/bindgen/Cargo.toml +++ b/third_party/rust/bindgen/Cargo.toml @@ -12,7 +12,7 @@ [package] name = "bindgen" -version = "0.49.3" +version = "0.49.2" authors = ["Jyun-Yan You ", "Emilio Cobos Álvarez ", "Nick Fitzgerald ", "The Servo project developers"] build = "build.rs" include = ["LICENSE", "README.md", "Cargo.toml", "build.rs", "src/*.rs", "src/**/*.rs"] @@ -32,7 +32,6 @@ path = "src/lib.rs" name = "bindgen" path = "src/main.rs" doc = false -required-features = ["clap"] [dependencies.bitflags] version = "1.0.3" @@ -48,7 +47,6 @@ features = ["runtime", "clang_6_0"] [dependencies.clap] version = "2" -optional = true [dependencies.env_logger] version = "0.6" @@ -93,7 +91,7 @@ version = "0.1" version = "0.1" [features] -default = ["logging", "clap"] +default = ["logging"] logging = ["env_logger", "log"] static = [] testing_only_docs = [] diff --git a/third_party/rust/bindgen/src/codegen/bitfield_unit.rs b/third_party/rust/bindgen/src/codegen/bitfield_unit.rs index caab2dc69aff..7f263fd12f29 100755 --- a/third_party/rust/bindgen/src/codegen/bitfield_unit.rs +++ b/third_party/rust/bindgen/src/codegen/bitfield_unit.rs @@ -1,26 +1,25 @@ #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit +where + Storage: AsRef<[u8]> + AsMut<[u8]>, { storage: Storage, align: [Align; 0], } impl __BindgenBitfieldUnit +where + Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] - pub const fn new(storage: Storage) -> Self { + pub fn new(storage: Storage) -> Self { Self { storage, align: [], } } -} -impl __BindgenBitfieldUnit -where - Storage: AsRef<[u8]> + AsMut<[u8]>, -{ #[inline] pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); diff --git a/third_party/rust/bindgen/src/codegen/helpers.rs b/third_party/rust/bindgen/src/codegen/helpers.rs index 1e8534ee094f..b630a70bd514 100644 --- a/third_party/rust/bindgen/src/codegen/helpers.rs +++ b/third_party/rust/bindgen/src/codegen/helpers.rs @@ -42,12 +42,6 @@ pub mod attributes { } } - pub fn non_exhaustive() -> TokenStream { - quote! { - #[non_exhaustive] - } - } - pub fn doc(comment: String) -> TokenStream { // NOTE(emilio): By this point comments are already preprocessed and in // `///` form. Quote turns them into `#[doc]` comments, but oh well. diff --git a/third_party/rust/bindgen/src/codegen/mod.rs b/third_party/rust/bindgen/src/codegen/mod.rs index 15ace9e91c73..c3b869831922 100644 --- a/third_party/rust/bindgen/src/codegen/mod.rs +++ b/third_party/rust/bindgen/src/codegen/mod.rs @@ -410,7 +410,7 @@ impl CodeGenerator for Module { utils::prepend_objc_header(ctx, &mut *result); } if result.saw_bitfield_unit { - utils::prepend_bitfield_unit_type(ctx, &mut *result); + utils::prepend_bitfield_unit_type(&mut *result); } } }; @@ -2170,10 +2170,7 @@ impl MethodCodegen for Method { #[derive(Copy, Clone, PartialEq, Debug)] pub enum EnumVariation { /// The code for this enum will use a Rust enum - Rust { - /// Indicates whether the generated struct should be #[non_exhaustive] - non_exhaustive: bool - }, + Rust, /// The code for this enum will use a bitfield Bitfield, /// The code for this enum will use consts @@ -2185,7 +2182,14 @@ pub enum EnumVariation { impl EnumVariation { fn is_rust(&self) -> bool { match *self { - EnumVariation::Rust{ .. } => true, + EnumVariation::Rust => true, + _ => false + } + } + + fn is_bitfield(&self) -> bool { + match *self { + EnumVariation::Bitfield {..} => true, _ => false } } @@ -2212,14 +2216,13 @@ impl std::str::FromStr for EnumVariation { /// Create a `EnumVariation` from a string. fn from_str(s: &str) -> Result { match s { - "rust" => Ok(EnumVariation::Rust{ non_exhaustive: false }), - "rust_non_exhaustive" => Ok(EnumVariation::Rust{ non_exhaustive: true }), + "rust" => Ok(EnumVariation::Rust), "bitfield" => Ok(EnumVariation::Bitfield), "consts" => Ok(EnumVariation::Consts), "moduleconsts" => Ok(EnumVariation::ModuleConsts), _ => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, concat!("Got an invalid EnumVariation. Accepted values ", - "are 'rust', 'rust_non_exhaustive', 'bitfield', 'consts', and ", + "are 'rust', 'bitfield', 'consts', and ", "'moduleconsts'."))), } } @@ -2285,7 +2288,7 @@ impl<'a> EnumBuilder<'a> { } } - EnumVariation::Rust { .. } => { + EnumVariation::Rust => { let tokens = quote!(); EnumBuilder::Rust { codegen_depth: enum_codegen_depth + 1, @@ -2577,24 +2580,15 @@ impl CodeGenerator for Enum { let variation = self.computed_enum_variation(ctx, item); // TODO(emilio): Delegate this to the builders? - match variation { - EnumVariation::Rust { non_exhaustive } => { - attrs.push(attributes::repr(repr_name)); - if non_exhaustive && ctx.options().rust_features().non_exhaustive { - attrs.push(attributes::non_exhaustive()); - } else if non_exhaustive && !ctx.options().rust_features().non_exhaustive { - panic!("The rust target you're using doesn't seem to support non_exhaustive enums"); - } - }, - EnumVariation::Bitfield => { - if ctx.options().rust_features.repr_transparent { - attrs.push(attributes::repr("transparent")); - } else { - attrs.push(attributes::repr("C")); - } - }, - _ => {}, - }; + if variation.is_rust() { + attrs.push(attributes::repr(repr_name)); + } else if variation.is_bitfield() { + if ctx.options().rust_features.repr_transparent { + attrs.push(attributes::repr("transparent")); + } else { + attrs.push(attributes::repr("C")); + } + } if let Some(comment) = item.comment(ctx) { attrs.push(attributes::doc(comment)); @@ -3597,21 +3591,11 @@ mod utils { use ir::item::{Item, ItemCanonicalPath}; use ir::ty::TypeKind; use proc_macro2; - use std::borrow::Cow; use std::mem; use std::str::FromStr; - pub fn prepend_bitfield_unit_type( - ctx: &BindgenContext, - result: &mut Vec - ) { - let bitfield_unit_src = include_str!("./bitfield_unit.rs"); - let bitfield_unit_src = if ctx.options().rust_features().min_const_fn { - Cow::Borrowed(bitfield_unit_src) - } else { - Cow::Owned(bitfield_unit_src.replace("const fn ", "fn ")) - }; - let bitfield_unit_type = proc_macro2::TokenStream::from_str(&bitfield_unit_src).unwrap(); + pub fn prepend_bitfield_unit_type(result: &mut Vec) { + let bitfield_unit_type = proc_macro2::TokenStream::from_str(include_str!("./bitfield_unit.rs")).unwrap(); let bitfield_unit_type = quote!(#bitfield_unit_type); let items = vec![bitfield_unit_type]; @@ -3669,14 +3653,6 @@ mod utils { ) { let prefix = ctx.trait_prefix(); - // If the target supports `const fn`, declare eligible functions - // as `const fn` else just `fn`. - let const_fn = if ctx.options().rust_features().min_const_fn { - quote!{ const fn } - } else { - quote!{ fn } - }; - // TODO(emilio): The fmt::Debug impl could be way nicer with // std::intrinsics::type_name, but... let union_field_decl = quote! { @@ -3687,7 +3663,7 @@ mod utils { let union_field_impl = quote! { impl __BindgenUnionField { #[inline] - pub #const_fn new() -> Self { + pub fn new() -> Self { __BindgenUnionField(::#prefix::marker::PhantomData) } @@ -3776,14 +3752,6 @@ mod utils { ) { let prefix = ctx.trait_prefix(); - // If the target supports `const fn`, declare eligible functions - // as `const fn` else just `fn`. - let const_fn = if ctx.options().rust_features().min_const_fn { - quote!{ const fn } - } else { - quote!{ fn } - }; - let incomplete_array_decl = quote! { #[repr(C)] #[derive(Default)] @@ -3794,7 +3762,7 @@ mod utils { let incomplete_array_impl = quote! { impl __IncompleteArrayField { #[inline] - pub #const_fn new() -> Self { + pub fn new() -> Self { __IncompleteArrayField(::#prefix::marker::PhantomData, []) } diff --git a/third_party/rust/bindgen/src/features.rs b/third_party/rust/bindgen/src/features.rs index 4dc526ec674b..50759c318968 100644 --- a/third_party/rust/bindgen/src/features.rs +++ b/third_party/rust/bindgen/src/features.rs @@ -102,8 +102,6 @@ macro_rules! rust_target_base { => Stable_1_27 => 1.27; /// Rust stable 1.28 => Stable_1_28 => 1.28; - /// Rust stable 1.30 - => Stable_1_30 => 1.30; /// Rust stable 1.33 => Stable_1_33 => 1.33; /// Nightly rust @@ -194,11 +192,6 @@ rust_feature_def!( /// repr(transparent) ([PR](https://github.com/rust-lang/rust/pull/51562)) => repr_transparent; } - Stable_1_30 { - /// `const fn` support for limited cases - /// ([PR](https://github.com/rust-lang/rust/pull/54835/) - => min_const_fn; - } Stable_1_33 { /// repr(packed(N)) ([PR](https://github.com/rust-lang/rust/pull/57049)) => repr_packed_n; @@ -206,8 +199,6 @@ rust_feature_def!( Nightly { /// `thiscall` calling convention ([Tracking issue](https://github.com/rust-lang/rust/issues/42202)) => thiscall_abi; - /// `non_exhaustive` enums/structs ([Tracking issue](https://github.com/rust-lang/rust/issues/44109)) - => non_exhaustive; } ); diff --git a/third_party/rust/bindgen/src/ir/enum_ty.rs b/third_party/rust/bindgen/src/ir/enum_ty.rs index be33ed4b7654..f3da21997afb 100644 --- a/third_party/rust/bindgen/src/ir/enum_ty.rs +++ b/third_party/rust/bindgen/src/ir/enum_ty.rs @@ -164,9 +164,7 @@ impl Enum { } else if self.is_matching_enum(ctx, &ctx.options().bitfield_enums, item) { EnumVariation::Bitfield } else if self.is_matching_enum(ctx, &ctx.options().rustified_enums, item) { - EnumVariation::Rust { non_exhaustive: false } - } else if self.is_matching_enum(ctx, &ctx.options().rustified_non_exhaustive_enums, item) { - EnumVariation::Rust { non_exhaustive: true } + EnumVariation::Rust } else if self.is_matching_enum(ctx, &ctx.options().constified_enums, item) { EnumVariation::Consts } else { diff --git a/third_party/rust/bindgen/src/lib.rs b/third_party/rust/bindgen/src/lib.rs index b669bcb26a7c..cb128f03d5a0 100644 --- a/third_party/rust/bindgen/src/lib.rs +++ b/third_party/rust/bindgen/src/lib.rs @@ -224,10 +224,9 @@ impl Builder { output_vector.push(self.options.rust_target.into()); if self.options.default_enum_style != Default::default() { - output_vector.push("--default-enum-style=".into()); + output_vector.push("--default-enum-variant=".into()); output_vector.push(match self.options.default_enum_style { - codegen::EnumVariation::Rust { non_exhaustive: false } => "rust", - codegen::EnumVariation::Rust { non_exhaustive: true } => "rust_non_exhaustive", + codegen::EnumVariation::Rust => "rust", codegen::EnumVariation::Bitfield => "bitfield", codegen::EnumVariation::Consts => "consts", codegen::EnumVariation::ModuleConsts => "moduleconsts", @@ -254,16 +253,6 @@ impl Builder { }) .count(); - self.options - .rustified_non_exhaustive_enums - .get_items() - .iter() - .map(|item| { - output_vector.push("--rustified-enum-non-exhaustive".into()); - output_vector.push(item.to_owned()); - }) - .count(); - self.options .constified_enum_modules .get_items() @@ -821,24 +810,15 @@ impl Builder { /// This makes bindgen generate enums instead of constants. Regular /// expressions are supported. /// - /// **Use this with caution,** you probably want to use the non_exhaustive - /// flavor of rust enums instead of this one. Take a look at - /// https://github.com/rust-lang/rust/issues/36927 for more information. + /// **Use this with caution.** You should not be using Rust enums unless + /// you have complete control of the C/C++ code that you're binding to. + /// Take a look at https://github.com/rust-lang/rust/issues/36927 for + /// more information. pub fn rustified_enum>(mut self, arg: T) -> Builder { self.options.rustified_enums.insert(arg); self } - /// Mark the given enum (or set of enums, if using a pattern) as a Rust - /// enum with the #[non_exhaustive] attribute. - /// - /// This makes bindgen generate enums instead of constants. Regular - /// expressions are supported. - pub fn rustified_non_exhaustive_enum>(mut self, arg: T) -> Builder { - self.options.rustified_non_exhaustive_enums.insert(arg); - self - } - /// Mark the given enum (or set of enums, if using a pattern) as a set of /// constants that are not to be put into a module. pub fn constified_enum>(mut self, arg: T) -> Builder { @@ -1387,8 +1367,6 @@ struct BindgenOptions { /// The enum patterns to mark an enum as a Rust enum. rustified_enums: RegexSet, - rustified_non_exhaustive_enums: RegexSet, - /// The enum patterns to mark an enum as a module of constants. constified_enum_modules: RegexSet, @@ -1642,7 +1620,6 @@ impl Default for BindgenOptions { default_enum_style: Default::default(), bitfield_enums: Default::default(), rustified_enums: Default::default(), - rustified_non_exhaustive_enums: Default::default(), constified_enums: Default::default(), constified_enum_modules: Default::default(), builtins: false, diff --git a/third_party/rust/bindgen/src/options.rs b/third_party/rust/bindgen/src/options.rs index 43ad2edc4259..300036e0a903 100644 --- a/third_party/rust/bindgen/src/options.rs +++ b/third_party/rust/bindgen/src/options.rs @@ -31,7 +31,7 @@ where .help("The default style of code used to generate enums.") .value_name("variant") .default_value("consts") - .possible_values(&["consts", "moduleconsts", "bitfield", "rust", "rust_non_exhaustive"]) + .possible_values(&["consts", "moduleconsts", "bitfield", "rust"]) .multiple(false), Arg::with_name("bitfield-enum") .long("bitfield-enum") diff --git a/third_party/rust/serde_repr/.cargo-checksum.json b/third_party/rust/serde_repr/.cargo-checksum.json new file mode 100644 index 000000000000..8f5519fd382c --- /dev/null +++ b/third_party/rust/serde_repr/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"8f7a4ed25474433e74d4059d73787e831395aa69c1e1d16b454598ed8ddd0bcc","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"1c365193e71eca0287ed4514768ef0d9a41b26f36afd8576068c611814864d1e","src/lib.rs":"63e3e8c186e362636e0f2026169bfa1c5731cb7f48e98ef0084b50dae8834ec1","src/parse.rs":"309bb9628074f9a490d61be8d002b731285dbe82c12296928d9bf58f214921a5","tests/compiletest.rs":"cf571696d49e4999dc3ee6c15264bc2e10c3ac171ef58ef089bca187a5920c14","tests/test.rs":"69deba0db55c4014b27fe5686b79f67e4926ff31f1655fd8dce0c45a6b3b6b36","tests/ui/empty_enum.rs":"fe1166f2f92ee213d26a23e57572a99c65c163d446fd8d67e1520bab34f4b859","tests/ui/empty_enum.stderr":"916395da697eaa28fa714229f8bc6de22e344414463c4f2c5ce0061db31896a4","tests/ui/missing_repr.rs":"b7ba9341111582cad52e761b82f14778c60352014c4265566e4d4d01ccdcb306","tests/ui/missing_repr.stderr":"96cfcb985e2d1492914c78577095ef9663e59360742fa35c34a5ef286eb88a6c","tests/ui/multiple_others.rs":"569658516619719f21e5071873a37125d5390edb77558e4381401f03efda0c83","tests/ui/multiple_others.stderr":"faf7e48de93190d6254188ae9740fc7d8d0ea950c58876176cb8e4ec4fab6fb4","tests/ui/non_unit_variant.rs":"0d8295ae08d882fc3ef4164857240038c5b0674ff0811da9b6ea7343e8bb955c","tests/ui/non_unit_variant.stderr":"7f0ba694144e2ce9aadf951bbaa29065cb254ad6de454b7793ea353385e7a199","tests/ui/not_enum.rs":"ada7637821c924a6b99175363c820375991be60223f96ca553d304fde2721386","tests/ui/not_enum.stderr":"ee57e1b1a5c274cc234211eab3d68cd8cef7663691bcb678ba29ec214e2efe37","tests/ui/update-references.sh":"81e65fc2a2dbc2dfea5abcfbc5dd5bdee99ddfc0073f40fd5bf1c904352edc06"},"package":"29a734c298df0346c4cd5919595981c266dabbf12dc747c85e1a95e96077a52b"} \ No newline at end of file diff --git a/third_party/rust/serde_repr/Cargo.toml b/third_party/rust/serde_repr/Cargo.toml new file mode 100644 index 000000000000..293e401fe34a --- /dev/null +++ b/third_party/rust/serde_repr/Cargo.toml @@ -0,0 +1,46 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "serde_repr" +version = "0.1.4" +authors = ["David Tolnay "] +description = "Derive Serialize and Deserialize that delegates to the underlying repr of a C-like enum." +documentation = "https://docs.rs/serde_repr" +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/serde-repr" + +[lib] +proc-macro = true +[dependencies.proc-macro2] +version = "0.4" + +[dependencies.quote] +version = "0.6" + +[dependencies.syn] +version = "0.15" +[dev-dependencies.compiletest] +version = "0.3" +features = ["stable"] +package = "compiletest_rs" + +[dev-dependencies.serde] +version = "1.0" + +[dev-dependencies.serde_json] +version = "1.0" + +[dev-dependencies.version_check] +version = "0.1" diff --git a/third_party/rust/serde_repr/LICENSE-APACHE b/third_party/rust/serde_repr/LICENSE-APACHE new file mode 100644 index 000000000000..16fe87b06e80 --- /dev/null +++ b/third_party/rust/serde_repr/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third_party/rust/serde_repr/LICENSE-MIT b/third_party/rust/serde_repr/LICENSE-MIT new file mode 100644 index 000000000000..31aa79387f27 --- /dev/null +++ b/third_party/rust/serde_repr/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/serde_repr/README.md b/third_party/rust/serde_repr/README.md new file mode 100644 index 000000000000..5f294d6bdfdc --- /dev/null +++ b/third_party/rust/serde_repr/README.md @@ -0,0 +1,56 @@ +Serde repr derive +================= + +[![Build Status](https://api.travis-ci.com/dtolnay/serde-repr.svg?branch=master)](https://travis-ci.com/dtolnay/serde-repr) +[![Latest Version](https://img.shields.io/crates/v/serde_repr.svg)](https://crates.io/crates/serde_repr) +[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/serde_repr) + +This crate provides a derive macro to derive Serde's `Serialize` and +`Deserialize` traits in a way that delegates to the underlying repr of a C-like +enum. + +```toml +[dependencies] +serde = "1.0" +serde_repr = "0.1" +``` + +```rust +use serde_repr::{Serialize_repr, Deserialize_repr}; + +#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] +#[repr(u8)] +enum SmallPrime { + Two = 2, + Three = 3, + Five = 5, + Seven = 7, +} + +fn main() -> serde_json::Result<()> { + let j = serde_json::to_string(&SmallPrime::Seven)?; + assert_eq!(j, "7"); + + let p: SmallPrime = serde_json::from_str("2")?; + assert_eq!(p, SmallPrime::Two); + + Ok(()) +} +``` + +
+ +#### License + + +Licensed under either of Apache License, Version +2.0 or MIT license at your option. + + +
+ + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + diff --git a/third_party/rust/serde_repr/src/lib.rs b/third_party/rust/serde_repr/src/lib.rs new file mode 100644 index 000000000000..b80fa9988fe1 --- /dev/null +++ b/third_party/rust/serde_repr/src/lib.rs @@ -0,0 +1,135 @@ +//! Derive `Serialize` and `Deserialize` that delegates to the underlying repr +//! of a C-like enum. +//! +//! # Examples +//! +//! ``` +//! use serde_repr::{Serialize_repr, Deserialize_repr}; +//! +//! #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] +//! #[repr(u8)] +//! enum SmallPrime { +//! Two = 2, +//! Three = 3, +//! Five = 5, +//! Seven = 7, +//! } +//! +//! fn main() -> serde_json::Result<()> { +//! let j = serde_json::to_string(&SmallPrime::Seven)?; +//! assert_eq!(j, "7"); +//! +//! let p: SmallPrime = serde_json::from_str("2")?; +//! assert_eq!(p, SmallPrime::Two); +//! +//! Ok(()) +//! } +//! ``` + +#![recursion_limit = "128"] + +extern crate proc_macro; + +mod parse; + +use proc_macro::TokenStream; +use quote::quote; +use syn::parse_macro_input; + +use crate::parse::Input; + +use std::iter; + +#[proc_macro_derive(Serialize_repr)] +pub fn derive_serialize(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as Input); + let ident = input.ident; + let repr = input.repr; + + let match_variants = input.variants.iter().map(|variant| { + let variant = &variant.ident; + quote! { + #ident::#variant => #ident::#variant as #repr, + } + }); + + TokenStream::from(quote! { + impl serde::Serialize for #ident { + fn serialize(&self, serializer: S) -> core::result::Result + where + S: serde::Serializer + { + let value: #repr = match *self { + #(#match_variants)* + }; + serde::Serialize::serialize(&value, serializer) + } + } + }) +} + +#[proc_macro_derive(Deserialize_repr, attributes(serde))] +pub fn derive_deserialize(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as Input); + let ident = input.ident; + let repr = input.repr; + let variants = input.variants.iter().map(|variant| &variant.ident); + + let declare_discriminants = input.variants.iter().map(|variant| { + let variant = &variant.ident; + quote! { + #[allow(non_upper_case_globals)] + const #variant: #repr = #ident::#variant as #repr; + } + }); + + let match_discriminants = input.variants.iter().map(|variant| { + let variant = &variant.ident; + quote! { + discriminant::#variant => core::result::Result::Ok(#ident::#variant), + } + }); + + let error_format = match input.variants.len() { + 1 => "invalid value: {}, expected {}".to_owned(), + 2 => "invalid value: {}, expected {} or {}".to_owned(), + n => { + "invalid value: {}, expected one of: {}".to_owned() + + &iter::repeat(", {}").take(n - 1).collect::() + } + }; + + let other_arm = match input.default_variant { + Some(variant) => { + let variant = &variant.ident; + quote! { + core::result::Result::Ok(#ident::#variant) + } + } + None => quote! { + core::result::Result::Err(serde::de::Error::custom( + format_args!(#error_format, other #(, discriminant::#variants)*) + )) + }, + }; + + TokenStream::from(quote! { + impl<'de> serde::Deserialize<'de> for #ident { + fn deserialize(deserializer: D) -> core::result::Result + where + D: serde::Deserializer<'de>, + { + struct discriminant; + + impl discriminant { + #(#declare_discriminants)* + } + + match <#repr as serde::Deserialize>::deserialize(deserializer)? { + #(#match_discriminants)* + other => #other_arm, + } + } + } + }) +} diff --git a/third_party/rust/serde_repr/src/parse.rs b/third_party/rust/serde_repr/src/parse.rs new file mode 100644 index 000000000000..d409c4fe2d5e --- /dev/null +++ b/third_party/rust/serde_repr/src/parse.rs @@ -0,0 +1,114 @@ +use proc_macro2::Span; +use syn::parse::{Error, Parse, ParseStream, Parser, Result}; +use syn::{parenthesized, Data, DeriveInput, Fields, Ident, Meta, NestedMeta}; + +pub struct Input { + pub ident: Ident, + pub repr: Ident, + pub variants: Vec, + pub default_variant: Option, +} + +#[derive(Clone)] +pub struct Variant { + pub ident: Ident, + pub attrs: VariantAttrs, +} + +#[derive(Clone)] +pub struct VariantAttrs { + pub is_default: bool, +} + +fn parse_meta(attrs: &mut VariantAttrs, meta: &Meta) { + if let Meta::List(value) = meta { + for meta in &value.nested { + if let NestedMeta::Meta(Meta::Word(word)) = meta { + if word == "other" { + attrs.is_default = true; + } + } + } + } +} + +fn parse_attrs(variant: &syn::Variant) -> Result { + let mut attrs = VariantAttrs { is_default: false }; + for attr in &variant.attrs { + if attr.path.is_ident("serde") { + parse_meta(&mut attrs, &attr.parse_meta()?); + } + } + Ok(attrs) +} + +impl Parse for Input { + fn parse(input: ParseStream) -> Result { + let call_site = Span::call_site(); + let derive_input = DeriveInput::parse(input)?; + + let data = match derive_input.data { + Data::Enum(data) => data, + _ => { + return Err(Error::new(call_site, "input must be an enum")); + } + }; + + let variants = data + .variants + .into_iter() + .map(|variant| match variant.fields { + Fields::Unit => { + let attrs = parse_attrs(&variant)?; + Ok(Variant { + ident: variant.ident, + attrs, + }) + } + Fields::Named(_) | Fields::Unnamed(_) => { + Err(Error::new(variant.ident.span(), "must be a unit variant")) + } + }) + .collect::>>()?; + + if variants.is_empty() { + return Err(Error::new(call_site, "there must be at least one variant")); + } + + let generics = derive_input.generics; + if !generics.params.is_empty() || generics.where_clause.is_some() { + return Err(Error::new(call_site, "generic enum is not supported")); + } + + let mut repr = None; + for attr in derive_input.attrs { + if attr.path.is_ident("repr") { + fn repr_arg(input: ParseStream) -> Result { + let content; + parenthesized!(content in input); + content.parse() + } + let ty = repr_arg.parse2(attr.tts)?; + repr = Some(ty); + break; + } + } + let repr = repr.ok_or_else(|| Error::new(call_site, "missing #[repr(...)] attribute"))?; + + let mut default_variants = variants.iter().filter(|x| x.attrs.is_default); + let default_variant = default_variants.next().cloned(); + if default_variants.next().is_some() { + return Err(Error::new( + call_site, + "only one variant can be #[serde(other)]", + )); + } + + Ok(Input { + ident: derive_input.ident, + repr, + variants, + default_variant, + }) + } +} diff --git a/third_party/rust/serde_repr/tests/compiletest.rs b/third_party/rust/serde_repr/tests/compiletest.rs new file mode 100644 index 000000000000..bb5cf6060398 --- /dev/null +++ b/third_party/rust/serde_repr/tests/compiletest.rs @@ -0,0 +1,25 @@ +#[test] +fn ui() { + if !version_check::is_nightly().unwrap() { + return; + } + + let mut config = compiletest::Config { + mode: compiletest::common::Mode::Ui, + src_base: std::path::PathBuf::from("tests/ui"), + target_rustcflags: Some(String::from( + "\ + --edition=2018 \ + -Z unstable-options \ + --extern serde_repr \ + ", + )), + build_base: std::path::PathBuf::from("target/ui"), + ..Default::default() + }; + + config.link_deps(); + config.clean_rmeta(); + + compiletest::run_tests(&config); +} diff --git a/third_party/rust/serde_repr/tests/test.rs b/third_party/rust/serde_repr/tests/test.rs new file mode 100644 index 000000000000..e7e9eff55892 --- /dev/null +++ b/third_party/rust/serde_repr/tests/test.rs @@ -0,0 +1,74 @@ +use serde_repr::{Deserialize_repr, Serialize_repr}; + +mod small_prime { + use super::*; + + #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] + #[repr(u8)] + enum SmallPrime { + Two = 2, + Three = 3, + Five = 5, + Seven = 7, + } + + #[test] + fn test_serialize() { + let j = serde_json::to_string(&SmallPrime::Seven).unwrap(); + assert_eq!(j, "7"); + } + + #[test] + fn test_deserialize() { + let p: SmallPrime = serde_json::from_str("2").unwrap(); + assert_eq!(p, SmallPrime::Two); + } +} + +mod other { + use super::*; + + #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] + #[repr(u8)] + enum TestOther { + A, + B, + #[serde(other, rename = "useless")] + Other, + } + + #[test] + fn test_deserialize() { + let p: TestOther = serde_json::from_str("0").unwrap(); + assert_eq!(p, TestOther::A); + let p: TestOther = serde_json::from_str("1").unwrap(); + assert_eq!(p, TestOther::B); + let p: TestOther = serde_json::from_str("5").unwrap(); + assert_eq!(p, TestOther::Other); + } +} + +mod implicit_discriminant { + use super::*; + + #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] + #[repr(u8)] + enum ImplicitDiscriminant { + Zero, + One, + Two, + Three, + } + + #[test] + fn test_serialize() { + let j = serde_json::to_string(&ImplicitDiscriminant::Three).unwrap(); + assert_eq!(j, "3"); + } + + #[test] + fn test_deserialize() { + let p: ImplicitDiscriminant = serde_json::from_str("2").unwrap(); + assert_eq!(p, ImplicitDiscriminant::Two); + } +} diff --git a/third_party/rust/serde_repr/tests/ui/empty_enum.rs b/third_party/rust/serde_repr/tests/ui/empty_enum.rs new file mode 100644 index 000000000000..f1fb6f9d56d2 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/empty_enum.rs @@ -0,0 +1,6 @@ +use serde_repr::Serialize_repr; + +#[derive(Serialize_repr)] +enum SmallPrime {} + +fn main() {} diff --git a/third_party/rust/serde_repr/tests/ui/empty_enum.stderr b/third_party/rust/serde_repr/tests/ui/empty_enum.stderr new file mode 100644 index 000000000000..26c155980199 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/empty_enum.stderr @@ -0,0 +1,8 @@ +error: there must be at least one variant + --> $DIR/empty_enum.rs:3:10 + | +3 | #[derive(Serialize_repr)] + | ^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/third_party/rust/serde_repr/tests/ui/missing_repr.rs b/third_party/rust/serde_repr/tests/ui/missing_repr.rs new file mode 100644 index 000000000000..00836356b93f --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/missing_repr.rs @@ -0,0 +1,11 @@ +use serde_repr::Serialize_repr; + +#[derive(Serialize_repr)] +enum SmallPrime { + Two = 2, + Three = 3, + Five = 5, + Seven = 7, +} + +fn main() {} diff --git a/third_party/rust/serde_repr/tests/ui/missing_repr.stderr b/third_party/rust/serde_repr/tests/ui/missing_repr.stderr new file mode 100644 index 000000000000..4c8b8f65b222 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/missing_repr.stderr @@ -0,0 +1,8 @@ +error: missing #[repr(...)] attribute + --> $DIR/missing_repr.rs:3:10 + | +3 | #[derive(Serialize_repr)] + | ^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/third_party/rust/serde_repr/tests/ui/multiple_others.rs b/third_party/rust/serde_repr/tests/ui/multiple_others.rs new file mode 100644 index 000000000000..fdb552b10903 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/multiple_others.rs @@ -0,0 +1,12 @@ +use serde_repr::Deserialize_repr; + +#[derive(Deserialize_repr)] +#[repr(u8)] +enum MultipleOthers { + #[serde(other)] + A, + #[serde(other)] + B, +} + +fn main() {} diff --git a/third_party/rust/serde_repr/tests/ui/multiple_others.stderr b/third_party/rust/serde_repr/tests/ui/multiple_others.stderr new file mode 100644 index 000000000000..060c53419620 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/multiple_others.stderr @@ -0,0 +1,8 @@ +error: only one variant can be #[serde(other)] + --> $DIR/multiple_others.rs:3:10 + | +3 | #[derive(Deserialize_repr)] + | ^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/third_party/rust/serde_repr/tests/ui/non_unit_variant.rs b/third_party/rust/serde_repr/tests/ui/non_unit_variant.rs new file mode 100644 index 000000000000..9cdc80d0afc6 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/non_unit_variant.rs @@ -0,0 +1,12 @@ +use serde_repr::Serialize_repr; + +#[derive(Serialize_repr)] +#[repr(u8)] +enum SmallPrime { + Two(u8), + Three(u8), + Five(u8), + Seven(u8), +} + +fn main() {} diff --git a/third_party/rust/serde_repr/tests/ui/non_unit_variant.stderr b/third_party/rust/serde_repr/tests/ui/non_unit_variant.stderr new file mode 100644 index 000000000000..689343f129a1 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/non_unit_variant.stderr @@ -0,0 +1,8 @@ +error: must be a unit variant + --> $DIR/non_unit_variant.rs:6:5 + | +6 | Two(u8), + | ^^^ + +error: aborting due to previous error + diff --git a/third_party/rust/serde_repr/tests/ui/not_enum.rs b/third_party/rust/serde_repr/tests/ui/not_enum.rs new file mode 100644 index 000000000000..92a1d746dc72 --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/not_enum.rs @@ -0,0 +1,11 @@ +use serde_repr::Serialize_repr; + +#[derive(Serialize_repr)] +struct SmallPrime { + two: u8, + three: u8, + five: u8, + seven: u8, +} + +fn main() {} diff --git a/third_party/rust/serde_repr/tests/ui/not_enum.stderr b/third_party/rust/serde_repr/tests/ui/not_enum.stderr new file mode 100644 index 000000000000..5ffa03aeb01f --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/not_enum.stderr @@ -0,0 +1,8 @@ +error: input must be an enum + --> $DIR/not_enum.rs:3:10 + | +3 | #[derive(Serialize_repr)] + | ^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/third_party/rust/serde_repr/tests/ui/update-references.sh b/third_party/rust/serde_repr/tests/ui/update-references.sh new file mode 100755 index 000000000000..ee500b60290f --- /dev/null +++ b/third_party/rust/serde_repr/tests/ui/update-references.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# +# Copyright 2015 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 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +# A script to update the references for particular tests. The idea is +# that you do a run, which will generate files in the build directory +# containing the (normalized) actual output of the compiler. This +# script will then copy that output and replace the "expected output" +# files. You can then commit the changes. +# +# If you find yourself manually editing a foo.stderr file, you're +# doing it wrong. + +cd "$(dirname "${BASH_SOURCE[0]}")" +BUILD_DIR="../../target/ui" + +for testcase in *.rs; do + STDERR_NAME="${testcase/%.rs/.stderr}" + STDOUT_NAME="${testcase/%.rs/.stdout}" + if [ -f "$BUILD_DIR/$STDOUT_NAME" ] && \ + ! (diff "$BUILD_DIR/$STDOUT_NAME" "$STDOUT_NAME" >& /dev/null); then + echo "updating $STDOUT_NAME" + cp "$BUILD_DIR/$STDOUT_NAME" "$STDOUT_NAME" + fi + if [ -f "$BUILD_DIR/$STDERR_NAME" ] && \ + ! (diff "$BUILD_DIR/$STDERR_NAME" "$STDERR_NAME" >& /dev/null); then + echo "updating $STDERR_NAME" + cp "$BUILD_DIR/$STDERR_NAME" "$STDERR_NAME" + fi +done