/
enumeration.rs
1540 lines (1395 loc) · 53.7 KB
/
enumeration.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::io::Write;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
use crate::bindgen::dependencies::Dependencies;
use crate::bindgen::ir::{
AnnotationSet, AnnotationValue, Cfg, ConditionWrite, Documentation, Field, GenericParams,
GenericPath, Item, ItemContainer, Literal, Path, Repr, ReprStyle, Struct, ToCondition, Type,
};
use crate::bindgen::library::Library;
use crate::bindgen::mangle;
use crate::bindgen::monomorph::Monomorphs;
use crate::bindgen::rename::{IdentifierType, RenameRule};
use crate::bindgen::reserved;
use crate::bindgen::writer::{ListType, Source, SourceWriter};
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum VariantBody {
Empty(AnnotationSet),
Body {
/// The variant field / export name.
name: String,
/// The struct with all the items.
body: Struct,
/// A separate named struct is not created for this variant,
/// an unnamed struct is inlined at the point of use instead.
/// This is a reasonable thing to do only for tuple variants with a single field.
inline: bool,
/// Generated cast methods return the variant's only field instead of the variant itself.
/// For backward compatibility casts are inlined in a slightly
/// larger set of cases than whole variants.
inline_casts: bool,
},
}
impl VariantBody {
fn empty() -> Self {
Self::Empty(AnnotationSet::new())
}
fn annotations(&self) -> &AnnotationSet {
match *self {
Self::Empty(ref anno) => anno,
Self::Body { ref body, .. } => &body.annotations,
}
}
fn is_empty(&self) -> bool {
match *self {
Self::Empty(..) => true,
Self::Body { .. } => false,
}
}
fn specialize(
&self,
generic_values: &[Type],
mappings: &[(&Path, &Type)],
config: &Config,
) -> Self {
match *self {
Self::Empty(ref annos) => Self::Empty(annos.clone()),
Self::Body {
ref name,
ref body,
inline,
inline_casts,
} => Self::Body {
name: name.clone(),
body: body.specialize(generic_values, mappings, config),
inline,
inline_casts,
},
}
}
}
#[derive(Debug, Clone)]
pub struct EnumVariant {
pub name: String,
pub export_name: String,
pub discriminant: Option<Literal>,
pub body: VariantBody,
pub cfg: Option<Cfg>,
pub documentation: Documentation,
}
impl EnumVariant {
fn load(
inline_tag_field: bool,
variant: &syn::Variant,
generic_params: GenericParams,
mod_cfg: Option<&Cfg>,
self_path: &Path,
enum_annotations: &AnnotationSet,
config: &Config,
) -> Result<Self, String> {
let discriminant = match variant.discriminant {
Some((_, ref expr)) => Some(Literal::load(expr)?),
None => None,
};
fn parse_fields(
inline_tag_field: bool,
fields: &syn::punctuated::Punctuated<syn::Field, syn::token::Comma>,
self_path: &Path,
inline_name: Option<&str>,
) -> Result<Vec<Field>, String> {
let mut res = Vec::new();
if inline_tag_field {
res.push(Field::from_name_and_type(
inline_name.map_or_else(|| "tag".to_string(), |name| format!("{}_tag", name)),
Type::Path(GenericPath::new(Path::new("Tag"), vec![])),
));
}
for (i, field) in fields.iter().enumerate() {
if let Some(mut ty) = Type::load(&field.ty)? {
ty.replace_self_with(self_path);
res.push(Field {
name: inline_name.map_or_else(
|| match field.ident {
Some(ref ident) => ident.unraw().to_string(),
None => i.to_string(),
},
|name| name.to_string(),
),
ty,
cfg: Cfg::load(&field.attrs),
annotations: AnnotationSet::load(&field.attrs)?,
documentation: Documentation::load(&field.attrs),
});
}
}
Ok(res)
}
let variant_cfg = Cfg::append(mod_cfg, Cfg::load(&variant.attrs));
let mut annotations = AnnotationSet::load(&variant.attrs)?;
if let Some(b) = enum_annotations.bool("derive-ostream") {
annotations.add_default("derive-ostream", AnnotationValue::Bool(b));
}
let body = match variant.fields {
syn::Fields::Unit => VariantBody::Empty(annotations),
syn::Fields::Named(ref fields) => {
let path = Path::new(format!("{}_Body", variant.ident));
let name = RenameRule::SnakeCase
.apply(
&variant.ident.unraw().to_string(),
IdentifierType::StructMember,
)
.into_owned();
VariantBody::Body {
body: Struct::new(
path,
generic_params,
parse_fields(inline_tag_field, &fields.named, self_path, None)?,
inline_tag_field,
true,
None,
false,
None,
annotations,
Documentation::none(),
),
name,
inline: false,
inline_casts: false,
}
}
syn::Fields::Unnamed(ref fields) => {
let path = Path::new(format!("{}_Body", variant.ident));
let name = RenameRule::SnakeCase
.apply(
&variant.ident.unraw().to_string(),
IdentifierType::StructMember,
)
.into_owned();
let inline_casts = fields.unnamed.len() == 1;
// In C++ types with destructors cannot be put into unnamed structs like the
// inlining requires, and it's hard to detect such types.
// Besides that for C++ we generate casts/getters that can be used instead of
// direct field accesses and also have a benefit of being checked.
// As a result we don't currently inline variant definitions in C++ mode at all.
let inline = inline_casts && config.language != Language::Cxx;
let inline_name = if inline { Some(&*name) } else { None };
VariantBody::Body {
body: Struct::new(
path,
generic_params,
parse_fields(inline_tag_field, &fields.unnamed, self_path, inline_name)?,
inline_tag_field,
true,
None,
false,
None,
annotations,
Documentation::none(),
),
name,
inline,
inline_casts,
}
}
};
Ok(EnumVariant::new(
variant.ident.unraw().to_string(),
discriminant,
body,
variant_cfg,
Documentation::load(&variant.attrs),
))
}
pub fn new(
name: String,
discriminant: Option<Literal>,
body: VariantBody,
cfg: Option<Cfg>,
documentation: Documentation,
) -> Self {
let export_name = name.clone();
Self {
name,
export_name,
discriminant,
body,
cfg,
documentation,
}
}
fn simplify_standard_types(&mut self, config: &Config) {
if let VariantBody::Body { ref mut body, .. } = self.body {
body.simplify_standard_types(config);
}
}
fn add_dependencies(&self, library: &Library, out: &mut Dependencies) {
if let VariantBody::Body { ref body, .. } = self.body {
body.add_dependencies(library, out);
}
}
fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
if let VariantBody::Body { ref mut body, .. } = self.body {
body.resolve_declaration_types(resolver);
}
}
fn specialize(
&self,
generic_values: &[Type],
mappings: &[(&Path, &Type)],
config: &Config,
) -> Self {
Self::new(
mangle::mangle_name(&self.name, generic_values, &config.export.mangle),
self.discriminant.clone(),
self.body.specialize(generic_values, mappings, config),
self.cfg.clone(),
self.documentation.clone(),
)
}
fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) {
if let VariantBody::Body { ref body, .. } = self.body {
body.add_monomorphs(library, out);
}
}
fn mangle_paths(&mut self, monomorphs: &Monomorphs) {
if let VariantBody::Body { ref mut body, .. } = self.body {
body.mangle_paths(monomorphs);
}
}
}
impl Source for EnumVariant {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
let condition = self.cfg.to_condition(config);
// Cython doesn't support conditional enum variants.
if config.language != Language::Cython {
condition.write_before(config, out);
}
self.documentation.write(config, out);
write!(out, "{}", self.export_name);
if let Some(discriminant) = &self.discriminant {
if config.language == Language::Cython {
// For extern Cython declarations the enumerator value is ignored,
// but still useful as documentation, so we write it as a comment.
out.write(" #")
}
out.write(" = ");
discriminant.write(config, out);
}
out.write(",");
if config.language != Language::Cython {
condition.write_after(config, out);
}
}
}
#[derive(Debug, Clone)]
pub struct Enum {
pub path: Path,
pub export_name: String,
pub generic_params: GenericParams,
pub repr: Repr,
pub variants: Vec<EnumVariant>,
pub tag: Option<String>,
pub cfg: Option<Cfg>,
pub annotations: AnnotationSet,
pub documentation: Documentation,
}
impl Enum {
/// Name of the generated tag enum.
fn tag_name(&self) -> &str {
self.tag.as_deref().unwrap_or_else(|| self.export_name())
}
/// Enum with data turns into a union of structs with each struct having its own tag field.
fn inline_tag_field(repr: &Repr) -> bool {
repr.style != ReprStyle::C
}
pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) {
if self.generic_params.len() > 0 {
return;
}
for v in &self.variants {
v.add_monomorphs(library, out);
}
}
fn can_derive_eq(&self) -> bool {
if self.tag.is_none() {
return false;
}
self.variants.iter().all(|variant| match variant.body {
VariantBody::Empty(..) => true,
VariantBody::Body { ref body, .. } => body.can_derive_eq(),
})
}
pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) {
for variant in &mut self.variants {
variant.mangle_paths(monomorphs);
}
}
pub fn load(
item: &syn::ItemEnum,
mod_cfg: Option<&Cfg>,
config: &Config,
) -> Result<Enum, String> {
let repr = Repr::load(&item.attrs)?;
if repr.style == ReprStyle::Rust && repr.ty.is_none() {
return Err("Enum is not marked with a valid #[repr(prim)] or #[repr(C)].".to_owned());
}
// TODO: Implement translation of aligned enums.
if repr.align.is_some() {
return Err("Enum is marked with #[repr(align(...))] or #[repr(packed)].".to_owned());
}
let path = Path::new(item.ident.unraw().to_string());
let generic_params = GenericParams::new(&item.generics);
let mut variants = Vec::new();
let mut has_data = false;
let annotations = AnnotationSet::load(&item.attrs)?;
for variant in item.variants.iter() {
let variant = EnumVariant::load(
Self::inline_tag_field(&repr),
variant,
generic_params.clone(),
mod_cfg,
&path,
&annotations,
config,
)?;
has_data = has_data || !variant.body.is_empty();
variants.push(variant);
}
if let Some(names) = annotations.list("enum-trailing-values") {
for name in names {
variants.push(EnumVariant::new(
name,
None,
VariantBody::empty(),
None,
Documentation::none(),
));
}
}
if config.enumeration.add_sentinel(&annotations) {
variants.push(EnumVariant::new(
"Sentinel".to_owned(),
None,
VariantBody::empty(),
None,
Documentation::simple(" Must be last for serialization purposes"),
));
}
let tag = if has_data {
Some("Tag".to_string())
} else {
None
};
Ok(Enum::new(
path,
generic_params,
repr,
variants,
tag,
Cfg::append(mod_cfg, Cfg::load(&item.attrs)),
annotations,
Documentation::load(&item.attrs),
))
}
#[allow(clippy::too_many_arguments)]
pub fn new(
path: Path,
generic_params: GenericParams,
repr: Repr,
variants: Vec<EnumVariant>,
tag: Option<String>,
cfg: Option<Cfg>,
annotations: AnnotationSet,
documentation: Documentation,
) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generic_params,
repr,
variants,
tag,
cfg,
annotations,
documentation,
}
}
}
impl Item for Enum {
fn path(&self) -> &Path {
&self.path
}
fn export_name(&self) -> &str {
&self.export_name
}
fn cfg(&self) -> Option<&Cfg> {
self.cfg.as_ref()
}
fn annotations(&self) -> &AnnotationSet {
&self.annotations
}
fn annotations_mut(&mut self) -> &mut AnnotationSet {
&mut self.annotations
}
fn container(&self) -> ItemContainer {
ItemContainer::Enum(self.clone())
}
fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) {
if self.tag.is_some() {
if self.repr.style == ReprStyle::C {
resolver.add_struct(&self.path);
} else {
resolver.add_union(&self.path);
}
} else if self.repr.style == ReprStyle::C {
resolver.add_enum(&self.path);
} else {
// This is important to handle conflicting names with opaque items.
resolver.add_none(&self.path);
}
}
fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
for &mut ref mut var in &mut self.variants {
var.resolve_declaration_types(resolver);
}
}
fn rename_for_config(&mut self, config: &Config) {
config.export.rename(&mut self.export_name);
if config.language != Language::Cxx && self.tag.is_some() {
// it makes sense to always prefix Tag with type name in C
let new_tag = format!("{}_Tag", self.export_name);
if self.repr.style == ReprStyle::Rust {
for variant in &mut self.variants {
if let VariantBody::Body { ref mut body, .. } = variant.body {
let path = Path::new(new_tag.clone());
let generic_path = GenericPath::new(path, vec![]);
body.fields[0].ty = Type::Path(generic_path);
}
}
}
self.tag = Some(new_tag);
}
for variant in &mut self.variants {
reserved::escape(&mut variant.export_name);
if let Some(discriminant) = &mut variant.discriminant {
discriminant.rename_for_config(config);
}
if let VariantBody::Body {
ref mut name,
ref mut body,
..
} = variant.body
{
body.rename_for_config(config);
reserved::escape(name);
}
}
if config.enumeration.prefix_with_name
|| self.annotations.bool("prefix-with-name").unwrap_or(false)
{
let separator = if config.export.mangle.remove_underscores {
""
} else {
"_"
};
for variant in &mut self.variants {
variant.export_name =
format!("{}{}{}", self.export_name, separator, variant.export_name);
if let VariantBody::Body { ref mut body, .. } = variant.body {
body.export_name =
format!("{}{}{}", self.export_name, separator, body.export_name());
}
}
}
let rules = self
.annotations
.parse_atom::<RenameRule>("rename-all")
.unwrap_or(config.enumeration.rename_variants);
if let Some(r) = rules.not_none() {
self.variants = self
.variants
.iter()
.map(|variant| {
EnumVariant::new(
r.apply(
&variant.export_name,
IdentifierType::EnumVariant {
prefix: &self.export_name,
},
)
.into_owned(),
variant.discriminant.clone(),
match variant.body {
VariantBody::Empty(..) => variant.body.clone(),
VariantBody::Body {
ref name,
ref body,
inline,
inline_casts,
} => VariantBody::Body {
name: r.apply(name, IdentifierType::StructMember).into_owned(),
body: body.clone(),
inline,
inline_casts,
},
},
variant.cfg.clone(),
variant.documentation.clone(),
)
})
.collect();
}
}
fn instantiate_monomorph(
&self,
generic_values: &[Type],
library: &Library,
out: &mut Monomorphs,
) {
assert!(
self.generic_params.len() > 0,
"{} is not generic",
self.path.name()
);
assert!(
self.generic_params.len() == generic_values.len(),
"{} has {} params but is being instantiated with {} values",
self.path.name(),
self.generic_params.len(),
generic_values.len(),
);
let mappings = self
.generic_params
.iter()
.zip(generic_values.iter())
.collect::<Vec<_>>();
for variant in &self.variants {
if let VariantBody::Body { ref body, .. } = variant.body {
body.instantiate_monomorph(generic_values, library, out);
}
}
let mangled_path = mangle::mangle_path(
&self.path,
generic_values,
&library.get_config().export.mangle,
);
let monomorph = Enum::new(
mangled_path,
GenericParams::default(),
self.repr,
self.variants
.iter()
.map(|v| v.specialize(generic_values, &mappings, library.get_config()))
.collect(),
self.tag.clone(),
self.cfg.clone(),
self.annotations.clone(),
self.documentation.clone(),
);
out.insert_enum(library, self, monomorph, generic_values.to_owned());
}
fn add_dependencies(&self, library: &Library, out: &mut Dependencies) {
for variant in &self.variants {
variant.add_dependencies(library, out);
}
}
}
impl Source for Enum {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
let size = self.repr.ty.map(|ty| ty.to_primitive().to_repr_c(config));
let has_data = self.tag.is_some();
let inline_tag_field = Self::inline_tag_field(&self.repr);
let tag_name = self.tag_name();
let condition = self.cfg.to_condition(config);
condition.write_before(config, out);
self.documentation.write(config, out);
self.generic_params.write(config, out);
// If the enum has data, we need to emit a struct or union for the data
// and enum for the tag. C++ supports nested type definitions, so we open
// the struct or union here and define the tag enum inside it (*).
if has_data && config.language == Language::Cxx {
self.open_struct_or_union(config, out, inline_tag_field);
}
// Emit the tag enum and everything related to it.
self.write_tag_enum(config, out, size, has_data, tag_name);
// If the enum has data, we need to emit structs for the variants and gather them together.
if has_data {
self.write_variant_defs(config, out);
out.new_line();
out.new_line();
// Open the struct or union for the data (**), gathering all the variants with data
// together, unless it's C++, then we have already opened that struct/union at (*) and
// are currently inside it.
if config.language != Language::Cxx {
self.open_struct_or_union(config, out, inline_tag_field);
}
// Emit tag field that is separate from all variants.
self.write_tag_field(config, out, size, inline_tag_field, tag_name);
out.new_line();
// Open union of all variants with data, only in the non-inline tag scenario.
// Cython extern declarations don't manage layouts, layouts are defined entierly by the
// corresponding C code. So we can inline the unnamed union into the struct and get the
// same observable result. Moreother we have to do it because Cython doesn't support
// unnamed unions.
if !inline_tag_field && config.language != Language::Cython {
out.write("union");
out.open_brace();
}
// Emit fields for all variants with data.
self.write_variant_fields(config, out, inline_tag_field);
// Close union of all variants with data, only in the non-inline tag scenario.
// See the comment about Cython on `open_brace`.
if !inline_tag_field && config.language != Language::Cython {
out.close_brace(true);
}
// Emit convenience methods for the struct or enum for the data.
self.write_derived_functions_data(config, out, tag_name);
// Emit the post_body section, if relevant.
if let Some(body) = config.export.post_body(&self.path) {
out.new_line();
out.write_raw_block(body);
}
// Close the struct or union opened either at (*) or at (**).
if config.language == Language::C && config.style.generate_typedef() {
out.close_brace(false);
write!(out, " {};", self.export_name);
} else {
out.close_brace(true);
}
}
condition.write_after(config, out);
}
}
impl Enum {
/// Emit the tag enum and convenience methods for it.
/// For enums with data this is only a part of the output,
/// but for enums without data it's the whole output (modulo doc comments etc.).
fn write_tag_enum<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
size: Option<&str>,
has_data: bool,
tag_name: &str,
) {
// Open the tag enum.
match config.language {
Language::C => {
if let Some(prim) = size {
// If we need to specify size, then we have no choice but to create a typedef,
// so `config.style` is not respected.
write!(out, "enum {}", tag_name);
if config.cpp_compatible_c() {
out.new_line();
out.write("#ifdef __cplusplus");
out.new_line();
write!(out, " : {}", prim);
out.new_line();
out.write("#endif // __cplusplus");
out.new_line();
}
} else {
if config.style.generate_typedef() {
out.write("typedef ");
}
out.write("enum");
if config.style.generate_tag() {
write!(out, " {}", tag_name);
}
}
}
Language::Cxx => {
if config.enumeration.enum_class(&self.annotations) {
out.write("enum class");
} else {
out.write("enum");
}
if self.annotations.must_use(config) {
if let Some(ref anno) = config.enumeration.must_use {
write!(out, " {}", anno)
}
}
write!(out, " {}", tag_name);
if let Some(prim) = size {
write!(out, " : {}", prim);
}
}
Language::Cython => {
if size.is_some() {
// If we need to specify size, then we have no choice but to create a typedef,
// so `config.style` is not respected.
write!(out, "cdef enum");
} else {
write!(out, "{}enum {}", config.style.cython_def(), tag_name);
}
}
}
out.open_brace();
// Emit enumerators for the tag enum.
for (i, variant) in self.variants.iter().enumerate() {
if i != 0 {
out.new_line()
}
variant.write(config, out);
}
// Close the tag enum.
if config.language == Language::C && size.is_none() && config.style.generate_typedef() {
out.close_brace(false);
write!(out, " {};", tag_name);
} else {
out.close_brace(true);
}
// Emit typedef specifying the tag enum's size if necessary.
// In C++ enums can "inherit" from numeric types (`enum E: uint8_t { ... }`),
// but in C `typedef uint8_t E` is the only way to give a fixed size to `E`.
if let Some(prim) = size {
if config.cpp_compatible_c() {
out.new_line_if_not_start();
out.write("#ifndef __cplusplus");
}
if config.language != Language::Cxx {
out.new_line();
write!(out, "{} {} {};", config.language.typedef(), prim, tag_name);
}
if config.cpp_compatible_c() {
out.new_line_if_not_start();
out.write("#endif // __cplusplus");
}
}
// Emit convenience methods for the tag enum.
self.write_derived_functions_enum(config, out, has_data, tag_name);
}
/// The code here mirrors the beginning of `Struct::write` and `Union::write`.
fn open_struct_or_union<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
inline_tag_field: bool,
) {
match config.language {
Language::C if config.style.generate_typedef() => out.write("typedef "),
Language::C | Language::Cxx => {}
Language::Cython => out.write(config.style.cython_def()),
}
out.write(if inline_tag_field { "union" } else { "struct" });
if self.annotations.must_use(config) {
if let Some(ref anno) = config.structure.must_use {
write!(out, " {}", anno);
}
}
if config.language != Language::C || config.style.generate_tag() {
write!(out, " {}", self.export_name());
}
out.open_brace();
// Emit the pre_body section, if relevant.
if let Some(body) = config.export.pre_body(&self.path) {
out.write_raw_block(body);
out.new_line();
}
}
/// Emit struct definitions for variants having data.
fn write_variant_defs<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
for variant in &self.variants {
if let VariantBody::Body {
ref body,
inline: false,
..
} = variant.body
{
out.new_line();
out.new_line();
let condition = variant.cfg.to_condition(config);
// Cython doesn't support conditional enum variants.
if config.language != Language::Cython {
condition.write_before(config, out);
}
body.write(config, out);
if config.language != Language::Cython {
condition.write_after(config, out);
}
}
}
}
/// Emit tag field that is separate from all variants.
/// For non-inline tag scenario this is *the* tag field, and it does not exist in the variants.
/// For the inline tag scenario this is just a convenience and another way
/// to refer to the same tag that exist in all the variants.
fn write_tag_field<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
size: Option<&str>,
inline_tag_field: bool,
tag_name: &str,
) {
// C++ allows accessing only common initial sequence of union
// fields so we have to wrap the tag field into an anonymous struct.
let wrap_tag = inline_tag_field && config.language == Language::Cxx;
if wrap_tag {
out.write("struct");
out.open_brace();
}
if config.language == Language::C && size.is_none() && !config.style.generate_typedef() {
out.write("enum ");
}
write!(out, "{} tag;", tag_name);
if wrap_tag {
out.close_brace(true);
}
}
/// Emit fields for all variants with data.
fn write_variant_fields<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
inline_tag_field: bool,
) {
let mut first = true;
for variant in &self.variants {
if let VariantBody::Body {
name, body, inline, ..
} = &variant.body
{
if !first {
out.new_line();
}
first = false;
let condition = variant.cfg.to_condition(config);
// Cython doesn't support conditional enum variants.
if config.language != Language::Cython {
condition.write_before(config, out);
}
if *inline {
// Write definition of an inlined variant with data.
// Cython extern declarations don't manage layouts, layouts are defined entierly
// by the corresponding C code. So we can inline the unnamed struct and get the
// same observable result. Moreother we have to do it because Cython doesn't
// support unnamed structs.
// For the same reason with Cython we can omit per-variant tags (the first
// field) to avoid extra noise, the main `tag` is enough in this case.
if config.language != Language::Cython {
out.write("struct");
out.open_brace();
}
let start_field =
usize::from(inline_tag_field && config.language == Language::Cython);
out.write_vertical_source_list(&body.fields[start_field..], ListType::Cap(";"));
if config.language != Language::Cython {
out.close_brace(true);
}
} else if config.style.generate_typedef() || config.language == Language::Cython {
write!(out, "{} {};", body.export_name(), name);
} else {
write!(out, "struct {} {};", body.export_name(), name);
}
if config.language != Language::Cython {
condition.write_after(config, out);
}
}
}
}
// Emit convenience methods for enums themselves.