Debian Codegraph @

.cargo/vendor/cbindgen/docs.md

raw
1 # cbindgen User Guide
2
3 cbindgen creates C/C++11 headers for Rust libraries which expose a public C API.
4
5 While you could do this by hand, it's not a particularly good use of your time. It's also much more likely to be error-prone than machine-generated headers that are based on your actual Rust code. The cbindgen developers have also worked closely with the developers of Rust to ensure that the headers we generate reflect actual guarantees about Rust's type layout and ABI.
6
7 C++ headers are nice because we can use operator overloads, constructors, enum classes, and templates to make the API more ergonomic and Rust-like. C headers are nice because you can be more confident that whoever you're interoperating with can handle them. With cbindgen *you don't need to choose*! You can just tell it to emit both from the same Rust library.
8
9 There are two ways to use cbindgen: as a standalone program, or as a library (presumably in your build.rs).
10 There isn't really much practical difference, because cbindgen is a simple rust library with no interesting dependencies. Using it as a program means people building your software will need it installed. Using it in your library means people may have to build cbindgen more frequently (e.g. every time they update their rust compiler).
11
12 It's worth noting that the development of cbindgen has been largely adhoc, as features have been added to support the usecases of the maintainers. This means cbindgen may randomly fail to support some particular situation simply because no one has put in the effort to handle it yet. [Please file an issue if you run into such a situation][file-it]. Although since we all have other jobs, you might need to do the implementation work too :)
13
14
15
16
17
18 # Quick Start
19
20 To install cbindgen, you just need to run
21
22 ```text
23 cargo install --force cbindgen
24 ```
25
26 (--force just makes it update to the latest cbindgen if it's already installed)
27
28 To use cbindgen you need two things:
29
30 * A configuration (cbindgen.toml, which can be empty to start)
31 * A Rust crate with a public C API
32
33 Then all you need to do is run it:
34
35 ```text
36 cbindgen --config cbindgen.toml --crate my_rust_library --output my_header.h
37 ```
38
39 This produces a header file for C++. For C, add the `--lang c` switch. \
40 `cbindgen` also supports generation of [Cython](https://cython.org) bindings,
41 use `--lang cython` for that.
42
43 See `cbindgen --help` for more options.
44
45 [Get a template cbindgen.toml here.](template.toml)
46
47
48
49 ## build.rs
50
51 If you don't want to use cbindgen as an application, here's an example build.rs script:
52
53 ```rust
54 extern crate cbindgen;
55
56 use std::env;
57
58 fn main() {
59 let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
60
61 cbindgen::Builder::new()
62 .with_crate(crate_dir)
63 .generate()
64 .expect("Unable to generate bindings")
65 .write_to_file("bindings.h");
66 }
67 ```
68
69 You can add configuration options using the [`Builder`](https://docs.rs/cbindgen/*/cbindgen/struct.Builder.html#methods) interface.
70
71 Be sure to add the following section to your Cargo.toml:
72
73 ```
74 [build-dependencies]
75 cbindgen = "0.24.0"
76 ```
77
78 If you'd like to use a `build.rs` script with a `cbindgen.toml`, consider using [`cbindgen::generate()`](https://docs.rs/cbindgen/*/cbindgen/fn.generate.html) instead.
79
80
81
82
83
84 # Writing Your C API
85
86 cbindgen has a simple but effective strategy. It walks through your crate looking for:
87
88 * `#[no_mangle] pub extern fn` ("functions")
89 * `#[no_mangle] pub static` ("globals")
90 * `pub const` ("constants")
91
92 and generates a header declaring those items. But to declare those items, it needs to also be able to describe the layout and ABI of the types that appear in their signatures. So it will also spider through your crate (and optionally its dependencies) to try to find the definitions of every type used in your public API.
93
94 > 🚨 NOTE: A major limitation of cbindgen is that it does not understand Rust's module system or namespacing. This means that if cbindgen sees that it needs the definition for `MyType` and there exists two things in your project with the type name `MyType`, it won't know what to do. Currently, cbindgen's behaviour is unspecified if this happens. However this may be ok if they have [different cfgs][section-cfgs].
95
96 If a type is determined to have a guaranteed layout, a full definition will be emitted in the header. If the type doesn't have a guaranteed layout, only a forward declaration will be emitted. This may be fine if the type is intended to be passed around opaquely and by reference.
97
98
99
100
101 # Examples
102
103 🚧 🏗
104
105 It would be really nice to have some curated and clean examples, but we don't have those yet.
106
107 [The README has some useful links though](README.md#examples).
108
109
110
111 # Supported Types
112
113 Most things in Rust don't have a guaranteed layout by default. In most cases this is nice because it enables layout to be optimized in the majority of cases where type layout isn't that interesting. However this is problematic for our purposes. Thankfully Rust lets us opt into guaranteed layouts with the `repr` attribute.
114
115 You can learn about all of the different repr attributes [by reading Rust's reference][reference], but here's a quick summary:
116
117 * `#[repr(C)]`: give this struct/union/enum the same layout and ABI C would
118 * `#[repr(u8, u16, ... etc)]`: give this enum the same layout and ABI as the given integer type
119 * `#[repr(transparent)]`: give this single-field struct the same ABI as its field (useful for newtyping integers but keeping the integer ABI)
120
121 cbindgen supports the `#[repr(align(N))]` and `#[repr(packed)]` attributes, but currently does not support `#[repr(packed(N))]`.
122
123 cbindgen also supports using `repr(C)`/`repr(u8)` on non-C-like enums (enums with fields). This gives a C-compatible tagged union layout, as [defined by this RFC 2195][really-tagged-unions]. `repr(C)` will give a simpler layout that is perhaps more intuitive, while `repr(u8)` will produce a more compact layout.
124
125 If you ensure everything has a guaranteed repr, then cbindgen will generate definitions for:
126
127 * struct (named-style or tuple-style)
128 * enum (fieldless or with fields)
129 * union
130 * type
131 * `[T; n]` (arrays always have a guaranteed C-compatible layout)
132 * `&T`, `&mut T`, `*const T`, `*mut T`, `Option<&T>`, `Option<&mut T>` (all have the same pointer ABI)
133 * `fn()` (as an actual function pointer)
134 * `bitflags! { ... }` (if macro_expansion.bitflags is enabled)
135
136 structs, enums, unions, and type aliases may be generic, although certain generic substitutions may fail to resolve under certain configurations. In C mode generics are resolved through monomorphization and mangling, while in C++ mode generics are resolved with templates. cbindgen cannot support generic functions, as they do not actually have a single defined symbol.
137
138 cbindgen sadly cannot ever support anonymous tuples `(A, B, ...)`, as there is no way to guarantee their layout. You must use a tuple struct.
139
140 cbindgen also cannot support wide pointers like `&dyn Trait` or `&[T]`, as their layout and ABI is not guaranteed. In the case of slices you can at least decompose them into a pointer and length, and reconstruct them with `slice::from_raw_parts`.
141
142 If cbindgen determines that a type is zero-sized, it will erase all references to that type (so fields of that type simply won't be emitted). This won't work if that type appears as a function argument because C, C++, and Rust all have different definitions of what it means for a type to be empty.
143
144 Don't use the `[u64; 0]` trick to over-align a struct, we don't support this.
145
146 cbindgen contains the following hardcoded mappings (again completely ignoring namespacing, literally just looking at the name of the type):
147
148
149
150
151 ## std types
152
153 * bool => bool
154 * char => uint32_t
155 * u8 => uint8_t
156 * u16 => uint16_t
157 * u32 => uint32_t
158 * u64 => uint64_t
159 * usize => uintptr_t
160 * i8 => int8_t
161 * i16 => int16_t
162 * i32 => int32_t
163 * i64 => int64_t
164 * isize => intptr_t
165 * f32 => float
166 * f64 => double
167 * VaList => va_list
168 * RawFd => int
169 * PhantomData => *evaporates*, can only appear as the field of a type
170 * PhantomPinned => *evaporates*, can only appear as the field of a type
171 * () => *evaporates*, can only appear as the field of a type
172 * MaybeUninit<T>, ManuallyDrop<T>, and Pin<T> => T
173
174
175
176
177 ## libc types
178
179 * c_void => void
180 * c_char => char
181 * c_schar => signed char
182 * c_uchar => unsigned char
183 * c_float => float
184 * c_double => double
185 * c_short => short
186 * c_int => int
187 * c_long => long
188 * c_longlong => long long
189 * c_ushort => unsigned short
190 * c_uint => unsigned int
191 * c_ulong => unsigned long
192 * c_ulonglong => unsigned long long
193
194
195
196 ## stdint types
197
198 * uint8_t => uint8_t
199 * uint16_t => uint16_t
200 * uint32_t => uint32_t
201 * uint64_t => uint64_t
202 * uintptr_t => uintptr_t
203 * size_t => size_t
204 * int8_t => int8_t
205 * int16_t => int16_t
206 * int32_t => int32_t
207 * int64_t => int64_t
208 * intptr_t => intptr_t
209 * ssize_t => ssize_t
210 * ptrdiff_t => ptrdiff_t
211
212
213
214
215
216
217 # Configuring Your Header
218
219 cbindgen supports several different options for configuring the output of your header, including target language, styling, mangling, prefixing, includes, and defines.
220
221
222
223
224
225 ## Defines and Cfgs
226
227 As cbindgen spiders through your crate, it will make note of all the cfgs it found on the path to every item. If it finds multiple declarations that share a single name but have different cfgs, it will then try to emit every version it found wrapped in defines that correspond to those cfgs. In this way platform-specific APIs or representations can be properly supported.
228
229 However cbindgen has no way of knowing how you want to map those cfgs to defines. You will need to use the `[defines]` section in your cbindgen.toml to specify all the different mappings. It natively understands concepts like any() and all(), so you only need to tell it how you want to translate base concepts like `target_os = "freebsd"` or `feature = "serde"`.
230
231 Note that because cbindgen just parses the source of your crate, you mostly don't need to worry about what crate features or what platform you're targetting. Every possible configuration should be visible to the parser. Our primitive mappings should also be completely platform agnostic (i32 is int32_t regardless of your target).
232
233 While modules within a crate form a tree with uniquely defined paths to each item, and therefore uniquely defined cfgs for those items, dependencies do not. If you depend on a crate in multiple ways, and those ways produce different cfgs, one of them will be arbitrarily chosen for any types found in that crate.
234
235
236
237
238 ## Annotations
239
240 While output configuration is primarily done through the cbindgen.toml, in some cases you need to manually override your global settings. In those cases you can add inline annotations to your types, which are doc comments that start with `cbindgen:`. Here's an example of using annotations to rename a struct's fields and opt into overloading `operator==`:
241
242 ```rust
243 /// cbindgen:field-names=[x, y]
244 /// cbindgen:derive-eq
245 #[repr(C)]
246 pub struct Point(pub f32, pub f32);
247 ```
248
249 An annotation may be a bool, string (no quotes), or list of strings. If just the annotation's name is provided, `=true` is assumed. The annotation parser is currently fairly naive and lacks any capacity for escaping, so don't try to make any strings with `=`, `,`, `[` or `]`.
250
251 Most annotations are just local overrides for identical settings in the cbindgen.toml, but a few are unique because they don't make sense in a global context. The set of supported annotation are as follows:
252
253 ### Ignore annotation
254
255 cbindgen will automatically ignore any `#[test]` or `#[cfg(test)]` item it
256 finds. You can manually ignore other stuff with the `ignore` annotation
257 attribute:
258
259 ```rust
260 pub mod my_interesting_mod;
261
262 /// cbindgen:ignore
263 pub mod my_uninteresting_mod; // This won't be scanned by cbindgen.
264 ```
265
266 ### Struct Annotations
267
268 * field-names=\[field1, field2, ...\] -- sets the names of all the fields in the output struct. These names will be output verbatim, and are not eligible for renaming.
269
270 The rest are just local overrides for the same options found in the cbindgen.toml:
271
272 * rename-all=RenameRule
273 * derive-constructor
274 * derive-eq
275 * derive-neq
276 * derive-lt
277 * derive-lte
278 * derive-gt
279 * derive-gte
280 * {eq,neq,lt,lte,gt,gte}-attributes: Takes a single identifier which will be
281 emitted before the signature of the auto-generated `operator==` / `operator!=`
282 / etc(if any). The idea is for this to be used to annotate the operator with
283 attributes, for example:
284
285 ```rust
286 /// cbindgen:eq-attributes=MY_ATTRIBUTES
287 #[repr(C)]
288 pub struct Foo { .. }
289 ```
290
291 Will generate something like:
292
293 ```
294 MY_ATTRIBUTES bool operator==(const Foo& other) const {
295 ...
296 }
297 ```
298
299 Combined with something like:
300
301 ```
302 #define MY_ATTRIBUTES [[nodiscard]]
303 ```
304
305 for example.
306
307 ### Enum Annotations
308
309 * enum-trailing-values=\[variant1, variant2, ...\] -- add the following fieldless enum variants to the end of the enum's definition. These variant names *will* have the enum's renaming rules applied.
310
311 WARNING: if any of these values are ever passed into Rust, behaviour will be Undefined. Rust does not know about them, and will assume they cannot happen.
312
313 The rest are just local overrides for the same options found in the cbindgen.toml:
314
315 * rename-all=RenameRule
316 * add-sentinel
317 * derive-helper-methods
318 * derive-const-casts
319 * derive-mut-casts
320 * derive-tagged-enum-destructor
321 * derive-tagged-enum-copy-constructor
322 * enum-class
323 * prefix-with-name
324 * private-default-tagged-enum-constructor
325 * {destructor,copy-constructor,copy-assignment}-attributes: See the description
326 of the struct attributes, these do the same for the respective generated code.
327
328 ### Enum variant annotations
329
330 These apply to both tagged and untagged enum _variants_.
331
332 * variant-{constructor,const-cast,mut-cast,is}-attributes: See the description
333 of the struct attributes. These do the same for the respective functions.
334
335 TODO: We should allow to override the `derive-{const,mut}-casts`, helper methods
336 et al. with per-variant annotations, probably.
337
338 ### Union Annotations
339
340 * field-names=\[field1, field2, ...\] -- sets the names of all the fields in the output union. These names will be output verbatim, and are not eligible for renaming.
341
342 The rest are just local overrides for the same options found in the cbindgen.toml:
343
344 * rename-all=RenameRule
345
346
347
348 ### Function Annotations
349
350 All function attributes are just local overrides for the same options found in the cbindgen.toml:
351
352 * rename-all=RenameRule
353 * prefix
354 * postfix
355 * ptrs-as-arrays=\[[ptr\_name1; array\_length1], [ptr\_name2; array\_length2], ...\] -- represents the pointer arguments of a function as arrays. Below how the mappings are performed:
356
357 ```
358 arg: *const T --> const T arg[array_length]
359 arg: *mut T ---> T arg[array_length]
360 ```
361
362 If `array_length` is not specified:
363
364 ```
365 arg: *const T --> const T arg[]
366 arg: *mut T --> T arg[]
367 ```
368
369 ## Generating Swift Bindings
370
371 In addition to parsing function names in C/C++ header files, the Swift compiler can make use of the `swift_name` attribute on functions to generate more idiomatic names for imported functions and methods.
372
373 This attribute is commonly used in Objective-C/C/C++ via the `NS_SWIFT_NAME` and `CF_SWIFT_NAME` macros.
374
375 Given configuration in the cbindgen.toml, `cbindgen` can generate these attributes for you by guessing an appropriate method signature based on the existing function name (and type, if it is a method in an `impl` block).
376
377 This is controlled by the `swift_name_macro` option in the cbindgen.toml.
378
379 ## cbindgen.toml
380
381 Most configuration happens through your cbindgen.toml file. Every value has a default (that is usually reasonable), so you can start with an empty cbindgen.toml and tweak it until you like the output you're getting.
382
383 Note that many options defined here only apply for one of C or C++. Usually it's an option specifying whether we should try to make use of a feature in C++'s type system or generate a helper method.
384
385 ```toml
386 # The language to output bindings in
387 #
388 # possible values: "C", "C++", "Cython"
389 #
390 # default: "C++"
391 language = "C"
392
393
394
395
396 # Options for wrapping the contents of the header:
397
398 # An optional string of text to output at the beginning of the generated file
399 # default: doesn't emit anything
400 header = "/* Text to put at the beginning of the generated file. Probably a license. */"
401
402 # An optional string of text to output at the end of the generated file
403 # default: doesn't emit anything
404 trailer = "/* Text to put at the end of the generated file */"
405
406 # An optional name to use as an include guard
407 # default: doesn't emit an include guard
408 include_guard = "mozilla_wr_bindings_h"
409
410 # Whether to add a `#pragma once` guard
411 # default: doesn't emit a `#pragma once`
412 pragma_once = true
413
414 # An optional string of text to output between major sections of the generated
415 # file as a warning against manual editing
416 #
417 # default: doesn't emit anything
418 autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */"
419
420 # Whether to include a comment with the version of cbindgen used to generate the file
421 # default: false
422 include_version = true
423
424 # An optional namespace to output around the generated bindings
425 # default: doesn't emit a namespace
426 namespace = "ffi"
427
428 # An optional list of namespaces to output around the generated bindings
429 # default: []
430 namespaces = ["mozilla", "wr"]
431
432 # An optional list of namespaces to declare as using with "using namespace"
433 # default: []
434 using_namespaces = ["mozilla", "wr"]
435
436 # A list of sys headers to #include (with angle brackets)
437 # default: []
438 sys_includes = ["stdio", "string"]
439
440 # A list of headers to #include (with quotes)
441 # default: []
442 includes = ["my_great_lib.h"]
443
444 # Whether cbindgen's default C/C++ standard imports should be suppressed. These
445 # imports are included by default because our generated headers tend to require
446 # them (e.g. for uint32_t). Currently, the generated imports are:
447 #
448 # * for C: <stdarg.h>, <stdbool.h>, <stdint.h>, <stdlib.h>, <uchar.h>
449 #
450 # * for C++: <cstdarg>, <cstdint>, <cstdlib>, <new>, <cassert> (depending on config)
451 #
452 # default: false
453 no_includes = false
454
455 # Whether to make a C header C++ compatible.
456 # These will wrap generated functions into a `extern "C"` block, e.g.
457 #
458 # #ifdef __cplusplus
459 # extern "C" {
460 # #endif // __cplusplus
461 #
462 # // Generated functions.
463 #
464 # #ifdef __cplusplus
465 # } // extern "C"
466 # #endif // __cplusplus
467 #
468 # If the language is not C this option won't have any effect.
469 #
470 # default: false
471 cpp_compat = false
472
473 # A list of lines to add verbatim after the includes block
474 after_includes = "#define VERSION 1"
475
476
477
478 # Code Style Options
479
480 # The style to use for curly braces
481 #
482 # possible values: "SameLine", "NextLine"
483 #
484 # default: "SameLine"
485 braces = "SameLine"
486
487 # The desired length of a line to use when formatting lines
488 # default: 100
489 line_length = 80
490
491 # The amount of spaces to indent by
492 # default: 2
493 tab_width = 3
494
495 # Include doc comments from Rust as documentation
496 documentation = true
497
498 # How the generated documentation should be commented.
499 #
500 # possible values:
501 # * "c": /* like this */
502 # * "c99": // like this
503 # * "c++": /// like this
504 # * "doxy": like C, but with leading *'s on each line
505 # * "auto": "c++" if that's the language, "doxy" otherwise
506 #
507 # default: "auto"
508 documentation_style = "doxy"
509
510 # How much of the documentation for each item is output.
511 #
512 # possible values:
513 # * "short": Only the first line.
514 # * "full": The full documentation.
515 #
516 # default: "full"
517 documentation_length = "short"
518
519
520
521
522 # Codegen Options
523
524 # When generating a C header, the kind of declaration style to use for structs
525 # or enums.
526 #
527 # possible values:
528 # * "type": typedef struct { ... } MyType;
529 # * "tag": struct MyType { ... };
530 # * "both": typedef struct MyType { ... } MyType;
531 #
532 # default: "both"
533 style = "both"
534
535 # If this option is true `usize` and `isize` will be converted into `size_t` and `ptrdiff_t`
536 # instead of `uintptr_t` and `intptr_t` respectively.
537 usize_is_size_t = true
538
539 # A list of substitutions for converting cfg's to ifdefs. cfgs which aren't
540 # defined here will just be discarded.
541 #
542 # e.g.
543 # `#[cfg(target = "freebsd")] ...`
544 # becomes
545 # `#if defined(DEFINE_FREEBSD) ... #endif`
546 [defines]
547 "target_os = freebsd" = "DEFINE_FREEBSD"
548 "feature = serde" = "DEFINE_SERDE"
549
550
551
552
553
554 [export]
555 # A list of additional items to always include in the generated bindings if they're
556 # found but otherwise don't appear to be used by the public API.
557 #
558 # default: []
559 include = ["MyOrphanStruct", "MyGreatTypeRename"]
560
561 # A list of items to not include in the generated bindings
562 # default: []
563 exclude = ["Bad"]
564
565 # A prefix to add before the name of every item
566 # default: no prefix is added
567 prefix = "CAPI_"
568
569 # Types of items that we'll generate. If empty, then all types of item are emitted.
570 #
571 # possible items: (TODO: explain these in detail)
572 # * "constants":
573 # * "globals":
574 # * "enums":
575 # * "structs":
576 # * "unions":
577 # * "typedefs":
578 # * "opaque":
579 # * "functions":
580 #
581 # default: []
582 item_types = ["enums", "structs", "opaque", "functions"]
583
584 # Whether applying rules in export.rename prevents export.prefix from applying.
585 #
586 # e.g. given this toml:
587 #
588 # [export]
589 # prefix = "capi_"
590 # [export.rename]
591 # "MyType" = "my_cool_type"
592 #
593 # You get the following results:
594 #
595 # renaming_overrides_prefixing = true:
596 # "MyType" => "my_cool_type"
597 #
598 # renaming_overrides_prefixing = false:
599 # "MyType => capi_my_cool_type"
600 #
601 # default: false
602 renaming_overrides_prefixing = true
603
604 # Table of name conversions to apply to item names (lhs becomes rhs)
605 [export.rename]
606 "MyType" = "my_cool_type"
607 "my_function" = "BetterFunctionName"
608
609 # Table of things to prepend to the body of any struct, union, or enum that has the
610 # given name. This can be used to add things like methods which don't change ABI,
611 # mark fields private, etc
612 [export.pre_body]
613 "MyType" = """
614 MyType() = delete;
615 private:
616 """
617
618 # Table of things to append to the body of any struct, union, or enum that has the
619 # given name. This can be used to add things like methods which don't change ABI.
620 [export.body]
621 "MyType" = """
622 void cppMethod() const;
623 """
624
625 # Configuration for name mangling
626 [export.mangle]
627 # Whether the types should be renamed during mangling, for example
628 # c_char -> CChar, etc.
629 rename_types = "PascalCase"
630 # Whether the underscores from the mangled name should be omitted.
631 remove_underscores = false
632
633 [layout]
634 # A string that should come before the name of any type which has been marked
635 # as `#[repr(packed)]`. For instance, "__attribute__((packed))" would be a
636 # reasonable value if targeting gcc/clang. A more portable solution would
637 # involve emitting the name of a macro which you define in a platform-specific
638 # way. e.g. "PACKED"
639 #
640 # default: `#[repr(packed)]` types will be treated as opaque, since it would
641 # be unsafe for C callers to use a incorrectly laid-out union.
642 packed = "PACKED"
643
644 # A string that should come before the name of any type which has been marked
645 # as `#[repr(align(n))]`. This string must be a function-like macro which takes
646 # a single argument (the requested alignment, `n`). For instance, a macro
647 # `#define`d as `ALIGNED(n)` in `header` which translates to
648 # `__attribute__((aligned(n)))` would be a reasonable value if targeting
649 # gcc/clang.
650 #
651 # default: `#[repr(align(n))]` types will be treated as opaque, since it
652 # could be unsafe for C callers to use a incorrectly-aligned union.
653 aligned_n = "ALIGNED"
654
655
656 [fn]
657 # An optional prefix to put before every function declaration
658 # default: no prefix added
659 prefix = "WR_START_FUNC"
660
661 # An optional postfix to put after any function declaration
662 # default: no postix added
663 postfix = "WR_END_FUNC"
664
665 # How to format function arguments
666 #
667 # possible values:
668 # * "horizontal": place all arguments on the same line
669 # * "vertical": place each argument on its own line
670 # * "auto": only use vertical if horizontal would exceed line_length
671 #
672 # default: "auto"
673 args = "horizontal"
674
675 # An optional string that should prefix function declarations which have been
676 # marked as `#[must_use]`. For instance, "__attribute__((warn_unused_result))"
677 # would be a reasonable value if targeting gcc/clang. A more portable solution
678 # would involve emitting the name of a macro which you define in a
679 # platform-specific way. e.g. "MUST_USE_FUNC"
680 # default: nothing is emitted for must_use functions
681 must_use = "MUST_USE_FUNC"
682
683 # An optional string that will be used in the attribute position for functions
684 # that don't return (that return `!` in Rust).
685 #
686 # For instance, `__attribute__((noreturn))` would be a reasonable value if
687 # targeting gcc/clang.
688 no_return = "NO_RETURN"
689
690 # An optional string that, if present, will be used to generate Swift function
691 # and method signatures for generated functions, for example "CF_SWIFT_NAME".
692 # If no such macro is available in your toolchain, you can define one using the
693 # `header` option in cbindgen.toml
694 # default: no swift_name function attributes are generated
695 swift_name_macro = "CF_SWIFT_NAME"
696
697 # A rule to use to rename function argument names. The renaming assumes the input
698 # is the Rust standard snake_case, however it accepts all the different rename_args
699 # inputs. This means many options here are no-ops or redundant.
700 #
701 # possible values (that actually do something):
702 # * "CamelCase": my_arg => myArg
703 # * "PascalCase": my_arg => MyArg
704 # * "GeckoCase": my_arg => aMyArg
705 # * "ScreamingSnakeCase": my_arg => MY_ARG
706 # * "None": apply no renaming
707 #
708 # technically possible values (that shouldn't have a purpose here):
709 # * "SnakeCase": apply no renaming
710 # * "LowerCase": apply no renaming (actually applies to_lowercase, is this bug?)
711 # * "UpperCase": same as ScreamingSnakeCase in this context
712 # * "QualifiedScreamingSnakeCase" => same as ScreamingSnakeCase in this context
713 #
714 # default: "None"
715 rename_args = "PascalCase"
716
717 # This rule specifies the order in which functions will be sorted.
718 #
719 # "Name": sort by the name of the function
720 # "None": keep order in which the functions have been parsed
721 #
722 # default: "None"
723 sort_by = "Name"
724
725 [struct]
726 # A rule to use to rename struct field names. The renaming assumes the input is
727 # the Rust standard snake_case, however it acccepts all the different rename_args
728 # inputs. This means many options here are no-ops or redundant.
729 #
730 # possible values (that actually do something):
731 # * "CamelCase": my_arg => myArg
732 # * "PascalCase": my_arg => MyArg
733 # * "GeckoCase": my_arg => mMyArg
734 # * "ScreamingSnakeCase": my_arg => MY_ARG
735 # * "None": apply no renaming
736 #
737 # technically possible values (that shouldn't have a purpose here):
738 # * "SnakeCase": apply no renaming
739 # * "LowerCase": apply no renaming (actually applies to_lowercase, is this bug?)
740 # * "UpperCase": same as ScreamingSnakeCase in this context
741 # * "QualifiedScreamingSnakeCase" => same as ScreamingSnakeCase in this context
742 #
743 # default: "None"
744 rename_fields = "PascalCase"
745
746 # An optional string that should come before the name of any struct which has been
747 # marked as `#[must_use]`. For instance, "__attribute__((warn_unused))"
748 # would be a reasonable value if targeting gcc/clang. A more portable solution
749 # would involve emitting the name of a macro which you define in a
750 # platform-specific way. e.g. "MUST_USE_STRUCT"
751 #
752 # default: nothing is emitted for must_use structs
753 must_use = "MUST_USE_STRUCT"
754
755 # Whether a Rust type with associated consts should emit those consts inside the
756 # type's body. Otherwise they will be emitted trailing and with the type's name
757 # prefixed. This does nothing if the target is C, or if
758 # [const]allow_static_const = false
759 #
760 # default: false
761 # associated_constants_in_body: false
762
763 # Whether to derive a simple constructor that takes a value for every field.
764 # default: false
765 derive_constructor = true
766
767 # Whether to derive an operator== for all structs
768 # default: false
769 derive_eq = false
770
771 # Whether to derive an operator!= for all structs
772 # default: false
773 derive_neq = false
774
775 # Whether to derive an operator< for all structs
776 # default: false
777 derive_lt = false
778
779 # Whether to derive an operator<= for all structs
780 # default: false
781 derive_lte = false
782
783 # Whether to derive an operator> for all structs
784 # default: false
785 derive_gt = false
786
787 # Whether to derive an operator>= for all structs
788 # default: false
789 derive_gte = false
790
791
792
793
794
795 [enum]
796 # A rule to use to rename enum variants, and the names of any fields those
797 # variants have. This should probably be split up into two separate options, but
798 # for now, they're the same! See the documentation for `[struct]rename_fields`
799 # for how this applies to fields. Renaming of the variant assumes that the input
800 # is the Rust standard PascalCase. In the case of QualifiedScreamingSnakeCase,
801 # it also assumed that the enum's name is PascalCase.
802 #
803 # possible values (that actually do something):
804 # * "CamelCase": MyVariant => myVariant
805 # * "SnakeCase": MyVariant => my_variant
806 # * "ScreamingSnakeCase": MyVariant => MY_VARIANT
807 # * "QualifiedScreamingSnakeCase": MyVariant => ENUM_NAME_MY_VARIANT
808 # * "LowerCase": MyVariant => myvariant
809 # * "UpperCase": MyVariant => MYVARIANT
810 # * "None": apply no renaming
811 #
812 # technically possible values (that shouldn't have a purpose for the variants):
813 # * "PascalCase": apply no renaming
814 # * "GeckoCase": apply no renaming
815 #
816 # default: "None"
817 rename_variants = "None"
818
819 # Whether an extra "sentinel" enum variant should be added to all generated enums.
820 # Firefox uses this for their IPC serialization library.
821 #
822 # WARNING: if the sentinel is ever passed into Rust, behaviour will be Undefined.
823 # Rust does not know about this value, and will assume it cannot happen.
824 #
825 # default: false
826 add_sentinel = false
827
828 # Whether enum variant names should be prefixed with the name of the enum.
829 # default: false
830 prefix_with_name = false
831
832 # Whether to emit enums using "enum class" when targeting C++.
833 # default: true
834 enum_class = true
835
836 # Whether to generate static `::MyVariant(..)` constructors and `bool IsMyVariant()`
837 # methods for enums with fields.
838 #
839 # default: false
840 derive_helper_methods = false
841
842 # Whether to generate `const MyVariant& AsMyVariant() const` methods for enums with fields.
843 # default: false
844 derive_const_casts = false
845
846 # Whether to generate `MyVariant& AsMyVariant()` methods for enums with fields
847 # default: false
848 derive_mut_casts = false
849
850 # The name of the macro/function to use for asserting `IsMyVariant()` in the body of
851 # derived `AsMyVariant()` cast methods.
852 #
853 # default: "assert" (but also causes `<cassert>` to be included by default)
854 cast_assert_name = "MOZ_RELEASE_ASSERT"
855
856 # An optional string that should come before the name of any enum which has been
857 # marked as `#[must_use]`. For instance, "__attribute__((warn_unused))"
858 # would be a reasonable value if targeting gcc/clang. A more portable solution
859 # would involve emitting the name of a macro which you define in a
860 # platform-specific way. e.g. "MUST_USE_ENUM"
861 #
862 # Note that this refers to the *output* type. That means this will not apply to an enum
863 # with fields, as it will be emitted as a struct. `[struct]must_use` will apply there.
864 #
865 # default: nothing is emitted for must_use enums
866 must_use = "MUST_USE_ENUM"
867
868 # Whether enums with fields should generate destructors. This exists so that generic
869 # enums can be properly instantiated with payloads that are C++ types with
870 # destructors. This isn't necessary for structs because C++ has rules to
871 # automatically derive the correct constructors and destructors for those types.
872 #
873 # Care should be taken with this option, as Rust and C++ cannot
874 # properly interoperate with eachother's notions of destructors. Also, this may
875 # change the ABI for the type. Either your destructor-full enums must live
876 # exclusively within C++, or they must only be passed by-reference between
877 # C++ and Rust.
878 #
879 # default: false
880 derive_tagged_enum_destructor = false
881
882 # Whether enums with fields should generate copy-constructor. See the discussion on
883 # derive_tagged_enum_destructor for why this is both useful and very dangerous.
884 #
885 # default: false
886 derive_tagged_enum_copy_constructor = false
887 # Whether enums with fields should generate copy-assignment operators.
888 #
889 # This depends on also deriving copy-constructors, and it is highly encouraged
890 # for this to be set to true.
891 #
892 # default: false
893 derive_tagged_enum_copy_assignment = false
894
895 # Whether enums with fields should generate an empty, private destructor.
896 # This allows the auto-generated constructor functions to compile, if there are
897 # non-trivially constructible members. This falls in the same family of
898 # dangerousness as `derive_tagged_enum_copy_constructor` and co.
899 #
900 # default: false
901 private_default_tagged_enum_constructor = false
902
903
904
905
906
907 [const]
908 # Whether a generated constant can be a static const in C++ mode. I have no
909 # idea why you would turn this off.
910 #
911 # default: true
912 allow_static_const = true
913
914 # Whether a generated constant can be constexpr in C++ mode.
915 #
916 # default: true
917 allow_constexpr = false
918
919 # This rule specifies the order in which constants will be sorted.
920 #
921 # "Name": sort by the name of the constant
922 # "None": keep order in which the constants have been parsed
923 #
924 # default: "None"
925 sort_by = "Name"
926
927
928
929
930 [macro_expansion]
931 # Whether bindings should be generated for instances of the bitflags! macro.
932 # default: false
933 bitflags = true
934
935
936
937
938
939
940 # Options for how your Rust library should be parsed
941
942 [parse]
943 # Whether to parse dependent crates and include their types in the output
944 # default: false
945 parse_deps = true
946
947 # A white list of crate names that are allowed to be parsed. If this is defined,
948 # only crates found in this list will ever be parsed.
949 #
950 # default: there is no whitelist (NOTE: this is the opposite of [])
951 include = ["webrender", "webrender_traits"]
952
953 # A black list of crate names that are not allowed to be parsed.
954 # default: []
955 exclude = ["libc"]
956
957 # Whether to use a new temporary target directory when running `rustc -Zunpretty=expanded`.
958 # This may be required for some build processes.
959 #
960 # default: false
961 clean = false
962
963 # Which crates other than the top-level binding crate we should generate
964 # bindings for.
965 #
966 # default: []
967 extra_bindings = ["my_awesome_dep"]
968
969 [parse.expand]
970 # A list of crate names that should be run through `cargo expand` before
971 # parsing to expand any macros. Note that if a crate is named here, it
972 # will always be parsed, even if the blacklist/whitelist says it shouldn't be.
973 #
974 # default: []
975 crates = ["euclid"]
976
977 # If enabled, use the `--all-features` option when expanding. Ignored when
978 # `features` is set. For backwards-compatibility, this is forced on if
979 # `expand = ["euclid"]` shorthand is used.
980 #
981 # default: false
982 all_features = false
983
984 # When `all_features` is disabled and this is also disabled, use the
985 # `--no-default-features` option when expanding.
986 #
987 # default: true
988 default_features = true
989
990 # A list of feature names that should be used when running `cargo expand`. This
991 # combines with `default_features` like in your `Cargo.toml`. Note that the features
992 # listed here are features for the current crate being built, *not* the crates
993 # being expanded. The crate's `Cargo.toml` must take care of enabling the
994 # appropriate features in its dependencies
995 #
996 # default: []
997 features = ["cbindgen"]
998
999 [ptr]
1000 # An optional string to decorate all pointers that are
1001 # required to be non null. Nullability is inferred from the Rust type: `&T`,
1002 # `&mut T` and `NonNull<T>` all require a valid pointer value.
1003 non_null_attribute = "_Nonnull"
1004
1005 # Options specific to Cython bindings.
1006
1007 [cython]
1008
1009 # Header specified in the top level `cdef extern from header:` declaration.
1010 #
1011 # default: *
1012 header = '"my_header.h"'
1013
1014 # `from module cimport name1, name2` declarations added in the same place
1015 # where you'd get includes in C.
1016 [cython.cimports]
1017 module = ["name1", "name2"]
1018 ```
1019
1020
1021
1022
1023
1024 [reference]: https://doc.rust-lang.org/nightly/reference/type-layout.html#representations
1025 [really-tagged-unions]: https://github.com/rust-lang/rfcs/blob/master/text/2195-really-tagged-unions.md
1026 [section-cfgs]: #defines-and-cfgs
1027 [file-it]: https://github.com/eqrion/cbindgen/issues/new