Debian Codegraph @

.cargo/vendor/cbindgen/src/bindgen/ir/enumeration.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use std::io::Write;
6
7 use syn::ext::IdentExt;
8
9 use crate::bindgen::config::{Config, Language};
10 use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
11 use crate::bindgen::dependencies::Dependencies;
12 use crate::bindgen::ir::{
13 AnnotationSet, AnnotationValue, Cfg, ConditionWrite, Documentation, Field, GenericArgument,
14 GenericParams, GenericPath, Item, ItemContainer, Literal, Path, Repr, ReprStyle, Struct,
15 ToCondition, Type,
16 };
17 use crate::bindgen::library::Library;
18 use crate::bindgen::mangle;
19 use crate::bindgen::monomorph::Monomorphs;
20 use crate::bindgen::rename::{IdentifierType, RenameRule};
21 use crate::bindgen::reserved;
22 use crate::bindgen::writer::{ListType, Source, SourceWriter};
23
24 #[allow(clippy::large_enum_variant)]
25 #[derive(Debug, Clone)]
26 pub enum VariantBody {
27 Empty(AnnotationSet),
28 Body {
29 /// The variant field / export name.
30 name: String,
31 /// The struct with all the items.
32 body: Struct,
33 /// A separate named struct is not created for this variant,
34 /// an unnamed struct is inlined at the point of use instead.
35 /// This is a reasonable thing to do only for tuple variants with a single field.
36 inline: bool,
37 /// Generated cast methods return the variant's only field instead of the variant itself.
38 /// For backward compatibility casts are inlined in a slightly
39 /// larger set of cases than whole variants.
40 inline_casts: bool,
41 },
42 }
43
44 impl VariantBody {
45 fn empty() -> Self {
46 Self::Empty(AnnotationSet::new())
47 }
48
49 fn annotations(&self) -> &AnnotationSet {
50 match *self {
51 Self::Empty(ref anno) => anno,
52 Self::Body { ref body, .. } => &body.annotations,
53 }
54 }
55
56 fn is_empty(&self) -> bool {
57 match *self {
58 Self::Empty(..) => true,
59 Self::Body { .. } => false,
60 }
61 }
62
63 fn specialize(
64 &self,
65 generic_values: &[GenericArgument],
66 mappings: &[(&Path, &GenericArgument)],
67 config: &Config,
68 ) -> Self {
69 match *self {
70 Self::Empty(ref annos) => Self::Empty(annos.clone()),
71 Self::Body {
72 ref name,
73 ref body,
74 inline,
75 inline_casts,
76 } => Self::Body {
77 name: name.clone(),
78 body: body.specialize(generic_values, mappings, config),
79 inline,
80 inline_casts,
81 },
82 }
83 }
84 }
85
86 #[derive(Debug, Clone)]
87 pub struct EnumVariant {
88 pub name: String,
89 pub export_name: String,
90 pub discriminant: Option<Literal>,
91 pub body: VariantBody,
92 pub cfg: Option<Cfg>,
93 pub documentation: Documentation,
94 }
95
96 impl EnumVariant {
97 fn load(
98 inline_tag_field: bool,
99 variant: &syn::Variant,
100 generic_params: GenericParams,
101 mod_cfg: Option<&Cfg>,
102 self_path: &Path,
103 enum_annotations: &AnnotationSet,
104 config: &Config,
105 ) -> Result<Self, String> {
106 let discriminant = match variant.discriminant {
107 Some((_, ref expr)) => Some(Literal::load(expr)?),
108 None => None,
109 };
110
111 fn parse_fields(
112 inline_tag_field: bool,
113 fields: &syn::punctuated::Punctuated<syn::Field, syn::token::Comma>,
114 self_path: &Path,
115 inline_name: Option<&str>,
116 ) -> Result<Vec<Field>, String> {
117 let mut res = Vec::new();
118
119 if inline_tag_field {
120 res.push(Field::from_name_and_type(
121 inline_name.map_or_else(|| "tag".to_string(), |name| format!("{}_tag", name)),
122 Type::Path(GenericPath::new(Path::new("Tag"), vec![])),
123 ));
124 }
125
126 for (i, field) in fields.iter().enumerate() {
127 if let Some(mut ty) = Type::load(&field.ty)? {
128 ty.replace_self_with(self_path);
129 res.push(Field {
130 name: inline_name.map_or_else(
131 || match field.ident {
132 Some(ref ident) => ident.unraw().to_string(),
133 None => i.to_string(),
134 },
135 |name| name.to_string(),
136 ),
137 ty,
138 cfg: Cfg::load(&field.attrs),
139 annotations: AnnotationSet::load(&field.attrs)?,
140 documentation: Documentation::load(&field.attrs),
141 });
142 }
143 }
144
145 Ok(res)
146 }
147
148 let variant_cfg = Cfg::append(mod_cfg, Cfg::load(&variant.attrs));
149 let mut annotations = AnnotationSet::load(&variant.attrs)?;
150 if let Some(b) = enum_annotations.bool("derive-ostream") {
151 annotations.add_default("derive-ostream", AnnotationValue::Bool(b));
152 }
153
154 let body_rule = enum_annotations
155 .parse_atom::<RenameRule>("rename-variant-name-fields")
156 .unwrap_or(config.enumeration.rename_variant_name_fields);
157
158 let body = match variant.fields {
159 syn::Fields::Unit => VariantBody::Empty(annotations),
160 syn::Fields::Named(ref fields) => {
161 let path = Path::new(format!("{}_Body", variant.ident));
162 let name = body_rule
163 .apply(
164 &variant.ident.unraw().to_string(),
165 IdentifierType::StructMember,
166 )
167 .into_owned();
168 VariantBody::Body {
169 body: Struct::new(
170 path,
171 generic_params,
172 parse_fields(inline_tag_field, &fields.named, self_path, None)?,
173 inline_tag_field,
174 true,
175 None,
176 false,
177 None,
178 annotations,
179 Documentation::none(),
180 ),
181 name,
182 inline: false,
183 inline_casts: false,
184 }
185 }
186 syn::Fields::Unnamed(ref fields) => {
187 let path = Path::new(format!("{}_Body", variant.ident));
188 let name = body_rule
189 .apply(
190 &variant.ident.unraw().to_string(),
191 IdentifierType::StructMember,
192 )
193 .into_owned();
194 let inline_casts = fields.unnamed.len() == 1;
195 // In C++ types with destructors cannot be put into unnamed structs like the
196 // inlining requires, and it's hard to detect such types.
197 // Besides that for C++ we generate casts/getters that can be used instead of
198 // direct field accesses and also have a benefit of being checked.
199 // As a result we don't currently inline variant definitions in C++ mode at all.
200 let inline = inline_casts && config.language != Language::Cxx;
201 let inline_name = if inline { Some(&*name) } else { None };
202 VariantBody::Body {
203 body: Struct::new(
204 path,
205 generic_params,
206 parse_fields(inline_tag_field, &fields.unnamed, self_path, inline_name)?,
207 inline_tag_field,
208 true,
209 None,
210 false,
211 None,
212 annotations,
213 Documentation::none(),
214 ),
215 name,
216 inline,
217 inline_casts,
218 }
219 }
220 };
221
222 Ok(EnumVariant::new(
223 variant.ident.unraw().to_string(),
224 discriminant,
225 body,
226 variant_cfg,
227 Documentation::load(&variant.attrs),
228 ))
229 }
230
231 pub fn new(
232 name: String,
233 discriminant: Option<Literal>,
234 body: VariantBody,
235 cfg: Option<Cfg>,
236 documentation: Documentation,
237 ) -> Self {
238 let export_name = name.clone();
239 Self {
240 name,
241 export_name,
242 discriminant,
243 body,
244 cfg,
245 documentation,
246 }
247 }
248
249 fn simplify_standard_types(&mut self, config: &Config) {
250 if let VariantBody::Body { ref mut body, .. } = self.body {
251 body.simplify_standard_types(config);
252 }
253 }
254
255 fn add_dependencies(&self, library: &Library, out: &mut Dependencies) {
256 if let VariantBody::Body { ref body, .. } = self.body {
257 body.add_dependencies(library, out);
258 }
259 }
260
261 fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
262 if let VariantBody::Body { ref mut body, .. } = self.body {
263 body.resolve_declaration_types(resolver);
264 }
265 }
266
267 fn specialize(
268 &self,
269 generic_values: &[GenericArgument],
270 mappings: &[(&Path, &GenericArgument)],
271 config: &Config,
272 ) -> Self {
273 Self::new(
274 mangle::mangle_name(&self.name, generic_values, &config.export.mangle),
275 self.discriminant.clone(),
276 self.body.specialize(generic_values, mappings, config),
277 self.cfg.clone(),
278 self.documentation.clone(),
279 )
280 }
281
282 fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) {
283 if let VariantBody::Body { ref body, .. } = self.body {
284 body.add_monomorphs(library, out);
285 }
286 }
287
288 fn mangle_paths(&mut self, monomorphs: &Monomorphs) {
289 if let VariantBody::Body { ref mut body, .. } = self.body {
290 body.mangle_paths(monomorphs);
291 }
292 }
293 }
294
295 impl Source for EnumVariant {
296 fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
297 let condition = self.cfg.to_condition(config);
298 // Cython doesn't support conditional enum variants.
299 if config.language != Language::Cython {
300 condition.write_before(config, out);
301 }
302 self.documentation.write(config, out);
303 write!(out, "{}", self.export_name);
304 if let Some(discriminant) = &self.discriminant {
305 if config.language == Language::Cython {
306 // For extern Cython declarations the enumerator value is ignored,
307 // but still useful as documentation, so we write it as a comment.
308 out.write(" #")
309 }
310 out.write(" = ");
311 discriminant.write(config, out);
312 }
313 out.write(",");
314 if config.language != Language::Cython {
315 condition.write_after(config, out);
316 }
317 }
318 }
319
320 #[derive(Debug, Clone)]
321 pub struct Enum {
322 pub path: Path,
323 pub export_name: String,
324 pub generic_params: GenericParams,
325 pub repr: Repr,
326 pub variants: Vec<EnumVariant>,
327 pub tag: Option<String>,
328 pub cfg: Option<Cfg>,
329 pub annotations: AnnotationSet,
330 pub documentation: Documentation,
331 }
332
333 impl Enum {
334 /// Name of the generated tag enum.
335 fn tag_name(&self) -> &str {
336 self.tag.as_deref().unwrap_or_else(|| self.export_name())
337 }
338
339 /// Enum with data turns into a union of structs with each struct having its own tag field.
340 fn inline_tag_field(repr: &Repr) -> bool {
341 repr.style != ReprStyle::C
342 }
343
344 pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) {
345 if self.generic_params.len() > 0 {
346 return;
347 }
348
349 for v in &self.variants {
350 v.add_monomorphs(library, out);
351 }
352 }
353
354 fn can_derive_eq(&self) -> bool {
355 if self.tag.is_none() {
356 return false;
357 }
358
359 self.variants.iter().all(|variant| match variant.body {
360 VariantBody::Empty(..) => true,
361 VariantBody::Body { ref body, .. } => body.can_derive_eq(),
362 })
363 }
364
365 pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) {
366 for variant in &mut self.variants {
367 variant.mangle_paths(monomorphs);
368 }
369 }
370
371 pub fn load(
372 item: &syn::ItemEnum,
373 mod_cfg: Option<&Cfg>,
374 config: &Config,
375 ) -> Result<Enum, String> {
376 let repr = Repr::load(&item.attrs)?;
377 if repr.style == ReprStyle::Rust && repr.ty.is_none() {
378 return Err("Enum is not marked with a valid #[repr(prim)] or #[repr(C)].".to_owned());
379 }
380 // TODO: Implement translation of aligned enums.
381 if repr.align.is_some() {
382 return Err("Enum is marked with #[repr(align(...))] or #[repr(packed)].".to_owned());
383 }
384
385 let path = Path::new(item.ident.unraw().to_string());
386 let generic_params = GenericParams::load(&item.generics)?;
387
388 let mut variants = Vec::new();
389 let mut has_data = false;
390
391 let annotations = AnnotationSet::load(&item.attrs)?;
392
393 for variant in item.variants.iter() {
394 let variant = EnumVariant::load(
395 Self::inline_tag_field(&repr),
396 variant,
397 generic_params.clone(),
398 mod_cfg,
399 &path,
400 &annotations,
401 config,
402 )?;
403 has_data = has_data || !variant.body.is_empty();
404 variants.push(variant);
405 }
406
407 if let Some(names) = annotations.list("enum-trailing-values") {
408 for name in names {
409 variants.push(EnumVariant::new(
410 name,
411 None,
412 VariantBody::empty(),
413 None,
414 Documentation::none(),
415 ));
416 }
417 }
418
419 if config.enumeration.add_sentinel(&annotations) {
420 variants.push(EnumVariant::new(
421 "Sentinel".to_owned(),
422 None,
423 VariantBody::empty(),
424 None,
425 Documentation::simple(" Must be last for serialization purposes"),
426 ));
427 }
428
429 let tag = if has_data {
430 Some("Tag".to_string())
431 } else {
432 None
433 };
434
435 Ok(Enum::new(
436 path,
437 generic_params,
438 repr,
439 variants,
440 tag,
441 Cfg::append(mod_cfg, Cfg::load(&item.attrs)),
442 annotations,
443 Documentation::load(&item.attrs),
444 ))
445 }
446
447 #[allow(clippy::too_many_arguments)]
448 pub fn new(
449 path: Path,
450 generic_params: GenericParams,
451 repr: Repr,
452 variants: Vec<EnumVariant>,
453 tag: Option<String>,
454 cfg: Option<Cfg>,
455 annotations: AnnotationSet,
456 documentation: Documentation,
457 ) -> Self {
458 let export_name = path.name().to_owned();
459 Self {
460 path,
461 export_name,
462 generic_params,
463 repr,
464 variants,
465 tag,
466 cfg,
467 annotations,
468 documentation,
469 }
470 }
471 }
472
473 impl Item for Enum {
474 fn path(&self) -> &Path {
475 &self.path
476 }
477
478 fn export_name(&self) -> &str {
479 &self.export_name
480 }
481
482 fn cfg(&self) -> Option<&Cfg> {
483 self.cfg.as_ref()
484 }
485
486 fn annotations(&self) -> &AnnotationSet {
487 &self.annotations
488 }
489
490 fn annotations_mut(&mut self) -> &mut AnnotationSet {
491 &mut self.annotations
492 }
493
494 fn container(&self) -> ItemContainer {
495 ItemContainer::Enum(self.clone())
496 }
497
498 fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) {
499 if self.tag.is_some() {
500 if self.repr.style == ReprStyle::C {
501 resolver.add_struct(&self.path);
502 } else {
503 resolver.add_union(&self.path);
504 }
505 } else if self.repr.style == ReprStyle::C {
506 resolver.add_enum(&self.path);
507 } else {
508 // This is important to handle conflicting names with opaque items.
509 resolver.add_none(&self.path);
510 }
511 }
512
513 fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
514 for &mut ref mut var in &mut self.variants {
515 var.resolve_declaration_types(resolver);
516 }
517 }
518
519 fn rename_for_config(&mut self, config: &Config) {
520 config.export.rename(&mut self.export_name);
521
522 if config.language != Language::Cxx && self.tag.is_some() {
523 // it makes sense to always prefix Tag with type name in C
524 let new_tag = format!("{}_Tag", self.export_name);
525 if self.repr.style == ReprStyle::Rust {
526 for variant in &mut self.variants {
527 if let VariantBody::Body { ref mut body, .. } = variant.body {
528 let path = Path::new(new_tag.clone());
529 let generic_path = GenericPath::new(path, vec![]);
530 body.fields[0].ty = Type::Path(generic_path);
531 }
532 }
533 }
534 self.tag = Some(new_tag);
535 }
536
537 for variant in &mut self.variants {
538 reserved::escape(&mut variant.export_name);
539 if let Some(discriminant) = &mut variant.discriminant {
540 discriminant.rename_for_config(config);
541 }
542 if let VariantBody::Body {
543 ref mut name,
544 ref mut body,
545 ..
546 } = variant.body
547 {
548 body.rename_for_config(config);
549 reserved::escape(name);
550 }
551 }
552
553 if config.enumeration.prefix_with_name
554 || self.annotations.bool("prefix-with-name").unwrap_or(false)
555 {
556 let separator = if config.export.mangle.remove_underscores {
557 ""
558 } else {
559 "_"
560 };
561
562 for variant in &mut self.variants {
563 variant.export_name =
564 format!("{}{}{}", self.export_name, separator, variant.export_name);
565 if let VariantBody::Body { ref mut body, .. } = variant.body {
566 body.export_name =
567 format!("{}{}{}", self.export_name, separator, body.export_name());
568 }
569 }
570 }
571
572 let rules = self
573 .annotations
574 .parse_atom::<RenameRule>("rename-all")
575 .unwrap_or(config.enumeration.rename_variants);
576
577 if let Some(r) = rules.not_none() {
578 self.variants = self
579 .variants
580 .iter()
581 .map(|variant| {
582 EnumVariant::new(
583 r.apply(
584 &variant.export_name,
585 IdentifierType::EnumVariant {
586 prefix: &self.export_name,
587 },
588 )
589 .into_owned(),
590 variant.discriminant.clone(),
591 match variant.body {
592 VariantBody::Empty(..) => variant.body.clone(),
593 VariantBody::Body {
594 ref name,
595 ref body,
596 inline,
597 inline_casts,
598 } => VariantBody::Body {
599 name: r.apply(name, IdentifierType::StructMember).into_owned(),
600 body: body.clone(),
601 inline,
602 inline_casts,
603 },
604 },
605 variant.cfg.clone(),
606 variant.documentation.clone(),
607 )
608 })
609 .collect();
610 }
611 }
612
613 fn instantiate_monomorph(
614 &self,
615 generic_values: &[GenericArgument],
616 library: &Library,
617 out: &mut Monomorphs,
618 ) {
619 let mappings = self.generic_params.call(self.path.name(), generic_values);
620
621 for variant in &self.variants {
622 if let VariantBody::Body { ref body, .. } = variant.body {
623 body.instantiate_monomorph(generic_values, library, out);
624 }
625 }
626
627 let mangled_path = mangle::mangle_path(
628 &self.path,
629 generic_values,
630 &library.get_config().export.mangle,
631 );
632
633 let monomorph = Enum::new(
634 mangled_path,
635 GenericParams::default(),
636 self.repr,
637 self.variants
638 .iter()
639 .map(|v| v.specialize(generic_values, &mappings, library.get_config()))
640 .collect(),
641 self.tag.clone(),
642 self.cfg.clone(),
643 self.annotations.clone(),
644 self.documentation.clone(),
645 );
646
647 out.insert_enum(library, self, monomorph, generic_values.to_owned());
648 }
649
650 fn add_dependencies(&self, library: &Library, out: &mut Dependencies) {
651 for variant in &self.variants {
652 variant.add_dependencies(library, out);
653 }
654 }
655 }
656
657 impl Source for Enum {
658 fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
659 let size = self.repr.ty.map(|ty| ty.to_primitive().to_repr_c(config));
660 let has_data = self.tag.is_some();
661 let inline_tag_field = Self::inline_tag_field(&self.repr);
662 let tag_name = self.tag_name();
663
664 let condition = self.cfg.to_condition(config);
665 condition.write_before(config, out);
666
667 self.documentation.write(config, out);
668 self.generic_params.write(config, out);
669
670 // If the enum has data, we need to emit a struct or union for the data
671 // and enum for the tag. C++ supports nested type definitions, so we open
672 // the struct or union here and define the tag enum inside it (*).
673 if has_data && config.language == Language::Cxx {
674 self.open_struct_or_union(config, out, inline_tag_field);
675 }
676
677 // Emit the tag enum and everything related to it.
678 self.write_tag_enum(config, out, size, has_data, tag_name);
679
680 // If the enum has data, we need to emit structs for the variants and gather them together.
681 if has_data {
682 self.write_variant_defs(config, out);
683 out.new_line();
684 out.new_line();
685
686 // Open the struct or union for the data (**), gathering all the variants with data
687 // together, unless it's C++, then we have already opened that struct/union at (*) and
688 // are currently inside it.
689 if config.language != Language::Cxx {
690 self.open_struct_or_union(config, out, inline_tag_field);
691 }
692
693 // Emit tag field that is separate from all variants.
694 self.write_tag_field(config, out, size, inline_tag_field, tag_name);
695 out.new_line();
696
697 // Open union of all variants with data, only in the non-inline tag scenario.
698 // Cython extern declarations don't manage layouts, layouts are defined entierly by the
699 // corresponding C code. So we can inline the unnamed union into the struct and get the
700 // same observable result. Moreother we have to do it because Cython doesn't support
701 // unnamed unions.
702 if !inline_tag_field && config.language != Language::Cython {
703 out.write("union");
704 out.open_brace();
705 }
706
707 // Emit fields for all variants with data.
708 self.write_variant_fields(config, out, inline_tag_field);
709
710 // Close union of all variants with data, only in the non-inline tag scenario.
711 // See the comment about Cython on `open_brace`.
712 if !inline_tag_field && config.language != Language::Cython {
713 out.close_brace(true);
714 }
715
716 // Emit convenience methods for the struct or enum for the data.
717 self.write_derived_functions_data(config, out, tag_name);
718
719 // Emit the post_body section, if relevant.
720 if let Some(body) = config.export.post_body(&self.path) {
721 out.new_line();
722 out.write_raw_block(body);
723 }
724
725 // Close the struct or union opened either at (*) or at (**).
726 if config.language == Language::C && config.style.generate_typedef() {
727 out.close_brace(false);
728 write!(out, " {};", self.export_name);
729 } else {
730 out.close_brace(true);
731 }
732 }
733
734 condition.write_after(config, out);
735 }
736 }
737
738 impl Enum {
739 /// Emit the tag enum and convenience methods for it.
740 /// For enums with data this is only a part of the output,
741 /// but for enums without data it's the whole output (modulo doc comments etc.).
742 fn write_tag_enum<F: Write>(
743 &self,
744 config: &Config,
745 out: &mut SourceWriter<F>,
746 size: Option<&str>,
747 has_data: bool,
748 tag_name: &str,
749 ) {
750 // Open the tag enum.
751 match config.language {
752 Language::C => {
753 if let Some(prim) = size {
754 // If we need to specify size, then we have no choice but to create a typedef,
755 // so `config.style` is not respected.
756 write!(out, "enum {}", tag_name);
757
758 if config.cpp_compatible_c() {
759 out.new_line();
760 out.write("#ifdef __cplusplus");
761 out.new_line();
762 write!(out, " : {}", prim);
763 out.new_line();
764 out.write("#endif // __cplusplus");
765 out.new_line();
766 }
767 } else {
768 if config.style.generate_typedef() {
769 out.write("typedef ");
770 }
771 out.write("enum");
772 if config.style.generate_tag() {
773 write!(out, " {}", tag_name);
774 }
775 }
776 }
777 Language::Cxx => {
778 if config.enumeration.enum_class(&self.annotations) {
779 out.write("enum class");
780 } else {
781 out.write("enum");
782 }
783
784 if self.annotations.must_use(config) {
785 if let Some(ref anno) = config.enumeration.must_use {
786 write!(out, " {}", anno)
787 }
788 }
789
790 write!(out, " {}", tag_name);
791 if let Some(prim) = size {
792 write!(out, " : {}", prim);
793 }
794 }
795 Language::Cython => {
796 if size.is_some() {
797 // If we need to specify size, then we have no choice but to create a typedef,
798 // so `config.style` is not respected.
799 write!(out, "cdef enum");
800 } else {
801 write!(out, "{}enum {}", config.style.cython_def(), tag_name);
802 }
803 }
804 }
805 out.open_brace();
806
807 // Emit enumerators for the tag enum.
808 for (i, variant) in self.variants.iter().enumerate() {
809 if i != 0 {
810 out.new_line()
811 }
812 variant.write(config, out);
813 }
814
815 // Close the tag enum.
816 if config.language == Language::C && size.is_none() && config.style.generate_typedef() {
817 out.close_brace(false);
818 write!(out, " {};", tag_name);
819 } else {
820 out.close_brace(true);
821 }
822
823 // Emit typedef specifying the tag enum's size if necessary.
824 // In C++ enums can "inherit" from numeric types (`enum E: uint8_t { ... }`),
825 // but in C `typedef uint8_t E` is the only way to give a fixed size to `E`.
826 if let Some(prim) = size {
827 if config.cpp_compatible_c() {
828 out.new_line_if_not_start();
829 out.write("#ifndef __cplusplus");
830 }
831
832 if config.language != Language::Cxx {
833 out.new_line();
834 write!(out, "{} {} {};", config.language.typedef(), prim, tag_name);
835 }
836
837 if config.cpp_compatible_c() {
838 out.new_line_if_not_start();
839 out.write("#endif // __cplusplus");
840 }
841 }
842
843 // Emit convenience methods for the tag enum.
844 self.write_derived_functions_enum(config, out, has_data, tag_name);
845 }
846
847 /// The code here mirrors the beginning of `Struct::write` and `Union::write`.
848 fn open_struct_or_union<F: Write>(
849 &self,
850 config: &Config,
851 out: &mut SourceWriter<F>,
852 inline_tag_field: bool,
853 ) {
854 match config.language {
855 Language::C if config.style.generate_typedef() => out.write("typedef "),
856 Language::C | Language::Cxx => {}
857 Language::Cython => out.write(config.style.cython_def()),
858 }
859
860 out.write(if inline_tag_field { "union" } else { "struct" });
861
862 if self.annotations.must_use(config) {
863 if let Some(ref anno) = config.structure.must_use {
864 write!(out, " {}", anno);
865 }
866 }
867
868 if config.language != Language::C || config.style.generate_tag() {
869 write!(out, " {}", self.export_name());
870 }
871
872 out.open_brace();
873
874 // Emit the pre_body section, if relevant.
875 if let Some(body) = config.export.pre_body(&self.path) {
876 out.write_raw_block(body);
877 out.new_line();
878 }
879 }
880
881 /// Emit struct definitions for variants having data.
882 fn write_variant_defs<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
883 for variant in &self.variants {
884 if let VariantBody::Body {
885 ref body,
886 inline: false,
887 ..
888 } = variant.body
889 {
890 out.new_line();
891 out.new_line();
892 let condition = variant.cfg.to_condition(config);
893 // Cython doesn't support conditional enum variants.
894 if config.language != Language::Cython {
895 condition.write_before(config, out);
896 }
897 body.write(config, out);
898 if config.language != Language::Cython {
899 condition.write_after(config, out);
900 }
901 }
902 }
903 }
904
905 /// Emit tag field that is separate from all variants.
906 /// For non-inline tag scenario this is *the* tag field, and it does not exist in the variants.
907 /// For the inline tag scenario this is just a convenience and another way
908 /// to refer to the same tag that exist in all the variants.
909 fn write_tag_field<F: Write>(
910 &self,
911 config: &Config,
912 out: &mut SourceWriter<F>,
913 size: Option<&str>,
914 inline_tag_field: bool,
915 tag_name: &str,
916 ) {
917 // C++ allows accessing only common initial sequence of union
918 // fields so we have to wrap the tag field into an anonymous struct.
919 let wrap_tag = inline_tag_field && config.language == Language::Cxx;
920
921 if wrap_tag {
922 out.write("struct");
923 out.open_brace();
924 }
925
926 if config.language == Language::C && size.is_none() && !config.style.generate_typedef() {
927 out.write("enum ");
928 }
929
930 write!(out, "{} tag;", tag_name);
931
932 if wrap_tag {
933 out.close_brace(true);
934 }
935 }
936
937 /// Emit fields for all variants with data.
938 fn write_variant_fields<F: Write>(
939 &self,
940 config: &Config,
941 out: &mut SourceWriter<F>,
942 inline_tag_field: bool,
943 ) {
944 let mut first = true;
945 for variant in &self.variants {
946 if let VariantBody::Body {
947 name, body, inline, ..
948 } = &variant.body
949 {
950 if !first {
951 out.new_line();
952 }
953 first = false;
954 let condition = variant.cfg.to_condition(config);
955 // Cython doesn't support conditional enum variants.
956 if config.language != Language::Cython {
957 condition.write_before(config, out);
958 }
959 if *inline {
960 // Write definition of an inlined variant with data.
961 // Cython extern declarations don't manage layouts, layouts are defined entierly
962 // by the corresponding C code. So we can inline the unnamed struct and get the
963 // same observable result. Moreother we have to do it because Cython doesn't
964 // support unnamed structs.
965 // For the same reason with Cython we can omit per-variant tags (the first
966 // field) to avoid extra noise, the main `tag` is enough in this case.
967 if config.language != Language::Cython {
968 out.write("struct");
969 out.open_brace();
970 }
971 let start_field =
972 usize::from(inline_tag_field && config.language == Language::Cython);
973 out.write_vertical_source_list(&body.fields[start_field..], ListType::Cap(";"));
974 if config.language != Language::Cython {
975 out.close_brace(true);
976 }
977 } else if config.style.generate_typedef() || config.language == Language::Cython {
978 write!(out, "{} {};", body.export_name(), name);
979 } else {
980 write!(out, "struct {} {};", body.export_name(), name);
981 }
982 if config.language != Language::Cython {
983 condition.write_after(config, out);
984 }
985 }
986 }
987 }
988
989 // Emit convenience methods for enums themselves.
990 fn write_derived_functions_enum<F: Write>(
991 &self,
992 config: &Config,
993 out: &mut SourceWriter<F>,
994 has_data: bool,
995 tag_name: &str,
996 ) {
997 if config.language != Language::Cxx {
998 return;
999 }
1000
1001 // Emit an ostream function if required.
1002 if config.enumeration.derive_ostream(&self.annotations) {
1003 // For enums without data, this emits the serializer function for the
1004 // enum. For enums with data, this emits the serializer function for
1005 // the tag enum. In the latter case we need a couple of minor changes
1006 // due to the function living inside the top-level struct or enum.
1007 let stream = config
1008 .function
1009 .rename_args
1010 .apply("stream", IdentifierType::FunctionArg);
1011 let instance = config
1012 .function
1013 .rename_args
1014 .apply("instance", IdentifierType::FunctionArg);
1015
1016 out.new_line();
1017 out.new_line();
1018 // For enums without data, we mark the function inline because the
1019 // header might get included into multiple compilation units that
1020 // get linked together, and not marking it inline would result in
1021 // multiply-defined symbol errors. For enums with data we don't have
1022 // the same problem, but mark it as a friend function of the
1023 // containing union/struct.
1024 // Note also that for enums with data, the case labels for switch
1025 // statements apparently need to be qualified to the top-level
1026 // generated struct or union. This is why the generated case labels
1027 // below use the A::B::C format for enums with data, with A being
1028 // self.export_name(). Failure to have that qualification results
1029 // in a surprising compilation failure for the generated header.
1030 write!(
1031 out,
1032 "{} std::ostream& operator<<(std::ostream& {}, const {}& {})",
1033 if has_data { "friend" } else { "inline" },
1034 stream,
1035 tag_name,
1036 instance,
1037 );
1038
1039 out.open_brace();
1040 if has_data {
1041 // C++ name resolution rules are weird.
1042 write!(
1043 out,
1044 "using {} = {}::{};",
1045 tag_name,
1046 self.export_name(),
1047 tag_name
1048 );
1049 out.new_line();
1050 }
1051 write!(out, "switch ({})", instance);
1052 out.open_brace();
1053 let vec: Vec<_> = self
1054 .variants
1055 .iter()
1056 .map(|x| {
1057 format!(
1058 "case {}::{}: {} << \"{}\"; break;",
1059 tag_name, x.export_name, stream, x.export_name
1060 )
1061 })
1062 .collect();
1063 out.write_vertical_source_list(&vec[..], ListType::Join(""));
1064 out.close_brace(false);
1065 out.new_line();
1066
1067 write!(out, "return {};", stream);
1068 out.close_brace(false);
1069
1070 if has_data {
1071 // For enums with data, this emits the serializer function for
1072 // the top-level union or struct.
1073 out.new_line();
1074 out.new_line();
1075 write!(
1076 out,
1077 "friend std::ostream& operator<<(std::ostream& {}, const {}& {})",
1078 stream,
1079 self.export_name(),
1080 instance,
1081 );
1082
1083 out.open_brace();
1084
1085 // C++ name resolution rules are weird.
1086 write!(
1087 out,
1088 "using {} = {}::{};",
1089 tag_name,
1090 self.export_name(),
1091 tag_name
1092 );
1093 out.new_line();
1094
1095 write!(out, "switch ({}.tag)", instance);
1096 out.open_brace();
1097 let vec: Vec<_> = self
1098 .variants
1099 .iter()
1100 .map(|x| {
1101 let tag_str = format!("\"{}\"", x.export_name);
1102 if let VariantBody::Body {
1103 ref name, ref body, ..
1104 } = x.body
1105 {
1106 format!(
1107 "case {}::{}: {} << {}{}{}.{}; break;",
1108 tag_name,
1109 x.export_name,
1110 stream,
1111 if body.has_tag_field { "" } else { &tag_str },
1112 if body.has_tag_field { "" } else { " << " },
1113 instance,
1114 name,
1115 )
1116 } else {
1117 format!(
1118 "case {}::{}: {} << {}; break;",
1119 tag_name, x.export_name, stream, tag_str,
1120 )
1121 }
1122 })
1123 .collect();
1124 out.write_vertical_source_list(&vec[..], ListType::Join(""));
1125 out.close_brace(false);
1126 out.new_line();
1127
1128 write!(out, "return {};", stream);
1129 out.close_brace(false);
1130 }
1131 }
1132 }
1133
1134 // Emit convenience methods for structs or unions produced for enums with data.
1135 fn write_derived_functions_data<F: Write>(
1136 &self,
1137 config: &Config,
1138 out: &mut SourceWriter<F>,
1139 tag_name: &str,
1140 ) {
1141 if config.language != Language::Cxx {
1142 return;
1143 }
1144
1145 if config.enumeration.derive_helper_methods(&self.annotations) {
1146 for variant in &self.variants {
1147 out.new_line();
1148 out.new_line();
1149
1150 let condition = variant.cfg.to_condition(config);
1151 condition.write_before(config, out);
1152
1153 let arg_renamer = |name: &str| {
1154 config
1155 .function
1156 .rename_args
1157 .apply(name, IdentifierType::FunctionArg)
1158 .into_owned()
1159 };
1160
1161 macro_rules! write_attrs {
1162 ($op:expr) => {{
1163 if let Some(Some(attrs)) =
1164 variant
1165 .body
1166 .annotations()
1167 .atom(concat!("variant-", $op, "-attributes"))
1168 {
1169 write!(out, "{} ", attrs);
1170 }
1171 }};
1172 }
1173
1174 write_attrs!("constructor");
1175 write!(out, "static {} {}(", self.export_name, variant.export_name);
1176
1177 if let VariantBody::Body { ref body, .. } = variant.body {
1178 let skip_fields = body.has_tag_field as usize;
1179 let vec: Vec<_> = body
1180 .fields
1181 .iter()
1182 .skip(skip_fields)
1183 .map(|field| {
1184 Field::from_name_and_type(
1185 // const-ref args to constructor
1186 arg_renamer(&field.name),
1187 Type::const_ref_to(&field.ty),
1188 )
1189 })
1190 .collect();
1191 out.write_vertical_source_list(&vec[..], ListType::Join(","));
1192 }
1193
1194 write!(out, ")");
1195 out.open_brace();
1196
1197 write!(out, "{} result;", self.export_name);
1198
1199 if let VariantBody::Body {
1200 name: ref variant_name,
1201 ref body,
1202 ..
1203 } = variant.body
1204 {
1205 let skip_fields = body.has_tag_field as usize;
1206 for field in body.fields.iter().skip(skip_fields) {
1207 out.new_line();
1208 match field.ty {
1209 Type::Array(ref ty, ref length) => {
1210 // arrays are not assignable in C++ so we
1211 // need to manually copy the elements
1212 write!(out, "for (int i = 0; i < {}; i++)", length.as_str());
1213 out.open_brace();
1214 write!(out, "::new (&result.{}.{}[i]) (", variant_name, field.name);
1215 ty.write(config, out);
1216 write!(out, ")({}[i]);", arg_renamer(&field.name));
1217 out.close_brace(false);
1218 }
1219 ref ty => {
1220 write!(out, "::new (&result.{}.{}) (", variant_name, field.name);
1221 ty.write(config, out);
1222 write!(out, ")({});", arg_renamer(&field.name));
1223 }
1224 }
1225 }
1226 }
1227
1228 out.new_line();
1229 write!(out, "result.tag = {}::{};", tag_name, variant.export_name);
1230 out.new_line();
1231 write!(out, "return result;");
1232 out.close_brace(false);
1233
1234 out.new_line();
1235 out.new_line();
1236
1237 write_attrs!("is");
1238 // FIXME: create a config for method case
1239 write!(out, "bool Is{}() const", variant.export_name);
1240 out.open_brace();
1241 write!(out, "return tag == {}::{};", tag_name, variant.export_name);
1242 out.close_brace(false);
1243
1244 let assert_name = match config.enumeration.cast_assert_name {
1245 Some(ref n) => &**n,
1246 None => "assert",
1247 };
1248
1249 let mut derive_casts = |const_casts: bool| {
1250 let (member_name, body, inline_casts) = match variant.body {
1251 VariantBody::Body {
1252 ref name,
1253 ref body,
1254 inline_casts,
1255 ..
1256 } => (name, body, inline_casts),
1257 VariantBody::Empty(..) => return,
1258 };
1259
1260 let skip_fields = body.has_tag_field as usize;
1261 let field_count = body.fields.len() - skip_fields;
1262 if field_count == 0 {
1263 return;
1264 }
1265
1266 out.new_line();
1267 out.new_line();
1268
1269 if const_casts {
1270 write_attrs!("const-cast");
1271 } else {
1272 write_attrs!("mut-cast");
1273 }
1274 if inline_casts {
1275 let field = body.fields.last().unwrap();
1276 let return_type = field.ty.clone();
1277 let return_type = Type::Ptr {
1278 ty: Box::new(return_type),
1279 is_const: const_casts,
1280 is_ref: true,
1281 is_nullable: false,
1282 };
1283 return_type.write(config, out);
1284 } else if const_casts {
1285 write!(out, "const {}&", body.export_name());
1286 } else {
1287 write!(out, "{}&", body.export_name());
1288 }
1289
1290 write!(out, " As{}()", variant.export_name);
1291 if const_casts {
1292 write!(out, " const");
1293 }
1294 out.open_brace();
1295 write!(out, "{}(Is{}());", assert_name, variant.export_name);
1296 out.new_line();
1297 write!(out, "return {}", member_name);
1298 if inline_casts {
1299 write!(out, "._0");
1300 }
1301 write!(out, ";");
1302 out.close_brace(false);
1303 };
1304
1305 if config.enumeration.derive_const_casts(&self.annotations) {
1306 derive_casts(true)
1307 }
1308
1309 if config.enumeration.derive_mut_casts(&self.annotations) {
1310 derive_casts(false)
1311 }
1312
1313 condition.write_after(config, out);
1314 }
1315 }
1316
1317 let other = config
1318 .function
1319 .rename_args
1320 .apply("other", IdentifierType::FunctionArg);
1321
1322 macro_rules! write_attrs {
1323 ($op:expr) => {{
1324 if let Some(Some(attrs)) = self.annotations.atom(concat!($op, "-attributes")) {
1325 write!(out, "{} ", attrs);
1326 }
1327 }};
1328 }
1329
1330 if self.can_derive_eq() && config.structure.derive_eq(&self.annotations) {
1331 out.new_line();
1332 out.new_line();
1333 write_attrs!("eq");
1334 write!(
1335 out,
1336 "bool operator==(const {}& {}) const",
1337 self.export_name, other
1338 );
1339 out.open_brace();
1340 write!(out, "if (tag != {}.tag)", other);
1341 out.open_brace();
1342 write!(out, "return false;");
1343 out.close_brace(false);
1344 out.new_line();
1345 write!(out, "switch (tag)");
1346 out.open_brace();
1347 let mut exhaustive = true;
1348 for variant in &self.variants {
1349 if let VariantBody::Body {
1350 name: ref variant_name,
1351 ..
1352 } = variant.body
1353 {
1354 let condition = variant.cfg.to_condition(config);
1355 condition.write_before(config, out);
1356 write!(
1357 out,
1358 "case {}::{}: return {} == {}.{};",
1359 self.tag.as_ref().unwrap(),
1360 variant.export_name,
1361 variant_name,
1362 other,
1363 variant_name
1364 );
1365 condition.write_after(config, out);
1366 out.new_line();
1367 } else {
1368 exhaustive = false;
1369 }
1370 }
1371 if !exhaustive {
1372 write!(out, "default: break;");
1373 }
1374 out.close_brace(false);
1375
1376 out.new_line();
1377 write!(out, "return true;");
1378
1379 out.close_brace(false);
1380
1381 if config.structure.derive_neq(&self.annotations) {
1382 out.new_line();
1383 out.new_line();
1384 write_attrs!("neq");
1385 write!(
1386 out,
1387 "bool operator!=(const {}& {}) const",
1388 self.export_name, other
1389 );
1390 out.open_brace();
1391 write!(out, "return !(*this == {});", other);
1392 out.close_brace(false);
1393 }
1394 }
1395
1396 if config
1397 .enumeration
1398 .private_default_tagged_enum_constructor(&self.annotations)
1399 {
1400 out.new_line();
1401 out.new_line();
1402 write!(out, "private:");
1403 out.new_line();
1404 write!(out, "{}()", self.export_name);
1405 out.open_brace();
1406 out.close_brace(false);
1407 out.new_line();
1408 write!(out, "public:");
1409 out.new_line();
1410 }
1411
1412 if config
1413 .enumeration
1414 .derive_tagged_enum_destructor(&self.annotations)
1415 {
1416 out.new_line();
1417 out.new_line();
1418 write_attrs!("destructor");
1419 write!(out, "~{}()", self.export_name);
1420 out.open_brace();
1421 write!(out, "switch (tag)");
1422 out.open_brace();
1423 let mut exhaustive = true;
1424 for variant in &self.variants {
1425 if let VariantBody::Body {
1426 ref name, ref body, ..
1427 } = variant.body
1428 {
1429 let condition = variant.cfg.to_condition(config);
1430 condition.write_before(config, out);
1431 write!(
1432 out,
1433 "case {}::{}: {}.~{}(); break;",
1434 self.tag.as_ref().unwrap(),
1435 variant.export_name,
1436 name,
1437 body.export_name(),
1438 );
1439 condition.write_after(config, out);
1440 out.new_line();
1441 } else {
1442 exhaustive = false;
1443 }
1444 }
1445 if !exhaustive {
1446 write!(out, "default: break;");
1447 }
1448 out.close_brace(false);
1449 out.close_brace(false);
1450 }
1451
1452 if config
1453 .enumeration
1454 .derive_tagged_enum_copy_constructor(&self.annotations)
1455 {
1456 out.new_line();
1457 out.new_line();
1458 write_attrs!("copy-constructor");
1459 write!(
1460 out,
1461 "{}(const {}& {})",
1462 self.export_name, self.export_name, other
1463 );
1464 out.new_line();
1465 write!(out, " : tag({}.tag)", other);
1466 out.open_brace();
1467 write!(out, "switch (tag)");
1468 out.open_brace();
1469 let mut exhaustive = true;
1470 for variant in &self.variants {
1471 if let VariantBody::Body {
1472 ref name, ref body, ..
1473 } = variant.body
1474 {
1475 let condition = variant.cfg.to_condition(config);
1476 condition.write_before(config, out);
1477 write!(
1478 out,
1479 "case {}::{}: ::new (&{}) ({})({}.{}); break;",
1480 self.tag.as_ref().unwrap(),
1481 variant.export_name,
1482 name,
1483 body.export_name(),
1484 other,
1485 name,
1486 );
1487 condition.write_after(config, out);
1488 out.new_line();
1489 } else {
1490 exhaustive = false;
1491 }
1492 }
1493 if !exhaustive {
1494 write!(out, "default: break;");
1495 }
1496 out.close_brace(false);
1497 out.close_brace(false);
1498
1499 if config
1500 .enumeration
1501 .derive_tagged_enum_copy_assignment(&self.annotations)
1502 {
1503 out.new_line();
1504 write_attrs!("copy-assignment");
1505 write!(
1506 out,
1507 "{}& operator=(const {}& {})",
1508 self.export_name, self.export_name, other
1509 );
1510 out.open_brace();
1511 write!(out, "if (this != &{})", other);
1512 out.open_brace();
1513 write!(out, "this->~{}();", self.export_name);
1514 out.new_line();
1515 write!(out, "new (this) {}({});", self.export_name, other);
1516 out.close_brace(false);
1517 out.new_line();
1518 write!(out, "return *this;");
1519 out.close_brace(false);
1520 }
1521 }
1522 }
1523
1524 pub fn simplify_standard_types(&mut self, config: &Config) {
1525 for variant in &mut self.variants {
1526 variant.simplify_standard_types(config);
1527 }
1528 }
1529 }