cxx-build-1.0.141/.cargo_vcs_info.json0000644000000001470000000000100131010ustar { "git": { "sha1": "926094db8792e43cc0e3f33b422f6319dbd2cfff" }, "path_in_vcs": "gen/build" }cxx-build-1.0.141/Cargo.lock0000644000000206350000000000100110600ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "anstyle" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" [[package]] name = "cc" version = "1.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c3d1b2e905a3a7b00a6141adb0e4c0bb941d11caf55349d863942a1cc44e3c9" dependencies = [ "jobserver", "libc", "shlex", ] [[package]] name = "clap" version = "4.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92b7b18d71fad5313a1e320fa9897994228ce274b60faa4d694fe0ea89cd9e6d" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" version = "4.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a35db2071778a7344791a4fb4f95308b5673d219dee3ae348b86642574ecc90c" dependencies = [ "anstyle", "clap_lex", "strsim", ] [[package]] name = "clap_lex" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "codespan-reporting" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" dependencies = [ "termcolor", "unicode-width", ] [[package]] name = "cxx" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc49567e08c72902f4cbc7242ee8d874ec9cbe97fbabf77b4e0e1f447513e13a" dependencies = [ "cc", "cxxbridge-cmd", "cxxbridge-flags", "cxxbridge-macro", "foldhash", "link-cplusplus", ] [[package]] name = "cxx-build" version = "1.0.141" dependencies = [ "cc", "codespan-reporting", "cxx", "cxx-gen", "pkg-config", "proc-macro2", "quote", "scratch", "syn", ] [[package]] name = "cxx-gen" version = "0.7.141" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3343179081b405510bd700a40272ea492d59eaa8d61981c3886242859b3d8ea1" dependencies = [ "codespan-reporting", "proc-macro2", "quote", "syn", ] [[package]] name = "cxxbridge-cmd" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4315c4ce8d23c26d87f2f83698725fd5718d8e6ace4a9093da2664d23294d372" dependencies = [ "clap", "codespan-reporting", "proc-macro2", "quote", "syn", ] [[package]] name = "cxxbridge-flags" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f55d69deb3a92f610a60ecc524a72c7374b6dc822f8fb7bb4e5d9473f10530c4" [[package]] name = "cxxbridge-macro" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bee7a1d9b5091462002c2b8de2a4ed0f0fde011d503cc272633f66075bd5141" dependencies = [ "proc-macro2", "quote", "rustversion", "syn", ] [[package]] name = "foldhash" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" [[package]] name = "jobserver" version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" dependencies = [ "libc", ] [[package]] name = "libc" version = "0.2.169" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" [[package]] name = "link-cplusplus" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d240c6f7e1ba3a28b0249f774e6a9dd0175054b52dfbb61b16eb8505c3785c9" dependencies = [ "cc", ] [[package]] name = "pkg-config" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" [[package]] name = "proc-macro2" version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" [[package]] name = "scratch" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3cf7c11c38cb994f3d40e8a8cde3bbd1f72a435e4c49e85d6553d8312306152" [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" version = "2.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "termcolor" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] [[package]] name = "unicode-ident" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe" [[package]] name = "unicode-width" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "winapi-util" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ "windows-sys", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" cxx-build-1.0.141/Cargo.toml0000644000000035770000000000100111110ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.73" name = "cxx-build" version = "1.0.141" authors = ["David Tolnay "] build = false exclude = ["build.rs"] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "C++ code generator for integrating `cxx` crate into a Cargo build." homepage = "https://cxx.rs" documentation = "https://docs.rs/cxx-build" readme = false keywords = [ "ffi", "build-dependencies", ] categories = [ "development-tools::build-utils", "development-tools::ffi", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/cxx" [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] [features] experimental-async-fn = [] parallel = ["cc/parallel"] [lib] name = "cxx_build" path = "src/lib.rs" [dependencies.cc] version = "1.0.83" [dependencies.codespan-reporting] version = "0.11.1" [dependencies.proc-macro2] version = "1.0.74" features = ["span-locations"] default-features = false [dependencies.quote] version = "1.0.35" default-features = false [dependencies.scratch] version = "1.0.5" [dependencies.syn] version = "2.0.46" features = [ "clone-impls", "full", "parsing", "printing", ] default-features = false [dev-dependencies.cxx] version = "1.0" [dev-dependencies.cxx-gen] version = "0.7" [dev-dependencies.pkg-config] version = "0.3.27" cxx-build-1.0.141/Cargo.toml.orig000064400000000000000000000023211046102023000145540ustar 00000000000000[package] name = "cxx-build" version = "1.0.141" authors = ["David Tolnay "] categories = ["development-tools::build-utils", "development-tools::ffi"] description = "C++ code generator for integrating `cxx` crate into a Cargo build." documentation = "https://docs.rs/cxx-build" edition = "2021" exclude = ["build.rs"] homepage = "https://cxx.rs" keywords = ["ffi", "build-dependencies"] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/cxx" rust-version = "1.73" [features] parallel = ["cc/parallel"] # incomplete features that are not covered by a compatibility guarantee: experimental-async-fn = [] [dependencies] cc = "1.0.83" codespan-reporting = "0.11.1" proc-macro2 = { version = "1.0.74", default-features = false, features = ["span-locations"] } quote = { version = "1.0.35", default-features = false } scratch = "1.0.5" syn = { version = "2.0.46", default-features = false, features = ["clone-impls", "full", "parsing", "printing"] } [dev-dependencies] cxx = { version = "1.0", path = "../.." } cxx-gen = { version = "0.7", path = "../lib" } pkg-config = "0.3.27" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] cxx-build-1.0.141/LICENSE-APACHE000064400000000000000000000227731046102023000136260ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS cxx-build-1.0.141/LICENSE-MIT000064400000000000000000000017771046102023000133370ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cxx-build-1.0.141/src/cargo.rs000064400000000000000000000101341046102023000141160ustar 00000000000000use crate::gen::{CfgEvaluator, CfgResult}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::{BTreeMap as Map, BTreeSet as Set}; use std::env; use std::sync::OnceLock; static ENV: OnceLock = OnceLock::new(); struct CargoEnv { features: Set, cfgs: Map, } pub(super) struct CargoEnvCfgEvaluator; impl CfgEvaluator for CargoEnvCfgEvaluator { fn eval(&self, name: &str, query_value: Option<&str>) -> CfgResult { let env = ENV.get_or_init(CargoEnv::load); if name == "feature" { return if let Some(query_value) = query_value { CfgResult::from(env.features.contains(Lookup::new(query_value))) } else { let msg = "expected `feature = \"...\"`".to_owned(); CfgResult::Undetermined { msg } }; } if name == "test" && query_value.is_none() { let msg = "cfg(test) is not supported because Cargo runs your build script only once across the lib and test build of the same crate".to_owned(); return CfgResult::Undetermined { msg }; } if let Some(cargo_value) = env.cfgs.get(Lookup::new(name)) { return if let Some(query_value) = query_value { CfgResult::from(cargo_value.split(',').any(|value| value == query_value)) } else { CfgResult::True }; } if name == "debug_assertions" && query_value.is_none() { return CfgResult::from(cfg!(debug_assertions)); } CfgResult::False } } impl CargoEnv { fn load() -> Self { const CARGO_FEATURE_PREFIX: &str = "CARGO_FEATURE_"; const CARGO_CFG_PREFIX: &str = "CARGO_CFG_"; let mut features = Set::new(); let mut cfgs = Map::new(); for (k, v) in env::vars_os() { let Some(k) = k.to_str() else { continue; }; let Ok(v) = v.into_string() else { continue; }; if let Some(feature_name) = k.strip_prefix(CARGO_FEATURE_PREFIX) { let feature_name = Name(feature_name.to_owned()); features.insert(feature_name); } else if let Some(cfg_name) = k.strip_prefix(CARGO_CFG_PREFIX) { let cfg_name = Name(cfg_name.to_owned()); cfgs.insert(cfg_name, v); } } CargoEnv { features, cfgs } } } struct Name(String); impl Ord for Name { fn cmp(&self, rhs: &Self) -> Ordering { Lookup::new(&self.0).cmp(Lookup::new(&rhs.0)) } } impl PartialOrd for Name { fn partial_cmp(&self, rhs: &Self) -> Option { Some(self.cmp(rhs)) } } impl Eq for Name {} impl PartialEq for Name { fn eq(&self, rhs: &Self) -> bool { Lookup::new(&self.0).eq(Lookup::new(&rhs.0)) } } #[repr(transparent)] struct Lookup(str); impl Lookup { fn new(name: &str) -> &Self { unsafe { &*(name as *const str as *const Self) } } } impl Borrow for Name { fn borrow(&self) -> &Lookup { Lookup::new(&self.0) } } impl Ord for Lookup { fn cmp(&self, rhs: &Self) -> Ordering { self.0 .bytes() .map(CaseAgnosticByte) .cmp(rhs.0.bytes().map(CaseAgnosticByte)) } } impl PartialOrd for Lookup { fn partial_cmp(&self, rhs: &Self) -> Option { Some(self.cmp(rhs)) } } impl Eq for Lookup {} impl PartialEq for Lookup { fn eq(&self, rhs: &Self) -> bool { self.0 .bytes() .map(CaseAgnosticByte) .eq(rhs.0.bytes().map(CaseAgnosticByte)) } } struct CaseAgnosticByte(u8); impl Ord for CaseAgnosticByte { fn cmp(&self, rhs: &Self) -> Ordering { self.0.to_ascii_lowercase().cmp(&rhs.0.to_ascii_lowercase()) } } impl PartialOrd for CaseAgnosticByte { fn partial_cmp(&self, rhs: &Self) -> Option { Some(self.cmp(rhs)) } } impl Eq for CaseAgnosticByte {} impl PartialEq for CaseAgnosticByte { fn eq(&self, rhs: &Self) -> bool { self.cmp(rhs) == Ordering::Equal } } cxx-build-1.0.141/src/cfg.rs000064400000000000000000000413671046102023000135760ustar 00000000000000use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::path::Path; /// Build configuration. See [CFG]. pub struct Cfg<'a> { /// See [`CFG.include_prefix`][CFG#cfginclude_prefix]. pub include_prefix: &'a str, /// See [`CFG.exported_header_dirs`][CFG#cfgexported_header_dirs]. pub exported_header_dirs: Vec<&'a Path>, /// See [`CFG.exported_header_prefixes`][CFG#cfgexported_header_prefixes]. pub exported_header_prefixes: Vec<&'a str>, /// See [`CFG.exported_header_links`][CFG#cfgexported_header_links]. pub exported_header_links: Vec<&'a str>, /// See [`CFG.doxygen`][CFG#cfgdoxygen]. pub doxygen: bool, marker: PhantomData<*const ()>, // !Send + !Sync } /// Global configuration of the current build. /// ///
/// ///
&str
/// /// ## **`CFG.include_prefix`** /// /// The prefix at which C++ code from your crate as well as directly dependent /// crates can access the code generated during this build. /// /// By default, the `include_prefix` is equal to the name of the current crate. /// That means if your crate is called `demo` and has Rust source files in a /// *src/* directory and maybe some handwritten C++ header files in an /// *include/* directory, then the current crate as well as downstream crates /// might include them as follows: /// /// ``` /// # const _: &str = stringify! { /// // include one of the handwritten headers: /// #include "demo/include/wow.h" /// /// // include a header generated from Rust cxx::bridge: /// #include "demo/src/lib.rs.h" /// # }; /// ``` /// /// By modifying `CFG.include_prefix` we can substitute a prefix that is /// different from the crate name if desired. Here we'll change it to /// `"path/to"` which will make import paths take the form /// `"path/to/include/wow.h"` and `"path/to/src/lib.rs.h"`. /// /// ```no_run /// // build.rs /// /// use cxx_build::CFG; /// /// fn main() { /// CFG.include_prefix = "path/to"; /// /// cxx_build::bridge("src/lib.rs") /// .file("src/demo.cc") // probably contains `#include "path/to/src/lib.rs.h"` /// /* ... */ /// .compile("demo"); /// } /// ``` /// /// Note that cross-crate imports are only made available between **direct /// dependencies**. Another crate must directly depend on your crate in order to /// #include its headers; a transitive dependency is not sufficient. /// Additionally, headers from a direct dependency are only importable if the /// dependency's Cargo.toml manifest contains a `links` key. If not, its headers /// will not be importable from outside of the same crate. /// ///
/// ///
Vec<&Path>
/// /// ## **`CFG.exported_header_dirs`** /// /// A vector of absolute paths. The current crate, directly dependent crates, /// and further crates to which this crate's headers are exported (see below) /// will be able to `#include` headers from these directories. /// /// Adding a directory to `exported_header_dirs` is similar to adding it to the /// current build via the `cc` crate's [`Build::include`][cc::Build::include], /// but *also* makes the directory available to downstream crates that want to /// `#include` one of the headers from your crate. If the dir were added only /// using `Build::include`, the downstream crate including your header would /// need to manually add the same directory to their own build as well. /// /// When using `exported_header_dirs`, your crate must also set a `links` key /// for itself in Cargo.toml. See [*the `links` manifest key*][links]. The /// reason is that Cargo imposes no ordering on the execution of build scripts /// without a `links` key, which means the downstream crate's build script might /// execute before yours decides what to put into `exported_header_dirs`. /// /// [links]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key /// /// ### Example /// /// One of your crate's headers wants to include a system library, such as /// `#include "Python.h"`. /// /// ```no_run /// // build.rs /// /// use cxx_build::CFG; /// use std::path::PathBuf; /// /// fn main() { /// let python3 = pkg_config::probe_library("python3").unwrap(); /// let python_include_paths = python3.include_paths.iter().map(PathBuf::as_path); /// CFG.exported_header_dirs.extend(python_include_paths); /// /// cxx_build::bridge("src/bridge.rs").compile("demo"); /// } /// ``` /// /// ### Example /// /// Your crate wants to rearrange the headers that it exports vs how they're /// laid out locally inside the crate's source directory. /// /// Suppose the crate as published contains a file at `./include/myheader.h` but /// wants it available to downstream crates as `#include "foo/v1/public.h"`. /// /// ```no_run /// // build.rs /// /// use cxx_build::CFG; /// use std::path::Path; /// use std::{env, fs}; /// /// fn main() { /// let out_dir = env::var_os("OUT_DIR").unwrap(); /// let headers = Path::new(&out_dir).join("headers"); /// CFG.exported_header_dirs.push(&headers); /// /// // We contain `include/myheader.h` locally, but /// // downstream will use `#include "foo/v1/public.h"` /// let foo = headers.join("foo").join("v1"); /// fs::create_dir_all(&foo).unwrap(); /// fs::copy("include/myheader.h", foo.join("public.h")).unwrap(); /// /// cxx_build::bridge("src/bridge.rs").compile("demo"); /// } /// ``` /// ///



/// ///
Vec<&str>
/// /// ## **`CFG.exported_header_prefixes`** /// /// Vector of strings. These each refer to the `include_prefix` of one of your /// direct dependencies, or a prefix thereof. They describe which of your /// dependencies participate in your crate's C++ public API, as opposed to /// private use by your crate's implementation. /// /// As a general rule, if one of your headers `#include`s something from one of /// your dependencies, you need to put that dependency's `include_prefix` into /// `CFG.exported_header_prefixes` (*or* their `links` key into /// `CFG.exported_header_links`; see below). On the other hand if only your C++ /// implementation files and *not* your headers are importing from the /// dependency, you do not export that dependency. /// /// The significance of exported headers is that if downstream code (crate 𝒜) /// contains an `#include` of a header from your crate (ℬ) and your header /// contains an `#include` of something from your dependency (𝒞), the exported /// dependency 𝒞 becomes available during the downstream crate 𝒜's build. /// Otherwise the downstream crate 𝒜 doesn't know about 𝒞 and wouldn't be able /// to find what header your header is referring to, and would fail to build. /// /// When using `exported_header_prefixes`, your crate must also set a `links` /// key for itself in Cargo.toml. /// /// ### Example /// /// Suppose you have a crate with 5 direct dependencies and the `include_prefix` /// for each one are: /// /// - "crate0" /// - "group/api/crate1" /// - "group/api/crate2" /// - "group/api/contrib/crate3" /// - "detail/crate4" /// /// Your header involves types from the first four so we re-export those as part /// of your public API, while crate4 is only used internally by your cc file not /// your header, so we do not export: /// /// ```no_run /// // build.rs /// /// use cxx_build::CFG; /// /// fn main() { /// CFG.exported_header_prefixes = vec!["crate0", "group/api"]; /// /// cxx_build::bridge("src/bridge.rs") /// .file("src/impl.cc") /// .compile("demo"); /// } /// ``` /// ///



/// ///
Vec<&str>
/// /// ## **`CFG.exported_header_links`** /// /// Vector of strings. These each refer to the `links` attribute ([*the `links` /// manifest key*][links]) of one of your crate's direct dependencies. /// /// This achieves an equivalent result to `CFG.exported_header_prefixes` by /// re-exporting a dependency as part of your crate's public API, except with /// finer grained control for cases when multiple crates might be sharing the /// same `include_prefix` and you'd like to export some but not others. Links /// attributes are guaranteed to be unique identifiers by Cargo. /// /// When using `exported_header_links`, your crate must also set a `links` key /// for itself in Cargo.toml. /// /// ### Example /// /// ```no_run /// // build.rs /// /// use cxx_build::CFG; /// /// fn main() { /// CFG.exported_header_links.push("git2"); /// /// cxx_build::bridge("src/bridge.rs").compile("demo"); /// } /// ``` /// ///



/// ///
bool
/// /// ## **`CFG.doxygen`** /// /// Boolean. Whether to propagate Rust documentation from inside the cxx::bridge /// module as Doxygen-style comments in the generated C++ header. /// /// Documentation on the following are supported: /// /// - shared structs, and fields of shared structs /// - shared enums, and their variants /// - extern "Rust" opaque types /// - extern "Rust" functions, including methods/member functions /// /// ### Example /// /// ```no_run /// // build.rs /// /// use cxx_build::CFG; /// /// fn main() { /// CFG.doxygen = true; /// /// cxx_build::bridge("src/bridge.rs").compile("demo"); /// } /// ``` /// /// ```rust /// // src/bridge.rs /// /// #[cxx::bridge] /// mod ffi { /// /// documentation of MyStruct /// pub struct MyStruct { /// /// documentation of the struct field /// lol: String, /// } /// /// extern "Rust" { /// /// documentation of MyType /// type MyType; /// /// /// function documentation /// fn asdf() -> bool; /// } /// } /// # /// # pub struct MyType; /// # fn asdf() -> bool { true } /// # fn main() {} /// ``` /// /// With `CFG.doxygen` enabled, the generated C++ header through which /// downstream C++ code will be able to access these shared structs and extern /// "Rust" signatures will have the Rust documentation comments propagated as /// Doxygen-style comments: /// /// ```cpp /// /// documentation of MyStruct /// struct MyStruct final { /// /// documentation of the struct field /// ::rust::String lol; /// … /// }; /// ``` /// /// Otherwise by default (without `CFG.doxygen`) they'll just be `//` comments. #[cfg(doc)] pub static mut CFG: Cfg = Cfg { include_prefix: "", exported_header_dirs: Vec::new(), exported_header_prefixes: Vec::new(), exported_header_links: Vec::new(), doxygen: false, marker: PhantomData, }; impl<'a> Debug for Cfg<'a> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let Self { include_prefix, exported_header_dirs, exported_header_prefixes, exported_header_links, doxygen, marker: _, } = self; formatter .debug_struct("Cfg") .field("include_prefix", include_prefix) .field("exported_header_dirs", exported_header_dirs) .field("exported_header_prefixes", exported_header_prefixes) .field("exported_header_links", exported_header_links) .field("doxygen", doxygen) .finish() } } #[cfg(not(doc))] pub use self::r#impl::Cfg::CFG; #[cfg(not(doc))] mod r#impl { use crate::intern::{intern, InternedString}; use crate::syntax::map::UnorderedMap as Map; use crate::vec::{self, InternedVec as _}; use std::cell::RefCell; use std::fmt::{self, Debug}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::sync::{OnceLock, PoisonError, RwLock}; struct CurrentCfg { include_prefix: InternedString, exported_header_dirs: Vec, exported_header_prefixes: Vec, exported_header_links: Vec, doxygen: bool, } impl CurrentCfg { fn default() -> Self { let include_prefix = crate::env_os("CARGO_PKG_NAME") .map(|pkg| intern(&pkg.to_string_lossy())) .unwrap_or_default(); let exported_header_dirs = Vec::new(); let exported_header_prefixes = Vec::new(); let exported_header_links = Vec::new(); let doxygen = false; CurrentCfg { include_prefix, exported_header_dirs, exported_header_prefixes, exported_header_links, doxygen, } } } fn current() -> &'static RwLock { static CURRENT: OnceLock> = OnceLock::new(); CURRENT.get_or_init(|| RwLock::new(CurrentCfg::default())) } thread_local! { // FIXME: If https://github.com/rust-lang/rust/issues/77425 is resolved, // we can delete this thread local side table and instead make each CFG // instance directly own the associated super::Cfg. // // #[allow(const_item_mutation)] // pub const CFG: Cfg = Cfg { // cfg: AtomicPtr::new(ptr::null_mut()), // }; // pub struct Cfg { // cfg: AtomicPtr, // } // static CONST_DEREFS: RefCell>>> = RefCell::default(); } #[derive(Eq, PartialEq, Hash)] struct Handle(*const Cfg<'static>); impl<'a> Cfg<'a> { fn current() -> super::Cfg<'a> { let current = current().read().unwrap_or_else(PoisonError::into_inner); let include_prefix = current.include_prefix.str(); let exported_header_dirs = current.exported_header_dirs.vec(); let exported_header_prefixes = current.exported_header_prefixes.vec(); let exported_header_links = current.exported_header_links.vec(); let doxygen = current.doxygen; super::Cfg { include_prefix, exported_header_dirs, exported_header_prefixes, exported_header_links, doxygen, marker: PhantomData, } } const fn handle(self: &Cfg<'a>) -> Handle { Handle(<*const Cfg>::cast(self)) } } // Since super::Cfg is !Send and !Sync, all Cfg are thread local and will // drop on the same thread where they were created. pub enum Cfg<'a> { Mut(super::Cfg<'a>), CFG, } impl<'a> Debug for Cfg<'a> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if let Cfg::Mut(cfg) = self { Debug::fmt(cfg, formatter) } else { Debug::fmt(&Cfg::current(), formatter) } } } impl<'a> Deref for Cfg<'a> { type Target = super::Cfg<'a>; fn deref(&self) -> &Self::Target { if let Cfg::Mut(cfg) = self { cfg } else { let cfg = CONST_DEREFS.with(|derefs| -> *mut super::Cfg { &mut **derefs .borrow_mut() .entry(self.handle()) .or_insert_with(|| Box::new(Cfg::current())) }); unsafe { &mut *cfg } } } } impl<'a> DerefMut for Cfg<'a> { fn deref_mut(&mut self) -> &mut Self::Target { if let Cfg::CFG = self { CONST_DEREFS.with(|derefs| derefs.borrow_mut().remove(&self.handle())); *self = Cfg::Mut(Cfg::current()); } match self { Cfg::Mut(cfg) => cfg, Cfg::CFG => unreachable!(), } } } impl<'a> Drop for Cfg<'a> { fn drop(&mut self) { if let Cfg::Mut(cfg) = self { let super::Cfg { include_prefix, exported_header_dirs, exported_header_prefixes, exported_header_links, doxygen, marker: _, } = cfg; let mut current = current().write().unwrap_or_else(PoisonError::into_inner); current.include_prefix = intern(include_prefix); current.exported_header_dirs = vec::intern(exported_header_dirs); current.exported_header_prefixes = vec::intern(exported_header_prefixes); current.exported_header_links = vec::intern(exported_header_links); current.doxygen = *doxygen; } else { CONST_DEREFS.with(|derefs| derefs.borrow_mut().remove(&self.handle())); } } } } cxx-build-1.0.141/src/deps.rs000064400000000000000000000071311046102023000137610ustar 00000000000000use std::collections::BTreeMap; use std::env; use std::ffi::OsString; use std::path::PathBuf; #[derive(Default)] pub(crate) struct Crate { pub include_prefix: Option, pub links: Option, pub header_dirs: Vec, } pub(crate) struct HeaderDir { pub exported: bool, pub path: PathBuf, } impl Crate { pub(crate) fn print_to_cargo(&self) { if let Some(include_prefix) = &self.include_prefix { println!( "cargo:CXXBRIDGE_PREFIX={}", include_prefix.to_string_lossy(), ); } if let Some(links) = &self.links { println!("cargo:CXXBRIDGE_LINKS={}", links.to_string_lossy()); } for (i, header_dir) in self.header_dirs.iter().enumerate() { if header_dir.exported { println!( "cargo:CXXBRIDGE_DIR{}={}", i, header_dir.path.to_string_lossy(), ); } } } } pub(crate) fn direct_dependencies() -> Vec { let mut crates: BTreeMap = BTreeMap::new(); let mut exported_header_dirs: BTreeMap> = BTreeMap::new(); // Only variables set from a build script of direct dependencies are // observable. That's exactly what we want! Your crate needs to declare a // direct dependency on the other crate in order to be able to #include its // headers. // // Also, they're only observable if the dependency's manifest contains a // `links` key. This is important because Cargo imposes no ordering on the // execution of build scripts without a `links` key. When exposing a // generated header for the current crate to #include, we need to be sure // the dependency's build script has already executed and emitted that // generated header. // // References: // - https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key // - https://doc.rust-lang.org/cargo/reference/build-script-examples.html#using-another-sys-crate for (k, v) in env::vars_os() { let mut k = k.to_string_lossy().into_owned(); if !k.starts_with("DEP_") { continue; } if k.ends_with("_CXXBRIDGE_PREFIX") { k.truncate(k.len() - "_CXXBRIDGE_PREFIX".len()); crates.entry(k).or_default().include_prefix = Some(PathBuf::from(v)); continue; } if k.ends_with("_CXXBRIDGE_LINKS") { k.truncate(k.len() - "_CXXBRIDGE_LINKS".len()); crates.entry(k).or_default().links = Some(v); continue; } let without_counter = k.trim_end_matches(|ch: char| ch.is_ascii_digit()); let counter_len = k.len() - without_counter.len(); if counter_len == 0 || !without_counter.ends_with("_CXXBRIDGE_DIR") { continue; } let sort_key = k[k.len() - counter_len..] .parse::() .unwrap_or(usize::MAX); k.truncate(k.len() - counter_len - "_CXXBRIDGE_DIR".len()); exported_header_dirs .entry(k) .or_default() .push((sort_key, PathBuf::from(v))); } for (k, mut dirs) in exported_header_dirs { dirs.sort_by_key(|(sort_key, _dir)| *sort_key); crates .entry(k) .or_default() .header_dirs .extend(dirs.into_iter().map(|(_sort_key, dir)| HeaderDir { exported: true, path: dir, })); } crates.into_iter().map(|entry| entry.1).collect() } cxx-build-1.0.141/src/error.rs000064400000000000000000000062011046102023000141540ustar 00000000000000use crate::cfg::CFG; use crate::gen::fs; use std::error::Error as StdError; use std::ffi::OsString; use std::fmt::{self, Display}; use std::path::Path; pub(super) type Result = std::result::Result; #[derive(Debug)] pub(super) enum Error { NoEnv(OsString), Fs(fs::Error), ExportedDirNotAbsolute(&'static Path), ExportedEmptyPrefix, ExportedDirsWithoutLinks, ExportedPrefixesWithoutLinks, ExportedLinksWithoutLinks, UnusedExportedPrefix(&'static str), UnusedExportedLinks(&'static str), } macro_rules! expr { ($expr:expr) => {{ let _ = $expr; // ensure it doesn't fall out of sync with CFG definition stringify!($expr) }}; } const LINKS_DOCUMENTATION: &str = "https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key"; impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::NoEnv(var) => { write!(f, "missing {} environment variable", var.to_string_lossy()) } Error::Fs(err) => err.fmt(f), Error::ExportedDirNotAbsolute(path) => write!( f, "element of {} must be absolute path, but was: {:?}", expr!(CFG.exported_header_dirs), path, ), Error::ExportedEmptyPrefix => write!( f, "element of {} must not be empty string", expr!(CFG.exported_header_prefixes), ), Error::ExportedDirsWithoutLinks => write!( f, "if {} is nonempty then `links` needs to be set in Cargo.toml; see {}", expr!(CFG.exported_header_dirs), LINKS_DOCUMENTATION, ), Error::ExportedPrefixesWithoutLinks => write!( f, "if {} is nonempty then `links` needs to be set in Cargo.toml; see {}", expr!(CFG.exported_header_prefixes), LINKS_DOCUMENTATION, ), Error::ExportedLinksWithoutLinks => write!( f, "if {} is nonempty then `links` needs to be set in Cargo.toml; see {}", expr!(CFG.exported_header_links), LINKS_DOCUMENTATION, ), Error::UnusedExportedPrefix(unused) => write!( f, "unused element in {}: {:?} does not match the include prefix of any direct dependency", expr!(CFG.exported_header_prefixes), unused, ), Error::UnusedExportedLinks(unused) => write!( f, "unused element in {}: {:?} does not match the `links` attribute any direct dependency", expr!(CFG.exported_header_links), unused, ), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { Error::Fs(err) => err.source(), _ => None, } } } impl From for Error { fn from(err: fs::Error) -> Self { Error::Fs(err) } } cxx-build-1.0.141/src/gen/block.rs000064400000000000000000000023671046102023000146770ustar 00000000000000use proc_macro2::Ident; #[derive(Copy, Clone, PartialEq, Debug)] pub(crate) enum Block<'a> { AnonymousNamespace, Namespace(&'static str), UserDefinedNamespace(&'a Ident), InlineNamespace(&'static str), ExternC, } impl<'a> Block<'a> { pub(crate) fn write_begin(self, out: &mut String) { if let Block::InlineNamespace(_) = self { out.push_str("inline "); } self.write_common(out); out.push_str(" {\n"); } pub(crate) fn write_end(self, out: &mut String) { out.push_str("} // "); self.write_common(out); out.push('\n'); } fn write_common(self, out: &mut String) { match self { Block::AnonymousNamespace => out.push_str("namespace"), Block::Namespace(name) => { out.push_str("namespace "); out.push_str(name); } Block::UserDefinedNamespace(name) => { out.push_str("namespace "); out.push_str(&name.to_string()); } Block::InlineNamespace(name) => { out.push_str("namespace "); out.push_str(name); } Block::ExternC => out.push_str("extern \"C\""), } } } cxx-build-1.0.141/src/gen/builtin.rs000064400000000000000000000321731046102023000152510ustar 00000000000000use crate::gen::block::Block; use crate::gen::ifndef; use crate::gen::out::{Content, OutFile}; #[derive(Default, PartialEq)] pub(crate) struct Builtins<'a> { pub panic: bool, pub rust_string: bool, pub rust_str: bool, pub rust_slice: bool, pub rust_box: bool, pub rust_vec: bool, pub rust_fn: bool, pub rust_isize: bool, pub opaque: bool, pub layout: bool, pub unsafe_bitcopy: bool, pub unsafe_bitcopy_t: bool, pub rust_error: bool, pub manually_drop: bool, pub maybe_uninit: bool, pub trycatch: bool, pub ptr_len: bool, pub repr_fat: bool, pub rust_str_new_unchecked: bool, pub rust_str_repr: bool, pub rust_slice_new: bool, pub rust_slice_repr: bool, pub relocatable: bool, pub relocatable_or_array: bool, pub friend_impl: bool, pub is_complete: bool, pub destroy: bool, pub deleter_if: bool, pub content: Content<'a>, } impl<'a> Builtins<'a> { pub(crate) fn new() -> Self { Builtins::default() } } pub(super) fn write(out: &mut OutFile) { if out.builtin == Default::default() { return; } let include = &mut out.include; let builtin = &mut out.builtin; let out = &mut builtin.content; if builtin.rust_string { include.array = true; include.cstdint = true; include.string = true; } if builtin.rust_str { include.array = true; include.cstdint = true; include.string = true; builtin.friend_impl = true; } if builtin.rust_vec { include.algorithm = true; include.array = true; include.cassert = true; include.cstddef = true; include.cstdint = true; include.initializer_list = true; include.iterator = true; include.new = true; include.stdexcept = true; include.type_traits = true; include.utility = true; builtin.panic = true; builtin.rust_slice = true; builtin.unsafe_bitcopy_t = true; } if builtin.rust_slice { include.array = true; include.cassert = true; include.cstddef = true; include.cstdint = true; include.iterator = true; include.ranges = true; include.stdexcept = true; include.type_traits = true; builtin.friend_impl = true; builtin.layout = true; builtin.panic = true; } if builtin.rust_box { include.new = true; include.type_traits = true; include.utility = true; } if builtin.rust_fn { include.utility = true; } if builtin.rust_error { include.exception = true; builtin.friend_impl = true; } if builtin.rust_isize { include.basetsd = true; include.sys_types = true; } if builtin.relocatable_or_array { include.cstddef = true; builtin.relocatable = true; } if builtin.relocatable { include.type_traits = true; } if builtin.layout { include.type_traits = true; include.cstddef = true; builtin.is_complete = true; } if builtin.is_complete { include.cstddef = true; include.type_traits = true; } if builtin.unsafe_bitcopy { builtin.unsafe_bitcopy_t = true; } if builtin.trycatch { builtin.ptr_len = true; } out.begin_block(Block::Namespace("rust")); out.begin_block(Block::InlineNamespace("cxxbridge1")); let cxx_header = include.has_cxx_header(); if !cxx_header { writeln!(out, "// #include \"rust/cxx.h\""); ifndef::write(out, builtin.panic, "CXXBRIDGE1_PANIC"); if builtin.rust_string { out.next_section(); writeln!(out, "struct unsafe_bitcopy_t;"); } if builtin.friend_impl { out.begin_block(Block::AnonymousNamespace); writeln!(out, "template "); writeln!(out, "class impl;"); out.end_block(Block::AnonymousNamespace); } out.next_section(); if builtin.rust_str && !builtin.rust_string { writeln!(out, "class String;"); } if builtin.layout && !builtin.opaque { writeln!(out, "class Opaque;"); } if builtin.rust_slice { out.next_section(); writeln!(out, "template "); writeln!(out, "::std::size_t size_of();"); writeln!(out, "template "); writeln!(out, "::std::size_t align_of();"); } ifndef::write(out, builtin.rust_string, "CXXBRIDGE1_RUST_STRING"); ifndef::write(out, builtin.rust_str, "CXXBRIDGE1_RUST_STR"); ifndef::write(out, builtin.rust_slice, "CXXBRIDGE1_RUST_SLICE"); ifndef::write(out, builtin.rust_box, "CXXBRIDGE1_RUST_BOX"); ifndef::write(out, builtin.unsafe_bitcopy_t, "CXXBRIDGE1_RUST_BITCOPY_T"); ifndef::write(out, builtin.unsafe_bitcopy, "CXXBRIDGE1_RUST_BITCOPY"); ifndef::write(out, builtin.rust_vec, "CXXBRIDGE1_RUST_VEC"); ifndef::write(out, builtin.rust_fn, "CXXBRIDGE1_RUST_FN"); ifndef::write(out, builtin.rust_error, "CXXBRIDGE1_RUST_ERROR"); ifndef::write(out, builtin.rust_isize, "CXXBRIDGE1_RUST_ISIZE"); ifndef::write(out, builtin.opaque, "CXXBRIDGE1_RUST_OPAQUE"); ifndef::write(out, builtin.is_complete, "CXXBRIDGE1_IS_COMPLETE"); ifndef::write(out, builtin.layout, "CXXBRIDGE1_LAYOUT"); ifndef::write(out, builtin.relocatable, "CXXBRIDGE1_RELOCATABLE"); } if builtin.rust_str_new_unchecked { out.next_section(); writeln!(out, "class Str::uninit {{}};"); writeln!(out, "inline Str::Str(uninit) noexcept {{}}"); } if builtin.rust_slice_new { out.next_section(); writeln!(out, "template "); writeln!(out, "class Slice::uninit {{}};"); writeln!(out, "template "); writeln!(out, "inline Slice::Slice(uninit) noexcept {{}}"); } out.begin_block(Block::Namespace("repr")); if builtin.repr_fat { include.array = true; include.cstdint = true; out.next_section(); writeln!(out, "using Fat = ::std::array<::std::uintptr_t, 2>;"); } if builtin.ptr_len { include.cstddef = true; out.next_section(); writeln!(out, "struct PtrLen final {{"); writeln!(out, " void *ptr;"); writeln!(out, " ::std::size_t len;"); writeln!(out, "}};"); } out.end_block(Block::Namespace("repr")); out.begin_block(Block::Namespace("detail")); if builtin.maybe_uninit { include.cstddef = true; include.new = true; out.next_section(); writeln!(out, "template "); writeln!(out, "struct operator_new {{"); writeln!( out, " void *operator()(::std::size_t sz) {{ return ::operator new(sz); }}", ); writeln!(out, "}};"); out.next_section(); writeln!(out, "template "); writeln!( out, "struct operator_new {{", ); writeln!( out, " void *operator()(::std::size_t sz) {{ return T::operator new(sz); }}", ); writeln!(out, "}};"); } if builtin.trycatch { include.string = true; out.next_section(); writeln!(out, "class Fail final {{"); writeln!(out, " ::rust::repr::PtrLen &throw$;"); writeln!(out, "public:"); writeln!( out, " Fail(::rust::repr::PtrLen &throw$) noexcept : throw$(throw$) {{}}", ); writeln!(out, " void operator()(char const *) noexcept;"); writeln!(out, " void operator()(std::string const &) noexcept;"); writeln!(out, "}};"); } out.end_block(Block::Namespace("detail")); if builtin.manually_drop { out.next_section(); include.utility = true; writeln!(out, "template "); writeln!(out, "union ManuallyDrop {{"); writeln!(out, " T value;"); writeln!( out, " ManuallyDrop(T &&value) : value(::std::move(value)) {{}}", ); writeln!(out, " ~ManuallyDrop() {{}}"); writeln!(out, "}};"); } if builtin.maybe_uninit { include.cstddef = true; out.next_section(); writeln!(out, "template "); writeln!(out, "union MaybeUninit {{"); writeln!(out, " T value;"); writeln!( out, " void *operator new(::std::size_t sz) {{ return detail::operator_new{{}}(sz); }}", ); writeln!(out, " MaybeUninit() {{}}"); writeln!(out, " ~MaybeUninit() {{}}"); writeln!(out, "}};"); } out.begin_block(Block::AnonymousNamespace); if builtin.rust_str_new_unchecked || builtin.rust_str_repr { out.next_section(); writeln!(out, "template <>"); writeln!(out, "class impl final {{"); writeln!(out, "public:"); if builtin.rust_str_new_unchecked { writeln!( out, " static Str new_unchecked(repr::Fat repr) noexcept {{", ); writeln!(out, " Str str = Str::uninit{{}};"); writeln!(out, " str.repr = repr;"); writeln!(out, " return str;"); writeln!(out, " }}"); } if builtin.rust_str_repr { writeln!(out, " static repr::Fat repr(Str str) noexcept {{"); writeln!(out, " return str.repr;"); writeln!(out, " }}"); } writeln!(out, "}};"); } if builtin.rust_slice_new || builtin.rust_slice_repr { out.next_section(); writeln!(out, "template "); writeln!(out, "class impl> final {{"); writeln!(out, "public:"); if builtin.rust_slice_new { writeln!(out, " static Slice slice(repr::Fat repr) noexcept {{"); writeln!(out, " Slice slice = typename Slice::uninit{{}};"); writeln!(out, " slice.repr = repr;"); writeln!(out, " return slice;"); writeln!(out, " }}"); } if builtin.rust_slice_repr { writeln!(out, " static repr::Fat repr(Slice slice) noexcept {{"); writeln!(out, " return slice.repr;"); writeln!(out, " }}"); } writeln!(out, "}};"); } if builtin.rust_error { out.next_section(); writeln!(out, "template <>"); writeln!(out, "class impl final {{"); writeln!(out, "public:"); writeln!(out, " static Error error(repr::PtrLen repr) noexcept {{"); writeln!(out, " Error error;"); writeln!(out, " error.msg = static_cast(repr.ptr);"); writeln!(out, " error.len = repr.len;"); writeln!(out, " return error;"); writeln!(out, " }}"); writeln!(out, "}};"); } if builtin.destroy { out.next_section(); writeln!(out, "template "); writeln!(out, "void destroy(T *ptr) {{"); writeln!(out, " ptr->~T();"); writeln!(out, "}}"); } if builtin.deleter_if { out.next_section(); writeln!(out, "template struct deleter_if {{"); writeln!(out, " template void operator()(T *) {{}}"); writeln!(out, "}};"); out.next_section(); writeln!(out, "template <> struct deleter_if {{"); writeln!( out, " template void operator()(T *ptr) {{ ptr->~T(); }}", ); writeln!(out, "}};"); } if builtin.relocatable_or_array { out.next_section(); writeln!(out, "template "); writeln!(out, "struct IsRelocatableOrArray : IsRelocatable {{}};"); writeln!(out, "template "); writeln!( out, "struct IsRelocatableOrArray : IsRelocatableOrArray {{}};", ); } out.end_block(Block::AnonymousNamespace); out.end_block(Block::InlineNamespace("cxxbridge1")); if builtin.trycatch { out.begin_block(Block::Namespace("behavior")); include.exception = true; include.type_traits = true; include.utility = true; writeln!(out, "class missing {{}};"); writeln!(out, "missing trycatch(...);"); writeln!(out); writeln!(out, "template "); writeln!(out, "static typename ::std::enable_if<"); writeln!( out, " ::std::is_same(), ::std::declval())),", ); writeln!(out, " missing>::value>::type"); writeln!(out, "trycatch(Try &&func, Fail &&fail) noexcept try {{"); writeln!(out, " func();"); writeln!(out, "}} catch (::std::exception const &e) {{"); writeln!(out, " fail(e.what());"); writeln!(out, "}}"); out.end_block(Block::Namespace("behavior")); } out.end_block(Block::Namespace("rust")); } cxx-build-1.0.141/src/gen/cfg.rs000064400000000000000000000076271046102023000143500ustar 00000000000000use crate::gen::{CfgEvaluator, CfgResult}; use crate::syntax::cfg::CfgExpr; use crate::syntax::report::Errors; use crate::syntax::Api; use quote::quote; use std::collections::BTreeSet as Set; use syn::{Error, LitStr}; pub(super) struct UnsupportedCfgEvaluator; impl CfgEvaluator for UnsupportedCfgEvaluator { fn eval(&self, name: &str, value: Option<&str>) -> CfgResult { let _ = name; let _ = value; let msg = "cfg attribute is not supported".to_owned(); CfgResult::Undetermined { msg } } } pub(super) fn strip( cx: &mut Errors, cfg_errors: &mut Set, cfg_evaluator: &dyn CfgEvaluator, apis: &mut Vec, ) { apis.retain(|api| eval(cx, cfg_errors, cfg_evaluator, api.cfg())); for api in apis { match api { Api::Struct(strct) => strct .fields .retain(|field| eval(cx, cfg_errors, cfg_evaluator, &field.cfg)), Api::Enum(enm) => enm .variants .retain(|variant| eval(cx, cfg_errors, cfg_evaluator, &variant.cfg)), _ => {} } } } pub(super) fn eval( cx: &mut Errors, cfg_errors: &mut Set, cfg_evaluator: &dyn CfgEvaluator, expr: &CfgExpr, ) -> bool { match try_eval(cfg_evaluator, expr) { Ok(value) => value, Err(errors) => { for error in errors { if cfg_errors.insert(error.to_string()) { cx.push(error); } } false } } } fn try_eval(cfg_evaluator: &dyn CfgEvaluator, expr: &CfgExpr) -> Result> { match expr { CfgExpr::Unconditional => Ok(true), CfgExpr::Eq(ident, string) => { let key = ident.to_string(); let value = string.as_ref().map(LitStr::value); match cfg_evaluator.eval(&key, value.as_deref()) { CfgResult::True => Ok(true), CfgResult::False => Ok(false), CfgResult::Undetermined { msg } => { let span = quote!(#ident #string); Err(vec![Error::new_spanned(span, msg)]) } } } CfgExpr::All(list) => { let mut all_errors = Vec::new(); for subexpr in list { match try_eval(cfg_evaluator, subexpr) { Ok(true) => {} Ok(false) => return Ok(false), Err(errors) => all_errors.extend(errors), } } if all_errors.is_empty() { Ok(true) } else { Err(all_errors) } } CfgExpr::Any(list) => { let mut all_errors = Vec::new(); for subexpr in list { match try_eval(cfg_evaluator, subexpr) { Ok(true) => return Ok(true), Ok(false) => {} Err(errors) => all_errors.extend(errors), } } if all_errors.is_empty() { Ok(false) } else { Err(all_errors) } } CfgExpr::Not(subexpr) => match try_eval(cfg_evaluator, subexpr) { Ok(value) => Ok(!value), Err(errors) => Err(errors), }, } } impl Api { fn cfg(&self) -> &CfgExpr { match self { Api::Include(include) => &include.cfg, Api::Struct(strct) => &strct.cfg, Api::Enum(enm) => &enm.cfg, Api::CxxType(ety) | Api::RustType(ety) => &ety.cfg, Api::CxxFunction(efn) | Api::RustFunction(efn) => &efn.cfg, Api::TypeAlias(alias) => &alias.cfg, Api::Impl(imp) => &imp.cfg, } } } impl From for CfgResult { fn from(value: bool) -> Self { if value { CfgResult::True } else { CfgResult::False } } } cxx-build-1.0.141/src/gen/check.rs000064400000000000000000000016341046102023000146560ustar 00000000000000use crate::gen::Opt; use crate::syntax::report::Errors; use crate::syntax::{error, Api}; use quote::{quote, quote_spanned}; use std::path::{Component, Path}; pub(super) use crate::syntax::check::{typecheck, Generator}; pub(super) fn precheck(cx: &mut Errors, apis: &[Api], opt: &Opt) { if !opt.allow_dot_includes { check_dot_includes(cx, apis); } } fn check_dot_includes(cx: &mut Errors, apis: &[Api]) { for api in apis { if let Api::Include(include) = api { let first_component = Path::new(&include.path).components().next(); if let Some(Component::CurDir | Component::ParentDir) = first_component { let begin = quote_spanned!(include.begin_span=> .); let end = quote_spanned!(include.end_span=> .); let span = quote!(#begin #end); cx.error(span, error::DOT_INCLUDE.msg); } } } } cxx-build-1.0.141/src/gen/error.rs000064400000000000000000000120311046102023000147230ustar 00000000000000use crate::gen::fs; use crate::syntax; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::files::SimpleFiles; use codespan_reporting::term::termcolor::{ColorChoice, StandardStream, WriteColor}; use codespan_reporting::term::{self, Config}; use std::borrow::Cow; use std::error::Error as StdError; use std::fmt::{self, Display}; use std::io::{self, Write}; use std::ops::Range; use std::path::{Path, PathBuf}; use std::process; use std::str::Utf8Error; pub(crate) type Result = std::result::Result; #[derive(Debug)] pub(crate) enum Error { NoBridgeMod, Fs(fs::Error), Utf8(PathBuf, Utf8Error), Syn(syn::Error), } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::NoBridgeMod => write!(f, "no #[cxx::bridge] module found"), Error::Fs(err) => err.fmt(f), Error::Utf8(path, _) => write!(f, "Failed to read file `{}`", path.display()), Error::Syn(err) => err.fmt(f), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { Error::Fs(err) => err.source(), Error::Utf8(_, err) => Some(err), Error::Syn(err) => err.source(), Error::NoBridgeMod => None, } } } impl From for Error { fn from(err: fs::Error) -> Self { Error::Fs(err) } } impl From for Error { fn from(err: syn::Error) -> Self { Error::Syn(err) } } pub(super) fn format_err(path: &Path, source: &str, error: Error) -> ! { match error { Error::Syn(syn_error) => { let syn_error = sort_syn_errors(syn_error); let writer = StandardStream::stderr(ColorChoice::Auto); let ref mut stderr = writer.lock(); for error in syn_error { let _ = writeln!(stderr); display_syn_error(stderr, path, source, error); } } Error::NoBridgeMod => { let _ = writeln!( io::stderr(), "cxxbridge: no #[cxx::bridge] module found in {}", path.display(), ); } _ => { let _ = writeln!(io::stderr(), "cxxbridge: {}", report(error)); } } process::exit(1); } pub(crate) fn report(error: impl StdError) -> impl Display { struct Report(E); impl Display for Report { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "{}", self.0)?; let mut error: &dyn StdError = &self.0; while let Some(cause) = error.source() { write!(formatter, "\n\nCaused by:\n {}", cause)?; error = cause; } Ok(()) } } Report(error) } fn sort_syn_errors(error: syn::Error) -> Vec { let mut errors: Vec<_> = error.into_iter().collect(); errors.sort_by_key(|e| { let start = e.span().start(); (start.line, start.column) }); errors } fn display_syn_error(stderr: &mut dyn WriteColor, path: &Path, source: &str, error: syn::Error) { let span = error.span(); let start = span.start(); let end = span.end(); let mut start_offset = 0; for _ in 1..start.line { start_offset += source[start_offset..].find('\n').unwrap() + 1; } let start_column = source[start_offset..] .chars() .take(start.column) .map(char::len_utf8) .sum::(); start_offset += start_column; let mut end_offset = start_offset; if start.line == end.line { end_offset -= start_column; } else { for _ in 0..end.line - start.line { end_offset += source[end_offset..].find('\n').unwrap() + 1; } } end_offset += source[end_offset..] .chars() .take(end.column) .map(char::len_utf8) .sum::(); let mut path = path.to_string_lossy(); if path == "-" { path = Cow::Borrowed(if cfg!(unix) { "/dev/stdin" } else { "stdin" }); } let mut files = SimpleFiles::new(); let file = files.add(path, source); let diagnostic = diagnose(file, start_offset..end_offset, error); let config = Config::default(); let _ = term::emit(stderr, &config, &files, &diagnostic); } fn diagnose(file: usize, range: Range, error: syn::Error) -> Diagnostic { let message = error.to_string(); let info = syntax::error::ERRORS .iter() .find(|e| message.contains(e.msg)); let mut diagnostic = Diagnostic::error().with_message(&message); let mut label = Label::primary(file, range); if let Some(info) = info { label.message = info.label.map_or(message, str::to_owned); diagnostic.labels.push(label); diagnostic.notes.extend(info.note.map(str::to_owned)); } else { label.message = message; diagnostic.labels.push(label); } diagnostic.code = Some("cxxbridge".to_owned()); diagnostic } cxx-build-1.0.141/src/gen/file.rs000064400000000000000000000043001046102023000145110ustar 00000000000000use crate::syntax::file::Module; use crate::syntax::namespace::Namespace; use syn::parse::discouraged::Speculative; use syn::parse::{Error, Parse, ParseStream, Result}; use syn::{braced, Attribute, Ident, Item, Meta, Token, Visibility}; pub(crate) struct File { pub modules: Vec, } impl Parse for File { fn parse(input: ParseStream) -> Result { let mut modules = Vec::new(); parse(input, &mut modules)?; Ok(File { modules }) } } fn parse(input: ParseStream, modules: &mut Vec) -> Result<()> { input.call(Attribute::parse_inner)?; while !input.is_empty() { let mut cxx_bridge = false; let mut namespace = Namespace::ROOT; let mut attrs = input.call(Attribute::parse_outer)?; for attr in &attrs { let path = &attr.path().segments; if path.len() == 2 && path[0].ident == "cxx" && path[1].ident == "bridge" { cxx_bridge = true; namespace = parse_args(attr)?; break; } } let ahead = input.fork(); ahead.parse::()?; ahead.parse::>()?; if !ahead.peek(Token![mod]) { let item: Item = input.parse()?; if cxx_bridge { return Err(Error::new_spanned(item, "expected a module")); } continue; } if cxx_bridge { let mut module: Module = input.parse()?; module.namespace = namespace; attrs.extend(module.attrs); module.attrs = attrs; modules.push(module); } else { input.advance_to(&ahead); input.parse::()?; input.parse::()?; let semi: Option = input.parse()?; if semi.is_none() { let content; braced!(content in input); parse(&content, modules)?; } } } Ok(()) } fn parse_args(attr: &Attribute) -> Result { if let Meta::Path(_) = attr.meta { Ok(Namespace::ROOT) } else { attr.parse_args_with(Namespace::parse_bridge_attr_namespace) } } cxx-build-1.0.141/src/gen/fs.rs000064400000000000000000000107631046102023000142140ustar 00000000000000#![allow(dead_code)] use std::error::Error as StdError; use std::fmt::{self, Display}; use std::io::{self, Read}; use std::path::{Path, PathBuf}; pub(crate) type Result = std::result::Result; #[derive(Debug)] pub(crate) struct Error { source: Option, message: String, } impl Error { pub(crate) fn kind(&self) -> io::ErrorKind { match &self.source { Some(io_error) => io_error.kind(), None => io::ErrorKind::Other, } } } impl Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(&self.message) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { let source = self.source.as_ref()?; Some(source) } } macro_rules! err { ($io_error:expr, $fmt:expr $(, $path:expr)* $(,)?) => { Err(Error { source: Option::from($io_error), message: format!($fmt $(, $path.display())*), }) } } pub(crate) fn copy(from: impl AsRef, to: impl AsRef) -> Result { let from = from.as_ref(); let to = to.as_ref(); match std::fs::copy(from, to) { Ok(n) => Ok(n), Err(e) => err!(e, "Failed to copy `{}` -> `{}`", from, to), } } pub(crate) fn create_dir_all(path: impl AsRef) -> Result<()> { let path = path.as_ref(); match std::fs::create_dir_all(path) { Ok(()) => Ok(()), Err(e) => err!(e, "Failed to create directory `{}`", path), } } pub(crate) fn current_dir() -> Result { match std::env::current_dir() { Ok(dir) => Ok(dir), Err(e) => err!(e, "Failed to determine current directory"), } } pub(crate) fn exists(path: impl AsRef) -> bool { let path = path.as_ref(); // If path is a symlink, this returns true, regardless of whether the // symlink points to a path that exists. std::fs::symlink_metadata(path).is_ok() } pub(crate) fn read(path: impl AsRef) -> Result> { let path = path.as_ref(); match std::fs::read(path) { Ok(string) => Ok(string), Err(e) => err!(e, "Failed to read file `{}`", path), } } pub(crate) fn read_stdin() -> Result> { let mut bytes = Vec::new(); match io::stdin().read_to_end(&mut bytes) { Ok(_len) => Ok(bytes), Err(e) => err!(e, "Failed to read input from stdin"), } } pub(crate) fn remove_file(path: impl AsRef) -> Result<()> { let path = path.as_ref(); match std::fs::remove_file(path) { Ok(()) => Ok(()), Err(e) => err!(e, "Failed to remove file `{}`", path), } } pub(crate) fn remove_dir(path: impl AsRef) -> Result<()> { let path = path.as_ref(); match std::fs::remove_dir(path) { Ok(()) => Ok(()), Err(e) => err!(e, "Failed to remove directory `{}`", path), } } fn symlink<'a>( original: &'a Path, link: &'a Path, fun: fn(&'a Path, &'a Path) -> io::Result<()>, ) -> Result<()> { match fun(original, link) { Ok(()) => Ok(()), Err(e) => err!( e, "Failed to create symlink `{}` pointing to `{}`", link, original, ), } } pub(crate) fn symlink_fail(original: impl AsRef, link: impl AsRef) -> Result<()> { err!( None, "Failed to create symlink `{}` pointing to `{}`", link.as_ref(), original.as_ref(), ) } #[cfg(unix)] #[allow(unused_imports)] pub(crate) use self::symlink_file as symlink_dir; #[cfg(not(any(unix, windows)))] #[allow(unused_imports)] pub(crate) use self::symlink_fail as symlink_dir; #[cfg(unix)] pub(crate) fn symlink_file(original: impl AsRef, link: impl AsRef) -> Result<()> { symlink(original.as_ref(), link.as_ref(), std::os::unix::fs::symlink) } #[cfg(windows)] pub(crate) fn symlink_file(original: impl AsRef, link: impl AsRef) -> Result<()> { symlink( original.as_ref(), link.as_ref(), std::os::windows::fs::symlink_file, ) } #[cfg(windows)] pub(crate) fn symlink_dir(original: impl AsRef, link: impl AsRef) -> Result<()> { symlink( original.as_ref(), link.as_ref(), std::os::windows::fs::symlink_dir, ) } pub(crate) fn write(path: impl AsRef, contents: impl AsRef<[u8]>) -> Result<()> { let path = path.as_ref(); match std::fs::write(path, contents) { Ok(()) => Ok(()), Err(e) => err!(e, "Failed to write file `{}`", path), } } cxx-build-1.0.141/src/gen/ifndef.rs000064400000000000000000000026651046102023000150410ustar 00000000000000use crate::gen::include::HEADER; use crate::gen::out::Content; pub(super) fn write(out: &mut Content, needed: bool, guard: &str) { let ifndef = format!("#ifndef {}", guard); let define = format!("#define {}", guard); let endif = format!("#endif // {}", guard); let mut offset = 0; loop { let begin = find_line(offset, &ifndef); let end = find_line(offset, &endif); if let (Some(begin), Some(end)) = (begin, end) { if !needed { return; } out.next_section(); if offset == 0 { writeln!(out, "{}", ifndef); writeln!(out, "{}", define); } for line in HEADER[begin + ifndef.len()..end].trim().lines() { if line != define && !line.trim_start().starts_with("//") { writeln!(out, "{}", line); } } offset = end + endif.len(); } else if offset == 0 { panic!("not found in cxx.h header: {}", guard) } else { writeln!(out, "{}", endif); return; } } } fn find_line(mut offset: usize, line: &str) -> Option { loop { offset += HEADER[offset..].find(line)?; let rest = &HEADER[offset + line.len()..]; if rest.starts_with('\n') || rest.starts_with('\r') { return Some(offset); } offset += line.len(); } } cxx-build-1.0.141/src/gen/include/cxx.h000064400000000000000000000711041046102023000156300ustar 00000000000000#pragma once #include #include #include #include #include #include #include #include #include #include #if __cplusplus >= 202002L #include #endif #include #include #include #include #include #if defined(_WIN32) #include #else #include #endif namespace rust { inline namespace cxxbridge1 { struct unsafe_bitcopy_t; namespace { template class impl; } #ifndef CXXBRIDGE1_RUST_STRING #define CXXBRIDGE1_RUST_STRING // https://cxx.rs/binding/string.html class String final { public: String() noexcept; String(const String &) noexcept; String(String &&) noexcept; ~String() noexcept; String(const std::string &); String(const char *); String(const char *, std::size_t); String(const char16_t *); String(const char16_t *, std::size_t); #if __cplusplus >= 202002L String(const char8_t *s); String(const char8_t *s, std::size_t len); #endif // Replace invalid Unicode data with the replacement character (U+FFFD). static String lossy(const std::string &) noexcept; static String lossy(const char *) noexcept; static String lossy(const char *, std::size_t) noexcept; static String lossy(const char16_t *) noexcept; static String lossy(const char16_t *, std::size_t) noexcept; String &operator=(const String &) & noexcept; String &operator=(String &&) & noexcept; explicit operator std::string() const; // Note: no null terminator. const char *data() const noexcept; std::size_t size() const noexcept; std::size_t length() const noexcept; bool empty() const noexcept; const char *c_str() noexcept; std::size_t capacity() const noexcept; void reserve(size_t new_cap) noexcept; using iterator = char *; iterator begin() noexcept; iterator end() noexcept; using const_iterator = const char *; const_iterator begin() const noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; bool operator==(const String &) const noexcept; bool operator!=(const String &) const noexcept; bool operator<(const String &) const noexcept; bool operator<=(const String &) const noexcept; bool operator>(const String &) const noexcept; bool operator>=(const String &) const noexcept; void swap(String &) noexcept; // Internal API only intended for the cxxbridge code generator. String(unsafe_bitcopy_t, const String &) noexcept; private: struct lossy_t; String(lossy_t, const char *, std::size_t) noexcept; String(lossy_t, const char16_t *, std::size_t) noexcept; friend void swap(String &lhs, String &rhs) noexcept { lhs.swap(rhs); } // Size and alignment statically verified by rust_string.rs. std::array repr; }; #endif // CXXBRIDGE1_RUST_STRING #ifndef CXXBRIDGE1_RUST_STR #define CXXBRIDGE1_RUST_STR // https://cxx.rs/binding/str.html class Str final { public: Str() noexcept; Str(const String &) noexcept; Str(const std::string &); Str(const char *); Str(const char *, std::size_t); Str &operator=(const Str &) & noexcept = default; explicit operator std::string() const; // Note: no null terminator. const char *data() const noexcept; std::size_t size() const noexcept; std::size_t length() const noexcept; bool empty() const noexcept; // Important in order for System V ABI to pass in registers. Str(const Str &) noexcept = default; ~Str() noexcept = default; using iterator = const char *; using const_iterator = const char *; const_iterator begin() const noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; bool operator==(const Str &) const noexcept; bool operator!=(const Str &) const noexcept; bool operator<(const Str &) const noexcept; bool operator<=(const Str &) const noexcept; bool operator>(const Str &) const noexcept; bool operator>=(const Str &) const noexcept; void swap(Str &) noexcept; private: class uninit; Str(uninit) noexcept; friend impl; std::array repr; }; #endif // CXXBRIDGE1_RUST_STR #ifndef CXXBRIDGE1_RUST_SLICE namespace detail { template struct copy_assignable_if {}; template <> struct copy_assignable_if { copy_assignable_if() noexcept = default; copy_assignable_if(const copy_assignable_if &) noexcept = default; copy_assignable_if &operator=(const copy_assignable_if &) & noexcept = delete; copy_assignable_if &operator=(copy_assignable_if &&) & noexcept = default; }; } // namespace detail // https://cxx.rs/binding/slice.html template class Slice final : private detail::copy_assignable_if::value> { public: using value_type = T; Slice() noexcept; Slice(T *, std::size_t count) noexcept; template explicit Slice(C &c) : Slice(c.data(), c.size()) {} Slice &operator=(const Slice &) & noexcept = default; Slice &operator=(Slice &&) & noexcept = default; T *data() const noexcept; std::size_t size() const noexcept; std::size_t length() const noexcept; bool empty() const noexcept; T &operator[](std::size_t n) const noexcept; T &at(std::size_t n) const; T &front() const noexcept; T &back() const noexcept; // Important in order for System V ABI to pass in registers. Slice(const Slice &) noexcept = default; ~Slice() noexcept = default; class iterator; iterator begin() const noexcept; iterator end() const noexcept; void swap(Slice &) noexcept; private: class uninit; Slice(uninit) noexcept; friend impl; friend void sliceInit(void *, const void *, std::size_t) noexcept; friend void *slicePtr(const void *) noexcept; friend std::size_t sliceLen(const void *) noexcept; std::array repr; }; template class Slice::iterator final { public: #if __cplusplus >= 202002L using iterator_category = std::contiguous_iterator_tag; #else using iterator_category = std::random_access_iterator_tag; #endif using value_type = T; using difference_type = std::ptrdiff_t; using pointer = typename std::add_pointer::type; using reference = typename std::add_lvalue_reference::type; reference operator*() const noexcept; pointer operator->() const noexcept; reference operator[](difference_type) const noexcept; iterator &operator++() noexcept; iterator operator++(int) noexcept; iterator &operator--() noexcept; iterator operator--(int) noexcept; iterator &operator+=(difference_type) noexcept; iterator &operator-=(difference_type) noexcept; iterator operator+(difference_type) const noexcept; friend inline iterator operator+(difference_type lhs, iterator rhs) noexcept { return rhs + lhs; } iterator operator-(difference_type) const noexcept; difference_type operator-(const iterator &) const noexcept; bool operator==(const iterator &) const noexcept; bool operator!=(const iterator &) const noexcept; bool operator<(const iterator &) const noexcept; bool operator<=(const iterator &) const noexcept; bool operator>(const iterator &) const noexcept; bool operator>=(const iterator &) const noexcept; private: friend class Slice; void *pos; std::size_t stride; }; #if __cplusplus >= 202002L static_assert(std::ranges::contiguous_range>); static_assert(std::contiguous_iterator::iterator>); #endif #endif // CXXBRIDGE1_RUST_SLICE #ifndef CXXBRIDGE1_RUST_BOX // https://cxx.rs/binding/box.html template class Box final { public: using element_type = T; using const_pointer = typename std::add_pointer::type>::type; using pointer = typename std::add_pointer::type; Box() = delete; Box(Box &&) noexcept; ~Box() noexcept; explicit Box(const T &); explicit Box(T &&); Box &operator=(Box &&) & noexcept; const T *operator->() const noexcept; const T &operator*() const noexcept; T *operator->() noexcept; T &operator*() noexcept; template static Box in_place(Fields &&...); void swap(Box &) noexcept; // Important: requires that `raw` came from an into_raw call. Do not pass a // pointer from `new` or any other source. static Box from_raw(T *) noexcept; T *into_raw() noexcept; /* Deprecated */ using value_type = element_type; private: class uninit; class allocation; Box(uninit) noexcept; void drop() noexcept; friend void swap(Box &lhs, Box &rhs) noexcept { lhs.swap(rhs); } T *ptr; }; #endif // CXXBRIDGE1_RUST_BOX #ifndef CXXBRIDGE1_RUST_VEC // https://cxx.rs/binding/vec.html template class Vec final { public: using value_type = T; Vec() noexcept; Vec(std::initializer_list); Vec(const Vec &); Vec(Vec &&) noexcept; ~Vec() noexcept; Vec &operator=(Vec &&) & noexcept; Vec &operator=(const Vec &) &; std::size_t size() const noexcept; bool empty() const noexcept; const T *data() const noexcept; T *data() noexcept; std::size_t capacity() const noexcept; const T &operator[](std::size_t n) const noexcept; const T &at(std::size_t n) const; const T &front() const noexcept; const T &back() const noexcept; T &operator[](std::size_t n) noexcept; T &at(std::size_t n); T &front() noexcept; T &back() noexcept; void reserve(std::size_t new_cap); void push_back(const T &value); void push_back(T &&value); template void emplace_back(Args &&...args); void truncate(std::size_t len); void clear(); using iterator = typename Slice::iterator; iterator begin() noexcept; iterator end() noexcept; using const_iterator = typename Slice::iterator; const_iterator begin() const noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; void swap(Vec &) noexcept; // Internal API only intended for the cxxbridge code generator. Vec(unsafe_bitcopy_t, const Vec &) noexcept; private: void reserve_total(std::size_t new_cap) noexcept; void set_len(std::size_t len) noexcept; void drop() noexcept; friend void swap(Vec &lhs, Vec &rhs) noexcept { lhs.swap(rhs); } // Size and alignment statically verified by rust_vec.rs. std::array repr; }; #endif // CXXBRIDGE1_RUST_VEC #ifndef CXXBRIDGE1_RUST_FN // https://cxx.rs/binding/fn.html template class Fn; template class Fn final { public: Ret operator()(Args... args) const noexcept; Fn operator*() const noexcept; private: Ret (*trampoline)(Args..., void *fn) noexcept; void *fn; }; #endif // CXXBRIDGE1_RUST_FN #ifndef CXXBRIDGE1_RUST_ERROR #define CXXBRIDGE1_RUST_ERROR // https://cxx.rs/binding/result.html class Error final : public std::exception { public: Error(const Error &); Error(Error &&) noexcept; ~Error() noexcept override; Error &operator=(const Error &) &; Error &operator=(Error &&) & noexcept; const char *what() const noexcept override; private: Error() noexcept = default; friend impl; const char *msg; std::size_t len; }; #endif // CXXBRIDGE1_RUST_ERROR #ifndef CXXBRIDGE1_RUST_ISIZE #define CXXBRIDGE1_RUST_ISIZE #if defined(_WIN32) using isize = SSIZE_T; #else using isize = ssize_t; #endif #endif // CXXBRIDGE1_RUST_ISIZE std::ostream &operator<<(std::ostream &, const String &); std::ostream &operator<<(std::ostream &, const Str &); #ifndef CXXBRIDGE1_RUST_OPAQUE #define CXXBRIDGE1_RUST_OPAQUE // Base class of generated opaque Rust types. class Opaque { public: Opaque() = delete; Opaque(const Opaque &) = delete; ~Opaque() = delete; }; #endif // CXXBRIDGE1_RUST_OPAQUE template std::size_t size_of(); template std::size_t align_of(); // IsRelocatable is used in assertions that a C++ type passed by value // between Rust and C++ is soundly relocatable by Rust. // // There may be legitimate reasons to opt out of the check for support of types // that the programmer knows are soundly Rust-movable despite not being // recognized as such by the C++ type system due to a move constructor or // destructor. To opt out of the relocatability check, do either of the // following things in any header used by `include!` in the bridge. // // --- if you define the type: // struct MyType { // ... // + using IsRelocatable = std::true_type; // }; // // --- otherwise: // + template <> // + struct rust::IsRelocatable : std::true_type {}; template struct IsRelocatable; using u8 = std::uint8_t; using u16 = std::uint16_t; using u32 = std::uint32_t; using u64 = std::uint64_t; using usize = std::size_t; // see static asserts in cxx.cc using i8 = std::int8_t; using i16 = std::int16_t; using i32 = std::int32_t; using i64 = std::int64_t; using f32 = float; using f64 = double; // Snake case aliases for use in code that uses this style for type names. using string = String; using str = Str; template using slice = Slice; template using box = Box; template using vec = Vec; using error = Error; template using fn = Fn; template using is_relocatable = IsRelocatable; //////////////////////////////////////////////////////////////////////////////// /// end public API, begin implementation details #ifndef CXXBRIDGE1_PANIC #define CXXBRIDGE1_PANIC template void panic [[noreturn]] (const char *msg); #endif // CXXBRIDGE1_PANIC #ifndef CXXBRIDGE1_RUST_FN #define CXXBRIDGE1_RUST_FN template Ret Fn::operator()(Args... args) const noexcept { return (*this->trampoline)(std::forward(args)..., this->fn); } template Fn Fn::operator*() const noexcept { return *this; } #endif // CXXBRIDGE1_RUST_FN #ifndef CXXBRIDGE1_RUST_BITCOPY_T #define CXXBRIDGE1_RUST_BITCOPY_T struct unsafe_bitcopy_t final { explicit unsafe_bitcopy_t() = default; }; #endif // CXXBRIDGE1_RUST_BITCOPY_T #ifndef CXXBRIDGE1_RUST_BITCOPY #define CXXBRIDGE1_RUST_BITCOPY constexpr unsafe_bitcopy_t unsafe_bitcopy{}; #endif // CXXBRIDGE1_RUST_BITCOPY #ifndef CXXBRIDGE1_RUST_SLICE #define CXXBRIDGE1_RUST_SLICE template Slice::Slice() noexcept { sliceInit(this, reinterpret_cast(align_of()), 0); } template Slice::Slice(T *s, std::size_t count) noexcept { assert(s != nullptr || count == 0); sliceInit(this, s == nullptr && count == 0 ? reinterpret_cast(align_of()) : const_cast::type *>(s), count); } template T *Slice::data() const noexcept { return reinterpret_cast(slicePtr(this)); } template std::size_t Slice::size() const noexcept { return sliceLen(this); } template std::size_t Slice::length() const noexcept { return this->size(); } template bool Slice::empty() const noexcept { return this->size() == 0; } template T &Slice::operator[](std::size_t n) const noexcept { assert(n < this->size()); auto ptr = static_cast(slicePtr(this)) + size_of() * n; return *reinterpret_cast(ptr); } template T &Slice::at(std::size_t n) const { if (n >= this->size()) { panic("rust::Slice index out of range"); } return (*this)[n]; } template T &Slice::front() const noexcept { assert(!this->empty()); return (*this)[0]; } template T &Slice::back() const noexcept { assert(!this->empty()); return (*this)[this->size() - 1]; } template typename Slice::iterator::reference Slice::iterator::operator*() const noexcept { return *static_cast(this->pos); } template typename Slice::iterator::pointer Slice::iterator::operator->() const noexcept { return static_cast(this->pos); } template typename Slice::iterator::reference Slice::iterator::operator[]( typename Slice::iterator::difference_type n) const noexcept { auto ptr = static_cast(this->pos) + this->stride * n; return *reinterpret_cast(ptr); } template typename Slice::iterator &Slice::iterator::operator++() noexcept { this->pos = static_cast(this->pos) + this->stride; return *this; } template typename Slice::iterator Slice::iterator::operator++(int) noexcept { auto ret = iterator(*this); this->pos = static_cast(this->pos) + this->stride; return ret; } template typename Slice::iterator &Slice::iterator::operator--() noexcept { this->pos = static_cast(this->pos) - this->stride; return *this; } template typename Slice::iterator Slice::iterator::operator--(int) noexcept { auto ret = iterator(*this); this->pos = static_cast(this->pos) - this->stride; return ret; } template typename Slice::iterator &Slice::iterator::operator+=( typename Slice::iterator::difference_type n) noexcept { this->pos = static_cast(this->pos) + this->stride * n; return *this; } template typename Slice::iterator &Slice::iterator::operator-=( typename Slice::iterator::difference_type n) noexcept { this->pos = static_cast(this->pos) - this->stride * n; return *this; } template typename Slice::iterator Slice::iterator::operator+( typename Slice::iterator::difference_type n) const noexcept { auto ret = iterator(*this); ret.pos = static_cast(this->pos) + this->stride * n; return ret; } template typename Slice::iterator Slice::iterator::operator-( typename Slice::iterator::difference_type n) const noexcept { auto ret = iterator(*this); ret.pos = static_cast(this->pos) - this->stride * n; return ret; } template typename Slice::iterator::difference_type Slice::iterator::operator-(const iterator &other) const noexcept { auto diff = std::distance(static_cast(other.pos), static_cast(this->pos)); return diff / static_cast::iterator::difference_type>( this->stride); } template bool Slice::iterator::operator==(const iterator &other) const noexcept { return this->pos == other.pos; } template bool Slice::iterator::operator!=(const iterator &other) const noexcept { return this->pos != other.pos; } template bool Slice::iterator::operator<(const iterator &other) const noexcept { return this->pos < other.pos; } template bool Slice::iterator::operator<=(const iterator &other) const noexcept { return this->pos <= other.pos; } template bool Slice::iterator::operator>(const iterator &other) const noexcept { return this->pos > other.pos; } template bool Slice::iterator::operator>=(const iterator &other) const noexcept { return this->pos >= other.pos; } template typename Slice::iterator Slice::begin() const noexcept { iterator it; it.pos = slicePtr(this); it.stride = size_of(); return it; } template typename Slice::iterator Slice::end() const noexcept { iterator it = this->begin(); it.pos = static_cast(it.pos) + it.stride * this->size(); return it; } template void Slice::swap(Slice &rhs) noexcept { std::swap(*this, rhs); } #endif // CXXBRIDGE1_RUST_SLICE #ifndef CXXBRIDGE1_RUST_BOX #define CXXBRIDGE1_RUST_BOX template class Box::uninit {}; template class Box::allocation { static T *alloc() noexcept; static void dealloc(T *) noexcept; public: allocation() noexcept : ptr(alloc()) {} ~allocation() noexcept { if (this->ptr) { dealloc(this->ptr); } } T *ptr; }; template Box::Box(Box &&other) noexcept : ptr(other.ptr) { other.ptr = nullptr; } template Box::Box(const T &val) { allocation alloc; ::new (alloc.ptr) T(val); this->ptr = alloc.ptr; alloc.ptr = nullptr; } template Box::Box(T &&val) { allocation alloc; ::new (alloc.ptr) T(std::move(val)); this->ptr = alloc.ptr; alloc.ptr = nullptr; } template Box::~Box() noexcept { if (this->ptr) { this->drop(); } } template Box &Box::operator=(Box &&other) & noexcept { if (this->ptr) { this->drop(); } this->ptr = other.ptr; other.ptr = nullptr; return *this; } template const T *Box::operator->() const noexcept { return this->ptr; } template const T &Box::operator*() const noexcept { return *this->ptr; } template T *Box::operator->() noexcept { return this->ptr; } template T &Box::operator*() noexcept { return *this->ptr; } template template Box Box::in_place(Fields &&...fields) { allocation alloc; auto ptr = alloc.ptr; ::new (ptr) T{std::forward(fields)...}; alloc.ptr = nullptr; return from_raw(ptr); } template void Box::swap(Box &rhs) noexcept { using std::swap; swap(this->ptr, rhs.ptr); } template Box Box::from_raw(T *raw) noexcept { Box box = uninit{}; box.ptr = raw; return box; } template T *Box::into_raw() noexcept { T *raw = this->ptr; this->ptr = nullptr; return raw; } template Box::Box(uninit) noexcept {} #endif // CXXBRIDGE1_RUST_BOX #ifndef CXXBRIDGE1_RUST_VEC #define CXXBRIDGE1_RUST_VEC template Vec::Vec(std::initializer_list init) : Vec{} { this->reserve_total(init.size()); std::move(init.begin(), init.end(), std::back_inserter(*this)); } template Vec::Vec(const Vec &other) : Vec() { this->reserve_total(other.size()); std::copy(other.begin(), other.end(), std::back_inserter(*this)); } template Vec::Vec(Vec &&other) noexcept : repr(other.repr) { new (&other) Vec(); } template Vec::~Vec() noexcept { this->drop(); } template Vec &Vec::operator=(Vec &&other) & noexcept { this->drop(); this->repr = other.repr; new (&other) Vec(); return *this; } template Vec &Vec::operator=(const Vec &other) & { if (this != &other) { this->drop(); new (this) Vec(other); } return *this; } template bool Vec::empty() const noexcept { return this->size() == 0; } template T *Vec::data() noexcept { return const_cast(const_cast *>(this)->data()); } template const T &Vec::operator[](std::size_t n) const noexcept { assert(n < this->size()); auto data = reinterpret_cast(this->data()); return *reinterpret_cast(data + n * size_of()); } template const T &Vec::at(std::size_t n) const { if (n >= this->size()) { panic("rust::Vec index out of range"); } return (*this)[n]; } template const T &Vec::front() const noexcept { assert(!this->empty()); return (*this)[0]; } template const T &Vec::back() const noexcept { assert(!this->empty()); return (*this)[this->size() - 1]; } template T &Vec::operator[](std::size_t n) noexcept { assert(n < this->size()); auto data = reinterpret_cast(this->data()); return *reinterpret_cast(data + n * size_of()); } template T &Vec::at(std::size_t n) { if (n >= this->size()) { panic("rust::Vec index out of range"); } return (*this)[n]; } template T &Vec::front() noexcept { assert(!this->empty()); return (*this)[0]; } template T &Vec::back() noexcept { assert(!this->empty()); return (*this)[this->size() - 1]; } template void Vec::reserve(std::size_t new_cap) { this->reserve_total(new_cap); } template void Vec::push_back(const T &value) { this->emplace_back(value); } template void Vec::push_back(T &&value) { this->emplace_back(std::move(value)); } template template void Vec::emplace_back(Args &&...args) { auto size = this->size(); this->reserve_total(size + 1); ::new (reinterpret_cast(reinterpret_cast(this->data()) + size * size_of())) T(std::forward(args)...); this->set_len(size + 1); } template void Vec::clear() { this->truncate(0); } template typename Vec::iterator Vec::begin() noexcept { return Slice(this->data(), this->size()).begin(); } template typename Vec::iterator Vec::end() noexcept { return Slice(this->data(), this->size()).end(); } template typename Vec::const_iterator Vec::begin() const noexcept { return this->cbegin(); } template typename Vec::const_iterator Vec::end() const noexcept { return this->cend(); } template typename Vec::const_iterator Vec::cbegin() const noexcept { return Slice(this->data(), this->size()).begin(); } template typename Vec::const_iterator Vec::cend() const noexcept { return Slice(this->data(), this->size()).end(); } template void Vec::swap(Vec &rhs) noexcept { using std::swap; swap(this->repr, rhs.repr); } // Internal API only intended for the cxxbridge code generator. template Vec::Vec(unsafe_bitcopy_t, const Vec &bits) noexcept : repr(bits.repr) {} #endif // CXXBRIDGE1_RUST_VEC #ifndef CXXBRIDGE1_IS_COMPLETE #define CXXBRIDGE1_IS_COMPLETE namespace detail { namespace { template struct is_complete : std::false_type {}; template struct is_complete : std::true_type {}; } // namespace } // namespace detail #endif // CXXBRIDGE1_IS_COMPLETE #ifndef CXXBRIDGE1_LAYOUT #define CXXBRIDGE1_LAYOUT class layout { template friend std::size_t size_of(); template friend std::size_t align_of(); template static typename std::enable_if::value, std::size_t>::type do_size_of() { return T::layout::size(); } template static typename std::enable_if::value, std::size_t>::type do_size_of() { return sizeof(T); } template static typename std::enable_if::value, std::size_t>::type size_of() { return do_size_of(); } template static typename std::enable_if::value, std::size_t>::type do_align_of() { return T::layout::align(); } template static typename std::enable_if::value, std::size_t>::type do_align_of() { return alignof(T); } template static typename std::enable_if::value, std::size_t>::type align_of() { return do_align_of(); } }; template std::size_t size_of() { return layout::size_of(); } template std::size_t align_of() { return layout::align_of(); } #endif // CXXBRIDGE1_LAYOUT #ifndef CXXBRIDGE1_RELOCATABLE #define CXXBRIDGE1_RELOCATABLE namespace detail { template struct make_void { using type = void; }; template using void_t = typename make_void::type; template class, typename...> struct detect : std::false_type {}; template