cxx-gen-0.7.141/.cargo_vcs_info.json0000644000000001450000000000100125570ustar { "git": { "sha1": "926094db8792e43cc0e3f33b422f6319dbd2cfff" }, "path_in_vcs": "gen/lib" }cxx-gen-0.7.141/Cargo.lock0000644000000103520000000000100105330ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[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-gen" version = "0.7.141" dependencies = [ "codespan-reporting", "proc-macro2", "quote", "syn", ] [[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 = "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-gen-0.7.141/Cargo.toml0000644000000030610000000000100105550ustar # 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-gen" version = "0.7.141" authors = ["Adrian Taylor "] build = false exclude = ["build.rs"] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "C++ code generator for integrating `cxx` crate into higher level tools." documentation = "https://docs.rs/cxx-gen" readme = false keywords = ["ffi"] categories = ["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"] [lib] name = "cxx_gen" path = "src/lib.rs" [[test]] name = "test" path = "tests/test.rs" [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.syn] version = "2.0.46" features = [ "clone-impls", "full", "parsing", "printing", ] default-features = false cxx-gen-0.7.141/Cargo.toml.orig000064400000000000000000000015261046102023000142420ustar 00000000000000[package] name = "cxx-gen" version = "0.7.141" authors = ["Adrian Taylor "] categories = ["development-tools::ffi"] description = "C++ code generator for integrating `cxx` crate into higher level tools." documentation = "https://docs.rs/cxx-gen" edition = "2021" exclude = ["build.rs"] keywords = ["ffi"] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/cxx" rust-version = "1.73" [dependencies] 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 } syn = { version = "2.0.46", default-features = false, features = ["clone-impls", "full", "parsing", "printing"] } [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] cxx-gen-0.7.141/LICENSE-APACHE000064400000000000000000000227731046102023000133060ustar 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-gen-0.7.141/LICENSE-MIT000064400000000000000000000017771046102023000130170ustar 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-gen-0.7.141/src/error.rs000064400000000000000000000033331046102023000136370ustar 00000000000000// We can expose more detail on the error as the need arises, but start with an // opaque error type for now. use std::error::Error as StdError; use std::fmt::{self, Debug, Display}; use std::iter; #[allow(missing_docs)] pub struct Error { pub(crate) err: crate::gen::Error, } impl Error { /// Returns the span of the error, if available. pub fn span(&self) -> Option { match &self.err { crate::gen::Error::Syn(err) => Some(err.span()), _ => None, } } } impl From for Error { fn from(err: crate::gen::Error) -> Self { Error { err } } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(&self.err, f) } } impl Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.err, f) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { self.err.source() } } impl IntoIterator for Error { type Item = Error; type IntoIter = IntoIter; fn into_iter(self) -> Self::IntoIter { match self.err { crate::gen::Error::Syn(err) => IntoIter::Syn(err.into_iter()), _ => IntoIter::Other(iter::once(self)), } } } pub enum IntoIter { Syn(::IntoIter), Other(iter::Once), } impl Iterator for IntoIter { type Item = Error; fn next(&mut self) -> Option { match self { IntoIter::Syn(iter) => iter .next() .map(|syn_err| Error::from(crate::gen::Error::Syn(syn_err))), IntoIter::Other(iter) => iter.next(), } } } cxx-gen-0.7.141/src/gen/block.rs000064400000000000000000000023671046102023000143570ustar 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-gen-0.7.141/src/gen/builtin.rs000064400000000000000000000321731046102023000147310ustar 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-gen-0.7.141/src/gen/cfg.rs000064400000000000000000000076271046102023000140300ustar 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-gen-0.7.141/src/gen/check.rs000064400000000000000000000016341046102023000143360ustar 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-gen-0.7.141/src/gen/error.rs000064400000000000000000000120311046102023000144030ustar 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-gen-0.7.141/src/gen/file.rs000064400000000000000000000043001046102023000141710ustar 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-gen-0.7.141/src/gen/fs.rs000064400000000000000000000107631046102023000136740ustar 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-gen-0.7.141/src/gen/ifndef.rs000064400000000000000000000026651046102023000145210ustar 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-gen-0.7.141/src/gen/include/cxx.h000064400000000000000000000711041046102023000153100ustar 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