bitflags_attr_macros/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::{parse::Parse, punctuated::Punctuated, Error, Ident, ItemEnum, Result, Token};
/// An attribute macro that transforms an C-like enum into a bitflag struct implementing an type API
/// similar to the `bitflags` crate, and implementing traits as listed below.
///
/// # Generated trait implementations
/// This macro generates some trait implementations: [`fmt::Debug`], [`ops:Not`], [`ops:BitAnd`],
/// [`ops:BitOr`], [`ops:BitXor`], [`ops:BitAndAssign`], [`ops:BitOrAssign`], [`ops:BitXorAssign`],
/// [`fmt::Binary`], [`fmt::LowerHex`], [`fmt::UpperHex`], [`fmt::Octal`], [`From`], [`Clone`],
/// [`Copy`], [`Extend`], [`FromIterator`], [`IntoIterator`]
///
/// If the macro receives `no_auto_debug`, the trait [`fmt::Debug`] will not be generated. Use this
/// flag when you want to implement [`fmt::Debug`] manually or use the standard derive.
///
/// ## Serde feature
///
/// If the crate is compiled with the `serde` feature, this crate will generate implementations for
/// the `serde::{Serialize, Deserialize}` traits, but it will not import/re-export these traits,
/// your project must have `serde` as dependency.
///
/// Having this feature enabled will also generate a type to represent the parsing error and helper
/// functions to do parsing the generated type from strings. And will generate the implementation
/// for the [`FromStr`] trait.
///
/// ## Custom types
///
/// If the crate is compiled with the `custom-types` feature, it allows to use more than the types
/// defined in Rust `core` ("i8",`u8`,`i16`,`u16`,`i32`,`u32`,`i64`,`u64`,`i128`,`u128`,`isize`,
/// `usize`,`c_char`,`c_schar`,`c_uchar`,`c_short`,`c_ushort`,`c_int`,`c_uint`,`c_long`,`c_ulong`,
/// `c_longlong`,`c_ulonglong`) as long as it is a type alias to one of those types.
///
/// The reason it is behind a feature flag is that to ensure the validity of such constrain, we have
/// to pay the price of having much worse error messages. With this feature enabled, a invalid type
/// will cause a massive wall of error message.
///
/// # Example
///
/// ```
/// use bitflag_attr::bitflag;
///
/// #[bitflag(u32)]
/// #[derive(PartialEq, PartialOrd, Eq, Ord, Hash)]
/// pub enum Flags {
/// /// The value `A`, at bit position `0`.
/// A = 0b00000001,
/// /// The value `B`, at bit position `1`.
/// B = 0b00000010,
/// /// The value `C`, at bit position `2`.
/// C = 0b00000100,
///
/// /// The combination of `A`, `B`, and `C`.
/// ABC = A | B | C,
/// }
/// ```
///
/// Without generating [`fmt::Debug`]:
///
/// ```
/// use bitflag_attr::bitflag;
///
/// #[bitflag(u32, no_auto_debug)]
/// #[derive(PartialEq, PartialOrd, Eq, Ord, Hash)]
/// pub enum Flags {
/// /// The value `A`, at bit position `0`.
/// A = 0b00000001,
/// /// The value `B`, at bit position `1`.
/// B = 0b00000010,
/// /// The value `C`, at bit position `2`.
/// C = 0b00000100,
///
/// /// The combination of `A`, `B`, and `C`.
/// ABC = A | B | C,
/// }
/// ```
///
/// # Syntax
///
/// ```text
/// #[bitflag($ty[, no_auto_debug])]
/// $visibility enum $StructName {
/// FlagOne = flag1_value_expr,
/// FlagTwo = flag2_value_expr,
/// // ...
/// FlagN = flagn_value_expr,
/// }
/// ```
///
/// [`fmt::Debug`]: core::fmt::Debug
/// [`ops:Not`]: core::ops::Not
/// [`ops:BitAnd`]: core::ops::BitAnd
/// [`ops:BitOr`]: core::ops::BitOr
/// [`ops:BitXor`]: core::ops::BitXor
/// [`ops:BitAndAssign`]: core::ops::BitAndAssign
/// [`ops:BitOrAssign`]: core::ops::BitOrAssign
/// [`ops:BitXorAssign`]: core::ops::BitXorAssign
/// [`fmt::Binary`]: core::fmt::Binary
/// [`fmt::LowerHex`]: core::fmt::LowerHex
/// [`fmt::UpperHex`]: core::fmt::UpperHex
/// [`fmt::Octal`]: core::fmt::Octal
/// [`From`]: From
/// [`FromStr`]: core::str::FromStr
#[proc_macro_attribute]
pub fn bitflag(attr: TokenStream, item: TokenStream) -> TokenStream {
match bitflag_impl(attr, item) {
Ok(ts) => ts,
Err(err) => err.into_compile_error().into(),
}
}
fn bitflag_impl(attr: TokenStream, item: TokenStream) -> Result<TokenStream> {
let args: Args = syn::parse(attr)?;
let ty = args.ty;
// let ty = parse_ty(attr)?;
let item: ItemEnum = syn::parse(item)?;
let vis = item.vis;
let attrs = item.attrs;
let ty_name = item.ident;
let iter_name_ty = {
let span = ty_name.span();
let mut ty_name = ty_name.to_string();
ty_name.push_str("IterNames");
Ident::new(&ty_name, span)
};
let iter_ty = {
let span = ty_name.span();
let mut ty_name = ty_name.to_string();
ty_name.push_str("Iter");
Ident::new(&ty_name, span)
};
let const_mut = if cfg!(feature = "const-mut-ref") {
quote!(mut)
} else {
quote!()
};
let number_flags = item.variants.len();
let mut all_attrs = Vec::with_capacity(number_flags);
let mut all_flags = Vec::with_capacity(number_flags);
let mut all_flags_names = Vec::with_capacity(number_flags);
let mut all_variants = Vec::with_capacity(number_flags);
// The raw flags as private itens to allow defining flags referencing other flag definitions
let mut raw_flags = Vec::with_capacity(number_flags);
let mut flags = Vec::with_capacity(number_flags); // Associated constants
// First generate the raw_flags
for variant in item.variants.iter() {
let var_attrs = &variant.attrs;
let var_name = &variant.ident;
let expr = match variant.discriminant.as_ref() {
Some((_, expr)) => expr,
None => {
return Err(Error::new_spanned(
variant,
"a discriminant must be defined",
))
}
};
all_attrs.push(
var_attrs
.clone()
.into_iter()
.filter(|attr| !attr.path().is_ident("doc"))
.collect::<Vec<syn::Attribute>>(),
);
raw_flags.push(quote! {
#(#var_attrs)*
#[allow(non_upper_case_globals, dead_code, unused)]
const #var_name: #ty = #expr;
});
}
for variant in item.variants.iter() {
let var_attrs = &variant.attrs;
let var_name = &variant.ident;
let expr = match variant.discriminant.as_ref() {
Some((_, expr)) => expr,
None => {
return Err(Error::new_spanned(
variant,
"a discriminant must be defined",
))
}
};
all_flags.push(quote!(Self::#var_name));
// all_flags_names.push(quote!(stringify!(#var_name)));
all_flags_names.push(syn::LitStr::new(&var_name.to_string(), var_name.span()));
all_variants.push(quote!(#var_name));
flags.push(quote! {
#(#var_attrs)*
#vis const #var_name: Self = {
#(#raw_flags)*
Self(#expr)
};
});
}
let debug_impl = if args.no_auto_debug {
quote! {}
} else {
quote! {
#[automatically_derived]
impl ::core::fmt::Debug for #ty_name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
struct HumanReadable<'a>(&'a #ty_name);
impl<'a> ::core::fmt::Debug for HumanReadable<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
self.0.to_writer(f)
}
}
let name = ::core::stringify!(#ty_name);
f.debug_struct(name)
.field("bits", &::core::format_args!("{:#b}", self.0))
.field("human_readable", &HumanReadable(self))
.finish()
}
}
}
};
let serde_impl = if cfg!(feature = "serde") {
let parser_error_ty = {
let span = ty_name.span();
let mut ty = ty_name.to_string();
ty.push_str("ParserError");
Ident::new(&ty, span)
};
quote! {
#[automatically_derived]
impl ::serde::Serialize for #ty_name {
fn serialize<S>(&self, serializer: S) -> ::core::result::Result<S::Ok, S::Error>
where
S: ::serde::Serializer
{
struct AsDisplay<'a>(&'a #ty_name);
impl<'a> ::core::fmt::Display for AsDisplay<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
self.0.to_writer(f)
}
}
// Serialize human-readable flags as a string like `"A | B"`
if serializer.is_human_readable() {
serializer.collect_str(&AsDisplay(self))
}
// Serialize non-human-readable flags directly as the underlying bits
else {
self.bits().serialize(serializer)
}
}
}
#[automatically_derived]
impl<'de> ::serde::Deserialize<'de> for #ty_name {
fn deserialize<D>(deserializer: D) -> ::core::result::Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>
{
if deserializer.is_human_readable() {
struct HelperVisitor(::core::marker::PhantomData<#ty_name>);
impl<'de> ::serde::de::Visitor<'de> for HelperVisitor {
type Value = #ty_name;
fn expecting(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.write_str("a string value of `|` separated flags")
}
fn visit_str<E>(self, flags: &str) -> ::core::result::Result<Self::Value, E>
where
E: ::serde::de::Error,
{
Self::Value::from_text(flags).map_err(|e| E::custom(e))
}
}
deserializer.deserialize_str(HelperVisitor(::core::marker::PhantomData))
} else {
let bits = #ty::deserialize(deserializer)?;
Ok(#ty_name::from_bits_retain(bits))
}
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum #parser_error_ty {
EmptyFlag,
InvalidNamedFlag,
InvalidHexFlag,
}
#[automatically_derived]
impl ::core::error::Error for #parser_error_ty {}
#[automatically_derived]
impl ::core::fmt::Display for #parser_error_ty {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
match self {
Self::EmptyFlag => write!(f, "encountered empty flag"),
Self::InvalidNamedFlag => write!(f, "unrecognized named flag"),
Self::InvalidHexFlag => write!(f, "invalid hex flag"),
}
}
}
impl #ty_name {
/// Helper to parse flags from human readable format. Parse a flags value from text.
///
/// This function will fail on any names that don't correspond to defined flags.
/// Unknown bits will be retained.
pub(crate) fn from_text(input: &str) -> ::core::result::Result<Self, #parser_error_ty> {
let mut parsed_flags = Self::empty();
// If the input is empty, then return an empty set of flags
if input.trim().is_empty() {
return Ok(parsed_flags);
}
for flag in input.split('|') {
let flag = flag.trim();
// If the flag is empty, then we've got a missing input
if flag.is_empty() {
return Err(#parser_error_ty::EmptyFlag);
}
// If the flag starts with `0x` ten it's a hex number
// Parse it directly to the underlying bits
let parsed_flag = if let Some(flag) = flag.strip_prefix("0x") {
let bits = #ty::from_str_radix(flag, 16).map_err(|_| #parser_error_ty::InvalidHexFlag)?;
Self::from_bits_retain(bits)
} else {
// Otherwise, the flag is a name
// The generated flags type will determine whether or not it is a valid
// identifier
Self::from_flag_name(flag).ok_or_else(|| #parser_error_ty::InvalidNamedFlag)?
};
parsed_flags.set(parsed_flag);
}
Ok(parsed_flags)
}
/// Helper to parse flags from human readable format. Parse a flags value from text.
///
/// This function will fail on any names that don't correspond to defined flags.
/// Unknown bits will be ignored.
pub(crate) fn from_text_truncate(input: &str) -> ::core::result::Result<Self, #parser_error_ty> {
Ok(Self::from_text(input)?.truncate())
}
/// Helper to parse flags from human readable format. Parse a flags value from text.
///
/// This function will fail on any names that don't correspond to defined flags.
/// This function will fail to parse hex values.
pub(crate) fn from_text_strict(input: &str) -> ::core::result::Result<Self, #parser_error_ty> {
let mut parsed_flags = Self::empty();
// If the input is empty, then return an empty set of flags
if input.trim().is_empty() {
return Ok(parsed_flags);
}
for flag in input.split('|') {
let flag = flag.trim();
// If the flag is empty, then we've got a missing input
if flag.is_empty() {
return Err(#parser_error_ty::EmptyFlag);
}
// If the flag starts with `0x` then it is a hex number
// There aren't supported in the strict parser
if flag.starts_with("0x") {
return Err(#parser_error_ty::InvalidHexFlag);
}
let parsed_flag = Self::from_flag_name(flag).ok_or_else(|| #parser_error_ty::InvalidNamedFlag)?;
parsed_flags.set(parsed_flag);
}
Ok(parsed_flags)
}
}
#[automatically_derived]
impl ::core::str::FromStr for #ty_name {
type Err = #parser_error_ty;
fn from_str(input: &str) -> ::core::result::Result<Self, Self::Err> {
Self::from_text(input)
}
}
}
} else {
quote!()
};
let generated = quote! {
#[repr(transparent)]
#[derive(Clone, Copy)]
#(#attrs)*
#vis struct #ty_name(#ty)
where
#ty: ::bitflag_attr::BitflagPrimitive;
#[allow(non_upper_case_globals)]
impl #ty_name {
#[doc(hidden)]
#[allow(clippy::unused_unit)]
const __OG: () = {
{
// Original enum
// This is a hack to make LSP coloring to still sees the original enum variant as a Enum variant token.
enum Original {
#(
#(#all_attrs)*
#all_variants,
)*
}
}
()
};
#(#flags)*
/// Return the underlying bits of the bitflag
#[inline]
pub const fn bits(&self) -> #ty {
self.0
}
/// Converts from a `bits` value. Returning [`None`] is any unknown bits are set.
#[inline]
pub const fn from_bits(bits: #ty) -> Option<Self> {
let truncated = Self::from_bits_truncate(bits).0;
if truncated == bits {
Some(Self(bits))
} else {
None
}
}
/// Convert from `bits` value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: #ty) -> Self {
Self(bits & Self::all().0)
}
/// Convert from `bits` value exactly.
#[inline]
pub const fn from_bits_retain(bits: #ty) -> Self {
Self(bits)
}
/// Convert from a flag `name`.
#[inline]
pub fn from_flag_name(name: &str) -> Option<Self> {
match name {
#(
#(#all_attrs)*
#all_flags_names => Some(#all_flags),
)*
_ => None
}
}
/// Construct an empty bitflag.
#[inline]
pub const fn empty() -> Self {
Self(0)
}
/// Returns `true` if the flag is empty.
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == 0
}
/// Returns a bitflag that contains all value.
///
/// This will include bits that do not have any flags/meaning.
/// Use [`all`](Self::all) if you want only the specified flags set.
#[inline]
pub const fn all_bits() -> Self {
Self(!0)
}
/// Returns `true` if the bitflag contains all value bits set.
///
/// This will check for all bits.
/// Use [`is_all`](Self::is_all) if you want to check for all specified flags.
#[inline]
pub const fn is_all_bits(&self) -> bool {
self.0 == !0
}
/// Construct a bitflag with all known flags set.
///
/// This will only set the flags specified as associated constant.
#[inline]
pub const fn all() -> Self {
// Self(#(#all_flags.0 |)* 0)
let mut all = 0;
#(
#(#all_attrs)*{
all |= #all_flags.0
}
)*
Self(all)
}
/// Returns `true` if the bitflag contais all known flags.
///
#[inline]
pub const fn is_all(&self) -> bool {
self.0 == Self::all().0
}
/// Returns a bit flag that only has bits corresponding to the specified flags as associated constant.
#[inline]
pub const fn truncate(&self) -> Self {
Self(self.0 & Self::all().0)
}
/// Returns `true` if this bitflag intersects with any value in `other`.
///
/// This is equivalent to `(self & other) != Self::empty()`
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
(self.0 & other.0) != Self::empty().0
}
/// Returns `true` if this bitflag contains all values of `other`.
///
/// This is equivalent to `(self & other) == other`
#[inline]
pub const fn contains(&self, other: Self) -> bool {
(self.0 & other.0) == other.0
}
/// Returns the bitwise NOT of the flag.
///
/// This function does not truncate unused bits (bits that do not have any flags/meaning).
/// Use [`complement`](Self::complement) if you want that the result to be truncated in one call.
#[inline]
#[doc(alias = "complement")]
pub const fn not(self) -> Self {
Self(!self.0)
}
/// Returns the bitwise AND of the flag.
#[inline]
#[doc(alias = "intersection")]
pub const fn and(self, other: Self) -> Self {
Self(self.0 & other.0)
}
/// Returns the bitwise OR of the flag with `other`.
#[inline]
#[doc(alias = "union")]
pub const fn or(self, other: Self) -> Self {
Self(self.0 | other.0)
}
/// Returns the bitwise XOR of the flag with `other`.
#[inline]
#[doc(alias = "symmetric_difference")]
pub const fn xor(self, other: Self) -> Self {
Self(self.0 ^ other.0)
}
/// Returns the intersection from this value with `other`.
#[inline]
#[doc(alias = "and")]
pub const fn intersection(self, other: Self) -> Self {
self.and(other)
}
/// Returns the union from this value with `other`
#[inline]
#[doc(alias = "or")]
pub const fn union(self, other: Self) -> Self {
self.or(other)
}
/// Returns the difference from this value with `other`.
///
/// In other words, returns the intersection of this value with the negation of `other`.
#[inline]
pub const fn difference(self, other: Self) -> Self {
self.and(other.not())
}
/// Returns the symmetric difference from this value with `other`.
#[inline]
#[doc(alias = "xor")]
pub const fn symmetric_difference(self, other: Self) -> Self {
self.xor(other)
}
/// Returns the complement of the value.
///
/// This is very similar to the [`not`](Self::not), but truncates non used bits
#[inline]
#[doc(alias = "not")]
pub const fn complement(self) -> Self {
self.not().truncate()
}
/// Set the flags in `other` in the value.
#[inline]
#[doc(alias = "insert")]
pub #const_mut fn set(&mut self, other: Self) {
self.0 = self.or(other).0
}
/// Unset the flags in `other` in the value.
#[inline]
#[doc(alias = "remove")]
pub #const_mut fn unset(&mut self, other: Self) {
self.0 = self.difference(other).0
}
/// Toggle the flags in `other` in the value.
#[inline]
pub #const_mut fn toggle(&mut self, other: Self) {
self.0 = self.xor(other).0
}
}
#[automatically_derived]
impl ::core::ops::Not for #ty_name {
type Output = Self;
#[inline]
fn not(self) -> Self::Output {
self.complement()
}
}
#[automatically_derived]
impl ::core::ops::BitAnd for #ty_name {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self::Output {
self.and(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitOr for #ty_name {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self::Output {
self.or(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitXor for #ty_name {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self::Output {
self.xor(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitAndAssign for #ty_name {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
::core::ops::BitAndAssign::bitand_assign(&mut self.0, rhs.0)
}
}
#[automatically_derived]
impl ::core::ops::BitOrAssign for #ty_name {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
::core::ops::BitOrAssign::bitor_assign(&mut self.0, rhs.0)
}
}
#[automatically_derived]
impl ::core::ops::BitXorAssign for #ty_name {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
::core::ops::BitXorAssign::bitxor_assign(&mut self.0, rhs.0)
}
}
#[automatically_derived]
impl ::core::ops::Sub for #ty_name {
type Output = Self;
/// The intersection of a source flag with the complement of a target flags value
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.difference(rhs)
}
}
#[automatically_derived]
impl ::core::ops::SubAssign for #ty_name {
/// The intersection of a source flag with the complement of a target flags value
#[inline]
fn sub_assign(&mut self, rhs: Self) {
self.unset(rhs)
}
}
#[automatically_derived]
impl ::core::convert::From<#ty> for #ty_name {
#[inline]
fn from(val: #ty) -> Self {
Self::from_bits_truncate(val)
}
}
#[automatically_derived]
impl ::core::convert::From<#ty_name> for #ty {
#[inline]
fn from(val: #ty_name) -> Self {
val.0
}
}
#[automatically_derived]
impl ::core::fmt::Binary for #ty_name {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Binary::fmt(&self.0, f)
}
}
#[automatically_derived]
impl ::core::fmt::LowerHex for #ty_name {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::LowerHex::fmt(&self.0, f)
}
}
#[automatically_derived]
impl ::core::fmt::UpperHex for #ty_name {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::UpperHex::fmt(&self.0, f)
}
}
#[automatically_derived]
impl ::core::fmt::Octal for #ty_name {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Octal::fmt(&self.0, f)
}
}
#debug_impl
impl #ty_name {
const FLAGS: &'static [(&'static str, #ty_name)] = &[#(
#(#all_attrs)*
(#all_flags_names , #all_flags) ,
)*];
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> #iter_ty {
#iter_ty::new(self)
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self) -> #iter_name_ty {
#iter_name_ty::new(self)
}
/// Helper for formatting in human readable format. Write a flags value as text.
///
/// Any bits that aren't part of a contained flag will be formatted as a hex number.
pub(crate) fn to_writer<W>(&self, mut writer: W) -> ::core::fmt::Result
where
W: ::core::fmt::Write,
{
// A formatter for bitflags that produces text output like:
//
// A | B | 0xf6
//
// The names of set flags are written in a bar-separated-format,
// followed by a hex number of any remaining bits that are set
// but don't correspond to any flags.
// Iterate over known flag values
let mut first = true;
let mut iter = self.iter_names();
for (name, _) in &mut iter {
if !first {
writer.write_str(" | ")?;
}
first = false;
writer.write_str(name)?;
}
// Append any extra bits that correspond to flags to the end of the format
let remaining = iter.remaining();
if !remaining.is_empty() {
if !first {
writer.write_str(" | ")?;
}
::core::write!(writer, "{:#X}", remaining.bits())?;
}
::core::fmt::Result::Ok(())
}
/// Helper for formatting in human readable format. Write a flags value as text,
/// ignoring any unknown bits.
pub(crate) fn to_writer_truncate<W>(&self, writer: W) -> ::core::fmt::Result
where
W: ::core::fmt::Write
{
self.truncate().to_writer(writer)
}
/// Helper for formatting in human readable format. Write only the contained, defined,
/// named flags in a flags value as text.
pub(crate) fn to_writer_strict<W>(&self, mut writer: W) -> ::core::fmt::Result
where
W: ::core::fmt::Write
{
// This is a simplified version of `to_writer` that ignores
// any bits not corresponding to a named flag
let mut first = true;
let mut iter = self.iter_names();
for (name, _) in &mut iter {
if !first {
writer.write_str(" | ")?;
}
first = false;
writer.write_str(name)?;
}
::core::fmt::Result::Ok(())
}
}
#[automatically_derived]
impl ::core::iter::Extend<#ty_name> for #ty_name {
/// Set all flags of `iter` to self
fn extend<T: ::core::iter::IntoIterator<Item = Self>>(&mut self, iter: T) {
for item in iter {
self.set(item);
}
}
}
#[automatically_derived]
impl ::core::iter::FromIterator<#ty_name> for #ty_name {
/// Create a `#ty_name` from a iterator of flags.
fn from_iter<T: ::core::iter::IntoIterator<Item = Self>>(iter: T) -> Self {
use ::core::iter::Extend;
let mut res = Self::empty();
res.extend(iter);
res
}
}
#[automatically_derived]
impl ::core::iter::IntoIterator for #ty_name {
type Item = Self;
type IntoIter = #iter_ty;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[automatically_derived]
impl ::core::iter::IntoIterator for &#ty_name {
type Item = #ty_name;
type IntoIter = #iter_ty;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// An iterator over flags values.
///
/// This iterator only yields flags values for contained, defined, named flags. Any remaining bits
/// won't be yielded, but can be found with the [`#iter_name_ty::remaining`] method.
#vis struct #iter_name_ty {
flags: &'static [(&'static str, #ty_name)],
index: usize,
source: #ty_name,
remaining: #ty_name,
}
impl #iter_name_ty {
pub(crate) const fn new(flags: &#ty_name) -> Self {
Self {
flags: #ty_name::FLAGS,
index: 0,
remaining: *flags,
source: *flags,
}
}
/// Get a flags value of any remaining bits that haven't been yielded yet.
///
/// Once the iterator has finished, this method can be used to
/// check whether or not there are any bits that didn't correspond
/// to a contained, defined, named flag remaining.
pub const fn remaining(&self) -> #ty_name {
self.remaining
}
}
#[automatically_derived]
impl ::core::iter::Iterator for #iter_name_ty {
type Item = (&'static str, #ty_name);
fn next(&mut self) -> ::core::option::Option<Self::Item> {
while let Some((name, flag)) = self.flags.get(self.index) {
// Short-circuit if our state is empty
if self.remaining.is_empty() {
return None;
}
self.index += 1;
// If the flag is set in the original source _and_ it has bits that haven't
// been covered by a previous flag yet then yield it. These conditions cover
// two cases for multi-bit flags:
//
// 1. When flags partially overlap, such as `0b00000001` and `0b00000101`, we'll
// yield both flags.
// 2. When flags fully overlap, such as in convenience flags that are a shorthand for others,
// we won't yield both flags.
if self.source.contains(*flag) && self.remaining.intersects(*flag) {
self.remaining.unset(*flag);
return Some((name, *flag))
}
}
None
}
}
#[automatically_derived]
impl ::core::iter::FusedIterator for #iter_name_ty {}
/// An iterator over flags values.
///
/// This iterator will yield flags values for contained, defined flags first, with any remaining bits yielded
/// as a final flags value.
#vis struct #iter_ty {
inner: #iter_name_ty,
done: bool,
}
impl #iter_ty {
pub(crate) const fn new(flags: &#ty_name) -> Self {
Self {
inner: #iter_name_ty::new(flags),
done: false,
}
}
}
#[automatically_derived]
impl ::core::iter::Iterator for #iter_ty {
type Item = #ty_name;
fn next(&mut self) -> ::core::option::Option<Self::Item> {
match self.inner.next() {
Some((_, flag)) => Some(flag),
None if !self.done => {
self.done = true;
// After iterating through valid names, if there are any bits left over
// then return one final value that includes them. This makes `into_iter`
// and `from_iter` roundtrip
if !self.inner.remaining().is_empty() {
Some(self.inner.remaining)
} else {
None
}
}
None => None
}
}
}
#[automatically_derived]
impl ::core::iter::FusedIterator for #iter_ty {}
#serde_impl
};
Ok(generated.into())
}
static VALID_TYPES: [&str; 23] = [
"i8",
"u8",
"i16",
"u16",
"i32",
"u32",
"i64",
"u64",
"i128",
"u128",
"isize",
"usize",
"c_char",
"c_schar",
"c_uchar",
"c_short",
"c_ushort",
"c_int",
"c_uint",
"c_long",
"c_ulong",
"c_longlong",
"c_ulonglong",
];
struct Args {
ty: Ident,
no_auto_debug: bool,
}
impl Parse for Args {
fn parse(input: syn::parse::ParseStream) -> Result<Self> {
let content: Punctuated<_, _> = input.parse_terminated(Ident::parse, Token![,])?;
if content.empty_or_trailing() {
return Ok(Args {
ty: Ident::new("u32", Span::call_site().into()),
no_auto_debug: false,
});
}
if content.len() > 2 {
return Err(Error::new_spanned(
content.last().unwrap(),
"more arguments than expected. Expected a max of one integer type and one `no_auto_debug` flag",
));
}
let mut no_debug_set = false;
let mut ty_set = false;
let mut no_auto_debug = false;
let mut ty = Ident::new("u32", Span::call_site().into());
for i in content {
if i == "no_auto_debug" {
if no_debug_set {
return Err(Error::new_spanned(
i,
"there must be only one instance of `no_auto_debug` flag",
));
}
no_auto_debug = true;
no_debug_set = true;
continue;
}
if cfg!(feature = "custom-types") {
if ty_set {
return Err(Error::new_spanned(
i,
"there must be only one instance of `{integer}` type specified",
));
}
ty = i;
ty_set = true;
} else if VALID_TYPES.contains(&i.to_string().as_str()) {
if ty_set {
return Err(Error::new_spanned(
i,
"there must be only one instance of `{integer}` type specified",
));
}
ty = i;
ty_set = true;
continue;
} else {
return Err(Error::new_spanned(i, "type must be a integer"));
}
}
Ok(Args { ty, no_auto_debug })
}
}