Debian Codegraph @

.cargo/vendor/cbindgen/src/bindgen/config.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::collections::{BTreeMap, HashMap};
6 use std::default::Default;
7 use std::str::FromStr;
8 use std::{fmt, fs, path::Path as StdPath, path::PathBuf as StdPathBuf};
9
10 use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer};
11 use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
12
13 use crate::bindgen::ir::annotation::AnnotationSet;
14 use crate::bindgen::ir::path::Path;
15 use crate::bindgen::ir::repr::ReprAlign;
16 pub use crate::bindgen::rename::RenameRule;
17
18 pub const VERSION: &str = env!("CARGO_PKG_VERSION");
19
20 /// A language type to generate bindings for.
21 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
22 pub enum Language {
23 Cxx,
24 C,
25 Cython,
26 }
27
28 impl FromStr for Language {
29 type Err = String;
30
31 fn from_str(s: &str) -> Result<Language, Self::Err> {
32 match s {
33 "cxx" => Ok(Language::Cxx),
34 "Cxx" => Ok(Language::Cxx),
35 "CXX" => Ok(Language::Cxx),
36 "cpp" => Ok(Language::Cxx),
37 "Cpp" => Ok(Language::Cxx),
38 "CPP" => Ok(Language::Cxx),
39 "c++" => Ok(Language::Cxx),
40 "C++" => Ok(Language::Cxx),
41 "c" => Ok(Language::C),
42 "C" => Ok(Language::C),
43 "cython" => Ok(Language::Cython),
44 "Cython" => Ok(Language::Cython),
45 _ => Err(format!("Unrecognized Language: '{}'.", s)),
46 }
47 }
48 }
49
50 deserialize_enum_str!(Language);
51
52 impl Language {
53 pub(crate) fn typedef(self) -> &'static str {
54 match self {
55 Language::Cxx | Language::C => "typedef",
56 Language::Cython => "ctypedef",
57 }
58 }
59 }
60
61 /// Controls what type of line endings are used in the generated code.
62 #[derive(Debug, Clone, Copy)]
63 #[allow(clippy::upper_case_acronyms)]
64 pub enum LineEndingStyle {
65 /// Use Unix-style linefeed characters
66 LF,
67 /// Use classic Mac-style carriage-return characters
68 CR,
69 /// Use Windows-style carriage-return and linefeed characters
70 CRLF,
71 /// Use the native mode for the platform: CRLF on Windows, LF everywhere else.
72 Native,
73 }
74
75 impl Default for LineEndingStyle {
76 fn default() -> Self {
77 LineEndingStyle::LF
78 }
79 }
80
81 impl LineEndingStyle {
82 pub fn as_str(&self) -> &'static str {
83 match self {
84 Self::LF => "\n",
85 Self::CR => "\r",
86 Self::CRLF => "\r\n",
87 Self::Native => {
88 #[cfg(target_os = "windows")]
89 {
90 Self::CRLF.as_str()
91 }
92 #[cfg(not(target_os = "windows"))]
93 {
94 Self::LF.as_str()
95 }
96 }
97 }
98 }
99 }
100
101 impl FromStr for LineEndingStyle {
102 type Err = String;
103
104 fn from_str(s: &str) -> Result<Self, Self::Err> {
105 match s.to_lowercase().as_ref() {
106 "native" => Ok(Self::Native),
107 "lf" => Ok(Self::LF),
108 "crlf" => Ok(Self::CRLF),
109 "cr" => Ok(Self::CR),
110 _ => Err(format!("Unrecognized line ending style: '{}'.", s)),
111 }
112 }
113 }
114
115 deserialize_enum_str!(LineEndingStyle);
116
117 /// A style of braces to use for generating code.
118 #[derive(Debug, Clone, PartialEq, Eq)]
119 pub enum Braces {
120 SameLine,
121 NextLine,
122 }
123
124 impl FromStr for Braces {
125 type Err = String;
126
127 fn from_str(s: &str) -> Result<Braces, Self::Err> {
128 match s {
129 "SameLine" => Ok(Braces::SameLine),
130 "same_line" => Ok(Braces::SameLine),
131 "NextLine" => Ok(Braces::NextLine),
132 "next_line" => Ok(Braces::NextLine),
133 _ => Err(format!("Unrecognized Braces: '{}'.", s)),
134 }
135 }
136 }
137
138 deserialize_enum_str!(Braces);
139
140 /// A type of layout to use when generating long lines of code.
141 #[derive(Debug, Clone, PartialEq, Eq)]
142 pub enum Layout {
143 Horizontal,
144 Vertical,
145 Auto,
146 }
147
148 impl FromStr for Layout {
149 type Err = String;
150
151 fn from_str(s: &str) -> Result<Layout, Self::Err> {
152 match s {
153 "Horizontal" => Ok(Layout::Horizontal),
154 "horizontal" => Ok(Layout::Horizontal),
155 "Vertical" => Ok(Layout::Vertical),
156 "vertical" => Ok(Layout::Vertical),
157 "Auto" => Ok(Layout::Auto),
158 "auto" => Ok(Layout::Auto),
159 _ => Err(format!("Unrecognized Layout: '{}'.", s)),
160 }
161 }
162 }
163
164 deserialize_enum_str!(Layout);
165
166 /// How the comments containing documentation should be styled.
167 #[derive(Debug, Clone, PartialEq, Eq, Copy)]
168 pub enum DocumentationStyle {
169 C,
170 C99,
171 Doxy,
172 Cxx,
173 Auto,
174 }
175
176 impl FromStr for DocumentationStyle {
177 type Err = String;
178
179 fn from_str(s: &str) -> Result<DocumentationStyle, Self::Err> {
180 match s.to_lowercase().as_ref() {
181 "c" => Ok(DocumentationStyle::C),
182 "c99" => Ok(DocumentationStyle::C99),
183 "cxx" => Ok(DocumentationStyle::Cxx),
184 "c++" => Ok(DocumentationStyle::Cxx),
185 "doxy" => Ok(DocumentationStyle::Doxy),
186 "auto" => Ok(DocumentationStyle::Auto),
187 _ => Err(format!("Unrecognized documentation style: '{}'.", s)),
188 }
189 }
190 }
191
192 deserialize_enum_str!(DocumentationStyle);
193
194 /// How much of the documentation to include in the header file.
195 #[derive(Debug, Clone, Copy)]
196 pub enum DocumentationLength {
197 Short,
198 Full,
199 }
200
201 impl FromStr for DocumentationLength {
202 type Err = String;
203
204 fn from_str(s: &str) -> Result<DocumentationLength, Self::Err> {
205 match s.to_lowercase().as_ref() {
206 "short" => Ok(DocumentationLength::Short),
207 "full" => Ok(DocumentationLength::Full),
208 _ => Err(format!("Unrecognized documentation style: '{}'.", s)),
209 }
210 }
211 }
212
213 deserialize_enum_str!(DocumentationLength);
214
215 /// A style of Style to use when generating structs and enums.
216 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
217 pub enum Style {
218 Both,
219 Tag,
220 Type,
221 }
222
223 impl Style {
224 pub fn generate_tag(self) -> bool {
225 match self {
226 Style::Both | Style::Tag => true,
227 Style::Type => false,
228 }
229 }
230
231 pub fn generate_typedef(self) -> bool {
232 match self {
233 Style::Both | Style::Type => true,
234 Style::Tag => false,
235 }
236 }
237
238 // https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html#styles-of-struct-union-and-enum-declaration
239 pub fn cython_def(self) -> &'static str {
240 if self.generate_tag() {
241 "cdef "
242 } else {
243 "ctypedef "
244 }
245 }
246 }
247
248 impl Default for Style {
249 fn default() -> Self {
250 Style::Both
251 }
252 }
253
254 impl FromStr for Style {
255 type Err = String;
256
257 fn from_str(s: &str) -> Result<Style, Self::Err> {
258 match s {
259 "Both" => Ok(Style::Both),
260 "both" => Ok(Style::Both),
261 "Tag" => Ok(Style::Tag),
262 "tag" => Ok(Style::Tag),
263 "Type" => Ok(Style::Type),
264 "type" => Ok(Style::Type),
265 _ => Err(format!("Unrecognized Style: '{}'.", s)),
266 }
267 }
268 }
269
270 deserialize_enum_str!(Style);
271
272 /// Different item types that we can generate and filter.
273 #[derive(Debug, Clone, PartialEq, Eq)]
274 pub enum ItemType {
275 Constants,
276 Globals,
277 Enums,
278 Structs,
279 Unions,
280 Typedefs,
281 OpaqueItems,
282 Functions,
283 }
284
285 impl FromStr for ItemType {
286 type Err = String;
287
288 fn from_str(s: &str) -> Result<Self, Self::Err> {
289 use self::ItemType::*;
290 Ok(match &*s.to_lowercase() {
291 "constants" => Constants,
292 "globals" => Globals,
293 "enums" => Enums,
294 "structs" => Structs,
295 "unions" => Unions,
296 "typedefs" => Typedefs,
297 "opaque" => OpaqueItems,
298 "functions" => Functions,
299 _ => return Err(format!("Unrecognized Style: '{}'.", s)),
300 })
301 }
302 }
303
304 deserialize_enum_str!(ItemType);
305
306 /// Type which specifies the sort order of functions
307 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
308 pub enum SortKey {
309 Name,
310 None,
311 }
312
313 impl FromStr for SortKey {
314 type Err = String;
315
316 fn from_str(s: &str) -> Result<Self, Self::Err> {
317 use self::SortKey::*;
318 Ok(match &*s.to_lowercase() {
319 "name" => Name,
320 "none" => None,
321 _ => return Err(format!("Unrecognized sort option: '{}'.", s)),
322 })
323 }
324 }
325
326 deserialize_enum_str!(SortKey);
327
328 /// Settings to apply when exporting items.
329 #[derive(Debug, Clone, Deserialize, Default)]
330 #[serde(rename_all = "snake_case")]
331 #[serde(deny_unknown_fields)]
332 #[serde(default)]
333 pub struct ExportConfig {
334 /// A list of additional items not used by exported functions to include in
335 /// the generated bindings
336 pub include: Vec<String>,
337 /// A list of items to not include in the generated bindings
338 pub exclude: Vec<String>,
339 /// Table of name conversions to apply to item names
340 pub rename: HashMap<String, String>,
341 /// Table of raw strings to prepend to the body of items.
342 pub pre_body: HashMap<String, String>,
343 /// Table of raw strings to append to the body of items.
344 pub body: HashMap<String, String>,
345 /// A prefix to add before the name of every item
346 pub prefix: Option<String>,
347 /// Types of items to generate.
348 pub item_types: Vec<ItemType>,
349 /// Whether renaming overrides or extends prefixing.
350 pub renaming_overrides_prefixing: bool,
351 /// Mangling configuration.
352 pub mangle: MangleConfig,
353 }
354
355 /// Mangling-specific configuration.
356 #[derive(Debug, Clone, Deserialize, Default)]
357 #[serde(rename_all = "snake_case")]
358 #[serde(deny_unknown_fields)]
359 #[serde(default)]
360 pub struct MangleConfig {
361 /// The rename rule to apply to the type names mangled.
362 pub rename_types: RenameRule,
363 /// Remove the underscores used for name mangling.
364 pub remove_underscores: bool,
365 }
366
367 impl ExportConfig {
368 pub(crate) fn should_generate(&self, item_type: ItemType) -> bool {
369 self.item_types.is_empty() || self.item_types.contains(&item_type)
370 }
371
372 pub(crate) fn pre_body(&self, path: &Path) -> Option<&str> {
373 self.pre_body.get(path.name()).map(|s| s.trim_matches('\n'))
374 }
375
376 pub(crate) fn post_body(&self, path: &Path) -> Option<&str> {
377 self.body.get(path.name()).map(|s| s.trim_matches('\n'))
378 }
379
380 pub(crate) fn rename(&self, item_name: &mut String) {
381 if let Some(name) = self.rename.get(item_name) {
382 *item_name = name.clone();
383 if self.renaming_overrides_prefixing {
384 return;
385 }
386 }
387 if let Some(ref prefix) = self.prefix {
388 item_name.insert_str(0, prefix);
389 }
390 }
391 }
392
393 /// Settings to apply to generated types with layout modifiers.
394 #[derive(Debug, Default, Clone, Deserialize)]
395 #[serde(rename_all = "snake_case")]
396 #[serde(deny_unknown_fields)]
397 #[serde(default)]
398 pub struct LayoutConfig {
399 /// The way to annotate C types as #[repr(packed)].
400 pub packed: Option<String>,
401 /// The way to annotate C types as #[repr(align(...))]. This is assumed to be a functional
402 /// macro which takes a single argument (the alignment).
403 pub aligned_n: Option<String>,
404 }
405
406 impl LayoutConfig {
407 pub(crate) fn ensure_safe_to_represent(&self, align: &ReprAlign) -> Result<(), String> {
408 match (align, &self.packed, &self.aligned_n) {
409 (ReprAlign::Packed, None, _) => Err("Cannot safely represent #[repr(packed)] type without configured 'packed' annotation.".to_string()),
410 (ReprAlign::Align(_), _, None) => Err("Cannot safely represent #[repr(aligned(...))] type without configured 'aligned_n' annotation.".to_string()),
411 _ => Ok(()),
412 }
413 }
414 }
415
416 /// Settings to apply to generated functions.
417 #[derive(Debug, Clone, Deserialize)]
418 #[serde(rename_all = "snake_case")]
419 #[serde(deny_unknown_fields)]
420 #[serde(default)]
421 pub struct FunctionConfig {
422 /// Optional text to output before each function declaration
423 pub prefix: Option<String>,
424 /// Optional text to output after each function declaration
425 pub postfix: Option<String>,
426 /// The way to annotation this function as #[must_use]
427 pub must_use: Option<String>,
428 /// The style to layout the args
429 pub args: Layout,
430 /// The rename rule to apply to function args
431 pub rename_args: RenameRule,
432 /// An optional macro to use when generating Swift function name attributes
433 pub swift_name_macro: Option<String>,
434 /// Sort key for functions
435 pub sort_by: Option<SortKey>,
436 /// Optional text to output after functions which return `!`.
437 pub no_return: Option<String>,
438 }
439
440 impl Default for FunctionConfig {
441 fn default() -> FunctionConfig {
442 FunctionConfig {
443 prefix: None,
444 postfix: None,
445 must_use: None,
446 args: Layout::Auto,
447 rename_args: RenameRule::None,
448 swift_name_macro: None,
449 sort_by: None,
450 no_return: None,
451 }
452 }
453 }
454
455 impl FunctionConfig {
456 pub(crate) fn prefix(&self, annotations: &AnnotationSet) -> Option<String> {
457 if let Some(x) = annotations.atom("prefix") {
458 return x;
459 }
460 self.prefix.clone()
461 }
462
463 pub(crate) fn postfix(&self, annotations: &AnnotationSet) -> Option<String> {
464 if let Some(x) = annotations.atom("postfix") {
465 return x;
466 }
467 self.postfix.clone()
468 }
469 }
470
471 /// Settings to apply to generated structs.
472 #[derive(Debug, Default, Clone, Deserialize)]
473 #[serde(rename_all = "snake_case")]
474 #[serde(deny_unknown_fields)]
475 #[serde(default)]
476 pub struct StructConfig {
477 /// The rename rule to apply to the name of struct fields
478 pub rename_fields: RenameRule,
479 /// Whether to generate a constructor for the struct (which takes
480 /// arguments to initialize all the members)
481 pub derive_constructor: bool,
482 /// Whether to generate a piecewise equality operator
483 pub derive_eq: bool,
484 /// Whether to generate a piecewise inequality operator
485 pub derive_neq: bool,
486 /// Whether to generate a less than operator on structs with one field
487 pub derive_lt: bool,
488 /// Whether to generate a less than or equal to operator on structs with one field
489 pub derive_lte: bool,
490 /// Whether to generate a greater than operator on structs with one field
491 pub derive_gt: bool,
492 /// Whether to generate a greater than or equal to operator on structs with one field
493 pub derive_gte: bool,
494 /// Whether to generate a ostream serializer for the struct
495 pub derive_ostream: bool,
496 /// Whether associated constants should be in the body. Only applicable to
497 /// non-transparent structs, and in C++-only.
498 pub associated_constants_in_body: bool,
499 /// The way to annotate this struct as #[must_use].
500 pub must_use: Option<String>,
501 }
502
503 impl StructConfig {
504 pub(crate) fn derive_constructor(&self, annotations: &AnnotationSet) -> bool {
505 if let Some(x) = annotations.bool("derive-constructor") {
506 return x;
507 }
508 self.derive_constructor
509 }
510 pub(crate) fn derive_eq(&self, annotations: &AnnotationSet) -> bool {
511 if let Some(x) = annotations.bool("derive-eq") {
512 return x;
513 }
514 self.derive_eq
515 }
516 pub(crate) fn derive_neq(&self, annotations: &AnnotationSet) -> bool {
517 if let Some(x) = annotations.bool("derive-neq") {
518 return x;
519 }
520 self.derive_neq
521 }
522 pub(crate) fn derive_lt(&self, annotations: &AnnotationSet) -> bool {
523 if let Some(x) = annotations.bool("derive-lt") {
524 return x;
525 }
526 self.derive_lt
527 }
528 pub(crate) fn derive_lte(&self, annotations: &AnnotationSet) -> bool {
529 if let Some(x) = annotations.bool("derive-lte") {
530 return x;
531 }
532 self.derive_lte
533 }
534 pub(crate) fn derive_gt(&self, annotations: &AnnotationSet) -> bool {
535 if let Some(x) = annotations.bool("derive-gt") {
536 return x;
537 }
538 self.derive_gt
539 }
540 pub(crate) fn derive_gte(&self, annotations: &AnnotationSet) -> bool {
541 if let Some(x) = annotations.bool("derive-gte") {
542 return x;
543 }
544 self.derive_gte
545 }
546 pub(crate) fn derive_ostream(&self, annotations: &AnnotationSet) -> bool {
547 if let Some(x) = annotations.bool("derive-ostream") {
548 return x;
549 }
550 self.derive_ostream
551 }
552 }
553
554 /// Settings to apply to generated enums.
555 #[derive(Debug, Clone, Deserialize)]
556 #[serde(rename_all = "snake_case")]
557 #[serde(deny_unknown_fields)]
558 #[serde(default)]
559 pub struct EnumConfig {
560 /// The rename rule to apply to the name of enum variants
561 pub rename_variants: RenameRule,
562 /// The rename rule to apply to the names of the union fields in C/C++
563 /// generated from the Rust enum. Applied before rename_variants
564 /// rename rule. Defaults to SnakeCase.
565 pub rename_variant_name_fields: RenameRule,
566 /// Whether to add a `Sentinel` value at the end of every enum
567 /// This is useful in Gecko for IPC serialization
568 pub add_sentinel: bool,
569 /// Whether the enum variants should be prefixed with the enum name
570 pub prefix_with_name: bool,
571 /// Whether to generate static `::X(..)` constructors and `IsX()`
572 /// methods for tagged enums.
573 pub derive_helper_methods: bool,
574 /// Whether to generate `AsX() const` methods for tagged enums.
575 pub derive_const_casts: bool,
576 /// Whether to generate `AsX()` methods for tagged enums.
577 pub derive_mut_casts: bool,
578 /// The name of the macro to use for `derive_{const,mut}casts`. If custom, you're
579 /// responsible to provide the necessary header, otherwise `assert` will be
580 /// used, and `<cassert>` will be included.
581 pub cast_assert_name: Option<String>,
582 /// The way to annotation this enum as #[must_use].
583 pub must_use: Option<String>,
584 /// Whether to generate destructors of tagged enums.
585 pub derive_tagged_enum_destructor: bool,
586 /// Whether to generate copy-constructors of tagged enums.
587 pub derive_tagged_enum_copy_constructor: bool,
588 /// Whether to generate copy-assignment operators of tagged enums.
589 ///
590 /// This is only generated if a copy constructor for the same tagged enum is
591 /// generated as well.
592 pub derive_tagged_enum_copy_assignment: bool,
593 /// Whether to generate a ostream serializer for the struct
594 pub derive_ostream: bool,
595 /// Declare the enum as an enum class.
596 /// Only relevant when targeting C++.
597 pub enum_class: bool,
598 /// Whether to generate empty, private default-constructors for tagged
599 /// enums.
600 pub private_default_tagged_enum_constructor: bool,
601 }
602
603 impl Default for EnumConfig {
604 fn default() -> EnumConfig {
605 EnumConfig {
606 rename_variants: RenameRule::None,
607 rename_variant_name_fields: RenameRule::SnakeCase,
608 add_sentinel: false,
609 prefix_with_name: false,
610 derive_helper_methods: false,
611 derive_const_casts: false,
612 derive_mut_casts: false,
613 cast_assert_name: None,
614 must_use: None,
615 derive_tagged_enum_destructor: false,
616 derive_tagged_enum_copy_constructor: false,
617 derive_tagged_enum_copy_assignment: false,
618 derive_ostream: false,
619 enum_class: true,
620 private_default_tagged_enum_constructor: false,
621 }
622 }
623 }
624
625 impl EnumConfig {
626 pub(crate) fn add_sentinel(&self, annotations: &AnnotationSet) -> bool {
627 if let Some(x) = annotations.bool("add-sentinel") {
628 return x;
629 }
630 self.add_sentinel
631 }
632 pub(crate) fn derive_helper_methods(&self, annotations: &AnnotationSet) -> bool {
633 if let Some(x) = annotations.bool("derive-helper-methods") {
634 return x;
635 }
636 self.derive_helper_methods
637 }
638 pub(crate) fn derive_const_casts(&self, annotations: &AnnotationSet) -> bool {
639 if let Some(x) = annotations.bool("derive-const-casts") {
640 return x;
641 }
642 self.derive_const_casts
643 }
644 pub(crate) fn derive_mut_casts(&self, annotations: &AnnotationSet) -> bool {
645 if let Some(x) = annotations.bool("derive-mut-casts") {
646 return x;
647 }
648 self.derive_mut_casts
649 }
650 pub(crate) fn derive_tagged_enum_destructor(&self, annotations: &AnnotationSet) -> bool {
651 if let Some(x) = annotations.bool("derive-tagged-enum-destructor") {
652 return x;
653 }
654 self.derive_tagged_enum_destructor
655 }
656 pub(crate) fn derive_tagged_enum_copy_constructor(&self, annotations: &AnnotationSet) -> bool {
657 if let Some(x) = annotations.bool("derive-tagged-enum-copy-constructor") {
658 return x;
659 }
660 self.derive_tagged_enum_copy_constructor
661 }
662 pub(crate) fn derive_tagged_enum_copy_assignment(&self, annotations: &AnnotationSet) -> bool {
663 if let Some(x) = annotations.bool("derive-tagged-enum-copy-assignment") {
664 return x;
665 }
666 self.derive_tagged_enum_copy_assignment
667 }
668 pub(crate) fn derive_ostream(&self, annotations: &AnnotationSet) -> bool {
669 if let Some(x) = annotations.bool("derive-ostream") {
670 return x;
671 }
672 self.derive_ostream
673 }
674 pub(crate) fn enum_class(&self, annotations: &AnnotationSet) -> bool {
675 if let Some(x) = annotations.bool("enum-class") {
676 return x;
677 }
678 self.enum_class
679 }
680 pub(crate) fn private_default_tagged_enum_constructor(
681 &self,
682 annotations: &AnnotationSet,
683 ) -> bool {
684 if let Some(x) = annotations.bool("private-default-tagged-enum-constructor") {
685 return x;
686 }
687 self.private_default_tagged_enum_constructor
688 }
689 }
690
691 /// Settings to apply to generated constants.
692 #[derive(Debug, Clone, Deserialize)]
693 #[serde(rename_all = "snake_case")]
694 #[serde(deny_unknown_fields)]
695 #[serde(default)]
696 pub struct ConstantConfig {
697 /// Whether a generated constant can be a static const in C++ mode.
698 pub allow_static_const: bool,
699 /// Whether a generated constant should be constexpr in C++ mode.
700 pub allow_constexpr: bool,
701 /// Sort key for constants
702 pub sort_by: Option<SortKey>,
703 }
704
705 impl Default for ConstantConfig {
706 fn default() -> ConstantConfig {
707 ConstantConfig {
708 allow_static_const: true,
709 allow_constexpr: true,
710 sort_by: None,
711 }
712 }
713 }
714
715 /// Settings for custom macro expansion.
716 #[derive(Debug, Clone, Deserialize, Default)]
717 #[serde(rename_all = "snake_case")]
718 #[serde(deny_unknown_fields)]
719 #[serde(default)]
720 pub struct MacroExpansionConfig {
721 /// Whether the `bitflags` macro should be expanded.
722 pub bitflags: bool,
723 }
724
725 /// Controls which Cargo profile is used for macro expansion.
726 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
727 pub enum Profile {
728 Debug,
729 Release,
730 }
731
732 impl FromStr for Profile {
733 type Err = String;
734
735 fn from_str(s: &str) -> Result<Profile, Self::Err> {
736 match s {
737 "debug" | "Debug" => Ok(Profile::Debug),
738 "release" | "Release" => Ok(Profile::Release),
739 _ => Err(format!("Unrecognized Profile: '{}'.", s)),
740 }
741 }
742 }
743
744 deserialize_enum_str!(Profile);
745
746 /// Settings to apply when running `rustc -Zunpretty=expanded`
747 #[derive(Debug, Clone, Deserialize)]
748 #[serde(rename_all = "snake_case")]
749 #[serde(deny_unknown_fields)]
750 #[serde(default)]
751 pub struct ParseExpandConfig {
752 /// The names of crates to parse with `rustc -Zunpretty=expanded`
753 pub crates: Vec<String>,
754 /// Whether to enable all the features when expanding.
755 pub all_features: bool,
756 /// Whether to use the default feature set when expanding.
757 pub default_features: bool,
758 /// List of features to use when expanding. Combines with `default_features` like in
759 /// `Cargo.toml`.
760 pub features: Option<Vec<String>>,
761 /// Controls whether or not to pass `--release` when expanding.
762 pub profile: Profile,
763 }
764
765 impl Default for ParseExpandConfig {
766 fn default() -> ParseExpandConfig {
767 ParseExpandConfig {
768 crates: Vec::new(),
769 all_features: false,
770 default_features: true,
771 features: None,
772 profile: Profile::Debug,
773 }
774 }
775 }
776
777 // Backwards-compatibility deserializer for ParseExpandConfig. This allows accepting both the
778 // simple `expand = ["crate"]` and the more complex `expand = {"crates": ["crate"],
779 // "default_features": false}` format for the `expand` key.
780 //
781 // Note that one (major) difference between the two forms is that, for backwards-compatibility
782 // reasons, the `expand = ["crate"]` form will enable the `--all-features` flag by default while
783 // the `expand = {"crates": ["crate"]}` form will use the default feature set by default.
784 fn retrocomp_parse_expand_config_deserialize<'de, D: Deserializer<'de>>(
785 deserializer: D,
786 ) -> Result<ParseExpandConfig, D::Error> {
787 struct ParseExpandVisitor;
788
789 impl<'de> Visitor<'de> for ParseExpandVisitor {
790 type Value = ParseExpandConfig;
791
792 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
793 formatter.write_str("a map or sequence of string")
794 }
795
796 fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
797 let crates =
798 <Vec<String> as Deserialize>::deserialize(SeqAccessDeserializer::new(seq))?;
799 Ok(ParseExpandConfig {
800 crates,
801 all_features: true,
802 default_features: true,
803 features: None,
804 profile: Profile::Debug,
805 })
806 }
807
808 fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
809 <ParseExpandConfig as Deserialize>::deserialize(MapAccessDeserializer::new(map))
810 }
811 }
812
813 deserializer.deserialize_any(ParseExpandVisitor)
814 }
815
816 /// Settings to apply when parsing.
817 #[derive(Debug, Default, Clone, Deserialize)]
818 #[serde(rename_all = "snake_case")]
819 #[serde(deny_unknown_fields)]
820 #[serde(default)]
821 pub struct ParseConfig {
822 /// Whether to parse dependencies when generating bindings. When this is true,
823 /// each dependent crate is found using a combination of `cargo metadata` and
824 /// `Cargo.lock`. To further control this behavior, crates can be whitelisted or
825 /// blacklisted using `include` and `exclude` respectively. Additionally in cases
826 /// where crates have types to expose in bindings hidden in macros, a crate can
827 /// be marked in `expand` and `cargo expand` will be used to expand the macros
828 /// before parsing. A crate marked in `expand` doesn't need to be added to any
829 /// whitelist.
830 pub parse_deps: bool,
831 /// An optional whitelist of names of crates to parse
832 pub include: Option<Vec<String>>,
833 /// The names of crates to not parse
834 pub exclude: Vec<String>,
835 /// The configuration options for `rustc -Zunpretty=expanded`
836 #[serde(deserialize_with = "retrocomp_parse_expand_config_deserialize")]
837 pub expand: ParseExpandConfig,
838 /// Whether to use a new temporary target directory when running `rustc -Zunpretty=expanded`.
839 /// This may be required for some build processes.
840 pub clean: bool,
841 /// List of crate names which generate consts, statics, and fns. By default
842 /// no dependent crates generate them.
843 pub extra_bindings: Vec<String>,
844 }
845
846 impl ParseConfig {
847 pub(crate) fn should_generate_top_level_item(
848 &self,
849 crate_name: &str,
850 binding_crate_name: &str,
851 ) -> bool {
852 if crate_name == binding_crate_name {
853 // Always generate items for the binding crate.
854 return true;
855 }
856
857 self.extra_bindings.iter().any(|dep| dep == crate_name)
858 }
859 }
860
861 /// Settings to apply to pointers
862 #[derive(Debug, Clone, Default, Deserialize)]
863 #[serde(rename_all = "snake_case")]
864 #[serde(deny_unknown_fields)]
865 #[serde(default)]
866 pub struct PtrConfig {
867 /// Optional attribute to apply to pointers that are required to not be null
868 pub non_null_attribute: Option<String>,
869 }
870
871 /// Settings specific to Cython bindings.
872 #[derive(Debug, Clone, Default, Deserialize)]
873 #[serde(rename_all = "snake_case")]
874 #[serde(deny_unknown_fields)]
875 #[serde(default)]
876 pub struct CythonConfig {
877 /// Header specified in the top level `cdef extern from header:` declaration.
878 pub header: Option<String>,
879 /// `from module cimport name1, name2, ...` declarations added in the same place
880 /// where you'd get includes in C.
881 pub cimports: BTreeMap<String, Vec<String>>,
882 }
883
884 /// A collection of settings to customize the generated bindings.
885 #[derive(Debug, Clone, Deserialize)]
886 #[serde(rename_all = "snake_case")]
887 #[serde(deny_unknown_fields)]
888 #[serde(default)]
889 pub struct Config {
890 /// Optional text to output at the beginning of the file
891 pub header: Option<String>,
892 /// A list of additional includes to put at the beginning of the generated header
893 pub includes: Vec<String>,
894 /// A list of additional system includes to put at the beginning of the generated header
895 pub sys_includes: Vec<String>,
896 /// Optional verbatim code added after the include blocks
897 pub after_includes: Option<String>,
898 /// Optional text to output at the end of the file
899 pub trailer: Option<String>,
900 /// Optional name to use for an include guard
901 pub include_guard: Option<String>,
902 /// Add a `#pragma once` guard
903 pub pragma_once: bool,
904 /// Generates no includes at all. Overrides all other include options
905 ///
906 /// This option is useful when using cbindgen with tools such as python's cffi which
907 /// doesn't understand include directives
908 pub no_includes: bool,
909 /// Optional text to output at major sections to deter manual editing
910 pub autogen_warning: Option<String>,
911 /// Include a comment with the version of cbindgen used to generate the file
912 pub include_version: bool,
913 /// An optional name for the root namespace. Only applicable when language="C++"
914 pub namespace: Option<String>,
915 /// An optional list of namespaces. Only applicable when language="C++"
916 pub namespaces: Option<Vec<String>>,
917 /// An optional list of namespaces to declare as using. Only applicable when language="C++"
918 pub using_namespaces: Option<Vec<String>>,
919 /// The style to use for braces
920 pub braces: Braces,
921 /// The preferred length of a line, used for auto breaking function arguments
922 pub line_length: usize,
923 /// The amount of spaces in a tab
924 pub tab_width: usize,
925 /// The type of line endings to generate
926 pub line_endings: LineEndingStyle,
927 /// The language to output bindings for
928 pub language: Language,
929 /// Include preprocessor defines in C bindings to ensure C++ compatibility
930 pub cpp_compat: bool,
931 /// The style to declare structs, enums and unions in for C
932 pub style: Style,
933 /// Default sort key for functions and constants.
934 pub sort_by: SortKey,
935 /// If this option is true `usize` and `isize` will be converted into `size_t` and `ptrdiff_t`
936 /// instead of `uintptr_t` and `intptr_t` respectively.
937 pub usize_is_size_t: bool,
938 /// The configuration options for parsing
939 pub parse: ParseConfig,
940 /// The configuration options for exporting
941 pub export: ExportConfig,
942 /// The configuration options for macros.
943 pub macro_expansion: MacroExpansionConfig,
944 /// The configuration options for type layouts.
945 pub layout: LayoutConfig,
946 /// The configuration options for functions
947 #[serde(rename = "fn")]
948 pub function: FunctionConfig,
949 /// The configuration options for structs
950 #[serde(rename = "struct")]
951 pub structure: StructConfig,
952 /// The configuration options for enums
953 #[serde(rename = "enum")]
954 pub enumeration: EnumConfig,
955 /// The configuration options for constants
956 #[serde(rename = "const")]
957 pub constant: ConstantConfig,
958 /// Preprocessor defines to use when generating #ifdef's for #[cfg]
959 pub defines: HashMap<String, String>,
960 /// Include doc comments from Rust as documentation
961 pub documentation: bool,
962 /// How documentation comments should be styled.
963 pub documentation_style: DocumentationStyle,
964 /// How much of the documentation should be output for each item.
965 pub documentation_length: DocumentationLength,
966 /// Configuration options for pointers
967 #[serde(rename = "ptr")]
968 pub pointer: PtrConfig,
969 /// Only download sources for dependencies needed for the target platform.
970 ///
971 /// By default, cbindgen will fetch sources for dependencies used on any platform so that if a
972 /// type is defined in terms of a type from a dependency on another target (probably behind a
973 /// `#[cfg]`), cbindgen will be able to generate the appropriate binding as it can see the
974 /// nested type's definition. However, this makes calling cbindgen slower, as it may have to
975 /// download a number of additional dependencies.
976 ///
977 /// As an example, consider this Cargo.toml:
978 ///
979 /// ```toml
980 /// [target.'cfg(windows)'.dependencies]
981 /// windows = "0.7"
982 /// ```
983 ///
984 /// with this declaration in one of the `.rs` files that cbindgen is asked to generate bindings
985 /// for:
986 ///
987 /// ```rust,ignore
988 /// #[cfg(windows)]
989 /// pub struct Error(windows::ErrorCode);
990 /// ```
991 ///
992 /// With the default value (`false`), cbindgen will download the `windows` dependency even when
993 /// not compiling for Windows, and will thus be able to generate the binding for `Error`
994 /// (behind a `#define`).
995 ///
996 /// If this value is instead to `true`, cbindgen will _not_ download the `windows` dependency
997 /// if it's not compiling for Windows, but will also fail to generate a Windows binding for
998 /// `Error` as it does not know the definition for `ErrorCode`.
999 ///
1000 /// The target can be chosen via the `TARGET` environment variable (if used
1001 /// via the CLI, when ran from a build script cargo sets this variable
1002 /// appropriately).
1003 pub only_target_dependencies: bool,
1004 /// Configuration options specific to Cython.
1005 pub cython: CythonConfig,
1006 #[serde(skip)]
1007 pub(crate) config_path: Option<StdPathBuf>,
1008 }
1009
1010 impl Default for Config {
1011 fn default() -> Config {
1012 Config {
1013 header: None,
1014 includes: Vec::new(),
1015 sys_includes: Vec::new(),
1016 after_includes: None,
1017 trailer: None,
1018 include_guard: None,
1019 pragma_once: false,
1020 autogen_warning: None,
1021 include_version: false,
1022 no_includes: false,
1023 namespace: None,
1024 namespaces: None,
1025 using_namespaces: None,
1026 braces: Braces::SameLine,
1027 line_length: 100,
1028 tab_width: 2,
1029 line_endings: LineEndingStyle::default(),
1030 language: Language::Cxx,
1031 cpp_compat: false,
1032 style: Style::default(),
1033 usize_is_size_t: false,
1034 sort_by: SortKey::None,
1035 macro_expansion: Default::default(),
1036 parse: ParseConfig::default(),
1037 export: ExportConfig::default(),
1038 layout: LayoutConfig::default(),
1039 function: FunctionConfig::default(),
1040 structure: StructConfig::default(),
1041 enumeration: EnumConfig::default(),
1042 constant: ConstantConfig::default(),
1043 defines: HashMap::new(),
1044 documentation: true,
1045 documentation_style: DocumentationStyle::Auto,
1046 documentation_length: DocumentationLength::Full,
1047 pointer: PtrConfig::default(),
1048 only_target_dependencies: false,
1049 cython: CythonConfig::default(),
1050 config_path: None,
1051 }
1052 }
1053 }
1054
1055 impl Config {
1056 pub(crate) fn cpp_compatible_c(&self) -> bool {
1057 self.language == Language::C && self.cpp_compat
1058 }
1059
1060 pub(crate) fn include_guard(&self) -> Option<&str> {
1061 if self.language == Language::Cython {
1062 None
1063 } else {
1064 self.include_guard.as_deref()
1065 }
1066 }
1067
1068 pub(crate) fn includes(&self) -> &[String] {
1069 if self.language == Language::Cython {
1070 &[]
1071 } else {
1072 &self.includes
1073 }
1074 }
1075
1076 pub(crate) fn sys_includes(&self) -> &[String] {
1077 if self.language == Language::Cython {
1078 &[]
1079 } else {
1080 &self.sys_includes
1081 }
1082 }
1083
1084 pub fn from_file<P: AsRef<StdPath>>(file_name: P) -> Result<Config, String> {
1085 let config_text = fs::read_to_string(file_name.as_ref()).map_err(|_| {
1086 format!(
1087 "Couldn't open config file: {}.",
1088 file_name.as_ref().display()
1089 )
1090 })?;
1091
1092 let mut config = toml::from_str::<Config>(&config_text)
1093 .map_err(|e| format!("Couldn't parse config file: {}.", e))?;
1094 config.config_path = Some(StdPathBuf::from(file_name.as_ref()));
1095 Ok(config)
1096 }
1097
1098 pub fn from_root_or_default<P: AsRef<StdPath>>(root: P) -> Config {
1099 let c = root.as_ref().join("cbindgen.toml");
1100
1101 if c.exists() {
1102 Config::from_file(c).unwrap()
1103 } else {
1104 Config::default()
1105 }
1106 }
1107 }