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
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
use syn::{
Attribute, DeriveInput, Error, Expr, Ident, LitInt, LitStr, Meta, MetaNameValue, Path,
Visibility, parse::Parse, punctuated::Punctuated, spanned::Spanned, token::Paren,
};
use proc_macro2::TokenStream;
use quote::{ToTokens, TokenStreamExt, quote};
pub struct Bitflag {
vis: Visibility,
attrs: Vec<Attribute>,
name: Ident,
inner_ty: Path,
repr_attr: Option<ReprAttr>,
derived_traits: Vec<Path>,
impl_flags: ImplFlags,
all_attrs: Vec<Vec<Attribute>>,
all_flags: Vec<TokenStream>,
all_flags_names: Vec<LitStr>,
flags: Vec<TokenStream>,
default_value: Option<Expr>,
custom_known_bits: Option<Expr>,
orig_enum: TokenStream,
}
impl Bitflag {
pub fn parse(args: Args, item: proc_macro::TokenStream) -> syn::Result<Self> {
let ty = args.ty;
let item: DeriveInput = syn::parse(item)?;
let item_span = item.span();
let ident_span = item.ident.span();
let og_attrs = item.attrs.iter().filter(|att| {
!att.path().is_ident("derive")
&& !att.path().is_ident("reserved_bits")
&& !att.path().is_ident("repr")
&& !att.path().is_ident("serde")
});
let vis = item.vis;
let name = item.ident;
let has_non_exhaustive = item
.attrs
.iter()
.any(|att| att.path().is_ident("non_exhaustive"));
let serde_helper = item.attrs.iter().find(|att| att.path().is_ident("serde"));
if let Some(serde) = serde_helper {
return Err(Error::new(
serde.span(),
"`serde` helper attribute is not compatible with `bitflag` attribute: in this case, manual implementation of serde traits should be considered",
));
}
// Attributes
let attrs = item
.attrs
.iter()
.filter(|att| {
!att.path().is_ident("derive")
&& !att.path().is_ident("reserved_bits")
&& !att.path().is_ident("repr")
})
.cloned()
.collect();
let repr_attr = item
.attrs
.iter()
.find(|att| att.path().is_ident("repr"))
.map(|att| syn::parse2::<ReprAttr>(att.meta.to_token_stream()));
let repr_attr = match repr_attr {
Some(repr) => {
use ReprKind::*;
let repr = repr?;
// Cause errors on invalid ones since Rust will cause worse errors
match repr.kinds() {
// ignore case | impossible case
(None, None) | (None, Some(_)) => {}
// Simplest cases
(Some(Rust(_) | C(_) | Transparent(_)), None) => {}
// Definitely wrong cases
(Some(kind), None)
| (Some(Rust(_) | C(_)), Some(kind))
| (Some(kind), Some(Rust(_) | C(_))) => {
return Err(Error::new(
kind.span(),
"`bitflag` unsupported repr: Supported repr are `C`, `Rust` and `transparent`",
));
}
// TODO: Theoretically, `packed(N)` and `align(N)` is allowed if N is the same
// or bigger than size_of the inner type. We can only prove it by this time
// if the inner type is one of the integers of specific type (i<BITS>|u<BITS>).
// We could allow and generate a static assert (a.k.a. a const that panics under
// condition) like we do with the `Pod` trait.
_ => {}
}
Some(repr)
}
None => None,
};
let valid_bits_attr = item
.attrs
.iter()
.find(|att| att.path().is_ident("reserved_bits"));
let derives = item
.attrs
.iter()
.filter(|att| att.path().is_ident("derive"));
let mut derived_traits = Vec::new();
let mut impl_flags = ImplFlags::empty();
let mut clone_found = false;
let mut copy_found = false;
for derive in derives {
derive.parse_nested_meta(|meta| {
let s = meta.path.to_token_stream().to_string().replace(" ", "");
match s.as_str() {
"Debug" => {
impl_flags |= ImplFlags::DEBUG;
return Ok(());
}
"Default" => {
impl_flags |= ImplFlags::DEFAULT;
return Ok(());
}
"Serialize" | "serde::Serialize" | "::serde::Serialize"
if cfg!(feature = "serde") =>
{
impl_flags |= ImplFlags::SERIALIZE;
return Ok(());
}
"Deserialize" | "serde::Deserialize" | "::serde::Deserialize"
if cfg!(feature = "serde") =>
{
impl_flags |= ImplFlags::DESERIALIZE;
return Ok(());
}
"Arbitrary" | "arbitrary::Arbitrary" | "::arbitrary::Arbitrary"
if cfg!(feature = "arbitrary") =>
{
impl_flags |= ImplFlags::ARBITRARY;
return Ok(());
}
"Pod" | "bytemuck::Pod" | "::bytemuck::Pod" if cfg!(feature = "bytemuck") => {
// Our types are repr(transparent) by default, and that is compatible with
// the constrains required by `Pod` trait.
if repr_attr.is_none() {
impl_flags |= ImplFlags::POD;
return Ok(());
}
if let Some(repr_attr) = &repr_attr {
match repr_attr.kinds() {
// Pod requires either `repr(transparent)` or `repr(C)` without
// padding (I think it's always safe for one field struct) or
// `repr(C, packed|align)`
// We should generate static checks to make sure though
(Some(ReprKind::Transparent(_) | ReprKind::C(_)), None)
| (
Some(ReprKind::C(_)),
Some(ReprKind::Packed(_, _) | ReprKind::Align(_, _)),
) => {
impl_flags |= ImplFlags::POD;
return Ok(());
}
_ => {
return Err(Error::new(
meta.path.span(),
format!(
"bitflag: deriving `Pod` for `{}` is not compatible",
repr_attr.to_token_stream()
),
));
}
}
}
}
"Zeroable" | "bytemuck::Zeroable" | "::bytemuck::Zeroable"
if cfg!(feature = "bytemuck") =>
{
impl_flags |= ImplFlags::ZEROABLE;
return Ok(());
}
path => {
if path == "Clone" {
clone_found = true;
}
if path == "Copy" {
copy_found = true;
}
derived_traits.push(meta.path);
}
}
Ok(())
})?;
}
if !clone_found || !copy_found {
return Err(syn::Error::new(
item_span,
"`bitflags` attribute requires the type to derive `Clone` and `Copy`",
));
}
let enun = if let syn::Data::Enum(e) = item.data {
e
} else {
return Err(syn::Error::new(
ident_span,
"the type for `bitflag` must be a `enum` (that will be turned into a `struct`)",
));
};
let number_flags = enun.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);
let mut all_non_doc_attrs = Vec::with_capacity(number_flags);
let mut default_value = None;
// 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 enun.variants.iter() {
let var_attrs = &variant.attrs;
let var_name = &variant.ident;
if !variant.fields.is_empty() {
let span = variant.fields.span();
return Err(Error::new(
span,
"an enum with `bitflag` attribute can not have a field",
));
}
let expr = match variant.discriminant.as_ref() {
Some((_, expr)) => expr,
None => {
return Err(Error::new_spanned(
variant,
"a discriminant must be defined",
));
}
};
let serde_helper = var_attrs.iter().find(|attr| attr.path().is_ident("serde"));
if let Some(serde) = serde_helper {
return Err(Error::new(
serde.span(),
"`serde` helper attribute is not compatible with `bitflag` attribute: in this case, manual implementation of serde traits should be considered",
));
}
let default_attr = var_attrs
.iter()
.find(|attr| attr.path().is_ident("default"));
if let Some(default) = default_attr {
if !impl_flags.contains(ImplFlags::DEFAULT) {
return Err(Error::new(
default.span(),
"`default` attribute without `#[derive(Default)]`",
));
}
default_value = Some(syn::parse2(quote!(Self::#var_name))?);
}
let non_doc_attrs: Vec<Attribute> = var_attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.cloned()
.collect();
let filtered_attrs = var_attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc") && !attr.path().is_ident("default"));
all_flags.push(quote!(#name::#var_name));
all_flags_names.push(syn::LitStr::new(&var_name.to_string(), var_name.span()));
all_variants.push(var_name.clone());
all_attrs.push(filtered_attrs.clone().cloned().collect::<Vec<_>>());
all_non_doc_attrs.push(non_doc_attrs.clone());
raw_flags.push(quote! {
#(#filtered_attrs)*
#[allow(non_upper_case_globals, dead_code, unused)]
const #var_name: #ty = #expr;
});
}
for variant in enun.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",
));
}
};
let all_attr = var_attrs
.iter()
.filter(|attr| !attr.path().is_ident("default"));
let generated = if can_simplify(expr, &all_variants) {
quote! {
#(#all_attr)*
#vis const #var_name: Self = Self(#expr);
}
} else {
quote! {
#(#all_attr)*
#vis const #var_name: Self = {
#(#raw_flags)*
Self(#expr)
};
}
};
flags.push(generated);
}
let og_derive = (impl_flags.contains(ImplFlags::DEFAULT) && default_value.is_some())
.then(|| quote!(#[derive(Default)]));
let orig_enum = quote! {
#[allow(dead_code)]
#(#og_attrs)*
#og_derive
enum #name {
#(
#(#all_non_doc_attrs)*
#all_variants,
)*
}
};
let custom_known_bits: Option<Expr> = if let Some(attr) = valid_bits_attr {
let parsed = ExtraValidBits::from_meta(&attr.meta)?;
Some(parsed.0)
} else if has_non_exhaustive {
Some(syn::parse2(quote! {!0})?)
} else {
None
};
Ok(Self {
vis,
attrs,
name,
inner_ty: ty,
derived_traits,
repr_attr,
impl_flags,
all_attrs,
all_flags,
all_flags_names,
default_value,
flags,
custom_known_bits,
orig_enum,
})
}
}
impl ToTokens for Bitflag {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self {
vis,
attrs,
name,
inner_ty,
repr_attr,
derived_traits,
impl_flags,
all_attrs,
all_flags,
all_flags_names,
default_value,
flags,
custom_known_bits,
orig_enum,
} = self;
let has_non_exhaustive = attrs
.iter()
.any(|att| att.path().is_ident("non_exhaustive"));
let reserved_bits = custom_known_bits
.as_ref()
.map(|expr| quote! {all |= #expr;});
let reserved_bits_value = if let Some(expr) = custom_known_bits {
quote! {#expr}
} else {
quote! {
{
let mut all = 0;
#(
#(#all_attrs)*{
all |= #all_flags.0;
}
)*
all
}
}
};
let repr_attr = match repr_attr {
Some(repr) => {
quote! {#repr}
}
None => quote! {#[repr(transparent)]},
};
let const_mut = cfg!(feature = "const-mut-ref").then(|| quote!(const));
let debug_impl = impl_flags.contains(ImplFlags::DEBUG).then(|| {
quote! {
#[automatically_derived]
impl ::core::fmt::Debug for #name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
struct HumanReadable<'a>(&'a #name);
impl<'a> ::core::fmt::Debug for HumanReadable<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
if self.0.is_empty() {
::core::write!(f, "{:#X}", self.0.0)
} else {
::bitflag_attr::parser::to_writer(self.0, f)
}
}
}
#[inline]
pub const fn octal_width() -> usize {
match #inner_ty::BITS as usize {
8 => 3,
16 => 6,
32 => 11,
64 => 22,
128 => 43,
// Not probable to happens, but if it does, do an approximation
x => x/3 + x%3
}
}
let name = ::core::stringify!(#name);
f.debug_struct(name)
.field("flags", &HumanReadable(self))
// The width `2 +` is to account for the 0b printed before the binary number
.field("bits", &::core::format_args!("{:#0width$b}", self.0, width = 2 + #inner_ty::BITS as usize))
.field("octal", &::core::format_args!("{:#0width$o}", self.0, width = 2 + const { octal_width() }))
.field("hex", &::core::format_args!("{:#0width$X}", self.0, width = 2 + const {#inner_ty::BITS as usize/4}))
.finish()
}
}
}
});
let default_impl = impl_flags.contains(ImplFlags::DEFAULT).then(|| {
if let Some(expr) = default_value {
quote! {
#[automatically_derived]
impl ::core::default::Default for #name {
#[inline]
fn default() -> Self {
#expr
}
}
}
} else {
quote! {
#[automatically_derived]
impl ::core::default::Default for #name {
#[inline]
fn default() -> Self {
Self(<#inner_ty as ::core::default::Default>::default())
}
}
}
}
});
let serialize_impl = (cfg!(feature = "serde") && impl_flags.contains(ImplFlags::SERIALIZE)).then(|| {
quote! {
#[automatically_derived]
impl ::bitflag_attr::external::Serialize for #name {
fn serialize<S>(&self, serializer: S) -> ::core::result::Result<S::Ok, S::Error>
where
S: ::bitflag_attr::external::Serializer
{
struct AsDisplay<'a>(&'a #name);
impl<'a> ::core::fmt::Display for AsDisplay<'a> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::bitflag_attr::parser::to_writer(self.0, 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)
}
}
}
}
});
let deserialize_impl = (cfg!(feature = "serde") && impl_flags.contains(ImplFlags::DESERIALIZE)).then(|| {
quote! {
#[automatically_derived]
impl<'de> ::bitflag_attr::external::Deserialize<'de> for #name {
fn deserialize<D>(deserializer: D) -> ::core::result::Result<Self, D::Error>
where
D: ::bitflag_attr::external::Deserializer<'de>
{
if deserializer.is_human_readable() {
struct HelperVisitor(::core::marker::PhantomData<#name>);
impl<'de> ::bitflag_attr::external::de::Visitor<'de> for HelperVisitor {
type Value = #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: ::bitflag_attr::external::de::Error,
{
::bitflag_attr::parser::from_text(flags).map_err(|e| E::custom(e))
}
}
deserializer.deserialize_str(HelperVisitor(::core::marker::PhantomData))
} else {
let bits = #inner_ty::deserialize(deserializer)?;
::core::result::Result::Ok(#name::from_bits_retain(bits))
}
}
}
}
});
let arbitrary_impl = (cfg!(feature = "arbitrary") && impl_flags.contains(ImplFlags::ARBITRARY)).then(|| {
quote! {
#[automatically_derived]
impl<'a> ::arbitrary::Arbitrary<'a> for #name {
fn arbitrary(u: &mut ::arbitrary::Unstructured<'a>) -> ::arbitrary::Result<Self> {
#name::from_bits(u.arbitrary()?).ok_or(::arbitrary::Error::IncorrectFormat)
}
}
}
});
let pod_impl =
(cfg!(feature = "bytemuck") && impl_flags.contains(ImplFlags::POD)).then(|| {
let error_str = LitStr::new(
&format!(
"`bitflag` error: type `{name}` not compatible with the `bytemuck::Pod` trait."
),
name.span(),
);
quote! {
/// Extra static check for the Pod implementation
#[doc(hidden)]
const _: () = {
if ::core::mem::size_of::<#name>() != ::core::mem::size_of::<#inner_ty>() {
::core::panic!(#error_str);
}
};
#[automatically_derived]
unsafe impl ::bytemuck::Pod for #name {}
}
});
let zeroable_impl =
(cfg!(feature = "bytemuck") && impl_flags.contains(ImplFlags::ZEROABLE)).then(|| {
quote! {
#[automatically_derived]
unsafe impl ::bytemuck::Zeroable for #name {}
}
});
let from_primitive_impl = if has_non_exhaustive {
quote! {
#[automatically_derived]
impl ::core::convert::From<#inner_ty> for #name {
#[inline]
fn from(val: #inner_ty) -> Self {
Self::from_bits_retain(val)
}
}
}
} else {
quote! {
#[automatically_derived]
impl ::core::convert::From<#inner_ty> for #name {
#[inline]
fn from(val: #inner_ty) -> Self {
Self::from_bits_truncate(val)
}
}
}
};
let doc_from_iter = format!("Create a `{name}` from a iterator of flags.");
let generated = quote! {
#repr_attr
#(#attrs)*
#[derive(#(#derived_traits,)*)]
#vis struct #name(#inner_ty)
where
#inner_ty: ::bitflag_attr::BitsPrimitive;
#[doc(hidden)]
#[allow(clippy::unused_unit)]
const _: () = {
{
// Original enum
// This is a hack to make LSP coloring to still sees the original enum variant as a Enum variant token.
#orig_enum
}
()
};
#[allow(non_upper_case_globals)]
impl #name {
#(#flags)*
}
#[allow(non_upper_case_globals)]
impl #name {
/// Return the underlying bits value.
#[inline]
pub const fn bits(&self) -> #inner_ty {
self.0
}
/// Converts from a `bits` value. Returning [`None`] is any unknown bits are set.
#[inline]
pub const fn from_bits(bits: #inner_ty) -> ::core::option::Option<Self> {
let truncated = Self::from_bits_truncate(bits).0;
if truncated == bits {
::core::option::Option::Some(Self(bits))
} else {
::core::option::Option::None
}
}
/// Convert from `bits` value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: #inner_ty) -> Self {
Self(bits & Self::all().0)
}
/// Convert from `bits` value exactly.
#[inline]
pub const fn from_bits_retain(bits: #inner_ty) -> Self {
Self(bits)
}
/// Convert from a flag `name`.
#[inline]
pub fn from_flag_name(name: &str) -> ::core::option::Option<Self> {
match name {
#(
#(#all_attrs)*
#all_flags_names => ::core::option::Option::Some(#all_flags),
)*
_ => ::core::option::Option::None
}
}
/// Construct a flags value with all bits unset.
#[inline]
pub const fn empty() -> Self {
Self(0)
}
/// Returns `true` if the flags value has all bits unset.
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == 0
}
/// Returns a flags value 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 flags value 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 flags value with all known flags set.
///
/// This will only set the flags specified as associated constant and the defined
/// extra valid bits.
#[inline]
pub const fn all() -> Self {
let mut all = 0;
#(
#(#all_attrs)*{
all |= #all_flags.0;
}
)*
#reserved_bits
Self(all)
}
/// Returns `true` if the flags value contais all known flags.
#[inline]
pub const fn is_all(&self) -> bool {
Self::all().0 | self.0 == self.0
}
/// Construct a flags value with all known named flags set.
///
/// This will only set the flags specified as associated constant **without** the
/// defined extra valid bits.
#[inline]
pub const fn all_named() -> Self {
let mut all = 0;
#(
#(#all_attrs)*{
all |= #all_flags.0;
}
)*
Self(all)
}
/// Returns `true` if the flags value contais all known named flags.
#[inline]
pub const fn is_all_named(&self) -> bool {
Self::all_named().0 | self.0 == self.0
}
/// Returns `true` if there are any unknown bits set in the flags value.
#[inline]
pub const fn contains_unknown_bits(&self) -> bool {
Self::all().0 & self.0 != self.0
}
/// Returns `true` if there are any unnamed known bits set in the flags value.
#[inline]
pub const fn contains_unnamed_bits(&self) -> bool {
Self::all_named().0 & self.0 != self.0
}
/// Returns a flags value with unknown bits removed from the original flags value.
#[inline]
pub const fn truncated(&self) -> Self {
Self(self.0 & Self::all().0)
}
/// Removes unknown bits from the flags value.
#[inline]
pub #const_mut fn truncate(&mut self) {
*self = Self::from_bits_truncate(self.0);
}
/// Returns `true` if this flags value 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 flags value 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 flags value.
///
/// 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 flags value with `other`.
#[inline]
#[doc(alias = "intersection")]
pub const fn and(self, other: Self) -> Self {
Self(self.0 & other.0)
}
/// Returns the bitwise OR of the flags value 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 flags value 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 flags value with `other`.
#[inline]
#[doc(alias = "and")]
pub const fn intersection(self, other: Self) -> Self {
self.and(other)
}
/// Returns the union from this flags value with `other`.
#[inline]
#[doc(alias = "or")]
pub const fn union(self, other: Self) -> Self {
self.or(other)
}
/// Returns the difference from this flags value with `other`.
///
/// In other words, returns the intersection of this flags value with the negation of `other`.
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
pub const fn difference(self, other: Self) -> Self {
self.and(other.not())
}
/// Returns the symmetric difference from this flags value with `other`.
#[inline]
#[doc(alias = "xor")]
pub const fn symmetric_difference(self, other: Self) -> Self {
self.xor(other)
}
/// Returns the complement of the flags 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().truncated()
}
/// Set the flags in `other` in the flags value.
#[inline]
#[doc(alias = "insert")]
pub #const_mut fn set(&mut self, other: Self) {
self.0 = self.or(other).0
}
/// Unset the flags bits in `other` in the flags 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 flags value.
#[inline]
pub #const_mut fn toggle(&mut self, other: Self) {
self.0 = self.xor(other).0
}
/// Resets the flags value to a empty state.
#[inline]
pub #const_mut fn clear(&mut self) {
self.0 = 0
}
}
#[automatically_derived]
impl ::core::ops::Not for #name {
type Output = Self;
#[inline]
fn not(self) -> Self::Output {
self.complement()
}
}
#[automatically_derived]
impl ::core::ops::BitAnd for #name {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self::Output {
self.and(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitOr for #name {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self::Output {
self.or(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitXor for #name {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self::Output {
self.xor(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitAndAssign for #name {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.and(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitOrAssign for #name {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.or(rhs)
}
}
#[automatically_derived]
impl ::core::ops::BitXorAssign for #name {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.xor(rhs)
}
}
#[automatically_derived]
impl ::core::ops::Sub for #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 #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)
}
}
#from_primitive_impl
#[automatically_derived]
impl ::core::convert::From<#name> for #inner_ty {
#[inline]
fn from(val: #name) -> Self {
val.0
}
}
#[automatically_derived]
impl ::core::fmt::Binary for #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 #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 #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 #name {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Octal::fmt(&self.0, f)
}
}
#[automatically_derived]
impl ::core::str::FromStr for #name {
type Err = ::bitflag_attr::parser::ParseError;
#[inline]
fn from_str(input: &str) -> ::core::result::Result<Self, Self::Err> {
::bitflag_attr::parser::from_text(input)
}
}
#debug_impl
#default_impl
#[automatically_derived]
impl ::bitflag_attr::Flags for #name {
const NAMED_FLAGS: &'static [(&'static str, #name)] = &[#(
#(#all_attrs)*
(#all_flags_names , #all_flags) ,
)*];
const RESERVED_BITS: #inner_ty = #reserved_bits_value;
type Bits = #inner_ty;
#[inline]
fn bits(&self) -> Self::Bits {
self.0
}
#[inline]
fn from_bits_retain(bits: Self::Bits) -> Self {
Self(bits)
}
}
impl #name {
const NAMED_FLAGS: &'static [(&'static str, #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) -> ::bitflag_attr::iter::Iter<Self> {
::bitflag_attr::iter::Iter::__private_const_new(Self::NAMED_FLAGS, *self, *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) -> ::bitflag_attr::iter::IterNames<Self> {
::bitflag_attr::iter::IterNames::__private_const_new(Self::NAMED_FLAGS, *self, *self)
}
}
#[automatically_derived]
impl ::core::iter::Extend<#name> for #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<#name> for #name {
#[doc = #doc_from_iter]
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 #name {
type Item = Self;
type IntoIter = ::bitflag_attr::iter::Iter<Self>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[automatically_derived]
impl ::core::iter::IntoIterator for &#name {
type Item = #name;
type IntoIter = ::bitflag_attr::iter::Iter<#name>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#serialize_impl
#deserialize_impl
#arbitrary_impl
#pod_impl
#zeroable_impl
};
tokens.append_all(generated);
}
}
pub struct Args {
ty: Path,
}
impl Parse for Args {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let ty: Path = input.parse().map_err(|err| {
Error::new(err.span(), "unexpected token: expected a `{integer}` type")
})?;
if !cfg!(feature = "custom-types") {
let path_s = ty.to_token_stream().to_string().replace(" ", "");
if !VALID_TYPES.contains(&path_s.as_str()) {
return Err(Error::new_spanned(ty, "type must be a `{integer}` type"));
}
}
Ok(Args { ty })
}
}
struct ExtraValidBits(Expr);
impl ExtraValidBits {
fn from_meta(meta: &Meta) -> syn::Result<Self> {
match meta {
Meta::NameValue(m) => {
if !m.path.is_ident("reserved_bits") {
return Err(Error::new(
m.span(),
"not a valid `reserved_bits` attribute",
));
}
Ok(Self(m.value.clone()))
}
_ => Err(Error::new(
meta.span(),
"reserved_bits must follow the syntax `reserved_bits = <expr>`",
)),
}
}
}
impl Parse for ExtraValidBits {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let meta: MetaNameValue = input.parse()?;
if !meta.path.is_ident("reserved_bits") {
return Err(Error::new(meta.span(), "not a `reserved_bits` attribute"));
}
Ok(Self(meta.value))
}
}
struct ReprAttr {
path: Path,
_paren_token: Paren,
kinds: Punctuated<ReprKind, syn::Token![,]>,
}
impl ReprAttr {
pub fn kinds(&self) -> (Option<ReprKind>, Option<ReprKind>) {
(self.kinds.get(0).cloned(), self.kinds.get(1).cloned())
}
}
impl Parse for ReprAttr {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let path: Path = input.parse()?;
let content;
let _paren_token = syn::parenthesized!(content in input);
if !path.is_ident("repr") {
return Err(Error::new(path.span(), "not a `#[repr]` attribute"));
}
let mut kinds = Punctuated::new();
while !content.is_empty() {
let first: ReprKind = content.parse()?;
kinds.push_value(first);
if content.is_empty() {
break;
}
let punct = content.parse()?;
kinds.push_punct(punct);
}
Ok(Self {
path,
_paren_token,
kinds,
})
}
}
impl ToTokens for ReprAttr {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self { path, kinds, .. } = self;
tokens.append_all(quote! {#[#path(#kinds)]});
}
}
/// Supported repr
#[derive(Clone)]
enum ReprKind {
C(Path),
Rust(Path),
Transparent(Path),
Integer(Path),
Packed(Path, Option<LitInt>),
Align(Path, LitInt),
}
impl Parse for ReprKind {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let meta: Meta = input.parse()?;
match meta {
Meta::Path(path) => {
let text = path
.get_ident()
.map(|p| p.to_string())
.unwrap_or("".to_string());
match text.as_str() {
"C" => Ok(Self::C(path)),
"Rust" => Ok(Self::Rust(path)),
"transparent" => Ok(Self::Transparent(path)),
"packed" => Ok(Self::Packed(path, None)),
x if VALID_REPR_INT.contains(&x) => Ok(Self::Integer(path)),
_ => Err(Error::new(path.span(), "invalid `repr` kind")),
}
}
Meta::List(list) => {
let text = list
.path
.get_ident()
.map(|p| p.to_string())
.unwrap_or("".to_string());
match text.as_str() {
"packed" => {
let lit = syn::parse2(list.tokens)?;
Ok(Self::Packed(list.path, Some(lit)))
}
"align" => {
let lit = syn::parse2(list.tokens)?;
Ok(Self::Align(list.path, lit))
}
_ => Err(Error::new(list.span(), "invalid `repr` kind")),
}
}
_ => Err(Error::new(meta.span(), "invalid `repr` kind")),
}
}
}
impl ToTokens for ReprKind {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
ReprKind::C(path)
| ReprKind::Rust(path)
| ReprKind::Transparent(path)
| ReprKind::Integer(path)
| ReprKind::Packed(path, None) => tokens.append_all(quote!(#path)),
ReprKind::Packed(path, Some(lit_int)) | ReprKind::Align(path, lit_int) => {
tokens.append_all(quote!(#path(#lit_int)))
}
}
}
}
const VALID_REPR_INT: &[&str] = &[
"i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "i128", "u128",
];
/// Flags of found derives that is handled specially by the macro.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct ImplFlags(u8);
impl ImplFlags {
pub const DEBUG: Self = Self(1);
pub const DEFAULT: Self = Self(1 << 1);
pub const SERIALIZE: Self = Self(1 << 2);
pub const DESERIALIZE: Self = Self(1 << 3);
pub const ARBITRARY: Self = Self(1 << 4);
pub const ZEROABLE: Self = Self(1 << 5);
pub const POD: Self = Self(1 << 6);
pub const fn empty() -> Self {
Self(0)
}
pub const fn contains(&self, other: Self) -> bool {
(self.0 & other.0) == other.0
}
}
impl core::ops::Not for ImplFlags {
type Output = Self;
#[inline]
fn not(self) -> Self::Output {
Self(!self.0)
}
}
impl core::ops::BitAnd for ImplFlags {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self::Output {
Self(self.0 & rhs.0)
}
}
impl core::ops::BitOr for ImplFlags {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self::Output {
Self(self.0 | rhs.0)
}
}
impl core::ops::BitXor for ImplFlags {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self::Output {
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitAndAssign for ImplFlags {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = Self(self.0 & rhs.0)
}
}
impl core::ops::BitOrAssign for ImplFlags {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = Self(self.0 | rhs.0)
}
}
impl core::ops::BitXorAssign for ImplFlags {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = Self(self.0 ^ rhs.0)
}
}
/// Recursively check if a expression can be simplified to a simple wrap of `Self(<expr>)`.
///
/// Logic behind this:
/// A literal and a path where it is not fancy and is not one of the variants names are always able to be simplified.
///
/// A unary expression can be simplified if it's underlying expression is also able to be simplified.
///
/// A binary expression can be simplified if both expression that compose it also are able to be simplified.
///
/// A parenthesized expression can be simplified if it's underlying expression is also able to be simplified.
///
/// A "as" cast can be simplified if it's underlying expression is also able to be simplified.
///
/// To-Do:
/// In theory, something like `FlagTypeName::FlagKind.bits()` could be simplified, but demands a more complicated analysis of method call expression
fn can_simplify(expr: &syn::Expr, variants: &[Ident]) -> bool {
match expr {
syn::Expr::Lit(_) => true,
syn::Expr::Path(expr_path) if is_simple_path(expr_path, variants) => true,
syn::Expr::Unary(expr_unary) => can_simplify(&expr_unary.expr, variants),
syn::Expr::Binary(expr_binary) => {
can_simplify(&expr_binary.left, variants) && can_simplify(&expr_binary.right, variants)
}
syn::Expr::Paren(expr_paren) => can_simplify(&expr_paren.expr, variants),
syn::Expr::Cast(expr_cast) => can_simplify(&expr_cast.expr, variants),
_ => false,
}
}
fn is_simple_path(expr: &syn::ExprPath, variants: &[Ident]) -> bool {
if expr.qself.is_some() {
return false;
}
// simplest path
if let Some(ident) = expr.path.get_ident() {
// if the ident is in variants, it is not a simple path
if !variants.contains(ident) {
return true;
}
}
// compound path
// All real usages I had it could be simplified, after simplification, even cases where type
// don't match, the resulting native error is very good.
if expr.path.segments.iter().count() >= 2 {
return true;
}
false
}
static VALID_TYPES: &[&str] = &[
"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",
"ffi::c_char",
"ffi::c_schar",
"ffi::c_uchar",
"ffi::c_short",
"ffi::c_ushort",
"ffi::c_int",
"ffi::c_uint",
"ffi::c_long",
"ffi::c_ulong",
"ffi::c_longlong",
"ffi::c_ulonglong",
"core::ffi::c_char",
"core::ffi::c_schar",
"core::ffi::c_uchar",
"core::ffi::c_short",
"core::ffi::c_ushort",
"core::ffi::c_int",
"core::ffi::c_uint",
"core::ffi::c_long",
"core::ffi::c_ulong",
"core::ffi::c_longlong",
"core::ffi::c_ulonglong",
"::core::ffi::c_char",
"::core::ffi::c_schar",
"::core::ffi::c_uchar",
"::core::ffi::c_short",
"::core::ffi::c_ushort",
"::core::ffi::c_int",
"::core::ffi::c_uint",
"::core::ffi::c_long",
"::core::ffi::c_ulong",
"::core::ffi::c_longlong",
"::core::ffi::c_ulonglong",
"libc::c_char",
"libc::c_schar",
"libc::c_uchar",
"libc::c_short",
"libc::c_ushort",
"libc::c_int",
"libc::c_uint",
"libc::c_long",
"libc::c_ulong",
"libc::c_longlong",
"libc::c_ulonglong",
"::libc::c_char",
"::libc::c_schar",
"::libc::c_uchar",
"::libc::c_short",
"::libc::c_ushort",
"::libc::c_int",
"::libc::c_uint",
"::libc::c_long",
"::libc::c_ulong",
"::libc::c_longlong",
"::libc::c_ulonglong",
"blkcnt_t",
"blksize_t",
"clock_t",
"clockid_t",
"dev_t",
"fsblkcnt_t",
"fsfilcnt_t",
"gid_t",
"id_t",
"ino_t",
"key_t",
"mode_t",
"nlink_t",
"off_t",
"pid_t",
"size_t",
"ssize_t",
"suseconds_t",
"time_t",
"uid_t",
"libc::blkcnt_t",
"libc::blksize_t",
"libc::clock_t",
"libc::clockid_t",
"libc::dev_t",
"libc::fsblkcnt_t",
"libc::fsfilcnt_t",
"libc::gid_t",
"libc::id_t",
"libc::ino_t",
"libc::key_t",
"libc::mode_t",
"libc::nlink_t",
"libc::off_t",
"libc::pid_t",
"libc::size_t",
"libc::ssize_t",
"libc::suseconds_t",
"libc::time_t",
"libc::uid_t",
"::libc::blkcnt_t",
"::libc::blksize_t",
"::libc::clock_t",
"::libc::clockid_t",
"::libc::dev_t",
"::libc::fsblkcnt_t",
"::libc::fsfilcnt_t",
"::libc::gid_t",
"::libc::id_t",
"::libc::ino_t",
"::libc::key_t",
"::libc::mode_t",
"::libc::nlink_t",
"::libc::off_t",
"::libc::pid_t",
"::libc::size_t",
"::libc::ssize_t",
"::libc::suseconds_t",
"::libc::time_t",
"::libc::uid_t",
];