Debian Codegraph @

.cargo/vendor/cbindgen/src/bindgen/ir/structure.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, LayoutConfig};
10 use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
11 use crate::bindgen::dependencies::Dependencies;
12 use crate::bindgen::ir::{
13 AnnotationSet, Cfg, ConditionWrite, Constant, Documentation, Field, GenericArgument,
14 GenericParams, Item, ItemContainer, Path, Repr, ReprAlign, ReprStyle, ToCondition, Type,
15 Typedef,
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::utilities::IterHelpers;
23 use crate::bindgen::writer::{ListType, Source, SourceWriter};
24
25 #[derive(Debug, Clone)]
26 pub struct Struct {
27 pub path: Path,
28 pub export_name: String,
29 pub generic_params: GenericParams,
30 pub fields: Vec<Field>,
31 /// Whether there's a tag field on the body of this struct. When this is
32 /// true, is_enum_variant_body is also guaranteed to be true.
33 pub has_tag_field: bool,
34 /// Whether this is an enum variant body.
35 pub is_enum_variant_body: bool,
36 pub alignment: Option<ReprAlign>,
37 pub is_transparent: bool,
38 pub cfg: Option<Cfg>,
39 pub annotations: AnnotationSet,
40 pub documentation: Documentation,
41 pub associated_constants: Vec<Constant>,
42 }
43
44 impl Struct {
45 /// Whether this struct can derive operator== / operator!=.
46 pub fn can_derive_eq(&self) -> bool {
47 !self.fields.is_empty() && self.fields.iter().all(|x| x.ty.can_cmp_eq())
48 }
49
50 pub fn add_associated_constant(&mut self, c: Constant) {
51 self.associated_constants.push(c);
52 }
53
54 pub fn load(
55 layout_config: &LayoutConfig,
56 item: &syn::ItemStruct,
57 mod_cfg: Option<&Cfg>,
58 ) -> Result<Self, String> {
59 let repr = Repr::load(&item.attrs)?;
60 let is_transparent = match repr.style {
61 ReprStyle::C => false,
62 ReprStyle::Transparent => true,
63 _ => {
64 return Err("Struct is not marked #[repr(C)] or #[repr(transparent)].".to_owned());
65 }
66 };
67
68 let path = Path::new(item.ident.unraw().to_string());
69
70 // Ensure we can safely represent the struct given the configuration.
71 if let Some(align) = repr.align {
72 layout_config.ensure_safe_to_represent(&align)?;
73 }
74
75 let fields = match item.fields {
76 syn::Fields::Unit => Vec::new(),
77 syn::Fields::Named(ref fields) => fields
78 .named
79 .iter()
80 .try_skip_map(|field| Field::load(field, &path))?,
81 syn::Fields::Unnamed(ref fields) => {
82 let mut out = Vec::new();
83 let mut current = 0;
84 for field in fields.unnamed.iter() {
85 if let Some(mut ty) = Type::load(&field.ty)? {
86 ty.replace_self_with(&path);
87 out.push(Field {
88 name: format!("{}", current),
89 ty,
90 cfg: Cfg::load(&field.attrs),
91 annotations: AnnotationSet::load(&field.attrs)?,
92 documentation: Documentation::load(&field.attrs),
93 });
94 current += 1;
95 }
96 }
97 out
98 }
99 };
100
101 let has_tag_field = false;
102 let is_enum_variant_body = false;
103
104 Ok(Struct::new(
105 path,
106 GenericParams::load(&item.generics)?,
107 fields,
108 has_tag_field,
109 is_enum_variant_body,
110 repr.align,
111 is_transparent,
112 Cfg::append(mod_cfg, Cfg::load(&item.attrs)),
113 AnnotationSet::load(&item.attrs)?,
114 Documentation::load(&item.attrs),
115 ))
116 }
117
118 #[allow(clippy::too_many_arguments)]
119 pub fn new(
120 path: Path,
121 generic_params: GenericParams,
122 fields: Vec<Field>,
123 has_tag_field: bool,
124 is_enum_variant_body: bool,
125 alignment: Option<ReprAlign>,
126 is_transparent: bool,
127 cfg: Option<Cfg>,
128 annotations: AnnotationSet,
129 documentation: Documentation,
130 ) -> Self {
131 let export_name = path.name().to_owned();
132 Self {
133 path,
134 export_name,
135 generic_params,
136 fields,
137 has_tag_field,
138 is_enum_variant_body,
139 alignment,
140 is_transparent,
141 cfg,
142 annotations,
143 documentation,
144 associated_constants: vec![],
145 }
146 }
147
148 pub fn simplify_standard_types(&mut self, config: &Config) {
149 for field in &mut self.fields {
150 field.ty.simplify_standard_types(config);
151 }
152 }
153
154 pub fn is_generic(&self) -> bool {
155 self.generic_params.len() > 0
156 }
157
158 pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) {
159 // Generic structs can instantiate monomorphs only once they've been
160 // instantiated. See `instantiate_monomorph` for more details.
161 if self.is_generic() {
162 return;
163 }
164
165 for field in &self.fields {
166 field.ty.add_monomorphs(library, out);
167 }
168 }
169
170 pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) {
171 for field in &mut self.fields {
172 field.ty.mangle_paths(monomorphs);
173 }
174 }
175
176 pub fn specialize(
177 &self,
178 generic_values: &[GenericArgument],
179 mappings: &[(&Path, &GenericArgument)],
180 config: &Config,
181 ) -> Self {
182 let mangled_path = mangle::mangle_path(&self.path, generic_values, &config.export.mangle);
183 Struct::new(
184 mangled_path,
185 GenericParams::default(),
186 self.fields
187 .iter()
188 .map(|field| Field {
189 name: field.name.clone(),
190 ty: field.ty.specialize(mappings),
191 cfg: field.cfg.clone(),
192 annotations: field.annotations.clone(),
193 documentation: field.documentation.clone(),
194 })
195 .collect(),
196 self.has_tag_field,
197 self.is_enum_variant_body,
198 self.alignment,
199 self.is_transparent,
200 self.cfg.clone(),
201 self.annotations.clone(),
202 self.documentation.clone(),
203 )
204 }
205
206 fn emit_bitflags_binop<F: Write>(
207 &self,
208 constexpr_prefix: &str,
209 operator: char,
210 other: &str,
211 out: &mut SourceWriter<F>,
212 ) {
213 out.new_line();
214 write!(
215 out,
216 "{}{} operator{}(const {}& {}) const",
217 constexpr_prefix,
218 self.export_name(),
219 operator,
220 self.export_name(),
221 other
222 );
223 out.open_brace();
224 write!(
225 out,
226 "return {} {{ static_cast<decltype(bits)>(this->bits {} {}.bits) }};",
227 self.export_name(),
228 operator,
229 other
230 );
231 out.close_brace(false);
232
233 out.new_line();
234 write!(
235 out,
236 "{}& operator{}=(const {}& {})",
237 self.export_name(),
238 operator,
239 self.export_name(),
240 other
241 );
242 out.open_brace();
243 write!(out, "*this = (*this {} {});", operator, other);
244 out.new_line();
245 write!(out, "return *this;");
246 out.close_brace(false);
247 }
248 }
249
250 impl Item for Struct {
251 fn path(&self) -> &Path {
252 &self.path
253 }
254
255 fn export_name(&self) -> &str {
256 &self.export_name
257 }
258
259 fn cfg(&self) -> Option<&Cfg> {
260 self.cfg.as_ref()
261 }
262
263 fn annotations(&self) -> &AnnotationSet {
264 &self.annotations
265 }
266
267 fn annotations_mut(&mut self) -> &mut AnnotationSet {
268 &mut self.annotations
269 }
270
271 fn container(&self) -> ItemContainer {
272 ItemContainer::Struct(self.clone())
273 }
274
275 fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) {
276 if self.is_transparent {
277 resolver.add_none(&self.path);
278 } else {
279 resolver.add_struct(&self.path);
280 }
281 }
282
283 fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
284 for field in &mut self.fields {
285 field.ty.resolve_declaration_types(resolver);
286 }
287 }
288
289 fn rename_for_config(&mut self, config: &Config) {
290 // Rename the name of the struct
291 if !(self.has_tag_field && config.language == Language::Cxx) {
292 config.export.rename(&mut self.export_name);
293 }
294
295 // Rename the types used in fields
296 {
297 let fields = self.fields.iter_mut().skip(self.has_tag_field as usize);
298 for field in fields {
299 field.ty.rename_for_config(config, &self.generic_params);
300 }
301 }
302
303 // Apply renaming rules to fields in the following order
304 // 1. `cbindgen::field-names` annotation
305 // 2. `cbindgen::rename-all` annotation
306 // 3. config struct rename rule
307 // If the struct is a tuple struct and we have not renamed the
308 // fields, then prefix each of them with an underscore.
309 // If any field is a reserved keyword, then postfix it with an
310 // underscore.
311
312 // Scope for mutable borrow of fields
313 {
314 let names = self.fields.iter_mut().map(|field| &mut field.name);
315
316 let field_rules = self
317 .annotations
318 .parse_atom::<RenameRule>("rename-all")
319 .unwrap_or(config.structure.rename_fields);
320
321 if let Some(o) = self.annotations.list("field-names") {
322 for (dest, src) in names.zip(o) {
323 *dest = src;
324 }
325 } else if let Some(r) = field_rules.not_none() {
326 for name in names {
327 *name = r.apply(name, IdentifierType::StructMember).into_owned();
328 }
329 } else {
330 // If we don't have any rules for a tuple struct, prefix them with
331 // an underscore so it still compiles.
332 for name in names {
333 if name.starts_with(|c: char| c.is_ascii_digit()) {
334 name.insert(0, '_');
335 }
336 }
337 }
338 }
339
340 for field in &mut self.fields {
341 reserved::escape(&mut field.name);
342 }
343
344 for c in self.associated_constants.iter_mut() {
345 c.rename_for_config(config);
346 }
347 }
348
349 fn add_dependencies(&self, library: &Library, out: &mut Dependencies) {
350 let mut fields = self.fields.iter();
351
352 // If there is a tag field, skip it
353 if self.has_tag_field {
354 fields.next();
355 }
356
357 for field in fields {
358 field
359 .ty
360 .add_dependencies_ignoring_generics(&self.generic_params, library, out);
361 }
362
363 for c in &self.associated_constants {
364 c.add_dependencies(library, out);
365 }
366 }
367
368 fn instantiate_monomorph(
369 &self,
370 generic_values: &[GenericArgument],
371 library: &Library,
372 out: &mut Monomorphs,
373 ) {
374 let mappings = self.generic_params.call(self.path.name(), generic_values);
375 let monomorph = self.specialize(generic_values, &mappings, library.get_config());
376 out.insert_struct(library, self, monomorph, generic_values.to_owned());
377 }
378 }
379
380 impl Source for Struct {
381 fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
382 if self.is_transparent {
383 let typedef = Typedef {
384 path: self.path.clone(),
385 export_name: self.export_name.to_owned(),
386 generic_params: self.generic_params.clone(),
387 aliased: self.fields[0].ty.clone(),
388 cfg: self.cfg.clone(),
389 annotations: self.annotations.clone(),
390 documentation: self.documentation.clone(),
391 };
392 typedef.write(config, out);
393 for constant in &self.associated_constants {
394 out.new_line();
395 constant.write(config, out, Some(self));
396 }
397 return;
398 }
399
400 let condition = self.cfg.to_condition(config);
401 condition.write_before(config, out);
402
403 self.documentation.write(config, out);
404
405 if !self.is_enum_variant_body {
406 self.generic_params.write(config, out);
407 }
408
409 // The following results in
410 // C++ or C with Tag as style:
411 // struct Name {
412 // C with Type only style:
413 // typedef struct {
414 // C with Both as style:
415 // typedef struct Name {
416 match config.language {
417 Language::C if config.style.generate_typedef() => out.write("typedef "),
418 Language::C | Language::Cxx => {}
419 Language::Cython => out.write(config.style.cython_def()),
420 }
421
422 // Cython extern declarations don't manage layouts, layouts are defined entierly by the
423 // corresponding C code. So this `packed` is only for documentation, and missing
424 // `aligned(n)` is also not a problem.
425 if config.language == Language::Cython {
426 if let Some(align) = self.alignment {
427 match align {
428 ReprAlign::Packed => out.write("packed "),
429 ReprAlign::Align(_) => {} // Not supported
430 }
431 }
432 }
433
434 out.write("struct");
435
436 if config.language != Language::Cython {
437 if let Some(align) = self.alignment {
438 match align {
439 ReprAlign::Packed => {
440 if let Some(ref anno) = config.layout.packed {
441 write!(out, " {}", anno);
442 }
443 }
444 ReprAlign::Align(n) => {
445 if let Some(ref anno) = config.layout.aligned_n {
446 write!(out, " {}({})", anno, n);
447 }
448 }
449 }
450 }
451 }
452
453 if self.annotations.must_use(config) {
454 if let Some(ref anno) = config.structure.must_use {
455 write!(out, " {}", anno);
456 }
457 }
458
459 if config.language != Language::C || config.style.generate_tag() {
460 write!(out, " {}", self.export_name());
461 }
462
463 out.open_brace();
464
465 // Emit the pre_body section, if relevant
466 if let Some(body) = config.export.pre_body(&self.path) {
467 out.write_raw_block(body);
468 out.new_line();
469 }
470
471 out.write_vertical_source_list(&self.fields, ListType::Cap(";"));
472 if config.language == Language::Cython && self.fields.is_empty() {
473 out.write("pass");
474 }
475
476 if config.language == Language::Cxx {
477 let mut wrote_start_newline = false;
478
479 if config.structure.derive_constructor(&self.annotations) && !self.fields.is_empty() {
480 if !wrote_start_newline {
481 wrote_start_newline = true;
482 out.new_line();
483 }
484
485 out.new_line();
486
487 let arg_renamer = |name: &str| {
488 config
489 .function
490 .rename_args
491 .apply(name, IdentifierType::FunctionArg)
492 .into_owned()
493 };
494 write!(out, "{}(", self.export_name());
495 let vec: Vec<_> = self
496 .fields
497 .iter()
498 .map(|field| {
499 Field::from_name_and_type(
500 // const-ref args to constructor
501 format!("const& {}", arg_renamer(&field.name)),
502 field.ty.clone(),
503 )
504 })
505 .collect();
506 out.write_vertical_source_list(&vec[..], ListType::Join(","));
507 write!(out, ")");
508 out.new_line();
509 write!(out, " : ");
510 let vec: Vec<_> = self
511 .fields
512 .iter()
513 .map(|field| format!("{}({})", field.name, arg_renamer(&field.name)))
514 .collect();
515 out.write_vertical_source_list(&vec[..], ListType::Join(","));
516 out.new_line();
517 write!(out, "{{}}");
518 out.new_line();
519 }
520
521 let other = config
522 .function
523 .rename_args
524 .apply("other", IdentifierType::FunctionArg);
525
526 if self
527 .annotations
528 .bool("internal-derive-bitflags")
529 .unwrap_or(false)
530 {
531 if !wrote_start_newline {
532 wrote_start_newline = true;
533 out.new_line();
534 }
535 let constexpr_prefix = if config.constant.allow_constexpr {
536 "constexpr "
537 } else {
538 ""
539 };
540
541 out.new_line();
542 write!(out, "{}explicit operator bool() const", constexpr_prefix);
543 out.open_brace();
544 write!(out, "return !!bits;");
545 out.close_brace(false);
546
547 out.new_line();
548 write!(
549 out,
550 "{}{} operator~() const",
551 constexpr_prefix,
552 self.export_name()
553 );
554 out.open_brace();
555 write!(
556 out,
557 "return {} {{ static_cast<decltype(bits)>(~bits) }};",
558 self.export_name()
559 );
560 out.close_brace(false);
561 self.emit_bitflags_binop(constexpr_prefix, '|', &other, out);
562 self.emit_bitflags_binop(constexpr_prefix, '&', &other, out);
563 self.emit_bitflags_binop(constexpr_prefix, '^', &other, out);
564 }
565
566 // Generate a serializer function that allows dumping this struct
567 // to an std::ostream. It's defined as a friend function inside the
568 // struct definition, and doesn't need the `inline` keyword even
569 // though it's implemented right in the generated header file.
570 if config.structure.derive_ostream(&self.annotations) {
571 if !wrote_start_newline {
572 wrote_start_newline = true;
573 out.new_line();
574 }
575
576 out.new_line();
577 let stream = config
578 .function
579 .rename_args
580 .apply("stream", IdentifierType::FunctionArg);
581 let instance = config
582 .function
583 .rename_args
584 .apply("instance", IdentifierType::FunctionArg);
585 write!(
586 out,
587 "friend std::ostream& operator<<(std::ostream& {}, const {}& {})",
588 stream,
589 self.export_name(),
590 instance,
591 );
592 out.open_brace();
593 write!(out, "return {} << \"{{ \"", stream);
594 let vec: Vec<_> = self
595 .fields
596 .iter()
597 .map(|x| format!(" << \"{}=\" << {}.{}", x.name, instance, x.name))
598 .collect();
599 out.write_vertical_source_list(&vec[..], ListType::Join(" << \", \""));
600 out.write(" << \" }\";");
601 out.close_brace(false);
602 }
603
604 let skip_fields = self.has_tag_field as usize;
605
606 macro_rules! emit_op {
607 ($op_name:expr, $op:expr, $conjuc:expr) => {{
608 if !wrote_start_newline {
609 #[allow(unused_assignments)]
610 {
611 wrote_start_newline = true;
612 }
613 out.new_line();
614 }
615
616 out.new_line();
617
618 if let Some(Some(attrs)) =
619 self.annotations.atom(concat!($op_name, "-attributes"))
620 {
621 write!(out, "{} ", attrs);
622 }
623
624 write!(
625 out,
626 "bool operator{}(const {}& {}) const",
627 $op,
628 self.export_name(),
629 other
630 );
631 out.open_brace();
632 out.write("return ");
633 let vec: Vec<_> = self
634 .fields
635 .iter()
636 .skip(skip_fields)
637 .map(|field| format!("{} {} {}.{}", field.name, $op, other, field.name))
638 .collect();
639 out.write_vertical_source_list(
640 &vec[..],
641 ListType::Join(&format!(" {}", $conjuc)),
642 );
643 out.write(";");
644 out.close_brace(false);
645 }};
646 }
647
648 if config.structure.derive_eq(&self.annotations) && self.can_derive_eq() {
649 emit_op!("eq", "==", "&&");
650 }
651 if config.structure.derive_neq(&self.annotations) && self.can_derive_eq() {
652 emit_op!("neq", "!=", "||");
653 }
654 if config.structure.derive_lt(&self.annotations)
655 && self.fields.len() == 1
656 && self.fields[0].ty.can_cmp_order()
657 {
658 emit_op!("lt", "<", "&&");
659 }
660 if config.structure.derive_lte(&self.annotations)
661 && self.fields.len() == 1
662 && self.fields[0].ty.can_cmp_order()
663 {
664 emit_op!("lte", "<=", "&&");
665 }
666 if config.structure.derive_gt(&self.annotations)
667 && self.fields.len() == 1
668 && self.fields[0].ty.can_cmp_order()
669 {
670 emit_op!("gt", ">", "&&");
671 }
672 if config.structure.derive_gte(&self.annotations)
673 && self.fields.len() == 1
674 && self.fields[0].ty.can_cmp_order()
675 {
676 emit_op!("gte", ">=", "&&");
677 }
678 }
679
680 // Emit the post_body section, if relevant
681 if let Some(body) = config.export.post_body(&self.path) {
682 out.new_line();
683 out.write_raw_block(body);
684 }
685
686 if config.language == Language::Cxx
687 && config.structure.associated_constants_in_body
688 && config.constant.allow_static_const
689 {
690 for constant in &self.associated_constants {
691 out.new_line();
692 constant.write_declaration(config, out, self);
693 }
694 }
695
696 if config.language == Language::C && config.style.generate_typedef() {
697 out.close_brace(false);
698 write!(out, " {};", self.export_name());
699 } else {
700 out.close_brace(true);
701 }
702
703 for constant in &self.associated_constants {
704 out.new_line();
705 constant.write(config, out, Some(self));
706 }
707
708 condition.write_after(config, out);
709 }
710 }