Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
1 value
problem_statement
stringlengths
79
2.53k
hints_text
stringlengths
0
2.82k
instance_id
stringlengths
21
22
issue_numbers
sequencelengths
1
2
base_commit
stringlengths
40
40
test_patch
stringlengths
336
78k
version
stringlengths
3
3
pull_number
int64
24
380
created_at
stringlengths
20
20
patch
stringlengths
251
103k
environment_setup_commit
stringlengths
40
40
bitflags/bitflags
Implement Arbitrary for bitflags? Would it be worth it to have an optional implementation of [`Arbitrary`](https://docs.rs/arbitrary/1.0.1/arbitrary/trait.Arbitrary.html) (in the [arbitrary crate](https://crates.io/crates/arbitrary)) for bitflags types, to make it easier to use them in fuzzing? I'm imagining something along the lines of this, added to the macro expansion when `cfg(feature = "arbitrary")` or so: ```rust impl arbitrary::Arbitrary for $BitFlags { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { Self::from_bits(u.arbitrary()).ok_or_else(|| arbitrary::Error::IncorrectFormat) } } ```
Can we think of any other implementation for `Arbitrary` that a consumer might want to add themselves? If not then this seems like a reasonable addition to me, since as I understand it, `Arbitrary` is meant to be a general API that different fuzzer implementations can lean on. Anything that makes fuzzing easier to get started with is worth doing! 😁 I've now submitted #260 implementing this. We've recently published `2.0.0` that reworks the library internals to support new external trait implementations without breaking consumers. We should now be able to add an implementation for `arbitrary` following the support for `serde` as an example.
bitflags__bitflags-324
[ "248" ]
11640f19a7644f3967631733f33ec87b9f911951
diff --git /dev/null b/src/external/arbitrary_support.rs new file mode 100644 --- /dev/null +++ b/src/external/arbitrary_support.rs @@ -0,0 +1,19 @@ +#[cfg(test)] +mod tests { + use arbitrary::Arbitrary; + + bitflags! { + #[derive(Arbitrary)] + struct Color: u32 { + const RED = 0x1; + const GREEN = 0x2; + const BLUE = 0x4; + } + } + + #[test] + fn test_arbitrary() { + let mut unstructured = arbitrary::Unstructured::new(&[0_u8; 256]); + let _color = Color::arbitrary(&mut unstructured); + } +}
2.0
324
2023-03-25T01:34:21Z
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -49,7 +49,7 @@ jobs: run: cargo install cargo-hack - name: Powerset - run: cargo hack test --feature-powerset --lib --optional-deps "std serde" --depth 3 --skip rustc-dep-of-std + run: cargo hack test --feature-powerset --lib --optional-deps --depth 3 --skip "compiler_builtins core rustc-dep-of-std" - name: Docs run: cargo doc --features example_generated diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ exclude = ["tests", ".github"] [dependencies] serde = { version = "1.0", optional = true, default-features = false } +arbitrary = { version = "1.0", optional = true } core = { version = "1.0.0", optional = true, package = "rustc-std-workspace-core" } compiler_builtins = { version = "0.1.2", optional = true } diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +31,7 @@ rustversion = "1.0" serde_derive = "1.0" serde_json = "1.0" serde_test = "1.0" +arbitrary = { version = "1.0", features = ["derive"] } [features] std = [] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -3,6 +3,9 @@ #[cfg(feature = "serde")] pub mod serde_support; +#[cfg(feature = "arbitrary")] +pub mod arbitrary_support; + /// Implements traits from external libraries for the internal bitflags type. #[macro_export(local_inner_macros)] #[doc(hidden)] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -27,6 +30,15 @@ macro_rules! __impl_external_bitflags { )* } } + + __impl_external_bitflags_arbitrary! { + $InternalBitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } }; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -80,3 +92,40 @@ macro_rules! __impl_external_bitflags_serde { } ) => {}; } + +/// Implement `Arbitrary` for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(feature = "arbitrary")] +macro_rules! __impl_external_bitflags_arbitrary { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + impl<'a> $crate::__private::arbitrary::Arbitrary<'a> for $InternalBitFlags { + fn arbitrary( + u: &mut $crate::__private::arbitrary::Unstructured<'a>, + ) -> $crate::__private::arbitrary::Result<Self> { + Self::from_bits(u.arbitrary()?).ok_or_else(|| $crate::__private::arbitrary::Error::IncorrectFormat) + } + } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "arbitrary"))] +macro_rules! __impl_external_bitflags_arbitrary { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => {}; +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -361,6 +361,9 @@ pub mod __private { #[cfg(feature = "serde")] pub use serde; + + #[cfg(feature = "arbitrary")] + pub use arbitrary; } /*
11640f19a7644f3967631733f33ec87b9f911951
bitflags/bitflags
Support bytemuck From #310 Add a `bytemuck` Cargo feature that derives `bytemuck` traits on the generated inner flags type so end-users can then `#[derive(bytemuck::*)]` traits on their own flags types.
bitflags__bitflags-336
[ "311" ]
597d40749224d3eee125a6ea9d6ac4c92b898ee8
diff --git /dev/null b/src/external/bytemuck_support.rs new file mode 100644 --- /dev/null +++ b/src/external/bytemuck_support.rs @@ -0,0 +1,19 @@ +#[cfg(test)] +mod tests { + use bytemuck::{Pod, Zeroable}; + + bitflags! { + #[derive(Pod, Zeroable, Clone, Copy)] + #[repr(transparent)] + struct Color: u32 { + const RED = 0x1; + const GREEN = 0x2; + const BLUE = 0x4; + } + } + + #[test] + fn test_bytemuck() { + assert_eq!(0x1, bytemuck::cast::<Color, u32>(Color::RED)); + } +}
2.1
336
2023-04-11T01:30:12Z
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ exclude = ["tests", ".github"] [dependencies] serde = { version = "1.0", optional = true, default-features = false } arbitrary = { version = "1.0", optional = true } +bytemuck = { version = "1.0", optional = true } core = { version = "1.0.0", optional = true, package = "rustc-std-workspace-core" } compiler_builtins = { version = "0.1.2", optional = true } diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +33,7 @@ serde_derive = "1.0" serde_json = "1.0" serde_test = "1.0" arbitrary = { version = "1.0", features = ["derive"] } +bytemuck = { version = "1.0", features = ["derive"] } [features] std = [] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -1,10 +1,83 @@ //! Conditional trait implementations for external libraries. +/* +How do I support a new external library? + +Let's say we want to add support for `my_library`. + +First, we define a macro like so: + +```rust +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(feature = "serde")] +macro_rules! __impl_external_bitflags_my_library { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + // Implementation goes here + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "my_library"))] +macro_rules! __impl_external_bitflags_my_library { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => {}; +} +``` + +Note that the macro is actually defined twice; once for when the `my_library` feature +is available, and once for when it's not. This is because the `__impl_external_bitflags_my_library` +macro is called in an end-user's library, not in `bitflags`. In an end-user's library we don't +know whether or not a particular feature of `bitflags` is enabled, so we unconditionally call +the macro, where the body of that macro depends on the feature flag. + +Now, we add our macro call to the `__impl_external_bitflags` macro body: + +```rust +__impl_external_bitflags_my_library! { + $InternalBitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } +} +``` + +What about libraries that _must_ be supported through `#[derive]`? + +In these cases, the attributes will need to be added to the `__declare_internal_bitflags` macro when +the internal type is declared. +*/ + #[cfg(feature = "serde")] pub mod serde_support; +#[cfg(feature = "serde")] +pub use serde; #[cfg(feature = "arbitrary")] pub mod arbitrary_support; +#[cfg(feature = "arbitrary")] +pub use arbitrary; + +#[cfg(feature = "bytemuck")] +pub mod bytemuck_support; +#[cfg(feature = "bytemuck")] +pub use bytemuck; /// Implements traits from external libraries for the internal bitflags type. #[macro_export(local_inner_macros)] diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -39,6 +112,15 @@ macro_rules! __impl_external_bitflags { )* } } + + __impl_external_bitflags_bytemuck! { + $InternalBitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } }; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -129,3 +211,50 @@ macro_rules! __impl_external_bitflags_arbitrary { } ) => {}; } + +/// Implement `Pod` and `Zeroable` for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(feature = "bytemuck")] +macro_rules! __impl_external_bitflags_bytemuck { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + // SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T, + // and $T implements Pod + unsafe impl $crate::__private::bytemuck::Pod for $InternalBitFlags + where + $T: $crate::__private::bytemuck::Pod, + { + + } + + // SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T, + // and $T implements Zeroable + unsafe impl $crate::__private::bytemuck::Zeroable for $InternalBitFlags + where + $T: $crate::__private::bytemuck::Zeroable, + { + + } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +#[cfg(not(feature = "bytemuck"))] +macro_rules! __impl_external_bitflags_bytemuck { + ( + $InternalBitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => {}; +} diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -14,6 +14,9 @@ macro_rules! __declare_internal_bitflags { $iter_vis:vis struct $Iter:ident; $iter_names_vis:vis struct $IterNames:ident; ) => { + // NOTE: The ABI of this type is _guaranteed_ to be the same as `T` + // This is relied on by some external libraries like `bytemuck` to make + // its `unsafe` trait impls sound. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] $vis struct $InternalBitFlags { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -394,8 +394,9 @@ //! example docs. #![cfg_attr(not(any(feature = "std", test)), no_std)] +#![cfg_attr(not(test), forbid(unsafe_code))] + #![doc(html_root_url = "https://docs.rs/bitflags/2.1.0")] -#![forbid(unsafe_code)] #[doc(inline)] pub use traits::BitFlags; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -408,12 +409,6 @@ pub mod __private { pub use crate::{external::*, traits::*}; pub use core; - - #[cfg(feature = "serde")] - pub use serde; - - #[cfg(feature = "arbitrary")] - pub use arbitrary; } /* diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -14,7 +14,7 @@ macro_rules! __declare_public_bitflags { $vis:vis struct $BitFlags:ident; ) => { $(#[$outer])* - $vis struct $BitFlags(<Self as $crate::__private::PublicFlags>::Internal); + $vis struct $BitFlags(<$BitFlags as $crate::__private::PublicFlags>::Internal); }; }
dc971042c8132a5381ab3e2165983ee7f9d44c63
bitflags/bitflags
`usize` / `isize` aren't supported anymore in `v2.0` This doesn't seem intentional at least and isn't mentioned in the changelog.
In what way are they not supported? What error message do they give? Or is there some other problem with them? They don't implement the new `Bits` trait, which is required to use bitflags: https://github.com/bitflags/bitflags/blob/main/src/traits.rs#L135-L141 Thanks for pointing this out @CryZe. This is a total oversight, they should implement the `Bits` trait.
bitflags__bitflags-321
[ "319" ]
8b43d2bb7efbd3d4189fdac92e411ad20c5140b5
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1548,4 +1548,57 @@ mod tests { assert_eq!(flags, rebuilt); } + + #[test] + fn bits_types() { + bitflags! { + pub struct I8: i8 { + const A = 1; + } + + pub struct I16: i16 { + const A = 1; + } + + pub struct I32: i32 { + const A = 1; + } + + pub struct I64: i64 { + const A = 1; + } + + pub struct I128: i128 { + const A = 1; + } + + pub struct Isize: isize { + const A = 1; + } + + pub struct U8: u8 { + const A = 1; + } + + pub struct U16: u16 { + const A = 1; + } + + pub struct U32: u32 { + const A = 1; + } + + pub struct U64: u64 { + const A = 1; + } + + pub struct U128: u128 { + const A = 1; + } + + pub struct Usize: usize { + const A = 1; + } + } + } }
2.0
321
2023-03-19T08:31:22Z
diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -138,6 +138,7 @@ impl_bits! { u32, i32, u64, i64, u128, i128, + usize, isize, } /// A trait for referencing the `bitflags`-owned internal type
11640f19a7644f3967631733f33ec87b9f911951
bitflags/bitflags
Display missing extra bits for multi-bit flags See: https://github.com/bitflags/bitflags/issues/310#issuecomment-1470122112 Given a flags type with two flags, `BIT = 0b0000_0001` and `MASK = 0b0001_1110`, formatting the value `3` should result in `BIT | 0x2`, but instead it gives `BIT`. That extra bit gets lost, so doesn't roundtrip. The problem seems to be in the generated `iter_names` method.
bitflags__bitflags-316
[ "315" ]
ad0271116e28a79ea880334dd3d06212a224ec09
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1154,17 +1154,39 @@ mod tests { #[test] fn test_display_from_str_roundtrip() { - fn format_parse_case(flags: FmtFlags) { + fn format_parse_case<T: fmt::Debug + fmt::Display + str::FromStr + PartialEq>(flags: T) where <T as str::FromStr>::Err: fmt::Display { assert_eq!(flags, { - match flags.to_string().parse::<FmtFlags>() { + match flags.to_string().parse::<T>() { Ok(flags) => flags, Err(e) => panic!("failed to parse `{}`: {}", flags, e), } }); } - fn parse_case(expected: FmtFlags, flags: &str) { - assert_eq!(expected, flags.parse::<FmtFlags>().unwrap()); + fn parse_case<T: fmt::Debug + str::FromStr + PartialEq>(expected: T, flags: &str) where <T as str::FromStr>::Err: fmt::Display + fmt::Debug { + assert_eq!(expected, flags.parse::<T>().unwrap()); + } + + bitflags! { + #[derive(Debug, Eq, PartialEq)] + pub struct MultiBitFmtFlags: u8 { + const A = 0b0000_0001u8; + const B = 0b0001_1110u8; + } + } + + impl fmt::Display for MultiBitFmtFlags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.0, f) + } + } + + impl str::FromStr for MultiBitFmtFlags { + type Err = crate::parser::ParseError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + Ok(MultiBitFmtFlags(s.parse()?)) + } } format_parse_case(FmtFlags::empty()); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1174,6 +1196,7 @@ mod tests { format_parse_case(FmtFlags::물고기_고양이); format_parse_case(FmtFlags::from_bits_retain(0xb8)); format_parse_case(FmtFlags::from_bits_retain(0x20)); + format_parse_case(MultiBitFmtFlags::from_bits_retain(3)); parse_case(FmtFlags::empty(), ""); parse_case(FmtFlags::empty(), " \r\n\t");
2.0
316
2023-03-16T00:19:13Z
diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -89,7 +89,8 @@ macro_rules! __impl_internal_bitflags { // Iterate over the valid flags let mut first = true; - for (name, _) in self.iter_names() { + let mut iter = self.iter_names(); + for (name, _) in &mut iter { if !first { f.write_str(" | ")?; } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -99,8 +100,7 @@ macro_rules! __impl_internal_bitflags { } // Append any extra bits that correspond to flags to the end of the format - let extra_bits = self.bits & !Self::all().bits; - + let extra_bits = iter.state.bits(); if extra_bits != <$T as $crate::__private::Bits>::EMPTY { if !first { f.write_str(" | ")?;
11640f19a7644f3967631733f33ec87b9f911951
bitflags/bitflags
Cannot use `#[doc(alias)]` The following code: ```rs bitflags::bitflags! { #[doc(alias = "SYMBOLIC_LINK_FLAGS")] pub struct SymbolicLinkFlags:u32 { #[doc(alias = "SYMBOLIC_LINK_FLAG_DIRECTORY")] const DIRECTORY = 0x1; #[doc(alias = "SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE")] const ALLOW_UNPRIVILEGED_CREATE = 0x2; } } ``` Produces the error: ``` error: `#[doc(alias = "...")]` isn't allowed on expression --> src\fs.rs:67:15 | 67 | #[doc(alias = "SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ```
This is a general problem for attributes that can't be applied to expressions now. In methods like `from_name` we now generate code like this: ```rust #[inline] pub fn from_name(name: &str) -> ::bitflags::__private::core::option::Option<Self> { match name { #[doc(alias = "SYMBOLIC_LINK_FLAG_DIRECTORY")] "DIRECTORY" => ::bitflags::__private::core::option::Option::Some(Self { bits: SymbolicLinkFlags::DIRECTORY.bits(), }), #[doc(alias = "SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE")] "ALLOW_UNPRIVILEGED_CREATE" => { ::bitflags::__private::core::option::Option::Some(Self { bits: SymbolicLinkFlags::ALLOW_UNPRIVILEGED_CREATE.bits(), }) } _ => ::bitflags::__private::core::option::Option::None, } } ``` I think the quickest fix would be to introduce a helper macro that filtered out some attributes like `#[doc(..)]` for these match arms. Any more of these that come up in the future could be added to that macro. What kinds of attributes would be useful to apply there other than `cfg`? I can't really think of any besides maybe `#[allow]`, but we handle those on the item itself. I think it would be fair to flip this into an allow-list so only `cfg` attributes get propagated.
bitflags__bitflags-341
[ "308" ]
dc971042c8132a5381ab3e2165983ee7f9d44c63
diff --git /dev/null b/tests/compile-pass/doc_alias.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/doc_alias.rs @@ -0,0 +1,14 @@ +#[macro_use] +extern crate bitflags; + +bitflags! { + #[doc(alias = "FLAG")] + pub struct Flags: u8 { + #[doc(alias = "FLAG_A")] + const A = 1; + } +} + +fn main() { + +}
2.1
341
2023-04-18T00:36:26Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -558,6 +558,315 @@ macro_rules! bitflags { } $($t:tt)* + ) => { + __declare_bitflags!( + $(#[$outer])* + $vis struct $BitFlags: $T { + $( + $(#[$inner $($args)*])* + const $Flag = $value; + )* + } + ); + + bitflags! { + $($t)* + } + }; + () => {}; +} + +/// A macro that processed the input to `bitflags!` and shuffles attributes around +/// based on whether or not they're "expression-safe". +/// +/// This macro is a token-tree muncher that works on 2 levels: +/// +/// 1. Each flag, like `#[cfg(true)] const A: 42` +/// 2. Each attribute on that flag, like `#[cfg(true)]` +/// +/// Flags and attributes start in an "unprocessed" list, and are shifted one token +/// at a time into an appropriate processed list until the unprocessed lists are empty. +/// +/// For each attribute, we explicitly match on its identifier, like `cfg` to determine +/// whether or not it should be considered expression-safe. +/// +/// If you find yourself with an attribute that should be considered expression-safe +/// and isn't, it can be added here. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __declare_bitflags { + // Entrypoint: Move all flags and all attributes into `unprocessed` lists + // where they'll be munched one-at-a-time + ( + $(#[$outer:meta])* + $vis:vis struct $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )* + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + // All flags start here + unprocessed: [ + $( + { + ident: $Flag, + value: $value, + attrs: { + // All attributes start here + unprocessed: [$(#[$inner $($args)*])*], + processed: { + // Attributes that should be added to item declarations go here + decl: [], + // Attributes that are safe on expressions go here + expr: [], + } + }, + }, + )* + ], + // Flags that have had their attributes sorted are pushed here + processed: [], + } + } + }; + // Process the next attribute on the current flag + // `cfg`: The next flag should be propagated to expressions + // NOTE: You can copy this rules block and replace `cfg` with + // your attribute name that should be considered expression-safe + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [ + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [ + // cfg matched here + #[cfg $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + decl: [$($decl:tt)*], + expr: [$($expr:tt)*], + } + }, + }, + $($flags_rest:tt)* + ], + processed: [ + $($flags:tt)* + ], + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + unprocessed: [ + { + ident: $Flag, + value: $value, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + decl: [ + // cfg added here + #[cfg $($args)*] + $($decl)* + ], + expr: [ + // cfg added here + #[cfg $($args)*] + $($expr)* + ], + } + }, + }, + $($flags_rest)* + ], + processed: [ + $($flags)* + ], + } + } + }; + // Process the next attribute on the current flag + // `$other`: The next flag should not be propagated to expressions + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [ + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [ + // $other matched here + #[$other:ident $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + decl: [$($decl:tt)*], + expr: [$($expr:tt)*], + } + }, + }, + $($flags_rest:tt)* + ], + processed: [ + $($flags:tt)* + ], + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + unprocessed: [ + { + ident: $Flag, + value: $value, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + decl: [ + // $other added here + #[$other $($args)*] + $($decl)* + ], + expr: [ + // $other not added here + $($expr)* + ], + } + }, + }, + $($flags_rest)* + ], + processed: [ + $($flags)* + ], + } + } + }; + // Complete the current flag once there are no unprocessed attributes left + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [ + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [], + processed: { + decl: [$($decl:tt)*], + expr: [$($expr:tt)*], + } + }, + }, + $($flags_rest:tt)* + ], + processed: [ + $($flags:tt)* + ], + } + ) => { + __declare_bitflags! { + decl: { + attrs: [$(#[$outer])*], + vis: $vis, + ident: $BitFlags, + ty: $T, + }, + flags: { + unprocessed: [ + $($flags_rest)* + ], + processed: [ + $($flags)* + { + ident: $Flag, + value: $value, + attrs: { + unprocessed: [], + processed: { + decl: [ + $($decl)* + ], + expr: [ + $($expr)* + ], + } + }, + }, + ], + } + } + }; + // Once all attributes on all flags are processed, generate the actual code + ( + decl: { + attrs: [$(#[$outer:meta])*], + vis: $vis:vis, + ident: $BitFlags:ident, + ty: $T:ty, + }, + flags: { + unprocessed: [], + processed: [ + $( + { + ident: $Flag:ident, + value: $value:expr, + attrs: { + unprocessed: [], + processed: { + decl: [$(#[$decl:ident $($declargs:tt)*])*], + expr: [$(#[$expr:ident $($exprargs:tt)*])*], + } + }, + }, + )* + ], + } ) => { // Declared in the scope of the `bitflags!` call // This type appears in the end-user's API diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -570,7 +879,7 @@ macro_rules! bitflags { __impl_public_bitflags_consts! { $BitFlags { $( - $(#[$inner $($args)*])* + $(#[$decl $($declargs)*])* #[allow( dead_code, deprecated, diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -603,7 +912,7 @@ macro_rules! bitflags { __impl_internal_bitflags! { InternalBitFlags: $T, $BitFlags, Iter, IterRaw { $( - $(#[$inner $($args)*])* + $(#[$expr $($exprargs)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -613,7 +922,7 @@ macro_rules! bitflags { __impl_external_bitflags! { InternalBitFlags: $T { $( - $(#[$inner $($args)*])* + $(#[$expr $($exprargs)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -623,12 +932,7 @@ macro_rules! bitflags { $BitFlags: $T, InternalBitFlags, Iter, IterRaw; } }; - - bitflags! { - $($t)* - } - }; - () => {}; + } } #[macro_use]
dc971042c8132a5381ab3e2165983ee7f9d44c63
bitflags/bitflags
Clippy warnings around "manual implementation of an assign operation" Hi. I've run into a new clippy lint warnings such as the following: > manual implementation of an assign operation > for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assign_op_pattern > `#[warn(clippy::assign_op_pattern)]` on by default I'm following the example from the docs page for the use of the macro (more or less, as below). Can you enlighten me as to why this lint notification is appearing here and if there is some way to fix it? I know I can silence the warnings, it's just annoying to see it pop up whenever I run into it. ```rust bitflags! { pub struct MemoryAccess: u8 { /// None. const N = 1 << 0; /// Public read. const R = 1 << 1; /// Public write. const W = 1 << 2; /// Private read. const PR = 1 << 3; /// Private write. const PW = 1 << 4; /// Execute. const EX = 1 << 5; } } ``` Thanks!
bitflags__bitflags-355
[ "357" ]
31d3e4afefc964045156d7fe3622733f48511353
diff --git a/tests/compile-fail/bitflags_custom_bits.rs b/tests/compile-fail/bitflags_custom_bits.rs --- a/tests/compile-fail/bitflags_custom_bits.rs +++ b/tests/compile-fail/bitflags_custom_bits.rs @@ -19,7 +19,7 @@ use std::{ }, }; -use bitflags::{bitflags, Bits, parser::{ParseError, FromHex}}; +use bitflags::{bitflags, Bits, parser::{ParseError, WriteHex, ParseHex}}; // Ideally we'd actually want this to work, but currently need something like `num`'s `Zero` // With some design work it could be made possible diff --git a/tests/compile-fail/bitflags_custom_bits.rs b/tests/compile-fail/bitflags_custom_bits.rs --- a/tests/compile-fail/bitflags_custom_bits.rs +++ b/tests/compile-fail/bitflags_custom_bits.rs @@ -117,12 +117,18 @@ impl Binary for MyInt { } } -impl FromHex for MyInt { - fn from_hex(input: &str) -> Result<Self, ParseError> { +impl ParseHex for MyInt { + fn parse_hex(input: &str) -> Result<Self, ParseError> { Ok(MyInt(u8::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))?)) } } +impl WriteHex for MyInt { + fn write_hex<W: fmt::Write>(&self, writer: W) -> fmt::Result { + LowerHex::fmt(&self.0, writer) + } +} + bitflags! { struct Flags128: MyInt { const A = MyInt(0b0000_0001u8); diff --git a/tests/compile-fail/bitflags_custom_bits.stderr b/tests/compile-fail/bitflags_custom_bits.stderr --- a/tests/compile-fail/bitflags_custom_bits.stderr +++ b/tests/compile-fail/bitflags_custom_bits.stderr @@ -1,7 +1,7 @@ error[E0277]: the trait bound `MyInt: bitflags::traits::Primitive` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:127:22 + --> tests/compile-fail/bitflags_custom_bits.rs:133:22 | -127 | struct Flags128: MyInt { +133 | struct Flags128: MyInt { | ^^^^^ the trait `bitflags::traits::Primitive` is not implemented for `MyInt` | = help: the following other types implement trait `bitflags::traits::Primitive`: diff --git a/tests/compile-fail/bitflags_custom_bits.stderr b/tests/compile-fail/bitflags_custom_bits.stderr --- a/tests/compile-fail/bitflags_custom_bits.stderr +++ b/tests/compile-fail/bitflags_custom_bits.stderr @@ -20,442 +20,457 @@ note: required by a bound in `PublicFlags::Primitive` | type Primitive: Primitive; | ^^^^^^^^^ required by this bound in `PublicFlags::Primitive` +error[E0308]: mismatched types + --> tests/compile-fail/bitflags_custom_bits.rs:128:32 + | +127 | fn write_hex<W: fmt::Write>(&self, writer: W) -> fmt::Result { + | - this type parameter +128 | LowerHex::fmt(&self.0, writer) + | ------------- ^^^^^^ expected `&mut Formatter<'_>`, found type parameter `W` + | | + | arguments to this function are incorrect + | + = note: expected mutable reference `&mut Formatter<'_>` + found type parameter `W` +note: method defined here + --> $RUST/core/src/fmt/mod.rs + error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt == _` | = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt == _` | = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt & MyInt` | = help: the trait `~const BitAnd` is not implemented for `MyInt` note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt == _` | = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitOr` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt | MyInt` | = help: the trait `~const BitOr` is not implemented for `MyInt` note: the trait `BitOr` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt == _` | = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitOr` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt | MyInt` | = help: the trait `~const BitOr` is not implemented for `MyInt` note: the trait `BitOr` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt == _` | = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt & MyInt` | = help: the trait `~const BitAnd` is not implemented for `MyInt` note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt & MyInt` | = help: the trait `~const BitAnd` is not implemented for `MyInt` note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `MyInt` with `_` in const contexts - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt == _` | = help: the trait `~const PartialEq<_>` is not implemented for `MyInt` note: the trait `PartialEq<_>` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt & MyInt` | = help: the trait `~const BitAnd` is not implemented for `MyInt` note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitOr` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt | MyInt` | = help: the trait `~const BitOr` is not implemented for `MyInt` note: the trait `BitOr` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitAnd` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt & MyInt` | = help: the trait `~const BitAnd` is not implemented for `MyInt` note: the trait `BitAnd` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: Not` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ the trait `~const Not` is not implemented for `MyInt` | note: the trait `Not` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: BitXor` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ no implementation for `MyInt ^ MyInt` | = help: the trait `~const BitXor` is not implemented for `MyInt` note: the trait `BitXor` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `MyInt: Not` is not satisfied - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ the trait `~const Not` is not implemented for `MyInt` | note: the trait `Not` is implemented for `MyInt`, but that implementation is not `const` - --> tests/compile-fail/bitflags_custom_bits.rs:126:1 - | -126 | / bitflags! { -127 | | struct Flags128: MyInt { -128 | | const A = MyInt(0b0000_0001u8); -129 | | const B = MyInt(0b0000_0010u8); -130 | | const C = MyInt(0b0000_0100u8); -131 | | } -132 | | } + --> tests/compile-fail/bitflags_custom_bits.rs:132:1 + | +132 | / bitflags! { +133 | | struct Flags128: MyInt { +134 | | const A = MyInt(0b0000_0001u8); +135 | | const B = MyInt(0b0000_0010u8); +136 | | const C = MyInt(0b0000_0100u8); +137 | | } +138 | | } | |_^ = note: this error originates in the macro `__impl_public_bitflags` which comes from the expansion of the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git /dev/null b/tests/compile-pass/bitflags_self_in_value.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/bitflags_self_in_value.rs @@ -0,0 +1,15 @@ +use bitflags::bitflags; + +bitflags! { + pub struct Flags: u32 { + const SOME_FLAG = 1 << Self::SOME_FLAG_SHIFT; + } +} + +impl Flags { + const SOME_FLAG_SHIFT: u32 = 5; +} + +fn main() { + +} diff --git a/tests/smoke-test/src/main.rs b/tests/smoke-test/src/main.rs --- a/tests/smoke-test/src/main.rs +++ b/tests/smoke-test/src/main.rs @@ -1,3 +1,5 @@ +#![deny(warnings)] + use bitflags::bitflags; bitflags! {
2.3
355
2023-05-17T11:22:15Z
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -81,6 +81,23 @@ jobs: - name: Default features run: cross test --target mips-unknown-linux-gnu + clippy: + name: Clippy + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab + + - name: Install Clippy + run: | + rustup update beta + rustup component add clippy --toolchain beta + + - name: Default features + run: | + cd ./tests/smoke-test + cargo +beta clippy + embedded: name: Build (embedded) runs-on: ubuntu-latest diff --git a/src/example_generated.rs b/src/example_generated.rs --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -39,7 +39,7 @@ __impl_public_bitflags_forward! { } __impl_public_bitflags_iter! { - Flags + Flags: u32, Flags } __impl_public_bitflags_consts! { diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -19,7 +19,7 @@ Next, define a macro like so: #[cfg(feature = "serde")] macro_rules! __impl_external_bitflags_my_library { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -35,7 +35,7 @@ macro_rules! __impl_external_bitflags_my_library { #[cfg(not(feature = "my_library"))] macro_rules! __impl_external_bitflags_my_library { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -55,7 +55,7 @@ Now, we add our macro call to the `__impl_external_bitflags` macro body: ```rust __impl_external_bitflags_my_library! { - $InternalBitFlags: $T { + $InternalBitFlags: $T, $PublicBitFlags { $( $(#[$attr $($args)*])* $Flag; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -76,6 +76,51 @@ pub(crate) mod __private { pub use bytemuck; } +/// Implements traits from external libraries for the internal bitflags type. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_external_bitflags { + ( + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } + ) => { + // Any new library traits impls should be added here + // Use `serde` as an example: generate code when the feature is available, + // and a no-op when it isn't + + __impl_external_bitflags_serde! { + $InternalBitFlags: $T, $PublicBitFlags { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } + + __impl_external_bitflags_arbitrary! { + $InternalBitFlags: $T, $PublicBitFlags { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } + + __impl_external_bitflags_bytemuck! { + $InternalBitFlags: $T, $PublicBitFlags { + $( + $(#[$attr $($args)*])* + $Flag; + )* + } + } + }; +} + #[cfg(feature = "serde")] pub mod serde; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -85,11 +130,11 @@ pub mod serde; #[cfg(feature = "serde")] macro_rules! __impl_external_bitflags_serde { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; - )* + )* } ) => { impl $crate::__private::serde::Serialize for $InternalBitFlags { diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -98,7 +143,7 @@ macro_rules! __impl_external_bitflags_serde { serializer: S, ) -> $crate::__private::core::result::Result<S::Ok, S::Error> { $crate::serde::serialize( - self, + &$PublicBitFlags::from_bits_retain(self.bits()), serializer, ) } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -108,9 +153,11 @@ macro_rules! __impl_external_bitflags_serde { fn deserialize<D: $crate::__private::serde::Deserializer<'de>>( deserializer: D, ) -> $crate::__private::core::result::Result<Self, D::Error> { - $crate::serde::deserialize( + let flags: $PublicBitFlags = $crate::serde::deserialize( deserializer, - ) + )?; + + Ok(flags.0) } } }; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -121,11 +168,11 @@ macro_rules! __impl_external_bitflags_serde { #[cfg(not(feature = "serde"))] macro_rules! __impl_external_bitflags_serde { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; - )* + )* } ) => {}; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -136,58 +183,13 @@ pub mod arbitrary; #[cfg(feature = "bytemuck")] mod bytemuck; -/// Implements traits from external libraries for the internal bitflags type. -#[macro_export(local_inner_macros)] -#[doc(hidden)] -macro_rules! __impl_external_bitflags { - ( - $InternalBitFlags:ident: $T:ty { - $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* - } - ) => { - // Any new library traits impls should be added here - // Use `serde` as an example: generate code when the feature is available, - // and a no-op when it isn't - - __impl_external_bitflags_serde! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - $Flag; - )* - } - } - - __impl_external_bitflags_arbitrary! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - $Flag; - )* - } - } - - __impl_external_bitflags_bytemuck! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - $Flag; - )* - } - } - }; -} - /// Implement `Arbitrary` for the internal bitflags type. #[macro_export(local_inner_macros)] #[doc(hidden)] #[cfg(feature = "arbitrary")] macro_rules! __impl_external_bitflags_arbitrary { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -198,7 +200,7 @@ macro_rules! __impl_external_bitflags_arbitrary { fn arbitrary( u: &mut $crate::__private::arbitrary::Unstructured<'a>, ) -> $crate::__private::arbitrary::Result<Self> { - $crate::arbitrary::arbitrary(u) + $crate::arbitrary::arbitrary::<$PublicBitFlags>(u).map(|flags| flags.0) } } }; diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -209,12 +211,12 @@ macro_rules! __impl_external_bitflags_arbitrary { #[cfg(not(feature = "arbitrary"))] macro_rules! __impl_external_bitflags_arbitrary { ( - $InternalBitFlags:ident: $T:ty { - $( - $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* - } + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident; + )* + } ) => {}; } diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -224,11 +226,11 @@ macro_rules! __impl_external_bitflags_arbitrary { #[cfg(feature = "bytemuck")] macro_rules! __impl_external_bitflags_bytemuck { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* + $Flag:ident; + )* } ) => { // SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T, diff --git a/src/external.rs b/src/external.rs --- a/src/external.rs +++ b/src/external.rs @@ -256,11 +258,11 @@ macro_rules! __impl_external_bitflags_bytemuck { #[cfg(not(feature = "bytemuck"))] macro_rules! __impl_external_bitflags_bytemuck { ( - $InternalBitFlags:ident: $T:ty { + $InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* - $Flag:ident; - )* + $Flag:ident; + )* } ) => {}; } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -98,7 +98,7 @@ macro_rules! __impl_internal_bitflags { // The internal flags type offers a similar API to the public one __impl_public_bitflags! { - $InternalBitFlags: $T { + $InternalBitFlags: $T, $PublicBitFlags { $( $(#[$attr $($args)*])* $Flag; diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -106,19 +106,8 @@ macro_rules! __impl_internal_bitflags { } } - __impl_public_bitflags_consts! { - $InternalBitFlags: $T { - $( - $(#[$attr $($args)*])* - #[allow( - dead_code, - deprecated, - unused_attributes, - non_upper_case_globals - )] - $Flag = $value; - )* - } + __impl_public_bitflags_iter! { + $InternalBitFlags: $T, $PublicBitFlags } impl $InternalBitFlags { diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -127,18 +116,6 @@ macro_rules! __impl_internal_bitflags { pub fn bits_mut(&mut self) -> &mut $T { &mut self.0 } - - /// Iterate over enabled flag values. - #[inline] - pub const fn iter(&self) -> $crate::iter::Iter<$PublicBitFlags> { - $crate::iter::Iter::__private_const_new(<$PublicBitFlags as $crate::Flags>::FLAGS, $PublicBitFlags::from_bits_retain(self.0), $PublicBitFlags::from_bits_retain(self.0)) - } - - /// Iterate over enabled flag values with their stringified names. - #[inline] - pub const fn iter_names(&self) -> $crate::iter::IterNames<$PublicBitFlags> { - $crate::iter::IterNames::__private_const_new(<$PublicBitFlags as $crate::Flags>::FLAGS, $PublicBitFlags::from_bits_retain(self.0), $PublicBitFlags::from_bits_retain(self.0)) - } } }; } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -590,7 +590,8 @@ macro_rules! bitflags { unused_attributes, unused_mut, unused_imports, - non_upper_case_globals + non_upper_case_globals, + clippy::assign_op_pattern )] const _: () = { // Declared in a "hidden" scope that can't be reached directly diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -610,7 +611,7 @@ macro_rules! bitflags { // This is where new library trait implementations can be added __impl_external_bitflags! { - InternalBitFlags: $T { + InternalBitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* $Flag; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -623,7 +624,7 @@ macro_rules! bitflags { } __impl_public_bitflags_iter! { - $BitFlags + $BitFlags: $T, $BitFlags } }; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -657,11 +658,12 @@ macro_rules! bitflags { unused_attributes, unused_mut, unused_imports, - non_upper_case_globals + non_upper_case_globals, + clippy::assign_op_pattern )] const _: () = { __impl_public_bitflags! { - $BitFlags: $T { + $BitFlags: $T, $BitFlags { $( $(#[$inner $($args)*])* $Flag; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -670,7 +672,7 @@ macro_rules! bitflags { } __impl_public_bitflags_iter! { - $BitFlags + $BitFlags: $T, $BitFlags } }; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -57,7 +57,7 @@ macro_rules! __impl_public_bitflags_forward { Self($InternalBitFlags::from_bits_retain(bits)) } - fn from_name(name){ + fn from_name(name) { match $InternalBitFlags::from_name(name) { $crate::__private::core::option::Option::Some(bits) => $crate::__private::core::option::Option::Some(Self(bits)), $crate::__private::core::option::Option::None => $crate::__private::core::option::Option::None, diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -130,7 +130,7 @@ macro_rules! __impl_public_bitflags_forward { #[doc(hidden)] macro_rules! __impl_public_bitflags { ( - $PublicBitFlags:ident: $T:ty { + $BitFlags:ident: $T:ty, $PublicBitFlags:ident { $( $(#[$attr:ident $($args:tt)*])* $Flag:ident; diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -138,7 +138,7 @@ macro_rules! __impl_public_bitflags { } ) => { __impl_bitflags! { - $PublicBitFlags: $T { + $BitFlags: $T { fn empty() { Self(<$T as $crate::Bits>::EMPTY) } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -260,7 +260,7 @@ macro_rules! __impl_public_bitflags { } } - __impl_public_bitflags_ops!($PublicBitFlags); + __impl_public_bitflags_ops!($BitFlags); }; } diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -268,8 +268,8 @@ macro_rules! __impl_public_bitflags { #[macro_export(local_inner_macros)] #[doc(hidden)] macro_rules! __impl_public_bitflags_iter { - ($PublicBitFlags:ident) => { - impl $PublicBitFlags { + ($BitFlags:ident: $T:ty, $PublicBitFlags:ident) => { + impl $BitFlags { /// Iterate over enabled flag values. #[inline] pub const fn iter(&self) -> $crate::iter::Iter<$PublicBitFlags> { diff --git a/src/public.rs b/src/public.rs --- a/src/public.rs +++ b/src/public.rs @@ -283,8 +283,8 @@ macro_rules! __impl_public_bitflags_iter { } } - impl $crate::__private::core::iter::IntoIterator for $PublicBitFlags { - type Item = Self; + impl $crate::__private::core::iter::IntoIterator for $BitFlags { + type Item = $PublicBitFlags; type IntoIter = $crate::iter::Iter<$PublicBitFlags>; fn into_iter(self) -> Self::IntoIter {
09f71f492d0f76d63cd286c3869c70676297e204
bitflags/bitflags
Bug: debug pretty-printing unknown flags display 0x0x main.rs ```rust use bitflags::bitflags; bitflags! { struct Flags: u8 { const TWO = 0x2; } } fn main() { let value = 0b11; let flags = unsafe { Flags::from_bits_unchecked(value) }; println!("{:?}", flags); println!("-----------"); println!("{:#?}", flags); } ``` will print the following: ```sh TWO | 0x1 ----------- TWO | 0x0x1 ``` the expected output would either be 0x1 for both, or 1, and 0x1 respectively
bitflags__bitflags-268
[ "267" ]
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
diff --git a/tests/compile-fail/trait/custom_impl.rs b/tests/compile-fail/trait/custom_impl.rs --- a/tests/compile-fail/trait/custom_impl.rs +++ b/tests/compile-fail/trait/custom_impl.rs @@ -62,4 +62,4 @@ impl BitFlags for BootlegFlags { } } -fn main() { } +fn main() {} diff --git a/tests/compile-pass/impls/convert.rs b/tests/compile-pass/impls/convert.rs --- a/tests/compile-pass/impls/convert.rs +++ b/tests/compile-pass/impls/convert.rs @@ -12,6 +12,4 @@ impl From<u32> for Flags { } } -fn main() { - -} +fn main() {} diff --git /dev/null b/tests/compile-pass/impls/fmt.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/impls/fmt.rs @@ -0,0 +1,14 @@ +use bitflags::bitflags; + +bitflags! { + struct Flags: u8 { + const TWO = 0x2; + } +} + +fn main() { + // bug #267 (https://github.com/bitflags/bitflags/issues/267) + let flags = unsafe { Flags::from_bits_unchecked(0b11) }; + assert_eq!(format!("{:?}", flags), "TWO | 0x1"); + assert_eq!(format!("{:#?}", flags), "TWO | 0x1"); +} diff --git a/tests/compile-pass/redefinition/stringify.rs b/tests/compile-pass/redefinition/macros.rs --- a/tests/compile-pass/redefinition/stringify.rs +++ b/tests/compile-pass/redefinition/macros.rs @@ -7,6 +7,11 @@ macro_rules! stringify { ($($t:tt)*) => { "..." }; } +#[allow(unused_macros)] +macro_rules! write { + ($($t:tt)*) => { "..." }; +} + bitflags! { struct Test: u8 { const A = 1; diff --git a/tests/compile-pass/redefinition/stringify.rs b/tests/compile-pass/redefinition/macros.rs --- a/tests/compile-pass/redefinition/stringify.rs +++ b/tests/compile-pass/redefinition/macros.rs @@ -14,6 +19,6 @@ bitflags! { } fn main() { - // Just make sure we don't call the redefined `stringify` macro - assert_eq!(format!("{:?}", Test::A), "A"); + // Just make sure we don't call the redefined `stringify` or `write` macro + assert_eq!(format!("{:?}", unsafe { Test::from_bits_unchecked(0b11) }), "A | 0x2"); }
1.3
268
2022-01-02T17:22:14Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -494,8 +494,7 @@ macro_rules! __impl_bitflags { f.write_str(" | ")?; } first = false; - f.write_str("0x")?; - $crate::_core::fmt::LowerHex::fmt(&extra_bits, f)?; + $crate::_core::write!(f, "{:#x}", extra_bits)?; } if first { f.write_str("(empty)")?;
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
The bitflags macro is not sanitary wrt. standard library types and enumerations The `bitflags` macro, expanded in the prescence of a definition of the type/value `Ok` errors. Reproduction code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3fda3e36c7c6a57e0f7a83c84e56df20 Interestingly, the relevant function, the `fmt` function from the Debug impl, does use `::bitflags::_core::fmt::Result`, however, it merely returns the value `Ok(())`.
bitflags__bitflags-266
[ "265" ]
1aa25e1b3baf35d3d3840f12fe7e8b55adc0164a
diff --git /dev/null b/tests/compile-pass/redefinition/result.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/redefinition/result.rs @@ -0,0 +1,15 @@ +use bitflags::bitflags; + +// Checks for possible errors caused by overriding names used by `bitflags!` internally. + +// bug #265 (https://github.com/bitflags/bitflags/issues/265) + +pub struct Ok<T>(T); + +bitflags! { + pub struct Flags: u16{ + const FOO = 0x0001; + } +} + +fn main() {}
1.3
266
2021-12-16T09:38:14Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -500,7 +500,7 @@ macro_rules! __impl_bitflags { if first { f.write_str("(empty)")?; } - Ok(()) + $crate::_core::fmt::Result::Ok(()) } } impl $crate::_core::fmt::Binary for $BitFlags {
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
Documenting bitflags: how to get documentation for the generated bitflags Some code that I'm writing uses the `#![warn(missing_docs)]` macro to enforce a requirement that all public interfaces have documentation. I haven't been able to figure out how to generate documentation when using the `bitflags!` macro; I also haven't been able to turn off the linter warning using `#![allow(missing_docs)]`. Is there a convenient way to add doc comments to a set of flags? * If so, is there an example somewhere that I can reference? This would be a great thing to include in bitflags documentation. * If not, then take this as a feature request!
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=530756068e54aa56eb519dd66c9fdfc5 https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f782c74e49e8c4c4ae940125265eb7ed Thanks @rusty-snake! Those would actually make some great compile-pass tests 🤔
bitflags__bitflags-380
[ "378" ]
472e392c0d082c0894b18fb31f4e68e0b145e29c
diff --git a/src/tests/iter.rs b/src/tests/iter.rs --- a/src/tests/iter.rs +++ b/src/tests/iter.rs @@ -3,6 +3,7 @@ use super::*; use crate::Flags; #[test] +#[cfg(not(miri))] // Very slow in miri fn roundtrip() { for a in 0u8..=255 { for b in 0u8..=255 { diff --git a/src/tests/parser.rs b/src/tests/parser.rs --- a/src/tests/parser.rs +++ b/src/tests/parser.rs @@ -6,6 +6,7 @@ use crate::{ }; #[test] +#[cfg(not(miri))] // Very slow in miri fn roundtrip() { let mut s = String::new(); diff --git a/tests/compile-pass/item_positions.rs b/tests/compile-pass/item_positions.rs --- a/tests/compile-pass/item_positions.rs +++ b/tests/compile-pass/item_positions.rs @@ -1,3 +1,5 @@ +#![allow(clippy::let_unit_value)] + #[macro_use] extern crate bitflags; diff --git /dev/null b/tests/compile-pass/missing_docs.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/missing_docs.rs @@ -0,0 +1,19 @@ +/*! +Crate-level doc +*/ + +#![deny(missing_docs)] + +use bitflags::bitflags; + +bitflags! { + #[allow(missing_docs)] + pub struct MyFlags: u32 { + #[allow(missing_docs)] + const A = 1; + #[allow(missing_docs)] + const B = 2; + } +} + +fn main() {} diff --git a/tests/compile.rs b/tests/compile.rs --- a/tests/compile.rs +++ b/tests/compile.rs @@ -2,6 +2,7 @@ // an impossible build between error messages emitted on various channels. // Since https://github.com/dtolnay/trybuild/pull/170 we always need to have a // `stderr` file for each test so we can't simply ignore the output on different channels. +#[cfg(not(miri))] #[rustversion::attr(beta, test)] #[allow(dead_code)] fn fail() { diff --git a/tests/compile.rs b/tests/compile.rs --- a/tests/compile.rs +++ b/tests/compile.rs @@ -9,6 +10,7 @@ fn fail() { t.compile_fail("tests/compile-fail/**/*.rs"); } +#[cfg(not(miri))] #[test] fn pass() { let t = trybuild::TestCases::new();
2.4
380
2023-10-09T04:48:32Z
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -84,18 +84,19 @@ jobs: cd ./tests/smoke-test cargo +$msrv build - mips: - name: Tests / MIPS (Big Endian) + miri: + name: "Miri" runs-on: ubuntu-latest steps: - - name: Checkout sources - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - - - name: Install Cross - run: cargo install cross - + - uses: actions/checkout@v3 + - name: Install Miri + run: | + rustup toolchain install nightly --component miri + cargo +nightly miri setup - name: Default features - run: cross test --target mips-unknown-linux-gnu + run: cargo +nightly miri test + - name: BE + run: cargo +nightly miri test --target s390x-unknown-linux-gnu clippy: name: Clippy diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -46,11 +46,17 @@ use bitflags::bitflags; // The `bitflags!` macro generates `struct`s that manage a set of flags. bitflags! { + /// Represents a set of flags. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] struct Flags: u32 { + /// The value `A`, at bit position `0`. const A = 0b00000001; + /// The value `B`, at bit position `1`. const B = 0b00000010; + /// The value `C`, at bit position `2`. const C = 0b00000100; + + /// The combination of `A`, `B`, and `C`. const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -481,7 +481,8 @@ macro_rules! bitflags { non_upper_case_globals, clippy::assign_op_pattern, clippy::indexing_slicing, - clippy::same_name_method + clippy::same_name_method, + clippy::iter_without_into_iter, )] const _: () = { // Declared in a "hidden" scope that can't be reached directly diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -553,7 +554,8 @@ macro_rules! bitflags { unused_mut, unused_imports, non_upper_case_globals, - clippy::assign_op_pattern + clippy::assign_op_pattern, + clippy::iter_without_into_iter, )] const _: () = { __impl_public_bitflags! {
472e392c0d082c0894b18fb31f4e68e0b145e29c
bitflags/bitflags
Empty bitflags definitions fail to parse This doesn't parse: ```rust bitflags::bitflags! { pub struct BoxFlags: u8 { } } ```
Hmm, it looks like we're using `+` rather than `*` as the repetition control. I can't imagine an empty set of `bitflags` would be very useful. Do you have a case where you've run into this? It might useful when introducing the type and designing the API first, before you even actually add the various bitflags Yeh that seems fair. If there’s no reason to require bitflags have at least one item then we could probably just allow these to be written. > It might useful when introducing the type and designing the API first, before you even actually add the various bitflags Yeah I was doing that, just propagating some flag value which I know I will need but didn't know yet what the flags themselves will be. You can just put something like this in there: ```rust #[cfg(empty_bitflag_workaround)] const EMPTY_BITFLAG_WORKAROUND = 0; ```
bitflags__bitflags-225
[ "179" ]
bd24f9d8d266bfb2dfe4b8238b196ecf5e37dee1
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -992,6 +1026,11 @@ mod tests { } } + bitflags! { + struct EmptyFlags: u32 { + } + } + #[test] fn test_bits() { assert_eq!(Flags::empty().bits(), 0b00000000); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1000,6 +1039,8 @@ mod tests { assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00); assert_eq!(AnotherSetOfFlags::ANOTHER_FLAG.bits(), !0_i8); + + assert_eq!(EmptyFlags::empty().bits(), 0b00000000); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1014,6 +1055,9 @@ mod tests { AnotherSetOfFlags::from_bits(!0_i8), Some(AnotherSetOfFlags::ANOTHER_FLAG) ); + + assert_eq!(EmptyFlags::from_bits(0), Some(EmptyFlags::empty())); + assert_eq!(EmptyFlags::from_bits(0b1), None); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1029,6 +1073,9 @@ mod tests { AnotherSetOfFlags::from_bits_truncate(0_i8), AnotherSetOfFlags::empty() ); + + assert_eq!(EmptyFlags::from_bits_truncate(0), EmptyFlags::empty()); + assert_eq!(EmptyFlags::from_bits_truncate(0b1), EmptyFlags::empty()); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1037,6 +1084,7 @@ mod tests { assert_eq!(unsafe { Flags::from_bits_unchecked(0) }, Flags::empty()); assert_eq!(unsafe { Flags::from_bits_unchecked(0b1) }, Flags::A); assert_eq!(unsafe { Flags::from_bits_unchecked(0b10) }, Flags::B); + assert_eq!( unsafe { Flags::from_bits_unchecked(0b11) }, (Flags::A | Flags::B) diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1049,6 +1097,12 @@ mod tests { unsafe { Flags::from_bits_unchecked(0b1001) }, (extra | Flags::A) ); + + let extra = unsafe { EmptyFlags::from_bits_unchecked(0b1000) }; + assert_eq!( + unsafe { EmptyFlags::from_bits_unchecked(0b1000) }, + (extra | EmptyFlags::empty()) + ); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1058,6 +1112,9 @@ mod tests { assert!(!Flags::ABC.is_empty()); assert!(!AnotherSetOfFlags::ANOTHER_FLAG.is_empty()); + + assert!(EmptyFlags::empty().is_empty()); + assert!(EmptyFlags::all().is_empty()); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1067,6 +1124,9 @@ mod tests { assert!(Flags::ABC.is_all()); assert!(AnotherSetOfFlags::ANOTHER_FLAG.is_all()); + + assert!(EmptyFlags::all().is_all()); + assert!(EmptyFlags::empty().is_all()); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1108,6 +1168,8 @@ mod tests { assert!(Flags::ABC.contains(e2)); assert!(AnotherSetOfFlags::ANOTHER_FLAG.contains(AnotherSetOfFlags::ANOTHER_FLAG)); + + assert!(EmptyFlags::empty().contains(EmptyFlags::empty())); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1293,10 +1355,16 @@ mod tests { let extra = unsafe { Flags::from_bits_unchecked(0xb8) }; assert_eq!(format!("{:?}", extra), "0xb8"); assert_eq!(format!("{:?}", Flags::A | extra), "A | 0xb8"); + assert_eq!( format!("{:?}", Flags::ABC | extra), "A | B | C | ABC | 0xb8" ); + + assert_eq!( + format!("{:?}", EmptyFlags::empty()), + "(empty)" + ); } #[test]
1.2
225
2020-10-01T16:10:42Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -360,7 +360,7 @@ macro_rules! bitflags { $( $(#[$inner:ident $($args:tt)*])* const $Flag:ident = $value:expr; - )+ + )* } $($t:tt)* ) => { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -370,7 +370,7 @@ macro_rules! bitflags { $( $(#[$inner $($args)*])* $Flag = $value; - )+ + )* } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -414,7 +414,7 @@ macro_rules! __bitflags { $( $(#[$inner:ident $($args:tt)*])* $Flag:ident = $value:expr; - )+ + )* } ) => { $(#[$outer])* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -428,7 +428,7 @@ macro_rules! __bitflags { $( $(#[$inner $($args)*])* $Flag = $value; - )+ + )* } } }; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -490,7 +490,7 @@ macro_rules! __fn_bitflags { #[macro_export(local_inner_macros)] #[doc(hidden)] -macro_rules! __impl_bitflags { +macro_rules! __all_bitflags { ( $BitFlags:ident: $T:ty { $( diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -498,6 +498,55 @@ macro_rules! __impl_bitflags { $Flag:ident = $value:expr; )+ } + ) => { + __fn_bitflags! { + /// Returns the set containing all flags. + #[inline] + pub const fn all() -> $BitFlags { + // See `Debug::fmt` for why this approach is taken. + #[allow(non_snake_case)] + trait __BitFlags { + $( + const $Flag: $T = 0; + )+ + } + impl __BitFlags for $BitFlags { + $( + __impl_bitflags! { + #[allow(deprecated)] + $(? #[$attr $($args)*])* + const $Flag: $T = Self::$Flag.bits; + } + )+ + } + $BitFlags { bits: $(<$BitFlags as __BitFlags>::$Flag)|+ } + } + } + }; + ( + $BitFlags:ident: $T:ty { + } + ) => { + __fn_bitflags! { + /// Returns the set containing all flags. + #[inline] + pub const fn all() -> $BitFlags { + $BitFlags { bits: 0 } + } + } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_bitflags { + ( + $BitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident = $value:expr; + )* + } ) => { impl $crate::_core::fmt::Debug for $BitFlags { fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -514,7 +563,7 @@ macro_rules! __impl_bitflags { $( #[inline] fn $Flag(&self) -> bool { false } - )+ + )* } // Conditionally override the check for just those flags that diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -533,7 +582,7 @@ macro_rules! __impl_bitflags { } } } - )+ + )* } let mut first = true; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -545,7 +594,7 @@ macro_rules! __impl_bitflags { first = false; f.write_str(__bitflags_stringify!($Flag))?; } - )+ + )* let extra_bits = self.bits & !$BitFlags::all().bits(); if extra_bits != 0 { if !first { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -587,7 +636,7 @@ macro_rules! __impl_bitflags { $( $(#[$attr $($args)*])* pub const $Flag: $BitFlags = $BitFlags { bits: $value }; - )+ + )* __fn_bitflags! { /// Returns an empty set of flags. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -597,29 +646,14 @@ macro_rules! __impl_bitflags { } } - __fn_bitflags! { - /// Returns the set containing all flags. - #[inline] - pub const fn all() -> $BitFlags { - // See `Debug::fmt` for why this approach is taken. - #[allow(non_snake_case)] - trait __BitFlags { - $( - const $Flag: $T = 0; - )+ - } - impl __BitFlags for $BitFlags { + __all_bitflags! { + $BitFlags: $T { $( - __impl_bitflags! { - #[allow(deprecated)] - $(? #[$attr $($args)*])* - const $Flag: $T = Self::$Flag.bits; - } - )+ + $(#[$attr $($args)*])* + $Flag = $value; + )* } - $BitFlags { bits: $(<$BitFlags as __BitFlags>::$Flag)|+ } } - } __fn_bitflags! { /// Returns the raw value of the flags currently stored.
bd24f9d8d266bfb2dfe4b8238b196ecf5e37dee1
bitflags/bitflags
from_bits accepts non existing flags ```rs #[test] fn test_from_bits_edge_cases() { bitflags! { struct Flags: u8 { const A = 0b00000001; const BC = 0b00000110; } } let flags = Flags::from_bits(0b00000100); assert!(flags.is_none()); } ``` Unless I'm missing something this test should pass but it fails cause from_bits accepts flags that are not declared. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6fd4adbddc8b8740cbd35af2306073ca This is related to this issue in the implementation of iterators in this PR https://github.com/bitflags/bitflags/pull/204#issuecomment-950304444 Using `from_bits` instead of `from_bits_unchecked` should allow to produce any valid flags that are not a combination of other flags but at the moment `from_bits` seems to accept any flag that is included in a combination even if it's not declared. I can try to send a PR.
bitflags__bitflags-276
[ "275" ]
0141a07e55184304857384b0093d00959f0acfa6
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1891,6 +1907,37 @@ mod tests { } } + #[test] + fn test_from_bits_edge_cases() { + bitflags! { + struct Flags: u8 { + const A = 0b00000001; + const BC = 0b00000110; + } + } + + + let flags = Flags::from_bits(0b00000100); + assert_eq!(flags, None); + let flags = Flags::from_bits(0b00000101); + assert_eq!(flags, None); + } + + #[test] + fn test_from_bits_truncate_edge_cases() { + bitflags! { + struct Flags: u8 { + const A = 0b00000001; + const BC = 0b00000110; + } + } + + let flags = Flags::from_bits_truncate(0b00000100); + assert_eq!(flags, Flags::empty()); + let flags = Flags::from_bits_truncate(0b00000101); + assert_eq!(flags, Flags::A); + } + #[test] fn test_iter() { bitflags! { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1924,22 +1971,4 @@ mod tests { assert_eq!(iter.next().unwrap(), Flags::THREE); assert_eq!(iter.next(), None); } - - #[test] - fn test_iter_edge_cases() { - bitflags! { - struct Flags: u8 { - const A = 0b00000001; - const BC = 0b00000110; - } - } - - - let flags = Flags::all(); - assert_eq!(flags.iter().count(), 2); - let mut iter = flags.iter(); - assert_eq!(iter.next().unwrap(), Flags::A); - assert_eq!(iter.next().unwrap(), Flags::BC); - assert_eq!(iter.next(), None); - } } diff --git a/tests/compile-fail/non_integer_base/all_defined.stderr.beta b/tests/compile-fail/non_integer_base/all_defined.stderr.beta --- a/tests/compile-fail/non_integer_base/all_defined.stderr.beta +++ b/tests/compile-fail/non_integer_base/all_defined.stderr.beta @@ -49,8 +49,41 @@ error[E0308]: mismatched types = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) help: try wrapping the expression in `MyInt` | -562 | if (bits & !Self::all().bits()) == MyInt(0) { - | ++++++ + +574 | if bits == MyInt(0) { + | ++++++ + + +error[E0277]: no implementation for `{integer} |= MyInt` + --> $DIR/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ no implementation for `{integer} |= MyInt` + | + = help: the trait `BitOrAssign<MyInt>` is not implemented for `{integer}` + = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0308]: mismatched types + --> $DIR/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ expected struct `MyInt`, found integer + | + = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) +help: try wrapping the expression in `MyInt` + | +589 | Self { bits: MyInt(truncated) } + | ++++++ + error[E0308]: mismatched types --> $DIR/all_defined.rs:115:1
1.3
276
2022-04-19T09:54:30Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -559,10 +559,11 @@ macro_rules! __impl_bitflags { /// representation contains bits that do not correspond to a flag. #[inline] pub const fn from_bits(bits: $T) -> $crate::_core::option::Option<Self> { - if (bits & !Self::all().bits()) == 0 { - $crate::_core::option::Option::Some(Self { bits }) + let truncated = Self::from_bits_truncate(bits).bits; + if truncated == bits { + Some(Self{ bits }) } else { - $crate::_core::option::Option::None + None } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -570,7 +571,22 @@ macro_rules! __impl_bitflags { /// that do not correspond to flags. #[inline] pub const fn from_bits_truncate(bits: $T) -> Self { - Self { bits: bits & Self::all().bits } + if bits == 0 { + return Self{ bits } + } + + #[allow(unused_mut)] + let mut truncated = 0; + + $( + #[allow(unused_doc_comments, unused_attributes)] + $(#[$attr $($args)*])* + if bits & Self::$Flag.bits == Self::$Flag.bits { + truncated |= Self::$Flag.bits + } + )* + + Self { bits: truncated } } /// Convert from underlying bit representation, preserving all
810dc35aba3df7314de01b93c7aa137968e925d4
bitflags/bitflags
`cargo build --test` fails on Windows [One of the tests](https://github.com/bitflags/bitflags/blob/8a10bdc144bb2a4b97c63cfa76be90228954d029/src/lib.rs#L920) for `bitflags-1.1.0` fails to compile on Windows with a stable rustc (version 1.36.0). ``` [INFO] [stderr] error[E0425]: cannot find value `_CFG_A` in this scope [INFO] [stderr] --> src\lib.rs:927:28 [INFO] [stderr] | [INFO] [stderr] 927 | const _CFG_C = _CFG_A.bits | 0b10; [INFO] [stderr] | ^^^^^^ not found in this scope [INFO] [stderr] [INFO] [stderr] error: aborting due to previous error ``` This suggests that `#[cfg]` attributes are not being properly added to `const` declarations, but I'm not quite sure exactly what's going on here.
Thanks for the report @ecstatic-morse! I'm not in front of my Windows box right now, but will look into this when I am, unless somebody else checks it first. I would guess that swapping `#[cfg(unix)]` and `#[cfg(windows)]` in that test will result in a failure on *nix. Btw, this arose while testing out `crater` runs on Windows. I'm guessing this test was a holdover from before `bitflags` used associated consts? Should be `Self::_CFG_A`. This test should probably just be rewritten though.
bitflags__bitflags-186
[ "185" ]
8a10bdc144bb2a4b97c63cfa76be90228954d029
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1111,7 +1111,7 @@ mod tests { #[cfg(bitflags_const_fn)] #[test] fn test_const_fn() { - const M1: Flags = Flags::empty(); + const _M1: Flags = Flags::empty(); const M2: Flags = Flags::A; assert_eq!(M2, Flags::A);
1.1
186
2019-07-20T12:27:25Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -919,12 +919,12 @@ mod tests { bitflags! { struct _CfgFlags: u32 { - #[cfg(windows)] - const _CFG_A = 0b01; #[cfg(unix)] - const _CFG_B = 0b01; + const _CFG_A = 0b01; #[cfg(windows)] - const _CFG_C = _CFG_A.bits | 0b10; + const _CFG_B = 0b01; + #[cfg(unix)] + const _CFG_C = Self::_CFG_A.bits | 0b10; } }
8a10bdc144bb2a4b97c63cfa76be90228954d029
bitflags/bitflags
Bitflags values of zero are considered always present When a bitflag is built with a zero valued item then it is treated as always present by bitflags functions. This may cause bugs but it definitely causes confusion when printing such a value. See the following for an example: ``` #[macro_use] extern crate bitflags; bitflags! { struct Flags: u32 { const NONE = 0b0; const SOME = 0b1; } } fn main() { let none = Flags::NONE; let some = Flags::SOME; println!("NONE = {:?}", none); println!("SOME = {:?}", some); assert!(some.contains(Flags::NONE)); } ``` Results in an output of: ``` NONE = NONE SOME = NONE | SOME ``` I noticed this when printing some flags from git2, specifically [MergeAnalysis](https://docs.rs/git2/0.7.1/git2/struct.MergeAnalysis.html). The output of a `format("{:?}", flag)` ended up being "(ANALYSIS_NONE | ANALYSIS_NORMAL | ANALYSIS_FASTFORWARD)" which confused me greatly. ANALYSIS_NONE is zero as that is how it is defined in [git2](https://github.com/libgit2/libgit2/blob/HEAD/include/git2/merge.h#L320) It seems to me that way that flag is intended to be used is that NONE only shows up when there are no other things to set, or maybe as a placeholder and should only appear when nothing else is set.
I agree, a zero value should only show up in Debug output if no bits are set. Would you be interested in sending a PR to fix this? I would definitely be interested in doing so, where should I start? The Debug impls are constructed [here](https://github.com/rust-lang-nursery/bitflags/blob/1.0.2/src/lib.rs#L401). After looking some more at the code I think this is more involved than I thought. With the code considering empty flags as always present I think that changing just the debug output will make for bugs that are even more difficult to track down. For example `some.contains(Flags::NONE)` is always true in my example above, but if we remove it from the debug it will be more difficult to realise this is happening. At least `none.is_empty()` behaves correctly. In any case, I am happy to add this special case if I can also add to the documentation an explanation of zero flags.
bitflags__bitflags-157
[ "151" ]
74aa397b0e6899c8b5131da34351e7d87d247038
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1157,4 +1191,22 @@ mod tests { assert_eq!(module::value(), 1) } + + #[test] + fn test_zero_value_flags() { + bitflags! { + struct Flags: u32 { + const NONE = 0b0; + const SOME = 0b1; + } + } + + + assert!(Flags::empty().contains(Flags::NONE)); + assert!(Flags::SOME.contains(Flags::NONE)); + assert!(Flags::NONE.is_empty()); + + assert_eq!(format!("{:?}", Flags::empty()), "NONE"); + assert_eq!(format!("{:?}", Flags::SOME), "SOME"); + } }
1.0
157
2018-04-30T12:18:19Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -215,6 +215,36 @@ //! assert_eq!(implemented_default, (Flags::A | Flags::C)); //! } //! ``` +//! +//! # Zero Flags +//! +//! Flags with a value equal to zero will have some strange behavior that one should be aware of. +//! +//! ``` +//! #[macro_use] +//! extern crate bitflags; +//! +//! bitflags! { +//! struct Flags: u32 { +//! const NONE = 0b00000000; +//! const SOME = 0b00000001; +//! } +//! } +//! +//! fn main() { +//! let empty = Flags::empty(); +//! let none = Flags::NONE; +//! let some = Flags::SOME; +//! +//! // Zero flags are treated as always present +//! assert!(empty.contains(Flags::NONE)); +//! assert!(none.contains(Flags::NONE)); +//! assert!(some.contains(Flags::NONE)); +//! +//! // Zero flags will be ignored when testing for emptiness +//! assert!(none.is_empty()); +//! } +//! ``` #![no_std] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -424,7 +454,11 @@ macro_rules! __impl_bitflags { #[inline] $(? #[$attr $($args)*])* fn $Flag(&self) -> bool { - self.bits & Self::$Flag.bits == Self::$Flag.bits + if Self::$Flag.bits == 0 && self.bits != 0 { + false + } else { + self.bits & Self::$Flag.bits == Self::$Flag.bits + } } } )+
74aa397b0e6899c8b5131da34351e7d87d247038
bitflags/bitflags
pub(restricted) bitflags cc https://github.com/rust-lang/rust/issues/32409 - maybe no action is warranted until this feature is stable. ```rust bitflags! { pub(super) flags Flags: u8 { const A = 1 } } ```
pub(restricted) is now stable. But I think it is still blocked by `:vis` matcher (rust-lang/rust#41022) to allow a proper fix. ---- Currently the straightforward fix using `:vis` causes an error in `example_generated.rs` ```rust error: local ambiguity: multiple parsing options: built-in NTs vis ('vis') or 1 other option. --> src/example_generated.rs:5:5 | 4 | / bitflags! { 5 | | /// This is the same `Flags` struct defined in the [crate level example](../index.html#example). | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 6 | | /// Note that this struct is just for documentation purposes only, it must not be used outside 7 | | /// this crate. ... | 15 | | } 16 | | } | |_- in this macro invocation error: Could not compile `bitflags`. ``` <details><summary>(diff)</summary> ```diff diff --git a/src/lib.rs b/src/lib.rs index 1694837..356fba1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(macro_vis_matcher)] + //! A typesafe bitmask flag generator useful for sets of C-style bitmask flags. //! It can be used for creating typesafe wrappers around C APIs. //! @@ -305,16 +307,16 @@ pub extern crate core as _core; /// ``` #[macro_export] macro_rules! bitflags { - ($(#[$attr:meta])* pub struct $BitFlags:ident: $T:ty { + ($(#[$attr:meta])* $vis:vis struct $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ }) => { #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] $(#[$attr])* - pub struct $BitFlags { + $vis struct $BitFlags { bits: $T, } - $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+ + $($(#[$Flag_attr])* $vis const $Flag: $BitFlags = $BitFlags { bits: $value };)+ __impl_bitflags! { struct $BitFlags: $T { @@ -322,24 +324,6 @@ macro_rules! bitflags { } } }; - ($(#[$attr:meta])* struct $BitFlags:ident: $T:ty { - $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+ - }) => { - #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] - $(#[$attr])* - struct $BitFlags { - bits: $T, - } - - $($(#[$Flag_attr])* const $Flag: $BitFlags = $BitFlags { bits: $value };)+ - - __impl_bitflags! { - struct $BitFlags: $T { - $($(#[$Flag_attr])* const $Flag = $value;)+ - } - } - - }; } ``` </details> It looks like using `:vis` here is unblocked now, right?
bitflags__bitflags-135
[ "72" ]
8e163c64ec3ce242a9fef0347c73a82f5ea84b90
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1092,4 +1111,46 @@ mod tests { } } } + + #[test] + fn test_pub_crate() { + mod module { + bitflags! { + pub (crate) struct Test: u8 { + const FOO = 1; + } + } + } + + assert_eq!(module::Test::FOO.bits(), 1); + } + + #[test] + fn test_pub_in_module() { + mod module { + mod submodule { + bitflags! { + // `pub (in super)` means only the module `module` will + // be able to access this. + pub (in super) struct Test: u8 { + const FOO = 1; + } + } + } + + mod test { + // Note: due to `pub (in super)`, + // this cannot be accessed directly by the testing code. + pub (in super) fn value() -> u8 { + super::submodule::Test::FOO.bits() + } + } + + pub fn value() -> u8 { + test::value() + } + } + + assert_eq!(module::value(), 1) + } }
1.0
135
2017-11-08T05:38:51Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -336,6 +336,25 @@ macro_rules! bitflags { } } }; + ( + $(#[$outer:meta])* + pub ($($vis:tt)+) struct $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )+ + } + ) => { + __bitflags! { + $(#[$outer])* + (pub ($($vis)+)) $BitFlags: $T { + $( + $(#[$inner $($args)*])* + $Flag = $value; + )+ + } + } + }; } #[macro_export]
74aa397b0e6899c8b5131da34351e7d87d247038
bitflags/bitflags
Bitflags reverses order of multiline doc comments When compiling code like ``` bitflags! { pub struct AdjustFlags: u32 { /// Add buf.time to the current time. If buf.status includes the ADJ_NANO flag, then buf.time.tv_usec is interpreted as a nanosecond value; /// otherwise it is interpreted as microseconds. /// /// The value of buf.time is the sum of its two fields, but the field buf.time.tv_usec must always be nonnegative. /// The following example shows how to normalize a timeval with nanosecond resolution. /// /// ```C /// while (buf.time.tv_usec < 0) { /// buf.time.tv_sec -= 1; /// buf.time.tv_usec += 1000000000; /// } /// ``` const SETOFFSET = libc::ADJ_SETOFFSET; } } ``` The doc-comments order is reversed on compile, causing issues with generated docs and the doctest. This bug only occurs on bitflags 2.2.0 and not on earlier versions
This should be trivially fixed by swapping the order attributes are "pushed" in `__declare_bitflags`. We've already yanked `2.2.0` because it requires a lot more recursion, but will keep this open to make sure any new approach doesn't reverse the order of attributes.
bitflags__bitflags-345
[ "344" ]
cbcafa710fc31172511e62efa06ad9eb214e4734
diff --git /dev/null b/tests/compile-pass/large.rs new file mode 100644 --- /dev/null +++ b/tests/compile-pass/large.rs @@ -0,0 +1,311 @@ +/* +Copyright (c) 2016 Anatoly Ikorsky + +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. +*/ + +#[macro_use] +extern crate bitflags; + +bitflags! { + /// Client capability flags + #[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)] + pub struct CapabilityFlags: u32 { + /// Use the improved version of Old Password Authentication. Assumed to be set since 4.1.1. + const CLIENT_LONG_PASSWORD = 0x0000_0001; + + /// Send found rows instead of affected rows in EOF_Packet. + const CLIENT_FOUND_ROWS = 0x0000_0002; + + /// Get all column flags. + /// Longer flags in Protocol::ColumnDefinition320. + /// + /// ### Server + /// Supports longer flags. + /// + /// ### Client + /// Expects longer flags. + const CLIENT_LONG_FLAG = 0x0000_0004; + + /// Database (schema) name can be specified on connect in Handshake Response Packet. + /// ### Server + /// Supports schema-name in Handshake Response Packet. + /// + /// ### Client + /// Handshake Response Packet contains a schema-name. + const CLIENT_CONNECT_WITH_DB = 0x0000_0008; + + /// Don't allow database.table.column. + const CLIENT_NO_SCHEMA = 0x0000_0010; + + /// Compression protocol supported. + /// + /// ### Server + /// Supports compression. + /// + /// ### Client + /// Switches to Compression compressed protocol after successful authentication. + const CLIENT_COMPRESS = 0x0000_0020; + + /// Special handling of ODBC behavior. + const CLIENT_ODBC = 0x0000_0040; + + /// Can use LOAD DATA LOCAL. + /// + /// ### Server + /// Enables the LOCAL INFILE request of LOAD DATA|XML. + /// + /// ### Client + /// Will handle LOCAL INFILE request. + const CLIENT_LOCAL_FILES = 0x0000_0080; + + /// Ignore spaces before '('. + /// + /// ### Server + /// Parser can ignore spaces before '('. + /// + /// ### Client + /// Let the parser ignore spaces before '('. + const CLIENT_IGNORE_SPACE = 0x0000_0100; + + const CLIENT_PROTOCOL_41 = 0x0000_0200; + + /// This is an interactive client. + /// Use System_variables::net_wait_timeout versus System_variables::net_interactive_timeout. + /// + /// ### Server + /// Supports interactive and noninteractive clients. + /// + /// ### Client + /// Client is interactive. + const CLIENT_INTERACTIVE = 0x0000_0400; + + /// Use SSL encryption for the session. + /// + /// ### Server + /// Supports SSL + /// + /// ### Client + /// Switch to SSL after sending the capability-flags. + const CLIENT_SSL = 0x0000_0800; + + /// Client only flag. Not used. + /// + /// ### Client + /// Do not issue SIGPIPE if network failures occur (libmysqlclient only). + const CLIENT_IGNORE_SIGPIPE = 0x0000_1000; + + /// Client knows about transactions. + /// + /// ### Server + /// Can send status flags in OK_Packet / EOF_Packet. + /// + /// ### Client + /// Expects status flags in OK_Packet / EOF_Packet. + /// + /// ### Note + /// This flag is optional in 3.23, but always set by the server since 4.0. + const CLIENT_TRANSACTIONS = 0x0000_2000; + + const CLIENT_RESERVED = 0x0000_4000; + + const CLIENT_SECURE_CONNECTION = 0x0000_8000; + + /// Enable/disable multi-stmt support. + /// Also sets CLIENT_MULTI_RESULTS. Currently not checked anywhere. + /// + /// ### Server + /// Can handle multiple statements per COM_QUERY and COM_STMT_PREPARE. + /// + /// ### Client + /// May send multiple statements per COM_QUERY and COM_STMT_PREPARE. + const CLIENT_MULTI_STATEMENTS = 0x0001_0000; + + /// Enable/disable multi-results. + /// + /// ### Server + /// Can send multiple resultsets for COM_QUERY. Error if the server needs to send + /// them and client does not support them. + /// + /// ### Client + /// Can handle multiple resultsets for COM_QUERY. + /// + /// ### Requires + /// `CLIENT_PROTOCOL_41` + const CLIENT_MULTI_RESULTS = 0x0002_0000; + + /// Multi-results and OUT parameters in PS-protocol. + /// + /// ### Server + /// Can send multiple resultsets for COM_STMT_EXECUTE. + /// + /// ### Client + /// Can handle multiple resultsets for COM_STMT_EXECUTE. + /// + /// ### Requires + /// `CLIENT_PROTOCOL_41` + const CLIENT_PS_MULTI_RESULTS = 0x0004_0000; + + /// Client supports plugin authentication. + /// + /// ### Server + /// Sends extra data in Initial Handshake Packet and supports the pluggable + /// authentication protocol. + /// + /// ### Client + /// Supports authentication plugins. + /// + /// ### Requires + /// `CLIENT_PROTOCOL_41` + const CLIENT_PLUGIN_AUTH = 0x0008_0000; + + /// Client supports connection attributes. + /// + /// ### Server + /// Permits connection attributes in Protocol::HandshakeResponse41. + /// + /// ### Client + /// Sends connection attributes in Protocol::HandshakeResponse41. + const CLIENT_CONNECT_ATTRS = 0x0010_0000; + + /// Enable authentication response packet to be larger than 255 bytes. + /// When the ability to change default plugin require that the initial password + /// field in the Protocol::HandshakeResponse41 paclet can be of arbitrary size. + /// However, the 4.1 client-server protocol limits the length of the auth-data-field + /// sent from client to server to 255 bytes. The solution is to change the type of + /// the field to a true length encoded string and indicate the protocol change with + /// this client capability flag. + /// + /// ### Server + /// Understands length-encoded integer for auth response data in + /// Protocol::HandshakeResponse41. + /// + /// ### Client + /// Length of auth response data in Protocol::HandshakeResponse41 is a + /// length-encoded integer. + /// + /// ### Note + /// The flag was introduced in 5.6.6, but had the wrong value. + const CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x0020_0000; + + /// Don't close the connection for a user account with expired password. + /// + /// ### Server + /// Announces support for expired password extension. + /// + /// ### Client + /// Can handle expired passwords. + const CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS = 0x0040_0000; + + /// Capable of handling server state change information. + /// Its a hint to the server to include the state change information in OK_Packet. + /// + /// ### Server + /// Can set SERVER_SESSION_STATE_CHANGED in the SERVER_STATUS_flags_enum and send + /// Session State Information in a OK_Packet. + /// + /// ### Client + /// Expects the server to send Session State Information in a OK_Packet. + const CLIENT_SESSION_TRACK = 0x0080_0000; + + /// Client no longer needs EOF_Packet and will use OK_Packet instead. + /// + /// ### Server + /// Can send OK after a Text Resultset. + /// + /// ### Client + /// Expects an OK_Packet (instead of EOF_Packet) after the resultset + /// rows of a Text Resultset. + /// + /// ### Background + /// To support CLIENT_SESSION_TRACK, additional information must be sent after all + /// successful commands. Although the OK_Packet is extensible, the EOF_Packet is + /// not due to the overlap of its bytes with the content of the Text Resultset Row. + /// + /// Therefore, the EOF_Packet in the Text Resultset is replaced with an OK_Packet. + /// EOF_Packet is deprecated as of MySQL 5.7.5. + const CLIENT_DEPRECATE_EOF = 0x0100_0000; + + /// The client can handle optional metadata information in the resultset. + const CLIENT_OPTIONAL_RESULTSET_METADATA = 0x0200_0000; + + /// Compression protocol extended to support zstd compression method. + /// + /// This capability flag is used to send zstd compression level between client and server + /// provided both client and server are enabled with this flag. + /// + /// # Server + /// + /// Server sets this flag when global variable protocol-compression-algorithms has zstd + /// in its list of supported values. + /// + /// # Client + /// + /// Client sets this flag when it is configured to use zstd compression method. + const CLIENT_ZSTD_COMPRESSION_ALGORITHM = 0x0400_0000; + + /// Support optional extension for query parameters into the COM_QUERY + /// and COM_STMT_EXECUTE packets. + /// + /// # Server + /// + /// Expects an optional part containing the query parameter set(s). + /// Executes the query for each set of parameters or returns an error if more than 1 set + /// of parameters is sent and the server can't execute it. + /// + /// # Client + /// + /// Can send the optional part containing the query parameter set(s). + const CLIENT_QUERY_ATTRIBUTES = 0x0800_0000; + + /// Support Multi factor authentication. + /// + /// # Server + /// + /// Server sends AuthNextFactor packet after every nth factor + /// authentication method succeeds, except the last factor authentication. + /// + /// # Client + /// + /// Client reads AuthNextFactor packet sent by server + /// and initiates next factor authentication method. + const MULTI_FACTOR_AUTHENTICATION = 0x1000_0000; + + /// Client or server supports progress reports within error packet. + const CLIENT_PROGRESS_OBSOLETE = 0x2000_0000; + + /// Verify server certificate. Client only flag. + /// + /// Deprecated in favor of –ssl-mode. + const CLIENT_SSL_VERIFY_SERVER_CERT = 0x4000_0000; + + /// Don't reset the options after an unsuccessful connect. Client only flag. + const CLIENT_REMEMBER_OPTIONS = 0x8000_0000; + } +} + +fn main() { + +}
2.2
345
2023-04-24T04:29:26Z
diff --git a/src/example_generated.rs b/src/example_generated.rs --- a/src/example_generated.rs +++ b/src/example_generated.rs @@ -33,8 +33,17 @@ __impl_public_bitflags! { __impl_public_bitflags_consts! { Flags { + /// Field `A`. + /// + /// This flag has the value `0b00000001`. A = 0b00000001; + /// Field `B`. + /// + /// This flag has the value `0b00000010`. B = 0b00000010; + /// Field `C`. + /// + /// This flag has the value `0b00000100`. C = 0b00000100; ABC = Self::A.bits() | Self::B.bits() | Self::C.bits(); } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -224,10 +224,14 @@ macro_rules! __impl_internal_bitflags { let mut truncated = <$T as $crate::__private::Bits>::EMPTY; $( - $(#[$attr $($args)*])* - if bits & $BitFlags::$Flag.bits() == $BitFlags::$Flag.bits() { - truncated |= $BitFlags::$Flag.bits() - } + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + if bits & $BitFlags::$Flag.bits() == $BitFlags::$Flag.bits() { + truncated |= $BitFlags::$Flag.bits() + } + } + ); )* Self { bits: truncated } diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -240,13 +244,19 @@ macro_rules! __impl_internal_bitflags { #[inline] pub fn from_name(name: &str) -> $crate::__private::core::option::Option<Self> { - match name { - $( + $( + __expr_safe_flags!( $(#[$attr $($args)*])* - $crate::__private::core::stringify!($Flag) => $crate::__private::core::option::Option::Some(Self { bits: $BitFlags::$Flag.bits() }), - )* - _ => $crate::__private::core::option::Option::None, - } + { + if name == $crate::__private::core::stringify!($Flag) { + return $crate::__private::core::option::Option::Some(Self { bits: $BitFlags::$Flag.bits() }); + } + } + ); + )* + + let _ = name; + $crate::__private::core::option::Option::None } #[inline] diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -384,10 +394,12 @@ macro_rules! __impl_internal_bitflags { let mut num_flags = 0; $( - $(#[$attr $($args)*])* - { - num_flags += 1; - } + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + { num_flags += 1; } + } + ); )* num_flags diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -395,15 +407,23 @@ macro_rules! __impl_internal_bitflags { const OPTIONS: [$T; NUM_FLAGS] = [ $( - $(#[$attr $($args)*])* - $BitFlags::$Flag.bits(), + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + $BitFlags::$Flag.bits() + } + ), )* ]; const OPTIONS_NAMES: [&'static str; NUM_FLAGS] = [ $( - $(#[$attr $($args)*])* - $crate::__private::core::stringify!($Flag), + __expr_safe_flags!( + $(#[$attr $($args)*])* + { + $crate::__private::core::stringify!($Flag) + } + ), )* ]; diff --git a/src/internal.rs b/src/internal.rs --- a/src/internal.rs +++ b/src/internal.rs @@ -439,3 +459,112 @@ macro_rules! __impl_internal_bitflags { } }; } + +/// A macro that processed the input to `bitflags!` and shuffles attributes around +/// based on whether or not they're "expression-safe". +/// +/// This macro is a token-tree muncher that works on 2 levels: +/// +/// For each attribute, we explicitly match on its identifier, like `cfg` to determine +/// whether or not it should be considered expression-safe. +/// +/// If you find yourself with an attribute that should be considered expression-safe +/// and isn't, it can be added here. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __expr_safe_flags { + // Entrypoint: Move all flags and all attributes into `unprocessed` lists + // where they'll be munched one-at-a-time + ( + $(#[$inner:ident $($args:tt)*])* + { $e:expr } + ) => { + __expr_safe_flags! { + expr: { $e }, + attrs: { + // All attributes start here + unprocessed: [$(#[$inner $($args)*])*], + processed: { + // Attributes that are safe on expressions go here + expr: [], + }, + }, + } + }; + // Process the next attribute on the current flag + // `cfg`: The next flag should be propagated to expressions + // NOTE: You can copy this rules block and replace `cfg` with + // your attribute name that should be considered expression-safe + ( + expr: { $e:expr }, + attrs: { + unprocessed: [ + // cfg matched here + #[cfg $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + expr: [$($expr:tt)*], + }, + }, + ) => { + __expr_safe_flags! { + expr: { $e }, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + expr: [ + $($expr)* + // cfg added here + #[cfg $($args)*] + ], + }, + }, + } + }; + // Process the next attribute on the current flag + // `$other`: The next flag should not be propagated to expressions + ( + expr: { $e:expr }, + attrs: { + unprocessed: [ + // $other matched here + #[$other:ident $($args:tt)*] + $($attrs_rest:tt)* + ], + processed: { + expr: [$($expr:tt)*], + }, + }, + ) => { + __expr_safe_flags! { + expr: { $e }, + attrs: { + unprocessed: [ + $($attrs_rest)* + ], + processed: { + expr: [ + // $other not added here + $($expr)* + ], + }, + }, + } + }; + // Once all attributes on all flags are processed, generate the actual code + ( + expr: { $e:expr }, + attrs: { + unprocessed: [], + processed: { + expr: [$(#[$expr:ident $($exprargs:tt)*])*], + }, + }, + ) => { + $(#[$expr $($exprargs)*])* + { $e } + } +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -558,315 +558,6 @@ macro_rules! bitflags { } $($t:tt)* - ) => { - __declare_bitflags!( - $(#[$outer])* - $vis struct $BitFlags: $T { - $( - $(#[$inner $($args)*])* - const $Flag = $value; - )* - } - ); - - bitflags! { - $($t)* - } - }; - () => {}; -} - -/// A macro that processed the input to `bitflags!` and shuffles attributes around -/// based on whether or not they're "expression-safe". -/// -/// This macro is a token-tree muncher that works on 2 levels: -/// -/// 1. Each flag, like `#[cfg(true)] const A: 42` -/// 2. Each attribute on that flag, like `#[cfg(true)]` -/// -/// Flags and attributes start in an "unprocessed" list, and are shifted one token -/// at a time into an appropriate processed list until the unprocessed lists are empty. -/// -/// For each attribute, we explicitly match on its identifier, like `cfg` to determine -/// whether or not it should be considered expression-safe. -/// -/// If you find yourself with an attribute that should be considered expression-safe -/// and isn't, it can be added here. -#[macro_export(local_inner_macros)] -#[doc(hidden)] -macro_rules! __declare_bitflags { - // Entrypoint: Move all flags and all attributes into `unprocessed` lists - // where they'll be munched one-at-a-time - ( - $(#[$outer:meta])* - $vis:vis struct $BitFlags:ident: $T:ty { - $( - $(#[$inner:ident $($args:tt)*])* - const $Flag:ident = $value:expr; - )* - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - // All flags start here - unprocessed: [ - $( - { - ident: $Flag, - value: $value, - attrs: { - // All attributes start here - unprocessed: [$(#[$inner $($args)*])*], - processed: { - // Attributes that should be added to item declarations go here - decl: [], - // Attributes that are safe on expressions go here - expr: [], - } - }, - }, - )* - ], - // Flags that have had their attributes sorted are pushed here - processed: [], - } - } - }; - // Process the next attribute on the current flag - // `cfg`: The next flag should be propagated to expressions - // NOTE: You can copy this rules block and replace `cfg` with - // your attribute name that should be considered expression-safe - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [ - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [ - // cfg matched here - #[cfg $($args:tt)*] - $($attrs_rest:tt)* - ], - processed: { - decl: [$($decl:tt)*], - expr: [$($expr:tt)*], - } - }, - }, - $($flags_rest:tt)* - ], - processed: [ - $($flags:tt)* - ], - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - unprocessed: [ - { - ident: $Flag, - value: $value, - attrs: { - unprocessed: [ - $($attrs_rest)* - ], - processed: { - decl: [ - // cfg added here - #[cfg $($args)*] - $($decl)* - ], - expr: [ - // cfg added here - #[cfg $($args)*] - $($expr)* - ], - } - }, - }, - $($flags_rest)* - ], - processed: [ - $($flags)* - ], - } - } - }; - // Process the next attribute on the current flag - // `$other`: The next flag should not be propagated to expressions - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [ - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [ - // $other matched here - #[$other:ident $($args:tt)*] - $($attrs_rest:tt)* - ], - processed: { - decl: [$($decl:tt)*], - expr: [$($expr:tt)*], - } - }, - }, - $($flags_rest:tt)* - ], - processed: [ - $($flags:tt)* - ], - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - unprocessed: [ - { - ident: $Flag, - value: $value, - attrs: { - unprocessed: [ - $($attrs_rest)* - ], - processed: { - decl: [ - // $other added here - #[$other $($args)*] - $($decl)* - ], - expr: [ - // $other not added here - $($expr)* - ], - } - }, - }, - $($flags_rest)* - ], - processed: [ - $($flags)* - ], - } - } - }; - // Complete the current flag once there are no unprocessed attributes left - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [ - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [], - processed: { - decl: [$($decl:tt)*], - expr: [$($expr:tt)*], - } - }, - }, - $($flags_rest:tt)* - ], - processed: [ - $($flags:tt)* - ], - } - ) => { - __declare_bitflags! { - decl: { - attrs: [$(#[$outer])*], - vis: $vis, - ident: $BitFlags, - ty: $T, - }, - flags: { - unprocessed: [ - $($flags_rest)* - ], - processed: [ - $($flags)* - { - ident: $Flag, - value: $value, - attrs: { - unprocessed: [], - processed: { - decl: [ - $($decl)* - ], - expr: [ - $($expr)* - ], - } - }, - }, - ], - } - } - }; - // Once all attributes on all flags are processed, generate the actual code - ( - decl: { - attrs: [$(#[$outer:meta])*], - vis: $vis:vis, - ident: $BitFlags:ident, - ty: $T:ty, - }, - flags: { - unprocessed: [], - processed: [ - $( - { - ident: $Flag:ident, - value: $value:expr, - attrs: { - unprocessed: [], - processed: { - decl: [$(#[$decl:ident $($declargs:tt)*])*], - expr: [$(#[$expr:ident $($exprargs:tt)*])*], - } - }, - }, - )* - ], - } ) => { // Declared in the scope of the `bitflags!` call // This type appears in the end-user's API diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -879,7 +570,7 @@ macro_rules! __declare_bitflags { __impl_public_bitflags_consts! { $BitFlags { $( - $(#[$decl $($declargs)*])* + $(#[$inner $($args)*])* #[allow( dead_code, deprecated, diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -912,7 +603,7 @@ macro_rules! __declare_bitflags { __impl_internal_bitflags! { InternalBitFlags: $T, $BitFlags, Iter, IterRaw { $( - $(#[$expr $($exprargs)*])* + $(#[$inner $($args)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -922,7 +613,7 @@ macro_rules! __declare_bitflags { __impl_external_bitflags! { InternalBitFlags: $T { $( - $(#[$expr $($exprargs)*])* + $(#[$inner $($args)*])* $Flag; )* } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -932,7 +623,12 @@ macro_rules! __declare_bitflags { $BitFlags: $T, InternalBitFlags, Iter, IterRaw; } }; - } + + bitflags! { + $($t)* + } + }; + () => {}; } #[macro_use]
cbcafa710fc31172511e62efa06ad9eb214e4734
bitflags/bitflags
serde support Are there any plans to support `Serialize` and `Deserialize` for generated types? I'm writing the impls manually in my code, but this falls apart once there's a ton of `bitflags` generated types. If others are interested in such a feature, maybe I can find the time to implement it myself and submit a pull request :)
During the libs blitz evaluation we saw that a grand total of 8 crates have dependencies on both bitflags and Serde, so we decided not to pursue it at the time. I would welcome a PR that adds Serialize and Deserialize impls behind a cfg. Adding `#[derive(Serialize, Deserialize)]` to the struct seems to work fine, I'm not sure it's really necessary to add this to the library itself.
bitflags__bitflags-125
[ "108" ]
29e60b23708123121a540fa9bde3254260952511
diff --git /dev/null b/tests/serde.rs new file mode 100644 --- /dev/null +++ b/tests/serde.rs @@ -0,0 +1,35 @@ +#[macro_use] +extern crate bitflags; + +#[macro_use] +extern crate serde_derive; +extern crate serde; +extern crate serde_json; + +bitflags! { + #[derive(Serialize, Deserialize)] + struct Flags: u32 { + const A = 1; + const B = 2; + const C = 4; + const D = 8; + } +} + +#[test] +fn serialize() { + let flags = Flags::A | Flags::B; + + let serialized = serde_json::to_string(&flags).unwrap(); + + assert_eq!(serialized, r#"{"bits":3}"#); +} + +#[test] +fn deserialize() { + let deserialized: Flags = serde_json::from_str(r#"{"bits":12}"#).unwrap(); + + let expected = Flags::C | Flags::D; + + assert_eq!(deserialized.bits, expected.bits); +}
1.0
125
2017-10-11T15:27:55Z
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -28,5 +28,8 @@ example_generated = [] [dev-dependencies] # Trick Cargo into testing this crate when we run `cargo test --all`. bitflags-compiletest = { path = "compiletest" } +serde = "1.0" +serde_derive = "1.0" +serde_json = "1.0" [workspace]
74aa397b0e6899c8b5131da34351e7d87d247038
bitflags/bitflags
is_all() vs. from_bits_unchecked() [`unsafe from_bits_unchecked()`](https://docs.rs/bitflags/1.2.1/bitflags/example_generated/struct.Flags.html#method.from_bits_unchecked) allows creating instances with extra bits. The caller of the `bitflags!` macro can decide if this is allowed for their type. Let's assume it is for `Example`. I checked the provided methods for surprising interactions with extra bits, and found (only) this: `is_all()` returns **false** when there are *more* than "all" flags. This does not match the documentation: > Returns true if all flags are currently set. Should we update the documentation or the implementation? --- ```rust use bitflags::bitflags; bitflags! { struct Example: u32 { const A = 1; } } fn main() { unsafe { assert!(Example::from_bits_unchecked(1).is_all()); // true assert!(Example::from_bits_unchecked(3).is_all()); // false } } ``` https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cda2672387dd0ff4ba629b1317a9c57c
bitflags__bitflags-211
[ "208" ]
15e911c304d5bd8805af55d7e4f8c5324ed798ee
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1048,6 +1048,11 @@ mod tests { assert!(!Flags::A.is_all()); assert!(Flags::ABC.is_all()); + let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + assert!(!extra.is_all()); + assert!(!(Flags::A | extra).is_all()); + assert!((Flags::ABC | extra).is_all()); + assert!(AnotherSetOfFlags::ANOTHER_FLAG.is_all()); }
1.2
211
2020-02-04T10:52:16Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -664,7 +664,7 @@ macro_rules! __impl_bitflags { /// Returns `true` if all flags are currently set. #[inline] pub const fn is_all(&self) -> bool { - self.bits == $BitFlags::all().bits + $BitFlags::all().bits | self.bits == self.bits } }
bd24f9d8d266bfb2dfe4b8238b196ecf5e37dee1
bitflags/bitflags
Create a test suite crate #61 adds an `unstable_testing` feature that is only considered by tests. It seems unfortunate to leak this into the public API. Having a separate crate for tests ([like in Serde](https://github.com/serde-rs/serde/tree/master/test_suite)) would avoid this.
bitflags__bitflags-127
[ "68" ]
862582d107bb74ce4c7b505b2490eb815bc3a8c2
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -9,23 +10,14 @@ rust: - beta - nightly sudo: false -before_script: - - pip install -v 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - - if [[ -e ~/Library/Python/2.7/bin ]]; then export PATH=~/Library/Python/2.7/bin:$PATH; fi script: - - travis-cargo build - - travis-cargo test - - travis-cargo --only nightly test -- --all - - travis-cargo --only stable doc -after_success: - - travis-cargo --only nightly doc-upload + - cargo test + - if [ "$TRAVIS_RUST_VERSION" = nightly ]; then (cd ./test_suite && cargo test --features unstable); fi env: global: - - TRAVIS_CARGO_NIGHTLY_FEATURE=unstable_testing - secure: "DoZ8g8iPs+X3xEEucke0Ae02JbkQ1qd1SSv/L2aQqxULmREtRcbzRauhiT+ToQO5Ft1Lul8uck14nPfs4gMr/O3jFFBhEBVpSlbkJx7eNL3kwUdp95UNroA8I43xPN/nccJaHDN6TMTD3+uajTQTje2SyzOQP+1gvdKg17kguvE=" - notifications: email: on_success: never diff --git a/compiletest/tests/tests.rs /dev/null --- a/compiletest/tests/tests.rs +++ /dev/null @@ -1,30 +0,0 @@ -extern crate compiletest_rs as compiletest; - -use std::fs; -use std::path::PathBuf; -use compiletest::common::Mode; - -fn run_mode(mode: Mode) { - let config = compiletest::Config { - mode: mode, - src_base: PathBuf::from(format!("tests/{}", mode)), - target_rustcflags: fs::read_dir("../target/debug/deps").unwrap().filter_map(|entry| { - let path = entry.unwrap().path(); - path.file_name().map(|file_name| file_name.to_string_lossy()).and_then(|file_name| { - if file_name.starts_with("libbitflags-") && file_name.ends_with(".rlib") { - Some(format!("--extern bitflags={}", path.to_string_lossy())) - } else { - None - } - }) - }).next(), - ..Default::default() - }; - - compiletest::run_tests(&config); -} - -#[test] -fn compile_test() { - run_mode(Mode::CompileFail); -} diff --git /dev/null b/test_suite/Cargo.toml new file mode 100644 --- /dev/null +++ b/test_suite/Cargo.toml @@ -0,0 +1,13 @@ +[project] +name = "test_suite" +version = "0.0.0" + +[features] +unstable = ["compiletest_rs"] + +[dependencies] +bitflags = { path = "../" } +compiletest_rs = { version = "*", optional = true } +serde = "1.0" +serde_derive = "1.0" +serde_json = "1.0" diff --git /dev/null b/test_suite/tests/compiletest.rs new file mode 100644 --- /dev/null +++ b/test_suite/tests/compiletest.rs @@ -0,0 +1,32 @@ +#![cfg(feature = "unstable")] + +extern crate compiletest_rs as compiletest; + +use std::result::Result; +use std::fs; + +use compiletest::common::Mode; + +fn run_mode(mode: Mode) { + let config = compiletest::Config { + mode: mode, + src_base: format!("tests/{}", mode).into(), + target_rustcflags: fs::read_dir("target/debug/deps").unwrap().map(Result::unwrap).filter(|entry| { + let file_name = entry.file_name(); + let file_name = file_name.to_string_lossy(); + file_name.starts_with("libbitflags-") && file_name.ends_with(".rlib") + }).max_by_key(|entry| { + entry.metadata().unwrap().modified().unwrap() + }).map(|entry| { + format!("--extern bitflags={}", entry.path().to_string_lossy()) + }), + ..Default::default() + }; + + compiletest::run_tests(&config); +} + +#[test] +fn compile_test() { + run_mode(Mode::CompileFail); +} diff --git a/tests/i128_bitflags.rs b/test_suite/tests/i128_bitflags.rs --- a/tests/i128_bitflags.rs +++ b/test_suite/tests/i128_bitflags.rs @@ -1,4 +1,4 @@ -#![cfg(feature = "unstable_testing")] +#![cfg(feature = "unstable")] #![feature(i128_type)]
1.0
127
2017-10-17T16:27:59Z
diff --git a/.gitignore b/.gitignore --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -/target -/Cargo.lock +target +Cargo.lock diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,7 @@ os: - linux - osx language: rust +cache: cargo rust: # This version is tested to avoid unintentional bumping of the minimum supported Rust version - 1.20.0 diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -22,14 +22,4 @@ travis-ci = { repository = "rust-lang-nursery/bitflags" } [features] default = ["example_generated"] -unstable_testing = [] example_generated = [] - -[dev-dependencies] -# Trick Cargo into testing this crate when we run `cargo test --all`. -bitflags-compiletest = { path = "compiletest" } -serde = "1.0" -serde_derive = "1.0" -serde_json = "1.0" - -[workspace] diff --git a/compiletest/Cargo.toml /dev/null --- a/compiletest/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[project] -name = "bitflags-compiletest" -version = "0.0.0" - -[dev-dependencies] -bitflags = { path = "../" } -compiletest_rs = { version = "0.2" }
74aa397b0e6899c8b5131da34351e7d87d247038
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1