cbindgen-0.12.1/.gitignore010064400017500001750000000000251356501061700135560ustar0000000000000000target .idea .vscode cbindgen-0.12.1/.travis.yml010064400017500001750000000023351357132107600137060ustar0000000000000000language: rust cache: cargo rust: - nightly before_script: - rustup component add rustfmt addons: apt: sources: - ubuntu-toolchain-r-test packages: - gcc-7 - g++-7 script: - export CC=gcc-7 - export CXX=g++-7 - cargo fmt --all -- --check - cargo build --verbose - cargo build --verbose --no-default-features - CBINDGEN_TEST_VERIFY=1 cargo test --verbose - cargo build --verbose --release deploy: provider: releases api_key: secure: TaUl6M8+S3jYB2iNw2AtjTG2ZTMz6Cvd3GeTLeMjYzHPM0Htx4zvU4llmS2XU4YGU7IygRr95epDPqp29MDMFE6gsV7z2MSls9fSEf4/hQFXyCMb6mr2rDvkX9pEFMolNeGt3Y/TAdXGEUm2DeGCPQ0tq6/Jk599pKgqpzv8S5y+z5k2JpV6ODvENtIMiM1C0C+Yt0vIX78VLPoKzncwcXYnDCuy/uQTrVgeWNNs2W20BsxB4Nw7rlJftXRAaV1PM4vjZrCCFqCns9zJ4Yrb+Bqo0DJZLcO404qhqBdMo/vJYNBuTk9Vb5osccJEdOclXOE8ZOtQJtbm1PpiVhqeSu9536jVXMwaFKMN5u+ioHeQ8ouHLeq7Ar6LhK5y8UiA8euNRNLh5T5Do3hM89h57lHABXREpWA4CHrEh7hgcyzlTbJGIbA0eVQX1D2ju2CWJy0b1zg3zmvUt9QGN0Z0jE4SffAOQ4faWTndMfVghr5Lp81ei5Hndyxw08M5F2aFk8qVq+UYpoXv4U8UDtNJ8FzyhKzOGr7Kl23bmKsylMngB0XPscQyQQFwT+du+3UrG5pbRMEMOFRAr4Q9COceZqRQe7Ozyw6X1eGs4G4fpnMczbu9nvjj7WqtltQKWD1OHmxbAd83oGldcIkqoP9u/NLGn4sg7pzu4cGRHr11iyU= file: target/release/cbindgen on: tags: true skip_cleanup: true cbindgen-0.12.1/CHANGES010066400017500001750000000117771360223651700126040ustar0000000000000000## 0.12.1 * Added support for #[repr*64)] on enums. https://github.com/eqrion/cbindgen/pull/441 * Added support to generate plain enums instead of enum classes for C++. https://github.com/eqrion/cbindgen/pull/443 * Fixed dependency resolution with lockfile v2. https://github.com/eqrion/cbindgen/pull/438 ## 0.12.0 * Added support for #[repr(align)] and #[repr(packed)] on structs and unions. https://github.com/eqrion/cbindgen/pull/431 * Added support to generate copy-assignment operators for enums. https://github.com/eqrion/cbindgen/pull/434 ## 0.11.1 * More binary operators and expressions are supported. https://github.com/eqrion/cbindgen/pull/425 * More built-in bitflags operators. https://github.com/eqrion/cbindgen/pull/426 ## 0.11.0 * Made rust char map to uint32_t. https://github.com/eqrion/cbindgen/pull/424 ## 0.10.1 * Improved error message for missing config file. https://github.com/eqrion/cbindgen/pull/422 * Add missing header for char32_t. https://github.com/eqrion/cbindgen/pull/414 ## 0.10.0 * Initialize struct literal with list-initializer for C++11 standard. https://github.com/eqrion/cbindgen/pull/401 * Surround namespace with __cplusplus ifdef in cpp_compat mode. https://github.com/eqrion/cbindgen/pull/407 * Add support for --quiet flag. https://github.com/eqrion/cbindgen/pull/400 * Map char to char32_t. https://github.com/eqrion/cbindgen/pull/396 * Improve binding_crate_ref() error message. https://github.com/eqrion/cbindgen/pull/395 * avoid prematurely returning during expansion. https://github.com/eqrion/cbindgen/pull/389 * Add support for adding "using namespace" statements. https://github.com/eqrion/cbindgen/pull/387 ## 0.9.1 * Various improvements to comment output. https://github.com/eqrion/cbindgen/pull/370 / https://github.com/eqrion/cbindgen/pull/375. * Fixed expand when ran from build.rs. https://github.com/eqrion/cbindgen/pull/371 * More debugging output for expansion. https://github.com/eqrion/cbindgen/pull/383 * New option to add a default private constructor in C++ tagged enums. https://github.com/eqrion/cbindgen/pull/377 * Syn and related dependencies updated to 1.0. https://github.com/eqrion/cbindgen/pull/379 ## 0.9.0 * Support to generate C headers with C++ compatibility. https://github.com/eqrion/cbindgen/pull/349 * Fix include guard generation when no_includes is set. https://github.com/eqrion/cbindgen/pull/352 * Fix crate parsing order so that types from the binding crate are preferred in presence of conflicting names. https://github.com/eqrion/cbindgen/pull/355 * Add extra_bindings option to generate bindings for dependencies. https://github.com/eqrion/cbindgen/pull/362 * Clap dependency is optional now so it's feasible to avoid building it if cbindgen is used as a library. https://github.com/eqrion/cbindgen/pull/363 ## 0.8.7 * Require C++11 to run the test-suite (#341, test-only) * Improve mangling error message (#340) * Add the ability to automatically derive copy-constructors for tagged enums (#339) * Use placement new for constructing in tagged unions' helper methods (#333) ## 0.8.6 * Fixed a panic when missing a lock file ## 0.8.5 * Improved support for Rust 2018 modules * Add possibility to autogenerate tagged union destructors ## 0.8.4 * Support for package renaming in Cargo.toml * Improved error messages for |cargo metadata| failures * Replaced 'test.py' harness with |cargo test| * Char constants will now be escaped properly * Visibility of constants will now be respected * Added a C99 doc comment style ## 0.8.2 * Improvements to bitflags parsing ## 0.8.1 * Support for manual parsing and expanding of bitflags macros * Support for optional tagged enum casts with asserts ## 0.8.0 * support for 'includes' without default includes * removed dependency on ancient serde_derive! ## 0.7.1 * Fix for crash when unwrapping unsupported type with associated constants ## 0.7.0 * support for libc::ssize_t * fixed some warnings on nightly * fix for transparent associated constants * switched more API's to use AsRef * impl std::error::Error for cbindgen::Error * now support putting user-defined content in item bodies ## 0.6.8 * ptrdiff_t is now a recognized primitive type * named function type arguments are now propagated * fixes for struct literals in constants * reserved C/C++ keywords are now escaped automatically * negative enum discriminants are now supported * fix for prefixing and formatting variant names * fix for snake_case formatter * syn update * doxygen style comments are now output by default * VaList is now a recognized primitive type * fix for comment processing * constant is propagated into array types * references are now supported in IR, and used for some helper method generation * assignment helper functions will generate array copies if necessary cbindgen-0.12.1/Cargo.toml.orig010066400017500001750000000020201360223651700144550ustar0000000000000000[package] name = "cbindgen" version = "0.12.1" authors = ["Jeff Muizelaar ", "Kartikaya Gupta ", "Ryan Hunt "] license = "MPL-2.0" description = "A tool for generating C bindings to Rust code." keywords = ["bindings", "ffi", "code-generation"] categories = ["external-ffi-bindings", "development-tools::ffi"] repository = "https://github.com/eqrion/cbindgen/" edition = "2018" [badges] travis-ci = { repository = "eqrion/cbindgen" } [dependencies] clap = { version = "2", optional = true } log = "0.4" serde = { version = "1.0", default-features = false, features = ["derive"]} serde_json = "1.0" tempfile = "3.0" toml = "0.5" proc-macro2 = "1" quote = "1" [dependencies.syn] version = "1" default-features = false features = ["clone-impls", "extra-traits", "full", "parsing", "printing"] [features] default = ["clap"] [[bin]] name = "cbindgen" path = "src/main.rs" doc = false required-features = ["clap"] [lib] name = "cbindgen" path = "src/lib.rs" cbindgen-0.12.1/Cargo.toml0000644000000032201360223660400107610ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "cbindgen" version = "0.12.1" authors = ["Jeff Muizelaar ", "Kartikaya Gupta ", "Ryan Hunt "] description = "A tool for generating C bindings to Rust code." keywords = ["bindings", "ffi", "code-generation"] categories = ["external-ffi-bindings", "development-tools::ffi"] license = "MPL-2.0" repository = "https://github.com/eqrion/cbindgen/" [lib] name = "cbindgen" path = "src/lib.rs" [[bin]] name = "cbindgen" path = "src/main.rs" doc = false required-features = ["clap"] [dependencies.clap] version = "2" optional = true [dependencies.log] version = "0.4" [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.serde] version = "1.0" features = ["derive"] default-features = false [dependencies.serde_json] version = "1.0" [dependencies.syn] version = "1" features = ["clone-impls", "extra-traits", "full", "parsing", "printing"] default-features = false [dependencies.tempfile] version = "3.0" [dependencies.toml] version = "0.5" [features] default = ["clap"] [badges.travis-ci] repository = "eqrion/cbindgen" cbindgen-0.12.1/Cargo.toml.orig0000644000000020201360223660400117150ustar00[package] name = "cbindgen" version = "0.12.1" authors = ["Jeff Muizelaar ", "Kartikaya Gupta ", "Ryan Hunt "] license = "MPL-2.0" description = "A tool for generating C bindings to Rust code." keywords = ["bindings", "ffi", "code-generation"] categories = ["external-ffi-bindings", "development-tools::ffi"] repository = "https://github.com/eqrion/cbindgen/" edition = "2018" [badges] travis-ci = { repository = "eqrion/cbindgen" } [dependencies] clap = { version = "2", optional = true } log = "0.4" serde = { version = "1.0", default-features = false, features = ["derive"]} serde_json = "1.0" tempfile = "3.0" toml = "0.5" proc-macro2 = "1" quote = "1" [dependencies.syn] version = "1" default-features = false features = ["clone-impls", "extra-traits", "full", "parsing", "printing"] [features] default = ["clap"] [[bin]] name = "cbindgen" path = "src/main.rs" doc = false required-features = ["clap"] [lib] name = "cbindgen" path = "src/lib.rs" cbindgen-0.12.1/LICENSE010064400017500001750000000405251356501061700126040ustar0000000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. cbindgen-0.12.1/README.md010064400017500001750000000074371356501061700130630ustar0000000000000000# `cbindgen`   [![Build Status]][travis] [![Latest Version]][crates.io] [![Api Rustdoc]][rustdoc] [![Rust](https://img.shields.io/badge/rust-1.32%2B-blue.svg?maxAge=3600)](https://github.com/eqrion/cbindgen) [Build Status]: https://api.travis-ci.org/eqrion/cbindgen.svg?branch=master [travis]: https://travis-ci.org/eqrion/cbindgen [Latest Version]: https://img.shields.io/crates/v/cbindgen.svg [crates.io]: https://crates.io/crates/cbindgen [Api Rustdoc]: https://img.shields.io/badge/api-rustdoc-blue.svg [rustdoc]: https://docs.rs/cbindgen [Read the full user docs here!](docs.md) cbindgen creates C/C++11 headers for Rust libraries which expose a public C API. 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. 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. There are two ways to use cbindgen: as a standalone program, or as a library (presumably in your build.rs). 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). 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](https://github.com/eqrion/cbindgen/issues/new). Although since we all have other jobs, you might need to do the implementation work too :) # Quick Start To install cbindgen, you just need to run ```text cargo install --force cbindgen ``` (--force just makes it update to the latest cbindgen if it's already installed) To use cbindgen you need two things: * A configuration (cbindgen.toml, which can be empty to start) * A Rust crate with a public C API Then all you need to do is run it: ```text cbindgen --config cbindgen.toml --crate my_rust_library --output my_header.h ``` See `cbindgen --help` for more options. [Read the full user docs here!](docs.md) [Get a template cbindgen.toml here.](template.toml) # Examples We don't currently have a nice tailored example application, but [the tests](tests/rust/) contain plenty of interesting examples of our features. You may also find it interesting to browse the projects that are using cbindgen in production: * [milksnake](https://github.com/getsentry/milksnake) * [webrender](https://searchfox.org/mozilla-central/source/gfx/webrender_bindings) ([generated header](https://searchfox.org/mozilla-central/source/__GENERATED__/gfx/webrender_bindings/webrender_ffi_generated.h)) * [stylo](https://searchfox.org/mozilla-central/source/layout/style) ([generated header](https://searchfox.org/mozilla-central/source/__GENERATED__/layout/style/ServoStyleConsts.h)) * [wgpu](https://github.com/gfx-rs/wgpu/tree/master/wgpu-native) ([generated header](https://github.com/gfx-rs/wgpu/blob/master/ffi/wgpu.h)) If you're using `cbindgen` and would like to be added to this list, please open a pull request! cbindgen-0.12.1/build.rs010064400017500001750000000036121356501061700132400ustar0000000000000000fn generate_tests() { use std::env; use std::ffi::OsStr; use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); let mut dst = File::create(Path::new(&out_dir).join("tests.rs")).unwrap(); let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let tests_dir = manifest_dir.join("tests").join("rust"); let tests = fs::read_dir(&tests_dir).unwrap(); let entries = tests.map(|t| t.expect("Couldn't read test file")); println!("cargo:rerun-if-changed={}", tests_dir.display()); // Try to make a decent guess at where our binary will end up in. // // TODO(emilio): Ideally running tests will just use the library-version of // cbindgen instead of the built binary. let cbindgen_path = out_dir .parent() .unwrap() .parent() .unwrap() .parent() .unwrap() .join("cbindgen"); for entry in entries { let path_segment = if entry.file_type().unwrap().is_file() { match entry.path().extension().and_then(OsStr::to_str) { Some("rs") => {} _ => continue, }; entry .path() .file_stem() .unwrap() .to_str() .unwrap() .to_owned() } else { entry.file_name().to_str().unwrap().to_owned() }; let identifier = path_segment .replace(|c| !char::is_alphanumeric(c), "_") .replace("__", "_"); writeln!( dst, "test_file!({:?}, test_{}, {:?}, {:?});", cbindgen_path, identifier, path_segment, entry.path(), ) .unwrap(); } dst.flush().unwrap(); } fn main() { generate_tests(); } cbindgen-0.12.1/contributing.md010064400017500001750000000023771356501061700146330ustar0000000000000000# Contributing Thanks for wanting to contribute! If you want help or mentorship, please file a Github issue and I'll be sure to provide guidance to the best of my ability. Otherwise be sure to check out `ARCHITECTURE.md` for an overview on the internals. ## Filing a pull request Check out [Servo's Github workflow](https://github.com/servo/servo/wiki/Github-workflow) for an overview on creating a pull request. Don't worry about requesting code review, as there is nothing formally setup for this repository. I try and review each pull request as soon as I can. There is continuous integration setup for `cbindgen` using [travis](https://travis-ci.org/). It automatically runs `cargo test` which runs `cbindgen` against a series of rust files from `tests/rust/` and checks that the output compiles using `gcc` or `g++`. Please run `cargo test` before filing a pull request to be sure that all tests pass. This will also update the test expectations. Rustfmt is also enforced by travis. To format your code install `rustfmt-preview` using `rustup component add rustfmt-preview` and then `cargo fmt`. Travis runs with rust nightly, so use `rustup run nightly -- cargo fmt` to guarantee consistent results. Writing new tests with your pull requests is also appreciated. cbindgen-0.12.1/docs.md010066400017500001750000000720331360223554200130500ustar0000000000000000# cbindgen User Guide cbindgen creates C/C++11 headers for Rust libraries which expose a public C API. 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. 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. There are two ways to use cbindgen: as a standalone program, or as a library (presumably in your build.rs). 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). 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 :) # Quick Start To install cbindgen, you just need to run ```text cargo install --force cbindgen ``` (--force just makes it update to the latest cbindgen if it's already installed) To use cbindgen you need two things: * A configuration (cbindgen.toml, which can be empty to start) * A Rust crate with a public C API Then all you need to do is run it: ```text cbindgen --config cbindgen.toml --crate my_rust_library --output my_header.h ``` See `cbindgen --help` for more options. [Get a template cbindgen.toml here.](template.toml) ## build.rs If you don't want to use cbindgen as an application, here's an example build.rs script: ```rust extern crate cbindgen; use std::env; fn main() { let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); cbindgen::Builder::new() .with_crate(crate_dir) .generate() .expect("Unable to generate bindings") .write_to_file("bindings.h"); } ``` You can add configuration options using the [`Builder`](https://docs.rs/cbindgen/*/cbindgen/struct.Builder.html#methods) interface. 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. # Writing Your C API cbindgen has a simple but effective strategy. It walks through your crate looking for: * `#[no_mangle] pub extern fn` ("functions") * `#[no_mangle] pub static` ("globals") * `pub const` ("constants") 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. > 🚨 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]. 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. # Examples 🚧 🏗 It would be really nice to have some curated and clean examples, but we don't have those yet. [The README has some useful links though](README.md#examples). # Supported Types 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. You can learn about all of the different repr attributes [by reading Rust's reference][reference], but here's a quick summary: * `#[repr(C)]`: give this struct/union/enum the same layout and ABI C would * `#[repr(u8, u16, ... etc)]`: give this enum the same layout and ABI as the given integer type * `#[repr(transparent)]`: give this single-field struct the same ABI as its field (useful for newtyping integers but keeping the integer ABI) cbindgen supports the `#[repr(align(N))]` and `#[repr(packed)]` attributes, but currently does not support `#[repr(packed(N))]`. 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. If you ensure everything has a guaranteed repr, then cbindgen will generate definitions for: * struct (named-style or tuple-style) * enum (fieldless or with fields) * union * type * `[T; n]` (arrays always have a guaranteed C-compatible layout) * `&T`, `&mut T`, `*const T`, `*mut T`, `Option<&T>`, `Option<&mut T>` (all have the same pointer ABI) * `fn()` (as an actual function pointer) * `bitflags! { ... }` (if macro_expansion.bitflags is enabled) 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. cbindgen sadly cannot ever support anonymous tuples `(A, B, ...)`, as there is no way to guarantee their layout. You must use a tuple struct. 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`. 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. Don't use the `[u64; 0]` trick to over-align a struct, we don't support this. cbindgen contains the following hardcoded mappings (again completely ignoring namespacing, literally just looking at the name of the type): ## std types * bool => bool * char => uint32_t * u8 => uint8_t * u16 => uint16_t * u32 => uint32_t * u64 => uint64_t * usize => uintptr_t * i8 => int8_t * i16 => int16_t * i32 => int32_t * i64 => int64_t * isize => intptr_t * f32 => float * f64 => double * VaList => va_list * PhantomData => *evaporates*, can only appear as the field of a type * () => *evaporates*, can only appear as the field of a type ## libc types * c_void => void * c_char => char * c_schar => signed char * c_uchar => unsigned char * c_float => float * c_double => double * c_short => short * c_int => int * c_long => long * c_longlong => long long * c_ushort => unsigned short * c_uint => unsigned int * c_ulong => unsigned long * c_ulonglong => unsigned long long ## stdint types * uint8_t => uint8_t * uint16_t => uint16_t * uint32_t => uint32_t * uint64_t => uint64_t * uintptr_t => uintptr_t * size_t => size_t * int8_t => int8_t * int16_t => int16_t * int32_t => int32_t * int64_t => int64_t * intptr_t => intptr_t * ssize_t => ssize_t * ptrdiff_t => ptrdiff_t # Configuring Your Header cbindgen supports several different options for configuring the output of your header, including target language, styling, mangling, prefixing, includes, and defines. ## Defines and Cfgs 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. 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"`. 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). 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. ## Annotations 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==`: ```rust /// cbindgen:field-names=[x, y] /// cbindgen:derive-eq #[repr(C)] pub struct Point(pub f32, pub f32); ``` 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 `]`. 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: ### Struct Annotations * 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. The rest are just local overrides for the same options found in the cbindgen.toml: * rename-all=RenameRule * derive-constructor * derive-eq * derive-neq * derive-lt * derive-lte * derive-gt * derive-gte ### Enum Annotations * 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. 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. The rest are just local overrides for the same options found in the cbindgen.toml: * rename-all=RenameRule * add-sentinel * derive-helper-methods * derive-const-casts * derive-mut-casts * derive-tagged-enum-destructor * derive-tagged-enum-copy-constructor * enum-class * prefix-with-name * private-default-tagged-enum-constructor ### Union Annotations * 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. The rest are just local overrides for the same options found in the cbindgen.toml: * rename-all=RenameRule ### Function Annotations All function attributes are just local overrides for the same options found in the cbindgen.toml: * rename-all=RenameRule * prefix * postfix ## cbindgen.toml 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. 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. ```toml # The language to output bindings in # # possible values: "C", "C++" # # default: "C++" language = "C" # Options for wrapping the contents of the header: # An optional string of text to output at the beginning of the generated file # default: doesn't emit anything header = "/* Text to put at the beginning of the generated file. Probably a license. */" # An optional string of text to output at the end of the generated file # default: doesn't emit anything trailer = "/* Text to put at the end of the generated file */" # An optional name to use as an include guard # default: doesn't emit an include guard include_guard = "mozilla_wr_bindings_h" # An optional string of text to output between major sections of the generated # file as a warning against manual editing # # default: doesn't emit anything autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */" # Whether to include a comment with the version of cbindgen used to generate the file # default: false include_version = true # An optional namespace to output around the generated bindings # default: doesn't emit a namespace namespace = "ffi" # An optional list of namespaces to output around the generated bindings # default: [] namespaces = ["mozilla", "wr"] # An optional list of namespaces to declare as using with "using namespace" # default: [] using_namespaces = ["mozilla", "wr"] # A list of sys headers to #include (with angle brackets) # default: [] sys_includes = ["stdio", "string"] # A list of headers to #include (with quotes) # default: [] includes = ["my_great_lib.h"] # Whether cbindgen's default C/C++ standard imports should be suppressed. These # imports are included by default because our generated headers tend to require # them (e.g. for uint32_t). Currently, the generated imports are: # # * for C: , , , , # # * for C++: , , , , (depending on config) # # default: false no_includes = false # Code Style Options # The style to use for curly braces # # possible values: "SameLine", "NextLine" # # default: "SameLine" braces = "SameLine" # The desired length of a line to use when formatting lines # default: 100 line_length = 80 # The amount of spaces to indent by # default: 2 tab_width = 3 # How the generated documentation should be commented. # # possible values: # * "c": /* like this */ # * "c99": // like this # * "c++": /// like this # * "doxy": like C, but with leading *'s on each line # * "auto": "c++" if that's the language, "doxy" otherwise # # default: "auto" documentation_style = "doxy" # Codegen Options # When generating a C header, the kind of declaration style to use for structs # or enums. # # possible values: # * "type": typedef struct { ... } MyType; # * "tag": struct MyType { ... }; # * "both": typedef struct MyType { ... } MyType; # # default: "both" style = "both" # A list of substitutions for converting cfg's to ifdefs. cfgs which aren't # defined here will just be discarded. # # e.g. # `#[cfg(target = "freebsd")] ...` # becomes # `#if defined(DEFINE_FREEBSD) ... #endif` [defines] "target_os = freebsd" = "DEFINE_FREEBSD" "feature = serde" = "DEFINE_SERDE" [export] # A list of additional items to always include in the generated bindings if they're # found but otherwise don't appear to be used by the public API. # # default: [] include = ["MyOrphanStruct", "MyGreatTypeRename"] # A list of items to not include in the generated bindings # default: [] exclude = ["Bad"] # A prefix to add before the name of every item # default: no prefix is added prefix = "CAPI_" # Types of items that we'll generate. If empty, then all types of item are emitted. # # possible items: (TODO: explain these in detail) # * "constants": # * "globals": # * "enums": # * "structs": # * "unions": # * "typedefs": # * "opaque": # * "functions": # # default: [] item_types = ["enums", "structs", "opaque", "functions"] # Whether applying rules in export.rename prevents export.prefix from applying. # # e.g. given this toml: # # [export] # prefix = "capi_" # [export.rename] # "MyType" = "my_cool_type" # # You get the following results: # # renaming_overrides_prefixing = true: # "MyType" => "my_cool_type" # # renaming_overrides_prefixing = false: # "MyType => capi_my_cool_type" # # default: false renaming_overrides_prefixing = true # Table of name conversions to apply to item names (lhs becomes rhs) [export.rename] "MyType" = "my_cool_type" "my_function" = "BetterFunctionName" # Table of things to add to the body of any struct, union, or enum that has the # given name. This can be used to add things like methods which don't change ABI. [export.body] "MyType" = """ void cppMethod() const; """ [layout] # A string that should come before the name of any type which has been marked # as `#[repr(packed)]`. For instance, "__attribute__((packed))" would be a # reasonable value if targeting gcc/clang. A more portable solution would # involve emitting the name of a macro which you define in a platform-specific # way. e.g. "PACKED" # # default: `#[repr(packed)]` types will be treated as opaque, since it would # be unsafe for C callers to use a incorrectly laid-out union. packed = "PACKED" # A string that should come before the name of any type which has been marked # as `#[repr(align(n))]`. This string must be a function-like macro which takes # a single argument (the requested alignment, `n`). For instance, a macro # `#define`d as `ALIGNED(n)` in `header` which translates to # `__attribute__((aligned(n)))` would be a reasonable value if targeting # gcc/clang. # # default: `#[repr(align(n))]` types will be treated as opaque, since it # could be unsafe for C callers to use a incorrectly-aligned union. aligned_n = "ALIGNED" [fn] # An optional prefix to put before every function declaration # default: no prefix added prefix = "WR_START_FUNC" # An optional postfix to put after any function declaration # default: no postix added postfix = "WR_END_FUNC" # How to format function arguments # # possible values: # * "horizontal": place all arguments on the same line # * "vertical": place each argument on its own line # * "auto": only use vertical if horizontal would exceed line_length # # default: "auto" args = "horizontal" # An optional string that should prefix function declarations which have been # marked as `#[must_use]`. For instance, "__attribute__((warn_unused_result))" # would be a reasonable value if targeting gcc/clang. A more portable solution # would involve emitting the name of a macro which you define in a # platform-specific way. e.g. "MUST_USE_FUNC" # default: nothing is emitted for must_use functions must_use = "MUST_USE_FUNC" # A rule to use to rename function argument names. The renaming assumes the input # is the Rust standard snake_case, however it accepts all the different rename_args # inputs. This means many options here are no-ops or redundant. # # possible values (that actually do something): # * "CamelCase": my_arg => myArg # * "PascalCase": my_arg => MyArg # * "GeckoCase": my_arg => aMyArg # * "ScreamingSnakeCase": my_arg => MY_ARG # * "None": apply no renaming # # technically possible values (that shouldn't have a purpose here): # * "SnakeCase": apply no renaming # * "LowerCase": apply no renaming (actually applies to_lowercase, is this bug?) # * "UpperCase": same as ScreamingSnakeCase in this context # * "QualifiedScreamingSnakeCase" => same as ScreamingSnakeCase in this context # # default: "None" rename_args = "PascalCase" [struct] # A rule to use to rename struct field names. The renaming assumes the input is # the Rust standard snake_case, however it acccepts all the different rename_args # inputs. This means many options here are no-ops or redundant. # # possible values (that actually do something): # * "CamelCase": my_arg => myArg # * "PascalCase": my_arg => MyArg # * "GeckoCase": my_arg => mMyArg # * "ScreamingSnakeCase": my_arg => MY_ARG # * "None": apply no renaming # # technically possible values (that shouldn't have a purpose here): # * "SnakeCase": apply no renaming # * "LowerCase": apply no renaming (actually applies to_lowercase, is this bug?) # * "UpperCase": same as ScreamingSnakeCase in this context # * "QualifiedScreamingSnakeCase" => same as ScreamingSnakeCase in this context # # default: "None" rename_fields = "PascalCase" # An optional string that should come before the name of any struct which has been # marked as `#[must_use]`. For instance, "__attribute__((warn_unused))" # would be a reasonable value if targeting gcc/clang. A more portable solution # would involve emitting the name of a macro which you define in a # platform-specific way. e.g. "MUST_USE_STRUCT" # # default: nothing is emitted for must_use structs must_use = "MUST_USE_STRUCT" # Whether a Rust type with associated consts should emit those consts inside the # type's body. Otherwise they will be emitted trailing and with the type's name # prefixed. This does nothing if the target is C, or if # [const]allow_static_const = false # # default: false # associated_constants_in_body: false # Whether to derive a simple constructor that takes a value for every field. # default: false derive_constructor = true # Whether to derive an operator== for all structs # default: false derive_eq = false # Whether to derive an operator!= for all structs # default: false derive_neq = false # Whether to derive an operator< for all structs # default: false derive_lt = false # Whether to derive an operator<= for all structs # default: false derive_lte = false # Whether to derive an operator> for all structs # default: false derive_gt = false # Whether to derive an operator>= for all structs # default: false derive_gte = false [enum] # A rule to use to rename enum variants, and the names of any fields those # variants have. This should probably be split up into two separate options, but # for now, they're the same! See the documentation for `[struct]rename_fields` # for how this applies to fields. Renaming of the variant assumes that the input # is the Rust standard PascalCase. In the case of QualifiedScreamingSnakeCase, # it also assumed that the enum's name is PascalCase. # # possible values (that actually do something): # * "CamelCase": MyVariant => myVariant # * "SnakeCase": MyVariant => my_variant # * "ScreamingSnakeCase": MyVariant => MY_VARIANT # * "QualifiedScreamingSnakeCase": MyVariant => ENUM_NAME_MY_VARIANT # * "LowerCase": MyVariant => myvariant # * "UpperCase": MyVariant => MYVARIANT # * "None": apply no renaming # # technically possible values (that shouldn't have a purpose for the variants): # * "PascalCase": apply no renaming # * "GeckoCase": apply no renaming # # default: "None" rename_variants = "None" # Whether an extra "sentinel" enum variant should be added to all generated enums. # Firefox uses this for their IPC serialization library. # # WARNING: if the sentinel is ever passed into Rust, behaviour will be Undefined. # Rust does not know about this value, and will assume it cannot happen. # # default: false add_sentinel = false # Whether enum variant names should be prefixed with the name of the enum. # default: false prefix_with_name = false # Whether to emit enums using "enum class" when targeting C++. # default: true enum_class = true # Whether to generate static `::MyVariant(..)` constructors and `bool IsMyVariant()` # methods for enums with fields. # # default: false derive_helper_methods = false # Whether to generate `const MyVariant& AsMyVariant() const` methods for enums with fields. # default: false derive_const_casts = false # Whether to generate `MyVariant& AsMyVariant()` methods for enums with fields # default: false derive_mut_casts = false # The name of the macro/function to use for asserting `IsMyVariant()` in the body of # derived `AsMyVariant()` cast methods. # # default: "assert" (but also causes `` to be included by default) cast_assert_name = "MOZ_RELEASE_ASSERT" # An optional string that should come before the name of any enum which has been # marked as `#[must_use]`. For instance, "__attribute__((warn_unused))" # would be a reasonable value if targeting gcc/clang. A more portable solution # would involve emitting the name of a macro which you define in a # platform-specific way. e.g. "MUST_USE_ENUM" # # Note that this refers to the *output* type. That means this will not apply to an enum # with fields, as it will be emitted as a struct. `[struct]must_use` will apply there. # # default: nothing is emitted for must_use enums must_use = "MUST_USE_ENUM" # Whether enums with fields should generate destructors. This exists so that generic # enums can be properly instantiated with payloads that are C++ types with # destructors. This isn't necessary for structs because C++ has rules to # automatically derive the correct constructors and destructors for those types. # # Care should be taken with this option, as Rust and C++ cannot # properly interoperate with eachother's notions of destructors. Also, this may # change the ABI for the type. Either your destructor-full enums must live # exclusively within C++, or they must only be passed by-reference between # C++ and Rust. # # default: false derive_tagged_enum_destructor = false # Whether enums with fields should generate copy-constructor. See the discussion on # derive_tagged_enum_destructor for why this is both useful and very dangerous. # # default: false derive_tagged_enum_copy_constructor = false # Whether enums with fields should generate copy-assignment operators. # # This depends on also deriving copy-constructors, and it is highly encouraged # for this to be set to true. # # default: false derive_tagged_enum_copy_assignment = false # Whether enums with fields should generate an empty, private destructor. # This allows the auto-generated constructor functions to compile, if there are # non-trivially constructible members. This falls in the same family of # dangerousness as `derive_tagged_enum_copy_constructor` and co. # # default: false private_default_tagged_enum_constructor = false [const] # Whether a generated constant can be a static const in C++ mode. I have no # idea why you would turn this off. # # default: true allow_static_const = true [macro_expansion] # Whether bindings should be generated for instances of the bitflags! macro. # default: false bitflags = true # Options for how your Rust library should be parsed [parse] # Whether to parse dependent crates and include their types in the output # default: false parse_deps = true # A white list of crate names that are allowed to be parsed. If this is defined, # only crates found in this list will ever be parsed. # # default: there is no whitelist (NOTE: this is the opposite of []) include = ["webrender", "webrender_traits"] # A black list of crate names that are not allowed to be parsed. # default: [] exclude = ["libc"] # Whether to use a new temporary target directory when running `rustc --pretty=expanded`. # This may be required for some build processes. # # default: false clean = false # Which crates other than the top-level binding crate we should generate # bindings for. # # default: [] extra_bindings = ["my_awesome_dep"] [parse.expand] # A list of crate names that should be run through `cargo expand` before # parsing to expand any macros. Note that if a crate is named here, it # will always be parsed, even if the blacklist/whitelist says it shouldn't be. # # default: [] crates = ["euclid"] # If enabled, use the `--all-features` option when expanding. Ignored when # `features` is set. For backwards-compatibility, this is forced on if # `expand = ["euclid"]` shorthand is used. # # default: false all_features = false # When `all_features` is disabled and this is also disabled, use the # `--no-default-features` option when expanding. # # default: true default_features = true # A list of feature names that should be used when running `cargo expand`. This # combines with `default_features` like in your `Cargo.toml`. Note that the features # listed here are features for the current crate being built, *not* the crates # being expanded. The crate's `Cargo.toml` must take care of enabling the # appropriate features in its dependencies # # default: [] features = ["cbindgen"] ``` [reference]: https://doc.rust-lang.org/nightly/reference/type-layout.html#representations [really-tagged-unions]: https://github.com/rust-lang/rfcs/blob/master/text/2195-really-tagged-unions.md [section-cfgs]: #defines-and-cfgs [file-it]: https://github.com/eqrion/cbindgen/issues/new cbindgen-0.12.1/internals.md010064400017500001750000000044671356501061700141250ustar0000000000000000## Overview `cbindgen` works in four phases: 1. *Parsing* - Crate information is gathered from `cargo`, and `rust` source files are read using `syn` 1. *Loading* - `syn` AST nodes are converted into an IR of `Item`s that loosely correspond to the C types that will be output 1. *Transformation* - Several passes are run that transform the IR. Some examples: - Generic `type` aliases are used to specialize the type they refer to - Annotations are transferred from `type` aliases to the item they refer to - `Option<&T>` is converted to `*const T` - `Option<&mut T>` is converted to `*mut T` - Generic paths in struct fields, union variants, and static globals are collected and used to generate monomorphs of the structs or unions they refer to - The items are sorted by dependencies and type and unused items are filtered out 1. *Writing* - The IR is pretty printed to a file or `stdout` ## Process Flow The main interface for `cbindgen` is `bindgen::Builder` which accepts configuration options and either a crate directory to parse or a list of source files. If a list of source files is given, then `bindgen::Builder` will parse them using `parser::parse_src` which will use `syn` to parse a specific file. No `extern crate` items will be followed for dependencies, but `mod` items will be attempted to be followed. If a crate directory is given, then `bindgen::Builder` will use `cargo::Cargo` to load a dependency graph from `Cargo.toml`, `Cargo.lock`, and `cargo metadata`. Then `parser::parse_lib` will parse each crate, following `extern crate` items when `ParseConfig::parse_deps` is enabled and the crate is not in the whitelist or blacklist of crates. In addition `bindgen::Parser` may use `cargo expand` on a crate to expand macro definitions. Once the `syn` nodes are collected by either method, they are given to `bindgen::Parse` which will perform *Loading* by creating a `ir::Item` for each `syn` node as appropriate. `bindgen::Builder` will then convert the resulting `bindgen::Parse`'s into a `bindgen::Library` which is the driver of all of the *Transformation* passes. // TODO - Talk more about passes Then finally the `bindgen::Library` will create a `bindgen::Bindings` which contains the `ir::Item`'s that are ready to be written. The `bindgen::Bindings` can then be written to `stdout` or a specific file. cbindgen-0.12.1/src/bindgen/bindings.rs010066400017500001750000000276011360223554200161370ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::fs::File; use std::io::{Read, Write}; use std::path; use std::rc::Rc; use crate::bindgen::config::{Config, Language}; use crate::bindgen::ir::{ Constant, Function, ItemContainer, ItemMap, Path as BindgenPath, Static, Struct, }; use crate::bindgen::writer::{Source, SourceWriter}; /// A bindings header that can be written. pub struct Bindings { pub config: Config, /// The map from path to struct, used to lookup whether a given type is a /// transparent struct. This is needed to generate code for constants. struct_map: ItemMap, struct_fileds_memo: RefCell>>>, globals: Vec, constants: Vec, items: Vec, functions: Vec, } #[derive(PartialEq)] enum NamespaceOperation { Open, Close, } impl Bindings { pub(crate) fn new( config: Config, struct_map: ItemMap, constants: Vec, globals: Vec, items: Vec, functions: Vec, ) -> Bindings { Bindings { config, struct_map, struct_fileds_memo: Default::default(), globals, constants, items, functions, } } // FIXME(emilio): What to do when the configuration doesn't match? pub fn struct_is_transparent(&self, path: &BindgenPath) -> bool { let mut any = false; self.struct_map.for_items(path, |s| any |= s.is_transparent); any } pub fn struct_exists(&self, path: &BindgenPath) -> bool { let mut any = false; self.struct_map.for_items(path, |_| any = true); any } pub fn struct_field_names(&self, path: &BindgenPath) -> Rc> { let mut memos = self.struct_fileds_memo.borrow_mut(); if let Some(memo) = memos.get(path) { return memo.clone(); } let mut fields = Vec::::new(); self.struct_map.for_items(path, |st| { let mut pos: usize = 0; for field in &st.fields { if let Some(found_pos) = fields.iter().position(|v| *v == field.0) { pos = found_pos + 1; } else { fields.insert(pos, field.0.clone()); pos += 1; } } }); let fields = Rc::new(fields); memos.insert(path.clone(), fields.clone()); fields } pub fn write_to_file>(&self, path: P) -> bool { // Don't compare files if we've never written this file before if !path.as_ref().is_file() { if let Some(parent) = path::Path::new(path.as_ref()).parent() { fs::create_dir_all(parent).unwrap(); } self.write(File::create(path).unwrap()); return true; } let mut new_file_contents = Vec::new(); self.write(&mut new_file_contents); let mut old_file_contents = Vec::new(); { let mut old_file = File::open(&path).unwrap(); old_file.read_to_end(&mut old_file_contents).unwrap(); } if old_file_contents != new_file_contents { let mut new_file = File::create(&path).unwrap(); new_file.write_all(&new_file_contents).unwrap(); true } else { false } } pub fn write_headers(&self, out: &mut SourceWriter) { if let Some(ref f) = self.config.header { out.new_line_if_not_start(); write!(out, "{}", f); out.new_line(); } if let Some(ref f) = self.config.include_guard { out.new_line_if_not_start(); write!(out, "#ifndef {}", f); out.new_line(); write!(out, "#define {}", f); out.new_line(); } if self.config.include_version { out.new_line_if_not_start(); write!( out, "/* Generated with cbindgen:{} */", crate::bindgen::config::VERSION ); out.new_line(); } if let Some(ref f) = self.config.autogen_warning { out.new_line_if_not_start(); write!(out, "{}", f); out.new_line(); } if self.config.no_includes && self.config.sys_includes.is_empty() && self.config.includes.is_empty() { return; } out.new_line_if_not_start(); if !self.config.no_includes { if self.config.language == Language::C { out.write("#include "); out.new_line(); out.write("#include "); out.new_line(); out.write("#include "); out.new_line(); out.write("#include "); out.new_line(); } else { out.write("#include "); out.new_line(); out.write("#include "); out.new_line(); out.write("#include "); out.new_line(); out.write("#include "); out.new_line(); if self.config.enumeration.cast_assert_name.is_none() && (self.config.enumeration.derive_mut_casts || self.config.enumeration.derive_const_casts) { out.write("#include "); out.new_line(); } } } for include in &self.config.sys_includes { write!(out, "#include <{}>", include); out.new_line(); } for include in &self.config.includes { write!(out, "#include \"{}\"", include); out.new_line(); } } pub fn write(&self, file: F) { let mut out = SourceWriter::new(file, self); self.write_headers(&mut out); self.open_namespaces(&mut out); for constant in &self.constants { if constant.ty.is_primitive_or_ptr_primitive() { out.new_line_if_not_start(); constant.write(&self.config, &mut out, None); out.new_line(); } } for item in &self.items { if item .deref() .annotations() .bool("no-export") .unwrap_or(false) { continue; } out.new_line_if_not_start(); match *item { ItemContainer::Constant(..) => unreachable!(), ItemContainer::Static(..) => unreachable!(), ItemContainer::Enum(ref x) => x.write(&self.config, &mut out), ItemContainer::Struct(ref x) => x.write(&self.config, &mut out), ItemContainer::Union(ref x) => x.write(&self.config, &mut out), ItemContainer::OpaqueItem(ref x) => x.write(&self.config, &mut out), ItemContainer::Typedef(ref x) => x.write(&self.config, &mut out), } out.new_line(); } for constant in &self.constants { if !constant.ty.is_primitive_or_ptr_primitive() { out.new_line_if_not_start(); constant.write(&self.config, &mut out, None); out.new_line(); } } if !self.functions.is_empty() || !self.globals.is_empty() { if self.config.language == Language::C && self.config.cpp_compat { out.new_line_if_not_start(); out.write("#ifdef __cplusplus"); } if self.config.language == Language::Cxx { if let Some(ref using_namespaces) = self.config.using_namespaces { for namespace in using_namespaces { out.new_line(); write!(out, "using namespace {};", namespace); } out.new_line(); } } if self.config.language == Language::Cxx || self.config.cpp_compat { out.new_line(); out.write("extern \"C\" {"); out.new_line(); } if self.config.language == Language::C && self.config.cpp_compat { out.write("#endif // __cplusplus"); out.new_line(); } for global in &self.globals { out.new_line_if_not_start(); global.write(&self.config, &mut out); out.new_line(); } for function in &self.functions { out.new_line_if_not_start(); function.write(&self.config, &mut out); out.new_line(); } if self.config.language == Language::C && self.config.cpp_compat { out.new_line(); out.write("#ifdef __cplusplus"); } if self.config.language == Language::Cxx || self.config.cpp_compat { out.new_line(); out.write("} // extern \"C\""); out.new_line(); } if self.config.language == Language::C && self.config.cpp_compat { out.write("#endif // __cplusplus"); out.new_line(); } } self.close_namespaces(&mut out); if let Some(ref f) = self.config.include_guard { out.new_line_if_not_start(); if self.config.language == Language::C { write!(out, "#endif /* {} */", f); } else { write!(out, "#endif // {}", f); } out.new_line(); } if let Some(ref f) = self.config.trailer { out.new_line_if_not_start(); write!(out, "{}", f); out.new_line(); } } fn all_namespaces(&self) -> Vec<&str> { if self.config.language != Language::Cxx && !self.config.cpp_compat { return vec![]; } let mut ret = vec![]; if let Some(ref namespace) = self.config.namespace { ret.push(&**namespace); } if let Some(ref namespaces) = self.config.namespaces { for namespace in namespaces { ret.push(&**namespace); } } ret } fn open_close_namespaces(&self, op: NamespaceOperation, out: &mut SourceWriter) { let mut namespaces = self.all_namespaces(); if namespaces.is_empty() { return; } if op == NamespaceOperation::Close { namespaces.reverse(); } let write_ifdefs = self.config.cpp_compat && self.config.language == Language::C; if write_ifdefs { out.new_line_if_not_start(); out.write("#ifdef __cplusplus"); } for namespace in namespaces { out.new_line(); match op { NamespaceOperation::Open => write!(out, "namespace {} {{", namespace), NamespaceOperation::Close => write!(out, "}} // namespace {}", namespace), } } out.new_line(); if write_ifdefs { out.write("#endif // __cplusplus"); out.new_line(); } } pub(crate) fn open_namespaces(&self, out: &mut SourceWriter) { self.open_close_namespaces(NamespaceOperation::Open, out); } pub(crate) fn close_namespaces(&self, out: &mut SourceWriter) { self.open_close_namespaces(NamespaceOperation::Close, out); } } cbindgen-0.12.1/src/bindgen/bitflags.rs010064400017500001750000000065241356501061700161360ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use proc_macro2::TokenStream; use syn; use syn::parse::{Parse, ParseStream, Parser, Result as ParseResult}; // $(#[$outer:meta])* // ($($vis:tt)*) $BitFlags:ident: $T:ty { // $( // $(#[$inner:ident $($args:tt)*])* // const $Flag:ident = $value:expr; // )+ // } #[derive(Debug)] pub struct Bitflags { attrs: Vec, vis: syn::Visibility, struct_token: Token![struct], name: syn::Ident, colon_token: Token![:], repr: syn::Type, flags: Flags, } impl Bitflags { pub fn expand(&self) -> (syn::ItemStruct, syn::ItemImpl) { let Bitflags { ref attrs, ref vis, ref name, ref repr, ref flags, .. } = *self; let struct_ = parse_quote! { /// cbindgen:internal-derive-bitflags=true #(#attrs)* #vis struct #name { bits: #repr, } }; let consts = flags.expand(name); let impl_ = parse_quote! { impl #name { #consts } }; (struct_, impl_) } } impl Parse for Bitflags { fn parse(input: ParseStream) -> ParseResult { Ok(Self { attrs: input.call(syn::Attribute::parse_outer)?, vis: input.parse()?, struct_token: input.parse()?, name: input.parse()?, colon_token: input.parse()?, repr: input.parse()?, flags: input.parse()?, }) } } // $(#[$inner:ident $($args:tt)*])* // const $Flag:ident = $value:expr; #[derive(Debug)] struct Flag { attrs: Vec, const_token: Token![const], name: syn::Ident, equals_token: Token![=], value: syn::Expr, semicolon_token: Token![;], } impl Flag { fn expand(&self, struct_name: &syn::Ident) -> TokenStream { let Flag { ref attrs, ref name, ref value, .. } = *self; quote! { #(#attrs)* pub const #name : #struct_name = #struct_name { bits: #value }; } } } impl Parse for Flag { fn parse(input: ParseStream) -> ParseResult { Ok(Self { attrs: input.call(syn::Attribute::parse_outer)?, const_token: input.parse()?, name: input.parse()?, equals_token: input.parse()?, value: input.parse()?, semicolon_token: input.parse()?, }) } } #[derive(Debug)] struct Flags(Vec); impl Parse for Flags { fn parse(input: ParseStream) -> ParseResult { let content; let _ = braced!(content in input); let mut flags = vec![]; while !content.is_empty() { flags.push(content.parse()?); } Ok(Flags(flags)) } } impl Flags { fn expand(&self, struct_name: &syn::Ident) -> TokenStream { let mut ts = quote! {}; for flag in &self.0 { ts.extend(flag.expand(struct_name)); } ts } } pub fn parse(tokens: TokenStream) -> ParseResult { let parser = Bitflags::parse; parser.parse2(tokens) } cbindgen-0.12.1/src/bindgen/builder.rs010066400017500001750000000234751360223554200157750ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::path; use crate::bindgen::bindings::Bindings; use crate::bindgen::cargo::Cargo; use crate::bindgen::config::{Braces, Config, Language}; use crate::bindgen::error::Error; use crate::bindgen::library::Library; use crate::bindgen::parser::{self, Parse}; /// A builder for generating a bindings header. #[derive(Debug, Clone)] pub struct Builder { config: Config, srcs: Vec, lib: Option<(path::PathBuf, Option)>, lib_cargo: Option, std_types: bool, lockfile: Option, } impl Builder { pub fn new() -> Builder { Builder { config: Config::default(), srcs: Vec::new(), lib: None, lib_cargo: None, std_types: true, lockfile: None, } } #[allow(unused)] pub fn with_header>(mut self, header: S) -> Builder { self.config.header = Some(String::from(header.as_ref())); self } #[allow(unused)] pub fn with_no_includes(mut self) -> Builder { self.config.no_includes = true; self } #[allow(unused)] pub fn with_include>(mut self, include: S) -> Builder { self.config.includes.push(String::from(include.as_ref())); self } #[allow(unused)] pub fn with_sys_include>(mut self, include: S) -> Builder { self.config .sys_includes .push(String::from(include.as_ref())); self } #[allow(unused)] pub fn with_trailer>(mut self, trailer: S) -> Builder { self.config.trailer = Some(String::from(trailer.as_ref())); self } #[allow(unused)] pub fn with_include_guard>(mut self, include_guard: S) -> Builder { self.config.include_guard = Some(String::from(include_guard.as_ref())); self } #[allow(unused)] pub fn with_autogen_warning>(mut self, autogen_warning: S) -> Builder { self.config.autogen_warning = Some(String::from(autogen_warning.as_ref())); self } #[allow(unused)] pub fn with_include_version(mut self, include_version: bool) -> Builder { self.config.include_version = include_version; self } #[allow(unused)] pub fn with_namespace>(mut self, namespace: S) -> Builder { self.config.namespace = Some(String::from(namespace.as_ref())); self } #[allow(unused)] pub fn with_namespaces>(mut self, namespaces: &[S]) -> Builder { self.config.namespaces = Some( namespaces .iter() .map(|x| String::from(x.as_ref())) .collect(), ); self } #[allow(unused)] pub fn with_braces(mut self, braces: Braces) -> Builder { self.config.braces = braces; self } #[allow(unused)] pub fn with_line_length(mut self, line_length: usize) -> Builder { self.config.line_length = line_length; self } #[allow(unused)] pub fn with_tab_width(mut self, tab_width: usize) -> Builder { self.config.tab_width = tab_width; self } #[allow(unused)] pub fn with_language(mut self, language: Language) -> Builder { self.config.language = language; self } #[allow(unused)] pub fn include_item>(mut self, item_name: S) -> Builder { self.config .export .include .push(String::from(item_name.as_ref())); self } #[allow(unused)] pub fn exclude_item>(mut self, item_name: S) -> Builder { self.config .export .exclude .push(String::from(item_name.as_ref())); self } #[allow(unused)] pub fn rename_item>(mut self, from: S, to: S) -> Builder { self.config .export .rename .insert(String::from(from.as_ref()), String::from(to.as_ref())); self } #[allow(unused)] pub fn with_item_prefix>(mut self, prefix: S) -> Builder { self.config.export.prefix = Some(String::from(prefix.as_ref())); self } #[allow(unused)] pub fn with_parse_deps(mut self, parse_deps: bool) -> Builder { self.config.parse.parse_deps = parse_deps; self } #[allow(unused)] pub fn with_parse_include>(mut self, include: &[S]) -> Builder { self.config.parse.include = Some(include.iter().map(|x| String::from(x.as_ref())).collect()); self } #[allow(unused)] pub fn with_parse_exclude>(mut self, exclude: &[S]) -> Builder { self.config.parse.exclude = exclude.iter().map(|x| String::from(x.as_ref())).collect(); self } #[allow(unused)] pub fn with_parse_expand>(mut self, expand: &[S]) -> Builder { self.config.parse.expand.crates = expand.iter().map(|x| String::from(x.as_ref())).collect(); self } #[allow(unused)] pub fn with_parse_expand_all_features(mut self, expand_all_features: bool) -> Builder { self.config.parse.expand.all_features = expand_all_features; self } #[allow(unused)] pub fn with_parse_expand_default_features(mut self, expand_default_features: bool) -> Builder { self.config.parse.expand.default_features = expand_default_features; self } #[allow(unused)] pub fn with_parse_expand_features>(mut self, expand_features: &[S]) -> Builder { self.config.parse.expand.features = Some( expand_features .iter() .map(|x| String::from(x.as_ref())) .collect(), ); self } #[allow(unused)] pub fn with_documentation(mut self, documentation: bool) -> Builder { self.config.documentation = documentation; self } #[allow(unused)] pub fn with_target_os_define(mut self, platform: &str, preprocessor_define: &str) -> Builder { self.config.defines.insert( format!("target_os = {}", platform), preprocessor_define.to_owned(), ); self } #[allow(unused)] pub fn with_define(mut self, key: &str, value: &str, preprocessor_define: &str) -> Builder { self.config.defines.insert( format!("{} = {}", key, value), preprocessor_define.to_owned(), ); self } #[allow(unused)] pub fn with_config(mut self, config: Config) -> Builder { self.config = config; self } #[allow(unused)] pub fn with_std_types(mut self, std_types: bool) -> Builder { self.std_types = std_types; self } #[allow(unused)] pub fn with_src>(mut self, src: P) -> Builder { self.srcs.push(src.as_ref().to_owned()); self } #[allow(unused)] pub fn with_crate>(mut self, lib_dir: P) -> Builder { debug_assert!(self.lib.is_none()); debug_assert!(self.lib_cargo.is_none()); self.lib = Some((path::PathBuf::from(lib_dir.as_ref()), None)); self } #[allow(unused)] pub fn with_crate_and_name, S: AsRef>( mut self, lib_dir: P, binding_lib_name: S, ) -> Builder { debug_assert!(self.lib.is_none()); debug_assert!(self.lib_cargo.is_none()); self.lib = Some(( path::PathBuf::from(lib_dir.as_ref()), Some(String::from(binding_lib_name.as_ref())), )); self } #[allow(unused)] pub(crate) fn with_cargo(mut self, lib: Cargo) -> Builder { debug_assert!(self.lib.is_none()); debug_assert!(self.lib_cargo.is_none()); self.lib_cargo = Some(lib); self } #[allow(unused)] pub fn with_lockfile>(mut self, lockfile: P) -> Builder { debug_assert!(self.lockfile.is_none()); debug_assert!(self.lib_cargo.is_none()); self.lockfile = Some(path::PathBuf::from(lockfile.as_ref())); self } pub fn generate(self) -> Result { let mut result = Parse::new(); if self.std_types { result.add_std_types(); } for x in &self.srcs { result.extend_with(&parser::parse_src(x, &self.config)?); } if let Some((lib_dir, binding_lib_name)) = self.lib.clone() { let lockfile = self.lockfile.as_ref().and_then(|p| p.to_str()); let cargo = if let Some(binding_lib_name) = binding_lib_name { Cargo::load( &lib_dir, lockfile, Some(&binding_lib_name), self.config.parse.parse_deps, self.config.parse.clean, )? } else { Cargo::load( &lib_dir, lockfile, None, self.config.parse.parse_deps, self.config.parse.clean, )? }; result.extend_with(&parser::parse_lib(cargo, &self.config)?); } else if let Some(cargo) = self.lib_cargo.clone() { result.extend_with(&parser::parse_lib(cargo, &self.config)?); } Library::new( self.config, result.constants, result.globals, result.enums, result.structs, result.unions, result.opaque_items, result.typedefs, result.functions, ) .generate() } } cbindgen-0.12.1/src/bindgen/cargo/cargo.rs010066400017500001750000000166361360223554200165360ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::path::{Path, PathBuf}; use crate::bindgen::cargo::cargo_expand; use crate::bindgen::cargo::cargo_lock::{self, Lock}; pub(crate) use crate::bindgen::cargo::cargo_metadata::PackageRef; use crate::bindgen::cargo::cargo_metadata::{self, Metadata}; use crate::bindgen::cargo::cargo_toml; use crate::bindgen::error::Error; use crate::bindgen::ir::Cfg; /// Parse a dependency string used in Cargo.lock fn parse_dep_string(dep_string: &str) -> (&str, Option<&str>) { let split: Vec<&str> = dep_string.split_whitespace().collect(); (split[0], split.get(1).cloned()) } /// A collection of metadata for a library from cargo. #[derive(Clone, Debug)] pub(crate) struct Cargo { manifest_path: PathBuf, binding_crate_name: String, lock: Option, metadata: Metadata, clean: bool, } impl Cargo { /// Gather metadata from cargo for a specific library and binding crate /// name. If dependency finding isn't needed then Cargo.lock files don't /// need to be parsed. pub(crate) fn load( crate_dir: &Path, lock_file: Option<&str>, binding_crate_name: Option<&str>, use_cargo_lock: bool, clean: bool, ) -> Result { let toml_path = crate_dir.join("Cargo.toml"); let metadata = cargo_metadata::metadata(&toml_path) .map_err(|x| Error::CargoMetadata(toml_path.to_str().unwrap().to_owned(), x))?; let lock_path = lock_file .map(PathBuf::from) .unwrap_or_else(|| Path::new(&metadata.workspace_root).join("Cargo.lock")); let lock = if use_cargo_lock { match cargo_lock::lock(&lock_path) { Ok(lock) => Some(lock), Err(x) => { warn!("Couldn't load lock file {:?}: {:?}", lock_path, x); None } } } else { None }; // Use the specified binding crate name or infer it from the manifest let manifest = cargo_toml::manifest(&toml_path) .map_err(|x| Error::CargoToml(toml_path.to_str().unwrap().to_owned(), x))?; let binding_crate_name = binding_crate_name.map_or(manifest.package.name.clone(), |x| x.to_owned()); Ok(Cargo { manifest_path: toml_path, binding_crate_name, lock, metadata, clean, }) } pub(crate) fn binding_crate_name(&self) -> &str { &self.binding_crate_name } pub(crate) fn binding_crate_ref(&self) -> PackageRef { match self.find_pkg_ref(&self.binding_crate_name) { Some(pkg_ref) => pkg_ref, None => panic!( "Unable to find {} for {:?}", self.binding_crate_name, self.manifest_path ), } } pub(crate) fn dependencies(&self, package: &PackageRef) -> Vec<(PackageRef, Option)> { let lock = match self.lock { Some(ref lock) => lock, None => return vec![], }; let mut dependencies = None; // Find the dependencies listing in the lockfile if let Some(ref root) = lock.root { // If the version is not on the lockfile then it shouldn't be // ambiguous. if root.name == package.name && package .version .as_ref() .map_or(true, |v| *v == root.version) { dependencies = root.dependencies.as_ref(); } } if dependencies.is_none() { if let Some(ref lock_packages) = lock.package { for lock_package in lock_packages { if lock_package.name == package.name && package .version .as_ref() .map_or(true, |v| *v == lock_package.version) { dependencies = lock_package.dependencies.as_ref(); break; } } } } if dependencies.is_none() { return vec![]; } dependencies .unwrap() .iter() .map(|dep| { let (dep_name, dep_version) = parse_dep_string(dep); // Try to find the cfgs in the Cargo.toml let cfg = self .metadata .packages .get(package) .and_then(|meta_package| meta_package.dependencies.get(dep_name)) .and_then(|meta_dep| Cfg::load_metadata(meta_dep)); let package_ref = PackageRef { name: dep_name.to_owned(), version: dep_version.map(|v| v.to_owned()), }; (package_ref, cfg) }) .collect() } /// Finds the package reference in `cargo metadata` that has `package_name` /// ignoring the version. fn find_pkg_ref(&self, package_name: &str) -> Option { for package in &self.metadata.packages { if package.name_and_version.name == package_name { return Some(package.name_and_version.clone()); } } None } /// Finds the directory for a specified package reference. #[allow(unused)] pub(crate) fn find_crate_dir(&self, package: &PackageRef) -> Option { self.metadata .packages .get(package) .and_then(|meta_package| { Path::new(&meta_package.manifest_path) .parent() .map(|x| x.to_owned()) }) } /// Finds `src/lib.rs` for a specified package reference. pub(crate) fn find_crate_src(&self, package: &PackageRef) -> Option { let kind_lib = String::from("lib"); let kind_staticlib = String::from("staticlib"); let kind_rlib = String::from("rlib"); let kind_cdylib = String::from("cdylib"); let kind_dylib = String::from("dylib"); self.metadata .packages .get(package) .and_then(|meta_package| { for target in &meta_package.targets { if target.kind.contains(&kind_lib) || target.kind.contains(&kind_staticlib) || target.kind.contains(&kind_rlib) || target.kind.contains(&kind_cdylib) || target.kind.contains(&kind_dylib) { return Some(PathBuf::from(&target.src_path)); } } None }) } pub(crate) fn expand_crate( &self, package: &PackageRef, expand_all_features: bool, expand_default_features: bool, expand_features: &Option>, ) -> Result { cargo_expand::expand( &self.manifest_path, &package.name, package.version.as_ref().map(|v| &**v), self.clean, expand_all_features, expand_default_features, expand_features, ) } } cbindgen-0.12.1/src/bindgen/cargo/cargo_expand.rs010066400017500001750000000100761360223554200200650ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::env; use std::error; use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::process::Command; use std::str::{from_utf8, Utf8Error}; extern crate tempfile; use self::tempfile::Builder; #[derive(Debug)] /// Possible errors that can occur during `rustc --pretty=expanded`. pub enum Error { /// Error during creation of temporary directory Io(io::Error), /// Output of `cargo metadata` was not valid utf8 Utf8(Utf8Error), /// Error during execution of `cargo rustc --pretty=expanded` Compile(String), } impl From for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } impl From for Error { fn from(err: Utf8Error) -> Self { Error::Utf8(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::Io(ref err) => err.fmt(f), Error::Utf8(ref err) => err.fmt(f), Error::Compile(ref err) => write!(f, "{}", err), } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::Io(ref err) => Some(err), Error::Utf8(ref err) => Some(err), Error::Compile(..) => None, } } } /// Use rustc to expand and pretty print the crate into a single file, /// removing any macros in the process. pub fn expand( manifest_path: &Path, crate_name: &str, version: Option<&str>, use_tempdir: bool, expand_all_features: bool, expand_default_features: bool, expand_features: &Option>, ) -> Result { let cargo = env::var("CARGO").unwrap_or_else(|_| String::from("cargo")); let mut cmd = Command::new(cargo); let mut _temp_dir = None; // drop guard if use_tempdir { _temp_dir = Some(Builder::new().prefix("cbindgen-expand").tempdir()?); cmd.env("CARGO_TARGET_DIR", _temp_dir.unwrap().path()); } else if let Ok(ref path) = env::var("CARGO_EXPAND_TARGET_DIR") { cmd.env("CARGO_TARGET_DIR", path); } else if let Ok(ref path) = env::var("OUT_DIR") { // When cbindgen was started programatically from a build.rs file, Cargo is running and // locking the default target directory. In this case we need to use another directory, // else we would end up in a deadlock. If Cargo is running `OUT_DIR` will be set, so we // can use a directory relative to that. cmd.env("CARGO_TARGET_DIR", PathBuf::from(path).join("expanded")); } // Set this variable so that we don't call it recursively if we expand a crate that is using // cbindgen cmd.env("_CBINDGEN_IS_RUNNING", "1"); cmd.arg("rustc"); cmd.arg("--lib"); cmd.arg("--manifest-path"); cmd.arg(manifest_path); if let Some(features) = expand_features { cmd.arg("--features"); let mut features_str = String::new(); for (index, feature) in features.iter().enumerate() { if index != 0 { features_str.push_str(" "); } features_str.push_str(feature); } cmd.arg(features_str); } if expand_all_features { cmd.arg("--all-features"); } if !expand_default_features { cmd.arg("--no-default-features"); } cmd.arg("-p"); let mut package = crate_name.to_owned(); if let Some(version) = version { package.push_str(":"); package.push_str(version); } cmd.arg(&package); cmd.arg("--verbose"); cmd.arg("--"); cmd.arg("-Z"); cmd.arg("unstable-options"); cmd.arg("--pretty=expanded"); info!("Command: {:?}", cmd); let output = cmd.output()?; let src = from_utf8(&output.stdout)?.to_owned(); let error = from_utf8(&output.stderr)?.to_owned(); if src.is_empty() { Err(Error::Compile(error)) } else { Ok(src) } } cbindgen-0.12.1/src/bindgen/cargo/cargo_lock.rs010066400017500001750000000025031360223554200175320ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::fs::File; use std::io; use std::io::Read; use std::path::Path; use toml; #[derive(Debug)] /// Possible errors that can occur during Cargo.toml parsing. pub enum Error { /// Error during reading of Cargo.toml Io(io::Error), /// Deserialization error Toml(toml::de::Error), } impl From for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } impl From for Error { fn from(err: toml::de::Error) -> Self { Error::Toml(err) } } #[derive(Clone, Deserialize, Debug)] pub struct Lock { pub root: Option, pub package: Option>, } #[derive(Clone, Deserialize, Debug)] pub struct Package { pub name: String, pub version: String, /// A list of dependencies formatted like "NAME VERSION-OPT REGISTRY-OPT" pub dependencies: Option>, } /// Parse the Cargo.toml for a given path pub fn lock(manifest_path: &Path) -> Result { let mut s = String::new(); let mut f = File::open(manifest_path)?; f.read_to_string(&mut s)?; toml::from_str::(&s).map_err(|x| x.into()) } cbindgen-0.12.1/src/bindgen/cargo/cargo_metadata.rs010066400017500001750000000127761360223554200203770ustar0000000000000000#![deny(missing_docs)] //! Structured access to the output of `cargo metadata` //! Usually used from within a `cargo-*` executable // Forked from `https://github.com/oli-obk/cargo_metadata` // Modifications: // 1. Remove `resolve` from Metadata because it was causing parse failures // 2. Fix the `manifest-path` argument // 3. Add `--all-features` argument // 4. Remove the `--no-deps` argument use std::borrow::Borrow; use std::collections::{HashMap, HashSet}; use std::env; use std::error; use std::fmt; use std::hash::{Hash, Hasher}; use std::io; use std::path::Path; use std::process::{Command, Output}; use std::str::{from_utf8, Utf8Error}; use serde_json; #[derive(Clone, Deserialize, Debug)] /// Starting point for metadata returned by `cargo metadata` pub struct Metadata { /// A list of all crates referenced by this crate (and the crate itself) pub packages: HashSet, version: usize, /// path to the workspace containing the `Cargo.lock` pub workspace_root: String, } /// A reference to a package including it's name and the specific version. #[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct PackageRef { pub name: String, pub version: Option, } #[derive(Clone, Deserialize, Debug)] /// A crate pub struct Package { #[serde(flatten)] pub name_and_version: PackageRef, id: String, source: Option, /// List of dependencies of this particular package pub dependencies: HashSet, /// Targets provided by the crate (lib, bin, example, test, ...) pub targets: Vec, features: HashMap>, /// path containing the `Cargo.toml` pub manifest_path: String, } #[derive(Clone, Deserialize, Debug)] /// A dependency of the main crate pub struct Dependency { /// Name as given in the `Cargo.toml` pub name: String, source: Option, /// Whether this is required or optional pub req: String, kind: Option, optional: bool, uses_default_features: bool, features: Vec, pub target: Option, } #[derive(Clone, Deserialize, Debug)] /// A single target (lib, bin, example, ...) provided by a crate pub struct Target { /// Name as given in the `Cargo.toml` or generated from the file name pub name: String, /// Kind of target ("bin", "example", "test", "bench", "lib") pub kind: Vec, /// Almost the same as `kind`, except when an example is a library instad of an executable. /// In that case `crate_types` contains things like `rlib` and `dylib` while `kind` is `example` #[serde(default)] pub crate_types: Vec, /// Path to the main source file of the target pub src_path: String, } #[derive(Debug)] /// Possible errors that can occur during metadata parsing. pub enum Error { /// Error during execution of `cargo metadata` Io(io::Error), /// Metadata extraction failure Metadata(Output), /// Output of `cargo metadata` was not valid utf8 Utf8(Utf8Error), /// Deserialization error (structure of json did not match expected structure) Json(serde_json::Error), } impl From for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } impl From for Error { fn from(err: Utf8Error) -> Self { Error::Utf8(err) } } impl From for Error { fn from(err: serde_json::Error) -> Self { Error::Json(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::Io(ref err) => err.fmt(f), Error::Metadata(_) => write!(f, "Metadata error"), Error::Utf8(ref err) => err.fmt(f), Error::Json(ref err) => err.fmt(f), } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::Io(ref err) => Some(err), Error::Metadata(_) => None, Error::Utf8(ref err) => Some(err), Error::Json(ref err) => Some(err), } } } // Implementations that let us lookup Packages and Dependencies by name (string) impl Borrow for Package { fn borrow(&self) -> &PackageRef { &self.name_and_version } } impl Hash for Package { fn hash(&self, state: &mut H) { self.name_and_version.hash(state); } } impl PartialEq for Package { fn eq(&self, other: &Self) -> bool { self.name_and_version == other.name_and_version } } impl Eq for Package {} impl Borrow for Dependency { fn borrow(&self) -> &str { &self.name } } impl Hash for Dependency { fn hash(&self, state: &mut H) { self.name.hash(state); } } impl PartialEq for Dependency { fn eq(&self, other: &Self) -> bool { self.name == other.name } } impl Eq for Dependency {} /// The main entry point to obtaining metadata pub fn metadata(manifest_path: &Path) -> Result { let cargo = env::var("CARGO").unwrap_or_else(|_| String::from("cargo")); let mut cmd = Command::new(cargo); cmd.arg("metadata"); cmd.arg("--all-features"); cmd.arg("--format-version").arg("1"); cmd.arg("--manifest-path"); cmd.arg(manifest_path.to_str().unwrap()); let output = cmd.output()?; if !output.status.success() { return Err(Error::Metadata(output)); } let stdout = from_utf8(&output.stdout)?; let meta: Metadata = serde_json::from_str(stdout)?; Ok(meta) } cbindgen-0.12.1/src/bindgen/cargo/cargo_toml.rs010064400017500001750000000031641356501061700175610ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::error; use std::fmt; use std::fs::File; use std::io; use std::io::Read; use std::path::Path; use toml; #[derive(Debug)] /// Possible errors that can occur during Cargo.toml parsing. pub enum Error { /// Error during reading of Cargo.toml Io(io::Error), /// Deserialization error Toml(toml::de::Error), } impl From for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } impl From for Error { fn from(err: toml::de::Error) -> Self { Error::Toml(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::Io(ref err) => err.fmt(f), Error::Toml(ref err) => err.fmt(f), } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::Io(ref err) => Some(err), Error::Toml(ref err) => Some(err), } } } #[derive(Clone, Deserialize, Debug)] pub struct Manifest { pub package: Package, } #[derive(Clone, Deserialize, Debug)] pub struct Package { pub name: String, } /// Parse the Cargo.toml for a given path pub fn manifest(manifest_path: &Path) -> Result { let mut s = String::new(); let mut f = File::open(manifest_path)?; f.read_to_string(&mut s)?; toml::from_str::(&s).map_err(|x| x.into()) } cbindgen-0.12.1/src/bindgen/cargo/mod.rs010064400017500001750000000005531356501061700162110ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ mod cargo; pub(crate) mod cargo_expand; pub(crate) mod cargo_lock; pub(crate) mod cargo_metadata; pub(crate) mod cargo_toml; pub(crate) use self::cargo::*; cbindgen-0.12.1/src/bindgen/cdecl.rs010066400017500001750000000231171360223554200154120ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use crate::bindgen::declarationtyperesolver::DeclarationType; use crate::bindgen::ir::{Function, Type}; use crate::bindgen::writer::{ListType, SourceWriter}; // This code is for translating Rust types into C declarations. // See Section 6.7, Declarations, in the C standard for background. // http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf enum CDeclarator { Ptr(bool), Ref, Array(String), Func(Vec<(Option, CDecl)>, bool), } impl CDeclarator { fn is_ptr(&self) -> bool { match self { CDeclarator::Ptr(..) | CDeclarator::Ref | CDeclarator::Func(..) => true, _ => false, } } } struct CDecl { type_qualifers: String, type_name: String, type_generic_args: Vec, declarators: Vec, type_ctype: Option, } impl CDecl { fn new() -> CDecl { CDecl { type_qualifers: String::new(), type_name: String::new(), type_generic_args: Vec::new(), declarators: Vec::new(), type_ctype: None, } } fn from_type(t: &Type) -> CDecl { let mut cdecl = CDecl::new(); cdecl.build_type(t, false); cdecl } fn from_func(f: &Function, layout_vertical: bool) -> CDecl { let mut cdecl = CDecl::new(); cdecl.build_func(f, layout_vertical); cdecl } fn build_func(&mut self, f: &Function, layout_vertical: bool) { let args = f .args .iter() .map(|&(ref arg_name, ref arg_ty)| (Some(arg_name.clone()), CDecl::from_type(arg_ty))) .collect(); self.declarators .push(CDeclarator::Func(args, layout_vertical)); self.build_type(&f.ret, false); } fn build_type(&mut self, t: &Type, is_const: bool) { match t { Type::Path(ref generic) => { if is_const { assert!( self.type_qualifers.is_empty(), "error generating cdecl for {:?}", t ); self.type_qualifers = "const".to_owned(); } assert!( self.type_name.is_empty(), "error generating cdecl for {:?}", t ); self.type_name = generic.export_name().to_owned(); assert!( self.type_generic_args.is_empty(), "error generating cdecl for {:?}", t ); self.type_generic_args = generic.generics().to_owned(); self.type_ctype = generic.ctype().cloned(); } Type::Primitive(ref p) => { if is_const { assert!( self.type_qualifers.is_empty(), "error generating cdecl for {:?}", t ); self.type_qualifers = "const".to_owned(); } assert!( self.type_name.is_empty(), "error generating cdecl for {:?}", t ); self.type_name = p.to_string(); } Type::ConstPtr(ref t) => { self.declarators.push(CDeclarator::Ptr(is_const)); self.build_type(t, true); } Type::Ptr(ref t) => { self.declarators.push(CDeclarator::Ptr(is_const)); self.build_type(t, false); } Type::Ref(ref t) => { self.declarators.push(CDeclarator::Ref); self.build_type(t, true); } Type::MutRef(ref t) => { self.declarators.push(CDeclarator::Ref); self.build_type(t, false); } Type::Array(ref t, ref constant) => { let len = constant.as_str().to_owned(); self.declarators.push(CDeclarator::Array(len)); self.build_type(t, is_const); } Type::FuncPtr(ref ret, ref args) => { let args = args .iter() .map(|(ref name, ref ty)| (name.clone(), CDecl::from_type(ty))) .collect(); self.declarators.push(CDeclarator::Ptr(false)); self.declarators.push(CDeclarator::Func(args, false)); self.build_type(ret, false); } } } fn write( &self, out: &mut SourceWriter, ident: Option<&str>, void_prototype: bool, ) { // Write the type-specifier and type-qualifier first if !self.type_qualifers.is_empty() { write!(out, "{} ", self.type_qualifers); } if let Some(ref ctype) = self.type_ctype { write!(out, "{} ", ctype.to_str()); } write!(out, "{}", self.type_name); if !self.type_generic_args.is_empty() { out.write("<"); out.write_horizontal_source_list(&self.type_generic_args, ListType::Join(", ")); out.write(">"); } // When we have an identifier, put a space between the type and the declarators if ident.is_some() { out.write(" "); } // Write the left part of declarators before the identifier let mut iter_rev = self.declarators.iter().rev().peekable(); #[allow(clippy::while_let_on_iterator)] while let Some(declarator) = iter_rev.next() { let next_is_pointer = iter_rev.peek().map_or(false, |x| x.is_ptr()); match *declarator { CDeclarator::Ptr(ref is_const) => { if *is_const { out.write("*const "); } else { out.write("*"); } } CDeclarator::Ref => { out.write("&"); } CDeclarator::Array(..) => { if next_is_pointer { out.write("("); } } CDeclarator::Func(..) => { if next_is_pointer { out.write("("); } } } } // Write the identifier if let Some(ident) = ident { write!(out, "{}", ident); } // Write the right part of declarators after the identifier let mut iter = self.declarators.iter(); let mut last_was_pointer = false; #[allow(clippy::while_let_on_iterator)] while let Some(declarator) = iter.next() { match *declarator { CDeclarator::Ptr(..) => { last_was_pointer = true; } CDeclarator::Ref => { last_was_pointer = true; } CDeclarator::Array(ref constant) => { if last_was_pointer { out.write(")"); } write!(out, "[{}]", constant); last_was_pointer = false; } CDeclarator::Func(ref args, layout_vertical) => { if last_was_pointer { out.write(")"); } out.write("("); if args.is_empty() && void_prototype { out.write("void"); } if layout_vertical { let align_length = out.line_length_for_align(); out.push_set_spaces(align_length); for (i, &(ref arg_ident, ref arg_ty)) in args.iter().enumerate() { if i != 0 { out.write(","); out.new_line(); } // Convert &Option to Option<&str> let arg_ident = arg_ident.as_ref().map(|x| x.as_ref()); arg_ty.write(out, arg_ident, void_prototype); } out.pop_tab(); } else { for (i, &(ref arg_ident, ref arg_ty)) in args.iter().enumerate() { if i != 0 { out.write(", "); } // Convert &Option to Option<&str> let arg_ident = arg_ident.as_ref().map(|x| x.as_ref()); arg_ty.write(out, arg_ident, void_prototype); } } out.write(")"); last_was_pointer = true; } } } } } pub fn write_func( out: &mut SourceWriter, f: &Function, layout_vertical: bool, void_prototype: bool, ) { CDecl::from_func(f, layout_vertical).write(out, Some(f.path().name()), void_prototype); } pub fn write_field(out: &mut SourceWriter, t: &Type, ident: &str) { CDecl::from_type(t).write(out, Some(ident), false); } pub fn write_type(out: &mut SourceWriter, t: &Type) { CDecl::from_type(t).write(out, None, false); } cbindgen-0.12.1/src/bindgen/config.rs010066400017500001750000000643241360223554200156120ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::HashMap; use std::default::Default; use std::str::FromStr; use std::{fmt, fs, path::Path as StdPath}; use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer}; use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; use toml; use crate::bindgen::ir::annotation::AnnotationSet; use crate::bindgen::ir::path::Path; use crate::bindgen::ir::repr::ReprAlign; pub use crate::bindgen::rename::RenameRule; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); /// A language type to generate bindings for. #[derive(Debug, Copy, Clone, PartialEq)] pub enum Language { Cxx, C, } impl FromStr for Language { type Err = String; fn from_str(s: &str) -> Result { match s { "cxx" => Ok(Language::Cxx), "Cxx" => Ok(Language::Cxx), "CXX" => Ok(Language::Cxx), "cpp" => Ok(Language::Cxx), "Cpp" => Ok(Language::Cxx), "CPP" => Ok(Language::Cxx), "c++" => Ok(Language::Cxx), "C++" => Ok(Language::Cxx), "c" => Ok(Language::C), "C" => Ok(Language::C), _ => Err(format!("Unrecognized Language: '{}'.", s)), } } } deserialize_enum_str!(Language); /// A style of braces to use for generating code. #[derive(Debug, Clone, PartialEq)] pub enum Braces { SameLine, NextLine, } impl FromStr for Braces { type Err = String; fn from_str(s: &str) -> Result { match s { "SameLine" => Ok(Braces::SameLine), "same_line" => Ok(Braces::SameLine), "NextLine" => Ok(Braces::NextLine), "next_line" => Ok(Braces::NextLine), _ => Err(format!("Unrecognized Braces: '{}'.", s)), } } } deserialize_enum_str!(Braces); /// A type of layout to use when generating long lines of code. #[derive(Debug, Clone, PartialEq)] pub enum Layout { Horizontal, Vertical, Auto, } impl FromStr for Layout { type Err = String; fn from_str(s: &str) -> Result { match s { "Horizontal" => Ok(Layout::Horizontal), "horizontal" => Ok(Layout::Horizontal), "Vertical" => Ok(Layout::Vertical), "vertical" => Ok(Layout::Vertical), "Auto" => Ok(Layout::Auto), "auto" => Ok(Layout::Auto), _ => Err(format!("Unrecognized Layout: '{}'.", s)), } } } deserialize_enum_str!(Layout); /// How the comments containing documentation should be styled. #[derive(Debug, Clone, PartialEq, Copy)] pub enum DocumentationStyle { C, C99, Doxy, Cxx, Auto, } impl FromStr for DocumentationStyle { type Err = String; fn from_str(s: &str) -> Result { match s.to_lowercase().as_ref() { "c" => Ok(DocumentationStyle::C), "c99" => Ok(DocumentationStyle::C99), "cxx" => Ok(DocumentationStyle::Cxx), "c++" => Ok(DocumentationStyle::Cxx), "doxy" => Ok(DocumentationStyle::Doxy), "auto" => Ok(DocumentationStyle::Auto), _ => Err(format!("Unrecognized documentation style: '{}'.", s)), } } } deserialize_enum_str!(DocumentationStyle); /// A style of Style to use when generating structs and enums. #[derive(Debug, Copy, Clone, PartialEq)] pub enum Style { Both, Tag, Type, } impl Style { pub fn generate_tag(self) -> bool { match self { Style::Both | Style::Tag => true, Style::Type => false, } } pub fn generate_typedef(self) -> bool { match self { Style::Both | Style::Type => true, Style::Tag => false, } } } impl FromStr for Style { type Err = String; fn from_str(s: &str) -> Result { match s { "Both" => Ok(Style::Both), "both" => Ok(Style::Both), "Tag" => Ok(Style::Tag), "tag" => Ok(Style::Tag), "Type" => Ok(Style::Type), "type" => Ok(Style::Type), _ => Err(format!("Unrecognized Style: '{}'.", s)), } } } deserialize_enum_str!(Style); /// Different item types that we can generate and filter. #[derive(Debug, Clone, PartialEq)] pub enum ItemType { Constants, Globals, Enums, Structs, Unions, Typedefs, OpaqueItems, Functions, } impl FromStr for ItemType { type Err = String; fn from_str(s: &str) -> Result { use self::ItemType::*; Ok(match &*s.to_lowercase() { "constants" => Constants, "globals" => Globals, "enums" => Enums, "structs" => Structs, "unions" => Unions, "typedefs" => Typedefs, "opaque" => OpaqueItems, "functions" => Functions, _ => return Err(format!("Unrecognized Style: '{}'.", s)), }) } } deserialize_enum_str!(ItemType); /// Settings to apply when exporting items. #[derive(Debug, Clone, Deserialize, Default)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct ExportConfig { /// A list of additional items not used by exported functions to include in /// the generated bindings pub include: Vec, /// A list of items to not include in the generated bindings pub exclude: Vec, /// Table of name conversions to apply to item names pub rename: HashMap, /// Table of raw strings to append to the body of items. pub body: HashMap, /// A prefix to add before the name of every item pub prefix: Option, /// Types of items to generate. pub item_types: Vec, /// Whether renaming overrides or extends prefixing. pub renaming_overrides_prefixing: bool, } impl ExportConfig { pub(crate) fn should_generate(&self, item_type: ItemType) -> bool { self.item_types.is_empty() || self.item_types.contains(&item_type) } pub(crate) fn extra_body(&self, path: &Path) -> Option<&str> { self.body.get(path.name()).map(|s| s.trim_matches('\n')) } pub(crate) fn rename(&self, item_name: &mut String) { if let Some(name) = self.rename.get(item_name) { *item_name = name.clone(); if self.renaming_overrides_prefixing { return; } } if let Some(ref prefix) = self.prefix { item_name.insert_str(0, &prefix); } } } /// Settings to apply to generated types with layout modifiers. #[derive(Debug, Default, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct LayoutConfig { /// The way to annotate C types as #[repr(packed)]. pub packed: Option, /// The way to annotate C types as #[repr(align(...))]. This is assumed to be a functional /// macro which takes a single argument (the alignment). pub aligned_n: Option, } impl LayoutConfig { pub(crate) fn ensure_safe_to_represent(&self, align: &ReprAlign) -> Result<(), String> { match (align, &self.packed, &self.aligned_n) { (ReprAlign::Packed, None, _) => Err("Cannot safely represent #[repr(packed)] type without configured 'packed' annotation.".to_string()), (ReprAlign::Align(_), _, None) => Err("Cannot safely represent #[repr(aligned(...))] type without configured 'aligned_n' annotation.".to_string()), _ => Ok(()), } } } /// Settings to apply to generated functions. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct FunctionConfig { /// Optional text to output before each function declaration pub prefix: Option, /// Optional text to output after each function declaration pub postfix: Option, /// The way to annotation this function as #[must_use]. pub must_use: Option, /// The style to layout the args pub args: Layout, /// The rename rule to apply to function args pub rename_args: Option, } impl Default for FunctionConfig { fn default() -> FunctionConfig { FunctionConfig { prefix: None, postfix: None, must_use: None, args: Layout::Auto, rename_args: None, } } } impl FunctionConfig { pub(crate) fn prefix(&self, annotations: &AnnotationSet) -> Option { if let Some(x) = annotations.atom("prefix") { return x; } self.prefix.clone() } pub(crate) fn postfix(&self, annotations: &AnnotationSet) -> Option { if let Some(x) = annotations.atom("postfix") { return x; } self.postfix.clone() } } /// Settings to apply to generated structs. #[derive(Debug, Default, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct StructConfig { /// The rename rule to apply to the name of struct fields pub rename_fields: Option, /// Whether to generate a constructor for the struct (which takes /// arguments to initialize all the members) pub derive_constructor: bool, /// Whether to generate a piecewise equality operator pub derive_eq: bool, /// Whether to generate a piecewise inequality operator pub derive_neq: bool, /// Whether to generate a less than operator on structs with one field pub derive_lt: bool, /// Whether to generate a less than or equal to operator on structs with one field pub derive_lte: bool, /// Whether to generate a greater than operator on structs with one field pub derive_gt: bool, /// Whether to generate a greater than or equal to operator on structs with one field pub derive_gte: bool, /// Whether associated constants should be in the body. Only applicable to /// non-transparent structs, and in C++-only. pub associated_constants_in_body: bool, /// The way to annotate this struct as #[must_use]. pub must_use: Option, } impl StructConfig { pub(crate) fn derive_constructor(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-constructor") { return x; } self.derive_constructor } pub(crate) fn derive_eq(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-eq") { return x; } self.derive_eq } pub(crate) fn derive_neq(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-neq") { return x; } self.derive_neq } pub(crate) fn derive_lt(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-lt") { return x; } self.derive_lt } pub(crate) fn derive_lte(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-lte") { return x; } self.derive_lte } pub(crate) fn derive_gt(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-gt") { return x; } self.derive_gt } pub(crate) fn derive_gte(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-gte") { return x; } self.derive_gte } } /// Settings to apply to generated enums. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct EnumConfig { /// The rename rule to apply to the name of enum variants pub rename_variants: Option, /// Whether to add a `Sentinel` value at the end of every enum /// This is useful in Gecko for IPC serialization pub add_sentinel: bool, /// Whether the enum variants should be prefixed with the enum name pub prefix_with_name: bool, /// Whether to generate static `::X(..)` constructors and `IsX()` /// methods for tagged enums. pub derive_helper_methods: bool, /// Whether to generate `AsX() const` methods for tagged enums. pub derive_const_casts: bool, /// Whether to generate `AsX()` methods for tagged enums. pub derive_mut_casts: bool, /// The name of the macro to use for `derive_{const,mut}casts`. If custom, you're /// responsible to provide the necessary header, otherwise `assert` will be /// used, and `` will be included. pub cast_assert_name: Option, /// The way to annotation this enum as #[must_use]. pub must_use: Option, /// Whether to generate destructors of tagged enums. pub derive_tagged_enum_destructor: bool, /// Whether to generate copy-constructors of tagged enums. pub derive_tagged_enum_copy_constructor: bool, /// Whether to generate copy-assignment operators of tagged enums. /// /// This is only generated if a copy constructor for the same tagged enum is /// generated as well. pub derive_tagged_enum_copy_assignment: bool, /// Declare the enum as an enum class. /// Only relevant when targeting C++. pub enum_class: bool, /// Whether to generate empty, private default-constructors for tagged /// enums. pub private_default_tagged_enum_constructor: bool, } impl Default for EnumConfig { fn default() -> EnumConfig { EnumConfig { rename_variants: None, add_sentinel: false, prefix_with_name: false, derive_helper_methods: false, derive_const_casts: false, derive_mut_casts: false, cast_assert_name: None, must_use: None, derive_tagged_enum_destructor: false, derive_tagged_enum_copy_constructor: false, derive_tagged_enum_copy_assignment: false, enum_class: true, private_default_tagged_enum_constructor: false, } } } impl EnumConfig { pub(crate) fn add_sentinel(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("add-sentinel") { return x; } self.add_sentinel } pub(crate) fn derive_helper_methods(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-helper-methods") { return x; } self.derive_helper_methods } pub(crate) fn derive_const_casts(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-const-casts") { return x; } self.derive_const_casts } pub(crate) fn derive_mut_casts(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-mut-casts") { return x; } self.derive_mut_casts } pub(crate) fn derive_tagged_enum_destructor(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-tagged-enum-destructor") { return x; } self.derive_tagged_enum_destructor } pub(crate) fn derive_tagged_enum_copy_constructor(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-tagged-enum-copy-constructor") { return x; } self.derive_tagged_enum_copy_constructor } pub(crate) fn derive_tagged_enum_copy_assignment(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("derive-tagged-enum-copy-assignment") { return x; } self.derive_tagged_enum_copy_assignment } pub(crate) fn enum_class(&self, annotations: &AnnotationSet) -> bool { if let Some(x) = annotations.bool("enum-class") { return x; } self.enum_class } pub(crate) fn private_default_tagged_enum_constructor( &self, annotations: &AnnotationSet, ) -> bool { if let Some(x) = annotations.bool("private-default-tagged-enum-constructor") { return x; } self.private_default_tagged_enum_constructor } } /// Settings to apply to generated constants. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct ConstantConfig { /// Whether a generated constant can be a static const in C++ mode. pub allow_static_const: bool, } impl Default for ConstantConfig { fn default() -> ConstantConfig { ConstantConfig { allow_static_const: true, } } } /// Settings for custom macro expansion. #[derive(Debug, Clone, Deserialize, Default)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct MacroExpansionConfig { /// Whether the `bitflags` macro should be expanded. pub bitflags: bool, } /// Settings to apply when running `rustc --pretty=expanded` #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct ParseExpandConfig { /// The names of crates to parse with `rustc --pretty=expanded` pub crates: Vec, /// Whether to enable all the features when expanding. pub all_features: bool, /// Whether to use the default feature set when expanding. pub default_features: bool, /// List of features to use when expanding. Combines with `default_features` like in /// `Cargo.toml`. pub features: Option>, } impl Default for ParseExpandConfig { fn default() -> ParseExpandConfig { ParseExpandConfig { crates: Vec::new(), all_features: false, default_features: true, features: None, } } } // Backwards-compatibility deserializer for ParseExpandConfig. This allows accepting both the // simple `expand = ["crate"]` and the more complex `expand = {"crates": ["crate"], // "default_features": false}` format for the `expand` key. // // Note that one (major) difference between the two forms is that, for backwards-compatibility // reasons, the `expand = ["crate"]` form will enable the `--all-features` flag by default while // the `expand = {"crates": ["crate"]}` form will use the default feature set by default. fn retrocomp_parse_expand_config_deserialize<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result { struct ParseExpandVisitor; impl<'de> Visitor<'de> for ParseExpandVisitor { type Value = ParseExpandConfig; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a map or sequence of string") } fn visit_seq>(self, seq: A) -> Result { let crates = as Deserialize>::deserialize(SeqAccessDeserializer::new(seq))?; Ok(ParseExpandConfig { crates, all_features: true, default_features: true, features: None, }) } fn visit_map>(self, map: A) -> Result { ::deserialize(MapAccessDeserializer::new(map)) } } deserializer.deserialize_any(ParseExpandVisitor) } /// Settings to apply when parsing. #[derive(Debug, Default, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct ParseConfig { /// Whether to parse dependencies when generating bindings. When this is true, /// each dependent crate is found using a combination of `cargo metadata` and /// `Cargo.lock`. To further control this behavior, crates can be whitelisted or /// blacklisted using `include` and `exclude` respectively. Additionally in cases /// where crates have types to expose in bindings hidden in macros, a crate can /// be marked in `expand` and `cargo expand` will be used to expand the macros /// before parsing. A crate marked in `expand` doesn't need to be added to any /// whitelist. pub parse_deps: bool, /// An optional whitelist of names of crates to parse pub include: Option>, /// The names of crates to not parse pub exclude: Vec, /// The configuration options for `rustc --pretty=expanded` #[serde(deserialize_with = "retrocomp_parse_expand_config_deserialize")] pub expand: ParseExpandConfig, /// Whether to use a new temporary target directory when running `rustc --pretty=expanded`. /// This may be required for some build processes. pub clean: bool, /// List of crate names which generate consts, statics, and fns. By default /// no dependent crates generate them. pub extra_bindings: Vec, } impl ParseConfig { pub(crate) fn should_generate_top_level_item( &self, crate_name: &str, binding_crate_name: &str, ) -> bool { if crate_name == binding_crate_name { // Always generate items for the binding crate. return true; } self.extra_bindings.iter().any(|dep| dep == crate_name) } } /// A collection of settings to customize the generated bindings. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "snake_case")] #[serde(deny_unknown_fields)] #[serde(default)] pub struct Config { /// Optional text to output at the beginning of the file pub header: Option, /// A list of additional includes to put at the beginning of the generated header pub includes: Vec, /// A list of additional system includes to put at the beginning of the generated header pub sys_includes: Vec, /// Optional text to output at the end of the file pub trailer: Option, /// Optional name to use for an include guard pub include_guard: Option, /// Generates no includes at all. Overrides all other include options /// /// This option is useful when using cbindgen with tools such as python's cffi which /// doesn't understand include directives pub no_includes: bool, /// Optional text to output at major sections to deter manual editing pub autogen_warning: Option, /// Include a comment with the version of cbindgen used to generate the file pub include_version: bool, /// An optional name for the root namespace. Only applicable when language="C++" pub namespace: Option, /// An optional list of namespaces. Only applicable when language="C++" pub namespaces: Option>, /// An optional list of namespaces to declare as using. Only applicable when language="C++" pub using_namespaces: Option>, /// The style to use for braces pub braces: Braces, /// The preferred length of a line, used for auto breaking function arguments pub line_length: usize, /// The amount of spaces in a tab pub tab_width: usize, /// The language to output bindings for pub language: Language, /// Include preprocessor defines in C bindings to ensure C++ compatibility pub cpp_compat: bool, /// The style to declare structs, enums and unions in for C pub style: Style, /// The configuration options for parsing pub parse: ParseConfig, /// The configuration options for exporting pub export: ExportConfig, /// The configuration options for macros. pub macro_expansion: MacroExpansionConfig, /// The configuration options for type layouts. pub layout: LayoutConfig, /// The configuration options for functions #[serde(rename = "fn")] pub function: FunctionConfig, /// The configuration options for structs #[serde(rename = "struct")] pub structure: StructConfig, /// The configuration options for enums #[serde(rename = "enum")] pub enumeration: EnumConfig, /// The configuration options for constants #[serde(rename = "const")] pub constant: ConstantConfig, /// Preprocessor defines to use when generating #ifdef's for #[cfg] pub defines: HashMap, /// Include doc comments from rust as documentation pub documentation: bool, /// How documentation comments should be styled. pub documentation_style: DocumentationStyle, } impl Default for Config { fn default() -> Config { Config { header: None, includes: Vec::new(), sys_includes: Vec::new(), trailer: None, include_guard: None, autogen_warning: None, include_version: false, no_includes: false, namespace: None, namespaces: None, using_namespaces: None, braces: Braces::SameLine, line_length: 100, tab_width: 2, language: Language::Cxx, cpp_compat: false, style: Style::Type, macro_expansion: Default::default(), parse: ParseConfig::default(), export: ExportConfig::default(), layout: LayoutConfig::default(), function: FunctionConfig::default(), structure: StructConfig::default(), enumeration: EnumConfig::default(), constant: ConstantConfig::default(), defines: HashMap::new(), documentation: true, documentation_style: DocumentationStyle::Auto, } } } impl Config { pub fn from_file>(file_name: P) -> Result { let config_text = fs::read_to_string(file_name.as_ref()).or_else(|_| { Err(format!( "Couldn't open config file: {}.", file_name.as_ref().display() )) })?; match toml::from_str::(&config_text) { Ok(x) => Ok(x), Err(e) => Err(format!("Couldn't parse config file: {}.", e)), } } pub fn from_root_or_default>(root: P) -> Config { let c = root.as_ref().join("cbindgen.toml"); if c.exists() { Config::from_file(c).unwrap() } else { Config::default() } } } cbindgen-0.12.1/src/bindgen/declarationtyperesolver.rs010066400017500001750000000033001360223554200213010ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::HashSet; use crate::bindgen::ir::Path; pub struct DeclarationTypeResolver { structs: HashSet, enums: HashSet, unions: HashSet, } #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum DeclarationType { Struct, Enum, Union, } impl DeclarationType { pub fn to_str(self) -> &'static str { match self { DeclarationType::Struct => "struct", DeclarationType::Enum => "enum", DeclarationType::Union => "union", } } } impl DeclarationTypeResolver { pub fn new() -> DeclarationTypeResolver { DeclarationTypeResolver { structs: HashSet::new(), enums: HashSet::new(), unions: HashSet::new(), } } pub fn add_enum(&mut self, path: &Path) { self.enums.insert(path.clone()); } pub fn add_struct(&mut self, path: &Path) { self.structs.insert(path.clone()); } pub fn add_union(&mut self, path: &Path) { self.unions.insert(path.clone()); } pub fn type_for(&self, path: &Path) -> Option { // FIXME: don't look up by name, but by full path: if self.structs.contains(path) { Some(DeclarationType::Struct) } else if self.enums.contains(path) { Some(DeclarationType::Enum) } else if self.unions.contains(path) { Some(DeclarationType::Union) } else { None } } } cbindgen-0.12.1/src/bindgen/dependencies.rs010066400017500001750000000031201360223554200167560ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cmp::Ordering; use std::collections::HashSet; use crate::bindgen::ir::{ItemContainer, Path}; /// A dependency list is used for gathering what order to output the types. pub struct Dependencies { pub order: Vec, pub items: HashSet, } impl Dependencies { pub fn new() -> Dependencies { Dependencies { order: Vec::new(), items: HashSet::new(), } } pub fn sort(&mut self) { // Sort untagged enums and opaque structs into their own layers because they don't // depend on each other or anything else. let ordering = |a: &ItemContainer, b: &ItemContainer| match (a, b) { (&ItemContainer::Enum(ref x), &ItemContainer::Enum(ref y)) if x.tag.is_none() && y.tag.is_none() => { x.path.cmp(&y.path) } (&ItemContainer::Enum(ref x), _) if x.tag.is_none() => Ordering::Less, (_, &ItemContainer::Enum(ref x)) if x.tag.is_none() => Ordering::Greater, (&ItemContainer::OpaqueItem(ref x), &ItemContainer::OpaqueItem(ref y)) => { x.path.cmp(&y.path) } (&ItemContainer::OpaqueItem(_), _) => Ordering::Less, (_, &ItemContainer::OpaqueItem(_)) => Ordering::Greater, _ => Ordering::Equal, }; self.order.sort_by(ordering); } } cbindgen-0.12.1/src/bindgen/error.rs010066400017500001750000000055151360223554200154730ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::error; use std::fmt; pub use crate::bindgen::cargo::cargo_expand::Error as CargoExpandError; pub use crate::bindgen::cargo::cargo_metadata::Error as CargoMetadataError; pub use crate::bindgen::cargo::cargo_toml::Error as CargoTomlError; pub use syn::parse::Error as ParseError; #[derive(Debug)] pub enum Error { CargoMetadata(String, CargoMetadataError), CargoToml(String, CargoTomlError), CargoExpand(String, CargoExpandError), ParseSyntaxError { crate_name: String, src_path: String, error: ParseError, }, ParseCannotOpenFile { crate_name: String, src_path: String, }, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::CargoMetadata(ref path, ref error) => write!( f, "Couldn't execute `cargo metadata` with manifest {:?}: {:?}", path, error ), Error::CargoToml(ref path, ref error) => { write!(f, "Couldn't load manifest file {:?}: {:?}", path, error) } Error::CargoExpand(ref crate_name, ref error) => write!( f, "Parsing crate `{}`: couldn't run `cargo rustc --pretty=expanded`: {:?}", crate_name, error ), Error::ParseSyntaxError { ref crate_name, ref src_path, ref error, } => { write!( f, "Parsing crate `{}`:`{}`:\n{:?}", crate_name, src_path, error )?; if !src_path.is_empty() { write!( f, "\nTry running `rustc -Z parse-only {}` to see a nicer error message", src_path, )? } Ok(()) } Error::ParseCannotOpenFile { ref crate_name, ref src_path, } => write!( f, "Parsing crate `{}`: cannot open file `{}`.", crate_name, src_path ), } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::CargoMetadata(_, ref error) => Some(error), Error::CargoToml(_, ref error) => Some(error), Error::CargoExpand(_, ref error) => Some(error), Error::ParseSyntaxError { ref error, .. } => Some(error), Error::ParseCannotOpenFile { .. } => None, } } } cbindgen-0.12.1/src/bindgen/ir/annotation.rs010066400017500001750000000115411360223554200171220ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::HashMap; use std::str::FromStr; use syn; use crate::bindgen::utilities::SynAttributeHelpers; // A system for specifying properties on items. Annotations are // given through document comments and parsed by this code. // // An annotation is in the form cbindgen:PROPERTY=VALUE // Where PROPERTY depends on the item // Where VALUE can be // * list - [Item1, Item2, Item3, ...] // * atom - Foo // * bool - true,false // Examples: // * cbindgen:field-names=[mHandle, mNamespace] // * cbindgen:function-postfix=WR_DESTRUCTOR_SAFE /// A value specified by an annotation. #[derive(Debug, Clone)] pub enum AnnotationValue { List(Vec), Atom(Option), Bool(bool), } /// A set of annotations specified by a document comment. #[derive(Debug, Clone)] pub struct AnnotationSet { annotations: HashMap, pub must_use: bool, } impl AnnotationSet { pub fn new() -> AnnotationSet { AnnotationSet { annotations: HashMap::new(), must_use: false, } } pub fn is_empty(&self) -> bool { self.annotations.is_empty() && !self.must_use } pub fn load(attrs: &[syn::Attribute]) -> Result { let lines = attrs.get_comment_lines(); let lines: Vec<&str> = lines .iter() .filter_map(|line| { let line = line.trim_start(); if !line.starts_with("cbindgen:") { return None; } Some(line) }) .collect(); let must_use = attrs.has_attr_word("must_use"); let mut annotations = HashMap::new(); // Look at each line for an annotation for line in lines { debug_assert!(line.starts_with("cbindgen:")); // Remove the "cbindgen:" prefix let annotation = &line[9..]; // Split the annotation in two let parts: Vec<&str> = annotation.split('=').map(|x| x.trim()).collect(); if parts.len() > 2 { return Err(format!("Couldn't parse {}.", line)); } // Grab the name that this annotation is modifying let name = parts[0]; // If the annotation only has a name, assume it's setting a bool flag if parts.len() == 1 { annotations.insert(name.to_string(), AnnotationValue::Bool(true)); continue; } // Parse the value we're setting the name to let value = parts[1]; if let Some(x) = parse_list(value) { annotations.insert(name.to_string(), AnnotationValue::List(x)); continue; } if let Ok(x) = value.parse::() { annotations.insert(name.to_string(), AnnotationValue::Bool(x)); continue; } annotations.insert( name.to_string(), if value.is_empty() { AnnotationValue::Atom(None) } else { AnnotationValue::Atom(Some(value.to_string())) }, ); } Ok(AnnotationSet { annotations, must_use, }) } pub fn list(&self, name: &str) -> Option> { match self.annotations.get(name) { Some(&AnnotationValue::List(ref x)) => Some(x.clone()), _ => None, } } pub fn atom(&self, name: &str) -> Option> { match self.annotations.get(name) { Some(&AnnotationValue::Atom(ref x)) => Some(x.clone()), _ => None, } } pub fn bool(&self, name: &str) -> Option { match self.annotations.get(name) { Some(&AnnotationValue::Bool(ref x)) => Some(*x), _ => None, } } pub fn parse_atom(&self, name: &str) -> Option where T: Default + FromStr, { match self.annotations.get(name) { Some(&AnnotationValue::Atom(ref x)) => Some( x.as_ref() .map_or(T::default(), |y| y.parse::().ok().unwrap()), ), _ => None, } } } /// Parse lists like "[x, y, z]". This is not implemented efficiently or well. fn parse_list(list: &str) -> Option> { if list.len() < 2 { return None; } match (list.chars().next(), list.chars().last()) { (Some('['), Some(']')) => Some( list[1..list.len() - 1] .split(',') .map(|x| x.trim().to_string()) .collect(), ), _ => None, } } cbindgen-0.12.1/src/bindgen/ir/cfg.rs010066400017500001750000000264301360223554200155120ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::fmt; use std::io::Write; use syn; use crate::bindgen::cargo::cargo_metadata::Dependency; use crate::bindgen::config::Config; use crate::bindgen::writer::SourceWriter; #[derive(PartialEq, Eq)] enum DefineKey<'a> { Boolean(&'a str), Named(&'a str, &'a str), } impl<'a> DefineKey<'a> { fn load(key: &str) -> DefineKey { // TODO: dirty parser if key.contains('=') { let mut splits = key.trim().split('='); let name = if let Some(name) = splits.next() { name.trim() } else { return DefineKey::Boolean(key); }; let value = if let Some(value) = splits.next() { value.trim() } else { return DefineKey::Boolean(key); }; if splits.next().is_some() { return DefineKey::Boolean(key); } DefineKey::Named(name, value) } else { DefineKey::Boolean(key) } } } #[derive(Debug, Clone)] pub enum Cfg { Boolean(String), Named(String, String), Any(Vec), All(Vec), Not(Box), } impl fmt::Display for Cfg { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Cfg::Boolean(key) => write!(f, "{}", key), Cfg::Named(key, value) => write!(f, "{} = {:?}", key, value), Cfg::Any(cfgs) => { write!(f, "any(")?; for (index, cfg) in cfgs.iter().enumerate() { if index > 0 { write!(f, ", ")?; } write!(f, "{}", cfg)?; } write!(f, ")") } Cfg::All(cfgs) => { write!(f, "all(")?; for (index, cfg) in cfgs.iter().enumerate() { if index > 0 { write!(f, ", ")?; } write!(f, "{}", cfg)?; } write!(f, ")") } Cfg::Not(cfg) => write!(f, "not({})", cfg), } } } impl Cfg { pub fn join(cfgs: &[Cfg]) -> Option { if cfgs.is_empty() { None } else { Some(Cfg::All(cfgs.to_owned())) } } pub fn append(parent: Option<&Cfg>, child: Option) -> Option { match (parent, child) { (None, None) => None, (None, Some(child)) => Some(child), (Some(parent), None) => Some(parent.clone()), (Some(parent), Some(child)) => Some(Cfg::All(vec![parent.clone(), child])), } } pub fn load(attrs: &[syn::Attribute]) -> Option { let mut configs = Vec::new(); for attr in attrs { if let Ok(syn::Meta::List(syn::MetaList { path, nested, .. })) = attr.parse_meta() { if !path.is_ident("cfg") || nested.len() != 1 { continue; } if let Some(config) = Cfg::load_single(nested.first().unwrap()) { configs.push(config); } } } match configs.len() { 0 => None, 1 => Some(configs.pop().unwrap()), _ => Some(Cfg::All(configs)), } } pub fn load_metadata(dependency: &Dependency) -> Option { dependency .target .as_ref() .map(|target| { syn::parse_str::(target) .expect("error parsing dependency's target metadata") }) .and_then(|target| { if let syn::Meta::List(syn::MetaList { path, nested, .. }) = target { if !path.is_ident("cfg") || nested.len() != 1 { return None; } Cfg::load_single(nested.first().unwrap()) } else { None } }) } fn load_single(item: &syn::NestedMeta) -> Option { match *item { syn::NestedMeta::Meta(syn::Meta::Path(ref path)) => Some(Cfg::Boolean(format!( "{}", path.segments.first().unwrap().ident ))), syn::NestedMeta::Meta(syn::Meta::NameValue(syn::MetaNameValue { ref path, ref lit, .. })) => match lit { &syn::Lit::Str(ref value) => Some(Cfg::Named( format!("{}", path.segments.first().unwrap().ident), value.value(), )), _ => None, }, syn::NestedMeta::Meta(syn::Meta::List(syn::MetaList { ref path, ref nested, .. })) => { if path.is_ident("any") { if let Some(configs) = Cfg::load_list(nested.iter()) { Some(Cfg::Any(configs)) } else { None } } else if path.is_ident("all") { if let Some(configs) = Cfg::load_list(nested.iter()) { Some(Cfg::All(configs)) } else { None } } else if path.is_ident("not") { if nested.len() != 1 { return None; } if let Some(config) = Cfg::load_single(&nested[0]) { Some(Cfg::Not(Box::new(config))) } else { None } } else { None } } _ => None, } } fn load_list<'a, I: Iterator>(attrs: I) -> Option> { let mut configs = Vec::new(); for attr in attrs { if let Some(config) = Cfg::load_single(attr) { configs.push(config); } else { return None; } } if configs.is_empty() { None } else { Some(configs) } } } pub trait ToCondition: Sized { type Output; fn to_condition(self, config: &Config) -> Option; } impl<'a> ToCondition for &'a Option { type Output = Condition; fn to_condition(self, config: &Config) -> Option { self.clone().and_then(|cfg| cfg.to_condition(config)) } } impl ToCondition for Option { type Output = Condition; fn to_condition(self, config: &Config) -> Option { self.and_then(|cfg| cfg.to_condition(config)) } } impl<'a> ToCondition for &'a Cfg { type Output = Condition; fn to_condition(self, config: &Config) -> Option { self.clone().to_condition(config) } } impl ToCondition for Cfg { type Output = Condition; fn to_condition(self, config: &Config) -> Option { match self { Cfg::Boolean(cfg_name) => { let define = config .defines .iter() .find(|(key, ..)| DefineKey::Boolean(&cfg_name) == DefineKey::load(key)); if let Some((_, define)) = define { Some(Condition::Define(define.to_owned())) } else { warn!( "Missing `[defines]` entry for `{}` in cbindgen config.", Cfg::Boolean(cfg_name) ); None } } Cfg::Named(cfg_name, cfg_value) => { let define = config.defines.iter().find(|(key, ..)| { DefineKey::Named(&cfg_name, &cfg_value) == DefineKey::load(key) }); if let Some((_, define)) = define { Some(Condition::Define(define.to_owned())) } else { warn!( "Missing `[defines]` entry for `{}` in cbindgen config.", Cfg::Named(cfg_name, cfg_value) ); None } } Cfg::Any(children) => { let conditions: Vec<_> = children .into_iter() .filter_map(|x| x.to_condition(config)) .collect(); match conditions.len() { 0 => None, 1 => conditions.into_iter().next(), _ => Some(Condition::Any(conditions)), } } Cfg::All(children) => { let cfgs: Vec<_> = children .into_iter() .filter_map(|x| x.to_condition(config)) .collect(); match cfgs.len() { 0 => None, 1 => cfgs.into_iter().next(), _ => Some(Condition::All(cfgs)), } } Cfg::Not(child) => child .to_condition(config) .map(|cfg| Condition::Not(Box::new(cfg))), } } } #[derive(Debug, Clone)] pub enum Condition { Define(String), Any(Vec), All(Vec), Not(Box), } impl Condition { fn write(&self, config: &Config, out: &mut SourceWriter) { match *self { Condition::Define(ref define) => { out.write("defined("); write!(out, "{}", define); out.write(")"); } Condition::Any(ref conditions) => { out.write("("); for (i, condition) in conditions.iter().enumerate() { if i != 0 { out.write(" || "); } condition.write(config, out); } out.write(")"); } Condition::All(ref conditions) => { out.write("("); for (i, condition) in conditions.iter().enumerate() { if i != 0 { out.write(" && "); } condition.write(config, out); } out.write(")"); } Condition::Not(ref condition) => { out.write("!"); condition.write(config, out); } } } } pub trait ConditionWrite { fn write_before(&self, config: &Config, out: &mut SourceWriter); fn write_after(&self, config: &Config, out: &mut SourceWriter); } impl ConditionWrite for Option { fn write_before(&self, config: &Config, out: &mut SourceWriter) { if let Some(ref cfg) = *self { out.write("#if "); cfg.write(config, out); out.new_line(); } } fn write_after(&self, _config: &Config, out: &mut SourceWriter) { if self.is_some() { out.new_line(); out.write("#endif"); } } } cbindgen-0.12.1/src/bindgen/ir/constant.rs010066400017500001750000000411201360223554200165750ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::Cow; use std::collections::HashMap; use std::io::Write; use syn::{self, UnOp}; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Path, Struct, ToCondition, Type, }; use crate::bindgen::library::Library; use crate::bindgen::writer::{Source, SourceWriter}; use crate::bindgen::Bindings; #[derive(Debug, Clone)] pub enum Literal { Expr(String), Path(String), PostfixUnaryOp { op: &'static str, value: Box, }, BinOp { left: Box, op: &'static str, right: Box, }, Struct { path: Path, export_name: String, fields: HashMap, }, } impl Literal { fn replace_self_with(&mut self, self_ty: &Path) { match *self { Literal::PostfixUnaryOp { .. } | Literal::BinOp { .. } | Literal::Expr(..) | Literal::Path(..) => {} Literal::Struct { ref mut path, ref mut export_name, ref mut fields, } => { if path.replace_self_with(self_ty) { *export_name = self_ty.name().to_owned(); } for (ref _name, ref mut expr) in fields { expr.replace_self_with(self_ty); } } } } fn is_valid(&self, bindings: &Bindings) -> bool { match *self { Literal::Expr(..) => true, Literal::Path(..) => true, Literal::PostfixUnaryOp { ref value, .. } => value.is_valid(bindings), Literal::BinOp { ref left, ref right, .. } => left.is_valid(bindings) && right.is_valid(bindings), Literal::Struct { ref path, .. } => bindings.struct_exists(path), } } } impl Literal { pub fn rename_for_config(&mut self, config: &Config) { match self { Literal::Struct { ref mut export_name, fields, .. } => { config.export.rename(export_name); for (_, lit) in fields { lit.rename_for_config(config); } } Literal::Path(ref mut name) => { config.export.rename(name); } Literal::PostfixUnaryOp { ref mut value, .. } => { value.rename_for_config(config); } Literal::BinOp { ref mut left, ref mut right, .. } => { left.rename_for_config(config); right.rename_for_config(config); } Literal::Expr(_) => {} } } // Translate from full blown `syn::Expr` into a simpler `Literal` type pub fn load(expr: &syn::Expr) -> Result { match *expr { // Match binary expressions of the form `a * b` syn::Expr::Binary(ref bin_expr) => { let l = Self::load(&bin_expr.left)?; let r = Self::load(&bin_expr.right)?; let op = match bin_expr.op { syn::BinOp::Add(..) => "+", syn::BinOp::Sub(..) => "-", syn::BinOp::Mul(..) => "*", syn::BinOp::Div(..) => "/", syn::BinOp::Rem(..) => "%", syn::BinOp::And(..) => "&&", syn::BinOp::Or(..) => "||", syn::BinOp::BitXor(..) => "^", syn::BinOp::BitAnd(..) => "&", syn::BinOp::BitOr(..) => "|", syn::BinOp::Shl(..) => "<<", syn::BinOp::Shr(..) => ">>", syn::BinOp::Eq(..) => "==", syn::BinOp::Lt(..) => "<", syn::BinOp::Le(..) => "<=", syn::BinOp::Ne(..) => "!=", syn::BinOp::Ge(..) => ">=", syn::BinOp::Gt(..) => ">", syn::BinOp::AddEq(..) => "+=", syn::BinOp::SubEq(..) => "-=", syn::BinOp::MulEq(..) => "*=", syn::BinOp::DivEq(..) => "/=", syn::BinOp::RemEq(..) => "%=", syn::BinOp::BitXorEq(..) => "^=", syn::BinOp::BitAndEq(..) => "&=", syn::BinOp::BitOrEq(..) => "|=", syn::BinOp::ShlEq(..) => ">>=", syn::BinOp::ShrEq(..) => "<<=", }; Ok(Literal::BinOp { left: Box::new(l), op, right: Box::new(r), }) } // Match literals like "one", 'a', 32 etc syn::Expr::Lit(syn::ExprLit { ref lit, .. }) => { match lit { syn::Lit::Str(ref value) => { Ok(Literal::Expr(format!("u8\"{}\"", value.value()))) } syn::Lit::Byte(ref value) => Ok(Literal::Expr(format!("{}", value.value()))), syn::Lit::Char(ref value) => Ok(Literal::Expr(match value.value() as u32 { 0..=255 => format!("'{}'", value.value().escape_default()), other_code => format!(r"L'\u{:X}'", other_code), })), syn::Lit::Int(ref value) => { Ok(Literal::Expr(value.base10_digits().to_string())) } syn::Lit::Float(ref value) => { Ok(Literal::Expr(value.base10_digits().to_string())) } syn::Lit::Bool(ref value) => Ok(Literal::Expr(format!("{}", value.value))), // TODO: Add support for byte string and Verbatim _ => Err(format!("Unsupported literal expression. {:?}", *lit)), } } syn::Expr::Struct(syn::ExprStruct { ref path, ref fields, .. }) => { let struct_name = path.segments[0].ident.to_string(); let mut field_map = HashMap::::default(); for field in fields { let ident = match field.member { syn::Member::Named(ref name) => name.to_string(), syn::Member::Unnamed(ref index) => format!("_{}", index.index), }; let key = ident.to_string(); let value = Literal::load(&field.expr)?; field_map.insert(key, value); } Ok(Literal::Struct { path: Path::new(struct_name.clone()), export_name: struct_name, fields: field_map, }) } syn::Expr::Unary(syn::ExprUnary { ref op, ref expr, .. }) => match *op { UnOp::Neg(_) => { let val = Self::load(expr)?; Ok(Literal::PostfixUnaryOp { op: "-", value: Box::new(val), }) } _ => Err(format!("Unsupported Unary expression. {:?}", *op)), }, // Match identifiers, like `5 << SHIFT` syn::Expr::Path(syn::ExprPath { path: syn::Path { ref segments, .. }, .. }) => { // Handle only the simplest identifiers and error for anything else. if segments.len() == 1 { Ok(Literal::Path(format!("{}", segments.last().unwrap().ident))) } else { Err(format!("Unsupported path expression. {:?}", *segments)) } } syn::Expr::Paren(syn::ExprParen { ref expr, .. }) => Self::load(expr), _ => Err(format!("Unsupported expression. {:?}", *expr)), } } fn write(&self, config: &Config, out: &mut SourceWriter) { match self { Literal::Expr(v) => write!(out, "{}", v), Literal::Path(v) => write!(out, "{}", v), Literal::PostfixUnaryOp { op, ref value } => { write!(out, "{}", op); value.write(config, out); } Literal::BinOp { ref left, op, ref right, } => { write!(out, "("); left.write(config, out); write!(out, " {} ", op); right.write(config, out); write!(out, ")"); } Literal::Struct { export_name, fields, path, } => { if config.language == Language::C { write!(out, "({})", export_name); } else { write!(out, "{}", export_name); } write!(out, "{{ "); let mut is_first_field = true; // In C++, same order as defined is required. let ordered_fields = out.bindings().struct_field_names(path); for ordered_key in ordered_fields.iter() { if let Some(ref lit) = fields.get(ordered_key) { if !is_first_field { write!(out, ", "); } else { is_first_field = false; } if config.language == Language::Cxx { write!(out, "/* .{} = */ ", ordered_key); } else { write!(out, ".{} = ", ordered_key); } lit.write(config, out); } } write!(out, " }}"); } } } } #[derive(Debug, Clone)] pub struct Constant { pub path: Path, pub export_name: String, pub ty: Type, pub value: Literal, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, pub associated_to: Option, } fn can_handle(ty: &Type, expr: &syn::Expr) -> bool { if ty.is_primitive_or_ptr_primitive() { return true; } match *expr { syn::Expr::Struct(_) => true, _ => false, } } impl Constant { pub fn load( path: Path, mod_cfg: Option<&Cfg>, ty: &syn::Type, expr: &syn::Expr, attrs: &[syn::Attribute], associated_to: Option, ) -> Result { let ty = Type::load(ty)?; let mut ty = match ty { Some(ty) => ty, None => { return Err("Cannot have a zero sized const definition.".to_owned()); } }; if !can_handle(&ty, expr) { return Err("Unhandled const definition".to_owned()); } let mut lit = Literal::load(&expr)?; if let Some(ref associated_to) = associated_to { ty.replace_self_with(associated_to); lit.replace_self_with(associated_to); } Ok(Constant::new( path, ty, lit, Cfg::append(mod_cfg, Cfg::load(attrs)), AnnotationSet::load(attrs)?, Documentation::load(attrs), associated_to, )) } pub fn new( path: Path, ty: Type, value: Literal, cfg: Option, annotations: AnnotationSet, documentation: Documentation, associated_to: Option, ) -> Self { let export_name = path.name().to_owned(); Self { path, export_name, ty, value, cfg, annotations, documentation, associated_to, } } } impl Item for Constant { fn path(&self) -> &Path { &self.path } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { self.ty.add_dependencies(library, out); } fn export_name(&self) -> &str { &self.export_name } fn cfg(&self) -> Option<&Cfg> { self.cfg.as_ref() } fn annotations(&self) -> &AnnotationSet { &self.annotations } fn annotations_mut(&mut self) -> &mut AnnotationSet { &mut self.annotations } fn container(&self) -> ItemContainer { ItemContainer::Constant(self.clone()) } fn rename_for_config(&mut self, config: &Config) { if self.associated_to.is_none() { config.export.rename(&mut self.export_name); } self.value.rename_for_config(config); self.ty.rename_for_config(config, &GenericParams::default()); // FIXME: should probably propagate something here } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { self.ty.resolve_declaration_types(resolver); } } impl Constant { pub fn write_declaration( &self, config: &Config, out: &mut SourceWriter, associated_to_struct: &Struct, ) { debug_assert!(self.associated_to.is_some()); debug_assert!(config.language == Language::Cxx); debug_assert!(!associated_to_struct.is_transparent); debug_assert!(config.structure.associated_constants_in_body); debug_assert!(config.constant.allow_static_const); if let Type::ConstPtr(..) = self.ty { out.write("static "); } else { out.write("static const "); } self.ty.write(config, out); write!(out, " {};", self.export_name()) } pub fn write( &self, config: &Config, out: &mut SourceWriter, associated_to_struct: Option<&Struct>, ) { if let Some(assoc) = associated_to_struct { if assoc.is_generic() { return; // Not tested / implemented yet, so bail out. } } if !self.value.is_valid(out.bindings()) { return; } let associated_to_transparent = associated_to_struct.map_or(false, |s| s.is_transparent); let in_body = associated_to_struct.is_some() && config.language == Language::Cxx && config.structure.associated_constants_in_body && config.constant.allow_static_const && !associated_to_transparent; let condition = (&self.cfg).to_condition(config); condition.write_before(config, out); let name = if in_body { Cow::Owned(format!( "{}::{}", associated_to_struct.unwrap().export_name(), self.export_name(), )) } else if self.associated_to.is_none() { Cow::Borrowed(self.export_name()) } else { let associated_name = match associated_to_struct { Some(s) => Cow::Borrowed(s.export_name()), None => { let mut name = self.associated_to.as_ref().unwrap().name().to_owned(); config.export.rename(&mut name); Cow::Owned(name) } }; Cow::Owned(format!("{}_{}", associated_name, self.export_name())) }; let value = match self.value { Literal::Struct { ref fields, ref path, .. } if out.bindings().struct_is_transparent(path) => &fields.iter().next().unwrap().1, _ => &self.value, }; if config.constant.allow_static_const && config.language == Language::Cxx { out.write(if in_body { "inline " } else { "static " }); if let Type::ConstPtr(..) = self.ty { // Nothing. } else { out.write("const "); } self.ty.write(config, out); write!(out, " {} = ", name); value.write(config, out); write!(out, ";"); } else { write!(out, "#define {} ", name); value.write(config, out); } condition.write_after(config, out); } } cbindgen-0.12.1/src/bindgen/ir/documentation.rs010066400017500001750000000053651360223554200176300ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use syn; use crate::bindgen::config::{Config, DocumentationStyle, Language}; use crate::bindgen::utilities::SynAttributeHelpers; use crate::bindgen::writer::{Source, SourceWriter}; #[derive(Debug, Clone)] pub struct Documentation { pub doc_comment: Vec, } impl Documentation { pub fn load(attrs: &[syn::Attribute]) -> Self { let doc = attrs .get_comment_lines() .into_iter() .filter(|x| !x.trim_start().starts_with("cbindgen:")) .collect(); Documentation { doc_comment: doc } } pub fn none() -> Self { Documentation { doc_comment: Vec::new(), } } } impl Source for Documentation { fn write(&self, config: &Config, out: &mut SourceWriter) { if self.doc_comment.is_empty() || !config.documentation { return; } let style = match config.documentation_style { DocumentationStyle::Auto if config.language == Language::C => DocumentationStyle::Doxy, DocumentationStyle::Auto if config.language == Language::Cxx => DocumentationStyle::Cxx, DocumentationStyle::Auto => DocumentationStyle::C, // Fallback if `Language` gets extended. other => other, }; // Following these documents for style conventions: // https://en.wikibooks.org/wiki/C++_Programming/Code/Style_Conventions/Comments // https://www.cs.cmu.edu/~410/doc/doxygen.html match style { DocumentationStyle::C => { out.write("/*"); out.new_line(); } DocumentationStyle::Doxy => { out.write("/**"); out.new_line(); } _ => (), } for line in &self.doc_comment { match style { DocumentationStyle::C => out.write(""), DocumentationStyle::Doxy => out.write(" *"), DocumentationStyle::C99 => out.write("//"), DocumentationStyle::Cxx => out.write("///"), DocumentationStyle::Auto => unreachable!(), // Auto case should always be covered } write!(out, "{}", line); out.new_line(); } match style { DocumentationStyle::C => { out.write(" */"); out.new_line(); } DocumentationStyle::Doxy => { out.write(" */"); out.new_line(); } _ => (), } } } cbindgen-0.12.1/src/bindgen/ir/enumeration.rs010066400017500001750000001050151360223554200172760ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use syn; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, GenericPath, Item, ItemContainer, Path, Repr, ReprStyle, ReprType, Struct, ToCondition, Type, }; use crate::bindgen::library::Library; use crate::bindgen::mangle; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::rename::{IdentifierType, RenameRule}; use crate::bindgen::utilities::find_first_some; use crate::bindgen::writer::{ListType, Source, SourceWriter}; #[derive(Debug, Clone)] pub struct EnumVariant { pub name: String, pub export_name: String, pub discriminant: Option, pub body: Option<(String, Struct)>, pub documentation: Documentation, } fn value_from_expr(val: &syn::Expr) -> Option { match *val { syn::Expr::Lit(ref lit) => match lit.lit { syn::Lit::Int(ref lit) => lit.base10_parse::().ok(), _ => None, }, syn::Expr::Unary(ref unary) => { let v = value_from_expr(&unary.expr)?; match unary.op { syn::UnOp::Deref(..) => None, syn::UnOp::Neg(..) => v.checked_mul(-1), syn::UnOp::Not(..) => v.checked_neg(), } } _ => None, } } impl EnumVariant { pub fn load( is_tagged: bool, variant: &syn::Variant, generic_params: GenericParams, mod_cfg: Option<&Cfg>, ) -> Result { let discriminant = match variant.discriminant { Some((_, ref expr)) => match value_from_expr(expr) { Some(v) => Some(v), None => return Err(format!("Unsupported discriminant {:?}.", expr)), }, None => None, }; fn parse_fields( is_tagged: bool, fields: &syn::punctuated::Punctuated, ) -> Result, String> { let mut res = Vec::new(); if is_tagged { res.push(( "tag".to_string(), Type::Path(GenericPath::new(Path::new("Tag"), vec![])), Documentation::none(), )); } for (i, field) in fields.iter().enumerate() { if let Some(ty) = Type::load(&field.ty)? { res.push(( match field.ident { Some(ref ident) => ident.to_string(), None => i.to_string(), }, ty, Documentation::load(&field.attrs), )); } } Ok(res) } let body = match variant.fields { syn::Fields::Unit => None, syn::Fields::Named(ref fields) => { let path = Path::new(format!("{}_Body", variant.ident)); Some(Struct::new( path, generic_params, parse_fields(is_tagged, &fields.named)?, is_tagged, true, None, false, false, Cfg::append(mod_cfg, Cfg::load(&variant.attrs)), AnnotationSet::load(&variant.attrs)?, Documentation::none(), )) } syn::Fields::Unnamed(ref fields) => { let path = Path::new(format!("{}_Body", variant.ident)); Some(Struct::new( path, generic_params, parse_fields(is_tagged, &fields.unnamed)?, is_tagged, true, None, false, true, Cfg::append(mod_cfg, Cfg::load(&variant.attrs)), AnnotationSet::load(&variant.attrs)?, Documentation::none(), )) } }; Ok(EnumVariant::new( variant.ident.to_string(), discriminant, body.map(|body| { ( RenameRule::SnakeCase.apply_to_pascal_case( &format!("{}", variant.ident), IdentifierType::StructMember, ), body, ) }), Documentation::load(&variant.attrs), )) } pub fn new( name: String, discriminant: Option, body: Option<(String, Struct)>, documentation: Documentation, ) -> Self { let export_name = name.clone(); Self { name, export_name, discriminant, body, documentation, } } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { if let Some((_, ref item)) = self.body { item.add_dependencies(library, out); } } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { if let Some((_, ref mut ty)) = self.body { ty.resolve_declaration_types(resolver); } } fn specialize(&self, generic_values: &[Type], mappings: &[(&Path, &Type)]) -> Self { Self::new( mangle::mangle_name(&self.name, generic_values), self.discriminant, self.body .as_ref() .map(|&(ref name, ref ty)| (name.clone(), ty.specialize(generic_values, mappings))), self.documentation.clone(), ) } fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { if let Some((_, ref ty)) = self.body { ty.add_monomorphs(library, out); } } fn mangle_paths(&mut self, monomorphs: &Monomorphs) { if let Some((_, ref mut ty)) = self.body { ty.mangle_paths(monomorphs); } } } impl Source for EnumVariant { fn write(&self, config: &Config, out: &mut SourceWriter) { self.documentation.write(config, out); write!(out, "{}", self.export_name); if let Some(discriminant) = self.discriminant { write!(out, " = {}", discriminant); } out.write(","); } } #[derive(Debug, Clone)] pub struct Enum { pub path: Path, pub export_name: String, pub generic_params: GenericParams, pub repr: Repr, pub variants: Vec, pub tag: Option, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, } impl Enum { pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { if self.generic_params.len() > 0 { return; } for v in &self.variants { v.add_monomorphs(library, out); } } fn can_derive_eq(&self) -> bool { if self.tag.is_none() { return false; } self.variants.iter().all(|variant| { variant .body .as_ref() .map_or(true, |&(_, ref body)| body.can_derive_eq()) }) } pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) { for variant in &mut self.variants { variant.mangle_paths(monomorphs); } } pub fn load(item: &syn::ItemEnum, mod_cfg: Option<&Cfg>) -> Result { let repr = Repr::load(&item.attrs)?; if repr.style == ReprStyle::Rust && repr.ty.is_none() { return Err("Enum is not marked with a valid #[repr(prim)] or #[repr(C)].".to_owned()); } // TODO: Implement translation of aligned enums. if repr.align.is_some() { return Err("Enum is marked with #[repr(align(...))] or #[repr(packed)].".to_owned()); } let generic_params = GenericParams::new(&item.generics); let mut variants = Vec::new(); let mut is_tagged = false; for variant in item.variants.iter() { let variant = EnumVariant::load( repr.style == ReprStyle::Rust, variant, generic_params.clone(), mod_cfg, )?; is_tagged = is_tagged || variant.body.is_some(); variants.push(variant); } let annotations = AnnotationSet::load(&item.attrs)?; if let Some(names) = annotations.list("enum-trailing-values") { for name in names { variants.push(EnumVariant::new(name, None, None, Documentation::none())); } } let path = Path::new(item.ident.to_string()); let tag = if is_tagged { Some("Tag".to_string()) } else { None }; Ok(Enum::new( path, generic_params, repr, variants, tag, Cfg::append(mod_cfg, Cfg::load(&item.attrs)), annotations, Documentation::load(&item.attrs), )) } pub fn new( path: Path, generic_params: GenericParams, repr: Repr, variants: Vec, tag: Option, cfg: Option, annotations: AnnotationSet, documentation: Documentation, ) -> Self { let export_name = path.name().to_owned(); Self { path, export_name, generic_params, repr, variants, tag, cfg, annotations, documentation, } } } impl Item for Enum { fn path(&self) -> &Path { &self.path } fn export_name(&self) -> &str { &self.export_name } fn cfg(&self) -> Option<&Cfg> { self.cfg.as_ref() } fn annotations(&self) -> &AnnotationSet { &self.annotations } fn annotations_mut(&mut self) -> &mut AnnotationSet { &mut self.annotations } fn container(&self) -> ItemContainer { ItemContainer::Enum(self.clone()) } fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { if self.tag.is_some() && self.repr.style == ReprStyle::C { resolver.add_struct(&self.path); } else if self.tag.is_some() && self.repr.style != ReprStyle::C { resolver.add_union(&self.path); } else if self.repr.style == ReprStyle::C { resolver.add_enum(&self.path); } } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { for &mut ref mut var in &mut self.variants { var.resolve_declaration_types(resolver); } } fn rename_for_config(&mut self, config: &Config) { config.export.rename(&mut self.export_name); if config.language == Language::C && self.tag.is_some() { // it makes sense to always prefix Tag with type name in C let new_tag = format!("{}_Tag", self.export_name); if self.repr.style == ReprStyle::Rust { for variant in &mut self.variants { if let Some((_, ref mut body)) = variant.body { let path = Path::new(new_tag.clone()); let generic_path = GenericPath::new(path, vec![]); body.fields[0].1 = Type::Path(generic_path); } } } self.tag = Some(new_tag); } for variant in &mut self.variants { if let Some((_, ref mut body)) = variant.body { body.rename_for_config(config); } } if config.enumeration.prefix_with_name || self.annotations.bool("prefix-with-name").unwrap_or(false) { for variant in &mut self.variants { variant.export_name = format!("{}_{}", self.export_name, variant.export_name); if let Some((_, ref mut body)) = variant.body { body.export_name = format!("{}_{}", self.export_name, body.export_name()); } } } let rules = [ self.annotations.parse_atom::("rename-all"), config.enumeration.rename_variants, ]; if let Some(r) = find_first_some(&rules) { self.variants = self .variants .iter() .map(|variant| { EnumVariant::new( r.apply_to_pascal_case( &variant.export_name, IdentifierType::EnumVariant(self), ), variant.discriminant, variant.body.as_ref().map(|body| { ( r.apply_to_snake_case(&body.0, IdentifierType::StructMember), body.1.clone(), ) }), variant.documentation.clone(), ) }) .collect(); } } fn instantiate_monomorph( &self, generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", self.path.name() ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", self.path.name(), self.generic_params.len(), generic_values.len(), ); let mappings = self .generic_params .iter() .zip(generic_values.iter()) .collect::>(); for variant in &self.variants { if let Some((_, ref body)) = variant.body { body.instantiate_monomorph(generic_values, library, out); } } let mangled_path = mangle::mangle_path(&self.path, generic_values); let monomorph = Enum::new( mangled_path, GenericParams::default(), self.repr, self.variants .iter() .map(|v| v.specialize(generic_values, &mappings)) .collect(), self.tag.clone(), self.cfg.clone(), self.annotations.clone(), self.documentation.clone(), ); monomorph.add_monomorphs(library, out); out.insert_enum(self, monomorph, generic_values.to_owned()); } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { for variant in &self.variants { variant.add_dependencies(library, out); } } } impl Source for Enum { fn write(&self, config: &Config, out: &mut SourceWriter) { let size = self.repr.ty.map(|ty| match ty { ReprType::USize => "uintptr_t", ReprType::U64 => "uint64_t", ReprType::U32 => "uint32_t", ReprType::U16 => "uint16_t", ReprType::U8 => "uint8_t", ReprType::ISize => "intptr_t", ReprType::I64 => "int64_t", ReprType::I32 => "int32_t", ReprType::I16 => "int16_t", ReprType::I8 => "int8_t", }); let condition = (&self.cfg).to_condition(config); condition.write_before(config, out); self.documentation.write(config, out); let is_tagged = self.tag.is_some(); let separate_tag = self.repr.style == ReprStyle::C; // If tagged, we need to emit a proper struct/union wrapper around our enum self.generic_params.write(config, out); if is_tagged && config.language == Language::Cxx { out.write(if separate_tag { "struct" } else { "union" }); if self.annotations.must_use { if let Some(ref anno) = config.structure.must_use { write!(out, " {}", anno) } } write!(out, " {}", self.export_name()); out.open_brace(); } let enum_name = if let Some(ref tag) = self.tag { tag } else { self.export_name() }; // Emit the actual enum if config.language == Language::C { if size.is_none() && config.style.generate_typedef() { out.write("typedef "); } out.write("enum"); if size.is_some() || config.style.generate_tag() { write!(out, " {}", enum_name); } if config.cpp_compat { if let Some(prim) = size { out.new_line(); out.write("#ifdef __cplusplus"); out.new_line(); write!(out, " : {}", prim); out.new_line(); out.write("#endif // __cplusplus"); out.new_line(); } } } else { if config.enumeration.enum_class(&self.annotations) { out.write("enum class"); } else { out.write("enum"); } if self.annotations.must_use { if let Some(ref anno) = config.enumeration.must_use { write!(out, " {}", anno) } } write!(out, " {}", enum_name); if let Some(prim) = size { write!(out, " : {}", prim); } } out.open_brace(); for (i, variant) in self.variants.iter().enumerate() { if i != 0 { out.new_line() } variant.write(config, out); } if config.enumeration.add_sentinel(&self.annotations) { out.new_line(); out.new_line(); out.write("Sentinel /* this must be last for serialization purposes. */"); } if config.language == Language::C && size.is_none() && config.style.generate_typedef() { out.close_brace(false); write!(out, " {};", enum_name); } else { out.close_brace(true); } if config.language == Language::C { if let Some(prim) = size { if config.cpp_compat { out.new_line_if_not_start(); out.write("#ifndef __cplusplus"); } out.new_line(); write!(out, "typedef {} {};", prim, enum_name); if config.cpp_compat { out.new_line_if_not_start(); out.write("#endif // __cplusplus"); } } } // Done emitting the enum // If tagged, we need to emit structs for the cases and union them together if is_tagged { // Emit the cases for the structs for variant in &self.variants { if let Some((_, ref body)) = variant.body { out.new_line(); out.new_line(); body.write(config, out); } } out.new_line(); out.new_line(); // Emit the actual union if config.language == Language::C { if config.style.generate_typedef() { out.write("typedef "); } out.write(if separate_tag { "struct" } else { "union" }); if config.style.generate_tag() { write!(out, " {}", self.export_name()); } out.open_brace(); } // C++ allows accessing only common initial sequence of union // branches so we need to wrap tag into an anonymous struct let wrap_tag = config.language == Language::Cxx && !separate_tag; if wrap_tag { out.write("struct"); out.open_brace(); } if config.language == Language::C && !config.style.generate_typedef() { out.write("enum "); } write!(out, "{} tag;", enum_name); if wrap_tag { out.close_brace(true); } out.new_line(); if separate_tag { out.write("union"); out.open_brace(); } for (i, &(ref field_name, ref body)) in self .variants .iter() .filter_map(|variant| variant.body.as_ref()) .enumerate() { if i != 0 { out.new_line(); } if config.style.generate_typedef() { write!(out, "{} {};", body.export_name(), field_name); } else { write!(out, "struct {} {};", body.export_name(), field_name); } } if separate_tag { out.close_brace(true); } let skip_fields = if separate_tag { 0 } else { 1 }; // Emit convenience methods let derive_helper_methods = config.enumeration.derive_helper_methods(&self.annotations); if config.language == Language::Cxx && derive_helper_methods { for variant in &self.variants { out.new_line(); out.new_line(); let arg_renamer = |name: &str| { config .function .rename_args .as_ref() .unwrap_or(&RenameRule::GeckoCase) .apply_to_snake_case(name, IdentifierType::FunctionArg) }; write!(out, "static {} {}(", self.export_name, variant.export_name); if let Some((_, ref body)) = variant.body { let vec: Vec<_> = body .fields .iter() .skip(skip_fields) .map(|&(ref name, ref ty, _)| { // const-ref args to constructor (arg_renamer(name), Type::Ref(Box::new(ty.clone()))) }) .collect(); out.write_vertical_source_list(&vec[..], ListType::Join(",")); } write!(out, ")"); out.open_brace(); write!(out, "{} result;", self.export_name); if let Some((ref variant_name, ref body)) = variant.body { for &(ref field_name, ref ty, ..) in body.fields.iter().skip(skip_fields) { out.new_line(); match ty { Type::Array(ref ty, ref length) => { // arrays are not assignable in C++ so we // need to manually copy the elements write!(out, "for (int i = 0; i < {}; i++)", length.as_str()); out.open_brace(); write!( out, "::new (&result.{}.{}[i]) (", variant_name, field_name ); ty.write(config, out); write!(out, ")({}[i]);", arg_renamer(field_name)); out.close_brace(false); } ref ty => { write!( out, "::new (&result.{}.{}) (", variant_name, field_name ); ty.write(config, out); write!(out, ")({});", arg_renamer(field_name)); } } } } out.new_line(); write!(out, "result.tag = {}::{};", enum_name, variant.export_name); out.new_line(); write!(out, "return result;"); out.close_brace(false); } for variant in &self.variants { out.new_line(); out.new_line(); // FIXME: create a config for method case write!(out, "bool Is{}() const", variant.export_name); out.open_brace(); write!(out, "return tag == {}::{};", enum_name, variant.export_name); out.close_brace(false); } } let derive_const_casts = config.enumeration.derive_const_casts(&self.annotations); let derive_mut_casts = config.enumeration.derive_mut_casts(&self.annotations); if config.language == Language::Cxx && derive_helper_methods && (derive_const_casts || derive_mut_casts) { let assert_name = match config.enumeration.cast_assert_name { Some(ref n) => &**n, None => "assert", }; for variant in &self.variants { let (member_name, body) = match variant.body { Some((ref member_name, ref body)) => (member_name, body), None => continue, }; let field_count = body.fields.len() - skip_fields; if field_count == 0 { continue; } let dig = field_count == 1 && body.tuple_struct; let mut derive_casts = |const_casts: bool| { out.new_line(); out.new_line(); if dig { let field = body.fields.iter().skip(skip_fields).next().unwrap(); let return_type = field.1.clone(); let return_type = if const_casts { Type::Ref(Box::new(return_type)) } else { Type::MutRef(Box::new(return_type)) }; return_type.write(config, out); } else if const_casts { write!(out, "const {}&", body.export_name()); } else { write!(out, "{}&", body.export_name()); } write!(out, " As{}()", variant.export_name); if const_casts { write!(out, " const"); } out.open_brace(); write!(out, "{}(Is{}());", assert_name, variant.export_name); out.new_line(); if dig { write!(out, "return {}._0;", member_name); } else { write!(out, "return {};", member_name); } out.close_brace(false); }; if derive_const_casts { derive_casts(true) } if derive_mut_casts { derive_casts(false) } } } let other = if let Some(r) = config.function.rename_args { r.apply_to_snake_case("other", IdentifierType::FunctionArg) } else { String::from("other") }; if config.language == Language::Cxx && self.can_derive_eq() && config.structure.derive_eq(&self.annotations) { out.new_line(); out.new_line(); write!( out, "bool operator==(const {}& {}) const", self.export_name, other ); out.open_brace(); write!(out, "if (tag != {}.tag)", other); out.open_brace(); write!(out, "return false;"); out.close_brace(false); out.new_line(); write!(out, "switch (tag)"); out.open_brace(); for variant in &self.variants { if let Some((ref variant_name, _)) = variant.body { write!( out, "case {}::{}: return {} == {}.{};", self.tag.as_ref().unwrap(), variant.export_name, variant_name, other, variant_name ); out.new_line(); } } write!(out, "default: return true;"); out.close_brace(false); out.close_brace(false); if config.structure.derive_neq(&self.annotations) { out.new_line(); out.new_line(); write!( out, "bool operator!=(const {}& {}) const", self.export_name, other ); out.open_brace(); write!(out, "return !(*this == {});", other); out.close_brace(false); } } if config.language == Language::Cxx && config .enumeration .private_default_tagged_enum_constructor(&self.annotations) { out.new_line(); out.new_line(); write!(out, "private:"); out.new_line(); write!(out, "{}()", self.export_name); out.open_brace(); out.close_brace(false); out.new_line(); write!(out, "public:"); out.new_line(); } if config.language == Language::Cxx && config .enumeration .derive_tagged_enum_destructor(&self.annotations) { out.new_line(); out.new_line(); write!(out, "~{}()", self.export_name); out.open_brace(); write!(out, "switch (tag)"); out.open_brace(); for variant in &self.variants { if let Some((ref variant_name, ref item)) = variant.body { write!( out, "case {}::{}: {}.~{}(); break;", self.tag.as_ref().unwrap(), variant.export_name, variant_name, item.export_name(), ); out.new_line(); } } write!(out, "default: break;"); out.close_brace(false); out.close_brace(false); } if config.language == Language::Cxx && config .enumeration .derive_tagged_enum_copy_constructor(&self.annotations) { out.new_line(); out.new_line(); write!( out, "{}(const {}& {})", self.export_name, self.export_name, other ); out.new_line(); write!(out, " : tag({}.tag)", other); out.open_brace(); write!(out, "switch (tag)"); out.open_brace(); for variant in &self.variants { if let Some((ref variant_name, ref item)) = variant.body { write!( out, "case {}::{}: ::new (&{}) ({})({}.{}); break;", self.tag.as_ref().unwrap(), variant.export_name, variant_name, item.export_name(), other, variant_name, ); out.new_line(); } } write!(out, "default: break;"); out.close_brace(false); out.close_brace(false); if config.language == Language::Cxx && config .enumeration .derive_tagged_enum_copy_assignment(&self.annotations) { out.new_line(); write!( out, "{}& operator=(const {}& {})", self.export_name, self.export_name, other ); out.open_brace(); write!(out, "if (this != &{})", other); out.open_brace(); write!(out, "this->~{}();", self.export_name); out.new_line(); write!(out, "new (this) {}({});", self.export_name, other); out.close_brace(false); out.new_line(); write!(out, "return *this;"); out.close_brace(false); } } if let Some(body) = config.export.extra_body(&self.path) { out.write_raw_block(body); } if config.language == Language::C && config.style.generate_typedef() { out.close_brace(false); write!(out, " {};", self.export_name); } else { out.close_brace(true); } } condition.write_after(config, out); } } cbindgen-0.12.1/src/bindgen/ir/function.rs010066400017500001750000000177131360223554200166040ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use syn; use crate::bindgen::cdecl; use crate::bindgen::config::{Config, Language, Layout}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Documentation, Path, PrimitiveType, ToCondition, Type, }; use crate::bindgen::library::Library; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::rename::{IdentifierType, RenameRule}; use crate::bindgen::reserved; use crate::bindgen::utilities::{find_first_some, IterHelpers}; use crate::bindgen::writer::{Source, SourceWriter}; #[derive(Debug, Clone)] pub struct Function { pub path: Path, pub ret: Type, pub args: Vec<(String, Type)>, pub extern_decl: bool, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, } impl Function { pub fn load( path: Path, sig: &syn::Signature, extern_decl: bool, attrs: &[syn::Attribute], mod_cfg: Option<&Cfg>, ) -> Result { let args = sig.inputs.iter().try_skip_map(|x| x.as_ident_and_type())?; let ret = match sig.output { syn::ReturnType::Default => Type::Primitive(PrimitiveType::Void), syn::ReturnType::Type(_, ref ty) => { if let Some(x) = Type::load(ty)? { x } else { Type::Primitive(PrimitiveType::Void) } } }; Ok(Function { path, ret, args, extern_decl, cfg: Cfg::append(mod_cfg, Cfg::load(attrs)), annotations: AnnotationSet::load(attrs)?, documentation: Documentation::load(attrs), }) } pub fn path(&self) -> &Path { &self.path } pub fn simplify_standard_types(&mut self) { self.ret.simplify_standard_types(); for &mut (_, ref mut ty) in &mut self.args { ty.simplify_standard_types(); } } pub fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { self.ret.add_dependencies(library, out); for &(_, ref ty) in &self.args { ty.add_dependencies(library, out); } } pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { self.ret.add_monomorphs(library, out); for &(_, ref ty) in &self.args { ty.add_monomorphs(library, out); } } pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) { self.ret.mangle_paths(monomorphs); for &mut (_, ref mut ty) in &mut self.args { ty.mangle_paths(monomorphs); } } pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { self.ret.resolve_declaration_types(resolver); for &mut (_, ref mut ty) in &mut self.args { ty.resolve_declaration_types(resolver); } } pub fn rename_for_config(&mut self, config: &Config) { // Rename the types used in arguments let generic_params = Default::default(); self.ret.rename_for_config(config, &generic_params); for &mut (_, ref mut ty) in &mut self.args { ty.rename_for_config(config, &generic_params); } // Apply rename rules to argument names let rules = [ self.annotations.parse_atom::("rename-all"), config.function.rename_args, ]; if let Some(r) = find_first_some(&rules) { self.args = self .args .iter() .map(|x| { ( r.apply_to_snake_case(&x.0, IdentifierType::FunctionArg), x.1.clone(), ) }) .collect() } // Escape C/C++ reserved keywords used in argument names for args in &mut self.args { reserved::escape(&mut args.0); } } } impl Source for Function { fn write(&self, config: &Config, out: &mut SourceWriter) { fn write_1(func: &Function, config: &Config, out: &mut SourceWriter) { let void_prototype = config.language == Language::C; let prefix = config.function.prefix(&func.annotations); let postfix = config.function.postfix(&func.annotations); let condition = (&func.cfg).to_condition(config); condition.write_before(config, out); func.documentation.write(config, out); if func.extern_decl { out.write("extern "); } else { if let Some(ref prefix) = prefix { write!(out, "{} ", prefix); } if func.annotations.must_use { if let Some(ref anno) = config.function.must_use { write!(out, "{} ", anno); } } } cdecl::write_func(out, &func, false, void_prototype); if !func.extern_decl { if let Some(ref postfix) = postfix { out.write(" "); write!(out, "{}", postfix); } } out.write(";"); condition.write_after(config, out); } fn write_2(func: &Function, config: &Config, out: &mut SourceWriter) { let void_prototype = config.language == Language::C; let prefix = config.function.prefix(&func.annotations); let postfix = config.function.postfix(&func.annotations); let condition = (&func.cfg).to_condition(config); condition.write_before(config, out); func.documentation.write(config, out); if func.extern_decl { out.write("extern "); } else { if let Some(ref prefix) = prefix { write!(out, "{}", prefix); out.new_line(); } if func.annotations.must_use { if let Some(ref anno) = config.function.must_use { write!(out, "{}", anno); out.new_line(); } } } cdecl::write_func(out, &func, true, void_prototype); if !func.extern_decl { if let Some(ref postfix) = postfix { out.new_line(); write!(out, "{}", postfix); } } out.write(";"); condition.write_after(config, out); }; let option_1 = out.measure(|out| write_1(self, config, out)); if (config.function.args == Layout::Auto && option_1 <= config.line_length) || config.function.args == Layout::Horizontal { write_1(self, config, out); } else { write_2(self, config, out); } } } pub trait SynFnArgHelpers { fn as_ident_and_type(&self) -> Result, String>; } impl SynFnArgHelpers for syn::FnArg { fn as_ident_and_type(&self) -> Result, String> { match self { &syn::FnArg::Typed(syn::PatType { ref pat, ref ty, .. }) => match **pat { syn::Pat::Ident(syn::PatIdent { ref ident, .. }) => { if let Some(x) = Type::load(ty)? { Ok(Some((ident.to_string(), x))) } else { Ok(None) } } _ => Err("Parameter has an unsupported type.".to_owned()), }, _ => Err("Parameter has an unsupported type.".to_owned()), } } } cbindgen-0.12.1/src/bindgen/ir/generic_path.rs010066400017500001750000000101621360223554200173760ustar0000000000000000use std::io::Write; use std::ops::Deref; use syn; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver}; use crate::bindgen::ir::{Path, Type}; use crate::bindgen::utilities::IterHelpers; use crate::bindgen::writer::{Source, SourceWriter}; #[derive(Default, Debug, Clone)] pub struct GenericParams(pub Vec); impl GenericParams { pub fn new(generics: &syn::Generics) -> Self { GenericParams( generics .params .iter() .filter_map(|x| match *x { syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => { Some(Path::new(ident.to_string())) } _ => None, }) .collect(), ) } } impl Deref for GenericParams { type Target = [Path]; fn deref(&self) -> &[Path] { &self.0 } } impl Source for GenericParams { fn write(&self, config: &Config, out: &mut SourceWriter) { if !self.0.is_empty() && config.language == Language::Cxx { out.write("template<"); for (i, item) in self.0.iter().enumerate() { if i != 0 { out.write(", "); } write!(out, "typename {}", item); } out.write(">"); out.new_line(); } } } #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct GenericPath { path: Path, export_name: String, generics: Vec, ctype: Option, } impl GenericPath { pub fn new(path: Path, generics: Vec) -> Self { let export_name = path.name().to_owned(); Self { path, export_name, generics, ctype: None, } } pub fn replace_self_with(&mut self, self_ty: &Path) { if self.path.replace_self_with(self_ty) { self.export_name = self_ty.name().to_owned(); } for ty in &mut self.generics { ty.replace_self_with(self_ty); } } pub fn path(&self) -> &Path { &self.path } pub fn generics(&self) -> &[Type] { &self.generics } pub fn ctype(&self) -> Option<&DeclarationType> { self.ctype.as_ref() } pub fn name(&self) -> &str { self.path.name() } pub fn export_name(&self) -> &str { &self.export_name } pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) { for generic in &mut self.generics { generic.rename_for_config(config, generic_params); } if !generic_params.contains(&self.path) { config.export.rename(&mut self.export_name); } } pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { self.ctype = resolver.type_for(&self.path); } pub fn load(path: &syn::Path) -> Result { assert!( !path.segments.is_empty(), "{:?} doesn't have any segments", path ); let last_segment = path.segments.last().unwrap(); let name = last_segment.ident.to_string(); let path = Path::new(name); let phantom_data_path = Path::new("PhantomData"); if path == phantom_data_path { return Ok(Self::new(path, Vec::new())); } let generics = match last_segment.arguments { syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { ref args, .. }) => args.iter().try_skip_map(|x| match *x { syn::GenericArgument::Type(ref x) => Type::load(x), syn::GenericArgument::Lifetime(_) => Ok(None), _ => Err(format!("can't handle generic argument {:?}", x)), })?, syn::PathArguments::Parenthesized(_) => { return Err("Path contains parentheses.".to_owned()); } _ => Vec::new(), }; Ok(Self::new(path, generics)) } } cbindgen-0.12.1/src/bindgen/ir/global.rs010066400017500001750000000061031360223554200162060ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use syn; use crate::bindgen::config::Config; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{AnnotationSet, Cfg, Documentation, Item, ItemContainer, Path, Type}; use crate::bindgen::library::Library; use crate::bindgen::writer::{Source, SourceWriter}; #[derive(Debug, Clone)] pub struct Static { pub path: Path, pub export_name: String, pub ty: Type, pub mutable: bool, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, } impl Static { pub fn load(item: &syn::ItemStatic, mod_cfg: Option<&Cfg>) -> Result { let ty = Type::load(&item.ty)?; if ty.is_none() { return Err("Cannot have a zero sized static definition.".to_owned()); } Ok(Static::new( Path::new(item.ident.to_string()), ty.unwrap(), item.mutability.is_some(), Cfg::append(mod_cfg, Cfg::load(&item.attrs)), AnnotationSet::load(&item.attrs)?, Documentation::load(&item.attrs), )) } pub fn new( path: Path, ty: Type, mutable: bool, cfg: Option, annotations: AnnotationSet, documentation: Documentation, ) -> Self { let export_name = path.name().to_owned(); Self { path, export_name, ty, mutable, cfg, annotations, documentation, } } pub fn simplify_standard_types(&mut self) { self.ty.simplify_standard_types(); } } impl Item for Static { fn path(&self) -> &Path { &self.path } fn export_name(&self) -> &str { &self.export_name } fn cfg(&self) -> Option<&Cfg> { self.cfg.as_ref() } fn annotations(&self) -> &AnnotationSet { &self.annotations } fn annotations_mut(&mut self) -> &mut AnnotationSet { &mut self.annotations } fn container(&self) -> ItemContainer { ItemContainer::Static(self.clone()) } fn rename_for_config(&mut self, config: &Config) { self.ty.rename_for_config(config, &Default::default()); } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { self.ty.resolve_declaration_types(resolver); } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { self.ty.add_dependencies(library, out); } } impl Source for Static { fn write(&self, config: &Config, out: &mut SourceWriter) { out.write("extern "); if let Type::ConstPtr(..) = self.ty { } else if !self.mutable { out.write("const "); } self.ty.write(config, out); write!(out, " {};", self.export_name()); } } cbindgen-0.12.1/src/bindgen/ir/item.rs010066400017500001750000000156311360223554200157120ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::BTreeMap; use std::mem; use crate::bindgen::config::Config; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{ AnnotationSet, Cfg, Constant, Enum, OpaqueItem, Path, Static, Struct, Type, Typedef, Union, }; use crate::bindgen::library::Library; use crate::bindgen::monomorph::Monomorphs; /// An item is any type of rust item besides a function pub trait Item { fn path(&self) -> &Path; fn name(&self) -> &str { self.path().name() } fn export_name(&self) -> &str { self.name() } fn cfg(&self) -> Option<&Cfg>; fn annotations(&self) -> &AnnotationSet; fn annotations_mut(&mut self) -> &mut AnnotationSet; fn container(&self) -> ItemContainer; fn collect_declaration_types(&self, _resolver: &mut DeclarationTypeResolver) { unimplemented!() } fn resolve_declaration_types(&mut self, _resolver: &DeclarationTypeResolver) { unimplemented!() } fn rename_for_config(&mut self, _config: &Config) {} fn add_dependencies(&self, _library: &Library, _out: &mut Dependencies) {} fn instantiate_monomorph(&self, _generics: &[Type], _library: &Library, _out: &mut Monomorphs) { unreachable!("Cannot instantiate {} as a generic.", self.name()) } } #[derive(Debug, Clone)] pub enum ItemContainer { Constant(Constant), Static(Static), OpaqueItem(OpaqueItem), Struct(Struct), Union(Union), Enum(Enum), Typedef(Typedef), } impl ItemContainer { pub fn deref(&self) -> &dyn Item { match *self { ItemContainer::Constant(ref x) => x, ItemContainer::Static(ref x) => x, ItemContainer::OpaqueItem(ref x) => x, ItemContainer::Struct(ref x) => x, ItemContainer::Union(ref x) => x, ItemContainer::Enum(ref x) => x, ItemContainer::Typedef(ref x) => x, } } } #[derive(Debug, Clone)] pub enum ItemValue { Cfg(Vec), Single(T), } #[derive(Debug, Clone)] pub struct ItemMap { data: BTreeMap>, } impl ItemMap { pub fn new() -> ItemMap { ItemMap { data: BTreeMap::new(), } } pub fn rebuild(&mut self) { let old = mem::replace(self, ItemMap::new()); old.for_all_items(|x| { self.try_insert(x.clone()); }); } pub fn try_insert(&mut self, item: T) -> bool { match (item.cfg().is_some(), self.data.get_mut(item.path())) { (true, Some(&mut ItemValue::Cfg(ref mut items))) => { items.push(item); return true; } (false, Some(&mut ItemValue::Cfg(_))) => { return false; } (true, Some(&mut ItemValue::Single(_))) => { return false; } (false, Some(&mut ItemValue::Single(_))) => { return false; } _ => {} } let path = item.path().clone(); if item.cfg().is_some() { self.data.insert(path, ItemValue::Cfg(vec![item])); } else { self.data.insert(path, ItemValue::Single(item)); } true } pub fn extend_with(&mut self, other: &ItemMap) { other.for_all_items(|x| { self.try_insert(x.clone()); }); } pub fn to_vec(&self) -> Vec { let mut result = Vec::with_capacity(self.data.len()); for container in self.data.values() { match *container { ItemValue::Cfg(ref items) => result.extend_from_slice(items), ItemValue::Single(ref item) => { result.push(item.clone()); } } } result } pub fn get_items(&self, path: &Path) -> Option> { Some(match *self.data.get(path)? { ItemValue::Cfg(ref items) => items.iter().map(|x| x.container()).collect(), ItemValue::Single(ref item) => vec![item.container()], }) } pub fn filter(&mut self, callback: F) where F: Fn(&T) -> bool, { let data = mem::replace(&mut self.data, BTreeMap::new()); for (name, container) in data { match container { ItemValue::Cfg(items) => { let mut new_items = Vec::new(); for item in items { if !callback(&item) { new_items.push(item); } } if !new_items.is_empty() { self.data.insert(name, ItemValue::Cfg(new_items)); } } ItemValue::Single(item) => { if !callback(&item) { self.data.insert(name, ItemValue::Single(item)); } } } } } pub fn for_all_items(&self, mut callback: F) where F: FnMut(&T), { for container in self.data.values() { match *container { ItemValue::Cfg(ref items) => { for item in items { callback(item); } } ItemValue::Single(ref item) => callback(item), } } } pub fn for_all_items_mut(&mut self, mut callback: F) where F: FnMut(&mut T), { for container in self.data.values_mut() { match *container { ItemValue::Cfg(ref mut items) => { for item in items { callback(item); } } ItemValue::Single(ref mut item) => callback(item), } } } pub fn for_items(&self, path: &Path, mut callback: F) where F: FnMut(&T), { match self.data.get(path) { Some(&ItemValue::Cfg(ref items)) => { for item in items { callback(item); } } Some(&ItemValue::Single(ref item)) => { callback(item); } None => {} } } pub fn for_items_mut(&mut self, path: &Path, mut callback: F) where F: FnMut(&mut T), { match self.data.get_mut(path) { Some(&mut ItemValue::Cfg(ref mut items)) => { for item in items { callback(item); } } Some(&mut ItemValue::Single(ref mut item)) => { callback(item); } None => {} } } } cbindgen-0.12.1/src/bindgen/ir/mod.rs010064400017500001750000000016521356501061700155310ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub mod annotation; pub mod cfg; pub mod constant; pub mod documentation; pub mod enumeration; pub mod function; pub mod generic_path; pub mod global; pub mod item; pub mod opaque; pub mod path; pub mod repr; pub mod structure; pub mod ty; pub mod typedef; pub mod union; pub use self::annotation::{AnnotationSet, AnnotationValue}; pub use self::cfg::*; pub use self::constant::*; pub use self::documentation::Documentation; pub use self::enumeration::*; pub use self::function::*; pub use self::generic_path::*; pub use self::global::*; pub use self::item::*; pub use self::opaque::*; pub use self::path::*; pub use self::repr::*; pub use self::structure::*; pub use self::ty::*; pub use self::typedef::*; pub use self::union::*; cbindgen-0.12.1/src/bindgen/ir/opaque.rs010066400017500001750000000102331360223554200162370ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use syn; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Path, ToCondition, Type, }; use crate::bindgen::library::Library; use crate::bindgen::mangle; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::writer::{Source, SourceWriter}; #[derive(Debug, Clone)] pub struct OpaqueItem { pub path: Path, pub export_name: String, pub generic_params: GenericParams, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, } impl OpaqueItem { pub fn load( path: Path, generics: &syn::Generics, attrs: &[syn::Attribute], mod_cfg: Option<&Cfg>, ) -> Result { Ok(Self::new( path, GenericParams::new(generics), Cfg::append(mod_cfg, Cfg::load(attrs)), AnnotationSet::load(attrs).unwrap_or_else(|_| AnnotationSet::new()), Documentation::load(attrs), )) } pub fn new( path: Path, generic_params: GenericParams, cfg: Option, annotations: AnnotationSet, documentation: Documentation, ) -> OpaqueItem { let export_name = path.name().to_owned(); Self { path, export_name, generic_params, cfg, annotations, documentation, } } } impl Item for OpaqueItem { fn path(&self) -> &Path { &self.path } fn export_name(&self) -> &str { &self.export_name } fn cfg(&self) -> Option<&Cfg> { self.cfg.as_ref() } fn annotations(&self) -> &AnnotationSet { &self.annotations } fn annotations_mut(&mut self) -> &mut AnnotationSet { &mut self.annotations } fn container(&self) -> ItemContainer { ItemContainer::OpaqueItem(self.clone()) } fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { resolver.add_struct(&self.path); } fn rename_for_config(&mut self, config: &Config) { config.export.rename(&mut self.export_name); } fn add_dependencies(&self, _: &Library, _: &mut Dependencies) {} fn instantiate_monomorph( &self, generic_values: &[Type], _library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", self.path, self.generic_params.len(), generic_values.len(), ); let mangled_path = mangle::mangle_path(&self.path, generic_values); let monomorph = OpaqueItem::new( mangled_path, GenericParams::default(), self.cfg.clone(), self.annotations.clone(), self.documentation.clone(), ); out.insert_opaque(self, monomorph, generic_values.to_owned()); } } impl Source for OpaqueItem { fn write(&self, config: &Config, out: &mut SourceWriter) { let condition = (&self.cfg).to_condition(config); condition.write_before(config, out); self.documentation.write(config, out); self.generic_params.write(config, out); if config.style.generate_typedef() && config.language == Language::C { write!( out, "typedef struct {} {};", self.export_name(), self.export_name() ); } else { write!(out, "struct {};", self.export_name()); } condition.write_after(config, out); } } cbindgen-0.12.1/src/bindgen/ir/path.rs010064400017500001750000000020611356501061700157010ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cmp::Ordering; use std::fmt; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Path { name: String, } impl Path { pub fn new(name: T) -> Self where String: From, { Self { name: name.into() } } pub fn name(&self) -> &str { &self.name } pub fn replace_self_with(&mut self, path: &Self) -> bool { if self.name() != "Self" { return false; } *self = path.clone(); true } } impl PartialOrd for Path { fn partial_cmp(&self, other: &Path) -> Option { Some(self.cmp(other)) } } impl Ord for Path { fn cmp(&self, other: &Path) -> Ordering { self.name.cmp(&other.name) } } impl fmt::Display for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name) } } cbindgen-0.12.1/src/bindgen/ir/repr.rs010066400017500001750000000147141360223554200157250ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use syn; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ReprStyle { Rust, C, Transparent, } impl Default for ReprStyle { fn default() -> Self { ReprStyle::Rust } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ReprType { U8, U16, U32, U64, USize, I8, I16, I32, I64, ISize, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ReprAlign { Packed, Align(u64), } #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] pub struct Repr { pub style: ReprStyle, pub ty: Option, pub align: Option, } impl Repr { pub fn load(attrs: &[syn::Attribute]) -> Result { let ids = attrs .iter() .filter_map(|attr| { if let syn::Meta::List(syn::MetaList { path, nested, .. }) = attr.parse_meta().ok()? { if path.is_ident("repr") { return Some(nested.into_iter().collect::>()); } } None }) .flat_map(|nested| nested) .filter_map(|meta| match meta { syn::NestedMeta::Meta(syn::Meta::Path(path)) => { Some((path.segments.first().unwrap().ident.to_string(), None)) } syn::NestedMeta::Meta(syn::Meta::List(syn::MetaList { path, nested, .. })) => { Some(( path.segments.first().unwrap().ident.to_string(), Some( nested .iter() .filter_map(|meta| match meta { // Only used for #[repr(align(...))]. syn::NestedMeta::Lit(syn::Lit::Int(literal)) => { Some(literal.base10_digits().to_string()) } // Only single levels of nesting supported at the moment. _ => None, }) .collect::>(), ), )) } _ => None, }); let mut repr = Repr::default(); for id in ids { let new_ty = match (id.0.as_ref(), id.1) { ("u8", None) => ReprType::U8, ("u16", None) => ReprType::U16, ("u32", None) => ReprType::U32, ("u64", None) => ReprType::U64, ("usize", None) => ReprType::USize, ("i8", None) => ReprType::I8, ("i16", None) => ReprType::I16, ("i32", None) => ReprType::I32, ("i64", None) => ReprType::I64, ("isize", None) => ReprType::ISize, ("C", None) => { repr.style = ReprStyle::C; continue; } ("transparent", None) => { repr.style = ReprStyle::Transparent; continue; } ("packed", args) => { // #[repr(packed(n))] not supported because of some open questions about how // to calculate the native alignment of types. See eqrion/cbindgen#433. if args.is_some() { return Err(format!( "Not-yet-implemented #[repr(packed(...))] encountered." )); } let align = ReprAlign::Packed; // Only permit a single alignment-setting repr. if let Some(old_align) = repr.align { return Err(format!( "Conflicting #[repr(align(...))] type hints {:?} and {:?}.", old_align, align )); } repr.align = Some(align); continue; } ("align", Some(args)) => { // #[repr(align(...))] only allows a single argument. if args.len() != 1 { return Err(format!( "Unsupported #[repr(align({}))], align must have exactly one argument.", args.join(", ") )); } // Must be a positive integer. let align = match args.first().unwrap().parse::() { Ok(align) => align, Err(_) => { return Err(format!("Non-numeric #[repr(align({}))].", args.join(", "))) } }; // Must be a power of 2. if !align.is_power_of_two() || align == 0 { return Err(format!("Invalid alignment to #[repr(align({}))].", align)); } // Only permit a single alignment-setting repr. if let Some(old_align) = repr.align { return Err(format!( "Conflicting #[repr(align(...))] type hints {:?} and {:?}.", old_align, ReprAlign::Align(align) )); } repr.align = Some(ReprAlign::Align(align)); continue; } (path, args) => match args { None => return Err(format!("Unsupported #[repr({})].", path)), Some(args) => { return Err(format!( "Unsupported #[repr({}({}))].", path, args.join(", ") )); } }, }; if let Some(old_ty) = repr.ty { return Err(format!( "Conflicting #[repr(...)] type hints {:?} and {:?}.", old_ty, new_ty )); } repr.ty = Some(new_ty); } Ok(repr) } } cbindgen-0.12.1/src/bindgen/ir/structure.rs010066400017500001750000000513011360223554200170060ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use syn; use crate::bindgen::config::{Config, Language, LayoutConfig}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Constant, Documentation, GenericParams, Item, ItemContainer, Path, Repr, ReprAlign, ReprStyle, ToCondition, Type, Typedef, }; use crate::bindgen::library::Library; use crate::bindgen::mangle; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::rename::{IdentifierType, RenameRule}; use crate::bindgen::reserved; use crate::bindgen::utilities::{find_first_some, IterHelpers}; use crate::bindgen::writer::{ListType, Source, SourceWriter}; #[derive(Debug, Clone)] pub struct Struct { pub path: Path, pub export_name: String, pub generic_params: GenericParams, pub fields: Vec<(String, Type, Documentation)>, /// Whether there's a tag field on the body of this struct. When this is /// true, is_enum_variant_body is also guaranteed to be true. pub is_tagged: bool, /// Whether this is an enum variant body. pub is_enum_variant_body: bool, pub alignment: Option, pub is_transparent: bool, pub tuple_struct: bool, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, pub associated_constants: Vec, } impl Struct { /// Whether this struct can derive operator== / operator!=. pub fn can_derive_eq(&self) -> bool { !self.fields.is_empty() && self.fields.iter().all(|x| x.1.can_cmp_eq()) } pub fn add_associated_constant(&mut self, c: Constant) { self.associated_constants.push(c); } pub fn load( layout_config: &LayoutConfig, item: &syn::ItemStruct, mod_cfg: Option<&Cfg>, ) -> Result { let repr = Repr::load(&item.attrs)?; let is_transparent = match repr.style { ReprStyle::C => false, ReprStyle::Transparent => true, _ => { return Err("Struct is not marked #[repr(C)] or #[repr(transparent)].".to_owned()); } }; // Ensure we can safely represent the struct given the configuration. if let Some(align) = repr.align { layout_config.ensure_safe_to_represent(&align)?; } let (fields, tuple_struct) = match item.fields { syn::Fields::Unit => (Vec::new(), false), syn::Fields::Named(ref fields) => { let out = fields .named .iter() .try_skip_map(|x| x.as_ident_and_type())?; (out, false) } syn::Fields::Unnamed(ref fields) => { let mut out = Vec::new(); let mut current = 0; for field in fields.unnamed.iter() { if let Some(x) = Type::load(&field.ty)? { out.push((format!("{}", current), x, Documentation::load(&field.attrs))); current += 1; } } (out, true) } }; let is_tagged = false; let is_enum_variant_body = false; Ok(Struct::new( Path::new(item.ident.to_string()), GenericParams::new(&item.generics), fields, is_tagged, is_enum_variant_body, repr.align, is_transparent, tuple_struct, Cfg::append(mod_cfg, Cfg::load(&item.attrs)), AnnotationSet::load(&item.attrs)?, Documentation::load(&item.attrs), )) } pub fn new( path: Path, generic_params: GenericParams, fields: Vec<(String, Type, Documentation)>, is_tagged: bool, is_enum_variant_body: bool, alignment: Option, is_transparent: bool, tuple_struct: bool, cfg: Option, annotations: AnnotationSet, documentation: Documentation, ) -> Self { let export_name = path.name().to_owned(); Self { path, export_name, generic_params, fields, is_tagged, is_enum_variant_body, alignment, is_transparent, tuple_struct, cfg, annotations, documentation, associated_constants: vec![], } } pub fn simplify_standard_types(&mut self) { for &mut (_, ref mut ty, _) in &mut self.fields { ty.simplify_standard_types(); } } pub fn is_generic(&self) -> bool { self.generic_params.len() > 0 } pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { // Generic structs can instantiate monomorphs only once they've been // instantiated. See `instantiate_monomorph` for more details. if self.is_generic() { return; } for &(_, ref ty, _) in &self.fields { ty.add_monomorphs(library, out); } } pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) { for &mut (_, ref mut ty, _) in &mut self.fields { ty.mangle_paths(monomorphs); } } pub fn specialize(&self, generic_values: &[Type], mappings: &[(&Path, &Type)]) -> Self { let mangled_path = mangle::mangle_path(&self.path, generic_values); Struct::new( mangled_path, GenericParams::default(), self.fields .iter() .map(|x| (x.0.clone(), x.1.specialize(mappings), x.2.clone())) .collect(), self.is_tagged, self.is_enum_variant_body, self.alignment, self.is_transparent, self.tuple_struct, self.cfg.clone(), self.annotations.clone(), self.documentation.clone(), ) } fn emit_bitflags_binop( &self, operator: char, other: &str, out: &mut SourceWriter, ) { out.new_line(); write!( out, "{} operator{}(const {}& {}) const", self.export_name(), operator, self.export_name(), other ); out.open_brace(); write!( out, "return {{static_cast(this->bits {} {}.bits)}};", operator, other ); out.close_brace(false); out.new_line(); write!( out, "{}& operator{}=(const {}& {})", self.export_name(), operator, self.export_name(), other ); out.open_brace(); write!(out, "*this = (*this {} {});", operator, other); out.new_line(); write!(out, "return *this;"); out.close_brace(false); } } impl Item for Struct { fn path(&self) -> &Path { &self.path } fn export_name(&self) -> &str { &self.export_name } fn cfg(&self) -> Option<&Cfg> { self.cfg.as_ref() } fn annotations(&self) -> &AnnotationSet { &self.annotations } fn annotations_mut(&mut self) -> &mut AnnotationSet { &mut self.annotations } fn container(&self) -> ItemContainer { ItemContainer::Struct(self.clone()) } fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { if !self.is_transparent { resolver.add_struct(&self.path); } } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { for &mut (_, ref mut ty, _) in &mut self.fields { ty.resolve_declaration_types(resolver); } } fn rename_for_config(&mut self, config: &Config) { // Rename the name of the struct if !self.is_tagged || config.language == Language::C { config.export.rename(&mut self.export_name); } // Rename the types used in fields { let fields = self .fields .iter_mut() .skip(if self.is_tagged { 1 } else { 0 }); for &mut (_, ref mut ty, _) in fields { ty.rename_for_config(config, &self.generic_params); } } // Apply renaming rules to fields in the following order // 1. `cbindgen::field-names` annotation // 2. `cbindgen::rename-all` annotation // 3. config struct rename rule // If the struct is a tuple struct and we have not renamed the // fields, then prefix each of them with an underscore. // If any field is a reserved keyword, then postfix it with an // underscore. // Scope for mutable borrow of fields { let mut names = self.fields.iter_mut().map(|field| &mut field.0); let field_rules = [ self.annotations.parse_atom::("rename-all"), config.structure.rename_fields, ]; if let Some(o) = self.annotations.list("field-names") { for (dest, src) in names.zip(o) { *dest = src; } } else if let Some(r) = find_first_some(&field_rules) { for name in names { *name = r.apply_to_snake_case(name, IdentifierType::StructMember); } } else if self.tuple_struct { // If there is a tag field, skip it if self.is_tagged { names.next(); } // If we don't have any rules for a tuple struct, prefix them with // an underscore so it still compiles for name in names { name.insert(0, '_'); } } } for field in &mut self.fields { reserved::escape(&mut field.0); } for c in self.associated_constants.iter_mut() { c.rename_for_config(config); } } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { let mut fields = self.fields.iter(); // If there is a tag field, skip it if self.is_tagged { fields.next(); } for &(_, ref ty, _) in fields { ty.add_dependencies_ignoring_generics(&self.generic_params, library, out); } for c in &self.associated_constants { c.add_dependencies(library, out); } } fn instantiate_monomorph( &self, generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", self.path, self.generic_params.len(), generic_values.len(), ); let mappings = self .generic_params .iter() .zip(generic_values.iter()) .collect::>(); let monomorph = self.specialize(generic_values, &mappings); // Instantiate any monomorphs for any generic paths we may have just created. monomorph.add_monomorphs(library, out); out.insert_struct(self, monomorph, generic_values.to_owned()); } } impl Source for Struct { fn write(&self, config: &Config, out: &mut SourceWriter) { if self.is_transparent { let typedef = Typedef { path: self.path.clone(), export_name: self.export_name.to_owned(), generic_params: self.generic_params.clone(), aliased: self.fields[0].1.clone(), cfg: self.cfg.clone(), annotations: self.annotations.clone(), documentation: self.documentation.clone(), }; typedef.write(config, out); for constant in &self.associated_constants { out.new_line(); constant.write(config, out, Some(self)); } return; } let condition = (&self.cfg).to_condition(config); condition.write_before(config, out); self.documentation.write(config, out); if !self.is_enum_variant_body { self.generic_params.write(config, out); } // The following results in // C++ or C with Tag as style: // struct Name { // C with Type only style: // typedef struct { // C with Both as style: // typedef struct Name { if config.language == Language::C && config.style.generate_typedef() { out.write("typedef "); } out.write("struct"); if let Some(align) = self.alignment { match align { ReprAlign::Packed => { if let Some(ref anno) = config.layout.packed { write!(out, " {}", anno); } } ReprAlign::Align(n) => { if let Some(ref anno) = config.layout.aligned_n { write!(out, " {}({})", anno, n); } } } } if self.annotations.must_use { if let Some(ref anno) = config.structure.must_use { write!(out, " {}", anno); } } if config.language == Language::Cxx || config.style.generate_tag() { write!(out, " {}", self.export_name()); } out.open_brace(); if config.documentation { out.write_vertical_source_list(&self.fields, ListType::Cap(";")); } else { let vec: Vec<_> = self .fields .iter() .map(|&(ref name, ref ty, _)| (name.clone(), ty.clone())) .collect(); out.write_vertical_source_list(&vec[..], ListType::Cap(";")); } if config.language == Language::Cxx { let mut wrote_start_newline = false; if config.structure.derive_constructor(&self.annotations) && !self.fields.is_empty() { if !wrote_start_newline { wrote_start_newline = true; out.new_line(); } out.new_line(); let arg_renamer = |name: &str| { config .function .rename_args .as_ref() .unwrap_or(&RenameRule::GeckoCase) .apply_to_snake_case(name, IdentifierType::FunctionArg) }; write!(out, "{}(", self.export_name()); let vec: Vec<_> = self .fields .iter() .map(|&(ref name, ref ty, _)| { // const-ref args to constructor (format!("const& {}", arg_renamer(name)), ty.clone()) }) .collect(); out.write_vertical_source_list(&vec[..], ListType::Join(",")); write!(out, ")"); out.new_line(); write!(out, " : "); let vec: Vec<_> = self .fields .iter() .map(|x| format!("{}({})", x.0, arg_renamer(&x.0))) .collect(); out.write_vertical_source_list(&vec[..], ListType::Join(",")); out.new_line(); write!(out, "{{}}"); out.new_line(); } let other = if let Some(r) = config.function.rename_args { r.apply_to_snake_case("other", IdentifierType::FunctionArg) } else { String::from("other") }; if self .annotations .bool("internal-derive-bitflags") .unwrap_or(false) { if !wrote_start_newline { wrote_start_newline = true; out.new_line(); } out.new_line(); write!(out, "explicit operator bool() const"); out.open_brace(); write!(out, "return !!bits;"); out.close_brace(false); out.new_line(); write!(out, "{} operator~() const", self.export_name()); out.open_brace(); write!(out, "return {{static_cast(~bits)}};"); out.close_brace(false); self.emit_bitflags_binop('|', &other, out); self.emit_bitflags_binop('&', &other, out); self.emit_bitflags_binop('^', &other, out); } let skip_fields = if self.is_tagged { 1 } else { 0 }; let mut emit_op = |op, conjuc| { if !wrote_start_newline { wrote_start_newline = true; out.new_line(); } out.new_line(); write!( out, "bool operator{}(const {}& {}) const", op, self.export_name(), other ); out.open_brace(); out.write("return "); let vec: Vec<_> = self .fields .iter() .skip(skip_fields) .map(|x| format!("{} {} {}.{}", x.0, op, other, x.0)) .collect(); out.write_vertical_source_list(&vec[..], ListType::Join(&format!(" {}", conjuc))); out.write(";"); out.close_brace(false); }; if config.structure.derive_eq(&self.annotations) && self.can_derive_eq() { emit_op("==", "&&"); } if config.structure.derive_neq(&self.annotations) && self.can_derive_eq() { emit_op("!=", "||"); } if config.structure.derive_lt(&self.annotations) && self.fields.len() == 1 && self.fields[0].1.can_cmp_order() { emit_op("<", "&&"); } if config.structure.derive_lte(&self.annotations) && self.fields.len() == 1 && self.fields[0].1.can_cmp_order() { emit_op("<=", "&&"); } if config.structure.derive_gt(&self.annotations) && self.fields.len() == 1 && self.fields[0].1.can_cmp_order() { emit_op(">", "&&"); } if config.structure.derive_gte(&self.annotations) && self.fields.len() == 1 && self.fields[0].1.can_cmp_order() { emit_op(">=", "&&"); } } if let Some(body) = config.export.extra_body(&self.path) { out.write_raw_block(body); } if config.language == Language::Cxx && config.structure.associated_constants_in_body && config.constant.allow_static_const { for constant in &self.associated_constants { out.new_line(); constant.write_declaration(config, out, self); } } if config.language == Language::C && config.style.generate_typedef() { out.close_brace(false); write!(out, " {};", self.export_name()); } else { out.close_brace(true); } for constant in &self.associated_constants { out.new_line(); constant.write(config, out, Some(self)); } condition.write_after(config, out); } } pub trait SynFieldHelpers { fn as_ident_and_type(&self) -> Result, String>; } impl SynFieldHelpers for syn::Field { fn as_ident_and_type(&self) -> Result, String> { let ident = self .ident .as_ref() .ok_or_else(|| "field is missing identifier".to_string())? .clone(); let converted_ty = Type::load(&self.ty)?; if let Some(x) = converted_ty { Ok(Some(( ident.to_string(), x, Documentation::load(&self.attrs), ))) } else { Ok(None) } } } cbindgen-0.12.1/src/bindgen/ir/ty.rs010066400017500001750000000626741360223554200154210ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::fmt; use std::io::Write; use syn; use crate::bindgen::cdecl; use crate::bindgen::config::Config; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{Documentation, GenericParams, GenericPath, Path}; use crate::bindgen::library::Library; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::utilities::IterHelpers; use crate::bindgen::writer::{Source, SourceWriter}; #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum PrimitiveType { Void, Bool, Char, SChar, UChar, Char32, Short, Int, Long, LongLong, UShort, UInt, ULong, ULongLong, USize, UInt8, UInt16, UInt32, UInt64, ISize, Int8, Int16, Int32, Int64, Float, Double, SizeT, SSizeT, PtrDiffT, VaList, } impl PrimitiveType { pub fn maybe(path: &str) -> Option { match path { "c_void" => Some(PrimitiveType::Void), "c_char" => Some(PrimitiveType::Char), "c_schar" => Some(PrimitiveType::SChar), "c_uchar" => Some(PrimitiveType::UChar), "c_float" => Some(PrimitiveType::Float), "c_double" => Some(PrimitiveType::Double), "c_short" => Some(PrimitiveType::Short), "c_int" => Some(PrimitiveType::Int), "c_long" => Some(PrimitiveType::Long), "c_longlong" => Some(PrimitiveType::LongLong), "c_ushort" => Some(PrimitiveType::UShort), "c_uint" => Some(PrimitiveType::UInt), "c_ulong" => Some(PrimitiveType::ULong), "c_ulonglong" => Some(PrimitiveType::ULongLong), "bool" => Some(PrimitiveType::Bool), "char" => Some(PrimitiveType::Char32), "usize" | "uintptr_t" => Some(PrimitiveType::USize), "u8" | "uint8_t" => Some(PrimitiveType::UInt8), "u16" | "uint16_t" => Some(PrimitiveType::UInt16), "u32" | "uint32_t" => Some(PrimitiveType::UInt32), "u64" | "uint64_t" => Some(PrimitiveType::UInt64), "isize" | "intptr_t" => Some(PrimitiveType::ISize), "i8" | "int8_t" => Some(PrimitiveType::Int8), "i16" | "int16_t" => Some(PrimitiveType::Int16), "i32" | "int32_t" => Some(PrimitiveType::Int32), "i64" | "int64_t" => Some(PrimitiveType::Int64), "f32" => Some(PrimitiveType::Float), "f64" => Some(PrimitiveType::Double), "size_t" => Some(PrimitiveType::SizeT), "ssize_t" => Some(PrimitiveType::SSizeT), "ptrdiff_t" => Some(PrimitiveType::PtrDiffT), "VaList" => Some(PrimitiveType::VaList), _ => None, } } pub fn to_repr_rust(&self) -> &'static str { match *self { PrimitiveType::Void => "c_void", PrimitiveType::Char => "c_char", PrimitiveType::SChar => "c_schar", PrimitiveType::UChar => "c_uchar", PrimitiveType::Char32 => "char", PrimitiveType::Short => "c_short", PrimitiveType::Int => "c_int", PrimitiveType::Long => "c_long", PrimitiveType::LongLong => "c_longlong", PrimitiveType::UShort => "c_ushort", PrimitiveType::UInt => "c_uint", PrimitiveType::ULong => "c_ulong", PrimitiveType::ULongLong => "c_ulonglong", PrimitiveType::Bool => "bool", PrimitiveType::USize => "usize", PrimitiveType::UInt8 => "u8", PrimitiveType::UInt16 => "u16", PrimitiveType::UInt32 => "u32", PrimitiveType::UInt64 => "u64", PrimitiveType::ISize => "isize", PrimitiveType::Int8 => "i8", PrimitiveType::Int16 => "i16", PrimitiveType::Int32 => "i32", PrimitiveType::Int64 => "i64", PrimitiveType::Float => "f32", PrimitiveType::Double => "f64", PrimitiveType::SizeT => "size_t", PrimitiveType::SSizeT => "ssize_t", PrimitiveType::PtrDiffT => "ptrdiff_t", PrimitiveType::VaList => "va_list", } } pub fn to_repr_c(&self) -> &'static str { match *self { PrimitiveType::Void => "void", PrimitiveType::Bool => "bool", PrimitiveType::Char => "char", PrimitiveType::SChar => "signed char", PrimitiveType::UChar => "unsigned char", // NOTE: It'd be nice to use a char32_t, but: // // * uchar.h is not present on mac (see #423). // // * char32_t isn't required to be compatible with Rust's char, as // the C++ spec only requires it to be the same size as // uint_least32_t, which is _not_ guaranteed to be 4-bytes. // PrimitiveType::Char32 => "uint32_t", PrimitiveType::Short => "short", PrimitiveType::Int => "int", PrimitiveType::Long => "long", PrimitiveType::LongLong => "long long", PrimitiveType::UShort => "unsigned short", PrimitiveType::UInt => "unsigned int", PrimitiveType::ULong => "unsigned long", PrimitiveType::ULongLong => "unsigned long long", PrimitiveType::USize => "uintptr_t", PrimitiveType::UInt8 => "uint8_t", PrimitiveType::UInt16 => "uint16_t", PrimitiveType::UInt32 => "uint32_t", PrimitiveType::UInt64 => "uint64_t", PrimitiveType::ISize => "intptr_t", PrimitiveType::Int8 => "int8_t", PrimitiveType::Int16 => "int16_t", PrimitiveType::Int32 => "int32_t", PrimitiveType::Int64 => "int64_t", PrimitiveType::Float => "float", PrimitiveType::Double => "double", PrimitiveType::SizeT => "size_t", PrimitiveType::SSizeT => "ssize_t", PrimitiveType::PtrDiffT => "ptrdiff_t", PrimitiveType::VaList => "va_list", } } fn can_cmp_order(&self) -> bool { match *self { PrimitiveType::Bool => false, _ => true, } } fn can_cmp_eq(&self) -> bool { true } } impl fmt::Display for PrimitiveType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_repr_c()) } } // The `U` part of `[T; U]` #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum ArrayLength { Name(String), Value(String), } impl ArrayLength { pub fn as_str(&self) -> &str { match self { ArrayLength::Name(ref string) | ArrayLength::Value(ref string) => string, } } fn rename_for_config(&mut self, config: &Config) { if let ArrayLength::Name(ref mut name) = self { config.export.rename(name); } } } #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Type { ConstPtr(Box), Ptr(Box), Ref(Box), MutRef(Box), Path(GenericPath), Primitive(PrimitiveType), Array(Box, ArrayLength), FuncPtr(Box, Vec<(Option, Type)>), } impl Type { pub fn load(ty: &syn::Type) -> Result, String> { let converted = match *ty { syn::Type::Reference(ref reference) => { let converted = Type::load(&reference.elem)?; let converted = match converted { Some(converted) => converted, None => { return Err("Cannot have a pointer to a zero sized type. If you are \ trying to represent `void*` use `c_void*`." .to_owned()); } }; match reference.mutability { Some(_) => Type::Ptr(Box::new(converted)), None => Type::ConstPtr(Box::new(converted)), } } syn::Type::Ptr(ref pointer) => { let converted = Type::load(&pointer.elem)?; let converted = match converted { Some(converted) => converted, None => { return Err("Cannot have a pointer to a zero sized type. If you are \ trying to represent `void*` use `c_void*`." .to_owned()); } }; match pointer.mutability { Some(_) => Type::Ptr(Box::new(converted)), None => Type::ConstPtr(Box::new(converted)), } } syn::Type::Path(ref path) => { let generic_path = GenericPath::load(&path.path)?; if generic_path.name() == "PhantomData" { return Ok(None); } if let Some(prim) = PrimitiveType::maybe(generic_path.name()) { if !generic_path.generics().is_empty() { return Err("Primitive has generics.".to_owned()); } Type::Primitive(prim) } else { Type::Path(generic_path) } } syn::Type::Array(syn::TypeArray { ref elem, len: syn::Expr::Path(ref path), .. }) => { let converted = Type::load(elem)?; let converted = match converted { Some(converted) => converted, None => return Err("Cannot have an array of zero sized types.".to_owned()), }; let generic_path = GenericPath::load(&path.path)?; let len = ArrayLength::Name(generic_path.export_name().to_owned()); Type::Array(Box::new(converted), len) } syn::Type::Array(syn::TypeArray { ref elem, len: syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(ref len), .. }), .. }) => { let converted = Type::load(elem)?; let converted = match converted { Some(converted) => converted, None => return Err("Cannot have an array of zero sized types.".to_owned()), }; let len = ArrayLength::Value(len.base10_digits().to_string()); // panic!("panic -> value: {:?}", len); Type::Array(Box::new(converted), len) } syn::Type::BareFn(ref function) => { let mut wildcard_counter = 0; let args = function.inputs.iter().try_skip_map(|x| { Type::load(&x.ty).map(|opt_ty| { opt_ty.map(|ty| { ( x.name.as_ref().map(|(ref ident, _)| { if ident == "_" { wildcard_counter += 1; if wildcard_counter == 1 { "_".to_owned() } else { format!("_{}", wildcard_counter - 1) } } else { ident.to_string() } }), ty, ) }) }) })?; let ret = match function.output { syn::ReturnType::Default => Type::Primitive(PrimitiveType::Void), syn::ReturnType::Type(_, ref ty) => { if let Some(x) = Type::load(ty)? { x } else { Type::Primitive(PrimitiveType::Void) } } }; Type::FuncPtr(Box::new(ret), args) } syn::Type::Tuple(ref tuple) => { if tuple.elems.is_empty() { return Ok(None); } return Err("Tuples are not supported types.".to_owned()); } _ => return Err(format!("Unsupported type: {:?}", ty)), }; Ok(Some(converted)) } pub fn is_primitive_or_ptr_primitive(&self) -> bool { match *self { Type::Primitive(..) => true, Type::ConstPtr(ref x) => match x.as_ref() { Type::Primitive(..) => true, _ => false, }, _ => false, } } pub fn is_repr_ptr(&self) -> bool { match *self { Type::Ptr(..) => true, Type::ConstPtr(..) => true, Type::FuncPtr(..) => true, _ => false, } } fn simplified_type(&self) -> Option { let path = match *self { Type::Path(ref p) => p, _ => return None, }; if path.generics().len() != 1 { return None; } let mut generic = path.generics()[0].clone(); generic.simplify_standard_types(); match path.name() { // FIXME(#223): This is not quite correct. "Option" if generic.is_repr_ptr() => Some(generic), "NonNull" => Some(Type::Ptr(Box::new(generic))), _ => None, } } pub fn simplify_standard_types(&mut self) { if let Some(ty) = self.simplified_type() { *self = ty; } } pub fn replace_self_with(&mut self, self_ty: &Path) { match *self { Type::Array(ref mut ty, ..) | Type::MutRef(ref mut ty) | Type::Ref(ref mut ty) | Type::Ptr(ref mut ty) | Type::ConstPtr(ref mut ty) => ty.replace_self_with(self_ty), Type::Path(ref mut generic_path) => { generic_path.replace_self_with(self_ty); } Type::Primitive(..) => {} Type::FuncPtr(ref mut ret, ref mut args) => { ret.replace_self_with(self_ty); for arg in args { arg.1.replace_self_with(self_ty); } } } } pub fn get_root_path(&self) -> Option { let mut current = self; loop { match *current { Type::ConstPtr(ref ty) => current = ty, Type::Ptr(ref ty) => current = ty, Type::Ref(ref ty) => current = ty, Type::MutRef(ref ty) => current = ty, Type::Path(ref generic) => { return Some(generic.path().clone()); } Type::Primitive(..) => { return None; } Type::Array(..) => { return None; } Type::FuncPtr(..) => { return None; } }; } } pub fn specialize(&self, mappings: &[(&Path, &Type)]) -> Type { match *self { Type::ConstPtr(ref ty) => Type::ConstPtr(Box::new(ty.specialize(mappings))), Type::Ptr(ref ty) => Type::Ptr(Box::new(ty.specialize(mappings))), Type::Ref(ref ty) => Type::Ref(Box::new(ty.specialize(mappings))), Type::MutRef(ref ty) => Type::MutRef(Box::new(ty.specialize(mappings))), Type::Path(ref generic_path) => { for &(param, value) in mappings { if generic_path.path() == param { return value.clone(); } } let specialized = GenericPath::new( generic_path.path().clone(), generic_path .generics() .iter() .map(|x| x.specialize(mappings)) .collect(), ); Type::Path(specialized) } Type::Primitive(ref primitive) => Type::Primitive(primitive.clone()), Type::Array(ref ty, ref constant) => { Type::Array(Box::new(ty.specialize(mappings)), constant.clone()) } Type::FuncPtr(ref ret, ref args) => Type::FuncPtr( Box::new(ret.specialize(mappings)), args.iter() .cloned() .map(|(name, ty)| (name, ty.specialize(mappings))) .collect(), ), } } pub fn add_dependencies_ignoring_generics( &self, generic_params: &GenericParams, library: &Library, out: &mut Dependencies, ) { match *self { Type::ConstPtr(ref ty) => { ty.add_dependencies_ignoring_generics(generic_params, library, out); } Type::Ptr(ref ty) => { ty.add_dependencies_ignoring_generics(generic_params, library, out); } Type::Ref(ref ty) | Type::MutRef(ref ty) => { ty.add_dependencies_ignoring_generics(generic_params, library, out); } Type::Path(ref generic) => { for generic_value in generic.generics() { generic_value.add_dependencies_ignoring_generics(generic_params, library, out); } let path = generic.path(); if !generic_params.contains(path) { if let Some(items) = library.get_items(path) { if !out.items.contains(path) { out.items.insert(path.clone()); for item in &items { item.deref().add_dependencies(library, out); } for item in items { out.order.push(item); } } } else { warn!( "Can't find {}. This usually means that this type was incompatible or \ not found.", path ); } } } Type::Primitive(_) => {} Type::Array(ref ty, _) => { ty.add_dependencies_ignoring_generics(generic_params, library, out); } Type::FuncPtr(ref ret, ref args) => { ret.add_dependencies_ignoring_generics(generic_params, library, out); for (_, ref arg) in args { arg.add_dependencies_ignoring_generics(generic_params, library, out); } } } } pub fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { self.add_dependencies_ignoring_generics(&GenericParams::default(), library, out) } pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { match *self { Type::ConstPtr(ref ty) => { ty.add_monomorphs(library, out); } Type::Ptr(ref ty) => { ty.add_monomorphs(library, out); } Type::Ref(ref ty) | Type::MutRef(ref ty) => { ty.add_monomorphs(library, out); } Type::Path(ref generic) => { if generic.generics().is_empty() || out.contains(&generic) { return; } let path = generic.path(); if let Some(items) = library.get_items(path) { for item in items { item.deref() .instantiate_monomorph(generic.generics(), library, out); } } } Type::Primitive(_) => {} Type::Array(ref ty, _) => { ty.add_monomorphs(library, out); } Type::FuncPtr(ref ret, ref args) => { ret.add_monomorphs(library, out); for (_, ref arg) in args { arg.add_monomorphs(library, out); } } } } pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) { match *self { Type::ConstPtr(ref mut ty) => { ty.rename_for_config(config, generic_params); } Type::Ptr(ref mut ty) => { ty.rename_for_config(config, generic_params); } Type::Ref(ref mut ty) | Type::MutRef(ref mut ty) => { ty.rename_for_config(config, generic_params); } Type::Path(ref mut ty) => { ty.rename_for_config(config, generic_params); } Type::Primitive(_) => {} Type::Array(ref mut ty, ref mut len) => { ty.rename_for_config(config, generic_params); len.rename_for_config(config); } Type::FuncPtr(ref mut ret, ref mut args) => { ret.rename_for_config(config, generic_params); for (_, arg) in args { arg.rename_for_config(config, generic_params); } } } } pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { match *self { Type::ConstPtr(ref mut ty) => { ty.resolve_declaration_types(resolver); } Type::Ptr(ref mut ty) => { ty.resolve_declaration_types(resolver); } Type::Ref(ref mut ty) | Type::MutRef(ref mut ty) => { ty.resolve_declaration_types(resolver); } Type::Path(ref mut generic_path) => { generic_path.resolve_declaration_types(resolver); } Type::Primitive(_) => {} Type::Array(ref mut ty, _) => { ty.resolve_declaration_types(resolver); } Type::FuncPtr(ref mut ret, ref mut args) => { ret.resolve_declaration_types(resolver); for (_, ref mut arg) in args { arg.resolve_declaration_types(resolver); } } } } pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) { match *self { Type::ConstPtr(ref mut ty) => { ty.mangle_paths(monomorphs); } Type::Ptr(ref mut ty) => { ty.mangle_paths(monomorphs); } Type::Ref(ref mut ty) | Type::MutRef(ref mut ty) => { ty.mangle_paths(monomorphs); } Type::Path(ref mut generic_path) => { if generic_path.generics().is_empty() { return; } if let Some(mangled_path) = monomorphs.mangle_path(&generic_path) { *generic_path = GenericPath::new(mangled_path.clone(), vec![]); } else { error!( "Cannot find a mangling for generic path {:?}. This usually means that a \ type referenced by this generic was incompatible or not found.", generic_path ); } } Type::Primitive(_) => {} Type::Array(ref mut ty, _) => { ty.mangle_paths(monomorphs); } Type::FuncPtr(ref mut ret, ref mut args) => { ret.mangle_paths(monomorphs); for (_, ref mut arg) in args { arg.mangle_paths(monomorphs); } } } } pub fn can_cmp_order(&self) -> bool { match *self { Type::ConstPtr(..) => true, Type::Ptr(..) => true, Type::Ref(..) | Type::MutRef(..) => false, Type::Path(..) => true, Type::Primitive(ref p) => p.can_cmp_order(), Type::Array(..) => false, Type::FuncPtr(..) => false, } } pub fn can_cmp_eq(&self) -> bool { match *self { Type::ConstPtr(..) => true, Type::Ptr(..) => true, Type::Ref(..) | Type::MutRef(..) => false, Type::Path(..) => true, Type::Primitive(ref p) => p.can_cmp_eq(), Type::Array(..) => false, Type::FuncPtr(..) => true, } } } impl Source for String { fn write(&self, _config: &Config, out: &mut SourceWriter) { write!(out, "{}", self); } } impl Source for Type { fn write(&self, _config: &Config, out: &mut SourceWriter) { cdecl::write_type(out, &self); } } impl Source for (String, Type) { fn write(&self, _config: &Config, out: &mut SourceWriter) { cdecl::write_field(out, &self.1, &self.0); } } impl Source for (String, Type, Documentation) { fn write(&self, config: &Config, out: &mut SourceWriter) { self.2.write(config, out); cdecl::write_field(out, &self.1, &self.0); } } cbindgen-0.12.1/src/bindgen/ir/typedef.rs010066400017500001750000000142731360223554200164150ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::HashMap; use std::io::Write; use syn; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Path, ToCondition, Type, }; use crate::bindgen::library::Library; use crate::bindgen::mangle; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::writer::{Source, SourceWriter}; /// A type alias that is represented as a C typedef #[derive(Debug, Clone)] pub struct Typedef { pub path: Path, pub export_name: String, pub generic_params: GenericParams, pub aliased: Type, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, } impl Typedef { pub fn load(item: &syn::ItemType, mod_cfg: Option<&Cfg>) -> Result { if let Some(x) = Type::load(&item.ty)? { let path = Path::new(item.ident.to_string()); Ok(Typedef::new( path, GenericParams::new(&item.generics), x, Cfg::append(mod_cfg, Cfg::load(&item.attrs)), AnnotationSet::load(&item.attrs)?, Documentation::load(&item.attrs), )) } else { Err("Cannot have a typedef of a zero sized type.".to_owned()) } } pub fn new( path: Path, generic_params: GenericParams, aliased: Type, cfg: Option, annotations: AnnotationSet, documentation: Documentation, ) -> Self { let export_name = path.name().to_owned(); Self { path, export_name, generic_params, aliased, cfg, annotations, documentation, } } pub fn simplify_standard_types(&mut self) { self.aliased.simplify_standard_types(); } pub fn transfer_annotations(&mut self, out: &mut HashMap) { if self.annotations.is_empty() { return; } if let Some(alias_path) = self.aliased.get_root_path() { if out.contains_key(&alias_path) { warn!( "Multiple typedef's with annotations for {}. Ignoring annotations from {}.", alias_path, self.path ); return; } out.insert(alias_path, self.annotations.clone()); self.annotations = AnnotationSet::new(); } } pub fn is_generic(&self) -> bool { self.generic_params.len() > 0 } pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { // Generic structs can instantiate monomorphs only once they've been // instantiated. See `instantiate_monomorph` for more details. if self.is_generic() { return; } self.aliased.add_monomorphs(library, out); } pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) { self.aliased.mangle_paths(monomorphs); } } impl Item for Typedef { fn path(&self) -> &Path { &self.path } fn export_name(&self) -> &str { &self.export_name } fn cfg(&self) -> Option<&Cfg> { self.cfg.as_ref() } fn annotations(&self) -> &AnnotationSet { &self.annotations } fn annotations_mut(&mut self) -> &mut AnnotationSet { &mut self.annotations } fn container(&self) -> ItemContainer { ItemContainer::Typedef(self.clone()) } fn rename_for_config(&mut self, config: &Config) { config.export.rename(&mut self.export_name); self.aliased.rename_for_config(config, &self.generic_params); } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { self.aliased.resolve_declaration_types(resolver); } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { self.aliased .add_dependencies_ignoring_generics(&self.generic_params, library, out); } fn instantiate_monomorph( &self, generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", self.path, self.generic_params.len(), generic_values.len(), ); let mappings = self .generic_params .iter() .zip(generic_values.iter()) .collect::>(); let mangled_path = mangle::mangle_path(&self.path, generic_values); let monomorph = Typedef::new( mangled_path, GenericParams::default(), self.aliased.specialize(&mappings), self.cfg.clone(), self.annotations.clone(), self.documentation.clone(), ); // Instantiate any monomorphs for any generic paths we may have just created. monomorph.add_monomorphs(library, out); out.insert_typedef(self, monomorph, generic_values.to_owned()); } } impl Source for Typedef { fn write(&self, config: &Config, out: &mut SourceWriter) { let condition = (&self.cfg).to_condition(config); condition.write_before(config, out); self.documentation.write(config, out); self.generic_params.write(config, out); if config.language == Language::C { out.write("typedef "); (self.export_name().to_owned(), self.aliased.clone()).write(config, out); } else { write!(out, "using {} = ", self.export_name()); self.aliased.write(config, out); } out.write(";"); condition.write_after(config, out); } } cbindgen-0.12.1/src/bindgen/ir/union.rs010066400017500001750000000234321360223554200161020ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io::Write; use syn; use crate::bindgen::config::{Config, Language, LayoutConfig}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::ir::SynFieldHelpers; use crate::bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Path, Repr, ReprAlign, ReprStyle, ToCondition, Type, }; use crate::bindgen::library::Library; use crate::bindgen::mangle; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::rename::{IdentifierType, RenameRule}; use crate::bindgen::utilities::{find_first_some, IterHelpers}; use crate::bindgen::writer::{ListType, Source, SourceWriter}; #[derive(Debug, Clone)] pub struct Union { pub path: Path, pub export_name: String, pub generic_params: GenericParams, pub fields: Vec<(String, Type, Documentation)>, pub tuple_union: bool, pub alignment: Option, pub cfg: Option, pub annotations: AnnotationSet, pub documentation: Documentation, } impl Union { pub fn load( layout_config: &LayoutConfig, item: &syn::ItemUnion, mod_cfg: Option<&Cfg>, ) -> Result { let repr = Repr::load(&item.attrs)?; if repr.style != ReprStyle::C { return Err("Union is not marked #[repr(C)].".to_owned()); } // Ensure we can safely represent the union given the configuration. if let Some(align) = repr.align { layout_config.ensure_safe_to_represent(&align)?; } let (fields, tuple_union) = { let out = item .fields .named .iter() .try_skip_map(|x| x.as_ident_and_type())?; (out, false) }; Ok(Union::new( Path::new(item.ident.to_string()), GenericParams::new(&item.generics), fields, repr.align, tuple_union, Cfg::append(mod_cfg, Cfg::load(&item.attrs)), AnnotationSet::load(&item.attrs)?, Documentation::load(&item.attrs), )) } pub fn new( path: Path, generic_params: GenericParams, fields: Vec<(String, Type, Documentation)>, alignment: Option, tuple_union: bool, cfg: Option, annotations: AnnotationSet, documentation: Documentation, ) -> Self { let export_name = path.name().to_owned(); Self { path, export_name, generic_params, fields, alignment, tuple_union, cfg, annotations, documentation, } } pub fn simplify_standard_types(&mut self) { for &mut (_, ref mut ty, _) in &mut self.fields { ty.simplify_standard_types(); } } pub fn is_generic(&self) -> bool { self.generic_params.len() > 0 } pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { // Generic unions can instantiate monomorphs only once they've been // instantiated. See `instantiate_monomorph` for more details. if self.is_generic() { return; } for &(_, ref ty, _) in &self.fields { ty.add_monomorphs(library, out); } } pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) { for &mut (_, ref mut ty, _) in &mut self.fields { ty.mangle_paths(monomorphs); } } } impl Item for Union { fn path(&self) -> &Path { &self.path } fn export_name(&self) -> &str { &self.export_name } fn cfg(&self) -> Option<&Cfg> { self.cfg.as_ref() } fn annotations(&self) -> &AnnotationSet { &self.annotations } fn annotations_mut(&mut self) -> &mut AnnotationSet { &mut self.annotations } fn container(&self) -> ItemContainer { ItemContainer::Union(self.clone()) } fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { resolver.add_union(&self.path); } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { for &mut (_, ref mut ty, _) in &mut self.fields { ty.resolve_declaration_types(resolver); } } fn rename_for_config(&mut self, config: &Config) { config.export.rename(&mut self.export_name); for &mut (_, ref mut ty, _) in &mut self.fields { ty.rename_for_config(config, &self.generic_params); } let rules = [ self.annotations.parse_atom::("rename-all"), config.structure.rename_fields, ]; if let Some(o) = self.annotations.list("field-names") { let mut overriden_fields = Vec::new(); for (i, &(ref name, ref ty, ref doc)) in self.fields.iter().enumerate() { if i >= o.len() { overriden_fields.push((name.clone(), ty.clone(), doc.clone())); } else { overriden_fields.push((o[i].clone(), ty.clone(), doc.clone())); } } self.fields = overriden_fields; } else if let Some(r) = find_first_some(&rules) { self.fields = self .fields .iter() .map(|x| { ( r.apply_to_snake_case(&x.0, IdentifierType::StructMember), x.1.clone(), x.2.clone(), ) }) .collect(); } else if self.tuple_union { // If we don't have any rules for a tuple union, prefix them with // an underscore so it still compiles for &mut (ref mut name, ..) in &mut self.fields { name.insert(0, '_'); } } } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { for &(_, ref ty, _) in &self.fields { ty.add_dependencies_ignoring_generics(&self.generic_params, library, out); } } fn instantiate_monomorph( &self, generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", self.path, self.generic_params.len(), generic_values.len(), ); let mappings = self .generic_params .iter() .zip(generic_values.iter()) .collect::>(); let mangled_path = mangle::mangle_path(&self.path, generic_values); let monomorph = Union::new( mangled_path, GenericParams::default(), self.fields .iter() .map(|x| (x.0.clone(), x.1.specialize(&mappings), x.2.clone())) .collect(), self.alignment, self.tuple_union, self.cfg.clone(), self.annotations.clone(), self.documentation.clone(), ); // Instantiate any monomorphs for any generic paths we may have just created. monomorph.add_monomorphs(library, out); out.insert_union(self, monomorph, generic_values.to_owned()); } } impl Source for Union { fn write(&self, config: &Config, out: &mut SourceWriter) { let condition = (&self.cfg).to_condition(config); condition.write_before(config, out); self.documentation.write(config, out); self.generic_params.write(config, out); // The following results in // C++ or C with Tag as style: // union Name { // C with Type only style: // typedef union { // C with Both as style: // typedef union Name { if config.language == Language::C && config.style.generate_typedef() { out.write("typedef "); } out.write("union"); if let Some(align) = self.alignment { match align { ReprAlign::Packed => { if let Some(ref anno) = config.layout.packed { write!(out, " {}", anno); } } ReprAlign::Align(n) => { if let Some(ref anno) = config.layout.aligned_n { write!(out, " {}({})", anno, n); } } } } if config.language == Language::Cxx || config.style.generate_tag() { write!(out, " {}", self.export_name); } out.open_brace(); if config.documentation { out.write_vertical_source_list(&self.fields, ListType::Cap(";")); } else { let vec: Vec<_> = self .fields .iter() .map(|&(ref name, ref ty, _)| (name.clone(), ty.clone())) .collect(); out.write_vertical_source_list(&vec[..], ListType::Cap(";")); } if let Some(body) = config.export.extra_body(&self.path) { out.write_raw_block(body); } if config.language == Language::C && config.style.generate_typedef() { out.close_brace(false); write!(out, " {};", self.export_name); } else { out.close_brace(true); } condition.write_after(config, out); } } cbindgen-0.12.1/src/bindgen/library.rs010066400017500001750000000321351360223554200160040ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::HashMap; use std::mem; use crate::bindgen::bindings::Bindings; use crate::bindgen::config::{Config, Language}; use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; use crate::bindgen::dependencies::Dependencies; use crate::bindgen::error::Error; use crate::bindgen::ir::{Constant, Enum, Function, Item, ItemContainer, ItemMap}; use crate::bindgen::ir::{OpaqueItem, Path, Static, Struct, Typedef, Union}; use crate::bindgen::monomorph::Monomorphs; use crate::bindgen::ItemType; #[derive(Debug, Clone)] pub struct Library { config: Config, constants: ItemMap, globals: ItemMap, enums: ItemMap, structs: ItemMap, unions: ItemMap, opaque_items: ItemMap, typedefs: ItemMap, functions: Vec, } impl Library { pub fn new( config: Config, constants: ItemMap, globals: ItemMap, enums: ItemMap, structs: ItemMap, unions: ItemMap, opaque_items: ItemMap, typedefs: ItemMap, functions: Vec, ) -> Library { Library { config, constants, globals, enums, structs, unions, opaque_items, typedefs, functions, } } pub fn generate(mut self) -> Result { self.remove_excluded(); self.functions.sort_by(|x, y| x.path.cmp(&y.path)); self.transfer_annotations(); self.simplify_standard_types(); if self.config.language == Language::C { self.instantiate_monomorphs(); self.resolve_declaration_types(); } self.rename_items(); let mut dependencies = Dependencies::new(); for function in &self.functions { function.add_dependencies(&self, &mut dependencies); } self.globals.for_all_items(|global| { global.add_dependencies(&self, &mut dependencies); }); self.constants.for_all_items(|constant| { constant.add_dependencies(&self, &mut dependencies); }); for name in &self.config.export.include { let path = Path::new(name.clone()); if let Some(items) = self.get_items(&path) { if !dependencies.items.contains(&path) { dependencies.items.insert(path); for item in &items { item.deref().add_dependencies(&self, &mut dependencies); } for item in items { dependencies.order.push(item); } } } } dependencies.sort(); let items = dependencies.order; let constants = if self.config.export.should_generate(ItemType::Constants) { self.constants.to_vec() } else { vec![] }; let globals = if self.config.export.should_generate(ItemType::Globals) { self.globals.to_vec() } else { vec![] }; let functions = if self.config.export.should_generate(ItemType::Functions) { mem::replace(&mut self.functions, vec![]) } else { vec![] }; Ok(Bindings::new( self.config, self.structs, constants, globals, items, functions, )) } pub fn get_items(&self, p: &Path) -> Option> { macro_rules! find { ($field:ident, $kind:ident) => { if self.config.export.should_generate(ItemType::$kind) { if let Some(x) = self.$field.get_items(p) { return Some(x); } } }; } find!(enums, Enums); find!(structs, Structs); find!(unions, Unions); find!(opaque_items, OpaqueItems); find!(typedefs, Typedefs); None } fn remove_excluded(&mut self) { let config = &self.config; // FIXME: interpret `config.export.exclude` as `Path`s. self.functions .retain(|x| !config.export.exclude.iter().any(|y| y == x.path().name())); self.enums .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.structs .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.unions .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.opaque_items .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.typedefs .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.globals .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.constants .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); } fn transfer_annotations(&mut self) { let mut annotations = HashMap::new(); self.typedefs.for_all_items_mut(|x| { x.transfer_annotations(&mut annotations); }); for (alias_path, annotations) in annotations { // TODO let mut transferred = false; self.enums.for_items_mut(&alias_path, |x| { if x.annotations().is_empty() { *x.annotations_mut() = annotations.clone(); transferred = true; } else { warn!( "Can't transfer annotations from typedef to alias ({}) \ that already has annotations.", alias_path ); } }); if transferred { continue; } self.structs.for_items_mut(&alias_path, |x| { if x.annotations().is_empty() { *x.annotations_mut() = annotations.clone(); transferred = true; } else { warn!( "Can't transfer annotations from typedef to alias ({}) \ that already has annotations.", alias_path ); } }); if transferred { continue; } self.unions.for_items_mut(&alias_path, |x| { if x.annotations().is_empty() { *x.annotations_mut() = annotations.clone(); transferred = true; } else { warn!( "Can't transfer annotations from typedef to alias ({}) \ that already has annotations.", alias_path ); } }); if transferred { continue; } self.opaque_items.for_items_mut(&alias_path, |x| { if x.annotations().is_empty() { *x.annotations_mut() = annotations.clone(); transferred = true; } else { warn!( "Can't transfer annotations from typedef to alias ({}) \ that already has annotations.", alias_path ); } }); if transferred { continue; } self.typedefs.for_items_mut(&alias_path, |x| { if x.annotations().is_empty() { *x.annotations_mut() = annotations.clone(); transferred = true; } else { warn!( "Can't transfer annotations from typedef to alias ({}) \ that already has annotations.", alias_path ); } }); if transferred { continue; } } } fn rename_items(&mut self) { let config = &self.config; self.globals .for_all_items_mut(|x| x.rename_for_config(config)); self.globals.rebuild(); self.constants .for_all_items_mut(|x| x.rename_for_config(config)); self.constants.rebuild(); self.structs .for_all_items_mut(|x| x.rename_for_config(config)); self.structs.rebuild(); self.unions .for_all_items_mut(|x| x.rename_for_config(config)); self.unions.rebuild(); self.enums .for_all_items_mut(|x| x.rename_for_config(config)); self.enums.rebuild(); self.opaque_items .for_all_items_mut(|x| x.rename_for_config(config)); self.opaque_items.rebuild(); self.typedefs .for_all_items_mut(|x| x.rename_for_config(config)); self.typedefs.rebuild(); for item in &mut self.functions { item.rename_for_config(&self.config); } } fn resolve_declaration_types(&mut self) { if self.config.style.generate_typedef() { return; } let mut resolver = DeclarationTypeResolver::new(); self.structs.for_all_items(|x| { x.collect_declaration_types(&mut resolver); }); self.opaque_items.for_all_items(|x| { x.collect_declaration_types(&mut resolver); }); self.enums.for_all_items(|x| { x.collect_declaration_types(&mut resolver); }); self.unions.for_all_items(|x| { x.collect_declaration_types(&mut resolver); }); self.enums .for_all_items_mut(|x| x.resolve_declaration_types(&resolver)); self.structs .for_all_items_mut(|x| x.resolve_declaration_types(&resolver)); self.unions .for_all_items_mut(|x| x.resolve_declaration_types(&resolver)); self.typedefs .for_all_items_mut(|x| x.resolve_declaration_types(&resolver)); self.globals .for_all_items_mut(|x| x.resolve_declaration_types(&resolver)); for item in &mut self.functions { item.resolve_declaration_types(&resolver); } } fn simplify_standard_types(&mut self) { self.structs.for_all_items_mut(|x| { x.simplify_standard_types(); }); self.unions.for_all_items_mut(|x| { x.simplify_standard_types(); }); self.globals.for_all_items_mut(|x| { x.simplify_standard_types(); }); self.typedefs.for_all_items_mut(|x| { x.simplify_standard_types(); }); for x in &mut self.functions { x.simplify_standard_types(); } } fn instantiate_monomorphs(&mut self) { // Collect a list of monomorphs let mut monomorphs = Monomorphs::default(); self.structs.for_all_items(|x| { x.add_monomorphs(self, &mut monomorphs); }); self.unions.for_all_items(|x| { x.add_monomorphs(self, &mut monomorphs); }); self.enums.for_all_items(|x| { x.add_monomorphs(self, &mut monomorphs); }); self.typedefs.for_all_items(|x| { x.add_monomorphs(self, &mut monomorphs); }); for x in &self.functions { x.add_monomorphs(self, &mut monomorphs); } // Insert the monomorphs into self for monomorph in monomorphs.drain_structs() { self.structs.try_insert(monomorph); } for monomorph in monomorphs.drain_unions() { self.unions.try_insert(monomorph); } for monomorph in monomorphs.drain_opaques() { self.opaque_items.try_insert(monomorph); } for monomorph in monomorphs.drain_typedefs() { self.typedefs.try_insert(monomorph); } for monomorph in monomorphs.drain_enums() { self.enums.try_insert(monomorph); } // Remove structs and opaque items that are generic self.opaque_items.filter(|x| x.generic_params.len() > 0); self.structs.filter(|x| x.generic_params.len() > 0); self.unions.filter(|x| x.generic_params.len() > 0); self.enums.filter(|x| x.generic_params.len() > 0); self.typedefs.filter(|x| x.generic_params.len() > 0); // Mangle the paths that remain self.unions .for_all_items_mut(|x| x.mangle_paths(&monomorphs)); self.structs .for_all_items_mut(|x| x.mangle_paths(&monomorphs)); self.enums .for_all_items_mut(|x| x.mangle_paths(&monomorphs)); self.typedefs .for_all_items_mut(|x| x.mangle_paths(&monomorphs)); for x in &mut self.functions { x.mangle_paths(&monomorphs); } } } cbindgen-0.12.1/src/bindgen/mangle.rs010066400017500001750000000070421360223554200156020ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::bindgen::ir::{Path, Type}; pub fn mangle_path(path: &Path, generic_values: &[Type]) -> Path { internal_mangle_path(path, generic_values, true) } pub fn mangle_name(name: &str, generic_values: &[Type]) -> String { internal_mangle_name(name, generic_values, true) } fn internal_mangle_path(path: &Path, generic_values: &[Type], last_in_parent: bool) -> Path { let name = path.name(); let mangled_name = internal_mangle_name(name, generic_values, last_in_parent); Path::new(mangled_name) } fn internal_mangle_name(name: &str, generic_values: &[Type], last_in_parent: bool) -> String { if generic_values.is_empty() { return name.to_owned(); } let mut mangled = name.to_owned(); mangled.push_str("_"); // < for (i, ty) in generic_values.iter().enumerate() { if i != 0 { mangled.push_str("__"); // , } let is_last = i == generic_values.len() - 1; match *ty { Type::Path(ref generic) => { mangled.push_str(&internal_mangle_name( generic.export_name(), generic.generics(), last_in_parent && is_last, )); } Type::Primitive(ref primitive) => { mangled.push_str(primitive.to_repr_rust()); } Type::MutRef(..) | Type::Ref(..) | Type::ConstPtr(..) | Type::Ptr(..) | Type::Array(..) | Type::FuncPtr(..) => { panic!("Unable to mangle generic parameter {:?} for '{}'", ty, name); } } // Skip writing the trailing '>' mangling when possible if is_last && !last_in_parent { mangled.push_str("___"); // > } } mangled } #[test] fn generics() { use crate::bindgen::ir::{GenericPath, PrimitiveType}; fn float() -> Type { Type::Primitive(PrimitiveType::Float) } fn path(path: &str) -> Type { generic_path(path, &vec![]) } fn generic_path(path: &str, generics: &[Type]) -> Type { let path = Path::new(path); let generic_path = GenericPath::new(path, generics.to_owned()); Type::Path(generic_path) } // Foo => Foo_f32 assert_eq!( mangle_path(&Path::new("Foo"), &vec![float()]), Path::new("Foo_f32") ); // Foo> => Foo_Bar_f32 assert_eq!( mangle_path(&Path::new("Foo"), &vec![generic_path("Bar", &[float()])]), Path::new("Foo_Bar_f32") ); // Foo => Foo_Bar assert_eq!( mangle_path(&Path::new("Foo"), &[path("Bar")]), Path::new("Foo_Bar") ); // Foo> => Foo_Bar_T assert_eq!( mangle_path(&Path::new("Foo"), &[generic_path("Bar", &[path("T")])]), Path::new("Foo_Bar_T") ); // Foo, E> => Foo_Bar_T_____E assert_eq!( mangle_path( &Path::new("Foo"), &[generic_path("Bar", &[path("T")]), path("E")] ), Path::new("Foo_Bar_T_____E") ); // Foo, Bar> => Foo_Bar_T_____Bar_E assert_eq!( mangle_path( &Path::new("Foo"), &[ generic_path("Bar", &[path("T")]), generic_path("Bar", &[path("E")]), ] ), Path::new("Foo_Bar_T_____Bar_E") ); } cbindgen-0.12.1/src/bindgen/mod.rs010064400017500001750000000034551356501061700151220ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// A helper macro for deriving deserialize for an enum to be used in toml-rs. /// This macro works be relying on an existing FromStr implementation for the /// desired type. macro_rules! deserialize_enum_str { ($name:ident) => { impl<'de> ::serde::Deserialize<'de> for $name { fn deserialize(deserializer: D) -> Result where D: ::serde::Deserializer<'de>, { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = $name; fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.write_str("$name") } fn visit_str(self, v: &str) -> Result<$name, E> where E: ::serde::de::Error, { match v.parse::<$name>() { Ok(v) => Ok(v), Err(m) => Err(E::custom(m)), } } } deserializer.deserialize_str(Visitor) } } }; } mod bindings; mod bitflags; mod builder; mod cargo; mod cdecl; mod config; mod declarationtyperesolver; mod dependencies; mod error; mod ir; mod library; mod mangle; mod monomorph; mod parser; mod rename; mod reserved; mod utilities; mod writer; #[allow(unused)] pub(crate) use self::cargo::*; pub use self::bindings::Bindings; pub use self::builder::Builder; pub use self::config::*; pub use self::error::Error; cbindgen-0.12.1/src/bindgen/monomorph.rs010066400017500001750000000067731360223554200163670ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::HashMap; use std::mem; use crate::bindgen::ir::{Enum, GenericPath, OpaqueItem, Path, Struct, Type, Typedef, Union}; #[derive(Default, Clone, Debug)] pub struct Monomorphs { replacements: HashMap, opaques: Vec, structs: Vec, unions: Vec, typedefs: Vec, enums: Vec, } impl Monomorphs { pub fn contains(&self, path: &GenericPath) -> bool { self.replacements.contains_key(path) } pub fn insert_struct(&mut self, generic: &Struct, monomorph: Struct, parameters: Vec) { let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements .insert(replacement_path, monomorph.path.clone()); self.structs.push(monomorph); } pub fn insert_enum(&mut self, generic: &Enum, monomorph: Enum, parameters: Vec) { let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements .insert(replacement_path, monomorph.path.clone()); self.enums.push(monomorph); } pub fn insert_union(&mut self, generic: &Union, monomorph: Union, parameters: Vec) { let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements .insert(replacement_path, monomorph.path.clone()); self.unions.push(monomorph); } pub fn insert_opaque( &mut self, generic: &OpaqueItem, monomorph: OpaqueItem, parameters: Vec, ) { let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements .insert(replacement_path, monomorph.path.clone()); self.opaques.push(monomorph); } pub fn insert_typedef(&mut self, generic: &Typedef, monomorph: Typedef, parameters: Vec) { let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements .insert(replacement_path, monomorph.path.clone()); self.typedefs.push(monomorph); } pub fn mangle_path(&self, path: &GenericPath) -> Option<&Path> { self.replacements.get(path) } pub fn drain_opaques(&mut self) -> Vec { mem::replace(&mut self.opaques, Vec::new()) } pub fn drain_structs(&mut self) -> Vec { mem::replace(&mut self.structs, Vec::new()) } pub fn drain_unions(&mut self) -> Vec { mem::replace(&mut self.unions, Vec::new()) } pub fn drain_typedefs(&mut self) -> Vec { mem::replace(&mut self.typedefs, Vec::new()) } pub fn drain_enums(&mut self) -> Vec { mem::replace(&mut self.enums, Vec::new()) } } cbindgen-0.12.1/src/bindgen/parser.rs010066400017500001750000000717511360223554200156430ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::Read; use std::path::{Path as FilePath, PathBuf as FilePathBuf}; use syn; use crate::bindgen::bitflags; use crate::bindgen::cargo::{Cargo, PackageRef}; use crate::bindgen::config::{Config, ParseConfig}; use crate::bindgen::error::Error; use crate::bindgen::ir::{ AnnotationSet, Cfg, Constant, Documentation, Enum, Function, GenericParams, ItemMap, OpaqueItem, Path, Static, Struct, Type, Typedef, Union, }; use crate::bindgen::utilities::{SynAbiHelpers, SynItemHelpers}; const STD_CRATES: &[&str] = &[ "std", "std_unicode", "alloc", "collections", "core", "proc_macro", ]; type ParseResult = Result; /// Parses a single rust source file, not following `mod` or `extern crate`. pub fn parse_src(src_file: &FilePath, config: &Config) -> ParseResult { let mod_name = src_file.file_stem().unwrap().to_str().unwrap(); let mut config = config.clone(); config.parse = ParseConfig { parse_deps: true, ..ParseConfig::default() }; let mut context = Parser { binding_crate_name: mod_name.to_owned(), config: &config, lib: None, parsed_crates: HashSet::new(), cache_src: HashMap::new(), cache_expanded_crate: HashMap::new(), cfg_stack: Vec::new(), out: Parse::new(), }; let pkg_ref = PackageRef { name: mod_name.to_owned(), version: None, }; context.parse_mod(&pkg_ref, src_file)?; Ok(context.out) } /// Recursively parses a rust library starting at the root crate's directory. /// /// Inside a crate, `mod` and `extern crate` declarations are followed /// and parsed. To find an external crate, the parser uses the `cargo metadata` /// command to find the location of dependencies. pub(crate) fn parse_lib(lib: Cargo, config: &Config) -> ParseResult { let mut context = Parser { binding_crate_name: lib.binding_crate_name().to_owned(), config, lib: Some(lib), parsed_crates: HashSet::new(), cache_src: HashMap::new(), cache_expanded_crate: HashMap::new(), cfg_stack: Vec::new(), out: Parse::new(), }; let binding_crate = context.lib.as_ref().unwrap().binding_crate_ref(); context.parse_crate(&binding_crate)?; Ok(context.out) } #[derive(Debug, Clone)] struct Parser<'a> { binding_crate_name: String, lib: Option, config: &'a Config, parsed_crates: HashSet, cache_src: HashMap>, cache_expanded_crate: HashMap>, cfg_stack: Vec, out: Parse, } impl<'a> Parser<'a> { fn should_parse_dependency(&self, pkg_name: &String) -> bool { if self.parsed_crates.contains(pkg_name) { return false; } if !self.config.parse.parse_deps { return false; } // Skip any whitelist or blacklist for expand if self.config.parse.expand.crates.contains(&pkg_name) { return true; } // If we have a whitelist, check it if let Some(ref include) = self.config.parse.include { if !include.contains(&pkg_name) { return false; } } // Check the blacklist !STD_CRATES.contains(&pkg_name.as_ref()) && !self.config.parse.exclude.contains(&pkg_name) } fn parse_crate(&mut self, pkg: &PackageRef) -> Result<(), Error> { assert!(self.lib.is_some()); self.parsed_crates.insert(pkg.name.clone()); // Check if we should use cargo expand for this crate if self.config.parse.expand.crates.contains(&pkg.name) { self.parse_expand_crate(pkg)?; } else { // Parse the crate before the dependencies otherwise the same-named idents we // want to generate bindings for would be replaced by the ones provided // by the first dependency containing it. let crate_src = self.lib.as_ref().unwrap().find_crate_src(pkg); match crate_src { Some(crate_src) => self.parse_mod(pkg, crate_src.as_path())?, None => { // This should be an error, but is common enough to just elicit a warning warn!( "Parsing crate `{}`: can't find lib.rs with `cargo metadata`.", pkg.name ); } } } for (dep_pkg, cfg) in self.lib.as_ref().unwrap().dependencies(&pkg) { if !self.should_parse_dependency(&dep_pkg.name) { continue; } if let Some(ref cfg) = cfg { self.cfg_stack.push(cfg.clone()); } self.parse_crate(&dep_pkg)?; if cfg.is_some() { self.cfg_stack.pop(); } } Ok(()) } fn parse_expand_crate(&mut self, pkg: &PackageRef) -> Result<(), Error> { assert!(self.lib.is_some()); // If you want to expand the crate you run cbindgen on you might end up in an endless // recursion if the cbindgen generation is triggered from build.rs. Hence don't run the // expansion if the build was already triggered by cbindgen. if std::env::var("_CBINDGEN_IS_RUNNING").is_ok() { return Ok(()); } let mod_parsed = { if !self.cache_expanded_crate.contains_key(&pkg.name) { let s = self .lib .as_ref() .unwrap() .expand_crate( pkg, self.config.parse.expand.all_features, self.config.parse.expand.default_features, &self.config.parse.expand.features, ) .map_err(|x| Error::CargoExpand(pkg.name.clone(), x))?; let i = syn::parse_file(&s).map_err(|x| Error::ParseSyntaxError { crate_name: pkg.name.clone(), src_path: "".to_owned(), error: x, })?; self.cache_expanded_crate.insert(pkg.name.clone(), i.items); } self.cache_expanded_crate.get(&pkg.name).unwrap().clone() }; self.process_expanded_mod(pkg, &mod_parsed) } fn process_expanded_mod(&mut self, pkg: &PackageRef, items: &[syn::Item]) -> Result<(), Error> { self.out.load_syn_crate_mod( &self.config, &self.binding_crate_name, &pkg.name, Cfg::join(&self.cfg_stack).as_ref(), items, ); for item in items { if item.has_test_attr() { continue; } if let syn::Item::Mod(ref item) = *item { let cfg = Cfg::load(&item.attrs); if let Some(ref cfg) = cfg { self.cfg_stack.push(cfg.clone()); } if let Some((_, ref inline_items)) = item.content { self.process_expanded_mod(pkg, inline_items)?; } else { unreachable!(); } if cfg.is_some() { self.cfg_stack.pop(); } } } Ok(()) } fn parse_mod(&mut self, pkg: &PackageRef, mod_path: &FilePath) -> Result<(), Error> { let mod_parsed = { let owned_mod_path = mod_path.to_path_buf(); if !self.cache_src.contains_key(&owned_mod_path) { let mut s = String::new(); let mut f = File::open(mod_path).map_err(|_| Error::ParseCannotOpenFile { crate_name: pkg.name.clone(), src_path: mod_path.to_str().unwrap().to_owned(), })?; f.read_to_string(&mut s) .map_err(|_| Error::ParseCannotOpenFile { crate_name: pkg.name.clone(), src_path: mod_path.to_str().unwrap().to_owned(), })?; let i = syn::parse_file(&s).map_err(|x| Error::ParseSyntaxError { crate_name: pkg.name.clone(), src_path: owned_mod_path.to_string_lossy().into(), error: x, })?; self.cache_src.insert(owned_mod_path.clone(), i.items); } self.cache_src.get(&owned_mod_path).unwrap().clone() }; let mod_dir = mod_path.parent().unwrap(); self.process_mod(pkg, mod_dir, &mod_parsed) } fn process_mod( &mut self, pkg: &PackageRef, mod_dir: &FilePath, items: &[syn::Item], ) -> Result<(), Error> { self.out.load_syn_crate_mod( &self.config, &self.binding_crate_name, &pkg.name, Cfg::join(&self.cfg_stack).as_ref(), items, ); for item in items { if item.has_test_attr() { continue; } if let syn::Item::Mod(ref item) = *item { let next_mod_name = item.ident.to_string(); let cfg = Cfg::load(&item.attrs); if let Some(ref cfg) = cfg { self.cfg_stack.push(cfg.clone()); } if let Some((_, ref inline_items)) = item.content { self.process_mod(pkg, &mod_dir.join(&next_mod_name), inline_items)?; } else { let next_mod_path1 = mod_dir.join(next_mod_name.clone() + ".rs"); let next_mod_path2 = mod_dir.join(next_mod_name.clone()).join("mod.rs"); if next_mod_path1.exists() { self.parse_mod(pkg, next_mod_path1.as_path())?; } else if next_mod_path2.exists() { self.parse_mod(pkg, next_mod_path2.as_path())?; } else { // Last chance to find a module path let mut path_attr_found = false; for attr in &item.attrs { match attr.parse_meta() { Ok(syn::Meta::NameValue(syn::MetaNameValue { path, lit, .. })) => match lit { syn::Lit::Str(ref path_lit) if path.is_ident("path") => { path_attr_found = true; self.parse_mod(pkg, &mod_dir.join(path_lit.value()))?; break; } _ => (), }, _ => (), } } // This should be an error, but it's common enough to // just elicit a warning if !path_attr_found { warn!( "Parsing crate `{}`: can't find mod {}`.", pkg.name, next_mod_name ); } } } if cfg.is_some() { self.cfg_stack.pop(); } } } Ok(()) } } #[derive(Debug, Clone)] pub struct Parse { pub constants: ItemMap, pub globals: ItemMap, pub enums: ItemMap, pub structs: ItemMap, pub unions: ItemMap, pub opaque_items: ItemMap, pub typedefs: ItemMap, pub functions: Vec, } impl Parse { pub fn new() -> Parse { Parse { constants: ItemMap::new(), globals: ItemMap::new(), enums: ItemMap::new(), structs: ItemMap::new(), unions: ItemMap::new(), opaque_items: ItemMap::new(), typedefs: ItemMap::new(), functions: Vec::new(), } } pub fn add_std_types(&mut self) { let mut add_opaque = |path: &str, generic_params: Vec<&str>| { let path = Path::new(path); let generic_params: Vec<_> = generic_params.into_iter().map(Path::new).collect(); self.opaque_items.try_insert(OpaqueItem::new( path, GenericParams(generic_params), None, AnnotationSet::new(), Documentation::none(), )) }; add_opaque("String", vec![]); add_opaque("Box", vec!["T"]); add_opaque("Rc", vec!["T"]); add_opaque("Arc", vec!["T"]); add_opaque("Result", vec!["T", "E"]); add_opaque("Option", vec!["T"]); add_opaque("NonNull", vec!["T"]); add_opaque("Vec", vec!["T"]); add_opaque("HashMap", vec!["K", "V"]); add_opaque("BTreeMap", vec!["K", "V"]); add_opaque("HashSet", vec!["T"]); add_opaque("BTreeSet", vec!["T"]); add_opaque("LinkedList", vec!["T"]); add_opaque("VecDeque", vec!["T"]); } pub fn extend_with(&mut self, other: &Parse) { self.constants.extend_with(&other.constants); self.globals.extend_with(&other.globals); self.enums.extend_with(&other.enums); self.structs.extend_with(&other.structs); self.unions.extend_with(&other.unions); self.opaque_items.extend_with(&other.opaque_items); self.typedefs.extend_with(&other.typedefs); self.functions.extend_from_slice(&other.functions); } pub fn load_syn_crate_mod( &mut self, config: &Config, binding_crate_name: &str, crate_name: &str, mod_cfg: Option<&Cfg>, items: &[syn::Item], ) { let mut impls_with_assoc_consts = Vec::new(); for item in items { if item.has_test_attr() { continue; } match item { syn::Item::ForeignMod(ref item) => { self.load_syn_foreign_mod( config, binding_crate_name, crate_name, mod_cfg, item, ); } syn::Item::Fn(ref item) => { self.load_syn_fn(config, binding_crate_name, crate_name, mod_cfg, item); } syn::Item::Const(ref item) => { self.load_syn_const(config, binding_crate_name, crate_name, mod_cfg, item); } syn::Item::Static(ref item) => { self.load_syn_static(config, binding_crate_name, crate_name, mod_cfg, item); } syn::Item::Struct(ref item) => { self.load_syn_struct(config, crate_name, mod_cfg, item); } syn::Item::Union(ref item) => { self.load_syn_union(config, crate_name, mod_cfg, item); } syn::Item::Enum(ref item) => { self.load_syn_enum(crate_name, mod_cfg, item); } syn::Item::Type(ref item) => { self.load_syn_ty(crate_name, mod_cfg, item); } syn::Item::Impl(ref item_impl) => { let has_assoc_const = item_impl.items.iter().any(|item| match item { syn::ImplItem::Const(_) => true, _ => false, }); if has_assoc_const { impls_with_assoc_consts.push(item_impl); } } syn::Item::Macro(ref item) => { self.load_builtin_macro(config, crate_name, mod_cfg, item) } _ => {} } } for item_impl in impls_with_assoc_consts { self.load_syn_assoc_consts_from_impl(crate_name, mod_cfg, item_impl) } } fn load_syn_assoc_consts_from_impl( &mut self, crate_name: &str, mod_cfg: Option<&Cfg>, item_impl: &syn::ItemImpl, ) { let associated_constants = item_impl.items.iter().filter_map(|item| match item { syn::ImplItem::Const(ref associated_constant) => Some(associated_constant), _ => None, }); self.load_syn_assoc_consts( crate_name, mod_cfg, &item_impl.self_ty, associated_constants, ); } /// Enters a `extern "C" { }` declaration and loads function declarations. fn load_syn_foreign_mod( &mut self, config: &Config, binding_crate_name: &str, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemForeignMod, ) { if !item.abi.is_c() { info!("Skip {} - (extern block must be extern C).", crate_name); return; } for foreign_item in &item.items { if let syn::ForeignItem::Fn(ref function) = *foreign_item { if !config .parse .should_generate_top_level_item(crate_name, binding_crate_name) { info!( "Skip {}::{} - (fn's outside of the binding crate are not used).", crate_name, &function.sig.ident ); return; } let path = Path::new(function.sig.ident.to_string()); match Function::load(path, &function.sig, true, &function.attrs, mod_cfg) { Ok(func) => { info!("Take {}::{}.", crate_name, &function.sig.ident); self.functions.push(func); } Err(msg) => { error!( "Cannot use fn {}::{} ({}).", crate_name, &function.sig.ident, msg ); } } } } } /// Loads a `fn` declaration fn load_syn_fn( &mut self, config: &Config, binding_crate_name: &str, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemFn, ) { if !config .parse .should_generate_top_level_item(crate_name, binding_crate_name) { info!( "Skip {}::{} - (fn's outside of the binding crate are not used).", crate_name, &item.sig.ident ); return; } if let syn::Visibility::Public(_) = item.vis { if item.is_no_mangle() && (item.sig.abi.is_omitted() || item.sig.abi.is_c()) { let path = Path::new(item.sig.ident.to_string()); match Function::load(path, &item.sig, false, &item.attrs, mod_cfg) { Ok(func) => { info!("Take {}::{}.", crate_name, &item.sig.ident); self.functions.push(func); } Err(msg) => { error!( "Cannot use fn {}::{} ({}).", crate_name, &item.sig.ident, msg ); } } return; } } // TODO if let syn::Visibility::Public(_) = item.vis { } else { warn!("Skip {}::{} - (not `pub`).", crate_name, &item.sig.ident); } if (item.sig.abi.is_omitted() || item.sig.abi.is_c()) && !item.is_no_mangle() { warn!( "Skip {}::{} - (`extern` but not `no_mangle`).", crate_name, &item.sig.ident ); } if item.sig.abi.is_some() && !(item.sig.abi.is_omitted() || item.sig.abi.is_c()) { warn!( "Skip {}::{} - (non `extern \"C\"`).", crate_name, &item.sig.ident ); } } /// Loads associated `const` declarations fn load_syn_assoc_consts<'a, I>( &mut self, crate_name: &str, mod_cfg: Option<&Cfg>, impl_ty: &syn::Type, items: I, ) where I: IntoIterator, { let ty = match Type::load(impl_ty) { Ok(ty) => ty, Err(e) => { warn!("Skipping associated constants for {:?}: {:?}", impl_ty, e); return; } }; if ty.is_none() { return; } let impl_path = ty.unwrap().get_root_path().unwrap(); for item in items.into_iter() { if let syn::Visibility::Public(_) = item.vis { } else { warn!("Skip {}::{} - (not `pub`).", crate_name, &item.ident); return; } let path = Path::new(item.ident.to_string()); match Constant::load( path, mod_cfg, &item.ty, &item.expr, &item.attrs, Some(impl_path.clone()), ) { Ok(constant) => { info!("Take {}::{}::{}.", crate_name, impl_path, &item.ident); let mut any = false; self.structs.for_items_mut(&impl_path, |item| { any = true; item.add_associated_constant(constant.clone()); }); // Handle associated constants to other item types that are // not structs like enums or such as regular constants. if !any && !self.constants.try_insert(constant) { error!( "Conflicting name for constant {}::{}::{}.", crate_name, impl_path, &item.ident, ); } } Err(msg) => { warn!("Skip {}::{} - ({})", crate_name, &item.ident, msg); } } } } /// Loads a `const` declaration fn load_syn_const( &mut self, config: &Config, binding_crate_name: &str, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemConst, ) { if !config .parse .should_generate_top_level_item(crate_name, binding_crate_name) { info!( "Skip {}::{} - (const's outside of the binding crate are not used).", crate_name, &item.ident ); return; } if let syn::Visibility::Public(_) = item.vis { } else { warn!("Skip {}::{} - (not `pub`).", crate_name, &item.ident); return; } let path = Path::new(item.ident.to_string()); match Constant::load(path, mod_cfg, &item.ty, &item.expr, &item.attrs, None) { Ok(constant) => { info!("Take {}::{}.", crate_name, &item.ident); let full_name = constant.path.clone(); if !self.constants.try_insert(constant) { error!("Conflicting name for constant {}", full_name); } } Err(msg) => { warn!("Skip {}::{} - ({})", crate_name, &item.ident, msg); } } } /// Loads a `static` declaration fn load_syn_static( &mut self, config: &Config, binding_crate_name: &str, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemStatic, ) { if !config .parse .should_generate_top_level_item(crate_name, binding_crate_name) { info!( "Skip {}::{} - (static's outside of the binding crate are not used).", crate_name, &item.ident ); return; } if let syn::Visibility::Public(_) = item.vis { if item.is_no_mangle() { match Static::load(item, mod_cfg) { Ok(constant) => { info!("Take {}::{}.", crate_name, &item.ident); self.globals.try_insert(constant); } Err(msg) => { warn!("Skip {}::{} - ({})", crate_name, &item.ident, msg); } } } } // TODO if let syn::Visibility::Public(_) = item.vis { } else { warn!("Skip {}::{} - (not `pub`).", crate_name, &item.ident); } if !item.is_no_mangle() { warn!("Skip {}::{} - (not `no_mangle`).", crate_name, &item.ident); } } /// Loads a `struct` declaration fn load_syn_struct( &mut self, config: &Config, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemStruct, ) { match Struct::load(&config.layout, item, mod_cfg) { Ok(st) => { info!("Take {}::{}.", crate_name, &item.ident); self.structs.try_insert(st); } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); let path = Path::new(item.ident.to_string()); self.opaque_items.try_insert( OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), ); } } } /// Loads a `union` declaration fn load_syn_union( &mut self, config: &Config, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemUnion, ) { match Union::load(&config.layout, item, mod_cfg) { Ok(st) => { info!("Take {}::{}.", crate_name, &item.ident); self.unions.try_insert(st); } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); let path = Path::new(item.ident.to_string()); self.opaque_items.try_insert( OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), ); } } } /// Loads a `enum` declaration fn load_syn_enum(&mut self, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemEnum) { if item.generics.lifetimes().count() > 0 { info!( "Skip {}::{} - (has generics or lifetimes or where bounds).", crate_name, &item.ident ); return; } match Enum::load(item, mod_cfg) { Ok(en) => { info!("Take {}::{}.", crate_name, &item.ident); self.enums.try_insert(en); } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); let path = Path::new(item.ident.to_string()); self.opaque_items.try_insert( OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), ); } } } /// Loads a `type` declaration fn load_syn_ty(&mut self, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemType) { match Typedef::load(item, mod_cfg) { Ok(st) => { info!("Take {}::{}.", crate_name, &item.ident); self.typedefs.try_insert(st); } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); let path = Path::new(item.ident.to_string()); self.opaque_items.try_insert( OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), ); } } } fn load_builtin_macro( &mut self, config: &Config, crate_name: &str, mod_cfg: Option<&Cfg>, item: &syn::ItemMacro, ) { let name = match item.mac.path.segments.last() { Some(ref n) => n.ident.to_string(), None => return, }; if name != "bitflags" || !config.macro_expansion.bitflags { return; } let bitflags = match bitflags::parse(item.mac.tokens.clone()) { Ok(b) => b, Err(e) => { warn!("Failed to parse bitflags invocation: {:?}", e); return; } }; let (struct_, impl_) = bitflags.expand(); self.load_syn_struct(config, crate_name, mod_cfg, &struct_); // We know that the expansion will only reference `struct_`, so it's // fine to just do it here instead of deferring it like we do with the // other calls to this function. self.load_syn_assoc_consts_from_impl(crate_name, mod_cfg, &impl_); } } cbindgen-0.12.1/src/bindgen/rename.rs010066400017500001750000000232631360223554200156110ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::str::FromStr; use crate::bindgen::ir::{Enum, Item}; /// The type of identifier to be renamed. #[derive(Debug, Clone, Copy)] pub enum IdentifierType<'a> { StructMember, EnumVariant(&'a Enum), FunctionArg, Enum, } impl<'a> IdentifierType<'a> { fn to_str(&'a self) -> &'static str { match *self { IdentifierType::StructMember => "m", IdentifierType::EnumVariant(..) => "", IdentifierType::FunctionArg => "a", IdentifierType::Enum => "", } } } /// A rule to apply to an identifier when generating bindings. #[derive(Debug, Clone, Copy)] pub enum RenameRule { /// Do not apply any renaming. The default. None, /// Converts the identifier to PascalCase and adds a context dependent prefix GeckoCase, /// Converts the identifier to lower case. LowerCase, /// Converts the identifier to upper case. UpperCase, /// Converts the identifier to PascalCase. PascalCase, /// Converts the identifier to camelCase. CamelCase, /// Converts the identifier to snake_case. SnakeCase, /// Converts the identifier to SCREAMING_SNAKE_CASE. ScreamingSnakeCase, /// Converts the identifier to SCREAMING_SNAKE_CASE and prefixes enum variants /// with the enum name. QualifiedScreamingSnakeCase, } impl RenameRule { /// Applies the rename rule to a string that is formatted in PascalCase. pub fn apply_to_pascal_case(self, text: &str, context: IdentifierType) -> String { if text.is_empty() { return String::new(); } match self { RenameRule::None => String::from(text), RenameRule::GeckoCase => context.to_str().to_owned() + text, RenameRule::LowerCase => text.to_lowercase(), RenameRule::UpperCase => text.to_uppercase(), RenameRule::PascalCase => text.to_owned(), RenameRule::CamelCase => text[..1].to_lowercase() + &text[1..], RenameRule::SnakeCase => { // Do not add additional `_` if the string already contains `_` e.g. `__Field` // Do not split consecutive capital letters let mut result = String::new(); let mut add_separator = true; let mut prev_uppercase = false; for (i, c) in text.char_indices() { if c == '_' { add_separator = false; prev_uppercase = false; } if c.is_uppercase() { if i != 0 && add_separator && !prev_uppercase { result.push_str("_"); } else { add_separator = true; } prev_uppercase = true; } else { prev_uppercase = false; } for x in c.to_lowercase() { result.push(x); } } result } RenameRule::ScreamingSnakeCase => { // Same as SnakeCase code above, but uses to_uppercase let mut result = String::new(); let mut add_separator = true; let mut prev_uppercase = false; for (i, c) in text.char_indices() { if c == '_' { add_separator = false; prev_uppercase = false; } if c.is_uppercase() { if i != 0 && add_separator && !prev_uppercase { result.push_str("_"); } else { add_separator = true; } prev_uppercase = true; } else { prev_uppercase = false; } for x in c.to_uppercase() { result.push(x); } } result } RenameRule::QualifiedScreamingSnakeCase => { let mut result = String::new(); if let IdentifierType::EnumVariant(e) = context { if let RenameRule::QualifiedScreamingSnakeCase = self { result.push_str( &RenameRule::ScreamingSnakeCase .apply_to_pascal_case(e.path().name(), IdentifierType::Enum), ); result.push_str("_"); } } result .push_str(&RenameRule::ScreamingSnakeCase.apply_to_pascal_case(&text, context)); result } } } /// Applies the rename rule to a string that is formatted in snake_case. pub fn apply_to_snake_case(self, mut text: &str, context: IdentifierType) -> String { if text.is_empty() { return String::new(); } match self { RenameRule::None => String::from(text), RenameRule::GeckoCase => { if &text[..1] == "_" { text = &text[1..]; } context.to_str().to_owned() + &RenameRule::PascalCase.apply_to_snake_case(text, context) } RenameRule::LowerCase => text.to_lowercase(), RenameRule::UpperCase => text.to_uppercase(), RenameRule::PascalCase => { let mut result = String::new(); let mut is_uppercase = true; for c in text.chars() { if c == '_' { is_uppercase = true; continue; } if is_uppercase { for x in c.to_uppercase() { result.push(x); } is_uppercase = false; } else { result.push(c); } } result } RenameRule::CamelCase => { // Same as PascalCase code above, but is_uppercase = false to start let mut result = String::new(); let mut is_uppercase = false; for c in text.chars() { if c == '_' { is_uppercase = true; continue; } if is_uppercase { for x in c.to_uppercase() { result.push(x); } is_uppercase = false; } else { result.push(c); } } result } RenameRule::SnakeCase => text.to_owned(), RenameRule::ScreamingSnakeCase => text.to_owned().to_uppercase(), RenameRule::QualifiedScreamingSnakeCase => { let mut result = String::new(); if let IdentifierType::EnumVariant(e) = context { if let RenameRule::QualifiedScreamingSnakeCase = self { result.push_str( &RenameRule::ScreamingSnakeCase .apply_to_snake_case(e.path().name(), IdentifierType::Enum), ); result.push_str("_"); } } result .push_str(&RenameRule::ScreamingSnakeCase.apply_to_snake_case(&text, context)); result } } } } impl Default for RenameRule { fn default() -> RenameRule { RenameRule::None } } impl FromStr for RenameRule { type Err = String; fn from_str(s: &str) -> Result { match s { "none" => Ok(RenameRule::None), "None" => Ok(RenameRule::None), "mGeckoCase" => Ok(RenameRule::GeckoCase), "GeckoCase" => Ok(RenameRule::GeckoCase), "gecko_case" => Ok(RenameRule::GeckoCase), "lowercase" => Ok(RenameRule::LowerCase), "LowerCase" => Ok(RenameRule::LowerCase), "lower_case" => Ok(RenameRule::LowerCase), "UPPERCASE" => Ok(RenameRule::UpperCase), "UpperCase" => Ok(RenameRule::UpperCase), "upper_case" => Ok(RenameRule::UpperCase), "PascalCase" => Ok(RenameRule::PascalCase), "pascal_case" => Ok(RenameRule::PascalCase), "camelCase" => Ok(RenameRule::CamelCase), "CamelCase" => Ok(RenameRule::CamelCase), "camel_case" => Ok(RenameRule::CamelCase), "snake_case" => Ok(RenameRule::SnakeCase), "SnakeCase" => Ok(RenameRule::SnakeCase), "SCREAMING_SNAKE_CASE" => Ok(RenameRule::ScreamingSnakeCase), "ScreamingSnakeCase" => Ok(RenameRule::ScreamingSnakeCase), "screaming_snake_case" => Ok(RenameRule::ScreamingSnakeCase), "QUALIFIED_SCREAMING_SNAKE_CASE" => Ok(RenameRule::QualifiedScreamingSnakeCase), "QualifiedScreamingSnakeCase" => Ok(RenameRule::QualifiedScreamingSnakeCase), "qualified_screaming_snake_case" => Ok(RenameRule::QualifiedScreamingSnakeCase), _ => Err(format!("Unrecognized RenameRule: '{}'.", s)), } } } deserialize_enum_str!(RenameRule); cbindgen-0.12.1/src/bindgen/reserved.rs010064400017500001750000000031701356501061700161540ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// Taken from `https://en.cppreference.com/w/cpp/keyword` /// Some experimental keywords were filtered out and the resulting list was /// sorted using a rust program. const RESERVED_KEYWORDS: &[&str] = &[ "alignas", "alignof", "auto", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "char8_t", "class", "const", "const_cast", "consteval", "constexpr", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "nullptr", "operator", "private", "protected", "public", "register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", ]; pub fn escape(rust_identifier: &mut String) { if RESERVED_KEYWORDS .binary_search(&rust_identifier.as_ref()) .is_ok() { rust_identifier.push('_'); } } cbindgen-0.12.1/src/bindgen/utilities.rs010064400017500001750000000205731356501061700163560ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![allow(clippy::redundant_closure_call)] use syn; pub trait IterHelpers: Iterator { fn try_skip_map(&mut self, f: F) -> Result, E> where F: FnMut(&Self::Item) -> Result, E>; } impl IterHelpers for I where I: Iterator, { fn try_skip_map(&mut self, mut f: F) -> Result, E> where F: FnMut(&Self::Item) -> Result, E>, { let mut out = Vec::new(); while let Some(item) = self.next() { if let Some(x) = f(&item)? { out.push(x); } } Ok(out) } } pub fn find_first_some(slice: &[Option]) -> Option<&T> { for x in slice { if let Some(ref x) = *x { return Some(x); } } None } pub trait SynItemHelpers { /// Searches for attributes like `#[test]`. /// Example: /// - `item.has_attr_word("test")` => `#[test]` fn has_attr_word(&self, name: &str) -> bool; /// Searches for attributes like `#[cfg(test)]`. /// Example: /// - `item.has_attr_list("cfg", &["test"])` => `#[cfg(test)]` fn has_attr_list(&self, name: &str, args: &[&str]) -> bool; /// Searches for attributes like `#[feature = "std"]`. /// Example: /// - `item.has_attr_name_value("feature", "std")` => `#[feature = "std"]` fn has_attr_name_value(&self, name: &str, value: &str) -> bool; fn is_no_mangle(&self) -> bool { self.has_attr_word("no_mangle") } /// Searches for attributes `#[test]` and/or `#[cfg(test)]`. fn has_test_attr(&self) -> bool { self.has_attr_list("cfg", &["test"]) || self.has_attr_word("test") } } macro_rules! syn_item_match_helper { ($s:ident => has_attrs: |$i:ident| $a:block, otherwise: || $b:block) => { match *$s { syn::Item::Const(ref item) => (|$i: &syn::ItemConst| $a)(item), syn::Item::Enum(ref item) => (|$i: &syn::ItemEnum| $a)(item), syn::Item::ExternCrate(ref item) => (|$i: &syn::ItemExternCrate| $a)(item), syn::Item::Fn(ref item) => (|$i: &syn::ItemFn| $a)(item), syn::Item::ForeignMod(ref item) => (|$i: &syn::ItemForeignMod| $a)(item), syn::Item::Impl(ref item) => (|$i: &syn::ItemImpl| $a)(item), syn::Item::Macro(ref item) => (|$i: &syn::ItemMacro| $a)(item), syn::Item::Macro2(ref item) => (|$i: &syn::ItemMacro2| $a)(item), syn::Item::Mod(ref item) => (|$i: &syn::ItemMod| $a)(item), syn::Item::Static(ref item) => (|$i: &syn::ItemStatic| $a)(item), syn::Item::Struct(ref item) => (|$i: &syn::ItemStruct| $a)(item), syn::Item::Trait(ref item) => (|$i: &syn::ItemTrait| $a)(item), syn::Item::Type(ref item) => (|$i: &syn::ItemType| $a)(item), syn::Item::Union(ref item) => (|$i: &syn::ItemUnion| $a)(item), syn::Item::Use(ref item) => (|$i: &syn::ItemUse| $a)(item), syn::Item::TraitAlias(ref item) => (|$i: &syn::ItemTraitAlias| $a)(item), syn::Item::Verbatim(_) => (|| $b)(), _ => panic!("Unhandled syn::Item: {:?}", $s), } }; } impl SynItemHelpers for syn::Item { fn has_attr_word(&self, name: &str) -> bool { syn_item_match_helper!(self => has_attrs: |item| { item.has_attr_word(name) }, otherwise: || { false } ) } fn has_attr_list(&self, name: &str, args: &[&str]) -> bool { syn_item_match_helper!(self => has_attrs: |item| { item.has_attr_list(name, args) }, otherwise: || { false } ) } fn has_attr_name_value(&self, name: &str, value: &str) -> bool { syn_item_match_helper!(self => has_attrs: |item| { item.has_attr_name_value(name, value) }, otherwise: || { false } ) } } macro_rules! impl_syn_item_helper { ($t:ty) => { impl SynItemHelpers for $t { fn has_attr_word(&self, name: &str) -> bool { self.attrs.has_attr_word(name) } fn has_attr_list(&self, name: &str, args: &[&str]) -> bool { self.attrs.has_attr_list(name, args) } fn has_attr_name_value(&self, name: &str, value: &str) -> bool { self.attrs.has_attr_name_value(name, value) } } }; } impl_syn_item_helper!(syn::ItemExternCrate); impl_syn_item_helper!(syn::ItemUse); impl_syn_item_helper!(syn::ItemStatic); impl_syn_item_helper!(syn::ItemConst); impl_syn_item_helper!(syn::ItemFn); impl_syn_item_helper!(syn::ItemMod); impl_syn_item_helper!(syn::ItemForeignMod); impl_syn_item_helper!(syn::ItemType); impl_syn_item_helper!(syn::ItemStruct); impl_syn_item_helper!(syn::ItemEnum); impl_syn_item_helper!(syn::ItemUnion); impl_syn_item_helper!(syn::ItemTrait); impl_syn_item_helper!(syn::ItemImpl); impl_syn_item_helper!(syn::ItemMacro); impl_syn_item_helper!(syn::ItemMacro2); impl_syn_item_helper!(syn::ItemTraitAlias); /// Helper function for accessing Abi information pub trait SynAbiHelpers { fn is_c(&self) -> bool; fn is_omitted(&self) -> bool; } impl SynAbiHelpers for Option { fn is_c(&self) -> bool { if let Some(ref abi) = *self { if let Some(ref lit_string) = abi.name { return lit_string.value() == String::from("C"); } } false } fn is_omitted(&self) -> bool { if let Some(ref abi) = *self { abi.name.is_none() } else { false } } } impl SynAbiHelpers for syn::Abi { fn is_c(&self) -> bool { if let Some(ref lit_string) = self.name { lit_string.value() == String::from("C") } else { false } } fn is_omitted(&self) -> bool { self.name.is_none() } } pub trait SynAttributeHelpers { fn get_comment_lines(&self) -> Vec; fn has_attr_word(&self, name: &str) -> bool; fn has_attr_list(&self, name: &str, args: &[&str]) -> bool; fn has_attr_name_value(&self, name: &str, value: &str) -> bool; } impl SynAttributeHelpers for [syn::Attribute] { fn has_attr_word(&self, name: &str) -> bool { self.iter().filter_map(|x| x.parse_meta().ok()).any(|attr| { if let syn::Meta::Path(ref path) = attr { path.is_ident(name) } else { false } }) } fn has_attr_list(&self, name: &str, args: &[&str]) -> bool { self.iter().filter_map(|x| x.parse_meta().ok()).any(|attr| { if let syn::Meta::List(syn::MetaList { path, nested, .. }) = attr { if !path.is_ident(name) { return false; } args.iter().all(|arg| { nested.iter().any(|nested_meta| { if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = nested_meta { path.is_ident(arg) } else { false } }) }) } else { false } }) } fn has_attr_name_value(&self, name: &str, value: &str) -> bool { self.iter().filter_map(|x| x.parse_meta().ok()).any(|attr| { if let syn::Meta::NameValue(syn::MetaNameValue { path, lit, .. }) = attr { if let syn::Lit::Str(lit) = lit { path.is_ident(name) && (&lit.value() == value) } else { false } } else { false } }) } fn get_comment_lines(&self) -> Vec { let mut comment = Vec::new(); for attr in self { if attr.style == syn::AttrStyle::Outer { if let Ok(syn::Meta::NameValue(syn::MetaNameValue { path, lit: syn::Lit::Str(content), .. })) = attr.parse_meta() { if path.is_ident("doc") { let text = content.value().trim_end().to_owned(); comment.push(text); } } } } comment } } cbindgen-0.12.1/src/bindgen/writer.rs010066400017500001750000000144461360223554200156610ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::cmp; use std::io; use std::io::Write; use crate::bindgen::config::{Braces, Config}; use crate::bindgen::Bindings; /// A type of way to format a list. pub enum ListType<'a> { /// Join each adjacent item with a str. Join(&'a str), /// End each item with a str. Cap(&'a str), } /// An empty file used for creating a null source writer and measuring line /// metrics for various code layouts. pub struct NullFile; impl Write for NullFile { fn write(&mut self, buf: &[u8]) -> io::Result { Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } /// A utility wrapper to write unbuffered data and correctly adjust positions. struct InnerWriter<'a, 'b: 'a, F: 'a + Write>(&'a mut SourceWriter<'b, F>); impl<'a, 'b, F: Write> Write for InnerWriter<'a, 'b, F> { fn write(&mut self, buf: &[u8]) -> io::Result { let writer = &mut self.0; if !writer.line_started { for _ in 0..writer.spaces() { write!(writer.out, " ").unwrap(); } writer.line_started = true; writer.line_length += writer.spaces(); } let written = writer.out.write(buf)?; writer.line_length += written; writer.max_line_length = cmp::max(writer.max_line_length, writer.line_length); Ok(written) } fn flush(&mut self) -> io::Result<()> { self.0.out.flush() } } /// A utility writer for generating code easier. pub struct SourceWriter<'a, F: Write> { out: F, bindings: &'a Bindings, spaces: Vec, line_started: bool, line_length: usize, line_number: usize, max_line_length: usize, } pub type MeasureWriter<'a> = SourceWriter<'a, NullFile>; impl<'a, F: Write> SourceWriter<'a, F> { pub fn new(out: F, bindings: &'a Bindings) -> Self { SourceWriter { out, bindings, spaces: vec![0], line_started: false, line_length: 0, line_number: 1, max_line_length: 0, } } pub fn bindings(&self) -> &Bindings { &self.bindings } /// Takes a function that writes source and returns the maximum line length /// written. pub fn measure(&self, func: T) -> usize where T: Fn(&mut MeasureWriter), { let mut measurer = SourceWriter { out: NullFile, bindings: self.bindings, spaces: self.spaces.clone(), line_started: self.line_started, line_length: self.line_length, line_number: self.line_number, max_line_length: self.line_length, }; func(&mut measurer); measurer.max_line_length } fn spaces(&self) -> usize { *self.spaces.last().unwrap() } pub fn push_set_spaces(&mut self, spaces: usize) { self.spaces.push(spaces); } pub fn line_length_for_align(&self) -> usize { if self.line_started { self.line_length } else { self.line_length + self.spaces() } } pub fn push_tab(&mut self) { let spaces = self.spaces() - (self.spaces() % self.bindings.config.tab_width) + self.bindings.config.tab_width; self.spaces.push(spaces); } pub fn pop_tab(&mut self) { assert!(!self.spaces.is_empty()); self.spaces.pop(); } pub fn new_line(&mut self) { writeln!(self.out).unwrap(); self.line_started = false; self.line_length = 0; self.line_number += 1; } pub fn new_line_if_not_start(&mut self) { if self.line_number != 1 { self.new_line(); } } pub fn open_brace(&mut self) { match self.bindings.config.braces { Braces::SameLine => { self.write(" {"); self.push_tab(); self.new_line(); } Braces::NextLine => { self.new_line(); self.write("{"); self.push_tab(); self.new_line(); } } } pub fn close_brace(&mut self, semicolon: bool) { self.pop_tab(); self.new_line(); if semicolon { self.write("};"); } else { self.write("}"); } } pub fn write(&mut self, text: &'static str) { write!(self, "{}", text); } pub fn write_raw_block(&mut self, block: &str) { self.new_line(); self.line_started = true; write!(self, "{}", block); } pub fn write_fmt(&mut self, fmt: ::std::fmt::Arguments) { InnerWriter(self).write_fmt(fmt).unwrap(); } pub fn write_horizontal_source_list<'b, S: Source>( &mut self, items: &[S], list_type: ListType<'b>, ) { for (i, ref item) in items.iter().enumerate() { item.write(&self.bindings.config, self); match list_type { ListType::Join(text) => { if i != items.len() - 1 { write!(self, "{}", text); } } ListType::Cap(text) => { write!(self, "{}", text); } } } } pub fn write_vertical_source_list<'b, S: Source>( &mut self, items: &[S], list_type: ListType<'b>, ) { let align_length = self.line_length_for_align(); self.push_set_spaces(align_length); for (i, ref item) in items.iter().enumerate() { item.write(&self.bindings.config, self); match list_type { ListType::Join(text) => { if i != items.len() - 1 { write!(self, "{}", text); } } ListType::Cap(text) => { write!(self, "{}", text); } } if i != items.len() - 1 { self.new_line(); } } self.pop_tab(); } } pub trait Source { fn write(&self, config: &Config, _: &mut SourceWriter); } cbindgen-0.12.1/src/lib.rs010066400017500001750000000021031360223554200134700ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[macro_use] extern crate log; extern crate proc_macro2; #[macro_use] extern crate serde; extern crate serde_json; #[macro_use] extern crate quote; #[macro_use] extern crate syn; extern crate toml; mod bindgen; pub use crate::bindgen::*; use std::path::Path; /// A utility function for build scripts to generate bindings for a crate, using /// a `cbindgen.toml` if it exists. pub fn generate>(crate_dir: P) -> Result { let config = Config::from_root_or_default(crate_dir.as_ref()); generate_with_config(crate_dir, config) } /// A utility function for build scripts to generate bindings for a crate with a /// custom config. pub fn generate_with_config>( crate_dir: P, config: Config, ) -> Result { Builder::new() .with_config(config) .with_crate(crate_dir) .generate() } cbindgen-0.12.1/src/logging.rs010064400017500001750000000050701356501061700143560ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::io; use std::io::Write; use log; use log::*; pub struct TraceLogger; pub struct WarnLogger; pub struct InfoLogger; pub struct ErrorLogger; impl TraceLogger { pub fn init() -> Result<(), SetLoggerError> { log::set_logger(&InfoLogger)?; log::set_max_level(LevelFilter::Trace); Ok(()) } } impl log::Log for TraceLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Trace } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { writeln!(io::stderr(), "{}: {}", record.level(), record.args()).unwrap(); } } fn flush(&self) { io::stderr().flush().unwrap(); } } impl WarnLogger { pub fn init() -> Result<(), SetLoggerError> { log::set_logger(&InfoLogger)?; log::set_max_level(LevelFilter::Warn); Ok(()) } } impl log::Log for WarnLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Warn } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { writeln!(io::stderr(), "{}: {}", record.level(), record.args()).unwrap(); } } fn flush(&self) { io::stderr().flush().unwrap(); } } impl ErrorLogger { pub fn init() -> Result<(), SetLoggerError> { log::set_logger(&InfoLogger)?; log::set_max_level(LevelFilter::Error); Ok(()) } } impl log::Log for ErrorLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Error } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { writeln!(io::stderr(), "{}: {}", record.level(), record.args()).unwrap(); } } fn flush(&self) { io::stderr().flush().unwrap(); } } impl InfoLogger { pub fn init() -> Result<(), SetLoggerError> { log::set_logger(&InfoLogger)?; log::set_max_level(LevelFilter::Info); Ok(()) } } impl log::Log for InfoLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Info } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { writeln!(io::stderr(), "{}: {}", record.level(), record.args()).unwrap(); } } fn flush(&self) { io::stderr().flush().unwrap(); } } cbindgen-0.12.1/src/main.rs010066400017500001750000000204071360223554200136550ustar0000000000000000/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::env; use std::io; use std::path::{Path, PathBuf}; extern crate clap; #[macro_use] extern crate log; extern crate proc_macro2; #[macro_use] extern crate serde; extern crate serde_json; #[macro_use] extern crate quote; #[macro_use] extern crate syn; extern crate toml; use clap::{App, Arg, ArgMatches}; mod bindgen; mod logging; use crate::bindgen::{Bindings, Builder, Cargo, Config, Error, Language, Style}; fn apply_config_overrides<'a>(config: &mut Config, matches: &ArgMatches<'a>) { // We allow specifying a language to override the config default. This is // used by compile-tests. if let Some(lang) = matches.value_of("lang") { config.language = match lang { "C++" => Language::Cxx, "c++" => Language::Cxx, "C" => Language::C, "c" => Language::C, _ => { error!("Unknown language specified."); return; } }; } if matches.is_present("cpp-compat") { config.cpp_compat = true; } if let Some(style) = matches.value_of("style") { config.style = match style { "Both" => Style::Both, "both" => Style::Both, "Tag" => Style::Tag, "tag" => Style::Tag, "Type" => Style::Type, "type" => Style::Type, _ => { error!("Unknown style specified."); return; } } } if matches.is_present("d") { config.parse.parse_deps = true; } } fn load_bindings<'a>(input: &Path, matches: &ArgMatches<'a>) -> Result { // If a file is specified then we load it as a single source if !input.is_dir() { // Load any config specified or search in the input directory let mut config = match matches.value_of("config") { Some(c) => Config::from_file(c).unwrap(), None => Config::from_root_or_default(input), }; apply_config_overrides(&mut config, &matches); return Builder::new() .with_config(config) .with_src(input) .generate(); } // We have to load a whole crate, so we use cargo to gather metadata let lib = Cargo::load( input, matches.value_of("lockfile"), matches.value_of("crate"), true, matches.is_present("clean"), )?; // Load any config specified or search in the binding crate directory let mut config = match matches.value_of("config") { Some(c) => Config::from_file(c).unwrap(), None => { let binding_crate_dir = lib.find_crate_dir(&lib.binding_crate_ref()); if let Some(binding_crate_dir) = binding_crate_dir { Config::from_root_or_default(&binding_crate_dir) } else { // This shouldn't happen Config::from_root_or_default(input) } } }; apply_config_overrides(&mut config, &matches); Builder::new() .with_config(config) .with_cargo(lib) .generate() } fn main() { let matches = App::new("cbindgen") .version(bindgen::VERSION) .about("Generate C bindings for a Rust library") .arg( Arg::with_name("v") .short("v") .multiple(true) .help("Enable verbose logging"), ) .arg( Arg::with_name("verify") .long("verify") .help("Generate bindings and compare it to the existing bindings file and error if they are different"), ) .arg( Arg::with_name("config") .short("c") .long("config") .value_name("PATH") .help("Specify path to a `cbindgen.toml` config to use"), ) .arg( Arg::with_name("lang") .short("l") .long("lang") .value_name("LANGUAGE") .help("Specify the language to output bindings in") .possible_values(&["c++", "C++", "c", "C"]), ) .arg( Arg::with_name("cpp-compat") .long("cpp-compat") .help("Whether to add C++ compatibility to generated C bindings") ) .arg( Arg::with_name("style") .short("s") .long("style") .value_name("STYLE") .help("Specify the declaration style to use for bindings") .possible_values(&["Both", "both", "Tag", "tag", "Type", "type"]), ) .arg( Arg::with_name("d") .short("d") .long("parse-dependencies") .help("Whether to parse dependencies when generating bindings"), ) .arg( Arg::with_name("clean") .long("clean") .help( "Whether to use a new temporary directory for expanding macros. \ Affects performance, but might be required in certain build processes.") .required(false) ) .arg( Arg::with_name("INPUT") .help( "A crate directory or source file to generate bindings for. \ In general this is the folder where the Cargo.toml file of \ source Rust library resides.") .required(false) .index(1), ) .arg( Arg::with_name("crate") .long("crate") .value_name("CRATE_NAME") .help( "If generating bindings for a crate, \ the specific crate to generate bindings for", ) .required(false), ) .arg( Arg::with_name("out") .short("o") .long("output") .value_name("PATH") .help("The file to output the bindings to") .required(false), ) .arg( Arg::with_name("lockfile") .long("lockfile") .value_name("PATH") .help( "Specify the path to the Cargo.lock file explicitly. If this \ is not specified, the Cargo.lock file is searched for in the \ same folder as the Cargo.toml file. This option is useful for \ projects that use workspaces.") .required(false), ) .arg( Arg::with_name("quiet") .short("q") .long("quiet") .help("Report errors only (overrides verbosity options).") .required(false), ) .get_matches(); if !matches.is_present("out") && matches.is_present("verify") { error!( "Cannot verify bindings against `stdout`, please specify a file to compare against." ); std::process::exit(2); } // Initialize logging if matches.is_present("quiet") { logging::ErrorLogger::init().unwrap(); } else { match matches.occurrences_of("v") { 0 => logging::WarnLogger::init().unwrap(), 1 => logging::InfoLogger::init().unwrap(), _ => logging::TraceLogger::init().unwrap(), } } // Find the input directory let input = match matches.value_of("INPUT") { Some(input) => PathBuf::from(input), None => env::current_dir().unwrap(), }; let bindings = match load_bindings(&input, &matches) { Ok(bindings) => bindings, Err(msg) => { error!("{}", msg); error!("Couldn't generate bindings for {}.", input.display()); std::process::exit(1); } }; // Write the bindings file match matches.value_of("out") { Some(file) => { let changed = bindings.write_to_file(file); if matches.is_present("verify") && changed { std::process::exit(2); } } _ => { bindings.write(io::stdout()); } } } cbindgen-0.12.1/template.toml010066400017500001750000000045011360223554200143010ustar0000000000000000# This is a template cbindgen.toml file with all of the default values. # Some values are commented out because their absence is the real default. # # See https://github.com/eqrion/cbindgen/blob/master/docs.md#cbindgentoml # for detailed documentation of every option here. language = "C++" ############## Options for Wrapping the Contents of the Header ################# # header = "/* Text to put at the beginning of the generated file. Probably a license. */" # trailer = "/* Text to put at the end of the generated file */" # include_guard = "my_bindings_h" # autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */" include_version = false # namespace = "my_namespace" namespaces = [] using_namespaces = [] sys_includes = [] includes = [] no_includes = false ############################ Code Style Options ################################ braces = "SameLine" line_length = 100 tab_width = 2 documentation_style = "auto" ############################# Codegen Options ################################## style = "both" [defines] # "target_os = freebsd" = "DEFINE_FREEBSD" # "feature = serde" = "DEFINE_SERDE" [export] include = [] exclude = [] # prefix = "CAPI_" item_types = [] renaming_overrides_prefixing = false [export.rename] [export.body] [fn] rename_args = "None" # must_use = "MUST_USE_FUNC" # prefix = "START_FUNC" # postfix = "END_FUNC" args = "auto" [struct] rename_fields = "None" # must_use = "MUST_USE_STRUCT" derive_constructor = false derive_eq = false derive_neq = false derive_lt = false derive_lte = false derive_gt = false derive_gte = false [enum] rename_variants = "None" # must_use = "MUST_USE_ENUM" add_sentinel = false prefix_with_name = false derive_helper_methods = false derive_const_casts = false derive_mut_casts = false # cast_assert_name = "ASSERT" derive_tagged_enum_destructor = false derive_tagged_enum_copy_constructor = false enum_class = true private_default_tagged_enum_constructor = false [const] allow_static_const = true [macro_expansion] bitflags = false ############## Options for How Your Rust library Should Be Parsed ############## [parse] parse_deps = false # include = [] exclude = [] clean = false extra_bindings = [] [parse.expand] crates = [] all_features = false default_features = true features = [] cbindgen-0.12.1/tests/rust/alias.rs010064400017500001750000000005611356501061700153710ustar0000000000000000#[repr(C)] struct Dep { a: i32, b: f32, } #[repr(C)] struct Foo { a: X, b: X, c: Dep, } #[repr(u32)] enum Status { Ok, Err, } type IntFoo = Foo; type DoubleFoo = Foo; type Unit = i32; type SpecialStatus = Status; #[no_mangle] pub extern "C" fn root( x: IntFoo, y: DoubleFoo, z: Unit, w: SpecialStatus ) { } cbindgen-0.12.1/tests/rust/annotation.rs010064400017500001750000000011611356501061700164470ustar0000000000000000/// cbindgen:derive-lt=true /// cbindgen:derive-lte=true /// cbindgen:derive-constructor=true /// cbindgen:rename-all=GeckoCase #[repr(C)] struct A(i32); /// cbindgen:field-names=[x, y] #[repr(C)] struct B(i32, f32); /// cbindgen:trailing-values=[Z, W] #[repr(u32)] enum C { X = 2, Y, } /// cbindgen:derive-helper-methods=true #[repr(u8)] enum F { Foo(i16), Bar { x: u8, y: i16 }, Baz } /// cbindgen:derive-helper-methods #[repr(C, u8)] enum H { Hello(i16), There { x: u8, y: i16 }, Everyone } #[no_mangle] pub extern "C" fn root( x: A, y: B, z: C, f: F, h: H, ) { } cbindgen-0.12.1/tests/rust/array.rs010064400017500001750000000001311356501061700154070ustar0000000000000000#[repr(C)] enum Foo { A([f32; 20]) } #[no_mangle] pub extern "C" fn root(a: Foo) {} cbindgen-0.12.1/tests/rust/array.toml010064400017500001750000000000441356501061700157410ustar0000000000000000[enum] derive_helper_methods = true cbindgen-0.12.1/tests/rust/asserted-cast.rs010064400017500001750000000010131356501061700170330ustar0000000000000000/// cbindgen:prefix-with-name #[repr(C, u8)] pub enum H { Foo(i16), Bar { x: u8, y: i16 }, Baz } /// cbindgen:prefix-with-name #[repr(C, u8, u16)] pub enum I { Foo(i16), Bar { x: u8, y: i16 }, Baz } /// cbindgen:prefix-with-name #[repr(C, u8)] pub enum J { Foo(i16), Bar { x: u8, y: i16 }, Baz } /// cbindgen:prefix-with-name #[repr(u8)] pub enum K { Foo(i16), Bar { x: u8, y: i16 }, Baz } #[no_mangle] pub extern "C" fn foo( h: H, i: I, j: J, k: K, ) {} cbindgen-0.12.1/tests/rust/asserted-cast.toml010064400017500001750000000003551356501061700173720ustar0000000000000000# This is a bit of an abuse of the warning config... autogen_warning = """ #define MY_ASSERT(...) do { } while (0) """ [enum] derive_helper_methods = true derive_const_casts = true derive_mut_casts = true cast_assert_name = "MY_ASSERT" cbindgen-0.12.1/tests/rust/assoc_const_conflict.rs010064400017500001750000000001361356501061700204750ustar0000000000000000#[repr(C)] struct Foo {} pub const Foo_FOO: u32 = 42; impl Foo { const FOO: i32 = 0; } cbindgen-0.12.1/tests/rust/assoc_constant.rs010064400017500001750000000004331356501061700173170ustar0000000000000000#[repr(C)] struct Foo {} impl Foo { pub const GA: i32 = 10; pub const BU: &'static str = "hello world"; pub const ZO: f32 = 3.14; pub(crate) const DONT_EXPORT_CRATE: i32 = 20; const DONT_EXPORT_PRIV: i32 = 30; } #[no_mangle] pub extern "C" fn root(x: Foo) { } cbindgen-0.12.1/tests/rust/associated_in_body.rs010064400017500001750000000010571356501061700201230ustar0000000000000000bitflags! { /// Constants shared by multiple CSS Box Alignment properties /// /// These constants match Gecko's `NS_STYLE_ALIGN_*` constants. #[derive(MallocSizeOf, ToComputedValue)] #[repr(C)] pub struct AlignFlags: u8 { /// 'auto' const AUTO = 0; /// 'normal' const NORMAL = 1; /// 'start' const START = 1 << 1; /// 'end' const END = 1 << 2; /// 'flex-start' const FLEX_START = 1 << 3; } } #[no_mangle] pub extern "C" fn root(flags: AlignFlags) {} cbindgen-0.12.1/tests/rust/associated_in_body.toml010064400017500001750000000002261356501061700204470ustar0000000000000000[struct] associated_constants_in_body = true [macro_expansion] bitflags = true [export] prefix = "Style" # Just ensuring they play well together :) cbindgen-0.12.1/tests/rust/bitflags.rs010064400017500001750000000010571356501061700160740ustar0000000000000000bitflags! { /// Constants shared by multiple CSS Box Alignment properties /// /// These constants match Gecko's `NS_STYLE_ALIGN_*` constants. #[derive(MallocSizeOf, ToComputedValue)] #[repr(C)] pub struct AlignFlags: u8 { /// 'auto' const AUTO = 0; /// 'normal' const NORMAL = 1; /// 'start' const START = 1 << 1; /// 'end' const END = 1 << 2; /// 'flex-start' const FLEX_START = 1 << 3; } } #[no_mangle] pub extern "C" fn root(flags: AlignFlags) {} cbindgen-0.12.1/tests/rust/bitflags.toml010064400017500001750000000000421356501061700164140ustar0000000000000000[macro_expansion] bitflags = true cbindgen-0.12.1/tests/rust/body.rs010064400017500001750000000005521356501061700152350ustar0000000000000000 #[repr(C)] pub struct MyFancyStruct { i: i32, } #[repr(C)] pub enum MyFancyEnum { Foo, Bar(i32), Baz(i32), } #[repr(C)] pub enum MyCLikeEnum { Foo1, Bar1, Baz1, } #[repr(C)] pub union MyUnion { pub f: f32, pub u: u32, } #[no_mangle] pub extern "C" fn root(s: MyFancyStruct, e: MyFancyEnum, c: MyCLikeEnum, u: MyUnion) {} cbindgen-0.12.1/tests/rust/body.toml010064400017500001750000000004311356501061700155600ustar0000000000000000[export.body] "MyFancyStruct" = """ #ifdef __cplusplus inline void foo(); #endif """ "MyFancyEnum" = """ #ifdef __cplusplus inline void wohoo(); #endif """ "MyCLikeEnum" = """ BogusVariantForSerializationForExample, """ "MyUnion" = """ int32_t extra_member; // yolo """ cbindgen-0.12.1/tests/rust/cdecl.rs010064400017500001750000000013011356501061700153430ustar0000000000000000type A = fn (); type B = fn () -> (); type C = fn (i32, i32) -> bool; type D = fn (i32) -> fn (f32) -> bool; type E = fn () -> *const [i32; 16]; type F = *const i32; type G = *const *const i32; type H = *const *mut i32; type I = *const [i32; 16]; type J = *const fn (f32) -> f64; type K = [i32; 16]; type L = [*const i32; 16]; type M = [fn (i32, i32) -> bool; 16]; type N = [fn (i32, i32) -> (); 16]; #[no_mangle] pub extern "C" fn O() -> fn () { } type P = fn (named1st: i32, bool, named3rd: bool, _: i32); #[no_mangle] pub extern "C" fn root( a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L, m: M, n: N, p: P ) { } cbindgen-0.12.1/tests/rust/cfg-2.rs010064400017500001750000000005471356501061700152020ustar0000000000000000#[cfg(any(windows, unix))] #[repr(C)] struct Foo { x: i32, } #[cfg(windows)] #[repr(C)] struct Bar { y: Foo, } #[cfg(unix)] #[repr(C)] struct Bar { z: Foo, } #[repr(C)] struct Root { w: Bar, } #[cfg(windows)] pub const DEFAULT_X: i32 = 0x08; #[cfg(unix)] pub const DEFAULT_X: i32 = 0x2a; #[no_mangle] pub extern "C" fn root(a: Root) { } cbindgen-0.12.1/tests/rust/cfg-2.toml010064400017500001750000000001171356501061700155220ustar0000000000000000[defines] "unix" = "DEFINED" "macos" = "NOT_DEFINED" "windows" = "NOT_DEFINED" cbindgen-0.12.1/tests/rust/cfg-field.rs010064400017500001750000000001701356501061700161140ustar0000000000000000struct Foo { #[cfg(windows)] x: i32, } pub fn foo() { Foo { #[cfg(windows)] x: 0, }; } cbindgen-0.12.1/tests/rust/cfg.rs010064400017500001750000000010621356501061700150340ustar0000000000000000#[cfg(all(unix, x11))] #[repr(u32)] enum FooType { A, B, C, } #[cfg(all(unix, x11))] #[repr(C)] struct FooHandle { ty: FooType, x: i32, y: f32, } #[cfg(any(windows, target_pointer_width="32"))] #[repr(u32)] enum BarType { A, B, C, } #[cfg(any(windows, target_pointer_width="32"))] #[repr(C)] struct BarHandle { ty: BarType, x: i32, y: f32, } #[cfg(all(unix, x11))] #[no_mangle] pub extern "C" fn root(a: FooHandle) { } #[cfg(any(windows, target_pointer_width="32"))] #[no_mangle] pub extern "C" fn root(a: BarHandle) { } cbindgen-0.12.1/tests/rust/cfg.toml010064400017500001750000000001611356501061700153620ustar0000000000000000[defines] "unix" = "PLATFORM_UNIX" "windows" = "PLATFORM_WIN" "x11" = "X11" "target_pointer_width = 32" = "M_32" cbindgen-0.12.1/tests/rust/char.rs010064400017500001750000000001271357132115100152060ustar0000000000000000#[repr(C)] struct Foo { a: char, } #[no_mangle] pub extern "C" fn root(a: Foo) {} cbindgen-0.12.1/tests/rust/const_conflict.rs010064400017500001750000000001361356501061700173050ustar0000000000000000#[repr(C)] struct Foo {} impl Foo { const FOO: i32 = 0; } pub const Foo_FOO: u32 = 42; cbindgen-0.12.1/tests/rust/const_transparent.rs010064400017500001750000000001561356501061700200470ustar0000000000000000#[repr(transparent)] struct Transparent { field: u8 } pub const FOO: Transparent = Transparent { field: 0 }; cbindgen-0.12.1/tests/rust/constant.rs010066400017500001750000000013201357325674700161440ustar0000000000000000pub const FOO: i32 = 10; pub const BAR: &'static str = "hello world"; pub const DELIMITER: char = ':'; pub const LEFTCURLY: char = '{'; pub const QUOTE: char = '\''; pub const TAB: char = '\t'; pub const NEWLINE: char = '\n'; pub const HEART: char = '❤'; pub const EQUID: char = '𐂃'; pub const ZOM: f32 = 3.14; pub(crate) const DONT_EXPORT_CRATE: i32 = 20; const DONT_EXPORT_PRIV: i32 = 30; pub const POS_ONE: i8 = 1; pub const NEG_ONE: i8 = -1; // Some doc for shifting // pub const SHIFT: i64 = 3; pub const XBOOL: i64 = 1; pub const XFALSE: i64 = (0 << SHIFT) | XBOOL; pub const XTRUE: i64 = 1 << (SHIFT | XBOOL); #[repr(C)] struct Foo { x: [i32; FOO], } #[no_mangle] pub extern "C" fn root(x: Foo) { } cbindgen-0.12.1/tests/rust/custom_header.rs010064400017500001750000000000521356501061700171150ustar0000000000000000#[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/custom_header.toml010064400017500001750000000001211356501061700174410ustar0000000000000000no_includes = true header = "// This file is generated by cbindgen. DO NOT EDIT" cbindgen-0.12.1/tests/rust/destructor-and-copy-ctor.rs010064400017500001750000000025421357565461000211640ustar0000000000000000use std::ptr::NonNull; /// This will have a destructor manually implemented via variant_body, and /// similarly a Drop impl in Rust. #[repr(C)] pub struct OwnedSlice { len: usize, ptr: NonNull, } #[repr(u8)] pub enum FillRule { A, B } #[repr(C)] pub struct Polygon { pub fill: FillRule, pub coordinates: OwnedSlice, } #[repr(C, u8)] pub enum Foo { Bar, Polygon1(Polygon), Slice1(OwnedSlice), Slice2(OwnedSlice), Slice3 { fill: FillRule, coords: OwnedSlice, }, Slice4 { fill: FillRule, coords: OwnedSlice, }, } #[repr(u8)] pub enum Baz { Bar2, Polygon21(Polygon), Slice21(OwnedSlice), Slice22(OwnedSlice), Slice23 { fill: FillRule, coords: OwnedSlice, }, Slice24 { fill: FillRule, coords: OwnedSlice, }, } #[repr(u8)] pub enum Taz { Bar3, Taz1(i32), Taz3(OwnedSlice), } /// cbindgen:derive-tagged-enum-destructor=false /// cbindgen:derive-tagged-enum-copy-constructor=false #[repr(u8)] pub enum Tazz { Bar4, Taz2(i32), } /// cbindgen:derive-tagged-enum-copy-assignment=false #[repr(u8)] pub enum Tazz { Bar4, Taz2(i32), } #[no_mangle] pub extern "C" fn root(a: &Foo, b: &Baz, c: &Taz, d: Tazz) {} cbindgen-0.12.1/tests/rust/destructor-and-copy-ctor.toml010064400017500001750000000004061357565455700215220ustar0000000000000000[enum] derive_tagged_enum_destructor = true derive_tagged_enum_copy_constructor = true derive_tagged_enum_copy_assignment = true derive_helper_methods = true private_default_tagged_enum_constructor = true [export.body] "OwnedSlice" = """ ~OwnedSlice() {} """ cbindgen-0.12.1/tests/rust/display_list.rs010066400017500001750000000005341357325674600170200ustar0000000000000000#[repr(u8)] pub enum DisplayItem { Fill(Rect, Color), Image { id: u32, bounds: Rect }, ClearScreen, } #[repr(C)] pub struct Rect { x: f32, y: f32, w: f32, h: f32 } #[repr(C)] pub struct Color { r: u8, g: u8, b: u8, a: u8 } #[no_mangle] pub extern "C" fn push_item(item: DisplayItem) -> bool { ::std::mem::drop(item); true } cbindgen-0.12.1/tests/rust/docstyle_auto.rs010064400017500001750000000001041356501061700171470ustar0000000000000000/// The root of all evil. #[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/docstyle_auto.toml010064400017500001750000000000351356501061700175010ustar0000000000000000documentation_style = "auto" cbindgen-0.12.1/tests/rust/docstyle_c99.rs010064400017500001750000000001041356501061700166030ustar0000000000000000/// The root of all evil. #[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/docstyle_c99.toml010064400017500001750000000000341356501061700171340ustar0000000000000000documentation_style = "c99" cbindgen-0.12.1/tests/rust/docstyle_doxy.rs010064400017500001750000000001041356501061700171620ustar0000000000000000/// The root of all evil. #[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/docstyle_doxy.toml010064400017500001750000000000351356501061700175140ustar0000000000000000documentation_style = "doxy" cbindgen-0.12.1/tests/rust/documentation.rs010064400017500001750000000012541356501061700171510ustar0000000000000000/// The root of all evil. /// /// But at least it contains some more documentation as someone would expect /// from a simple test case like this. /// /// # Hint /// /// Always ensure that everything is properly documented, even if you feel lazy. /// **Sometimes** it is also helpful to include some markdown formatting. /// /// //////////////////////////////////////////////////////////////////////////// /// /// Attention: /// /// Rust is going to trim all leading `/` symbols. If you want to use them as a /// marker you need to add at least a single whitespace inbetween the tripple /// slash doc-comment marker and the rest. /// #[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/enum.rs010066400017500001750000000026131360223554200152440ustar0000000000000000enum Opaque { Foo(i32), Bar, } #[repr(u64)] enum A { a1 = 0, a2 = 2, a3, a4 = 5, } #[repr(u32)] enum B { b1 = 0, b2 = 2, b3, b4 = 5, } #[repr(u16)] enum C { c1 = 0, c2 = 2, c3, c4 = 5, } #[repr(u8)] enum D { d1 = 0, d2 = 2, d3, d4 = 5, } #[repr(usize)] enum E { e1 = 0, e2 = 2, e3, e4 = 5, } #[repr(isize)] enum F { f1 = 0, f2 = 2, f3, f4 = 5, } #[repr(u8)] enum G { Foo(i16), Bar { x: u8, y: i16 }, Baz, } /// cbindgen:prefix-with-name #[repr(C)] enum H { Foo(i16), Bar { x: u8, y: i16 }, Baz, } /// cbindgen:prefix-with-name #[repr(C, u8)] enum I { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C, u8, u16)] enum J { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C, u8, unknown_hint)] enum K { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C)] enum L { l1, l2, l3, l4, } #[repr(i8)] enum M { m1 = -1, m2 = 0, m3 = 1, } /// cbindgen:enum-class=false #[repr(C)] enum N { n1, n2, n3, n4, } /// cbindgen:enum-class=false #[repr(i8)] enum O { o1, o2, o3, o4, } #[no_mangle] pub extern "C" fn root( opaque: *mut Opaque, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L, m: M, n: N, o: O, ) { } cbindgen-0.12.1/tests/rust/euclid.rs010064400017500001750000000041161356501061700155450ustar0000000000000000struct UnknownUnit; struct LayoutUnit; #[repr(C)] struct TypedLength(T, PhantomData); #[repr(C)] struct TypedSideOffsets2D { top: T, right: T, bottom: T, left: T, _phantom: PhantomData, } #[repr(C)] struct TypedSize2D { width: T, height: T, _phantom: PhantomData, } #[repr(C)] struct TypedPoint2D { x: T, y: T, _phantom: PhantomData, } #[repr(C)] struct TypedRect { origin: TypedPoint2D, size: TypedSize2D, _phantom: PhantomData, } #[repr(C)] struct TypedTransform2D { m11: T, m12: T, m21: T, m22: T, m31: T, m32: T, _phantom: PhantomData, } type Length = TypedLength; type SideOffsets2D = TypedSideOffsets2D; type Size2D = TypedSize2D; type Point2D = TypedPoint2D; type Rect = TypedRect; type LayoutLength = TypedLength; type LayoutSideOffsets2D = TypedSideOffsets2D; type LayoutSize2D = TypedSize2D; type LayoutPoint2D = TypedPoint2D; type LayoutRect = TypedRect; #[no_mangle] pub extern "C" fn root( length_a: TypedLength, length_b: TypedLength, length_c: Length, length_d: LayoutLength, side_offsets_a: TypedSideOffsets2D, side_offsets_b: TypedSideOffsets2D, side_offsets_c: SideOffsets2D, side_offsets_d: LayoutSideOffsets2D, size_a: TypedSize2D, size_b: TypedSize2D, size_c: Size2D, size_d: LayoutSize2D, point_a: TypedPoint2D, point_b: TypedPoint2D, point_c: Point2D, point_d: LayoutPoint2D, rect_a: TypedRect, rect_b: TypedRect, rect_c: Rect, rect_d: LayoutRect, transform_a: TypedTransform2D, transform_b: TypedTransform2D ) { } cbindgen-0.12.1/tests/rust/extern-2.rs010064400017500001750000000001651356501061700157440ustar0000000000000000#[no_mangle] pub extern "C" fn first() { } #[no_mangle] pub extern fn second() { } #[no_mangle] pub fn third() { } cbindgen-0.12.1/tests/rust/extern.rs010064400017500001750000000001621356501061700156020ustar0000000000000000#[repr(C)] struct Normal { x: i32, y: f32, } extern "C" { fn foo() -> i32; fn bar(a: Normal); } cbindgen-0.12.1/tests/rust/fns.rs010064400017500001750000000004011356501061700150570ustar0000000000000000#[repr(C)] pub struct Fns { noArgs: fn(), anonymousArg: fn(i32), returnsNumber: fn() -> i32, namedArgs: fn(first: i32, snd: i16) -> i8, namedArgsWildcards: fn(_: i32, named: i16, _: i64) -> i8, } #[no_mangle] pub extern "C" fn root(_fns: Fns) {} cbindgen-0.12.1/tests/rust/global_attr.rs010064400017500001750000000000341356501061700165650ustar0000000000000000#![allow(unused_variables)] cbindgen-0.12.1/tests/rust/include.rs010064400017500001750000000000001356501061700157070ustar0000000000000000cbindgen-0.12.1/tests/rust/include.toml010064400017500001750000000000321356501061700162430ustar0000000000000000sys_includes = ["math.h"] cbindgen-0.12.1/tests/rust/include_guard.rs010064400017500001750000000000521356501061700171000ustar0000000000000000#[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/include_guard.toml010064400017500001750000000000651356501061700174330ustar0000000000000000include_guard = "INCLUDE_GUARD_H" no_includes = true cbindgen-0.12.1/tests/rust/include_item.rs010064400017500001750000000001261356501061700167360ustar0000000000000000#[repr(C)] struct A { x: i32, y: f32, } #[repr(C)] struct B { data: A, } cbindgen-0.12.1/tests/rust/include_item.toml010064400017500001750000000000311356501061700172600ustar0000000000000000[export] include = ["B"] cbindgen-0.12.1/tests/rust/include_specific.rs010064400017500001750000000000001356501061700175540ustar0000000000000000cbindgen-0.12.1/tests/rust/include_specific.toml010064400017500001750000000000551356501061700201150ustar0000000000000000sys_includes = ["math.h"] no_includes = true cbindgen-0.12.1/tests/rust/inner_mod.rs010064400017500001750000000001701356501061700162460ustar0000000000000000mod foo { #[repr(C)] struct Foo { x: f32, } } #[no_mangle] pub extern "C" fn root(a: foo::Foo) { } cbindgen-0.12.1/tests/rust/item_types.rs010064400017500001750000000002301356501061700164530ustar0000000000000000 pub const MY_CONST: u8 = 4; #[no_mangle] pub extern "C" fn ExternFunction() { } #[repr(u8)] pub enum OnlyThisShouldBeGenerated { Foo, Bar, } cbindgen-0.12.1/tests/rust/item_types.toml010064400017500001750000000001101356501061700167770ustar0000000000000000[export] item_types = ["enums"] include = ["OnlyThisShouldBeGenerated"] cbindgen-0.12.1/tests/rust/item_types_renamed.rs010064400017500001750000000002301356501061700201460ustar0000000000000000 pub const MY_CONST: u8 = 4; #[no_mangle] pub extern "C" fn ExternFunction() { } #[repr(u8)] pub enum OnlyThisShouldBeGenerated { Foo, Bar, } cbindgen-0.12.1/tests/rust/item_types_renamed.toml010064400017500001750000000001311356501061700204750ustar0000000000000000[export] item_types = ["enums"] include = ["OnlyThisShouldBeGenerated"] prefix = "Style" cbindgen-0.12.1/tests/rust/layout.rs010064400017500001750000000037001357565316600156300ustar0000000000000000#[repr(align(1), C)] pub struct Align1Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(2), C)] pub struct Align2Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(4), C)] pub struct Align4Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(8), C)] pub struct Align8Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(32), C)] pub struct Align32Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(packed, C)] pub struct PackedStruct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(1), C)] pub union Align1Union { pub variant1: usize, pub variant2: *mut u8, } #[repr(align(4), C)] pub union Align4Union { pub variant1: usize, pub variant2: *mut u8, } #[repr(align(16), C)] pub union Align16Union { pub variant1: usize, pub variant2: *mut u8, } #[repr(packed, C)] pub union PackedUnion { pub variant1: usize, pub variant2: *mut u8, } // #[repr(packed(n), C)] structs are currently unsupported. #[repr(packed(4), C)] pub struct UnsupportedPacked4Struct { pub arg1: usize, pub arg2: *mut u8, } // #[repr(packed(n), C)] unions are currently unsupported. #[repr(packed(4), C)] pub union UnsupportedPacked4Union { pub variant1: usize, pub variant2: *mut u8, } // #[repr(align(n), C)] enums are currently unsupported. #[repr(align(4), C)] pub enum UnsupportedAlign4Enum { Variant1, Variant2, } // Non-repr(C) structs aren't translated. #[repr(align(4))] pub struct RustAlign4Struct { pub arg1: usize, pub arg2: *mut u8, } // Non-repr(C) structs aren't translated. #[repr(packed)] pub struct RustPackedStruct { pub arg1: usize, pub arg2: *mut u8, } // Non-repr(C) unions aren't translated. #[repr(align(4))] pub struct RustAlign4Union { pub arg1: usize, pub arg2: *mut u8, } // Non-repr(C) unions aren't translated. #[repr(packed)] pub struct RustPackedUnion { pub arg1: usize, pub arg2: *mut u8, } cbindgen-0.12.1/tests/rust/layout.toml010064400017500001750000000010501357565316600161530ustar0000000000000000header = """ #define CBINDGEN_PACKED __attribute__ ((packed)) #define CBINDGEN_ALIGNED(n) __attribute__ ((aligned(n))) """ [layout] packed = "CBINDGEN_PACKED" aligned_n = "CBINDGEN_ALIGNED" [export] include = [ "Align1Struct", "Align2Struct", "Align4Struct", "Align8Struct", "Align32Struct", "PackedStruct", "Align1Union", "Align4Union", "Align16Union", "PackedUnion", "UnsupportedPacked4Struct", "UnsupportedPacked4Union", "UnsupportedAlign4Enum", "RustAlign4Struct", "RustPackedStruct", "RustAlign4Union", "RustPackedUnion", ] cbindgen-0.12.1/tests/rust/layout_aligned_opaque.rs010064400017500001750000000025231357565316600206670ustar0000000000000000#[repr(packed, C)] pub struct PackedStruct { pub arg1: usize, pub arg2: *mut u8, } #[repr(packed, C)] pub union PackedUnion { pub variant1: usize, pub variant2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(1), C)] pub union OpaqueAlign1Union { pub variant1: usize, pub variant2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(4), C)] pub union OpaqueAlign4Union { pub variant1: usize, pub variant2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(16), C)] pub union OpaqueAlign16Union { pub variant1: usize, pub variant2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(1), C)] pub struct OpaqueAlign1Struct { pub arg1: usize, pub arg2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(2), C)] pub struct OpaqueAlign2Struct { pub arg1: usize, pub arg2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(4), C)] pub struct OpaqueAlign4Struct { pub arg1: usize, pub arg2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(8), C)] pub struct OpaqueAlign8Struct { pub arg1: usize, pub arg2: *mut u8, } // Opaque because aligned_n is not defined. #[repr(align(32), C)] pub struct OpaqueAlign32Struct { pub arg1: usize, pub arg2: *mut u8, } cbindgen-0.12.1/tests/rust/layout_aligned_opaque.toml010064400017500001750000000006701357565316600212170ustar0000000000000000header = """ #define CBINDGEN_PACKED __attribute__ ((packed)) #define CBINDGEN_ALIGNED(n) __attribute__ ((aligned(n))) """ [layout] # We do not define aligned_n. packed = "CBINDGEN_PACKED" [export] include = [ "PackedStruct", "PackedUnion", "OpaqueAlign1Union", "OpaqueAlign4Union", "OpaqueAlign16Union", "OpaqueAlign1Struct", "OpaqueAlign2Struct", "OpaqueAlign4Struct", "OpaqueAlign8Struct", "OpaqueAlign32Struct", ] cbindgen-0.12.1/tests/rust/layout_packed_opaque.rs010064400017500001750000000020411357565316600205060ustar0000000000000000#[repr(align(1), C)] pub union Align1Union { pub variant1: usize, pub variant2: *mut u8, } #[repr(align(4), C)] pub union Align4Union { pub variant1: usize, pub variant2: *mut u8, } #[repr(align(16), C)] pub union Align16Union { pub variant1: usize, pub variant2: *mut u8, } #[repr(align(1), C)] pub struct Align1Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(2), C)] pub struct Align2Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(4), C)] pub struct Align4Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(8), C)] pub struct Align8Struct { pub arg1: usize, pub arg2: *mut u8, } #[repr(align(32), C)] pub struct Align32Struct { pub arg1: usize, pub arg2: *mut u8, } // Opaque because packed is not defined. #[repr(packed, C)] pub struct OpaquePackedStruct { pub arg1: usize, pub arg2: *mut u8, } // Opaque because packed is not defined. #[repr(packed, C)] pub union OpaquePackedUnion { pub variant1: usize, pub variant2: *mut u8, } cbindgen-0.12.1/tests/rust/layout_packed_opaque.toml010064400017500001750000000006251357565316600210430ustar0000000000000000header = """ #define CBINDGEN_PACKED __attribute__ ((packed)) #define CBINDGEN_ALIGNED(n) __attribute__ ((aligned(n))) """ [layout] # We do not define packed. aligned_n = "CBINDGEN_ALIGNED" [export] include = [ "Align1Union", "Align4Union", "Align16Union", "Align1Struct", "Align2Struct", "Align4Struct", "Align8Struct", "Align32Struct", "OpaquePackedStruct", "OpaquePackedUnion", ] cbindgen-0.12.1/tests/rust/lifetime_arg.rs010064400017500001750000000001461356501061700167260ustar0000000000000000#[repr(C)] struct A<'a> { data: &'a i32 } #[no_mangle] pub extern "C" fn root<'a>(_a: A<'a>) { } cbindgen-0.12.1/tests/rust/monomorph-1.rs010064400017500001750000000006271356501061700164570ustar0000000000000000#[repr(C)] struct Foo { data: *const T } struct Bar { data: *const T } #[repr(C)] struct Tuple { a: *const T, b: *const E, } type Indirection = Tuple; #[no_mangle] pub extern "C" fn root( a: Foo, b: Foo, c: Bar, d: Foo>, e: Bar>, f: Bar>, g: Tuple, f32>, h: Indirection ) { } cbindgen-0.12.1/tests/rust/monomorph-2.rs010064400017500001750000000003041356501061700164500ustar0000000000000000#[repr(C)] struct List { members: *mut T, count: usize } struct A; struct B; #[no_mangle] pub extern "C" fn foo(a: List) { } #[no_mangle] pub extern "C" fn bar(b: List) { } cbindgen-0.12.1/tests/rust/monomorph-3.rs010064400017500001750000000006241356501061700164560ustar0000000000000000#[repr(C)] union Foo { data: *const T } union Bar { data: *const T } #[repr(C)] union Tuple { a: *const T, b: *const E, } type Indirection = Tuple; #[no_mangle] pub extern "C" fn root( a: Foo, b: Foo, c: Bar, d: Foo>, e: Bar>, f: Bar>, g: Tuple, f32>, h: Indirection ) { } cbindgen-0.12.1/tests/rust/must-use.rs010064400017500001750000000004051356501061700160570ustar0000000000000000 #[repr(C)] #[must_use] pub struct OwnedPtr { ptr: *mut T, } #[repr(C, u8)] #[must_use] pub enum MaybeOwnedPtr { Owned(*mut T), None, } #[no_mangle] #[must_use] pub extern "C" fn maybe_consume(input: OwnedPtr) -> MaybeOwnedPtr { } cbindgen-0.12.1/tests/rust/must-use.toml010064400017500001750000000004171356501061700164110ustar0000000000000000header = """ #define MUST_USE_FUNC __attribute__((warn_unused_result)) #define MUST_USE_STRUCT __attribute__((warn_unused)) #define MUST_USE_ENUM /* nothing */ """ [fn] must_use = "MUST_USE_FUNC" [struct] must_use = "MUST_USE_STRUCT" [enum] must_use = "MUST_USE_ENUM" cbindgen-0.12.1/tests/rust/namespace_constant.rs010064400017500001750000000003001356501061700201340ustar0000000000000000pub const FOO: i32 = 10; pub const BAR: &'static str = "hello world"; pub const ZOM: f32 = 3.14; #[repr(C)] struct Foo { x: [i32; FOO], } #[no_mangle] pub extern "C" fn root(x: Foo) { } cbindgen-0.12.1/tests/rust/namespace_constant.toml010064400017500001750000000000301356501061700204630ustar0000000000000000namespace = "constants" cbindgen-0.12.1/tests/rust/namespaces_constant.rs010064400017500001750000000003001356501061700203170ustar0000000000000000pub const FOO: i32 = 10; pub const BAR: &'static str = "hello world"; pub const ZOM: f32 = 3.14; #[repr(C)] struct Foo { x: [i32; FOO], } #[no_mangle] pub extern "C" fn root(x: Foo) { } cbindgen-0.12.1/tests/rust/namespaces_constant.toml010064400017500001750000000000431356501061700206520ustar0000000000000000namespaces = ["constants", "test"] cbindgen-0.12.1/tests/rust/nested_import.rs010064400017500001750000000000501356501061700171450ustar0000000000000000use std::{result, marker::PhantomData}; cbindgen-0.12.1/tests/rust/no_includes.rs010064400017500001750000000000521356501061700165750ustar0000000000000000#[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/no_includes.toml010064400017500001750000000000231356501061700171220ustar0000000000000000no_includes = true cbindgen-0.12.1/tests/rust/nonnull.rs010064400017500001750000000006571356501061700157730ustar0000000000000000use std::ptr::NonNull; struct Opaque; #[repr(C)] pub struct Foo { a: NonNull, b: NonNull, c: NonNull, d: NonNull>, e: NonNull>, f: NonNull>, g: Option>, h: Option>, i: Option>>, } #[no_mangle] pub extern "C" fn root(arg: NonNull, foo: *mut Foo, d: NonNull>) { } cbindgen-0.12.1/tests/rust/prefix.rs010066400017500001750000000005601357325674700156150ustar0000000000000000pub const LEN: i32 = 42; pub type NamedLenArray = [i32; LEN]; pub type ValuedLenArray = [i32; 42]; #[repr(u8)] pub enum AbsoluteFontWeight { Weight(f32), Normal, Bold, } #[no_mangle] pub extern "C" fn root(x: NamedLenArray, y: ValuedLenArray, z: AbsoluteFontWeight) { } #[no_mangle] pub const X: i64 = 42 << 42; #[no_mangle] pub const Y: i64 = X + X; cbindgen-0.12.1/tests/rust/prefix.toml010064400017500001750000000000341356501061700161170ustar0000000000000000[export] prefix = "PREFIX_" cbindgen-0.12.1/tests/rust/prefixed_struct_literal.rs010064400017500001750000000003161356501061700212240ustar0000000000000000#[repr(C)] struct Foo { a: i32, b: u32, } impl Foo { pub const FOO: Foo = Foo{ a: 42, b: 47, }; } pub const BAR: Foo = Foo{ a: 42, b: 1337, }; #[no_mangle] pub extern "C" fn root(x: Foo) { } cbindgen-0.12.1/tests/rust/prefixed_struct_literal.toml010064400017500001750000000000331356501061700215470ustar0000000000000000[export] prefix = "PREFIX" cbindgen-0.12.1/tests/rust/prefixed_struct_literal_deep.rs010064400017500001750000000003471356501061700222250ustar0000000000000000#[repr(C)] struct Foo { a: i32, b: u32, bar: Bar, } #[repr(C)] struct Bar { a: i32, } pub const VAL: Foo = Foo { a: 42, b: 1337, bar: Bar { a: 323 }, }; #[no_mangle] pub extern "C" fn root(x: Foo) {} cbindgen-0.12.1/tests/rust/prefixed_struct_literal_deep.toml010064400017500001750000000000331356501061700225440ustar0000000000000000[export] prefix = "PREFIX" cbindgen-0.12.1/tests/rust/rename.rs010064400017500001750000000006241356501061700155470ustar0000000000000000struct A { x: i32, y: f32, } #[repr(C)] struct B { x: i32, y: f32, } union C { x: i32, y: f32, } #[repr(C)] union D { x: i32, y: f32, } #[repr(u8)] enum E { x = 0, y = 1, } type F = A; #[no_mangle] pub static G: i32 = 10; pub const H: i32 = 10; #[no_mangle] pub extern "C" fn root( a: *const A, b: B, c: C, d: D, e: E, f: F, ) { } cbindgen-0.12.1/tests/rust/rename.toml010064400017500001750000000000711356501061700160720ustar0000000000000000[export] prefix = "C_" [export.rename] "B" = "AwesomeB" cbindgen-0.12.1/tests/rust/renaming-overrides-prefixing.rs010064400017500001750000000002211356501061700220620ustar0000000000000000struct A { x: i32, y: f32, } #[repr(C)] struct B { x: i32, y: f32, } #[no_mangle] pub extern "C" fn root(a: *const A, b: B) {} cbindgen-0.12.1/tests/rust/renaming-overrides-prefixing.toml010064400017500001750000000001671356501061700224220ustar0000000000000000[export] prefix = "Style" renaming_overrides_prefixing = true [export.rename] "B" = "B" # B should remain unprefixed. cbindgen-0.12.1/tests/rust/reserved.rs010064400017500001750000000004671356501061700161240ustar0000000000000000#[repr(C)] struct A { namespace: i32, float: f32, } /// cbindgen:field-names=[namespace, float] #[repr(C)] struct B(i32, f32); #[repr(C, u8)] enum C { D { namespace: i32, float: f32 }, } #[no_mangle] pub extern "C" fn root( a: A, b: B, c: C, namespace: i32, float: f32, ) { } cbindgen-0.12.1/tests/rust/simplify-option-ptr.rs010064400017500001750000000005331356501061700202440ustar0000000000000000 struct Opaque(); #[repr(C)] struct Foo { x: Option<&Opaque>, y: Option<&mut Opaque>, z: Option ()>, } #[repr(C)] union Bar { x: Option<&Opaque>, y: Option<&mut Opaque>, z: Option ()>, } #[no_mangle] pub extern "C" fn root( a: Option<&Opaque>, b: Option<&mut Opaque>, c: Foo, d: Bar ) { } cbindgen-0.12.1/tests/rust/static.rs010064400017500001750000000003351356501061700155660ustar0000000000000000#[no_mangle] pub static NUMBER: i32 = 10; #[repr(C)] struct Foo { } struct Bar { } #[no_mangle] pub static mut FOO: Foo = Foo { }; #[no_mangle] pub static BAR: Bar = Bar { }; #[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/std_lib.rs010064400017500001750000000001561356501061700157200ustar0000000000000000#[no_mangle] pub extern "C" fn root( a: &Vec, b: &Option, c: &Result ) { } cbindgen-0.12.1/tests/rust/struct.rs010064400017500001750000000010021356501061700156130ustar0000000000000000use std::marker::PhantomData; struct Opaque { x: i32, y: f32, } #[repr(C)] struct Normal { x: i32, y: f32, } #[repr(C)] struct NormalWithZST { x: i32, y: f32, z: (), w: PhantomData, } /// cbindgen:rename-all=GeckoCase #[repr(C)] struct TupleRenamed(i32, f32); /// cbindgen:field-names=[x, y] #[repr(C)] struct TupleNamed(i32, f32); #[no_mangle] pub extern "C" fn root( a: *mut Opaque, b: Normal, c: NormalWithZST, d: TupleRenamed, e: TupleNamed ) { } cbindgen-0.12.1/tests/rust/struct_literal.rs010064400017500001750000000007061356501061700173410ustar0000000000000000#[repr(C)] struct Foo { a: i32, b: u32, } struct Bar { a: i32, b: u32, } impl Foo { pub const FOO: Foo = Foo { a: 42, b: 47, }; pub const FOO2: Self = Foo { a: 42, b: 47, }; pub const FOO3: Self = Self { a: 42, b: 47, }; pub const BAZ: Bar = Bar { a: 42, b: 47, }; } pub const BAR: Foo = Foo { a: 42, b: 1337, }; pub const BAZZ: Bar = Bar { a: 42, b: 1337, }; #[no_mangle] pub extern "C" fn root(x: Foo, bar: Bar) { } cbindgen-0.12.1/tests/rust/struct_literal_order.rs010064400017500001750000000010511356501061700205260ustar0000000000000000#[repr(C)] struct ABC { pub a: f32, pub b: u32, pub c: u32, } #[repr(C)] struct BAC { pub b: u32, pub a: f32, pub c: i32, } impl ABC { pub const abc: ABC = ABC { a: 1.0, b: 2, c: 3 }; pub const bac: ABC = ABC { b: 2, a: 1.0, c: 3 }; pub const cba: ABC = ABC { c: 3, b: 2, a: 1.0 }; } impl BAC { pub const abc: BAC = BAC { a: 2.0, b: 1, c: 3 }; pub const bac: BAC = BAC { b: 1, a: 2.0, c: 3 }; pub const cba: BAC = BAC { c: 3, b: 1, a: 2.0 }; } #[no_mangle] pub extern "C" fn root(a1: ABC, a2: BAC) {} cbindgen-0.12.1/tests/rust/style-crash.rs010064400017500001750000000002641356501061700165360ustar0000000000000000pub trait SpecifiedValueInfo { const SUPPORTED_TYPES: u8 = 0; } impl SpecifiedValueInfo for [T] { const SUPPORTED_TYPES: u8 = T::SUPPORTED_TYPES; } cbindgen-0.12.1/tests/rust/transform-op.rs010064400017500001750000000012051356501061700167230ustar0000000000000000#[repr(C)] pub struct Point { pub x: T, pub y: T, } #[repr(u8)] pub enum Foo { Foo { x: i32, y: Point, z: Point, }, Bar(T), Baz(Point), Bazz, } #[repr(C)] pub enum Bar { Bar1 { x: i32, y: Point, z: Point, u: unsafe extern "C" fn(i32) -> i32, }, Bar2(T), Bar3(Point), Bar4, } #[repr(u8)] pub enum Baz { Baz1(Bar), Baz2(Point), Baz3, } #[repr(C, u8)] pub enum Taz { Taz1(Bar), Taz2(Baz), Taz3, } #[no_mangle] pub extern "C" fn foo( foo: *const Foo, bar: *const Bar, baz: *const Baz, taz: *const Taz, ) {} cbindgen-0.12.1/tests/rust/transform-op.toml010064400017500001750000000001611356501061700172520ustar0000000000000000[export] prefix = "Style" [enum] derive_helper_methods = true derive_const_casts = true derive_mut_casts = true cbindgen-0.12.1/tests/rust/transparent.rs010064400017500001750000000042231356501061700166400ustar0000000000000000struct DummyStruct; // Transparent struct tuple wrapping a struct. #[repr(transparent)] struct TransparentComplexWrappingStructTuple(DummyStruct); // Transparent struct tuple wrapping a primitive. #[repr(transparent)] struct TransparentPrimitiveWrappingStructTuple(u32); // Transparent structure wrapping a struct. #[repr(transparent)] struct TransparentComplexWrappingStructure { only_field: DummyStruct } // Transparent structure wrapping a primitive. #[repr(transparent)] struct TransparentPrimitiveWrappingStructure { only_field: u32 } // Transparent struct wrapper with a marker wrapping a struct. #[repr(transparent)] struct TransparentComplexWrapper { only_non_zero_sized_field: DummyStruct, marker: PhantomData, } // Transparent struct wrapper with a marker wrapping a primitive. #[repr(transparent)] struct TransparentPrimitiveWrapper { only_non_zero_sized_field: u32, marker: PhantomData, } // Associated constant declared before struct declaration. impl TransparentPrimitiveWithAssociatedConstants { pub const ZERO: TransparentPrimitiveWithAssociatedConstants = TransparentPrimitiveWithAssociatedConstants { bits: 0 }; } // Transparent structure wrapping a primitive with associated constants. #[repr(transparent)] struct TransparentPrimitiveWithAssociatedConstants { bits: u32 } // Associated constant declared after struct declaration. impl TransparentPrimitiveWithAssociatedConstants { pub const ONE: TransparentPrimitiveWithAssociatedConstants = TransparentPrimitiveWithAssociatedConstants { bits: 1 }; } enum EnumWithAssociatedConstantInImpl { A } impl EnumWithAssociatedConstantInImpl { pub const TEN: TransparentPrimitiveWrappingStructure = TransparentPrimitiveWrappingStructure { only_field: 10 }; } #[no_mangle] pub extern "C" fn root( a: TransparentComplexWrappingStructTuple, b: TransparentPrimitiveWrappingStructTuple, c: TransparentComplexWrappingStructure, d: TransparentPrimitiveWrappingStructure, e: TransparentComplexWrapper, f: TransparentPrimitiveWrapper, g: TransparentPrimitiveWithAssociatedConstants, h: EnumWithAssociatedConstantInImpl, ) { } cbindgen-0.12.1/tests/rust/typedef.rs010064400017500001750000000002141356501061700157330ustar0000000000000000#[repr(C)] struct Foo { x: T, y: U, } type IntFoo = Foo; #[no_mangle] pub extern "C" fn root(a: IntFoo) { } cbindgen-0.12.1/tests/rust/union.rs010064400017500001750000000005011356501061700154220ustar0000000000000000use std::marker::PhantomData; union Opaque { x: i32, y: f32, } #[repr(C)] union Normal { x: i32, y: f32, } #[repr(C)] union NormalWithZST { x: i32, y: f32, z: (), w: PhantomData, } #[no_mangle] pub extern "C" fn root( a: *mut Opaque, b: Normal, c: NormalWithZST ) { } cbindgen-0.12.1/tests/rust/using_namespaces.rs010064400017500001750000000000521356501061700176170ustar0000000000000000#[no_mangle] pub extern "C" fn root() { } cbindgen-0.12.1/tests/rust/using_namespaces.toml010064400017500001750000000000601356501061700201450ustar0000000000000000namespaces = ["root"] using_namespaces = ["std"]cbindgen-0.12.1/tests/rust/va_list.rs010064400017500001750000000001661356501061700157420ustar0000000000000000use std::ffi::VaList; #[no_mangle] pub unsafe extern "C" fn va_list_test(mut ap: VaList) -> int32_t { ap.arg() } cbindgen-0.12.1/tests/tests.rs010064400017500001750000000103231356501061700144420ustar0000000000000000extern crate cbindgen; use cbindgen::*; use std::path::Path; use std::process::Command; use std::{env, fs, str}; fn run_cbindgen( cbindgen_path: &'static str, path: &Path, output: &Path, language: Language, cpp_compat: bool, style: Option