diff --git a/.github/workflows/bench-ffi.yml b/.github/workflows/bench-ffi.yml deleted file mode 100644 index ac120ac44..000000000 --- a/.github/workflows/bench-ffi.yml +++ /dev/null @@ -1,68 +0,0 @@ -name: Bench FFI - -permissions: - contents: read - -on: - schedule: - - cron: "0 8 * * *" - workflow_dispatch: - # A change to the fork measures its effect against the PR's base, and a change to - # the benchmark or its toolchains reports its numbers, before either merges. The - # toolchains are moq's dev shell at the pin, so this repo's flake is not one. - pull_request: - paths: - - uniffi/** - - "!uniffi/**/*.md" - - Cargo.toml - - Cargo.lock - - bench/ffi/** - - "!bench/ffi/**/*.md" - - .github/workflows/bench-ffi.yml - -concurrency: - group: bench-ffi-${{ github.ref }} - cancel-in-progress: true - -jobs: - bench: - name: Bench FFI (${{ matrix.name }}) - runs-on: ${{ matrix.os }} - timeout-minutes: 330 - strategy: - fail-fast: false - # Each job measures its own Rust baselines, so ratios never cross machines. - matrix: - include: - - name: Linux - os: ubuntu-24.04 - - name: Swift - os: macos-latest - args: --runner swift - - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - # --base needs the PR's base commit. - fetch-depth: 0 - - - uses: ./.github/actions/nix - - - name: Bench - run: nix develop --command just bench-ffi ${{ matrix.args }} ${{ github.event_name == 'pull_request' && format('--base {0}', github.event.pull_request.base.sha) || '' }} --out bench-results - env: - # The pinned moq's flake names its binary cache; without it the dev shell builds from source. - NIX_CONFIG: accept-flake-config = true - - - name: Summary - run: cat bench-results/report.md >>"$GITHUB_STEP_SUMMARY" - - - name: Upload - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: bench-ffi-${{ strategy.job-index }} - path: bench-results - if-no-files-found: ignore diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 55606b776..0c2b2459e 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -62,88 +62,6 @@ jobs: - name: Encoder in Chromium run: nix develop .#bench --command env RUST2_TS_SYSROOT= just ts test --test fixtures -- --ignored --exact encoder - uniffi-fixtures: - name: UniFFI fixtures - # x86_64: nixpkgs marks Swift 6.3 broken on aarch64-linux, where it fails to link with - # gold. Swift 6.4 links with LLD and lifts the mark once it reaches nixpkgs-unstable. - runs-on: ubuntu-24.04 - timeout-minutes: 90 - - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - uses: ./.github/actions/nix - - # Kotlin, Swift, Python, and Dart run under cargo; Go and C++ run their own harness. - - name: Fixtures - run: nix develop .#uniffi --command just uniffi fixtures - - # The Linux job above builds the C and C++ fixtures with GCC; consumers also build them - # with these. Each standard reuses the job's one Rust build. - uniffi-cpp: - name: UniFFI C and C++ (${{ matrix.name }}) - runs-on: ${{ matrix.os }} - timeout-minutes: 60 - strategy: - fail-fast: false - matrix: - include: - - name: MSVC - os: windows-latest - - name: Apple Clang - os: macos-latest - defaults: - run: - shell: bash - - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - # No Nix: its dev shell would replace the system compiler under test. The runner's - # rustup installs rust-toolchain.toml's channel. The suite also builds its expected-style - # and C consumers without exceptions or RTTI. - - name: C++17 - run: | - cmake -S uniffi/cpp/cpp-tests -B target/cpp17 -DCMAKE_BUILD_TYPE=Debug - cmake --build target/cpp17 --config Debug --parallel - ctest --test-dir target/cpp17 -C Debug --output-on-failure - - - name: C++20 - run: | - cmake -S uniffi/cpp/cpp-tests -B target/cpp20 -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_STANDARD=20 - cmake --build target/cpp20 --config Debug --parallel - ctest --test-dir target/cpp20 -C Debug --output-on-failure - - uniffi-install: - name: UniFFI install - runs-on: ubuntu-24.04-arm - timeout-minutes: 60 - - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - uses: ./.github/actions/nix - - # A consumer's `cargo install` ignores the lockfile, so resolve it fresh. - - name: Install - run: nix develop --command just uniffi install - - - name: Symlink - run: nix develop --command just uniffi symlink - - # The flake packages moq pins. - - name: Build - run: nix build .#uniffi - bench: name: Benchmark runs-on: ubuntu-24.04-arm diff --git a/.taplo.toml b/.taplo.toml index 317d23a8a..23ddc3dfb 100644 --- a/.taplo.toml +++ b/.taplo.toml @@ -1,5 +1,4 @@ -# The UniFFI fork keeps its upstream formatting, like uniffi/rustfmt.toml. -exclude = ["**/target/**", "**/.direnv/**", ".scratch/**", ".tmp/**", "uniffi/**"] +exclude = ["**/target/**", "**/.direnv/**", ".scratch/**", ".tmp/**"] [formatting] indent_string = " " diff --git a/AGENTS.md b/AGENTS.md index 8797700d1..b6c21fc06 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,4 +1,4 @@ -rust2 holds Rust tools that take Rust somewhere else: to any language through an exporter of a crate's `pub` API, which replaces a fork of UniFFI, to TypeScript through an own rustc driver, and to faster builds by measuring upstream's levers. +rust2 holds Rust tools that take Rust somewhere else: to any language through an exporter of a crate's `pub` API, to TypeScript through an own rustc driver, and to faster builds by measuring upstream's levers. Each project lives in its own top-level directory; the [quest tree](quest/README.md) says what each is doing now. # Required diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 93110116f..000000000 --- a/Cargo.lock +++ /dev/null @@ -1,3848 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "anes" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "askama" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d4744ed2eef2645831b441d8f5459689ade2ab27c854488fbab1fbe94fce1a7" -dependencies = [ - "askama_derive 0.13.1", - "itoa", - "percent-encoding", - "serde", - "serde_json", -] - -[[package]] -name = "askama" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4" -dependencies = [ - "askama_macros", - "itoa", - "percent-encoding", - "serde", - "serde_json", -] - -[[package]] -name = "askama_derive" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d661e0f57be36a5c14c48f78d09011e67e0cb618f269cca9f2fd8d15b68c46ac" -dependencies = [ - "askama_parser 0.13.0", - "basic-toml", - "memchr", - "proc-macro2", - "quote", - "rustc-hash", - "serde", - "serde_derive", - "syn 2.0.119", -] - -[[package]] -name = "askama_derive" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39" -dependencies = [ - "askama_parser 0.16.1", - "memchr", - "proc-macro2", - "quote", - "rustc-hash", - "syn 3.0.9", -] - -[[package]] -name = "askama_macros" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b" -dependencies = [ - "askama_derive 0.16.1", -] - -[[package]] -name = "askama_parser" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf315ce6524c857bb129ff794935cf6d42c82a6cff60526fe2a63593de4d0d4f" -dependencies = [ - "memchr", - "serde", - "serde_derive", - "winnow 0.7.15", -] - -[[package]] -name = "askama_parser" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583" -dependencies = [ - "rustc-hash", - "unicode-ident", - "winnow 1.0.4", -] - -[[package]] -name = "async-channel" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" -dependencies = [ - "concurrent-queue", - "event-listener 2.5.3", - "futures-core", -] - -[[package]] -name = "async-channel" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-compat" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c97d7ff3c25d6c10d64170c12acaf5d4245e76dece3779c1d92b153a64f11df" -dependencies = [ - "futures-core", - "futures-io", - "once_cell", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "async-executor" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" -dependencies = [ - "async-task", - "concurrent-queue", - "fastrand 2.5.0", - "futures-lite 2.6.1", - "pin-project-lite", - "slab", -] - -[[package]] -name = "async-fs" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "279cf904654eeebfa37ac9bb1598880884924aab82e290aa65c9e77a0e142e06" -dependencies = [ - "async-lock 2.8.0", - "autocfg", - "blocking", - "futures-lite 1.13.0", -] - -[[package]] -name = "async-global-executor" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" -dependencies = [ - "async-channel 2.5.0", - "async-executor", - "async-io 2.6.0", - "async-lock 3.4.2", - "blocking", - "futures-lite 2.6.1", - "once_cell", -] - -[[package]] -name = "async-io" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" -dependencies = [ - "async-lock 2.8.0", - "autocfg", - "cfg-if", - "concurrent-queue", - "futures-lite 1.13.0", - "log", - "parking", - "polling 2.8.0", - "rustix 0.37.28", - "slab", - "socket2", - "waker-fn", -] - -[[package]] -name = "async-io" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" -dependencies = [ - "autocfg", - "cfg-if", - "concurrent-queue", - "futures-io", - "futures-lite 2.6.1", - "parking", - "polling 3.11.0", - "rustix 1.1.5", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-lock" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" -dependencies = [ - "event-listener 2.5.3", -] - -[[package]] -name = "async-lock" -version = "3.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" -dependencies = [ - "event-listener 5.4.2", - "event-listener-strategy", - "pin-project-lite", -] - -[[package]] -name = "async-net" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0434b1ed18ce1cf5769b8ac540e33f01fa9471058b5e89da9e06f3c882a8c12f" -dependencies = [ - "async-io 1.13.0", - "blocking", - "futures-lite 1.13.0", -] - -[[package]] -name = "async-process" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6438ba0a08d81529c69b36700fa2f95837bfe3e776ab39cde9c14d9149da88" -dependencies = [ - "async-io 1.13.0", - "async-lock 2.8.0", - "async-signal", - "blocking", - "cfg-if", - "event-listener 3.1.0", - "futures-lite 1.13.0", - "rustix 0.38.44", - "windows-sys 0.48.0", -] - -[[package]] -name = "async-signal" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" -dependencies = [ - "async-io 2.6.0", - "async-lock 3.4.2", - "atomic-waker", - "cfg-if", - "futures-core", - "futures-io", - "rustix 1.1.5", - "signal-hook-registry", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-std" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b" -dependencies = [ - "async-channel 1.9.0", - "async-global-executor", - "async-io 2.6.0", - "async-lock 3.4.2", - "crossbeam-utils", - "futures-channel", - "futures-core", - "futures-io", - "futures-lite 2.6.1", - "gloo-timers", - "kv-log-macro", - "log", - "memchr", - "once_cell", - "pin-project-lite", - "pin-utils", - "slab", - "wasm-bindgen-futures", -] - -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "async-task" -version = "4.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "basic-toml" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" -dependencies = [ - "serde", -] - -[[package]] -name = "benchmarks" -version = "0.1.0" -dependencies = [ - "camino", - "clap", - "criterion", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "blocking" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" -dependencies = [ - "async-channel 2.5.0", - "async-task", - "futures-io", - "futures-lite 2.6.1", - "piper", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - -[[package]] -name = "bytes_types" -version = "0.1.0" -dependencies = [ - "anyhow", - "thiserror 2.0.21", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "callbacks" -version = "0.1.0" -dependencies = [ - "anyhow", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "camino" -version = "1.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" -dependencies = [ - "serde_core", -] - -[[package]] -name = "camino-tempfile" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64308c4c82a5c38679945ddf88738dc1483dcc563bbb5780755ae9f8497d2b20" -dependencies = [ - "camino", - "tempfile", -] - -[[package]] -name = "cargo-platform" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" -dependencies = [ - "serde", -] - -[[package]] -name = "cargo-platform" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "cargo_metadata" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d886547e41f740c616ae73108f6eb70afe6d940c7bc697cb30f13daec073037" -dependencies = [ - "camino", - "cargo-platform 0.1.9", - "semver", - "serde", - "serde_json", - "thiserror 1.0.69", -] - -[[package]] -name = "cargo_metadata" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9" -dependencies = [ - "camino", - "cargo-platform 0.3.3", - "semver", - "serde", - "serde_json", - "thiserror 2.0.21", -] - -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "num-traits", -] - -[[package]] -name = "ciborium" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] - -[[package]] -name = "ciborium-io" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" - -[[package]] -name = "ciborium-ll" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" -dependencies = [ - "ciborium-io", - "half", -] - -[[package]] -name = "clap" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "clap_lex" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "criterion" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" -dependencies = [ - "anes", - "cast", - "ciborium", - "clap", - "criterion-plot", - "is-terminal", - "itertools", - "num-traits", - "once_cell", - "oorandom", - "plotters", - "rayon", - "regex", - "serde", - "serde_derive", - "serde_json", - "tinytemplate", - "walkdir", -] - -[[package]] -name = "criterion-plot" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" -dependencies = [ - "cast", - "itertools", -] - -[[package]] -name = "crossbeam" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e71406cd8807725f7ac2f999a4cdd32e98f829fdf65f528343cebf945e41df1e" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-epoch", - "crossbeam-queue", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-queue" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "custom_types" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "dart_async" -version = "0.1.0" -dependencies = [ - "anyhow", - "async-trait", - "futures", - "once_cell", - "thiserror 2.0.21", - "tokio", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "dart_namespaces" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", - "uniffi-fixture-namespaces-media", - "uniffi-fixture-namespaces-net", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "docstring-proc-macro" -version = "0.1.0" -dependencies = [ - "camino", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "duration_type_test" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" - -[[package]] -name = "enum_variant_collision" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "event-listener" -version = "2.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" - -[[package]] -name = "event-listener" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d93877bcde0eb80ca09131a08d23f0a5c18a620b01db137dba666d18cd9b30c2" -dependencies = [ - "concurrent-queue", - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener" -version = "5.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener 5.4.2", - "pin-project-lite", -] - -[[package]] -name = "extend" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "311a6d2f1f9d60bff73d2c78a0af97ed27f79672f15c238192a5bbb64db56d00" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "fastrand" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" -dependencies = [ - "instant", -] - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fs-err" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41" -dependencies = [ - "autocfg", -] - -[[package]] -name = "fs-err" -version = "3.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" -dependencies = [ - "autocfg", -] - -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - -[[package]] -name = "futures" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-executor" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-lite" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" -dependencies = [ - "fastrand 1.9.0", - "futures-core", - "futures-io", - "memchr", - "parking", - "pin-project-lite", - "waker-fn", -] - -[[package]] -name = "futures-lite" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" -dependencies = [ - "fastrand 2.5.0", - "futures-core", - "futures-io", - "parking", - "pin-project-lite", -] - -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-timer" -version = "3.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "genco" -version = "0.17.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a35958104272e516c2a5f66a9d82fba4784d2b585fc1e2358b8f96e15d342995" -dependencies = [ - "genco-macros", - "relative-path", - "smallvec", -] - -[[package]] -name = "genco-macros" -version = "0.17.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43eaff6bbc0b3a878361aced5ec6a2818ee7c541c5b33b5880dfa9a86c23e9e7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "libc", - "r-efi", -] - -[[package]] -name = "glob" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" - -[[package]] -name = "gloo-timers" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" -dependencies = [ - "futures-channel", - "futures-core", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "goblin" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47" -dependencies = [ - "log", - "plain", - "scroll", -] - -[[package]] -name = "half" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" -dependencies = [ - "cfg-if", - "crunchy", - "zerocopy", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hello_world" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - -[[package]] -name = "hermit-abi" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" - -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "icu_collections" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" -dependencies = [ - "displaydoc", - "litemap", - "serde", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_locale_fallback" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" -dependencies = [ - "icu_locale_core", - "icu_locale_fallback_data", - "icu_provider", - "potential_utf", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locale_fallback_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" - -[[package]] -name = "icu_normalizer" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" - -[[package]] -name = "icu_properties" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" - -[[package]] -name = "icu_provider" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" -dependencies = [ - "displaydoc", - "icu_locale_core", - "serde", - "stable_deref_trait", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_segmenter" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" -dependencies = [ - "icu_collections", - "icu_locale_fallback", - "icu_provider", - "icu_segmenter_data", - "potential_utf", - "smallvec", - "utf8_iter", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_segmenter_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown", - "serde", - "serde_core", -] - -[[package]] -name = "input_scratch" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "io-lifetimes" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" -dependencies = [ - "hermit-abi 0.3.9", - "libc", - "windows-sys 0.48.0", -] - -[[package]] -name = "is-terminal" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" -dependencies = [ - "hermit-abi 0.5.3", - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "js-sys" -version = "0.3.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "kv-log-macro" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" -dependencies = [ - "log", -] - -[[package]] -name = "large-enum" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "large-error" -version = "0.26.1" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "lazy_static" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "library_config" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "linux-raw-sys" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" - -[[package]] -name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "litemap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" - -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" -dependencies = [ - "value-bag", -] - -[[package]] -name = "map_type" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "metadata" -version = "0.1.0" -dependencies = [ - "camino", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "oorandom" -version = "11.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" - -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "pin-utils" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" - -[[package]] -name = "piper" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" -dependencies = [ - "atomic-waker", - "fastrand 2.5.0", - "futures-io", -] - -[[package]] -name = "plain" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" - -[[package]] -name = "plotters" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "plotters-backend" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" - -[[package]] -name = "plotters-svg" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" -dependencies = [ - "plotters-backend", -] - -[[package]] -name = "polling" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" -dependencies = [ - "autocfg", - "bitflags 1.3.2", - "cfg-if", - "concurrent-queue", - "libc", - "log", - "pin-project-lite", - "windows-sys 0.48.0", -] - -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" -dependencies = [ - "cfg-if", - "concurrent-queue", - "hermit-abi 0.5.3", - "pin-project-lite", - "rustix 1.1.5", - "windows-sys 0.61.2", -] - -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "serde_core", - "writeable", - "zerovec", -] - -[[package]] -name = "proc-macro-no-implicit-prelude" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "proc_macro_uniffi" -version = "0.1.0" -dependencies = [ - "anyhow", - "lazy_static", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rayon" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "relative-path" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustix" -version = "0.37.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "519165d378b97752ca44bbe15047d5d3409e875f39327546b42ac81d7e18c1b6" -dependencies = [ - "bitflags 1.3.2", - "errno", - "io-lifetimes", - "libc", - "linux-raw-sys 0.3.8", - "windows-sys 0.48.0", -] - -[[package]] -name = "rustix" -version = "0.38.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", -] - -[[package]] -name = "rustix" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scroll" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6" -dependencies = [ - "scroll_derive", -] - -[[package]] -name = "scroll_derive" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_spanned" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" -dependencies = [ - "serde_core", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "simple_arithmetic" -version = "0.1.0" -dependencies = [ - "anyhow", - "thiserror 2.0.21", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "simple_fns" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "simple_iface" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "siphasher" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" - -[[package]] -name = "smawk" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" - -[[package]] -name = "smol" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13f2b548cd8447f8de0fdf1c592929f70f4fc7039a05e47404b0d096ec6987a1" -dependencies = [ - "async-channel 1.9.0", - "async-executor", - "async-fs", - "async-io 1.13.0", - "async-lock 2.8.0", - "async-net", - "async-process", - "blocking", - "futures-lite 1.13.0", -] - -[[package]] -name = "socket2" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "streams_ext" -version = "0.1.0" -dependencies = [ - "anyhow", - "async-stream", - "futures", - "lazy_static", - "smol", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", - "uniffi_dart_macro", -] - -[[package]] -name = "stringcase" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04028eeb851ed08af6aba5caa29f2d59a13ed168cee4d6bd753aeefcf1d636b0" - -[[package]] -name = "stringcase" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72abeda133c49d7bddece6c154728f83eec8172380c80ab7096da9487e20d27c" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "struct_default_values" -version = "0.1.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "swift-bridging-header-compile" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "uniffi", - "uniffi_testing", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "synstructure" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "target-tuple" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "876fef147edbcbddc8ac5cbbba92c7b86519e314e86638596c09673b2ed01e7f" - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand 2.5.0", - "getrandom", - "once_cell", - "rustix 1.1.5", - "windows-sys 0.61.2", -] - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "textwrap" -version = "0.16.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" -dependencies = [ - "icu_segmenter", - "smawk", - "unicode-width", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl 2.0.21", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "tinystr" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" -dependencies = [ - "displaydoc", - "serde_core", - "zerovec", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "tokio" -version = "1.54.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" -dependencies = [ - "pin-project-lite", -] - -[[package]] -name = "toml" -version = "1.1.8+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" -dependencies = [ - "indexmap", - "serde_core", - "serde_spanned", - "toml_datetime", - "toml_parser", - "toml_writer", - "winnow 1.0.4", -] - -[[package]] -name = "toml_datetime" -version = "1.1.2+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_parser" -version = "1.1.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" -dependencies = [ - "winnow 1.0.4", -] - -[[package]] -name = "toml_writer" -version = "1.1.3+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" - -[[package]] -name = "topological-sort" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d" - -[[package]] -name = "trait_interfaces" -version = "0.1.0" -dependencies = [ - "anyhow", - "once_cell", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "trait_methods" -version = "0.1.0" -dependencies = [ - "anyhow", - "once_cell", - "thiserror 1.0.69", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "trybuild" -version = "1.0.122" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62db9c92d704393fbf2132041720cc80b689f2d3f28521015c2ac866223c11b8" -dependencies = [ - "glob", - "serde", - "serde_derive", - "serde_json", - "target-tuple", - "termcolor", - "toml", -] - -[[package]] -name = "type_limits" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "uniffi", - "uniffi-dart", -] - -[[package]] -name = "unary-result-alias" -version = "0.1.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "unicode-width" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" - -[[package]] -name = "uniffi" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "cargo_metadata 0.23.1", - "clap", - "trybuild", - "uniffi_bindgen", - "uniffi_build", - "uniffi_core", - "uniffi_macros", - "uniffi_pipeline", -] - -[[package]] -name = "uniffi-async-calls" -version = "0.21.0" -dependencies = [ - "futures-timer", - "once_cell", - "thiserror 1.0.69", - "tokio", - "uniffi", -] - -[[package]] -name = "uniffi-bindgen-cpp" -version = "0.1.0" -dependencies = [ - "anyhow", - "askama 0.13.1", - "camino", - "clap", - "heck 0.4.1", - "paste", - "serde", - "textwrap", - "toml", - "topological-sort", - "uniffi_bindgen", -] - -[[package]] -name = "uniffi-bindgen-cpp-fixtures" -version = "1.0.0" -dependencies = [ - "uniffi", - "uniffi-async-calls", - "uniffi-c-api", - "uniffi-custom-types-builtin", - "uniffi-empty-type", - "uniffi-enum-style-test", - "uniffi-error-types-builtin", - "uniffi-example-arithmetic", - "uniffi-example-callbacks", - "uniffi-example-custom-types", - "uniffi-example-geometry", - "uniffi-example-rondpoint", - "uniffi-example-sprites", - "uniffi-example-todolist", - "uniffi-example-traits", - "uniffi-ext-types-export", - "uniffi-ext-types-import", - "uniffi-fixture-callbacks", - "uniffi-fixture-coverall", - "uniffi-fixture-docstring", - "uniffi-fixture-namespaces-media", - "uniffi-fixture-namespaces-net", - "uniffi-fixture-time", - "uniffi-fixture-trait-methods", - "uniffi-reserved-field-name", - "uniffi-type-flattening", -] - -[[package]] -name = "uniffi-bindgen-go" -version = "0.1.0" -dependencies = [ - "anyhow", - "askama 0.13.1", - "camino", - "clap", - "extend", - "fs-err 2.11.0", - "heck 0.5.0", - "paste", - "serde", - "serde_json", - "textwrap", - "toml", - "uniffi_bindgen", - "uniffi_meta", - "uniffi_udl", -] - -[[package]] -name = "uniffi-bindgen-go-fixtures" -version = "0.1.0" -dependencies = [ - "large-enum", - "large-error", - "uniffi-example-arithmetic", - "uniffi-example-callbacks", - "uniffi-example-custom-types", - "uniffi-example-futures", - "uniffi-example-geometry", - "uniffi-example-rondpoint", - "uniffi-example-sprites", - "uniffi-example-todolist", - "uniffi-example-traits", - "uniffi-fixture-callbacks", - "uniffi-fixture-coverall", - "uniffi-fixture-docstring", - "uniffi-fixture-enum-types", - "uniffi-fixture-error-types", - "uniffi-fixture-ext-types", - "uniffi-fixture-ext-types-custom-types", - "uniffi-fixture-ext-types-lib-one", - "uniffi-fixture-ext-types-proc-macro", - "uniffi-fixture-namespaces-media", - "uniffi-fixture-namespaces-net", - "uniffi-fixture-proc-macro", - "uniffi-fixture-simple-fns", - "uniffi-fixture-simple-iface", - "uniffi-fixture-time", - "uniffi-fixture-trait-methods", - "uniffi-fixture-type-limits", - "uniffi-go-fixture-destroy", - "uniffi-go-fixture-empty-string-and-bytes", - "uniffi-go-fixture-errors", - "uniffi-go-fixture-futures", - "uniffi-go-fixture-issue43", - "uniffi-go-fixture-issue45", - "uniffi-go-fixture-name-case", - "uniffi-go-fixture-objects", -] - -[[package]] -name = "uniffi-bindgen-tests" -version = "0.31.0" -dependencies = [ - "async-trait", - "camino", - "glob", - "thiserror 2.0.21", - "uniffi", - "uniffi-bindgen-tests-external-types-source", - "url", -] - -[[package]] -name = "uniffi-bindgen-tests-external-types-source" -version = "0.31.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-bindgen-tests-kotlin" -version = "0.31.0" -dependencies = [ - "camino", - "glob", - "uniffi", - "uniffi-bindgen-tests", -] - -[[package]] -name = "uniffi-bindgen-tests-python" -version = "0.31.0" -dependencies = [ - "camino", - "glob", - "uniffi", - "uniffi-bindgen-tests", -] - -[[package]] -name = "uniffi-bindgen-tests-swift" -version = "0.31.0" -dependencies = [ - "camino", - "glob", - "uniffi", - "uniffi-bindgen-tests", -] - -[[package]] -name = "uniffi-c-api" -version = "0.1.0" -dependencies = [ - "thiserror 1.0.69", - "uniffi", -] - -[[package]] -name = "uniffi-custom-types-builtin" -version = "0.1.0" -dependencies = [ - "once_cell", - "paste", - "thiserror 1.0.69", - "uniffi", -] - -[[package]] -name = "uniffi-dart" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "camino-tempfile", - "cargo_metadata 0.18.1", - "fs_extra", - "genco", - "glob", - "heck 0.5.0", - "lazy_static", - "paste", - "proc-macro2", - "serde", - "stringcase 0.4.0", - "toml", - "uniffi", - "uniffi_bindgen", - "uniffi_build", - "uniffi_dart_macro", - "uniffi_testing", -] - -[[package]] -name = "uniffi-empty-type" -version = "0.1.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-enum-style-test" -version = "0.1.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-error-types-builtin" -version = "0.1.0" -dependencies = [ - "anyhow", - "thiserror 1.0.69", - "uniffi", -] - -[[package]] -name = "uniffi-example-arithmetic" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-example-arithmetic-procmacro" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-example-async-api-client" -version = "0.26.1" -dependencies = [ - "async-trait", - "serde", - "serde_json", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-example-callbacks" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-example-custom-types" -version = "0.22.0" -dependencies = [ - "anyhow", - "bytes", - "uniffi", - "url", -] - -[[package]] -name = "uniffi-example-futures" -version = "0.22.0" -dependencies = [ - "async-std", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-example-geometry" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-example-remote-types" -version = "0.22.0" -dependencies = [ - "anyhow", - "log", - "uniffi", -] - -[[package]] -name = "uniffi-example-rondpoint" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-example-sprites" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-example-todolist" -version = "0.22.0" -dependencies = [ - "once_cell", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-example-traits" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-ext-types-export" -version = "0.1.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-ext-types-import" -version = "0.1.0" -dependencies = [ - "uniffi", - "uniffi-ext-types-export", -] - -[[package]] -name = "uniffi-fixture-benchmarks" -version = "0.22.0" -dependencies = [ - "anyhow", - "camino", - "clap", - "criterion", - "indexmap", - "regex", - "serde_json", - "thiserror 2.0.21", - "uniffi", - "uniffi_bindgen", -] - -[[package]] -name = "uniffi-fixture-callbacks" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-coverall" -version = "0.22.0" -dependencies = [ - "once_cell", - "thiserror 2.0.21", - "uniffi", - "uniffi_meta", -] - -[[package]] -name = "uniffi-fixture-docstring" -version = "0.22.0" -dependencies = [ - "camino", - "glob", - "thiserror 2.0.21", - "uniffi", - "uniffi_bindgen", - "uniffi_testing", -] - -[[package]] -name = "uniffi-fixture-docstring-proc-macro" -version = "0.22.0" -dependencies = [ - "cargo_metadata 0.23.1", - "glob", - "thiserror 2.0.21", - "uniffi", - "uniffi_bindgen", - "uniffi_testing", -] - -[[package]] -name = "uniffi-fixture-enum-types" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-error-types" -version = "0.22.0" -dependencies = [ - "anyhow", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-ext-types" -version = "0.22.0" -dependencies = [ - "anyhow", - "bytes", - "uniffi", - "uniffi-example-custom-types", - "uniffi-fixture-ext-types-custom-types", - "uniffi-fixture-ext-types-external-crate", - "uniffi-fixture-ext-types-lib-one", - "uniffi-fixture-ext-types-sub-lib", - "url", -] - -[[package]] -name = "uniffi-fixture-ext-types-custom-types" -version = "0.22.0" -dependencies = [ - "anyhow", - "bytes", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-ext-types-external-crate" -version = "0.22.0" - -[[package]] -name = "uniffi-fixture-ext-types-http-headermap" -version = "0.22.0" -dependencies = [ - "anyhow", - "bytes", - "http", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-ext-types-lib-one" -version = "0.22.0" -dependencies = [ - "anyhow", - "bytes", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-ext-types-proc-macro" -version = "0.22.0" -dependencies = [ - "anyhow", - "bytes", - "uniffi", - "uniffi-example-custom-types", - "uniffi-fixture-ext-types-custom-types", - "uniffi-fixture-ext-types-lib-one", - "url", -] - -[[package]] -name = "uniffi-fixture-ext-types-sub-lib" -version = "0.22.0" -dependencies = [ - "anyhow", - "uniffi", - "uniffi-fixture-ext-types-lib-one", -] - -[[package]] -name = "uniffi-fixture-futures" -version = "0.21.0" -dependencies = [ - "async-trait", - "futures", - "once_cell", - "thiserror 2.0.21", - "tokio", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-gh-2600" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-keywords-kotlin" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-keywords-rust" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-keywords-swift" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-logging-callback-interface" -version = "0.22.0" -dependencies = [ - "log", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-metadata" -version = "0.1.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", - "uniffi_core", - "uniffi_meta", -] - -[[package]] -name = "uniffi-fixture-multi-arch-extract" -version = "0.22.0" -dependencies = [ - "tempfile", - "uniffi_bindgen", - "xshell", -] - -[[package]] -name = "uniffi-fixture-mutable-records" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-namespaces-media" -version = "0.1.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", - "uniffi-fixture-namespaces-net", -] - -[[package]] -name = "uniffi-fixture-namespaces-net" -version = "0.1.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-proc-macro" -version = "0.22.0" -dependencies = [ - "lazy_static", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-proc-macro-no-implicit-prelude" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-callbacks-omit-labels" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-cdylib-dependency" -version = "0.22.0" - -[[package]] -name = "uniffi-fixture-regression-cdylib-dependency-ffi-crate" -version = "0.22.0" -dependencies = [ - "uniffi", - "uniffi-fixture-regression-cdylib-dependency", -] - -[[package]] -name = "uniffi-fixture-regression-i1015-fully-qualified-types" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-i356-enum-without-int-helpers" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-kotlin-enum-payload-clash" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-kotlin-experimental-unsigned-types" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-missing-newline" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-swift-dictionary-nesting" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-regression-wrong-lower-check" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-rename" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "uniffi", - "url", -] - -[[package]] -name = "uniffi-fixture-simple-fns" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-simple-iface" -version = "0.22.0" -dependencies = [ - "lazy_static", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-struct-default-values" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-swift-codable" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-swift-link-frameworks" -version = "0.1.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-swift-mock-objects" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-swift-omit-argument-labels" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-time" -version = "0.22.0" -dependencies = [ - "chrono", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-trait-methods" -version = "0.22.0" -dependencies = [ - "once_cell", - "thiserror 2.0.21", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-type-limits" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixture-version-mismatch" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-fixtures-wasm-unstable-single-threaded" -version = "0.29.0" -dependencies = [ - "async-trait", - "uniffi", -] - -[[package]] -name = "uniffi-go-fixture-destroy" -version = "1.0.0" -dependencies = [ - "once_cell", - "thiserror 1.0.69", - "uniffi", - "uniffi_build", - "uniffi_macros", -] - -[[package]] -name = "uniffi-go-fixture-empty-string-and-bytes" -version = "1.0.0" -dependencies = [ - "uniffi", - "uniffi_build", - "uniffi_macros", -] - -[[package]] -name = "uniffi-go-fixture-errors" -version = "1.0.0" -dependencies = [ - "thiserror 1.0.69", - "uniffi", - "uniffi_build", - "uniffi_macros", -] - -[[package]] -name = "uniffi-go-fixture-futures" -version = "0.21.0" -dependencies = [ - "async-trait", - "futures", - "once_cell", - "thiserror 1.0.69", - "tokio", - "uniffi", -] - -[[package]] -name = "uniffi-go-fixture-issue43" -version = "1.0.0" -dependencies = [ - "uniffi", - "uniffi-go-fixture-issue45", - "uniffi_build", - "uniffi_macros", -] - -[[package]] -name = "uniffi-go-fixture-issue45" -version = "1.0.0" -dependencies = [ - "uniffi", - "uniffi_build", - "uniffi_macros", -] - -[[package]] -name = "uniffi-go-fixture-name-case" -version = "0.22.0" -dependencies = [ - "glob", - "thiserror 1.0.69", - "uniffi", - "uniffi_bindgen", - "uniffi_testing", -] - -[[package]] -name = "uniffi-go-fixture-objects" -version = "1.0.0" -dependencies = [ - "crossbeam", - "once_cell", - "thiserror 1.0.69", - "uniffi", - "uniffi_build", - "uniffi_macros", -] - -[[package]] -name = "uniffi-reserved-field-name" -version = "0.1.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-type-flattening" -version = "0.1.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi_bindgen" -version = "0.1.0" -dependencies = [ - "anyhow", - "askama 0.16.1", - "camino", - "cargo_metadata 0.23.1", - "fs-err 3.3.2", - "glob", - "goblin", - "heck 0.5.0", - "indexmap", - "once_cell", - "serde", - "tempfile", - "textwrap", - "toml", - "uniffi_internal_macros", - "uniffi_meta", - "uniffi_pipeline", - "uniffi_testing", - "uniffi_udl", -] - -[[package]] -name = "uniffi_build" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "uniffi_bindgen", -] - -[[package]] -name = "uniffi_core" -version = "0.1.0" -dependencies = [ - "anyhow", - "async-compat", - "bytes", - "once_cell", - "static_assertions", -] - -[[package]] -name = "uniffi_dart_macro" -version = "0.1.0" -dependencies = [ - "futures", - "proc-macro2", - "quote", - "stringcase 0.3.0", - "syn 1.0.109", - "uniffi", -] - -[[package]] -name = "uniffi_internal_macros" -version = "0.1.0" -dependencies = [ - "anyhow", - "indexmap", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "uniffi_macros" -version = "0.1.0" -dependencies = [ - "camino", - "fs-err 3.3.2", - "once_cell", - "proc-macro2", - "quote", - "serde", - "syn 2.0.119", - "toml", - "uniffi_build", - "uniffi_meta", -] - -[[package]] -name = "uniffi_meta" -version = "0.1.0" -dependencies = [ - "anyhow", - "siphasher", - "uniffi_internal_macros", - "uniffi_pipeline", -] - -[[package]] -name = "uniffi_pipeline" -version = "0.1.0" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap", - "tempfile", - "uniffi_internal_macros", -] - -[[package]] -name = "uniffi_testing" -version = "0.1.0" -dependencies = [ - "anyhow", - "camino", - "cargo_metadata 0.23.1", - "fs-err 3.3.2", - "once_cell", -] - -[[package]] -name = "uniffi_udl" -version = "0.1.0" -dependencies = [ - "anyhow", - "textwrap", - "uniffi_meta", - "weedle2", -] - -[[package]] -name = "uniffi_uitests" -version = "0.22.0" -dependencies = [ - "thiserror 2.0.21", - "trybuild", - "uniffi", - "uniffi_macros", -] - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "value-bag" -version = "1.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2799ffb329a792ecfd902b71306c8a815a6ef1c0470fa9953a6aa4d4cecbe511" - -[[package]] -name = "waker-fn" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" -dependencies = [ - "js-sys", - "tokio", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.9", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "web-sys" -version = "0.3.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "weedle2" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e" -dependencies = [ - "nom", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - -[[package]] -name = "winnow" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" -dependencies = [ - "memchr", -] - -[[package]] -name = "writeable" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" - -[[package]] -name = "xshell" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e7290c623014758632efe00737145b6867b66292c42167f2ec381eb566a373d" -dependencies = [ - "xshell-macros", -] - -[[package]] -name = "xshell-macros" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32ac00cd3f8ec9c1d33fb3e7958a82df6989c42d747bd326c822b1d625283547" - -[[package]] -name = "yoke" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", - "synstructure", -] - -[[package]] -name = "zerotrie" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "zerovec" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" -dependencies = [ - "serde", - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index 755e5956e..000000000 --- a/Cargo.toml +++ /dev/null @@ -1,150 +0,0 @@ -[workspace] -members = [ - "uniffi/bindgen-tests/external-types", - "uniffi/bindgen-tests/kotlin", - "uniffi/bindgen-tests/kotlin/enum-payload-clash", - "uniffi/bindgen-tests/kotlin/experimental-unsigned-types", - "uniffi/bindgen-tests/kotlin/keywords", - "uniffi/bindgen-tests/lib", - "uniffi/bindgen-tests/python", - "uniffi/bindgen-tests/swift", - "uniffi/bindgen-tests/swift/bridging-header-compile", - "uniffi/bindgen-tests/swift/callbacks-omit-labels", - "uniffi/bindgen-tests/swift/codable", - "uniffi/bindgen-tests/swift/dictionary-nesting", - "uniffi/bindgen-tests/swift/keywords", - "uniffi/bindgen-tests/swift/link-frameworks", - "uniffi/bindgen-tests/swift/mock-objects", - "uniffi/bindgen-tests/swift/omit-labels", - "uniffi/cpp/bindgen", - "uniffi/cpp/fixtures", - "uniffi/cpp/fixtures/async-calls", - "uniffi/cpp/fixtures/c-api", - "uniffi/cpp/fixtures/custom-types-builtin", - "uniffi/cpp/fixtures/empty-type", - "uniffi/cpp/fixtures/enum-style-test", - "uniffi/cpp/fixtures/error-types-builtin", - "uniffi/cpp/fixtures/ext-types-export", - "uniffi/cpp/fixtures/ext-types-import", - "uniffi/cpp/fixtures/reserved-field-name", - "uniffi/cpp/fixtures/type-flattening", - "uniffi/dart", - "uniffi/dart/fixtures/arithmetic", - "uniffi/dart/fixtures/input-scratch", - "uniffi/dart/fixtures/benchmarks", - "uniffi/dart/fixtures/bytes_types", - "uniffi/dart/fixtures/callbacks", - "uniffi/dart/fixtures/custom_types", - "uniffi/dart/fixtures/dart_async", - "uniffi/dart/fixtures/docstring-proc-macro", - "uniffi/dart/fixtures/duration_type_test", - "uniffi/dart/fixtures/enum_variant_collision", - "uniffi/dart/fixtures/hello_world", - "uniffi/dart/fixtures/library_config", - "uniffi/dart/fixtures/map_type", - "uniffi/dart/fixtures/metadata", - "uniffi/dart/fixtures/namespaces", - "uniffi/dart/fixtures/proc-macro", - "uniffi/dart/fixtures/proc-macro-no-implicit-prelude", - "uniffi/dart/fixtures/simple-fns", - "uniffi/dart/fixtures/simple-iface", - "uniffi/dart/fixtures/streams_ext", - "uniffi/dart/fixtures/struct-default-values", - "uniffi/dart/fixtures/trait-interfaces", - "uniffi/dart/fixtures/trait-methods", - "uniffi/dart/fixtures/type-limits", - "uniffi/dart/uniffi_dart_macro", - "uniffi/examples/arithmetic", - "uniffi/examples/arithmetic-procmacro", - "uniffi/examples/async-api-client", - "uniffi/examples/callbacks", - "uniffi/examples/custom-types", - "uniffi/examples/futures", - "uniffi/examples/geometry", - "uniffi/examples/remote-types", - "uniffi/examples/rondpoint", - "uniffi/examples/sprites", - "uniffi/examples/todolist", - "uniffi/examples/traits", - "uniffi/fixtures/benchmarks", - "uniffi/fixtures/callbacks", - "uniffi/fixtures/coverall", - "uniffi/fixtures/docstring", - "uniffi/fixtures/docstring-proc-macro", - "uniffi/fixtures/enum-types", - "uniffi/fixtures/error-types", - "uniffi/fixtures/ext-types/custom-types", - "uniffi/fixtures/ext-types/external-crate", - "uniffi/fixtures/ext-types/http-headermap", - "uniffi/fixtures/ext-types/lib", - "uniffi/fixtures/ext-types/proc-macro-lib", - "uniffi/fixtures/ext-types/sub-lib", - "uniffi/fixtures/ext-types/uniffi-one", - "uniffi/fixtures/futures", - "uniffi/fixtures/gh-2600", - "uniffi/fixtures/keywords/rust", - "uniffi/fixtures/large-enum", - "uniffi/fixtures/large-error", - "uniffi/fixtures/metadata", - "uniffi/fixtures/multi-arch-extract", - "uniffi/fixtures/mutable-records", - "uniffi/fixtures/namespaces/media", - "uniffi/fixtures/namespaces/net", - "uniffi/fixtures/proc-macro", - "uniffi/fixtures/proc-macro-no-implicit-prelude", - "uniffi/fixtures/regressions/cdylib-crate-type-dependency/cdylib-dependency", - "uniffi/fixtures/regressions/cdylib-crate-type-dependency/ffi-crate", - "uniffi/fixtures/regressions/enum-without-i32-helpers", - "uniffi/fixtures/regressions/fully-qualified-types", - "uniffi/fixtures/regressions/logging-callback-interface", - "uniffi/fixtures/regressions/missing-newline", - "uniffi/fixtures/regressions/unary-result-alias", - "uniffi/fixtures/regressions/wrong-lower-check", - "uniffi/fixtures/rename", - "uniffi/fixtures/simple-fns", - "uniffi/fixtures/simple-iface", - "uniffi/fixtures/struct-default-values", - "uniffi/fixtures/trait-methods", - "uniffi/fixtures/type-limits", - "uniffi/fixtures/uitests", - "uniffi/fixtures/uniffi-fixture-time", - "uniffi/fixtures/version-mismatch", - "uniffi/fixtures/wasm-unstable-single-threaded", - "uniffi/go/bindgen", - "uniffi/go/fixtures", - "uniffi/go/fixtures/destroy", - "uniffi/go/fixtures/empty_string_and_bytes", - "uniffi/go/fixtures/errors", - "uniffi/go/fixtures/futures", - "uniffi/go/fixtures/name-case", - "uniffi/go/fixtures/objects", - "uniffi/go/fixtures/regressions/issue43", - "uniffi/go/fixtures/regressions/issue45", - "uniffi/uniffi", - "uniffi/uniffi_bindgen", - "uniffi/uniffi_build", - "uniffi/uniffi_core", - "uniffi/uniffi_internal_macros", - "uniffi/uniffi_macros", - "uniffi/uniffi_meta", - "uniffi/uniffi_pipeline", - "uniffi/uniffi_testing", - "uniffi/uniffi_udl", -] -resolver = "2" - -[workspace.lints.clippy] -# Every suppression says why, so the next lint audit can judge it. The UniFFI fork's -# crates do not inherit this: they keep upstream's lints, so cherry-picks apply unchanged. -allow_attributes_without_reason = "warn" - -# The UniFFI fork's fixtures depend on its crates through the workspace, as upstream's do. -[workspace.dependencies] -uniffi = { path = "uniffi/uniffi", version = "=0.1.0" } -uniffi_bindgen = { path = "uniffi/uniffi_bindgen", version = "=0.1.0" } -uniffi_core = { path = "uniffi/uniffi_core", version = "=0.1.0" } -uniffi_macros = { path = "uniffi/uniffi_macros", version = "=0.1.0" } -uniffi_build = { path = "uniffi/uniffi_build", version = "=0.1.0" } -uniffi_meta = { path = "uniffi/uniffi_meta", version = "=0.1.0" } -uniffi_testing = { path = "uniffi/uniffi_testing", version = "=0.1.0" } -uniffi_udl = { path = "uniffi/uniffi_udl", version = "=0.1.0" } diff --git a/README.md b/README.md index 222a36ea4..f4edcf1d7 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,6 @@ Rust to other places. - **TypeScript**: an own rustc driver that translates a [documented Rust subset](ts/README.md) to TypeScript, without WASM. - **C, then any language**: an [exporter](ffi/README.md) that turns a crate's `pub` API into a C ABI and header with no attributes, sharing the TypeScript driver's front end. -- **Any language**: [a hard fork](uniffi/README.md) of [UniFFI](https://github.com/mozilla/uniffi-rs) with every generator [moq](https://github.com/moq-dev/moq) uses. - **Faster builds**: a reproducible [build-speed benchmark](bench/build/README.md) of upstream's levers on moq, and [rust2-lint](driver/src/bin/rust2-lint/main.rs), which fails a build whose generics' copies cost its codegen more than a budget (`nix run github:moq-dev/rust2#lint -- --help`). Everything here is early; the [quest tree](quest/README.md) holds the plan. @@ -14,11 +13,8 @@ Everything here is early; the [quest tree](quest/README.md) holds the plan. ```bash nix develop # or direnv allow just ci # just check, then just test, as the merge queue runs them - -# The UniFFI fixture suites need every foreign toolchain. -nix develop .#uniffi --command just uniffi fixtures ``` ## License -Licensed under either [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option, unless a directory's own license says otherwise (the UniFFI fork keeps its upstream licenses: MPL-2.0, and MIT for the Dart generator). +Licensed under either [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option. diff --git a/bench/ffi/README.md b/bench/ffi/README.md index 3811994fb..a2c0c1a0e 100644 --- a/bench/ffi/README.md +++ b/bench/ffi/README.md @@ -1,55 +1,13 @@ # Binding benchmark -`just bench-ffi` measures what each of moq's binding wrappers adds over Rust, with moq-ffi at the revision pinned in [pins.toml](pins.toml) built against [the UniFFI fork](../../uniffi/README.md) in this tree. -It runs nightly in CI ([bench-ffi.yml](../../.github/workflows/bench-ffi.yml)), and every fork perf change states its effect with its numbers. - -```bash -just bench-ffi # every wrapper this host runs, three rounds -just bench-ffi --runner py --rounds 1 # a quick smoke test -just bench-ffi --base origin/main # a fork change against its base -``` - -Results land in `target/bench/ffi/`, newest at `target/bench/ffi/latest/report.md`. -Checkouts and builds live in `/var/tmp/rust2-bench-/ffi/`, with their own `CARGO_HOME` and none of the caller's cargo or rustc variables, as in the [build-speed benchmark](../build/README.md). -Runs on one host share that directory, so a second run waits for the first to finish. - -## What runs - -The native runners, their recipes, and the Rust baselines stay in moq beside the wrappers they measure (see moq's [bench/README.md](https://github.com/moq-dev/moq/blob/main/bench/README.md)); this harness drives them. -The browser runner lives here, since moq has no browser wrapper over moq-ffi yet. -Every runner runs the same in-process rounds with no network: each publisher writes one group while every subscriber reads it on its own task. -They sweep frame sizes from 100 B to 1 MiB at one publisher and subscriber, then 1 and 4 publishers by 1 and 4 subscribers at 1 KiB, and time two sync calls (`sequence`, `info`). -Each case reports delivered MB/s and process CPU per MB, and checks every received frame byte for byte. - -- `rust-ffi` calls moq-ffi's API from Rust without crossing the FFI, so a wrapper's ratio to it is what its boundary and wrapper cost. -- `rust-net` runs the same rounds on moq-net, so its ratio is what moq-ffi's handles and runtime cost. -- `go`, `py`, `kt`, `cpp`, `dart`, and `browser` run on Linux and macOS; `swift` runs on macOS only. -- `browser` builds moq-ffi for wasm32, generates its TypeScript with ubrn's `wasm2` player, and runs [browser-page.ts](browser-page.ts) in headless Chromium through [browser.ts](browser.ts). Its CPU is every thread of the renderer, read over CDP. No ubrn release reads UniFFI 0.32 yet, so [pins.toml](pins.toml) pins the head of [jhugman/uniffi-bindgen-react-native#468](https://github.com/jhugman/uniffi-bindgen-react-native/pull/468), and the run builds its CLI and packs its `@ubjs/core` and `@ubjs/wasm` runtimes from that source. - -The run enters the pinned moq's own dev shell, so every wrapper builds with the toolchains moq ships with. -moq's Go, Dart, and C++ scripts find their generators on `PATH`, where the run puts the fork's. -Its Kotlin, Python, and Swift generator and moq-ffi's runtime are the `uniffi` crate, which the run points at the fork's path in every manifest; the run fails if any UniFFI crate still resolves elsewhere. -For the browser, the run also links ubrn's `uniffi-runtime-wasm` helper crate into moq-ffi on wasm32, as ubrn's player requires. -Bump a pin in its own change, since numbers on either side of it do not compare. - -## Variants - -- `fork` builds against this tree. -- `control` reruns fork's builds, so its change against fork is the run's noise floor: an A/A control. -- `base`, with `--base REV`, builds against the fork at another rust2 revision, so fork's change against it is the effect of the change. - -An untimed warm-up round builds every runner once per checkout. -The timed rounds interleave the variants and rotate which goes first each round, so drift over a long job spreads across all of them. -The report shows each case's trimmed mean over the rounds (without the fastest and slowest) with its cost against `rust-ffi`, taken within each round so drift between rounds cancels, then each comparison as a change in that cost, so one slow round on a busy host does not move it. -`results.jsonl` keeps every round's value, mean, and standard deviation. -The host, its load average before and after, and every toolchain's version head the report. -No threshold is set: the numbers inform a decision, they do not gate one. +What moq's bindings cost over Rust, measured before [rust2-ffi](../../ffi/README.md) replaced UniFFI. +The harness that built moq-ffi against the UniFFI fork was deleted with the fork; [its quest](/quest/m1/ffi-export/bench.md) rebuilds it on rust2-ffi, against the targets below. ## BoltFFI comparison Before forking UniFFI, moq compared it with [BoltFFI](https://github.com/boltffi/boltffi) 0.31.1 on a slice of moq-ffi bound by each generator, measured from Python and Kotlin with a Rust floor. Its harness is deleted; [moq-dev/moq@0f986d9](https://github.com/moq-dev/moq/tree/0f986d9fdb7c074b0bd4b34739f7199c3bf2d9e5/bench/ffi-gen) holds it if a decision needs fresh numbers. -BoltFFI's numbers are the targets for the fork's backends: its speed comes from calling conventions a UniFFI fork can adopt one backend at a time (a CPython extension instead of `ctypes`, JNI instead of JNA, and bulk byte copies), not from its core. +BoltFFI's numbers are the targets for rust2-ffi's generators: its speed comes from calling conventions (a CPython extension instead of `ctypes`, JNI instead of JNA, and bulk byte copies), not from its core. Measured 2026-10-16 on an Intel Core Ultra 7 270K Plus (24 threads), Linux, at moq `b4eab0db1`, on a shared host (load average 8 to 29), so cells are medians of 3 rounds. Rust 1.98.1, CPython 3.14.7, OpenJDK 17 with Kotlin 2.4.20 and kotlinx-coroutines 1.11.0, JNA 5.19.1. diff --git a/bench/ffi/browser-page.ts b/bench/ffi/browser-page.ts deleted file mode 100644 index a0dd5acfa..000000000 --- a/bench/ffi/browser-page.ts +++ /dev/null @@ -1,161 +0,0 @@ -/** - * The browser runner of the binding benchmark: moq-ffi bound by UniFFI over ubrn's - * `wasm2` player, running the same in-process rounds as moq's other runners. - * - * `browser.ts` bundles this page, serves it, and reads the renderer's CPU for it. - */ -import { - MoqBroadcastProducer, - MoqOriginConfig, - MoqOriginProducer, - MoqTrackInfo, - type MoqTrackConsumerLike, - uniffiInitAsync, -} from "./dist/index.ts"; - -interface Result { - name: string; - unit: string; - value: number; -} - -declare global { - interface Window { - /** Renderer CPU seconds, read by the driver over CDP. */ - rendererCpu(): Promise; - runBench(seconds: number): Promise; - } -} - -const WARMUP = 3; -// Each case's origin cache budget: far above one round's groups, so eviction only -// reclaims groups every subscriber has read, and memory stays flat over a long run. -const CACHE_BYTES = 64n << 20n; -// Far longer than any honest round, so only a lost wakeup trips it. -const ROUND_TIMEOUT_MS = 30_000; - -/** One throughput case: `publishers` tracks, each read by `subscribers` consumers. */ -class Case { - constructor( - readonly size: number, - readonly publishers: number, - readonly subscribers: number, - ) {} - - /** Frames per group, holding a group under moq-net's 32 MB group cache. */ - get frames(): number { - return Math.min(Math.max(Math.floor((8 << 20) / this.size), 1), 64); - } - - get delivered(): number { - return this.publishers * this.subscribers * this.frames * this.size; - } - - get name(): string { - return `size=${this.size}/pub=${this.publishers}/sub=${this.subscribers}`; - } -} - -// Frame sizes at one publisher and subscriber, then fan-out at 1 KiB. -const CASES = [ - ...[100, 1024, 64 * 1024, 1024 * 1024].map((size) => new Case(size, 1, 1)), - ...[ - [1, 4], - [4, 1], - [4, 4], - ].map(([p, s]) => new Case(1024, p, s)), -]; - -/** A non-uniform payload, so a zero-filled or truncated copy fails the check. */ -function payload(size: number): ArrayBuffer { - const bytes = new Uint8Array(size); - for (let i = 0; i < size; i++) bytes[i] = i % 251; - return bytes.buffer; -} - -function same(a: ArrayBuffer, b: ArrayBuffer): boolean { - if (a.byteLength !== b.byteLength) return false; - const x = new Uint8Array(a); - const y = new Uint8Array(b); - for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return false; - return true; -} - -async function read(c: Case, consumer: MoqTrackConsumerLike, want: ArrayBuffer, n: number): Promise { - const group = await consumer.recvGroup(); - if (!group) throw new Error("track ended"); - for (let f = 0; f < c.frames; f++) { - const frame = await group.readFrame(); - if (!frame) throw new Error("group ended"); - if (!same(frame.payload, want)) throw new Error(`corrupt frame ${f} of round ${n}`); - if (frame.timestampUs !== BigInt(n * c.frames + f)) throw new Error(`wrong timestamp on frame ${f} of round ${n}`); - } -} - -async function within(promise: Promise, ms: number, what: string): Promise { - let timer: ReturnType | undefined; - try { - return await Promise.race([ - promise, - new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error(`${what} did not finish in ${ms} ms`)), ms); - }), - ]); - } finally { - clearTimeout(timer); - } -} - -async function throughput(c: Case, budget: number, results: Result[]): Promise { - const origin = new MoqOriginProducer(MoqOriginConfig.create({ cacheCapacityBytes: CACHE_BYTES })); - const broadcast = origin.createBroadcast("bench"); - const info = MoqTrackInfo.create({ timescale: 1_000_000n }); - const tracks = Array.from({ length: c.publishers }, (_, p) => broadcast.publishTrack(String(p), info)); - const consumers = tracks.flatMap((track) => Array.from({ length: c.subscribers }, () => track.consume(undefined))); - const bytes = payload(c.size); - - // Each consumer reads on its own task while this one writes each group in turn. - const step = async (n: number) => { - const readers = consumers.map((consumer) => read(c, consumer, bytes, n)); - for (const track of tracks) { - const group = track.appendGroup(); - for (let f = 0; f < c.frames; f++) group.writeFrame({ payload: bytes, timestampUs: BigInt(n * c.frames + f) }); - group.finish(); - } - await within(Promise.all(readers), ROUND_TIMEOUT_MS, `round ${n} of ${c.name}`); - }; - - for (let n = 0; n < WARMUP; n++) await step(n); - const cpuStart = await window.rendererCpu(); - const start = performance.now(); - let n = WARMUP; - while (performance.now() - start < budget * 1000) await step(n++); - const wall = (performance.now() - start) / 1000; - const cpu = (await window.rendererCpu()) - cpuStart; - const mb = ((n - WARMUP) * c.delivered) / 1e6; - results.push({ name: `throughput/${c.name}`, unit: "MB/s", value: mb / wall }); - results.push({ name: `cpu/${c.name}`, unit: "ms/MB", value: (cpu * 1e3) / mb }); -} - -function call(name: string, budget: number, fn: () => unknown, results: Result[]): void { - const start = performance.now(); - let calls = 0; - while (performance.now() - start < budget * 1000) { - for (let i = 0; i < 1000; i++) fn(); - calls += 1000; - } - results.push({ name: `call/${name}`, unit: "ns", value: ((performance.now() - start) * 1e6) / calls }); -} - -window.runBench = async (budget: number): Promise => { - await uniffiInitAsync(new URL("/moq_ffi.wasm", location.href)); - const results: Result[] = []; - for (const c of CASES) await throughput(c, budget, results); - - const track = new MoqBroadcastProducer().publishTrack("calls", undefined); - const group = track.appendGroup().consume(); - call("sequence", budget, () => group.sequence(), results); - const consumer = track.consume(undefined); - call("info", budget, () => consumer.info(), results); - return results; -}; diff --git a/bench/ffi/browser.sh b/bench/ffi/browser.sh deleted file mode 100755 index a02a7d263..000000000 --- a/bench/ffi/browser.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash -# The browser runner: builds moq-ffi for wasm32 in a moq checkout, generates its -# TypeScript over ubrn's wasm2 player, and runs browser-page.ts in headless Chromium. -# Runs inside moq's dev shell, which carries cargo, wasm-bindgen, bun, and Chromium. -# Usage: browser.sh CHECKOUT DIR UBRN, with MOQ_BENCH_DIR and MOQ_BENCH_SECONDS set. -set -euo pipefail - -bench=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -checkout=$1 dir=$2 ubrn=$3 -mkdir -p "$dir" - -(cd "$checkout" && cargo build --locked -q -p moq-ffi --profile wasm-release --target wasm32-unknown-unknown) - -# ubrn wants a package.json and its config beside it. Playwright matches the shell's Chromium. -jq -n --arg pkgs "$ubrn/pkgs" --arg playwright "$PLAYWRIGHT_VERSION" '{ - name: "moq-ffi-bench", - private: true, - repository: {type: "git", url: "https://github.com/moq-dev/rust2"}, - dependencies: { - "@ubjs/core": "file:\($pkgs)/ubjs-core.tgz", - "@ubjs/wasm": "file:\($pkgs)/ubjs-wasm.tgz", - playwright: $playwright - } -}' >"$dir/package.json" -cat >"$dir/ubrn.config.yaml" </dev/null -bun build page.ts --outfile bundle/page.js --target browser >/dev/null -cp dist/moq_ffi.wasm bundle/ -bun driver.ts bundle diff --git a/bench/ffi/browser.ts b/bench/ffi/browser.ts deleted file mode 100644 index b0a3b51cc..000000000 --- a/bench/ffi/browser.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Runs the browser runner (`browser-page.ts`) in headless Chromium and writes - * `$MOQ_BENCH_DIR/browser.json`, as moq's other runners write theirs. - * - * Usage: bun browser.ts DIST, where DIST holds the bundled `page.js` and `moq_ffi.wasm`. - */ -import { join } from "node:path"; -import { chromium } from "playwright"; - -const dist = process.argv[2]; -const out = process.env.MOQ_BENCH_DIR; -const seconds = Number(process.env.MOQ_BENCH_SECONDS ?? "1"); -if (!dist || !out) throw new Error("usage: MOQ_BENCH_DIR=... bun browser.ts DIST"); -if (!Number.isFinite(seconds) || seconds <= 0) throw new Error("MOQ_BENCH_SECONDS must be positive and finite"); - -const server = Bun.serve({ - hostname: "127.0.0.1", - port: 0, - async fetch(req) { - const path = new URL(req.url).pathname; - if (path === "/") - return new Response(``, { - headers: { "content-type": "text/html" }, - }); - const file = Bun.file(join(dist, path)); - return (await file.exists()) ? new Response(file) : new Response("not found", { status: 404 }); - }, -}); - -const browser = await chromium.launch({ channel: "chromium", headless: true }); -try { - const page = await browser.newPage(); - const errors: string[] = []; - page.on("pageerror", (error) => errors.push(error.message)); - page.on("console", (message) => { - if (message.text().includes("panicked at")) errors.push(`panic: ${message.text()}`); - }); - // Process CPU like the other runners' getrusage: every thread of the renderers, - // where the module, its runtime, and the page's garbage collection run. - const system = await browser.newBrowserCDPSession(); - await page.exposeFunction("rendererCpu", async () => { - const { processInfo } = (await system.send("SystemInfo.getProcessInfo")) as { - processInfo: { type: string; cpuTime: number }[]; - }; - return processInfo.filter((p) => p.type === "renderer").reduce((sum, p) => sum + p.cpuTime, 0); - }); - await page.goto(`http://127.0.0.1:${server.port}/`); - await page.waitForFunction(() => typeof window.runBench === "function"); - const results = await page.evaluate((budget) => window.runBench(budget), seconds); - if (errors.length) throw new Error(errors.join("; ")); - await Bun.write(join(out, "browser.json"), JSON.stringify(results, null, 2)); - console.log(`browser bench: wrote ${join(out, "browser.json")} (Chromium ${browser.version()})`); -} finally { - await browser.close(); - server.stop(true); -} diff --git a/bench/ffi/pins.toml b/bench/ffi/pins.toml deleted file mode 100644 index 985f12c27..000000000 --- a/bench/ffi/pins.toml +++ /dev/null @@ -1,12 +0,0 @@ -# What `just bench-ffi` builds. Changing a pin is a pin bump: land it on its own -# so numbers on either side of it are not compared. - -[moq] -git = "https://github.com/moq-dev/moq" -rev = "0f986d9fdb7c074b0bd4b34739f7199c3bf2d9e5" - -# The browser runner's generator and runtime. No release reads UniFFI 0.32 yet, -# so this is the head of jhugman/uniffi-bindgen-react-native#468, which does. -[ubrn] -git = "https://github.com/jhugman/uniffi-bindgen-react-native" -rev = "06f0a30d257573ffcc852e84e814670d53085979" diff --git a/bench/ffi/report.jq b/bench/ffi/report.jq deleted file mode 100644 index 513d8adca..000000000 --- a/bench/ffi/report.jq +++ /dev/null @@ -1,73 +0,0 @@ -# Renders a run as Markdown. Inputs: $host (host.json) and $results -# (results.jsonl). Run with `jq -n -r`. - -def fixed(p): (. * pow(10; p) | round) / pow(10; p) | tostring; -def num: if . >= 100 then round | tostring elif . >= 10 then fixed(1) elif . >= 1 then fixed(2) else fixed(3) end; -def pct: (. * 100 | fixed(1)) as $p | if . > 0 then "+\($p)%" else "\($p)%" end; -def row: "| " + join(" | ") + " |"; -# How much more a result costs than another: time and CPU as they are, throughput inverted. -def cost($other): if .unit == "MB/s" then $other.trimmed / .trimmed else .trimmed / $other.trimmed end; -# Baselines first, then the wrappers in a stable order. -def runners: ["rust-net", "rust-ffi", "go", "python", "kotlin", "cpp", "dart", "swift", "browser"] as $known - | (map(.runner) | unique) as $seen - | ($known | map(select(. as $r | $seen | index($r)))) + ($seen - $known); -# In the order rust-ffi reports them; a runner may order its cases differently. -def cases: group_by(.name) - | map({name: .[0].name, unit: .[0].unit, order: ((map(select(.runner == "rust-ffi") | .order) | min) // 1e9)}) - | sort_by(.order); - -# One table of `$variant`, each cell drawn by `cell` from {result, by}. -def matrix($variant; cell): - map(select(.variant == $variant)) as $rows - | ($rows | map({key: "\(.runner)/\(.name)", value: .}) | from_entries) as $by - | ($rows | runners) as $columns - | (["case", "unit"] + $columns | row), - ("| --- | --- |" + ($columns | map(" ---: |") | join(""))), - ( - $rows | cases[] | . as $case - | [$case.name, $case.unit] - + ($columns | map($by["\(.)/\($case.name)"] as $r | if $r == null then "" else {result: $r, by: $by} | cell end)) - | row - ); - -# The change of each of `$variant`'s results against its base's. -def change($variant): - . as $all - | ($all | map(select(.variant == $variant)) | first | .base) as $base - | ($all | map(select(.variant == $base)) | map({key: "\(.runner)/\(.name)", value: .}) | from_entries) as $baseline - | $all | matrix($variant; .result as $r | $baseline["\($r.runner)/\($r.name)"] as $b | if $b == null then "" else ($r | cost($b)) - 1 | pct end); - -$host[0] as $h -| $results as $results -| [ - "# Binding benchmark", - "", - "\($h.date) on \($h.cpu) (\($h.cpus) CPUs, \($h.memory)), \($h.os), runner `\($h.runner)`; load average \($h.load_start) before, \($h.load_end) after.", - "rust2 `\($h.rust2[:12])`\(if $h.base == "" then "" else ", base `\($h.base[:12])`" end); moq `\($h.moq[:12])`\(if ($h.ubrn // "") == "" then "" else ", ubrn `\($h.ubrn[:12])`" end); \($h.rounds) round\(if $h.rounds == 1 then "" else "s" end) of \($h.seconds) s per case.", - "\([$h.tools[] | select(. != "missing")] | join("; ")).", - "", - "Each cell is the trimmed mean over the rounds (without the fastest and slowest), and the trimmed mean of its cost against `rust-ffi` in the same round: above 1x is slower or costlier.", - "`rust-ffi` calls moq-ffi's API from Rust without crossing the FFI; `rust-net` runs the same rounds on moq-net, below moq-ffi's handles and runtime.", - "", - "## fork", - "", - ($results | matrix("fork"; .result as $r | "\($r.trimmed | num)" + (if $r.ratio == null then "" else " (\($r.ratio | num)x)" end))), - "", - "## Noise: control against fork", - "", - "`control` reruns fork's builds in the same rounds, so its change is this run's noise floor.", - "Change in trimmed-mean cost (time per call, CPU per MB, or the inverse of throughput): negative is cheaper.", - "", - ($results | change("control")), - ( - if $h.base == "" then empty else - "", - "## Change: fork against base", - "", - "The change in cost from base to fork. Compare it with the noise floor above.", - "", - ($results | change("fork")) - end - ) -] -| .[] diff --git a/bench/ffi/run.sh b/bench/ffi/run.sh deleted file mode 100755 index fcfefed9c..000000000 --- a/bench/ffi/run.sh +++ /dev/null @@ -1,382 +0,0 @@ -#!/usr/bin/env bash -# Measures what each of moq's binding wrappers adds over Rust, with moq-ffi at -# the revision in pins.toml built against this tree's UniFFI fork. -# Usage and output are described in README.md. -set -euo pipefail - -bench=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -root=$(cd "$bench/../.." && pwd -P) - -die() { - echo "bench-ffi: $*" >&2 - exit 1 -} - -usage() { - cat <<'EOF' -Usage: just bench-ffi [OPTIONS] - -Options: - --runner NAME Measure only this wrapper (repeatable): go, py, kt, cpp, dart, - browser, or swift (macOS). Default: every one this host runs. - The Rust baselines always run. - --rounds N Timed rounds per variant (default: 3) - --seconds S Time budget per case and round (default: 1) - --base REV Also measure the fork at this rust2 revision, as `base` - --out DIR Write results to this new or empty directory - (default: target/bench/ffi/) -EOF -} - -# The result files each runner writes into MOQ_BENCH_DIR. -outputs() { - case $1 in - rust) echo rust-ffi rust-net ;; - py) echo python ;; - kt) echo kotlin ;; - *) echo "$1" ;; - esac -} - -# Summarizes a results directory's raw samples and renders its report.md. One -# sample per runner, case, variant, and round, then one record per runner, case, -# and variant. A wrapper's ratio to rust-ffi is taken within each round and -# variant, so drift between rounds cancels. Trimmed means, which drop each -# variant's fastest and slowest round, so one slow round on a busy host does not -# move a comparison. -report() { - local dir=$1 file rel - for file in "$dir"/raw/*/[0-9]*/*.json; do - rel=${file#"$dir/raw/"} - jq -c --arg variant "${rel%%/*}" --argjson round "$(cut -d/ -f2 <<<"$rel")" --arg runner "$(basename "$file" .json)" \ - 'to_entries[] | .value + {$variant, $round, $runner, order: .key} | {variant, round, runner, name, unit, value, order}' "$file" - done >"$dir/samples.jsonl" - jq -s -c --slurpfile host "$dir/host.json" ' - def mean: add / length; - def trimmed: sort | if length > 2 then .[1:-1] else . end | mean; - def worse($b): if .unit == "MB/s" then $b / .value else .value / $b end; - (map(select(.runner == "rust-ffi") | {key: "\(.variant)/\(.round)/\(.name)", value: .value}) | from_entries) as $rust - | map(. + {ratio: (if .runner == "rust-ffi" then null else worse($rust["\(.variant)/\(.round)/\(.name)"]) end)}) - | group_by([.variant, .runner, .name])[] - | map(.value) as $v - | ($v | mean) as $mean - | { - variant: .[0].variant, - base: ({control: "fork", fork: (if $host[0].base == "" then null else "base" end)}[.[0].variant]), - runner: .[0].runner, - name: .[0].name, - unit: .[0].unit, - trimmed: ($v | trimmed), - $mean, - stddev: (if ($v | length) > 1 then $v | map(. - $mean | . * .) | add / (length - 1) | sqrt else null end), - min: ($v | min), - max: ($v | max), - ratio: (if .[0].ratio == null then null else map(.ratio) | trimmed end), - values: $v, - order: (map(.order) | min) - }' "$dir/samples.jsonl" >"$dir/results.jsonl" - jq -n -r -f "$bench/report.jq" --slurpfile host "$dir/host.json" \ - --slurpfile results "$dir/results.jsonl" >"$dir/report.md" -} - -# Inside moq's dev shell: one untimed round per checkout, then the timed rounds, -# interleaving the variants and rotating which goes first each round. -measure() { - local out=$1 plan seconds rounds ubrn count i j variant checkout - local -a runners variants - plan=$out/plan.json - seconds=$(jq -r .seconds "$plan") - rounds=$(jq -r .rounds "$plan") - ubrn=$(jq -r .ubrn "$plan") - mapfile -t runners < <(jq -r '.runners[]' "$plan") - mapfile -t variants < <(jq -r '.variants[].name' "$plan") - count=${#variants[@]} - - jq -n \ - --arg rustc "$(rustc -V)" \ - --arg python "$(python3 --version)" \ - --arg go "$(go version 2>/dev/null || echo missing)" \ - --arg java "$(java -version 2>&1 | head -1 || echo missing)" \ - --arg dart "$(dart --version 2>&1 || echo missing)" \ - --arg cmake "$(cmake --version 2>/dev/null | head -1 || echo missing)" \ - --arg cxx "$(c++ --version 2>/dev/null | head -1 || echo missing)" \ - --arg swift "$(swift --version 2>/dev/null | head -1 || echo missing)" \ - --arg playwright "Playwright ${PLAYWRIGHT_VERSION:-missing}" \ - '$ARGS.named' >"$out/tools.json" - - # One round, timed or not, of every runner on one variant. - run_round() { # variant round - local variant=$1 round=$2 checkout generators browser dest runner log file - checkout=$(jq -r --arg n "$variant" '.variants[] | select(.name == $n) | .checkout' "$plan") - generators=$(jq -r --arg n "$variant" '.variants[] | select(.name == $n) | .generators' "$plan") - browser=$(jq -r --arg n "$variant" '.variants[] | select(.name == $n) | .browser' "$plan") - dest=$out/raw/$variant/$round - mkdir -p "$dest" - for runner in rust "${runners[@]}"; do - log=$out/logs/$variant.$round.$runner.log - echo "bench-ffi: $variant round $round $runner" - ( - cd "$checkout" - export PATH=$generators:$PATH MOQ_BENCH_DIR=$dest MOQ_BENCH_SECONDS=$seconds - # Each runner builds moq-ffi with its own features and environment; in a - # shared target directory they rebuild each other every round. Dart's - # script hardcodes the default one, and its host build scripts land in - # target/release, so the others leave that directory to it. - case $runner in - rust | go | py | kt | cpp) export CARGO_TARGET_DIR=$checkout/target/bench-$runner ;; - esac - case $runner in - # As `just rs test` runs it, minus its clippy gate: lints are not this run's to judge. - rust) bash sh/rs/nextest.sh cargo nextest run --locked --tests -p moq-ffi --cargo-profile release \ - -E 'test(bench::benchmark_ffi)' --run-ignored only ;; - go) just go bench -benchtime="${seconds}s" ;; - browser) "$bench/browser.sh" "$checkout" "$browser" "$ubrn" ;; - *) just "$runner" bench ;; - esac - ) >"$log" 2>&1 || { tail -40 "$log" >&2 && die "$runner failed on $variant; see $log"; } - for file in $(outputs "$runner"); do - [[ -s $dest/$file.json ]] || die "$runner wrote no $file.json on $variant; see $log" - done - done - } - - # The warm-up builds every runner once per checkout, so no build lands in a timed round. - local -A warmed=() - for variant in "${variants[@]}"; do - checkout=$(jq -r --arg n "$variant" '.variants[] | select(.name == $n) | .checkout' "$plan") - [[ -z ${warmed[$checkout]:-} ]] || continue - warmed[$checkout]=1 - run_round "$variant" warmup - done - for ((i = 0; i < rounds; i++)); do - for ((j = 0; j < count; j++)); do - run_round "${variants[(i + j) % count]}" "$i" - done - done -} - -case ${1:-} in - measure) - measure "${2:?measure needs a results directory}" - exit 0 - ;; - report) - report "${2:?report needs a results directory}" - exit 0 - ;; -esac - -all_runners=(go py kt cpp dart browser) -[[ $(uname -s) != Darwin ]] || all_runners+=(swift) -runners=() -rounds=3 -seconds=1 -base= -out= -while (($#)); do - case $1 in - --runner) runners+=("${2:?--runner needs a name}") && shift 2 ;; - --rounds) rounds=${2:?--rounds needs a count} && shift 2 ;; - --seconds) seconds=${2:?--seconds needs a duration} && shift 2 ;; - --base) base=${2:?--base needs a revision} && shift 2 ;; - --out) out=${2:?--out needs a directory} && shift 2 ;; - -h | --help) usage && exit 0 ;; - *) usage >&2 && die "unknown argument: $1" ;; - esac -done -[[ $rounds =~ ^[1-9][0-9]*$ ]] || die "--rounds must be a positive integer, got $rounds" -[[ $seconds =~ ^[0-9]*\.?[0-9]+$ && $seconds != 0 ]] || die "--seconds must be a positive number, got $seconds" -((${#runners[@]})) || runners=("${all_runners[@]}") -for runner in "${runners[@]}"; do - [[ " ${all_runners[*]} " == *" $runner "* ]] || die "unknown runner on this host: $runner" -done - -# Cargo reads every .cargo/config.toml above its working directory, and a user's -# (say, a target-cpu rustflag) would change the code measured. Build outside -# $HOME, with a private CARGO_HOME and none of the caller's cargo or rustc variables. -work=/var/tmp/rust2-bench-$(id -un)/ffi -results=$root/target/bench/ffi -out=${out:-$results/$(date -u +%Y%m%dT%H%M%SZ)} -[[ -z $(find "$out" -mindepth 1 -print -quit 2>/dev/null) ]] || die "$out is not empty; pass a new --out" -mkdir -p "$work" "$out/logs" -# Physical paths: on macOS /var is a symlink, and a --base revision that still has -# uniffi_bindgen's askama.toml cannot build through one. -work=$(cd "$work" && pwd -P) -# Every run shares the checkouts and builds under $work, and timings taken side -# by side would measure each other, so runs take turns. -exec 9>"$work/lock" -flock -n 9 || { echo "bench-ffi: waiting for another run to release $work" && flock 9; } -out=$(cd "$out" && pwd) -dir=$work -while :; do - for f in "$dir/.cargo/config" "$dir/.cargo/config.toml"; do - [[ ! -e $f ]] || die "$f would configure the builds; move it" - done - [[ $dir != / ]] || break - dir=$(dirname "$dir") -done -caller_vars=("${!CARGO@}" "${!RUSTC@}" "${!RUSTDOC@}" "${!RUSTUP@}") -[[ -z ${RUSTFLAGS+set} ]] || caller_vars+=(RUSTFLAGS) -if ((${#caller_vars[@]})); then - echo "bench-ffi: ignoring ${caller_vars[*]}" - unset "${caller_vars[@]}" -fi -export CARGO_HOME=$work/cargo-home - -moq_git=$(taplo get -f "$bench/pins.toml" moq.git) -moq_rev=$(taplo get -f "$bench/pins.toml" moq.rev) -ubrn_git=$(taplo get -f "$bench/pins.toml" ubrn.git) -ubrn_rev=$(taplo get -f "$bench/pins.toml" ubrn.rev) -fork_rev=$(git -C "$root" rev-parse HEAD) -[[ -z $(git -C "$root" status --porcelain -- uniffi Cargo.toml Cargo.lock) ]] || fork_rev+="-dirty" -base_rev= -if [[ -n $base ]]; then - base_rev=$(git -C "$root" rev-parse --verify "$base^{commit}") || die "unknown revision: $base" -fi - -# Builds the fork's Go, Dart, and C++ generators from a rust2 tree. moq's scripts -# find them on PATH; its own Kotlin, Python, and Swift generator builds from the -# redirected `uniffi` crate. -generators() { # tree dest - local tree=$1 dest=$2 bin - CARGO_TARGET_DIR=$dest/target cargo build --locked -q --manifest-path "$tree/Cargo.toml" \ - -p uniffi-bindgen-go -p uniffi-bindgen-cpp -p uniffi-dart --features uniffi-dart/binary --bins - mkdir -p "$dest/bin" - for bin in uniffi-bindgen-go uniffi-bindgen-cpp uniffi_bindgen_dart; do - ln -sfn "$dest/target/debug/$bin" "$dest/bin/$bin" - done -} - -# Clones a repository at a pinned revision, undoing anything an earlier run left -# in its tracked files. -clone() { # git rev dir - local url=$1 rev=$2 dir=$3 - if [[ ! -d $dir/.git ]]; then - git init -q "$dir" - git -C "$dir" remote add origin "$url" - fi - if [[ $(git -C "$dir" rev-parse -q --verify HEAD || true) != "$rev" ]]; then - git -C "$dir" fetch -q --depth 1 origin "$rev" - git -C "$dir" checkout -q --detach FETCH_HEAD - fi - git -C "$dir" reset -q --hard "$rev" - git -C "$dir" clean -qfd -} - -# Builds ubrn's CLI and packs its two TypeScript runtimes, @ubjs/core and @ubjs/wasm. -ubrn() { # dir - local dir=$1 - clone "$ubrn_git" "$ubrn_rev" "$dir/src" - [[ $(cat "$dir/stamp" 2>/dev/null) == "$ubrn_rev" ]] && return - rm -rf "${dir:?}/bin" "${dir:?}/pkgs" - cargo install --locked -q --root "$dir" --path "$dir/src/crates/ubrn_cli" - mkdir -p "$dir/pkgs" - (cd "$dir/src/typescript" && npm ci -s --no-audit --no-fund && npm run -s build && - npm pack -s --pack-destination "$dir/pkgs" >/dev/null) - (cd "$dir/src/runtimes/wasm" && npm ci -s --no-audit --no-fund && npm pack -s --pack-destination "$dir/pkgs" >/dev/null) - mv "$dir"/pkgs/ubjs-core-*.tgz "$dir/pkgs/ubjs-core.tgz" - mv "$dir"/pkgs/ubjs-wasm-*.tgz "$dir/pkgs/ubjs-wasm.tgz" - echo "$ubrn_rev" >"$dir/stamp" -} - -# Clones moq at the pin and points every `uniffi` dependency at the fork in `tree`. -checkout() { # tree dir - local tree=$1 dir=$2 strays - clone "$moq_git" "$moq_rev" "$dir" - # A crate keeps its upstream name but not its version, so `[patch]` cannot - # redirect it: rewrite each `uniffi` dependency's source to the fork's path. - git -C "$dir" ls-files -z '*Cargo.toml' | (cd "$dir" && xargs -0 sed -i -E \ - -e "s#^(uniffi = )\"[^\"]*\"\$#\\1{ path = \"$tree/uniffi/uniffi\" }#" \ - -e "s#^(uniffi = \\{ )(version = \"[^\"]*\"|git = \"[^\"]*\", (rev|tag|branch) = \"[^\"]*\")#\\1path = \"$tree/uniffi/uniffi\"#") - # Resolving without --locked updates the lockfile to the fork, so moq's own - # --locked builds accept it. Every uniffi crate must then be the fork's. - strays=$(cargo metadata --format-version 1 --manifest-path "$dir/Cargo.toml" | jq -r --arg fork "$tree/uniffi/" ' - .packages[] - | select(.name | test("^uniffi(_|$)")) - | select(.manifest_path | startswith($fork) | not) - | "\(.name) \(.version) from \(.source // .manifest_path)"') - [[ -z $strays ]] || die "moq still builds upstream UniFFI: $(tr '\n' ' ' <<<"$strays")" - # ubrn's player calls an allocator and panic hook its helper crate exports on wasm32. - if [[ -n $browser ]]; then - sed -i "/^uniffi = { workspace = true, features = \[\"wasm-unstable-single-threaded\"\] }\$/a uniffi-runtime-wasm = { path = \"$work/ubrn/src/runtimes/wasm/helper-crate\" }" \ - "$dir/rs/moq-ffi/Cargo.toml" - sed -i 's/^uniffi::setup_scaffolding!/#[cfg(target_arch = "wasm32")]\nextern crate uniffi_runtime_wasm as _;\n\n&/' "$dir/rs/moq-ffi/src/lib.rs" - if ! grep -q '^uniffi-runtime-wasm = ' "$dir/rs/moq-ffi/Cargo.toml" || - ! grep -q '^extern crate uniffi_runtime_wasm' "$dir/rs/moq-ffi/src/lib.rs"; then - die "could not link ubrn's runtime into moq-ffi; its manifest or crate root moved" - fi - cargo metadata --format-version 1 --manifest-path "$dir/Cargo.toml" >/dev/null - fi -} - -browser= -if [[ " ${runners[*]} " == *" browser "* ]]; then - browser=1 - echo "bench-ffi: preparing ubrn" - ubrn "$work/ubrn" -fi - -variants=() -add_variant() { # name tree - variants+=("$(jq -n -c --arg name "$1" --arg checkout "$work/moq/$1" --arg generators "$work/generators/$1/bin" \ - --arg browser "$work/browser/$1" '$ARGS.named')") - echo "bench-ffi: preparing $1" - generators "$2" "$work/generators/$1" - checkout "$2" "$work/moq/$1" -} -add_variant fork "$root" -# The A/A control reruns fork's builds, so its change is the run's noise floor. -variants+=("$(jq -c '.name = "control"' <<<"${variants[0]}")") -if [[ -n $base_rev ]]; then - tree=$work/rust2-base - git -C "$root" worktree remove --force "$tree" 2>/dev/null || rm -rf "$tree" - git -C "$root" worktree add -q --detach "$tree" "$base_rev" - trap 'git -C "$root" worktree remove --force "$tree"' EXIT - add_variant base "$tree" -fi - -jq -n \ - --argjson rounds "$rounds" \ - --arg seconds "$seconds" \ - --arg ubrn "$work/ubrn" \ - --args '{$rounds, $seconds, $ubrn, runners: $ARGS.positional}' "${runners[@]}" | - jq -c --slurpfile variants <(printf '%s\n' "${variants[@]}") '. + {$variants}' >"$out/plan.json" - -# Linux reads /proc; macOS has none and answers through sysctl. -if [[ -r /proc/cpuinfo ]]; then - cpu=$(sed -n 's/^model name[[:space:]]*: //p' /proc/cpuinfo | head -1) - memory=$(awk '/MemTotal/ { printf "%.0f GiB", $2 / 1048576 }' /proc/meminfo) -else - cpu=$(sysctl -n machdep.cpu.brand_string) - memory="$(($(sysctl -n hw.memsize) / 1073741824)) GiB" -fi -load() { - if [[ -r /proc/loadavg ]]; then cut -d' ' -f1-3 /proc/loadavg; else sysctl -n vm.loadavg | tr -d '{}' | xargs; fi -} -load_start=$(load) - -# The dev shell of the pinned moq carries every wrapper's toolchain. -nix develop "github:moq-dev/moq/$moq_rev" --command "$bench/run.sh" measure "$out" - -jq -n \ - --arg date "$(date -u +%FT%TZ)" \ - --arg os "$(uname -srm)" \ - --arg cpu "$cpu" \ - --arg cpus "$(getconf _NPROCESSORS_ONLN)" \ - --arg memory "$memory" \ - --arg runner "${RUNNER_NAME:-local}" \ - --arg load_start "$load_start" \ - --arg load_end "$(load)" \ - --arg rust2 "$fork_rev" \ - --arg base "$base_rev" \ - --arg moq "$moq_rev" \ - --arg ubrn "${browser:+$ubrn_rev}" \ - --argjson rounds "$rounds" \ - --arg seconds "$seconds" \ - --slurpfile tools "$out/tools.json" \ - '$ARGS.named + {tools: $tools[0]}' >"$out/host.json" - -report "$out" -mkdir -p "$results" -ln -sfn "$out" "$results/latest" -echo "bench-ffi: report at $out/report.md" diff --git a/ffi/README.md b/ffi/README.md index cafd58099..825a4ef9d 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -1,7 +1,7 @@ # rust2-ffi A rustc driver that exports a crate's `pub` API as a C ABI and a C header, with no -attributes in the Rust source. It replaces [the UniFFI fork](../uniffi/README.md) for moq. +attributes in the Rust source. Every language's generator but Python's builds on the C ABI. ```bash @@ -659,7 +659,7 @@ abort with its message; the Python with another contract must refuse the library language mode and type-checked in Swift 5's, checks its futures the same way and that releasing frees, and breaks each runtime check, which must trap or abort with its message. It runs with nixpkgs' Swift on Linux, which builds none for aarch64-linux -([quest](/quest/m2/uniffi-swift-arm.md)), and nightly with Apple's on macOS. +([quest](/quest/m2/swift-arm.md)), and nightly with Apple's on macOS. `tests/api.go` runs the script through the Go after `go vet`, checks its futures the same way, plus a context done before the call, a deadline, and a handle closed during a call, checks that bytes cross both ways, that a `Bytes` keeps Rust's buffer while only a sub-view diff --git a/ffi/justfile b/ffi/justfile index 77e9a7bae..481937680 100644 --- a/ffi/justfile +++ b/ffi/justfile @@ -68,7 +68,7 @@ bench checkout="": (moq checkout) kotlinc -Werror -cp "$KOTLINX_COROUTINES" "$out/kotlin/moq.kt" moq/bench/export.kt -d target/bench-kt swift=true if [ "{{ os() }}-{{ arch() }}" = linux-aarch64 ]; then - echo "skipping the Swift: nixpkgs builds no Swift for aarch64-linux (quest/m2/uniffi-swift-arm.md)" >&2 + echo "skipping the Swift: nixpkgs builds no Swift for aarch64-linux (quest/m2/swift-arm.md)" >&2 swift=false else {{ quote(just_executable()) }} swift-module -O @@ -103,7 +103,7 @@ moq checkout="": (moq-cpp checkout) mypy --strict --python-version 3.11 --cache-dir target/mypy "$out/python/moq.py" pyright -p tests/pyright.json "$out/python/moq.py" if [ "{{ os() }}-{{ arch() }}" = linux-aarch64 ]; then - echo "skipping moq/moq.swift: nixpkgs builds no Swift for aarch64-linux (quest/m2/uniffi-swift-arm.md)" >&2 + echo "skipping moq/moq.swift: nixpkgs builds no Swift for aarch64-linux (quest/m2/swift-arm.md)" >&2 else {{ quote(just_executable()) }} moq-swift-run fi diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index f1fb9c580..1de4a0d97 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -612,7 +612,7 @@ fn kotlin_contract(kotlin: &Path) -> u64 { #[test] #[cfg_attr( all(target_os = "linux", target_arch = "aarch64"), - ignore = "nixpkgs builds no Swift for aarch64-linux: quest/m2/uniffi-swift-arm.md" + ignore = "nixpkgs builds no Swift for aarch64-linux: quest/m2/swift-arm.md" )] fn api_swift() { let api = api(); diff --git a/flake.nix b/flake.nix index 2fc28e529..c95069ebe 100644 --- a/flake.nix +++ b/flake.nix @@ -156,49 +156,7 @@ doCheck = false; }; - # Every generator binary of the UniFFI fork, built once from its lockfile. - uniffi = - (pkgs.makeRustPlatform { - cargo = toolchain; - rustc = toolchain; - }).buildRustPackage - { - pname = "rust2-uniffi"; - version = (builtins.fromTOML (builtins.readFile ./uniffi/uniffi/Cargo.toml)).package.version; - # The root workspace, without the other projects. - src = pkgs.lib.fileset.toSource { - root = ./.; - fileset = pkgs.lib.fileset.unions [ - ./Cargo.toml - ./Cargo.lock - ./uniffi - ]; - }; - cargoLock.lockFile = ./Cargo.lock; - cargoBuildFlags = [ - "--package=uniffi" - "--package=uniffi-bindgen-go" - "--package=uniffi-dart" - "--package=uniffi-bindgen-cpp" - "--bins" - ]; - buildFeatures = [ - "uniffi/cli" - "uniffi-dart/binary" - ]; - # The fixture suite needs every foreign toolchain; `just uniffi fixtures` runs it. - doCheck = false; - }; - - # One generator's binaries, so a consumer can put only that one on PATH. - generator = - name: bins: - pkgs.runCommand name { } '' - mkdir -p $out/bin - ${pkgs.lib.concatMapStringsSep "\n" (bin: "ln -s ${uniffi}/bin/${bin} $out/bin/") bins} - ''; - - # Kotlin's generated async code, UniFFI's and rust2-ffi's, needs coroutines on the + # rust2-ffi's generated async Kotlin needs coroutines on the # classpath; nixpkgs has no jar. kotlinx-coroutines = pkgs.fetchurl { url = "https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core-jvm/1.10.2/kotlinx-coroutines-core-jvm-1.10.2.jar"; @@ -210,14 +168,6 @@ quest = quest-cli; ts = rust2-ts; lint = rust2-lint; - inherit uniffi; - uniffi-bindgen = generator "uniffi-bindgen" [ - "uniffi-bindgen" - "uniffi-bindgen-swift" - ]; - uniffi-bindgen-go = generator "uniffi-bindgen-go" [ "uniffi-bindgen-go" ]; - uniffi-bindgen-dart = generator "uniffi-bindgen-dart" [ "uniffi_bindgen_dart" ]; - uniffi-bindgen-cpp = generator "uniffi-bindgen-cpp" [ "uniffi-bindgen-cpp" ]; } # ra-jit and its toolchain for the benchmark's ra-jit variants, which build it # only when they run: it compiles from source. ra-jit skips Intel macOS. @@ -270,8 +220,6 @@ shellcheck shfmt taplo - # bench/ffi/run.sh serializes runs that share a work directory. - flock nixfmt # The TypeScript driver's tests run and type-check its output, and bundle a # caller with Bun and esbuild to check that unused output shakes out. @@ -324,17 +272,6 @@ ]; }; }); - # Every foreign toolchain the UniFFI fixture suite runs, apart for their size. - devShells.uniffi = self.devShells.${system}.default.overrideAttrs (old: { - nativeBuildInputs = old.nativeBuildInputs ++ [ - pkgs.kotlin - pkgs.swift - pkgs.go - pkgs.dart - pkgs.cmake - ]; - CLASSPATH = "${pkgs.jna}/share/java/jna.jar:${kotlinx-coroutines}"; - }); formatter = pkgs.nixfmt; checks.quest-tree = pkgs.runCommand "quest-tree" { nativeBuildInputs = [ quest-cli ]; } '' quest --root ${self} check diff --git a/justfile b/justfile index b5de31e78..4d6084143 100644 --- a/justfile +++ b/justfile @@ -12,9 +12,6 @@ mod go # The drivers' shared front end and rust2-lint, its own workspace on the TypeScript driver's nightly: `just driver `. mod driver -# The UniFFI fork, in the root workspace: `just uniffi `. -mod uniffi - # List the available development commands. default: @just --list @@ -43,16 +40,11 @@ test $BASE="": bench *args: bench/build/run.sh {{ args }} -# Measure what moq's binding wrappers add over Rust, against the UniFFI fork; see bench/ffi/README.md. -bench-ffi *args: - bench/ffi/run.sh {{ args }} - # Apply formatters without changing program behavior. fix: shfmt -w bench/*/*.sh sh/*.sh taplo format nixfmt flake.nix - cargo fmt --all just ts fix just ffi fix just go fix diff --git a/quest/README.md b/quest/README.md index 8e72f65f5..a4adeb112 100644 --- a/quest/README.md +++ b/quest/README.md @@ -36,7 +36,7 @@ Decided with the maintainer on 2026-10-23, when rust2 was planned from moq ## Required -- [m0: immediate priorities](/quest/m0/README.md) - urgent fixes, a green nightly, and the fork's deletion +- [m0: immediate priorities](/quest/m0/README.md) - urgent fixes, the checks' cost, and a green nightly - [m1: consumers waiting](/quest/m1/README.md) - the exporter moq can pin and switch its bindings to - [m2: research](/quest/m2/README.md) - rust2-wasm as the browser route, and the TypeScript translator that has to beat it - [m3: deferred](/quest/m3/README.md) - upstream's build-speed levers, the translator features that wait on the gate, and binding targets planned ahead of a consumer diff --git a/quest/m0/README.md b/quest/m0/README.md index 702253f88..492dd18a0 100644 --- a/quest/m0/README.md +++ b/quest/m0/README.md @@ -8,5 +8,4 @@ each run: the checks, a red nightly, and code no consumer uses. ## Required - [Checks at moq's cost](/quest/m0/checks/README.md) - `just ci` selects by the diff, builds warm, and runs the differential optimized, with a nightly full `just gate` -- [Delete the UniFFI fork](/quest/m0/delete-uniffi.md) - `uniffi/`, its workspace, flake packages, nightly jobs, and the benchmark harness built on it are gone - [The nightly passes](/quest/m0/nightly-green.md) - red since 2026-10-29: the wasm-bindgen fixture's NaN, Kotlin on Android API 35, and `just ffi moq` diff --git a/quest/m0/delete-uniffi.md b/quest/m0/delete-uniffi.md deleted file mode 100644 index b8809f493..000000000 --- a/quest/m0/delete-uniffi.md +++ /dev/null @@ -1,40 +0,0 @@ -# [M] Delete the UniFFI fork - -## Goal - -`uniffi/` and everything that exists only for it are gone: the root Cargo workspace, which -holds only the fork (`sh/dispatch.sh`), the flake's `uniffi*` packages and `.#uniffi` -shell, the nightly `uniffi-*` jobs, and the [binding benchmark](/bench/ffi/README.md)'s -harness, which builds moq-ffi against the fork (`run.sh`, its `fork`, `control`, and `base` -variants, the ubrn browser runner, `pins.toml`, and `bench-ffi.yml`). The benchmark's -README keeps what was measured: the BoltFFI comparison and the fork's generated sizes. -`just ci` and the nightly report their cost before and after. - -## Plan - -Decided with the maintainer on 2026-11-09, in the quest audit: ✅ delete it now. moq decided -on 2026-11-02 never to build on it ([m1](/quest/m1/README.md#plan)), so its consumers here -were only the benchmark's baseline and CI: 1,426 of the repository's 3,596 tracked files -(118k lines), about 7 minutes of each nightly gate, and nightly jobs of 46 minutes -(fixtures), 11 (install), 14 (C and C++), and 100 to 125 (the benchmark on Linux and -macOS). `UniFFI fixtures` has failed every scheduled run since 2026-11-02, and the -benchmark's Swift job since then too. Rejected: keeping it until moq switches, with a -retirement quest; keeping it as is. - -- The baseline no longer matched what moq ships anyway: moq's generator pins moved on - (go `.2`, dart `.7`, cpp `.7`) from the ones `uniffi/README.md` lists. -- Docs the deletion makes stale change with it: the root `README.md`'s fork bullet, - nix command, and license note, `AGENTS.md`'s first line ("to any language through a fork - of UniFFI"), `quest/README.md`'s Plan, and `ffi/README.md`'s first paragraph. -- Rename [the Swift-on-arm wait](/quest/m2/uniffi-swift-arm.md) with `quest mv` to a name - without `uniffi`, and rewrite its Goal around rust2-ffi's skips, which are all it then - holds; `ffi/tests/fixtures.rs`, `ffi/justfile`, and `ffi/README.md` cite its path. -- The exporter's own numbers come from - [its benchmark quest](/quest/m1/ffi-export/bench.md), which rebuilds the harness on - rust2-ffi. -- moq's `quest/m3/ffi-exporter.md` links quests here that are long deleted - (`quest/m1/uniffi.md`, `ffi-bytes.md`, `kt-ffi-calls.md`, `ffi-poll-protocol.md`) and - carries fork-era requirements; report them in the PR for moq's tree to fix. - -Public API: the flake's `uniffi*` packages and `.#uniffi` shell are removed (breaking for -anyone pinning them; no consumer does). diff --git a/quest/m0/nightly-green.md b/quest/m0/nightly-green.md index e686734e8..a1cf78922 100644 --- a/quest/m0/nightly-green.md +++ b/quest/m0/nightly-green.md @@ -9,8 +9,8 @@ cause, and a regression in a suite only the nightly runs cannot go unseen for a Found in the 2026-11-09 quest audit: the nightly has failed every scheduled run since 2026-10-29, with no quest owning it. Decided with the maintainer on 2026-11-09: ✅ m0, -after [the fork's deletion](/quest/m0/delete-uniffi.md), which removes the `uniffi-*` -jobs, so this fixes only what remains. Rejected: m1. +after the UniFFI fork's deletion removed the `uniffi-*` jobs, so this fixes only what +remains. Rejected: m1. What failed on 2026-11-09 (run [42655190735](https://github.com/moq-dev/rust2/actions/runs/42655190735), at `f7a0c279`): @@ -37,7 +37,3 @@ issue the maintainer sees, and `just ffi moq`'s export step joins `just ci` when or the pin changes, if it fits the gate's budget; measure it and report. Public API: none. - -## Required - -- [Delete the UniFFI fork](/quest/m0/delete-uniffi.md) - the nightly's `uniffi-*` jobs, one of them red, are deleted rather than fixed diff --git a/quest/m1/README.md b/quest/m1/README.md index 1769491c0..cebfc58d5 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -15,10 +15,9 @@ whose feature quests are folded into the [exporter's](/quest/m1/ffi-export/READM Decided 2026-11-02 (maintainer, moq's /quest-unblock): the fork is not published to crates.io. moq skips it and switches straight to the exporter ([moq's switch](https://github.com/moq-dev/moq/blob/main/quest/m3/ffi-exporter.md)), so publishing would only commit permanent `rust2-*` names to code already slated for retirement. moq keeps its own pinned generator forks until the exporter is ready. -Decided with the maintainer on 2026-11-09, in the quest audit: ✅ the fork is deleted now -([its quest](/quest/m0/delete-uniffi.md)), since moq never builds on it and its only -consumers here were the binding benchmark's baseline and nightly jobs. Rejected: keeping it -until moq switches; keeping it as is. +Decided with the maintainer on 2026-11-09, in the quest audit: ✅ the fork is deleted now, +since moq never builds on it and its only consumers here were the binding benchmark's +baseline and nightly jobs. Rejected: keeping it until moq switches; keeping it as is. ## Required diff --git a/quest/m1/ffi-export/bench.md b/quest/m1/ffi-export/bench.md index 6698ea87d..09d009799 100644 --- a/quest/m1/ffi-export/bench.md +++ b/quest/m1/ffi-export/bench.md @@ -10,9 +10,10 @@ numbers justify as quests. ## Plan -Found in the 2026-11-09 quest audit: no exporter measurement is committed. The benchmark -measures moq-ffi over the UniFFI fork, `just ffi bench` (`ffi/justfile`, -`ffi/moq/bench/export.*`) prints timings and records nothing, and the epic's rule that +Found in the 2026-11-09 quest audit: no exporter measurement is committed. The benchmark's +harness, which measured moq-ffi over the UniFFI fork, was deleted with the fork; its README +keeps the numbers. `just ffi bench` (`ffi/justfile`, `ffi/moq/bench/export.*`) prints +timings and records nothing, and the epic's rule that every generator "is measured on the binding benchmark" and "reports its generated size" had no owner. Speed ranks above ergonomics here (AGENTS.md), so it needs a baseline. @@ -40,7 +41,3 @@ had no owner. Speed ranks above ergonomics here (AGENTS.md), so it needs a basel report plans. Public API: none. - -## Required - -- [Delete the UniFFI fork](/quest/m0/delete-uniffi.md) - the benchmark's harness stops building the fork, so this rebuilds it on the exporter diff --git a/quest/m2/README.md b/quest/m2/README.md index e5a9e5dac..2f65eea47 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -31,4 +31,4 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export/README - [rust2-wasm](/quest/m2/wasm/README.md) - a crate's `pub` API in the browser through the exporter's wasm32 target, and the gate the translator has to pass - [Translate moq-net's model to TypeScript](/quest/m2/ts-model/README.md) - the model translates with kio and moq-pattern, for the gate to compare -- [Waiting: Swift 6.4 in nixpkgs-unstable](/quest/m2/uniffi-swift-arm.md) - the nightly UniFFI fixtures move back to arm +- [Waiting: Swift 6.4 in nixpkgs-unstable](/quest/m2/swift-arm.md) - rust2-ffi stops skipping its Swift on aarch64-linux diff --git a/quest/m2/uniffi-swift-arm.md b/quest/m2/swift-arm.md similarity index 59% rename from quest/m2/uniffi-swift-arm.md rename to quest/m2/swift-arm.md index fdcfaedf8..e96b3b08e 100644 --- a/quest/m2/uniffi-swift-arm.md +++ b/quest/m2/swift-arm.md @@ -2,18 +2,17 @@ ## Goal -The nightly `uniffi-fixtures` job runs on `ubuntu-24.04-arm` again, and -`nix develop .#uniffi` evaluates on aarch64-linux. +rust2-ffi's Swift builds and runs on aarch64-linux: `api_swift` runs there, and +`just ffi moq` and `just ffi bench` stop skipping the Swift. ## Plan Decided with the maintainer on 2026-10-26, from [#93](https://github.com/moq-dev/rust2/pull/93): swiftc 6.3.3 is marked broken on -aarch64-linux in the pinned nixpkgs, where its gold link fails, so the job moved to -x86_64. Then bump the `nixpkgs` input in its own change, move the job back, and -drop the workflow comment. The default shell then has Swift on aarch64-linux too, so -drop rust2-ffi's skips there as well: `api_swift`'s `ignore`, and the Swift's in -`just ffi moq` and `just ffi bench`, and the default dev shell's "not on aarch64-linux" +aarch64-linux in the pinned nixpkgs, where its gold link fails, so the default dev shell +leaves Swift out there. Bump the `nixpkgs` input in its own change, then drop +`api_swift`'s `ignore` in `ffi/tests/fixtures.rs`, the Swift skips in `just ffi moq` and +`just ffi bench` (`ffi/justfile`), and the default dev shell's "not on aarch64-linux" comment in `flake.nix` that [#653](https://github.com/moq-dev/rust2/pull/653) added. Keep that shell's `swiftc.meta.broken` guard, which covers any later broken Swift. Never allow the broken package. @@ -27,4 +26,4 @@ Public API: none. `staging` on 2026-10-22 and to `master` on 2026-11-07 through [NixOS/nixpkgs#580394](https://github.com/NixOS/nixpkgs/pull/580394), not in `nixpkgs-unstable` on 2026-11-09). Check that - `nix build --dry-run .#devShells.aarch64-linux.uniffi` succeeds after a bump. + `nix eval .#devShells.aarch64-linux.default.nativeBuildInputs` lists Swift after a bump. diff --git a/sh/dispatch.sh b/sh/dispatch.sh index fe86c25b7..507134a4d 100755 --- a/sh/dispatch.sh +++ b/sh/dispatch.sh @@ -25,7 +25,6 @@ declare -A scope=( [lint]='' [quest]='^quest/' [sh]='^sh/dispatch\.test\.py$' - [uniffi]='^uniffi/' # The driver and ffi link ts's toolchain, and both of the others build on # the driver's front end. [driver]='^(driver/|ts/rust-toolchain\.toml$)' @@ -35,7 +34,7 @@ declare -A scope=( [ts]='^(ts|driver)/' ) # Cheapest first, so a lint fails before the builds start. -modules=(lint quest sh uniffi driver ffi go ts) +modules=(lint quest sh driver ffi go ts) # Paths that only the repository-wide lints read. lints='^(bench/|\.agents/|\.claude/|\.codex/|[^/]+\.md$|LICENSE-|\.(editorconfig|gitattributes|gitignore|taplo\.toml)$)' @@ -58,7 +57,7 @@ else } | sort -u) # A path no module claims is a shared input, such as the flake, a - # toolchain, the root Cargo.* and justfile, .github, or this map, so it + # toolchain, the root justfile, .github, or this map, so it # selects everything. A new project selects everything until it is mapped. claimed=$lints for module in "${modules[@]}"; do @@ -94,18 +93,11 @@ check_lint() { nixfmt --check flake.nix } check_quest() { quest check; } -# The root workspace holds only the UniFFI fork. -check_uniffi() { - cargo fmt --all --check - cargo clippy --locked --workspace --all-targets -- -D warnings - just uniffi check -} check_driver() { just driver check; } check_ffi() { just ffi check; } check_go() { just go check; } check_ts() { just ts check; } test_sh() { python3 -I sh/dispatch.test.py; } -test_uniffi() { just uniffi test; } test_driver() { just driver test; } test_ffi() { just ffi test; } test_go() { just go test; } diff --git a/sh/dispatch.test.py b/sh/dispatch.test.py index ba9f152e8..9316ded99 100755 --- a/sh/dispatch.test.py +++ b/sh/dispatch.test.py @@ -9,7 +9,7 @@ from pathlib import Path DISPATCH = Path(__file__).with_name("dispatch.sh").resolve() -EVERYTHING = ["lint", "quest", "sh", "uniffi", "driver", "ffi", "go", "ts"] +EVERYTHING = ["lint", "quest", "sh", "driver", "ffi", "go", "ts"] class SelectTests(unittest.TestCase): @@ -68,7 +68,6 @@ def test_projects_select_themselves_and_the_lints(self): (["ffi/src/lib.rs"], ["lint", "ffi"]), (["go/src/lib.rs"], ["lint", "go"]), (["ts/fixtures/codec/src/lib.rs"], ["lint", "go", "ts"]), - (["uniffi/uniffi_core/src/lib.rs"], ["lint", "uniffi"]), (["quest/m0/example.md"], ["lint", "quest"]), (["sh/dispatch.test.py"], ["lint", "sh"]), (["ts/src/lib.rs", "ffi/src/lib.rs"], ["lint", "ffi", "ts"]), @@ -102,8 +101,6 @@ def test_shared_inputs_select_everything(self): "flake.nix", "flake.lock", "rust-toolchain.toml", - "Cargo.toml", - "Cargo.lock", "justfile", ".github/workflows/nightly.yml", "sh/dispatch.sh", @@ -127,7 +124,7 @@ def test_deletions_count(self): def test_base_changes_since_the_branch_do_not_count(self): branch = self.git("rev-parse", "HEAD") - self.commit("uniffi/uniffi_core/src/lib.rs") + self.commit("go/src/lib.rs") self.git("update-ref", "refs/remotes/origin/main", "HEAD") self.git("checkout", "-q", "-b", "work", branch) self.commit("ts/src/lib.rs") diff --git a/uniffi/.gitignore b/uniffi/.gitignore deleted file mode 100644 index 9b584b7f3..000000000 --- a/uniffi/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Bindings `just uniffi go` generates for the Go tests. -/go/binding_tests/generated/ -# Dart tooling state the fixture tests leave behind. -.dart_tool/ diff --git a/uniffi/LICENSE b/uniffi/LICENSE deleted file mode 100644 index a612ad981..000000000 --- a/uniffi/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/uniffi/README.md b/uniffi/README.md deleted file mode 100644 index 593ef6701..000000000 --- a/uniffi/README.md +++ /dev/null @@ -1,141 +0,0 @@ -# UniFFI fork - -A hard fork of [UniFFI](https://github.com/mozilla/uniffi-rs) 0.32.2 with every generator -[moq](https://github.com/moq-dev/moq) uses: Kotlin, Swift, Python, Go, Dart, C++, and C. -It never merges upstream; fixes are cherry-picked by hand. - -## Use - -Nothing is published to crates.io yet, so depend on a revision of this repository: - -```toml -[dependencies] -uniffi = { git = "https://github.com/moq-dev/rust2", rev = "" } -``` - -Every crate keeps its upstream name (`uniffi`, `uniffi_core`, `uniffi_bindgen`, ...), so code -written for UniFFI 0.32 compiles as is. Do not link upstream UniFFI into the same library. - -The generators read a cdylib built against this runtime: - -| Binary | Languages | Package | -| --- | --- | --- | -| `uniffi-bindgen` | Kotlin, Swift, Python | `uniffi` with `--features cli` | -| `uniffi-bindgen-swift` | Swift modules and xcframeworks | `uniffi` with `--features cli` | -| `uniffi-bindgen-go` | Go | `uniffi-bindgen-go` | -| `uniffi_bindgen_dart` | Dart | `uniffi-dart` with `--features binary` | -| `uniffi-bindgen-cpp` | C++, and C with `--lang c` | `uniffi-bindgen-cpp` | - -The flake builds them all as `packages.uniffi`, and each one alone as `uniffi-bindgen`, -`uniffi-bindgen-go`, `uniffi-bindgen-dart`, and `uniffi-bindgen-cpp`. Without Nix: -`cargo install --git https://github.com/moq-dev/rust2 --rev uniffi-bindgen-go`. - -Upstream's [user guide](https://mozilla.github.io/uniffi-rs/0.32/) applies, minus Ruby. The -generators document their options in [go/docs](go/docs/CONFIGURATION.md), -[cpp/README.md](cpp/README.md), and [cpp/docs](cpp/docs/CONFIGURATION.md). - -## Contract - -The FFI contract is still upstream 0.32's (contract version 30), which is what keeps moq's -generated bindings byte-identical. The first change to the contract gives it its own -namespace, so a library and bindings from different forks fail at load time instead of -mixing silently. - -## Imports - -| Directory | Upstream | Imported revision | License | -| --- | --- | --- | --- | -| `uniffi*/`, `examples/`, `fixtures/`, `bindgen-tests/` | [mozilla/uniffi-rs](https://github.com/mozilla/uniffi-rs) | [kixelated/uniffi-rs@88d835d](https://github.com/kixelated/uniffi-rs/commit/88d835d66abc6357b0bcd290b4c2adb35096cd10) (v0.32.2 plus one fix) | [MPL-2.0](LICENSE) | -| `go/` | [NordSecurity/uniffi-bindgen-go](https://github.com/NordSecurity/uniffi-bindgen-go) | [kixelated/uniffi-bindgen-go@v0.10.0-kixelated.1+v0.32.0](https://github.com/kixelated/uniffi-bindgen-go/tree/v0.10.0-kixelated.1%2Bv0.32.0) | [MPL-2.0](go/LICENSE) | -| `dart/` | [acterglobal/uniffi-dart](https://github.com/acterglobal/uniffi-dart) | [kixelated/uniffi-dart@v0.3.1-kixelated.6+v0.32.0](https://github.com/kixelated/uniffi-dart/tree/v0.3.1-kixelated.6%2Bv0.32.0) | [MIT](dart/LICENSE) | -| `cpp/` | [NordSecurity/uniffi-bindgen-cpp](https://github.com/NordSecurity/uniffi-bindgen-cpp) | [kixelated/uniffi-bindgen-cpp@v0.11.0-kixelated.5+v0.32.2](https://github.com/kixelated/uniffi-bindgen-cpp/tree/v0.11.0-kixelated.5%2Bv0.32.2) | [MPL-2.0](cpp/LICENSE) | - -Each directory keeps its upstream layout, except `uniffi_bindgen`'s templates (see -[Carried changes](#carried-changes)), so an upstream commit applies with -`git am --directory=uniffi/` (no `` for uniffi-rs). Their crates build in the -repository's root workspace, in place of each upstream's own. - -Left out: the Ruby generator and its tests, weedle2 (used from crates.io), upstream's docs, -CI, and Docker setup, the Android, iOS, and fxa-client examples, and the Dart fixtures upstream -does not build. - -## Carried changes - -Offering a change upstream needs maintainer approval each time, so most have no upstream PR. - -uniffi-rs: - -- Python prefers the running event loop to the configured callback fallback - ([mozilla/uniffi-rs@f903c36c](https://github.com/mozilla/uniffi-rs/commit/f903c36c09fd396560e4dc28763a97a5c552e1c3)); the public setter keeps its 0.32 name. - Unlike upstream, an async callback still goes to the configured loop while it runs, since - a sync call may block the caller's loop on the callback. -- Kotlin refuses a destroyed object passed as an argument (kixelated/uniffi-rs@88d835d). -- Ruby is removed. -- `toml` is pinned to major 1. Upstream's `>=0.9, <2` spans two majors, so a generator that - resolved the other one got a second `toml::Value` that no longer matched the trait. -- Clippy 1.98 fixes, including an allow on the UDL metadata const, which it flags in every UDL - consumer. -- Test expectations that hold a path relative to the workspace root (`file!()` output and - trybuild snapshots) gain the `uniffi/` prefix. -- A crate can use another crate's type of the same name - ([mozilla/uniffi-rs#3026](https://github.com/mozilla/uniffi-rs/issues/3026)): the type - universe, the errors, and the recursion check key types by crate and name, and an external - type is walked through its own crate's interface. Kotlin spells external types with their - package, Swift qualifies an ambiguous one with its module (so same-named types need one - Swift module per crate), and Python keeps both definitions (mozilla/uniffi-rs#2985, from - upstream `main`). Container helpers for an external type carry its namespace. The - `namespaces` fixture covers it in every generator. -- Scaffolding is written to a temporary file and renamed into place. Two trybuild cases - expanding `generate_and_include_scaffolding!` on one UDL write it concurrently, and the - in-place truncate let one include a partial file. -- The bindgen tests generate into a directory per test instead of one per language, so they - run under nextest, which runs each test in its own process. -- `uniffi_bindgen` has no `askama.toml`: its templates move from `src/**/templates` to - `templates/`, askama's default directory, so a patch to - them needs its paths rewritten. askama canonicalizes the config file's path and then - reaches it by a relative path from the unresolved source file, which fails when the fork - sits behind a symlink (askama-rs/askama#744 was closed unmerged). - -uniffi-bindgen-go, on top of upstream v0.7.1+v0.31.0: - -- The UniFFI 0.32 port ([NordSecurity/uniffi-bindgen-go#98](https://github.com/NordSecurity/uniffi-bindgen-go/pull/98)). -- Generated async calls take a `context.Context` and cancel the Rust future. -- An exported `Display` on an enum error renders as its `Error()`. -- Container helpers for another crate's type carry its namespace, so they don't collide with - a same-named local type's. -- `Types.go` renders its object, enum, error, record, callback interface, and custom type - templates in their own functions, with byte-identical output. Inlined into one, the borrow - checker took about 16 GB to check it, more than a CI runner has. - -uniffi-dart, on top of upstream `main` at acterglobal/uniffi-dart@72d26c1: - -- The UniFFI 0.32 port and the library-mode CLI, by Sasha Denisov. -- RustBuffer and async result leak fixes, `liftAndFree` type arguments, non-null optionals - lowered through `toRustBuffer`, an exported `Display` as an enum's `toString()`, and - disposed objects refused as arguments. -- Input scratch is released on partial allocation failure, and disposal reserves status - storage before closing the handle, so allocation failure leaves it owned and retryable - ([Uniffi-Dart/uniffi-dart@71dc9f8b](https://github.com/Uniffi-Dart/uniffi-dart/commit/71dc9f8b8f54cdfa6ef5d08f24e70cd93ef11d7d), - [@a2751c4c](https://github.com/Uniffi-Dart/uniffi-dart/commit/a2751c4cb0df3d28b5efab0bac1dadf439d9b163)). -- Record errors keep their converter name, and futures cancel per operation (moq's - `nix/uniffi-dart-record-error.patch` and `nix/uniffi-dart-cancellation.patch`). -- Another crate's library is imported with a `uniffi_` prefix that its types, - converters, and container helpers go through, the shared runtime comes from the same crate - every run, and the test harness drives library mode. - -uniffi-bindgen-cpp, on top of upstream `main` at NordSecurity/uniffi-bindgen-cpp@20bef75: - -- LiveKit's async support (livekit/uniffi-bindgen-cpp, by Alan George), ported to UniFFI 0.32. -- `error_style = "expected"`, `strip_type_prefix`, exported `Display` and `Debug` on enums, - newline-terminated files, released async results, and the C backend (`--lang c`). -- The CMake test suite finds the fixtures in the root workspace's target directory. -- Scaffolding mode (`--scaffolding`) is removed. It had no consumer and stubbed out generation, - and its tests need the Go and C# generators, so they were never imported. -- Async needs `error_style = "expected"`. The exceptions style's async, including async callback - interfaces, had no consumer, raced a cancel against the Rust future's free, and leaked - results, so it is removed, and that style refuses an async item. The C++ coverall test goes - with it, since coverall mixes async with callback interfaces, which the expected style lacks. -- Another crate's types are qualified from the global namespace, with aliased converters and - namespaced container helpers, definitions sort per crate, and `strip_type_prefix` renames - per crate. The C backend supports external types, and prefixes every C name with its - namespace. diff --git a/uniffi/bindgen-tests/README.md b/uniffi/bindgen-tests/README.md deleted file mode 100644 index 7f3a581ca..000000000 --- a/uniffi/bindgen-tests/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# bindgen-tests - -These are a new test suite for UniFFI that we're currently working on switching to. -They replace the older tests in fixtures/examples. - -The main difference is that these tests don't try to represent any kind of real-world scenario. -Instead, they try to directly exercise the bindings code with artificial cases. -This has a few advantages: - -* You can test new bindgen code step-by-step as you build it. - Each test targets a particular feature, and you can enable them one-by-one using crate features. - For example, start with `simple_fns`, then move to `primitive_types`, `records`, `enums`, etc. -* It's more obvious why things fail. Since each test is very specific, you can more easily know what failed. - If the `records` test fails, you can be pretty sure you have an issue with your record-related code. - When the `examples/todolist` test fails, it's not so clear. -* There's less crates involved. - If we wanted, we could publish the 2 test crates involved without too much overhead. - Publishing all of the examples/fixtures is a lot. -* Simplified test harness code. - This kind-of follows from the last points. - Since we only need to build a single library, we don't need so much abstraction. -* Language-specific tests get their own directory. - For example, the Swift-specific tests all live in the `swift/` subdirectory. - If we decide to split `uniffi-bindgen-swift` into it's own crate, - this will make it easier for the tests to move there. - -## Running the tests - -* Go to one of the language directories (for example `bindgen-tests/swift`) -* `cargo test` -* ...or something like `cargo test test_records` to test a specific feature - -## Adding tests for a new feature - -* Create a library types/functions to the test feature - * Create a new module in `bindgen-tests/lib/src/` - * Add a feature flag for it - * Add a `pub mod` statement in `bindgen-tests/lib/src/lib.rs`, conditional on that feature flag. -* Add tests for each language - * Swift - * Add a Swift test case file in `bindgen-tests/swift/tests` - * Add a test function for the new test case in `bindgen-tests/swift/src/lib.rs` - * Kotlin: TODO (see `bindgen-tests/kotlin/` — partially implemented) - * Python: see `bindgen-tests/python/tests/` - * Ruby: see `bindgen-tests/ruby/tests/` - -## Migration plan - -Swift was the first language migrated; Ruby and Python suites also exist under `bindgen-tests/`. -Kotlin support is still being ported. - -After that, we'll want to keep the existing fixtures for a while, since these tests may not be testing everything. -New tests should be added here if possible. -If we see a failure in one of the existing fixtures, we should update these tests to also catch it. -We should review the existing fixtures, think if these tests are missing anything from them, and update them if so. - -At some point, we'll be confident that the older fixtures aren't needed anymore and we can start to get rid of them. -We'll still want to keep the examples around, since they serve as a form of documentation. -We may also decide to keep running tests for them, since they could serve as a form of end-to-end testing. diff --git a/uniffi/bindgen-tests/external-types/Cargo.toml b/uniffi/bindgen-tests/external-types/Cargo.toml deleted file mode 100644 index eaf2a2007..000000000 --- a/uniffi/bindgen-tests/external-types/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "uniffi-bindgen-tests-external-types-source" -version = "0.31.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib", "staticlib"] - -[dependencies] -thiserror = "2" -uniffi = { path = "../../uniffi", default-features = false } diff --git a/uniffi/bindgen-tests/external-types/README b/uniffi/bindgen-tests/external-types/README deleted file mode 100644 index 2c3b14e5e..000000000 --- a/uniffi/bindgen-tests/external-types/README +++ /dev/null @@ -1,4 +0,0 @@ -Separate crate for testing external types. - -This crate defines a bunch of external types and `uniffi-bindgen-tests` exports functions that use -them. diff --git a/uniffi/bindgen-tests/external-types/src/lib.rs b/uniffi/bindgen-tests/external-types/src/lib.rs deleted file mode 100644 index 4071e4a66..000000000 --- a/uniffi/bindgen-tests/external-types/src/lib.rs +++ /dev/null @@ -1,41 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -uniffi::setup_scaffolding!("uniffi_bindgen_tests_external_types_source"); - -#[derive(uniffi::Record)] -pub struct ExternalRec { - pub a: u8, -} - -#[derive(uniffi::Enum)] -pub enum ExternalEnum { - One, - Two, - Three, -} - -#[derive(uniffi::Object)] -pub struct ExternalInterface { - value: u32, -} - -#[uniffi::export] -impl ExternalInterface { - #[uniffi::constructor] - pub fn new(value: u32) -> Self { - Self { value } - } - - pub fn get_value(&self) -> u32 { - self.value - } -} - -pub struct ExternalCustomType(u64); - -uniffi::custom_type!(ExternalCustomType, u64, { - try_lift: |val| Ok(ExternalCustomType(val)), - lower: |custom| custom.0, -}); diff --git a/uniffi/bindgen-tests/kotlin/Cargo.toml b/uniffi/bindgen-tests/kotlin/Cargo.toml deleted file mode 100644 index 116f1d979..000000000 --- a/uniffi/bindgen-tests/kotlin/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "uniffi-bindgen-tests-kotlin" -version = "0.31.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["cdylib"] - -[dependencies] -camino = "1" -glob = "0.3" -uniffi = { path = "../../uniffi", features = ["bindgen"] } -uniffi-bindgen-tests = { path = "../lib" } diff --git a/uniffi/bindgen-tests/kotlin/enum-payload-clash/Cargo.toml b/uniffi/bindgen-tests/kotlin/enum-payload-clash/Cargo.toml deleted file mode 100644 index c32732d19..000000000 --- a/uniffi/bindgen-tests/kotlin/enum-payload-clash/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "uniffi-fixture-regression-kotlin-enum-payload-clash" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_regression_kotlin_enum_payload_clash" - -[dependencies] -uniffi = { workspace = true } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/kotlin/enum-payload-clash/src/lib.rs b/uniffi/bindgen-tests/kotlin/enum-payload-clash/src/lib.rs deleted file mode 100644 index c36f3c2c4..000000000 --- a/uniffi/bindgen-tests/kotlin/enum-payload-clash/src/lib.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::collections::HashMap; - -#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)] -pub struct Amount { - pub value: u64, -} - -#[derive(Clone, Debug, PartialEq, Eq, uniffi::Enum)] -pub enum AmountOrMax { - Amount { amount: Amount }, - Max, -} - -#[derive(Clone, Debug, PartialEq, Eq, uniffi::Enum)] -pub enum ComplexValue { - OptionalAmount { - maybe_amount: Option, - }, - Amounts { - amounts: Vec, - }, - AmountMap { - amount_map: HashMap, - }, - NestedOptional { - maybe_amounts: Option>, - }, - NestedMap { - nested_map: HashMap>, - }, -} - -#[uniffi::export] -pub fn get_value() -> AmountOrMax { - AmountOrMax::Amount { - amount: Amount { value: 100 }, - } -} - -#[uniffi::export] -pub fn get_complex_value() -> ComplexValue { - ComplexValue::Amounts { - amounts: vec![Amount { value: 1 }, Amount { value: 2 }], - } -} - -uniffi::setup_scaffolding!("regression_kotlin_enum_payload_clash"); diff --git a/uniffi/bindgen-tests/kotlin/enum-payload-clash/tests/bindings/test.kts b/uniffi/bindgen-tests/kotlin/enum-payload-clash/tests/bindings/test.kts deleted file mode 100644 index f8eefd4d0..000000000 --- a/uniffi/bindgen-tests/kotlin/enum-payload-clash/tests/bindings/test.kts +++ /dev/null @@ -1,60 +0,0 @@ -import uniffi.regression_kotlin_enum_payload_clash.* - -// Test basic enum with name clash -val value = getValue() -when (value) { - is AmountOrMax.Amount -> check(value.amount.value == 100UL) - is AmountOrMax.Max -> error("Expected Amount, got Max") -} - -// Test complex nested types to cover fully_qualified_type_label paths -val complexValue = getComplexValue() -when (complexValue) { - is ComplexValue.Amounts -> { - check(complexValue.amounts.size == 2) - check(complexValue.amounts[0].value == 1UL) - check(complexValue.amounts[1].value == 2UL) - } - else -> error("Expected Amounts variant") -} - -// Test Optional type path -val optionalAmount = ComplexValue.OptionalAmount(Amount(42UL)) -when (optionalAmount) { - is ComplexValue.OptionalAmount -> check(optionalAmount.maybeAmount?.value == 42UL) - else -> error("Expected OptionalAmount") -} - -// Test Map type path -val amountMap = ComplexValue.AmountMap(mapOf("key1" to Amount(10UL), "key2" to Amount(20UL))) -when (amountMap) { - is ComplexValue.AmountMap -> { - check(amountMap.amountMap["key1"]?.value == 10UL) - check(amountMap.amountMap["key2"]?.value == 20UL) - } - else -> error("Expected AmountMap") -} - -// Test deeply nested Optional -val nestedOptional = ComplexValue.NestedOptional(listOf(Amount(1UL), Amount(2UL))) -when (nestedOptional) { - is ComplexValue.NestedOptional -> { - check(nestedOptional.maybeAmounts?.size == 2) - } - else -> error("Expected NestedOptional") -} - -// Test deeply nested Map -val nestedMap = ComplexValue.NestedMap( - mapOf( - "list1" to listOf(Amount(1UL), Amount(2UL)), - "list2" to listOf(Amount(3UL)) - ) -) -when (nestedMap) { - is ComplexValue.NestedMap -> { - check(nestedMap.nestedMap["list1"]?.size == 2) - check(nestedMap.nestedMap["list2"]?.size == 1) - } - else -> error("Expected NestedMap") -} diff --git a/uniffi/bindgen-tests/kotlin/enum-payload-clash/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/kotlin/enum-payload-clash/tests/test_generated_bindings.rs deleted file mode 100644 index 8f6905e9a..000000000 --- a/uniffi/bindgen-tests/kotlin/enum-payload-clash/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test.kts"); diff --git a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/Cargo.toml b/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/Cargo.toml deleted file mode 100644 index dc2cea0b7..000000000 --- a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-regression-kotlin-experimental-unsigned-types" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_regression_test_kt_unsigned_types" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/README.md b/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/README.md deleted file mode 100644 index 54d1d43c9..000000000 --- a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Regression test for propagating annotations on Kotlin unsigned types. - -Kotlin's support for unsigned integers is currently experimental (kotlin stabilizes this api in [1.5](#kotlin-1.5)), -and requires explicit opt-in from the consuming application. -Since we can generate Kotlin code that uses unsigned types, we -need to ensure that such code is annotated with -[`@ExperimentalUnsignedTypes`][https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-experimental-unsigned-types/] -in order to avoid compilation warnings. - -This crate exposes an API that uses unsigned types in a variety of -ways, and tests that the resulting Kotlin bindings can be compiled -without warnings. - ---- - -## Kotlin 1.5 - -As of Kotlin 1.5, [unsigned types are stablized](https://kotlinlang.org/docs/whatsnew15.html#stable-unsigned-integer-types). This will elimate the need for this test fixture as well as any places in the code the `@ExperimentalUnsignedTypes` annotation lives. This will most likely be done when the minimum supported version of kotlin in uniffi-rs becomes 1.5. diff --git a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/build.rs b/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/build.rs deleted file mode 100644 index 05b0af143..000000000 --- a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/test.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/src/lib.rs b/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/src/lib.rs deleted file mode 100644 index d6b62b641..000000000 --- a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/src/lib.rs +++ /dev/null @@ -1,50 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -pub fn returns_u16() -> u16 { - 16 -} - -pub fn accepts_and_returns_unsigned(a: u8, b: u16, c: u32, d: u64) -> u64 { - (a as u64) + (b as u64) + (c as u64) + d -} - -pub fn accepts_unsigned_returns_void(a: u8, b: u16, c: u32, d: u64) { - let _unused = accepts_and_returns_unsigned(a, b, c, d); -} - -pub struct DirectlyUsesU8 { - member: u8, - member_two: u16, - member_three: u32, - member_four: u64, - other: String, -} - -pub enum UnsignedEnum { - V1 { q1: u8 }, - V2 { addr: String }, -} - -pub struct RecursivelyUsesU8 { - member: DirectlyUsesU8, - member_two: UnsignedEnum, -} - -#[derive(Debug)] -pub struct InterfaceUsingUnsigned { - _member: u64, -} - -impl InterfaceUsingUnsigned { - pub fn new(new: u64) -> Self { - Self { _member: new } - } - - fn uses_unsigned_struct(&self, mut p1: RecursivelyUsesU8) { - p1.member_two = UnsignedEnum::V1 { q1: 0 } - } -} - -uniffi::include_scaffolding!("test"); diff --git a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/src/test.udl b/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/src/test.udl deleted file mode 100644 index 776438ef9..000000000 --- a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/src/test.udl +++ /dev/null @@ -1,36 +0,0 @@ -// This API doesn't really *do* anything, it's just designed -// to include various unsigned types in various interesting -// positions. The test passes if we can compile the resulting -// Kotlin bindings without any warnings. - -namespace regression_test_kt_unsigned_types { - u16 returns_u16(); - u64 accepts_and_returns_unsigned(u8 a, u16 b, u32 c, u64 d); - void accepts_unsigned_returns_void(u8 a, u16 b, u32 c, u64 d); -}; - -[Enum] -interface UnsignedEnum { - V1(u8 q1); - V2(string addr); -}; - -dictionary DirectlyUsesU8 { - u8 member; - u16 member_two; - u32 member_three; - u64 member_four; - - string other; -}; - -dictionary RecursivelyUsesU8 { - DirectlyUsesU8 member; - UnsignedEnum member_two; -}; - -interface InterfaceUsingUnsigned { - constructor(u64 a); - - void uses_unsigned_struct(RecursivelyUsesU8 p1); -}; diff --git a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/tests/bindings/test.kts b/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/tests/bindings/test.kts deleted file mode 100644 index ec497b947..000000000 --- a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/tests/bindings/test.kts +++ /dev/null @@ -1,8 +0,0 @@ -// This is just a basic "it compiled and ran" test. -// What we're really guarding against is failure to -// compile the bindings as a result of warnings about -// experimental features. - -import uniffi.regression_test_kt_unsigned_types.*; - -assert(returnsU16().toInt() == 16) diff --git a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/tests/test_generated_bindings.rs deleted file mode 100644 index d61ca3ff6..000000000 --- a/uniffi/bindgen-tests/kotlin/experimental-unsigned-types/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test.kts",); diff --git a/uniffi/bindgen-tests/kotlin/keywords/Cargo.toml b/uniffi/bindgen-tests/kotlin/keywords/Cargo.toml deleted file mode 100644 index f6357247a..000000000 --- a/uniffi/bindgen-tests/kotlin/keywords/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-keywords-kotlin" -version = "0.22.0" -edition = "2021" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_keywords_kotlin" - -[dependencies] -thiserror = "2" -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/kotlin/keywords/build.rs b/uniffi/bindgen-tests/kotlin/keywords/build.rs deleted file mode 100644 index 58fc0ba0f..000000000 --- a/uniffi/bindgen-tests/kotlin/keywords/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/keywords.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/kotlin/keywords/src/keywords.udl b/uniffi/bindgen-tests/kotlin/keywords/src/keywords.udl deleted file mode 100644 index 1f0c62ddc..000000000 --- a/uniffi/bindgen-tests/kotlin/keywords/src/keywords.udl +++ /dev/null @@ -1,51 +0,0 @@ -namespace keywords_kotlin { - void if(u8 break); -}; - -interface break { - void class(u8 object); - void object(u8? class); -}; - -callback interface continue { - return return(return v); - continue? continue(); - record break(break? v); - while while(sequence while); - record>? class(record> v); -}; - -callback interface true { - void false(); -}; - -dictionary return { - u8 class; - u8? object; -}; - -dictionary while { - return class; - return? fun; - sequence object; - record break; -}; - -[Enum] -interface false { - true(u8 object); -}; - -enum class { - "object", -}; - -[Error] -interface fun { - class(u8 object); -}; - -[Error] -interface Error { - class(u8 object); -}; diff --git a/uniffi/bindgen-tests/kotlin/keywords/src/lib.rs b/uniffi/bindgen-tests/kotlin/keywords/src/lib.rs deleted file mode 100644 index 8bfaf9496..000000000 --- a/uniffi/bindgen-tests/kotlin/keywords/src/lib.rs +++ /dev/null @@ -1,102 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#![allow(dead_code)] - -use std::{collections::HashMap, sync::Arc}; - -pub fn r#if(_object: u8) {} - -#[allow(non_camel_case_types)] -pub struct r#break {} - -impl r#break { - pub fn class(&self, _object: u8) {} - pub fn object(&self, _class: Option) {} -} - -#[allow(non_camel_case_types)] -trait r#continue { - fn r#return(&self, _v: r#return) -> r#return { - unimplemented!() - } - fn r#continue(&self) -> Option> { - unimplemented!() - } - fn r#break(&self, _v: Option>) -> HashMap> { - unimplemented!() - } - fn r#while(&self, _v: Vec) -> r#while { - unimplemented!() - } - fn class(&self, _v: HashMap>) -> Option>> { - unimplemented!() - } -} - -#[allow(non_camel_case_types)] -trait r#true { - fn r#false(&self); -} - -#[uniffi::export] -impl r#true for r#break { - fn r#false(&self) { - unimplemented!() - } -} - -#[allow(non_camel_case_types)] -pub struct r#return { - class: u8, - object: Option, -} - -#[allow(non_camel_case_types)] -pub struct r#while { - class: r#return, - fun: Option, - object: Vec, - r#break: HashMap, -} - -#[allow(non_camel_case_types)] -pub enum r#false { - #[allow(non_camel_case_types)] - r#true { object: u8 }, -} - -#[allow(non_camel_case_types)] -#[derive(Debug)] -pub enum class { - object, -} - -#[allow(non_camel_case_types)] -#[derive(Debug, thiserror::Error)] -pub enum fun { - #[error("class?")] - class { object: u8 }, -} - -// `FooError` is turned into `FooException`, so this enum will end up -// being named just `Exception`. Without special care, this will clash -// with `kotlin.Exception` class. -#[allow(non_camel_case_types)] -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("class?")] - class { object: u8 }, -} - -#[allow(non_camel_case_types)] -pub struct r#else(pub r#return); -uniffi::custom_newtype!(r#else, r#return); - -#[uniffi::export] -pub fn get_else(e: r#else) -> r#else { - e -} - -uniffi::include_scaffolding!("keywords"); diff --git a/uniffi/bindgen-tests/kotlin/keywords/tests/bindings/test_keywords.kts b/uniffi/bindgen-tests/kotlin/keywords/tests/bindings/test_keywords.kts deleted file mode 100644 index f8dfb065a..000000000 --- a/uniffi/bindgen-tests/kotlin/keywords/tests/bindings/test_keywords.kts +++ /dev/null @@ -1,9 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import java.util.concurrent.* - -import uniffi.keywords_kotlin.* -// able to import is the real test, but might as well call something. -`if`(1.toUByte()) diff --git a/uniffi/bindgen-tests/kotlin/keywords/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/kotlin/keywords/tests/test_generated_bindings.rs deleted file mode 100644 index 00c32caf3..000000000 --- a/uniffi/bindgen-tests/kotlin/keywords/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test_keywords.kts",); diff --git a/uniffi/bindgen-tests/kotlin/src/lib.rs b/uniffi/bindgen-tests/kotlin/src/lib.rs deleted file mode 100644 index 3965120de..000000000 --- a/uniffi/bindgen-tests/kotlin/src/lib.rs +++ /dev/null @@ -1,205 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -extern crate uniffi_bindgen_tests; - -#[cfg(test)] -mod test { - use std::{env, process::Command, sync::OnceLock}; - - use camino::{Utf8Path, Utf8PathBuf}; - - use uniffi::TargetLanguage; - use uniffi_bindgen_tests::test_util; - - #[test] - fn test_simple_fns() { - run_tests(test_dir(), "tests/simple_fns.kts"); - } - - #[test] - fn test_primitive_types() { - run_tests(test_dir(), "tests/primitive_types.kts"); - } - - #[test] - fn test_records() { - run_tests(test_dir(), "tests/records.kts"); - } - - #[test] - fn test_collections() { - run_tests(test_dir(), "tests/collections.kts"); - } - - #[test] - fn test_options() { - run_tests(test_dir(), "tests/options.kts"); - } - - #[test] - fn test_enums() { - run_tests(test_dir(), "tests/enums.kts"); - } - - #[test] - fn test_interfaces() { - run_tests(test_dir(), "tests/interfaces.kts"); - } - - #[test] - fn test_errors() { - run_tests(test_dir(), "tests/errors.kts"); - } - - #[test] - fn test_callback_interfaces() { - run_tests(test_dir(), "tests/callback_interfaces.kts"); - } - - #[test] - fn test_futures() { - run_tests(test_dir(), "tests/futures.kts"); - } - - #[test] - fn test_trait_interfaces() { - run_tests(test_dir(), "tests/trait_interfaces.kts"); - } - - #[test] - fn test_defaults() { - run_tests(test_dir(), "tests/defaults.kts"); - } - - #[test] - fn test_references() { - run_tests(test_dir(), "tests/references.kts"); - } - - #[test] - fn test_custom_types() { - run_tests(test_dir(), "tests/custom_types.kts"); - } - - #[test] - fn test_external_types() { - run_tests(test_dir(), "tests/external_types.kts"); - } - - #[test] - fn test_renames() { - run_tests(test_dir(), "tests/renames.kts"); - } - - #[test] - fn test_bytes() { - run_tests(test_dir(), "tests/bytes.kts"); - } - - #[test] - fn test_recursive_types() { - run_tests(test_dir(), "tests/recursive_types.kts"); - } - - #[test] - fn test_time() { - run_tests(test_dir(), "tests/time.kts"); - } - - #[test] - fn test_rust_traits() { - run_tests(test_dir(), "tests/rust_traits.kts"); - } - - fn test_dir() -> &'static Utf8Path { - static TEST_TEMPDIR: OnceLock = OnceLock::new(); - TEST_TEMPDIR.get_or_init(|| { - let temp_dir = test_util::setup_test_dir("kotlin"); - test_util::build_library(&temp_dir); - test_util::copy_test_sources(&temp_dir, "tests/*.kts"); - test_util::generate_sources(&temp_dir, TargetLanguage::Kotlin); - build_jar(&temp_dir); - temp_dir - }) - } - - fn run_tests(tempdir: &Utf8Path, script_filename: &str) { - run_test_script(tempdir, script_filename); - } - - fn build_jar(temp_dir: &Utf8Path) -> Utf8PathBuf { - let jar_file = temp_dir.join("uniffi_bindgen_tests.jar"); - let sources = glob::glob(temp_dir.join("uniffi/**/*.kt").as_str()) - .unwrap() - .flatten() - .map(|p| String::from(p.to_string_lossy())) - .collect::>(); - - let mut command = Command::new("kotlinc"); - command - // Our generated bindings should not produce any warnings; fail tests if they do. - .arg("-Werror") - .arg("-d") - .arg(&jar_file) - .arg("-classpath") - .arg(calc_classpath(vec![])) - .args(sources); - - let output = command - .output() - .expect("Failed to spawn `python3` when running test script"); - // The `output()` call above sets up pipes to print stdout/stderr. This allows it to be - // integrated with the Rust test harness's output handling. - print!("{}", String::from_utf8_lossy(&output.stdout)); - if !output.status.success() { - println!("---------------------------------------- STDERR ----------------------------------------"); - print!("{}", String::from_utf8_lossy(&output.stderr)); - println!("----------------------------------------------------------------------------------------"); - panic!("running `python` to run test script failed ({:?})", command); - } - jar_file - } - - fn run_test_script(temp_dir: &Utf8Path, script_file: &str) { - let jar_file = temp_dir.join("uniffi_bindgen_tests.jar"); - let mut command = Command::new("kotlinc"); - command - .arg("-classpath") - .arg(calc_classpath(vec![temp_dir, &jar_file])) - // Enable runtime assertions, for easy testing etc. - .arg("-J-ea") - // Our test scripts should not produce any warnings. - .arg("-Werror") - .arg("-script") - .arg(script_file); - - let output = command - .output() - .expect("Failed to spawn `python3` when running test script"); - // The `output()` call above sets up pipes to print stdout/stderr. This allows it to be - // integrated with the Rust test harness's output handling. - print!("{}", String::from_utf8_lossy(&output.stdout)); - if !output.status.success() { - println!("---------------------------------------- STDERR ----------------------------------------"); - print!("{}", String::from_utf8_lossy(&output.stderr)); - println!("----------------------------------------------------------------------------------------"); - panic!( - "running `kotlinc` to run test script failed ({:?})", - command - ); - } - } - - fn calc_classpath(extra_paths: Vec<&Utf8Path>) -> String { - extra_paths - .into_iter() - .map(|p| p.to_string()) - // Add the system classpath as a component, using the fact that env::var returns an Option, - // which implement Iterator - .chain(env::var("CLASSPATH")) - .collect::>() - .join(":") - } -} diff --git a/uniffi/bindgen-tests/kotlin/tests/bytes.kts b/uniffi/bindgen-tests/kotlin/tests/bytes.kts deleted file mode 100644 index abab54e0f..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/bytes.kts +++ /dev/null @@ -1,22 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* -import java.nio.ByteBuffer - -var bytes = ByteArray(4) -bytes[0] = 0.toByte() -bytes[1] = 1.toByte() -bytes[2] = 2.toByte() -bytes[3] = 3.toByte() -assert(roundtripBytes(bytes).contentEquals(bytes)) - -// Zero-copy &[u8] — proc-macro path -fun directBufferOf(vararg bytes: Byte): ByteBuffer { - val buf = ByteBuffer.allocateDirect(bytes.size) - buf.put(bytes) - buf.flip() - return buf -} - -assert(sumBytesProcmacro(ByteBuffer.allocateDirect(0)) == 0u) -assert(sumBytesProcmacro(directBufferOf(1, 2, 3)) == 6u) -assert(firstByteProcmacro(ByteBuffer.allocateDirect(0)) == null) -assert(firstByteProcmacro(directBufferOf(42)) == 42.toUByte()) diff --git a/uniffi/bindgen-tests/kotlin/tests/callback_interfaces.kts b/uniffi/bindgen-tests/kotlin/tests/callback_interfaces.kts deleted file mode 100644 index 9f1568479..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/callback_interfaces.kts +++ /dev/null @@ -1,55 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -class CallbackImpl(var value: UInt) : TestCallbackInterface { - override fun noop() { - } - - override fun getValue(): UInt { - return this.value - } - - override fun setValue(value: UInt) { - this.value = value - } - - override fun throwIfEqual(numbers: CallbackInterfaceNumbers): CallbackInterfaceNumbers { - if (numbers.a == 6u && numbers.b == 7u) { - throw RuntimeException("unexpected failure") - } else if (numbers.a == numbers.b) { - throw TestException.Failure1() - } else { - return numbers - } - } - - override fun echo(s: String): String { - return s - } -} - -// Construct a callback interface to pass to rust -val cbi = CallbackImpl(42u) -// Test calling callback interface methods, which we can only do indirectly. -// Each of these Rust functions inputs a callback interface, calls a method on it, then returns the result. -invokeTestCallbackInterfaceNoop(cbi) -assert(invokeTestCallbackInterfaceGetValue(cbi) == 42u) -invokeTestCallbackInterfaceSetValue(cbi, 43u) -assert(invokeTestCallbackInterfaceGetValue(cbi) == 43u) -assert(invokeTestCallbackInterfaceEcho(cbi, "test-string") == "test-string") - - -assert(invokeTestCallbackInterfaceThrowIfEqual(cbi, CallbackInterfaceNumbers(1u, 2u)) == CallbackInterfaceNumbers(1u, 2u)) -try { - invokeTestCallbackInterfaceThrowIfEqual(cbi, CallbackInterfaceNumbers(1u, 1u)) - throw RuntimeException("Expected TestException.Failure1 to be thrown") -} catch(e: TestException.Failure1) { - // Expected -} - -// Test unexpected errors -try { - invokeTestCallbackInterfaceThrowIfEqual(cbi, CallbackInterfaceNumbers(6u, 7u)) - throw RuntimeException("Expected RuntimeException to be caught, converted to TestException.Failure2, and thrown") -} catch(e: TestException.Failure2) { - assert(e.data.contains("unexpected failure")) -} diff --git a/uniffi/bindgen-tests/kotlin/tests/collections.kts b/uniffi/bindgen-tests/kotlin/tests/collections.kts deleted file mode 100644 index fc21d1d90..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/collections.kts +++ /dev/null @@ -1,49 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -assert(roundtripVecI8(listOf(1.toByte(), 2.toByte(), 3.toByte())) == listOf(1.toByte(), 2.toByte(), 3.toByte())); -assert(roundtripVecU16(listOf(1.toUShort(), 2.toUShort(), 3.toUShort())) == listOf(1.toUShort(), 2.toUShort(), 3.toUShort())); -assert(roundtripVecI16(listOf(1.toShort(), 2.toShort(), 3.toShort())) == listOf(1.toShort(), 2.toShort(), 3.toShort())); -assert(roundtripVecU32(listOf(1u, 2u, 3u)) == listOf(1u, 2u, 3u)); -assert(roundtripVecI32(listOf(1, 2, 3)) == listOf(1, 2, 3)); -assert(roundtripVecU64(listOf(1uL, 2uL, 3uL)) == listOf(1uL, 2uL, 3uL)); -assert(roundtripVecI64(listOf(1L, 2L, 3L)) == listOf(1L, 2L, 3L)); -assert(roundtripVecF32(listOf(1.0f, 2.0f, 3.0f)) == listOf(1.0f, 2.0f, 3.0f)); -assert(roundtripVecF64(listOf(1.0, 2.0, 3.0)) == listOf(1.0, 2.0, 3.0)); -assert(roundtripVecBool(listOf(true, false)) == listOf(true, false)); -assert(roundtripVecString(listOf("test-string")) == listOf("test-string")); -assert(roundtripVecRec(listOf(CollectionsRec(67.toUByte()))) == listOf(CollectionsRec(67.toUByte()))) - -assert(roundtripHashMap(mapOf("a" to 1u, "b" to 2u)) == mapOf("a" to 1u, "b" to 2u)) -assert(roundtripHashSet(setOf("a", "b", "c")) == setOf("a", "b", "c")) -assert(roundtripHashMapU32Key(mapOf(1u to 2u, 2u to 4u)) == mapOf(1u to 2u, 2u to 4u)) - -assert( - roundtripRecWithCollections( - RecWithCollections( - EnumWithCollections.A(null), - null, - listOf(true, false), - mapOf("a" to 10.toUByte(), "b" to 20.toUByte()), - ) - ) == RecWithCollections( - EnumWithCollections.A(null), - null, - listOf(true, false), - mapOf("a" to 10.toUByte(), "b" to 20.toUByte()), - ) -) - -assert(roundtripVecHashSet(listOf(setOf("a", "b"))) == listOf(setOf("a", "b"))) -assert(roundtripVecHashSet(null) == null) -assert(roundtripComplexCollectionType(listOf( - mapOf( - "a" to CollectionsComplexRec(10u, "Test", CollectionsEnum.A(100)), - "b" to CollectionsComplexRec(20u, "Test2", CollectionsEnum.B(1.0f, true)) - ) -)) == listOf( - mapOf( - "a" to CollectionsComplexRec(10u, "Test", CollectionsEnum.A(100)), - "b" to CollectionsComplexRec(20u, "Test2", CollectionsEnum.B(1.0f, true)) - ) -)) -assert(roundtripComplexCollectionType(null) == null) diff --git a/uniffi/bindgen-tests/kotlin/tests/custom_types.kts b/uniffi/bindgen-tests/kotlin/tests/custom_types.kts deleted file mode 100644 index f1d0df458..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/custom_types.kts +++ /dev/null @@ -1,4 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -assert(roundtripCustomType1(100uL) == 100uL) -assert(roundtripCustomType2(mapOf("value" to 200uL)) == mapOf("value" to 200uL)) diff --git a/uniffi/bindgen-tests/kotlin/tests/defaults.kts b/uniffi/bindgen-tests/kotlin/tests/defaults.kts deleted file mode 100644 index cf787c8e9..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/defaults.kts +++ /dev/null @@ -1,18 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -// Records -val r = RecWithDefault() -assert(r.n == 42.toUByte()) -assert(r.v == listOf()) - -// Enums -val e = EnumWithDefault.OtherVariant() -assert(e == EnumWithDefault.OtherVariant(a="default")) - -// default arguments -assert(funcWithDefault() == "DEFAULT") -assert(funcWithDefault("NON-DEFAULT") == "NON-DEFAULT") - -val i = InterfaceWithDefaults() -assert(i.methodWithDefault() == "DEFAULT") -assert(i.methodWithDefault("NON-DEFAULT") == "NON-DEFAULT") diff --git a/uniffi/bindgen-tests/kotlin/tests/enums.kts b/uniffi/bindgen-tests/kotlin/tests/enums.kts deleted file mode 100644 index 1b6294eda..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/enums.kts +++ /dev/null @@ -1,35 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -// simple enums -assert(roundtripEnumWithData(EnumWithData.A(10.toUByte(), 20.toUShort())) == EnumWithData.A(10.toUByte(), 20.toUShort())) -assert(roundtripEnumWithData(EnumWithData.B("Ten", 10u)) == EnumWithData.B("Ten", 10u)) -assert(roundtripEnumWithData(EnumWithData.C) == EnumWithData.C) - -// Test field names for tuple-style enums -assert(EnumWithData.B("Ten", 10u).v1 == "Ten") -assert(EnumWithData.B("Ten", 10u).v2 == 10u) - -// complex enums -assert( - roundtripComplexEnum(ComplexEnum.A(EnumNoData.C)) == - ComplexEnum.A(EnumNoData.C)) -assert( - roundtripComplexEnum(ComplexEnum.B(EnumWithData.A(20.toUByte(), 40.toUShort()))) == - ComplexEnum.B(EnumWithData.A(20.toUByte(), 40.toUShort()))) -assert( - roundtripComplexEnum(ComplexEnum.C(SimpleRec(a=30.toUByte()))) == - ComplexEnum.C(SimpleRec(a=30.toUByte()))) - -// enum discriminants -assert(ExplicitValuedEnum.FIRST.value == 1.toUByte()) -assert(ExplicitValuedEnum.SECOND.value == 2.toUByte()) -assert(ExplicitValuedEnum.FOURTH.value == 4.toUByte()) -assert(ExplicitValuedEnum.TENTH.value == 10.toUByte()) -assert(ExplicitValuedEnum.ELEVENTH.value == 11.toUByte()) -assert(ExplicitValuedEnum.THIRTEENTH.value == 13.toUByte()) -// Some discriminants specified, increment by one for any unspecified variants -assert(GappedEnum.ONE.value == 10.toUByte()) -assert(GappedEnum.TWO.value == 11.toUByte()) // Sequential value after ONE (10+1) -assert(GappedEnum.THREE.value == 14.toUByte()) // Explicit value again -// Enum methods -assert(EnumWithData.A(20.toUByte(), 40.toUShort()).roundtrip() == EnumWithData.A(20.toUByte(), 40.toUShort())) diff --git a/uniffi/bindgen-tests/kotlin/tests/errors.kts b/uniffi/bindgen-tests/kotlin/tests/errors.kts deleted file mode 100644 index d8c24b532..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/errors.kts +++ /dev/null @@ -1,60 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - - -try { - funcWithError(0u) - throw RuntimeException("Should have thrown TestException.Failure1") -} catch (e: TestException.Failure1) { - // Expected -} - -try { - funcWithError(1u) - throw RuntimeException("Should have thrown TestException.Failure2") -} catch (e: TestException.Failure2) { - // Expected - assert(e.data == "DATA") -} - -try { - funcWithError(50u) - throw RuntimeException("Should have thrown TestException.Failure3") -} catch (e: TestException.Failure3) { - assert(e.v1 == 50u) -} - -try { - funcWithFlatError(0u) - throw RuntimeException("Should have thrown TestException.Failure1") -} catch (e: TestFlatException.IoException) { - // Expected -} - -// These shouldn't throw -funcWithError(200u) -funcWithFlatError(1u) - -// Error enum with no data -try { - funcWithErrorNoData(0u) - throw RuntimeException("Should have thrown TestErrorNoData.Failure1") -} catch (e: TestErrorNoData.Failure1) { - // Expected -} - -try { - funcWithErrorNoData(1u) - throw RuntimeException("Should have thrown TestErrorNoData.Failure2") -} catch (e: TestErrorNoData.Failure2) { - // Expected -} - -try { - funcWithErrorNoData(2u) - throw RuntimeException("Should have thrown TestErrorNoData.Failure3") -} catch (e: TestErrorNoData.Failure3) { - // Expected -} - -// This shouldn't throw -funcWithErrorNoData(200u) diff --git a/uniffi/bindgen-tests/kotlin/tests/external_types.kts b/uniffi/bindgen-tests/kotlin/tests/external_types.kts deleted file mode 100644 index a1da8a1f0..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/external_types.kts +++ /dev/null @@ -1,10 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* -import uniffi.uniffi_bindgen_tests_external_types_source.* - -assert(roundtripExtRecord(ExternalRec(a=42.toUByte())) == ExternalRec(a=42.toUByte())) -assert(roundtripExtEnum(ExternalEnum.TWO) == ExternalEnum.TWO) - -val extInterface = ExternalInterface(20u) -assert(roundtripExtInterface(extInterface).getValue() == 20u) - -assert(roundtripExtCustomType(100uL) == 100uL) diff --git a/uniffi/bindgen-tests/kotlin/tests/futures.kts b/uniffi/bindgen-tests/kotlin/tests/futures.kts deleted file mode 100644 index 67b2d1bbb..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/futures.kts +++ /dev/null @@ -1,87 +0,0 @@ -import kotlinx.coroutines.* -import uniffi.uniffi_bindgen_tests.* - -// Simple functions -runBlocking { - assert(asyncRoundtripU8(42.toUByte()) == 42.toUByte()) - assert(asyncRoundtripI8((-42).toByte()) == (-42).toByte()) - assert(asyncRoundtripU16(42.toUShort()) == 42.toUShort()) - assert(asyncRoundtripI16((-42).toShort()) == (-42).toShort()) - assert(asyncRoundtripU32(42u) == 42u) - assert(asyncRoundtripI32(-42) == -42) - assert(asyncRoundtripU64(42uL) == 42uL) - assert(asyncRoundtripI64(-42L) == -42L) - assert(asyncRoundtripF32(0.5f) == 0.5f) - assert(asyncRoundtripF64(-0.5) == -0.5) - assert(asyncRoundtripString("hi") == "hi") - assert(asyncRoundtripVec(listOf(42u)) == listOf(42u)) - assert(asyncRoundtripMap(mapOf("hello" to "world")) == mapOf("hello" to "world")) -} - -// Errors -runBlocking { - try { - asyncThrowError() - throw RuntimeException("Expected TestException.Failure1") - } catch(e: TestException.Failure1) { - // expected - } -} - -// Objects and methods -runBlocking { - val obj = AsyncInterface("Alice") - assert(obj.name() == "Alice") - - val obj2 = asyncRoundtripObj(obj) - assert(obj2.name() == "Alice") - - val rec = AsyncRecord("Bob") - assert(rec.getName() == "Bob") -} - - -// Async callback interfaces -class AsyncCallbackImpl(var value: UInt) : TestAsyncCallbackInterface { - override suspend fun noop() { } - - override suspend fun getValue(): UInt { - return this.value - } - - override suspend fun setValue(value: UInt) { - this.value = value - } - - override suspend fun throwIfEqual(numbers: CallbackInterfaceNumbers): CallbackInterfaceNumbers { - if (numbers.a == numbers.b) { - throw TestException.Failure1() - } - return numbers - } -} - -runBlocking { - val cbi = AsyncCallbackImpl(42u) - invokeTestAsyncCallbackInterfaceNoop(cbi) - - assert(invokeTestAsyncCallbackInterfaceGetValue(cbi) == 42u) - - invokeTestAsyncCallbackInterfaceSetValue(cbi, 43u) - assert(invokeTestAsyncCallbackInterfaceGetValue(cbi) == 43u) - - try { - invokeTestAsyncCallbackInterfaceThrowIfEqual( - cbi, - CallbackInterfaceNumbers(a=10u, b=10u) - ) - throw RuntimeException("Expected TestException.Failure1") - } catch (e: TestException.Failure1) { - // expected - } - - assert(invokeTestAsyncCallbackInterfaceThrowIfEqual( - cbi, - CallbackInterfaceNumbers(a=10u, b=11u) - ) == CallbackInterfaceNumbers(a=10u, b=11u)) -} diff --git a/uniffi/bindgen-tests/kotlin/tests/interfaces.kts b/uniffi/bindgen-tests/kotlin/tests/interfaces.kts deleted file mode 100644 index 1913be870..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/interfaces.kts +++ /dev/null @@ -1,45 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -val testInterface = TestInterface(20u) -assert(testInterface.getValue() == 20u) -assert(cloneInterface(testInterface).getValue() == 20u) - -// Test optional interfaces -assert(roundtripOptionalInterface(null) == null) -assert(roundtripOptionalInterface(TestInterface(20u))?.getValue() == 20u) - -// Test secondary constructors -assert(TestInterface.secondaryConstructor(20u).getValue() == 40u) - -fun assertDestroyedArgumentRefused(call: (TestInterface) -> Unit) { - val destroyed = TestInterface(20u) - destroyed.destroy() - try { - call(destroyed) - throw RuntimeException("Expected destroyed argument to be refused") - } catch (e: IllegalStateException) { - assert(e.message?.contains("already been destroyed") == true) - } -} - -// Object lowering is shared by constructors, methods, and free functions. -assertDestroyedArgumentRefused { TestInterface.fromInterface(it) } -assertDestroyedArgumentRefused { testInterface.cloneOther(it) } -assertDestroyedArgumentRefused { cloneInterface(it) } - -// Test records that store interfaces -val two = TwoTestInterfaces(first=TestInterface(1u), second=TestInterface(2u)) -val swapped = swapTestInterfaces(two) -assert(swapped.first.getValue() == 2u) -assert(swapped.second.getValue() == 1u) - -// Test enums that store interfaces -val en = TestInterfaceEnum.One(TestInterface(1u)) -assert(en.i.getValue() == 1u) - -// Test argument name mapping -// the following calls will fail if the argument name differs -testInterface.methodWithMultiWordArg(theArgument="test") - -// Other bindgens test that we free references, but that's much harder for Kotlin. -// For now, we don't test this at all diff --git a/uniffi/bindgen-tests/kotlin/tests/options.kts b/uniffi/bindgen-tests/kotlin/tests/options.kts deleted file mode 100644 index b94694d7c..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/options.kts +++ /dev/null @@ -1,28 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -assert(roundtripOptionU8(67.toUByte()) == 67.toUByte()); -assert(roundtripOptionU8(null) == null); -assert(roundtripOptionI8(67.toByte()) == 67.toByte()); -assert(roundtripOptionI8(null) == null); -assert(roundtripOptionU16(67.toUShort()) == 67.toUShort()); -assert(roundtripOptionU16(null) == null); -assert(roundtripOptionI16(67.toShort()) == 67.toShort()); -assert(roundtripOptionI16(null) == null); -assert(roundtripOptionU32(67u) == 67u); -assert(roundtripOptionU32(null) == null); -assert(roundtripOptionI32(67) == 67); -assert(roundtripOptionI32(null) == null); -assert(roundtripOptionU64(67uL) == 67uL); -assert(roundtripOptionU64(null) == null); -assert(roundtripOptionI64(67L) == 67L); -assert(roundtripOptionI64(null) == null); -assert(roundtripOptionF32(67.0f) == 67.0f); -assert(roundtripOptionF32(null) == null); -assert(roundtripOptionF64(67.0) == 67.0); -assert(roundtripOptionF64(null) == null); -assert(roundtripOptionBool(true) == true); -assert(roundtripOptionBool(null) == null); -assert(roundtripOptionString("test-string") == "test-string"); -assert(roundtripOptionString(null) == null); -assert(roundtripOptionRec(OptionsRec(67.toUByte())) == OptionsRec(67.toUByte())) -assert(roundtripOptionRec(null) == null); diff --git a/uniffi/bindgen-tests/kotlin/tests/primitive_types.kts b/uniffi/bindgen-tests/kotlin/tests/primitive_types.kts deleted file mode 100644 index 5304c4672..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/primitive_types.kts +++ /dev/null @@ -1,64 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -// Test passing arguments from Kotlin to Rust -inputU8(42.toUByte()) -inputI8((-42).toByte()) -inputU16(42.toUShort()) -inputI16((-42).toShort()) -inputU32(42u) -inputI32(-42) -inputU64(42uL) -inputI64(-42L) -inputF32(0.5f) -inputF64(-3.5) -inputBool(true) -inputString("ABC") -// Test returning values from Rust to Kotlin -assert(outputU8() == 1.toUByte()) -assert(outputI8() == 1.toByte()) -assert(outputU16() == 1.toUShort()) -assert(outputI16() == 1.toShort()) -assert(outputU32() == 1u) -assert(outputI32() == 1) -assert(outputU64() == 1uL) -assert(outputI64() == 1L) -assert(outputF32() == 1.0f) -assert(outputF64() == 1.0) -assert(outputBool() == true) -assert(outputString() == "test-string") -assert(outputU8Max() == 255.toUByte()) -assert(outputU16Max() == 65535.toUShort()) -// Test passing values both ways -assert(roundtripU8(42.toUByte()) == 42.toUByte()) -assert(roundtripI8((-42).toByte()) == (-42).toByte()) -assert(roundtripU16(42.toUShort()) == 42.toUShort()) -assert(roundtripI16((-42).toShort()) == (-42).toShort()) -assert(roundtripU8(255.toUByte()) == 255.toUByte()) -assert(roundtripU16(65535.toUShort()) == 65535.toUShort()) -assert(roundtripU32(42u) == 42u) -assert(roundtripI32(-42) == -42) -assert(roundtripU64(42uL) == 42uL) -assert(roundtripI64(-42L) == -42L) -assert(roundtripF32(0.5f) == 0.5f) -assert(roundtripF64(-3.5) == -3.5) -assert(roundtripBool(true) == true) -assert(roundtripString("ABC") == "ABC") -// Test calling a function with lots of args -// This function will sum up all the numbers, then negate the value since we passed in `true` -assert(sumWithManyTypes( - 1.toUByte(), - (-2).toByte(), - 3.toUShort(), - (-4).toShort(), - 5u, - -6, - 7uL, - -8L, - 9.5f, - -10.5, - true -) == 5.0) - -// Test argument name mapping -// the following calls will fail if the argument name differs -funcWithMultiWordArg(theArgument=16) diff --git a/uniffi/bindgen-tests/kotlin/tests/records.kts b/uniffi/bindgen-tests/kotlin/tests/records.kts deleted file mode 100644 index e37d41bd6..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/records.kts +++ /dev/null @@ -1,37 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -assert(roundtripSimpleRec(SimpleRec(a=42.toUByte())) == SimpleRec(a=42.toUByte())) -assert(UnitRec() == UnitRec()) -assert( - roundtripComplexRec( - ComplexRec( - fieldU8=0.toUByte(), - fieldI8=(-1).toByte(), - fieldU16=2.toUShort(), - fieldI16=(-3).toShort(), - fieldU32=4u, - fieldI32=-5, - fieldU64=6uL, - fieldI64=-7L, - fieldF32=8.5.toFloat(), - fieldF64=9.5, - fieldString="test", - fieldRec=SimpleRec(a=42.toUByte()) - ) - ) == ComplexRec( - fieldU8=0.toUByte(), - fieldI8=(-1).toByte(), - fieldU16=2.toUShort(), - fieldI16=(-3).toShort(), - fieldU32=4u, - fieldI32=-5, - fieldU64=6uL, - fieldI64=-7L, - fieldF32=8.5.toFloat(), - fieldF64=9.5, - fieldString="test", - fieldRec=SimpleRec(a=42.toUByte()) - ) -) -// methods -assert(SimpleRec(a=42.toUByte()).roundtrip() == SimpleRec(a=42.toUByte())) diff --git a/uniffi/bindgen-tests/kotlin/tests/recursive_types.kts b/uniffi/bindgen-tests/kotlin/tests/recursive_types.kts deleted file mode 100644 index 20f2b8821..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/recursive_types.kts +++ /dev/null @@ -1,75 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi.uniffi_bindgen_tests.* - -// Tree (self-recursive) -val leaf = Tree.Leaf(5) -assert(sumTree(leaf) == 5) - -val node = Tree.Node(Tree.Leaf(3), Tree.Leaf(4)) -assert(sumTree(node) == 7) - -val deep = Tree.Node( - Tree.Node(Tree.Leaf(1), Tree.Leaf(2)), - Tree.Leaf(10) -) -assert(sumTree(deep) == 13) - -// Expr / BoolExpr (mutually recursive) -assert(evalExpr(Expr.Lit(42)) == 42) - -val ifTrue = Expr.If( - cond = BoolExpr.IsZero(Expr.Lit(0)), - then = Expr.Lit(1), - `else` = Expr.Lit(2) -) -assert(evalExpr(ifTrue) == 1) - -val ifFalse = Expr.If( - cond = BoolExpr.IsZero(Expr.Lit(5)), - then = Expr.Lit(1), - `else` = Expr.Lit(2) -) -assert(evalExpr(ifFalse) == 2) - -assert(evalBool(BoolExpr.Not(BoolExpr.True)) == false) -assert(evalBool(BoolExpr.Not(BoolExpr.False)) == true) - -// LinkedList (cycle through Optional: Cons.tail is LinkedList?) -assert(listSum(LinkedList.Nil) == 0) -assert(listSum(LinkedList.Cons(head = 5, tail = null)) == 5) -assert(listSum(LinkedList.Cons(head = 3, tail = LinkedList.Cons(head = 4, tail = null))) == 7) - -// Trie (cycle through Map value: Branch.children is Map) -assert(trieSum(Trie.Leaf(5)) == 5) -assert(trieSum(Trie.Branch(children = mapOf())) == 0) -assert(trieSum(Trie.Branch(children = mapOf("a" to Trie.Leaf(1), "b" to Trie.Leaf(2)))) == 3) -assert(trieSum(Trie.Branch(children = mapOf("x" to Trie.Branch(children = mapOf("y" to Trie.Leaf(7)))))) == 7) - -// RoseTree (cycle through a record: RoseTree → RoseData → List) -assert(sumRoseTree(RoseTree.Leaf(7)) == 7) - -assert(sumRoseTree(RoseTree.Branch(RoseData(value = 10, children = listOf()))) == 10) - -assert(sumRoseTree(RoseTree.Branch( - RoseData(value = 1, children = listOf(RoseTree.Leaf(2), RoseTree.Leaf(3))) -)) == 6) - -assert(sumRoseTree(RoseTree.Branch(RoseData( - value = 1, - children = listOf( - RoseTree.Branch(RoseData(value = 2, children = listOf(RoseTree.Leaf(3)))), - RoseTree.Leaf(4), - ) -))) == 10) - -// EvalError (recursive error enum) -assert(maybeThrowError(false) == 42) -try { - maybeThrowError(true) - throw AssertionError("expected EvalError") -} catch (e: EvalException) { - // recursive error enum compiled and is throwable -} diff --git a/uniffi/bindgen-tests/kotlin/tests/references.kts b/uniffi/bindgen-tests/kotlin/tests/references.kts deleted file mode 100644 index ce8139fa9..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/references.kts +++ /dev/null @@ -1,14 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi.uniffi_bindgen_tests.* - -assert(roundtripU8Ref(2.toUByte()) == 2.toUByte()) - -val i = ReferenceTestInterface() -assert(i.doubleValue(2u) == 4u) -assert(callDoubleValue(i, 3u) == 6u) - -val t = createReferenceTestTraitInterface() -assert(callTripleValueTraitInterface(t, 10u) == 30u) diff --git a/uniffi/bindgen-tests/kotlin/tests/renames.kts b/uniffi/bindgen-tests/kotlin/tests/renames.kts deleted file mode 100644 index 5a79e19d5..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/renames.kts +++ /dev/null @@ -1,47 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - - -val rec = RenamedRecord(item=42) -assert(rec.item == 42) - -val enum1 = RenamedEnum.RenamedVariant -val enum2 = RenamedEnum.Record(rec) - -val returnedRec = renamedFunction(rec) -when(returnedRec) { - is RenamedEnum.Record -> assert(returnedRec.v1 == rec) - else -> throw RuntimeException("invalid renamedFunction return: ${returnedRec}") -} - -val obj = RenamedObject.renamedConstructor(123) -assert(obj.renamedMethod() == 123) - -val traitImpl = createTraitImpl(5) -assert(traitImpl.renamedTraitMethod(10) == 50) - -val ktRec = KtRecord(ktItem=100) -assert(ktRec.ktItem == 100) - -// Test constructing BindingEnumToRename variants -KtEnum.KtVariantA -KtEnum.KtRecord(ktRec) -KtEnumWithFields.KtVariantA(1u) - -val returnedKtRec = ktFunction(ktRec); -when (returnedKtRec) { - is KtEnum.KtRecord -> assert(returnedKtRec.v1 == ktRec) - else -> throw RuntimeException("invalid ktFunction return: ${returnedKtRec}") -} - -try { - ktFunction(null) - throw RuntimeException("expected KtException.KtSimple") -} catch (e: KtException.KtSimple) { - // Expected -} - -val ktObj = KtObject(200) -assert(ktObj.ktMethod(50) == 250) - -val ktTraitImpl = createBindingTraitToRenameImpl(3) -assert(ktTraitImpl.ktTraitMethod(7) == 21) diff --git a/uniffi/bindgen-tests/kotlin/tests/rust_traits.kts b/uniffi/bindgen-tests/kotlin/tests/rust_traits.kts deleted file mode 100644 index 53d98cffa..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/rust_traits.kts +++ /dev/null @@ -1,21 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -// Kotlin uses the display impl for `toString` -assert(RustTraitTest(1, 2).toString() == "display-test-string") - -// Kotlin falls back to the debug impl for `Display` is not exported -assert(RustTraitTest2(1, 2).toString() == "debug-test-string") - -// The Rust code only uses `a` for the equality -assert(RustTraitTest(1, 2) == RustTraitTest(1, 3)) -assert(RustTraitTest(1, 2) != RustTraitTest(2, 2)) - - -// The Rust code only uses `a` for the ordering -assert(RustTraitTest(1, 2) < RustTraitTest(2, 3)) -assert(RustTraitTest(1, 2) <= RustTraitTest(1, 3) - && RustTraitTest(1, 2) >= RustTraitTest(1, 3)) - -// The Rust code only uses `a` for the hash -assert(RustTraitTest(1, 2).hashCode() == RustTraitTest(1, 3).hashCode()) -assert(RustTraitTest(2, 2).hashCode() != RustTraitTest(1, 2).hashCode()) diff --git a/uniffi/bindgen-tests/kotlin/tests/simple_fns.kts b/uniffi/bindgen-tests/kotlin/tests/simple_fns.kts deleted file mode 100644 index 5af19c888..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/simple_fns.kts +++ /dev/null @@ -1,11 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* - -// the test here is just that we can successfully call a function across the FFI -testFunc() - -try { - testUnexpectedErrorFunc() - throw RuntimeException("Expected InternalException") -} catch (e: InternalException) { - // Expected -} diff --git a/uniffi/bindgen-tests/kotlin/tests/time.kts b/uniffi/bindgen-tests/kotlin/tests/time.kts deleted file mode 100644 index 409428807..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/time.kts +++ /dev/null @@ -1,7 +0,0 @@ -import uniffi.uniffi_bindgen_tests.* -import java.time.Duration -import java.time.Instant - -val now = Instant.now() -assert(roundtripSystemtime(now) == now) -assert(roundtripDuration(Duration.ofMinutes(5)) == Duration.ofMinutes(5)) diff --git a/uniffi/bindgen-tests/kotlin/tests/trait_interfaces.kts b/uniffi/bindgen-tests/kotlin/tests/trait_interfaces.kts deleted file mode 100644 index 3ec411611..000000000 --- a/uniffi/bindgen-tests/kotlin/tests/trait_interfaces.kts +++ /dev/null @@ -1,217 +0,0 @@ -import kotlinx.coroutines.* -import uniffi.uniffi_bindgen_tests.* - -class TraitImpl(var value: UInt) : TestTraitInterface { - override fun noop() { } - - override fun getValue(): UInt { - return this.value - } - - override fun setValue(value: UInt) { - this.value = value - } - - override fun throwIfEqual(numbers: CallbackInterfaceNumbers): CallbackInterfaceNumbers { - if (numbers.a == numbers.b) { - throw TestException.Failure1() - } - return numbers - } - - override fun roundtripRecord(value: SimpleRec): SimpleRec = value - - override fun roundtripEnum(value: EnumWithData): EnumWithData = value - - override fun roundtripInterface(value: TestInterface): TestInterface = value -} - -fun checkRustImpl(rustTraitImpl: TestTraitInterface) { - rustTraitImpl.noop() - assert(rustTraitImpl.getValue() == 42u) - rustTraitImpl.setValue(43u) - assert(rustTraitImpl.getValue() == 43u) - try { - rustTraitImpl.throwIfEqual(CallbackInterfaceNumbers(a=10u, b=10u)) - throw RuntimeException("Expected TestException.Failure1") - } catch (e: TestException.Failure1) { - // Expected - } - assert( - rustTraitImpl.throwIfEqual(CallbackInterfaceNumbers(a=10u, b=11u)) == - CallbackInterfaceNumbers(a=10u, b=11u) - ) - assert(rustTraitImpl.roundtripRecord(SimpleRec(a=10.toUByte())) == SimpleRec(a=10.toUByte())) - assert( - rustTraitImpl.roundtripEnum(EnumWithData.A(10.toUByte(), 20.toUShort())) == - EnumWithData.A(10.toUByte(), 20.toUShort()) - ) - assert(rustTraitImpl.roundtripInterface(TestInterface(20u)).getValue() == 20u) -} - -fun checkKtImpl(ktTraitImpl: TestTraitInterface) { - invokeTestTraitInterfaceNoop(ktTraitImpl) - assert(invokeTestTraitInterfaceGetValue(ktTraitImpl) == 42u) - invokeTestTraitInterfaceSetValue(ktTraitImpl, 43u) - assert(invokeTestTraitInterfaceGetValue(ktTraitImpl) == 43u) - - try { - invokeTestTraitInterfaceThrowIfEqual( - ktTraitImpl, - CallbackInterfaceNumbers(a=10u, b=10u) - ) - throw RuntimeException("Expected TestException.Failure1") - } catch (e: TestException.Failure1) { - // Expected - } - assert( - invokeTestTraitInterfaceThrowIfEqual( - ktTraitImpl, - CallbackInterfaceNumbers(a=10u, b=11u) - ) == CallbackInterfaceNumbers(a=10u, b=11u) - ) - assert( - invokeTestTraitInterfaceRoundtripRecord(ktTraitImpl, SimpleRec(a=10.toUByte())) == - SimpleRec(a=10.toUByte()) - ) - assert( - invokeTestTraitInterfaceRoundtripEnum(ktTraitImpl, EnumWithData.A(10.toUByte(), 20.toUShort())) == - EnumWithData.A(10.toUByte(), 20.toUShort()) - ) - assert(invokeTestTraitInterfaceRoundtripInterface(ktTraitImpl, TestInterface(20u)).getValue() == 20u) -} - -checkRustImpl(createTestTraitInterface(42u)) -checkRustImpl( - roundtripTestTraitInterface(createTestTraitInterface(42u)) -) -checkRustImpl( - roundtripTestTraitInterfaceList(listOf(createTestTraitInterface(42u)))[0] -) - -checkKtImpl(TraitImpl(42u)) -checkKtImpl(roundtripTestTraitInterface(TraitImpl(42u))) -checkKtImpl( - roundtripTestTraitInterfaceList(listOf(TraitImpl(42u)))[0] -) - - - -class AsyncTraitImpl(var value: UInt) : AsyncTestTraitInterface { - override suspend fun noop() { } - - override suspend fun getValue(): UInt { - return this.value - } - - override suspend fun setValue(value: UInt) { - this.value = value - } - - override suspend fun throwIfEqual(numbers: CallbackInterfaceNumbers): CallbackInterfaceNumbers { - if (numbers.a == numbers.b) { - throw TestException.Failure1() - } - return numbers - } -} - -suspend fun checkAsyncRustImpl(rustTraitImpl: AsyncTestTraitInterface) { - rustTraitImpl.noop() - assert(rustTraitImpl.getValue() == 42u) - rustTraitImpl.setValue(43u) - assert(rustTraitImpl.getValue() == 43u) - try { - rustTraitImpl.throwIfEqual(CallbackInterfaceNumbers(a=10u, b=10u)) - throw RuntimeException("Expected TestException.Failure1") - } catch (e: TestException.Failure1) { - // Expected - } - assert( - rustTraitImpl.throwIfEqual(CallbackInterfaceNumbers(a=10u, b=11u)) == - CallbackInterfaceNumbers(a=10u, b=11u) - ) -} - -suspend fun checkAsyncKtImpl(ktTraitImpl: AsyncTestTraitInterface) { - invokeAsyncTestTraitInterfaceNoop(ktTraitImpl) - assert(invokeAsyncTestTraitInterfaceGetValue(ktTraitImpl) == 42u) - invokeAsyncTestTraitInterfaceSetValue(ktTraitImpl, 43u) - assert(invokeAsyncTestTraitInterfaceGetValue(ktTraitImpl) == 43u) - - try { - invokeAsyncTestTraitInterfaceThrowIfEqual( - ktTraitImpl, - CallbackInterfaceNumbers(a=10u, b=10u) - ) - throw RuntimeException("Expected TestException.Failure1") - } catch (e: TestException.Failure1) { - // Expected - } - assert( - invokeAsyncTestTraitInterfaceThrowIfEqual( - ktTraitImpl, - CallbackInterfaceNumbers(a=10u, b=11u) - ) == CallbackInterfaceNumbers(a=10u, b=11u) - ) -} - -runBlocking { - checkAsyncRustImpl(createAsyncTestTraitInterface(42u)) - checkAsyncRustImpl( - roundtripAsyncTestTraitInterface(createAsyncTestTraitInterface(42u)) - ) - checkAsyncRustImpl( - roundtripAsyncTestTraitInterfaceList(listOf(createAsyncTestTraitInterface(42u)))[0] - ) -} - -runBlocking { - checkAsyncKtImpl(AsyncTraitImpl(42u)) - checkAsyncKtImpl(roundtripAsyncTestTraitInterface(AsyncTraitImpl(42u))) - checkAsyncKtImpl( - roundtripAsyncTestTraitInterfaceList(listOf(AsyncTraitImpl(42u)))[0] - ) -} - -// Rust-only trait: smoke-test for the #[uniffi::export(rust)] codegen path -fun checkRustOnlyImpl(impl: TestRustOnlyTraitInterface) { - try { - impl.throwIfEqual(CallbackInterfaceNumbers(a=10u, b=10u)) - throw RuntimeException("Expected TestException.Failure1") - } catch (e: TestException.Failure1) { - // expected - } - assert( - impl.throwIfEqual(CallbackInterfaceNumbers(a=10u, b=11u)) == - CallbackInterfaceNumbers(a=10u, b=11u) - ) -} - -checkRustOnlyImpl(createRustOnlyTestTraitInterface()) - -// Foreign-only trait: smoke-test for the #[uniffi::export(foreign)] codegen path -class ForeignOnlyImpl : TestForeignOnlyTraitInterface { - override fun throwIfEqual(numbers: CallbackInterfaceNumbers): CallbackInterfaceNumbers { - if (numbers.a == numbers.b) { - throw TestException.Failure1() - } - return numbers - } -} - -fun checkForeignOnlyImpl(impl: TestForeignOnlyTraitInterface) { - try { - invokeTestForeignOnlyTraitThrowIfEqual(impl, CallbackInterfaceNumbers(a=10u, b=10u)) - throw RuntimeException("Expected TestException.Failure1") - } catch (e: TestException.Failure1) { - // expected - } - assert( - invokeTestForeignOnlyTraitThrowIfEqual(impl, CallbackInterfaceNumbers(a=10u, b=11u)) == - CallbackInterfaceNumbers(a=10u, b=11u) - ) -} - -checkForeignOnlyImpl(ForeignOnlyImpl()) -checkForeignOnlyImpl(roundtripTestForeignOnlyTrait(ForeignOnlyImpl())) diff --git a/uniffi/bindgen-tests/lib/Cargo.toml b/uniffi/bindgen-tests/lib/Cargo.toml deleted file mode 100644 index 9f887774e..000000000 --- a/uniffi/bindgen-tests/lib/Cargo.toml +++ /dev/null @@ -1,43 +0,0 @@ -[package] -name = "uniffi-bindgen-tests" -version = "0.31.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib", "staticlib"] - -[dependencies] -async-trait = "0.1" -camino = "1" -glob = "0.3" -thiserror = "2" -uniffi = { path = "../../uniffi", features = ["bindgen", "ffi-trace", "cargo-metadata"], default-features = false } -url = "2.5" - -uniffi-bindgen-tests-external-types-source = { path = "../external-types" } - -[features] -default = ["simple_fns", "primitive_types", "records", "enums", "collections", "options", "interfaces", - "custom_types", "errors", "callback_interfaces", "futures", "trait_interfaces", "defaults", - "references", "external-types", "renames", "bytes", "recursive_types", "time", "rust_traits"] -simple_fns = [] -primitive_types = [] -records = [] -enums = [] -collections = [] -options = [] -interfaces = [] -custom_types = [] -errors = [] -callback_interfaces = [] -futures = [] -trait_interfaces = [] -defaults = [] -references = [] -external-types = [] -renames = [] -bytes = [] -recursive_types = [] -time = [] -rust_traits = [] diff --git a/uniffi/bindgen-tests/lib/src/bytes.rs b/uniffi/bindgen-tests/lib/src/bytes.rs deleted file mode 100644 index 3a3f332d3..000000000 --- a/uniffi/bindgen-tests/lib/src/bytes.rs +++ /dev/null @@ -1,18 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[uniffi::export] -pub fn roundtrip_bytes(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn sum_bytes_procmacro(buf: &[u8]) -> u32 { - buf.iter().map(|b| *b as u32).sum() -} - -#[uniffi::export] -pub fn first_byte_procmacro(buf: &[u8]) -> Option { - buf.first().copied() -} diff --git a/uniffi/bindgen-tests/lib/src/callback_interfaces.rs b/uniffi/bindgen-tests/lib/src/callback_interfaces.rs deleted file mode 100644 index 580049042..000000000 --- a/uniffi/bindgen-tests/lib/src/callback_interfaces.rs +++ /dev/null @@ -1,68 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use crate::errors::TestError; - -#[uniffi::export(callback_interface)] -pub trait TestCallbackInterface { - /// No-op function, this tests if that we can make calls at all - fn noop(&self); - /// Get the internal value - fn get_value(&self) -> u32; - /// Set the internal value - fn set_value(&self, value: u32); - /// Method aimed at maximizing the complexity - /// - /// This should return an error if `numbers.a == numbers.b` otherwise it should return numbers back - /// unchanged. - fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result; - /// Test passing a string using a callback interface - fn echo(&self, s: String) -> String; -} - -#[derive(uniffi::Record)] -pub struct CallbackInterfaceNumbers { - pub a: u32, - pub b: u32, -} - -#[uniffi::export] -pub fn invoke_test_callback_interface_noop(cbi: Box) { - cbi.noop() -} - -#[uniffi::export] -pub fn invoke_test_callback_interface_get_value(cbi: Box) -> u32 { - cbi.get_value() -} - -#[uniffi::export] -pub fn invoke_test_callback_interface_set_value(cbi: Box, value: u32) { - cbi.set_value(value) -} - -#[uniffi::export] -pub fn invoke_test_callback_interface_throw_if_equal( - cbi: Box, - numbers: CallbackInterfaceNumbers, -) -> Result { - cbi.throw_if_equal(numbers) -} - -#[uniffi::export] -pub fn invoke_test_callback_interface_echo( - cbi: Box, - s: String, -) -> String { - cbi.echo(s) -} - -impl From for TestError { - fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self { - Self::Failure2 { data: e.reason } - } -} diff --git a/uniffi/bindgen-tests/lib/src/collections.rs b/uniffi/bindgen-tests/lib/src/collections.rs deleted file mode 100644 index ab082a52d..000000000 --- a/uniffi/bindgen-tests/lib/src/collections.rs +++ /dev/null @@ -1,137 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -use std::collections::{HashMap, HashSet}; - -// Simple tests for inputting and returning arguments - -// Rec that's contained inside vecs/maps -#[derive(uniffi::Record)] -pub struct CollectionsRec { - pub a: u8, -} - -// Rec that contains options/vecs/maps -#[derive(uniffi::Record)] -pub struct RecWithCollections { - // Put `EnumWithCollections` first to exorcise the buffer packing code - // It can be tricky to add the right padding for an enum that contains a dynamically sized type. - pub a: EnumWithCollections, - pub b: Option, - pub c: Vec, - pub d: HashMap, -} - -#[derive(uniffi::Enum)] -pub enum EnumWithCollections { - A(Option), - B(Vec), - C(HashMap), -} - -// Note: no Vec test, since that's covered by the bytes test -#[uniffi::export] -pub fn roundtrip_vec_i8(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_u16(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_i16(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_u32(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_i32(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_u64(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_i64(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_f32(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_f64(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_string(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_bool(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_rec(a: Vec) -> Vec { - a -} - -#[uniffi::export] -pub fn roundtrip_hash_map(a: HashMap) -> HashMap { - a -} - -#[uniffi::export] -pub fn roundtrip_hash_set(a: HashSet) -> HashSet { - a -} - -#[uniffi::export] -pub fn roundtrip_vec_hash_set(a: Option>>) -> Option>> { - a -} - -#[uniffi::export] -pub fn roundtrip_hash_map_u32_key(a: HashMap) -> HashMap { - a -} - -#[uniffi::export] -pub fn roundtrip_rec_with_collections(a: RecWithCollections) -> RecWithCollections { - a -} - -#[derive(uniffi::Record)] -pub struct CollectionsComplexRec { - pub a: u32, - pub b: String, - pub c: CollectionsEnum, -} - -#[derive(uniffi::Enum)] -pub enum CollectionsEnum { - A(i64), - B { a: f32, b: bool }, -} - -#[uniffi::export] -pub fn roundtrip_complex_collection_type( - a: Option>>, -) -> Option>> { - a -} diff --git a/uniffi/bindgen-tests/lib/src/custom_types.rs b/uniffi/bindgen-tests/lib/src/custom_types.rs deleted file mode 100644 index d142079e8..000000000 --- a/uniffi/bindgen-tests/lib/src/custom_types.rs +++ /dev/null @@ -1,28 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Create 2 custom types on the Rust side. -// -// Bindings tests will typically customize only one of them on the foreign side. -pub struct CustomType1(u64); -pub struct CustomType2(u64); - -uniffi::custom_type!(CustomType1, u64, { - try_lift: |val| Ok(CustomType1(val)), - lower: |custom| custom.0, -}); -uniffi::custom_type!(CustomType2, u64, { - try_lift: |val| Ok(CustomType2(val)), - lower: |custom| custom.0, -}); - -#[uniffi::export] -pub fn roundtrip_custom_type1(custom1: CustomType1) -> CustomType1 { - custom1 -} - -#[uniffi::export] -pub fn roundtrip_custom_type2(custom2: CustomType2) -> CustomType2 { - custom2 -} diff --git a/uniffi/bindgen-tests/lib/src/defaults.rs b/uniffi/bindgen-tests/lib/src/defaults.rs deleted file mode 100644 index 45b551997..000000000 --- a/uniffi/bindgen-tests/lib/src/defaults.rs +++ /dev/null @@ -1,42 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -#[derive(uniffi::Record)] -pub struct RecWithDefault { - #[uniffi(default = 42)] - pub n: u8, - #[uniffi(default)] - pub v: Vec, -} - -#[derive(Default, uniffi::Enum)] -pub enum EnumWithDefault { - #[default] - DefaultVariant, - OtherVariant { - #[uniffi(default = "default")] - a: String, - }, -} - -#[uniffi::export(default(arg = "DEFAULT"))] -pub fn func_with_default(arg: String) -> String { - arg -} - -#[derive(uniffi::Object, Default)] -pub struct InterfaceWithDefaults; - -#[uniffi::export] -impl InterfaceWithDefaults { - #[uniffi::constructor()] - pub fn new() -> Self { - Self - } - - #[uniffi::method(default(arg = "DEFAULT"))] - pub fn method_with_default(&self, arg: String) -> String { - arg - } -} diff --git a/uniffi/bindgen-tests/lib/src/enums.rs b/uniffi/bindgen-tests/lib/src/enums.rs deleted file mode 100644 index 35fa9d00f..000000000 --- a/uniffi/bindgen-tests/lib/src/enums.rs +++ /dev/null @@ -1,69 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use crate::records::SimpleRec; - -#[derive(uniffi::Enum)] -pub enum EnumNoData { - A, - B, - C, -} - -#[derive(uniffi::Enum, Clone)] -pub enum EnumWithData { - A { value: u8, value2: u16 }, - B(String, u32), - C, -} - -#[uniffi::export] -impl EnumWithData { - pub fn roundtrip(&self) -> Self { - self.clone() - } -} - -#[derive(uniffi::Enum)] -pub enum ComplexEnum { - A { value: EnumNoData }, - B { value: EnumWithData }, - C { value: SimpleRec }, -} - -// Test enum with explicit discriminant values and gaps -#[repr(u8)] -#[derive(Debug, Clone, Copy, uniffi::Enum)] -pub enum ExplicitValuedEnum { - First = 1, - Second = 2, - Fourth = 4, - Tenth = 10, - Eleventh = 11, - Thirteenth = 13, -} - -// Example with sequential and explicit values mixed -#[repr(u8)] -#[derive(Debug, Clone, Copy, uniffi::Enum)] -pub enum GappedEnum { - One = 10, - Two, // should be 11 - Three = 14, -} - -#[uniffi::export] -pub fn roundtrip_enum_no_data(en: EnumNoData) -> EnumNoData { - en -} - -#[uniffi::export] -pub fn roundtrip_enum_with_data(en: EnumWithData) -> EnumWithData { - en -} - -#[uniffi::export] -pub fn roundtrip_complex_enum(en: ComplexEnum) -> ComplexEnum { - en -} diff --git a/uniffi/bindgen-tests/lib/src/errors.rs b/uniffi/bindgen-tests/lib/src/errors.rs deleted file mode 100644 index 2f0b0da02..000000000 --- a/uniffi/bindgen-tests/lib/src/errors.rs +++ /dev/null @@ -1,76 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::io; - -/// Error enum -#[derive(uniffi::Error, thiserror::Error, Debug)] -pub enum TestError { - #[error("Failure1")] - Failure1, - #[error("Failure2(data={data})")] - Failure2 { data: String }, - #[error("Failure3(code={0})")] - Failure3(u32), -} - -/// Flat error enum -/// -/// The associated data for this won't be across the FFI. Flat errors are mostly just a historical -/// artifact, but there are some use-cases for them -- for example variants that wrap errors from -/// other crates. -#[derive(uniffi::Error, thiserror::Error, Debug)] -#[uniffi(flat_error)] -pub enum TestFlatError { - /// Here's an example of a variant that only works with a flat error, `io::Error` is not - /// UniFFI compatible and can't be passed across the FFI. - #[error("Failure1")] - IoError(io::Error), -} - -/// Error enum with no data. -/// -/// This is subtly different than a flat error -#[derive(uniffi::Error, thiserror::Error, Debug)] -pub enum TestErrorNoData { - #[error("Failure1")] - Failure1, - #[error("Failure2")] - Failure2, - #[error("Failure3")] - Failure3, -} - -#[uniffi::export] -pub fn func_with_error(input: u32) -> Result<(), TestError> { - match input { - 0 => Err(TestError::Failure1), - 1 => Err(TestError::Failure2 { - data: "DATA".to_string(), - }), - n if n < 100 => Err(TestError::Failure3(n)), - _ => Ok(()), - } -} - -#[uniffi::export] -pub fn func_with_flat_error(input: u32) -> Result<(), TestFlatError> { - match input { - 0 => Err(TestFlatError::IoError(io::Error::new( - io::ErrorKind::NotFound, - "NotFound".to_string(), - ))), - _ => Ok(()), - } -} - -#[uniffi::export] -pub fn func_with_error_no_data(input: u32) -> Result<(), TestErrorNoData> { - match input { - 0 => Err(TestErrorNoData::Failure1), - 1 => Err(TestErrorNoData::Failure2), - 2 => Err(TestErrorNoData::Failure3), - _ => Ok(()), - } -} diff --git a/uniffi/bindgen-tests/lib/src/external_types.rs b/uniffi/bindgen-tests/lib/src/external_types.rs deleted file mode 100644 index 0b9ed235c..000000000 --- a/uniffi/bindgen-tests/lib/src/external_types.rs +++ /dev/null @@ -1,28 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; -use uniffi_bindgen_tests_external_types_source::{ - ExternalCustomType, ExternalEnum, ExternalInterface, ExternalRec, -}; - -#[uniffi::export] -pub fn roundtrip_ext_record(rec: ExternalRec) -> ExternalRec { - rec -} - -#[uniffi::export] -pub fn roundtrip_ext_enum(en: ExternalEnum) -> ExternalEnum { - en -} - -#[uniffi::export] -pub fn roundtrip_ext_interface(interface: Arc) -> Arc { - interface -} - -#[uniffi::export] -pub fn roundtrip_ext_custom_type(custom: ExternalCustomType) -> ExternalCustomType { - custom -} diff --git a/uniffi/bindgen-tests/lib/src/futures.rs b/uniffi/bindgen-tests/lib/src/futures.rs deleted file mode 100644 index 377bbcebe..000000000 --- a/uniffi/bindgen-tests/lib/src/futures.rs +++ /dev/null @@ -1,156 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Async functions that round-trip data. -//! -//! The purpose of these is to test the lift/lower implementations in the async code. - -use crate::callback_interfaces::CallbackInterfaceNumbers; -use crate::errors::TestError; -use std::{collections::HashMap, sync::Arc}; - -#[uniffi::export] -pub async fn async_roundtrip_u8(v: u8) -> u8 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_i8(v: i8) -> i8 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_u16(v: u16) -> u16 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_i16(v: i16) -> i16 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_u32(v: u32) -> u32 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_i32(v: i32) -> i32 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_u64(v: u64) -> u64 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_i64(v: i64) -> i64 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_f32(v: f32) -> f32 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_f64(v: f64) -> f64 { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_string(v: String) -> String { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_vec(v: Vec) -> Vec { - v -} - -#[uniffi::export] -pub async fn async_roundtrip_map(v: HashMap) -> HashMap { - v -} - -#[uniffi::export] -pub async fn async_throw_error() -> Result<(), TestError> { - Err(TestError::Failure1) -} - -#[derive(uniffi::Object)] -pub struct AsyncInterface { - name: String, -} - -#[uniffi::export] -impl AsyncInterface { - #[uniffi::constructor] - pub fn new(name: String) -> Arc { - Arc::new(AsyncInterface { name }) - } - - pub async fn name(&self) -> String { - self.name.clone() - } -} - -#[derive(uniffi::Record)] -pub struct AsyncRecord { - name: String, -} - -#[uniffi::export] -impl AsyncRecord { - pub async fn get_name(&self) -> String { - self.name.clone() - } -} - -#[uniffi::export] -pub async fn async_roundtrip_obj(v: Arc) -> Arc { - v -} - -/// Async version of `TestCallbackInterface` -#[uniffi::export(callback_interface)] -#[async_trait::async_trait] -pub trait TestAsyncCallbackInterface: Send + Sync { - async fn noop(&self); - async fn get_value(&self) -> u32; - async fn set_value(&self, value: u32); - async fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result; -} - -#[uniffi::export] -pub async fn invoke_test_async_callback_interface_noop(cbi: Box) { - cbi.noop().await -} - -#[uniffi::export] -pub async fn invoke_test_async_callback_interface_get_value( - cbi: Box, -) -> u32 { - cbi.get_value().await -} - -#[uniffi::export] -pub async fn invoke_test_async_callback_interface_set_value( - cbi: Box, - value: u32, -) { - cbi.set_value(value).await -} - -#[uniffi::export] -pub async fn invoke_test_async_callback_interface_throw_if_equal( - cbi: Box, - numbers: CallbackInterfaceNumbers, -) -> Result { - cbi.throw_if_equal(numbers).await -} diff --git a/uniffi/bindgen-tests/lib/src/interfaces.rs b/uniffi/bindgen-tests/lib/src/interfaces.rs deleted file mode 100644 index 0deda5aae..000000000 --- a/uniffi/bindgen-tests/lib/src/interfaces.rs +++ /dev/null @@ -1,84 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -#[derive(uniffi::Object)] -pub struct TestInterface { - value: u32, -} - -#[uniffi::export] -impl TestInterface { - #[uniffi::constructor] - pub fn new(value: u32) -> Self { - Self { value } - } - - #[uniffi::constructor] - pub fn secondary_constructor(value: u32) -> Self { - Self { value: value * 2 } - } - - #[uniffi::constructor] - pub fn from_interface(other: Arc) -> Self { - Self { value: other.value } - } - - pub fn get_value(&self) -> u32 { - self.value - } - - /// Get the current reference count for this object - /// - /// The count does not include the extra reference needed to call this method. - pub fn ref_count(self: Arc) -> u32 { - (Arc::strong_count(&self) - 1) as u32 - } - - /// Test a multi-word argument. `the_argument` should be normalized to the naming style of the - /// foreign language. - pub fn method_with_multi_word_arg(&self, the_argument: String) -> String { - the_argument - } - - pub fn clone_other(&self, other: Arc) -> Arc { - other - } -} - -#[uniffi::export] -pub fn clone_interface(interface: Arc) -> Arc { - interface -} - -// Test optional interfaces -#[uniffi::export] -pub fn roundtrip_optional_interface( - interface: Option>, -) -> Option> { - interface -} - -// Test interfaces in records -#[derive(uniffi::Record)] -pub struct TwoTestInterfaces { - pub first: Arc, - pub second: Arc, -} - -#[uniffi::export] -pub fn swap_test_interfaces(interfaces: TwoTestInterfaces) -> TwoTestInterfaces { - TwoTestInterfaces { - first: interfaces.second, - second: interfaces.first, - } -} - -// Test interfaces in enums -#[derive(uniffi::Enum)] -pub enum TestInterfaceEnum { - One { i: Arc }, - Two { i: Arc }, -} diff --git a/uniffi/bindgen-tests/lib/src/lib.rs b/uniffi/bindgen-tests/lib/src/lib.rs deleted file mode 100644 index c7cffbf02..000000000 --- a/uniffi/bindgen-tests/lib/src/lib.rs +++ /dev/null @@ -1,165 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -uniffi::setup_scaffolding!("uniffi_bindgen_tests"); - -#[cfg(feature = "bytes")] -pub mod bytes; - -#[cfg(feature = "callback_interfaces")] -pub mod callback_interfaces; - -#[cfg(feature = "collections")] -pub mod collections; - -#[cfg(feature = "custom_types")] -pub mod custom_types; - -#[cfg(feature = "defaults")] -pub mod defaults; - -#[cfg(feature = "enums")] -pub mod enums; - -#[cfg(feature = "errors")] -pub mod errors; - -#[cfg(feature = "external-types")] -pub mod external_types; - -#[cfg(feature = "futures")] -pub mod futures; - -#[cfg(feature = "interfaces")] -pub mod interfaces; - -#[cfg(feature = "options")] -pub mod options; - -#[cfg(feature = "primitive_types")] -pub mod primitive_types; - -#[cfg(feature = "records")] -pub mod records; - -#[cfg(feature = "recursive_types")] -pub mod recursive_types; - -#[cfg(feature = "references")] -pub mod references; - -#[cfg(feature = "renames")] -pub mod renames; - -#[cfg(feature = "rust_traits")] -pub mod rust_traits; - -#[cfg(feature = "simple_fns")] -pub mod simple_fns; - -#[cfg(feature = "time")] -pub mod time; - -#[cfg(feature = "trait_interfaces")] -pub mod trait_interfaces; - -// Utility functions for the Rust tests -pub mod test_util { - use camino::{Utf8Path, Utf8PathBuf}; - use std::{ - env::{ - consts::{DLL_PREFIX, DLL_SUFFIX}, - var, - }, - fs, - process::Command, - sync::OnceLock, - }; - - pub fn current_crate_dir() -> Utf8PathBuf { - Utf8PathBuf::from(var("CARGO_MANIFEST_DIR").unwrap()) - } - - pub fn workspace_dir() -> Utf8PathBuf { - static DIR: OnceLock = OnceLock::new(); - DIR.get_or_init(|| { - let output: String = Command::new("cargo") - .args(["locate-project", "--workspace", "--message-format=plain"]) - .output() - .unwrap() - .stdout - .try_into() - .unwrap(); - Utf8PathBuf::from(output).parent().unwrap().to_path_buf() - }) - .to_path_buf() - } - - pub fn library_filename() -> String { - let package_name = var("CARGO_PKG_NAME").expect("CARGO_PKG_NAME not set"); - let lib_name = package_name.replace("-", "_"); - format!("{DLL_PREFIX}{lib_name}{DLL_SUFFIX}") - } - - // Named after the libtest thread asking for it, so each nextest process (one test each) gets - // its own directory instead of deleting one another process is using. - pub fn setup_test_dir(language_name: &str) -> Utf8PathBuf { - let thread = std::thread::current(); - let test_name = match thread.name() { - Some(name) if name != "main" => name.rsplit("::").next().unwrap(), - _ => panic!("setup_test_dir must run on a libtest test thread"), - }; - let path = workspace_dir() - .join("target") - .join("uniffi-tests") - .join(language_name) - .join(test_name); - if path.exists() { - std::fs::remove_dir_all(&path).unwrap(); - } - std::fs::create_dir_all(&path).unwrap(); - path - } - - pub fn build_library(tempdir: &Utf8Path) { - let package_name = var("CARGO_PKG_NAME").expect("CARGO_PKG_NAME not set"); - let status = Command::new("cargo") - .args(["build", "-p", &package_name]) - .status() - .unwrap(); - if !status.success() { - panic!("cargo build -p {package_name} failed"); - } - let target_dir = workspace_dir().join("target/debug").to_string(); - let library_filename = library_filename(); - fs::copy( - format!("{target_dir}/{library_filename}"), - tempdir.join(&library_filename), - ) - .unwrap(); - } - - pub fn generate_sources(library_dir: &Utf8Path, language: uniffi::TargetLanguage) { - let library_filename = library_filename(); - uniffi::generate(uniffi::GenerateOptions { - languages: vec![language], - source: library_dir.join(library_filename), - format: false, - out_dir: library_dir.to_path_buf(), - ..uniffi::GenerateOptions::default() - }) - .unwrap(); - } - - // Copy sources to the temp directory - // - // globspec is relative to the current crate directory - pub fn copy_test_sources(tempdir: &Utf8Path, globspec: &str) { - for path in glob::glob(globspec).unwrap() { - let path = Utf8PathBuf::from_path_buf(path.unwrap()).unwrap(); - std::fs::create_dir_all(tempdir.join(path.parent().unwrap())).unwrap(); - fs::copy(&path, tempdir.join(&path)).unwrap(); - } - } -} diff --git a/uniffi/bindgen-tests/lib/src/options.rs b/uniffi/bindgen-tests/lib/src/options.rs deleted file mode 100644 index b38d554f3..000000000 --- a/uniffi/bindgen-tests/lib/src/options.rs +++ /dev/null @@ -1,76 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -// Tests for inputting and returning `Option` arguments - -// Rec that's contained inside options -#[derive(uniffi::Record)] -pub struct OptionsRec { - pub a: u8, -} - -#[uniffi::export] -pub fn roundtrip_option_u8(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_i8(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_u16(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_i16(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_u32(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_i32(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_u64(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_i64(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_f32(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_f64(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_string(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_bool(a: Option) -> Option { - a -} - -#[uniffi::export] -pub fn roundtrip_option_rec(a: Option) -> Option { - a -} diff --git a/uniffi/bindgen-tests/lib/src/primitive_types.rs b/uniffi/bindgen-tests/lib/src/primitive_types.rs deleted file mode 100644 index 757c62c69..000000000 --- a/uniffi/bindgen-tests/lib/src/primitive_types.rs +++ /dev/null @@ -1,217 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -//! Test lifting/lowering primitive types - -// Simple tests for inputting and returning arguments - -#[uniffi::export] -pub fn input_u8(_a: u8) {} - -#[uniffi::export] -pub fn input_i8(_a: i8) {} - -#[uniffi::export] -pub fn input_u16(_a: u16) {} - -#[uniffi::export] -pub fn input_i16(_a: i16) {} - -#[uniffi::export] -pub fn input_u32(_a: u32) {} - -#[uniffi::export] -pub fn input_i32(_a: i32) {} - -#[uniffi::export] -pub fn input_u64(_a: u64) {} - -#[uniffi::export] -pub fn input_i64(_a: i64) {} - -#[uniffi::export] -pub fn input_f32(_a: f32) {} - -#[uniffi::export] -pub fn input_f64(_a: f64) {} - -#[uniffi::export] -pub fn input_bool(_a: bool) {} - -#[uniffi::export] -pub fn input_string(_a: String) {} - -#[uniffi::export] -pub fn output_u8() -> u8 { - 1 -} - -#[uniffi::export] -pub fn output_i8() -> i8 { - 1 -} - -#[uniffi::export] -pub fn output_u16() -> u16 { - 1 -} - -#[uniffi::export] -pub fn output_u8_max() -> u8 { - u8::MAX -} - -#[uniffi::export] -pub fn output_u16_max() -> u16 { - u16::MAX -} - -#[uniffi::export] -pub fn output_i16() -> i16 { - 1 -} - -#[uniffi::export] -pub fn output_u32() -> u32 { - 1 -} - -#[uniffi::export] -pub fn output_i32() -> i32 { - 1 -} - -#[uniffi::export] -pub fn output_u64() -> u64 { - 1 -} - -#[uniffi::export] -pub fn output_i64() -> i64 { - 1 -} - -#[uniffi::export] -pub fn output_f32() -> f32 { - 1.0 -} - -#[uniffi::export] -pub fn output_f64() -> f64 { - 1.0 -} - -#[uniffi::export] -pub fn output_bool() -> bool { - true -} - -#[uniffi::export] -pub fn output_string() -> String { - "test-string".into() -} - -#[uniffi::export] -pub fn roundtrip_u8(a: u8) -> u8 { - a -} - -#[uniffi::export] -pub fn roundtrip_i8(a: i8) -> i8 { - a -} - -#[uniffi::export] -pub fn roundtrip_u16(a: u16) -> u16 { - a -} - -#[uniffi::export] -pub fn roundtrip_i16(a: i16) -> i16 { - a -} - -#[uniffi::export] -pub fn roundtrip_u32(a: u32) -> u32 { - a -} - -#[uniffi::export] -pub fn roundtrip_i32(a: i32) -> i32 { - a -} - -#[uniffi::export] -pub fn roundtrip_u64(a: u64) -> u64 { - a -} - -#[uniffi::export] -pub fn roundtrip_i64(a: i64) -> i64 { - a -} - -#[uniffi::export] -pub fn roundtrip_f32(a: f32) -> f32 { - a -} - -#[uniffi::export] -pub fn roundtrip_f64(a: f64) -> f64 { - a -} - -#[uniffi::export] -pub fn roundtrip_bool(a: bool) -> bool { - a -} - -#[uniffi::export] -pub fn roundtrip_string(a: String) -> String { - a -} - -/// Complex test: input a bunch of different values and add them together -#[uniffi::export] -#[allow(clippy::too_many_arguments)] -pub fn sum_with_many_types( - a: u8, - b: i8, - c: u16, - d: i16, - e: u32, - f: i32, - g: u64, - h: i64, - i: f32, - j: f64, - negate: bool, -) -> f64 { - uniffi::trace!("sum_with_many_types: {a} {b} {c} {d} {e} {f} {g} {h} {i} {j} {negate}"); - let all_values = [ - a as f64, b as f64, c as f64, d as f64, e as f64, f as f64, g as f64, h as f64, i as f64, j, - ]; - let sum: f64 = all_values.into_iter().sum(); - if negate { - -sum - } else { - sum - } -} - -/// Test a multi-word argument. `the_argument` should be normalized to the naming style of the -/// foreign language. -#[uniffi::export] -pub fn func_with_multi_word_arg(the_argument: i32) -> i32 { - the_argument -} - -// Round-trip strings prefixed with U+FEFF (byte order mark) so the bindings -// can assert string converters preserve the BOM rather than treating it as -// encoding metadata. The two functions cover both converter paths: `lift` -// for top-level returns and `read` for elements inside a serialized buffer. -#[uniffi::export] -pub fn string_with_bom() -> String { - "\u{feff}hello".to_string() -} diff --git a/uniffi/bindgen-tests/lib/src/records.rs b/uniffi/bindgen-tests/lib/src/records.rs deleted file mode 100644 index ec2670893..000000000 --- a/uniffi/bindgen-tests/lib/src/records.rs +++ /dev/null @@ -1,46 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[derive(uniffi::Record)] -pub struct SimpleRec { - pub a: u8, -} - -#[uniffi::export] -impl SimpleRec { - pub fn roundtrip(&self) -> Self { - SimpleRec { a: self.a } - } -} - -#[derive(uniffi::Record)] -pub struct UnitRec; - -// Note: tuple-style records are currently not supported - -#[derive(uniffi::Record)] -pub struct ComplexRec { - pub field_u8: u8, - pub field_i8: i8, - pub field_u16: u16, - pub field_i16: i16, - pub field_u32: u32, - pub field_i32: i32, - pub field_u64: u64, - pub field_i64: i64, - pub field_f32: f32, - pub field_f64: f64, - pub field_string: String, - pub field_rec: SimpleRec, -} - -#[uniffi::export] -pub fn roundtrip_simple_rec(rec: SimpleRec) -> SimpleRec { - rec -} - -#[uniffi::export] -pub fn roundtrip_complex_rec(rec: ComplexRec) -> ComplexRec { - rec -} diff --git a/uniffi/bindgen-tests/lib/src/recursive_types.rs b/uniffi/bindgen-tests/lib/src/recursive_types.rs deleted file mode 100644 index e0d9398bd..000000000 --- a/uniffi/bindgen-tests/lib/src/recursive_types.rs +++ /dev/null @@ -1,152 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Test recursive types and boxed fields - -// Self-recursive tree -#[derive(uniffi::Enum)] -pub enum Tree { - Leaf(i32), - Node { left: Box, right: Box }, -} - -// Mutually recursive pair -#[derive(uniffi::Enum)] -pub enum Expr { - Lit(i32), - If { - cond: Box, - then_: Box, - else_: Box, - }, -} - -#[derive(uniffi::Enum)] -pub enum BoolExpr { - True_, - False_, - Not(Box), - IsZero(Box), -} - -// Cycle through Optional: LinkedList → Option> -#[derive(uniffi::Enum)] -pub enum LinkedList { - Nil, - Cons { - head: i32, - tail: Option>, - }, -} - -#[uniffi::export] -pub fn list_sum(list: LinkedList) -> i32 { - match list { - LinkedList::Nil => 0, - LinkedList::Cons { head, tail } => head + tail.map(|t| list_sum(*t)).unwrap_or(0), - } -} - -// Cycle through Map value: Trie → HashMap> -#[derive(uniffi::Enum)] -pub enum Trie { - Leaf(i32), - Branch { - children: std::collections::HashMap>, - }, -} - -#[uniffi::export] -pub fn trie_sum(trie: Trie) -> i32 { - match trie { - Trie::Leaf(v) => v, - Trie::Branch { children } => children.into_values().map(|t| trie_sum(*t)).sum(), - } -} - -// Cycle through a record: RoseTree → RoseData → Vec -#[derive(uniffi::Enum)] -pub enum RoseTree { - Leaf(i32), - Branch(RoseData), -} - -#[derive(uniffi::Record)] -pub struct RoseData { - pub value: i32, - pub children: Vec, -} - -#[uniffi::export] -pub fn sum_rose_tree(tree: RoseTree) -> i32 { - match tree { - RoseTree::Leaf(v) => v, - RoseTree::Branch(data) => { - data.value + data.children.into_iter().map(sum_rose_tree).sum::() - } - } -} - -#[uniffi::export] -pub fn sum_tree(tree: Tree) -> i32 { - match tree { - Tree::Leaf(v) => v, - Tree::Node { left, right } => sum_tree(*left) + sum_tree(*right), - } -} - -#[uniffi::export] -pub fn eval_expr(expr: Expr) -> i32 { - match expr { - Expr::Lit(v) => v, - Expr::If { cond, then_, else_ } => { - if eval_bool(*cond) { - eval_expr(*then_) - } else { - eval_expr(*else_) - } - } - } -} - -#[uniffi::export] -pub fn eval_bool(expr: BoolExpr) -> bool { - match expr { - BoolExpr::True_ => true, - BoolExpr::False_ => false, - BoolExpr::Not(inner) => !eval_bool(*inner), - BoolExpr::IsZero(inner) => eval_expr(*inner) == 0, - } -} - -// Recursive error enum: Nested(Box) forms a self-cycle. -// Verifies that #[derive(uniffi::Error)] enums are detected as recursive -// and generate correct indirect/forward-ref bindings. -#[derive(Debug, uniffi::Error)] -pub enum EvalError { - Overflow, - Nested { inner: Box }, -} - -impl std::fmt::Display for EvalError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - EvalError::Overflow => write!(f, "overflow"), - EvalError::Nested { .. } => write!(f, "nested error"), - } - } -} - -impl std::error::Error for EvalError {} - -#[uniffi::export] -pub fn maybe_throw_error(should_throw: bool) -> Result { - if should_throw { - Err(EvalError::Nested { - inner: Box::new(EvalError::Overflow), - }) - } else { - Ok(42) - } -} diff --git a/uniffi/bindgen-tests/lib/src/references.rs b/uniffi/bindgen-tests/lib/src/references.rs deleted file mode 100644 index 41afa84a3..000000000 --- a/uniffi/bindgen-tests/lib/src/references.rs +++ /dev/null @@ -1,57 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -// Function that inputs an argument by reference -#[uniffi::export] -pub fn roundtrip_u8_ref(a: &u8) -> u8 { - *a -} - -// Input an interface reference -#[uniffi::export] -pub fn call_double_value(i: &ReferenceTestInterface, a: u32) -> u32 { - i.double_value(&a) -} - -// Input an trait interface reference -#[uniffi::export] -pub fn call_triple_value_trait_interface(t: &dyn ReferenceTestTraitInterface, a: u32) -> u32 { - t.triple_value(a) -} - -#[derive(uniffi::Object, Default)] -pub struct ReferenceTestInterface; - -#[uniffi::export] -impl ReferenceTestInterface { - #[uniffi::constructor] - pub fn new() -> Self { - Self - } - - // Test a method that inputs a reference - pub fn double_value(&self, a: &u32) -> u32 { - a * 2 - } -} - -#[uniffi::export] -pub trait ReferenceTestTraitInterface: Send + Sync { - fn triple_value(&self, a: u32) -> u32; -} - -#[uniffi::export] -pub fn create_reference_test_trait_interface() -> Arc { - Arc::new(ReferenceTestTraitInterfaceImpl) -} - -struct ReferenceTestTraitInterfaceImpl; - -impl ReferenceTestTraitInterface for ReferenceTestTraitInterfaceImpl { - fn triple_value(&self, a: u32) -> u32 { - a * 3 - } -} diff --git a/uniffi/bindgen-tests/lib/src/renames.rs b/uniffi/bindgen-tests/lib/src/renames.rs deleted file mode 100644 index 212bab110..000000000 --- a/uniffi/bindgen-tests/lib/src/renames.rs +++ /dev/null @@ -1,154 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[uniffi::export(name = "renamed_function")] -pub fn function_to_rename(record: RecordToRename) -> EnumToRename { - EnumToRename::Record(record) -} - -#[derive(uniffi::Record)] -#[uniffi(name = "RenamedRecord")] -pub struct RecordToRename { - pub item: i32, -} - -#[derive(uniffi::Enum)] -#[uniffi(name = "RenamedEnum")] -pub enum EnumToRename { - #[uniffi(name = "RenamedVariant")] - VariantA, - Record(RecordToRename), -} - -#[derive(thiserror::Error, uniffi::Error, Debug)] -#[uniffi(name = "RenamedError")] -pub enum ErrorToRename { - #[error("Simple error")] - #[uniffi(name = "RenamedErrorVariant")] - Simple, -} - -#[derive(uniffi::Object)] -#[uniffi(name = "RenamedObject")] -pub struct ObjectToRename { - value: i32, -} - -#[uniffi::export(name = "RenamedObject")] -impl ObjectToRename { - #[uniffi::constructor(name = "renamed_constructor")] - pub fn new(value: i32) -> Self { - ObjectToRename { value } - } - - #[uniffi::method(name = "renamed_method")] - pub fn method(&self) -> i32 { - self.value - } -} - -// Can't rename traits yet, should be possible though, just trickier. -#[uniffi::export] -pub trait TraitToRename: Send + Sync { - #[uniffi::method(name = "renamed_trait_method")] - fn trait_method(&self, value: i32) -> i32; -} - -struct TraitImpl { - multiplier: i32, -} - -impl TraitToRename for TraitImpl { - fn trait_method(&self, value: i32) -> i32 { - value * self.multiplier - } -} - -#[uniffi::export(name = "create_trait_impl")] -pub fn create_trait_to_rename_impl(multiplier: i32) -> std::sync::Arc { - std::sync::Arc::new(TraitImpl { multiplier }) -} - -/// BINDINGS TESTS -/// -/// The way our tests are setup makes it inconvenient to reuse the above, -/// so we duplicate much of the above for testing renaming tests in bindings. -/// -/// All types have a "bindings" prefix, the actual bindings will replace with, eg, "python" -#[uniffi::export] -pub fn binding_function_to_rename( - record: Option, -) -> Result { - match record { - Some(r) => Ok(BindingEnumToRename::Record(r)), - None => Err(BindingErrorToRename::Simple), - } -} - -#[derive(uniffi::Record)] -pub struct BindingRecordToRename { - pub item: i32, -} - -#[derive(uniffi::Enum)] -pub enum BindingEnumToRename { - VariantA, - Record(BindingRecordToRename), -} - -#[derive(uniffi::Enum)] -pub enum BindingEnumWithFieldsToRename { - VariantA { - binding_int: u32, - }, - Record { - binding_record: BindingRecordToRename, - binding_int: u32, - }, -} - -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum BindingErrorToRename { - #[error("Simple error")] - Simple, -} - -#[derive(uniffi::Object)] -pub struct BindingObjectToRename { - value: i32, -} - -#[uniffi::export] -impl BindingObjectToRename { - #[uniffi::constructor] - pub fn new(value: i32) -> Self { - BindingObjectToRename { value } - } - - pub fn method(&self, arg: i32) -> Result { - Ok(self.value + arg) - } -} - -#[uniffi::export] -pub trait BindingTraitToRename: Send + Sync { - fn trait_method(&self, value: i32) -> i32; -} - -struct BindingTraitImpl { - multiplier: i32, -} - -impl BindingTraitToRename for BindingTraitImpl { - fn trait_method(&self, value: i32) -> i32 { - value * self.multiplier - } -} - -#[uniffi::export] -pub fn create_binding_trait_to_rename_impl( - multiplier: i32, -) -> std::sync::Arc { - std::sync::Arc::new(BindingTraitImpl { multiplier }) -} diff --git a/uniffi/bindgen-tests/lib/src/rust_traits.rs b/uniffi/bindgen-tests/lib/src/rust_traits.rs deleted file mode 100644 index cb5d641a8..000000000 --- a/uniffi/bindgen-tests/lib/src/rust_traits.rs +++ /dev/null @@ -1,77 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::{ - cmp::Ordering, - collections::hash_map::DefaultHasher, - fmt, - hash::{Hash, Hasher}, -}; - -#[derive(Eq, uniffi::Record)] -#[uniffi::export(Debug, Display, Eq, Ord, Hash)] -pub struct RustTraitTest { - pub a: i32, - pub b: i32, -} - -impl fmt::Debug for RustTraitTest { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - write!(f, "debug-test-string") - } -} - -impl fmt::Display for RustTraitTest { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - write!(f, "display-test-string") - } -} - -// Only include `a` in the hash/ord/eq impls -// This gives us a way to test this in the foreign bindings. - -impl Hash for RustTraitTest { - fn hash(&self, state: &mut H) { - self.a.hash(state); - } -} - -impl PartialEq for RustTraitTest { - fn eq(&self, other: &RustTraitTest) -> bool { - self.a == other.a - } -} - -#[allow(clippy::non_canonical_partial_ord_impl)] -impl PartialOrd for RustTraitTest { - fn partial_cmp(&self, other: &RustTraitTest) -> Option { - Some(self.a.cmp(&other.a)) - } -} - -impl Ord for RustTraitTest { - fn cmp(&self, other: &RustTraitTest) -> Ordering { - self.a.cmp(&other.a) - } -} - -#[uniffi::export] -pub fn rust_trait_test_hash(trait_test: RustTraitTest) -> u64 { - let mut s = DefaultHasher::new(); - Hash::hash(&trait_test, &mut s); - s.finish() -} - -#[derive(uniffi::Record)] -#[uniffi::export(Debug)] -pub struct RustTraitTest2 { - pub a: i32, - pub b: i32, -} - -impl fmt::Debug for RustTraitTest2 { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - write!(f, "debug-test-string") - } -} diff --git a/uniffi/bindgen-tests/lib/src/simple_fns.rs b/uniffi/bindgen-tests/lib/src/simple_fns.rs deleted file mode 100644 index 238879ef1..000000000 --- a/uniffi/bindgen-tests/lib/src/simple_fns.rs +++ /dev/null @@ -1,16 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -//! Extremely simple fixture to test making scaffolding calls without any arguments or return types - -/// Test that bindings the bindings can make a call to `test_func`. If in doubt, run the tests with -/// `--features=ffi-trace` to check that the function is actually called. -#[uniffi::export] -pub fn test_func() {} - -/// Test what happens when there's an unexpected error in the Rust function, like a panic. -#[uniffi::export] -pub fn test_unexpected_error_func() { - panic!("test panic") -} diff --git a/uniffi/bindgen-tests/lib/src/time.rs b/uniffi/bindgen-tests/lib/src/time.rs deleted file mode 100644 index 38abcaa4c..000000000 --- a/uniffi/bindgen-tests/lib/src/time.rs +++ /dev/null @@ -1,17 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Test SystemTime and Duration - -pub use std::time::{Duration, SystemTime}; - -#[uniffi::export] -pub fn roundtrip_systemtime(a: SystemTime) -> SystemTime { - a -} - -#[uniffi::export] -pub fn roundtrip_duration(a: Duration) -> Duration { - a -} diff --git a/uniffi/bindgen-tests/lib/src/trait_interfaces.rs b/uniffi/bindgen-tests/lib/src/trait_interfaces.rs deleted file mode 100644 index c5e018dfa..000000000 --- a/uniffi/bindgen-tests/lib/src/trait_interfaces.rs +++ /dev/null @@ -1,310 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Trait interface test. This is the like the `callback_interfaces` module, except it uses a -//! trait that has `with_foreign` enabled (AKA a trait interface). This means UniFFI supports both -//! Rust and foreign language implementations of the trait. Also includes a minimal -//! `#[uniffi::export(foreign)]` trait to verify the foreign-only codegen path. - -use std::sync::{ - atomic::{AtomicU32, Ordering}, - Arc, -}; - -use crate::errors::TestError; -use crate::{ - callback_interfaces::CallbackInterfaceNumbers, enums::EnumWithData, interfaces::TestInterface, - records::SimpleRec, -}; - -/// Trait interface that can be implemented by both Rust and the foreign side -/// -/// This is the main thing we'll test -#[uniffi::export(rust, foreign)] -pub trait TestTraitInterface: Send + Sync { - /// No-op function, this tests if that we can make calls at all - fn noop(&self); - /// Get the internal value - fn get_value(&self) -> u32; - /// Set the internal value - fn set_value(&self, value: u32); - - // Test inputting/outputting different types - fn roundtrip_record(&self, value: SimpleRec) -> SimpleRec; - fn roundtrip_enum(&self, value: EnumWithData) -> EnumWithData; - fn roundtrip_interface(&self, value: Arc) -> Arc; - - /// Method aimed at maximizing the complexity - /// - /// This inputs a bunch of different types and also can throw an error - /// - /// This should return an error if `numbers.a == numbers.b` otherwise it should return numbers back - /// unchanged. - fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result; -} - -#[uniffi::export] -pub fn invoke_test_trait_interface_noop(interface: Arc) { - interface.noop() -} - -#[uniffi::export] -pub fn invoke_test_trait_interface_get_value(interface: Arc) -> u32 { - interface.get_value() -} - -#[uniffi::export] -pub fn invoke_test_trait_interface_set_value(interface: Arc, value: u32) { - interface.set_value(value) -} - -#[uniffi::export] -pub fn invoke_test_trait_interface_roundtrip_record( - interface: Arc, - rec: SimpleRec, -) -> SimpleRec { - interface.roundtrip_record(rec) -} - -#[uniffi::export] -pub fn invoke_test_trait_interface_roundtrip_enum( - interface: Arc, - en: EnumWithData, -) -> EnumWithData { - interface.roundtrip_enum(en) -} - -#[uniffi::export] -pub fn invoke_test_trait_interface_roundtrip_interface( - interface: Arc, - iface: Arc, -) -> Arc { - interface.roundtrip_interface(iface) -} - -#[uniffi::export] -pub fn invoke_test_trait_interface_throw_if_equal( - interface: Arc, - numbers: CallbackInterfaceNumbers, -) -> Result { - interface.throw_if_equal(numbers) -} - -/// Create an implementation of the interface in Rust -#[uniffi::export] -pub fn create_test_trait_interface(value: u32) -> Arc { - Arc::new(TestTraitInterfaceImpl { - value: AtomicU32::new(value), - }) -} - -pub struct TestTraitInterfaceImpl { - value: AtomicU32, -} - -impl TestTraitInterface for TestTraitInterfaceImpl { - fn noop(&self) {} - - fn get_value(&self) -> u32 { - self.value.load(Ordering::Relaxed) - } - - fn set_value(&self, value: u32) { - self.value.store(value, Ordering::Relaxed); - } - - fn roundtrip_record(&self, value: SimpleRec) -> SimpleRec { - value - } - - fn roundtrip_enum(&self, value: EnumWithData) -> EnumWithData { - value - } - - fn roundtrip_interface(&self, value: Arc) -> Arc { - value - } - - fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result { - if numbers.a == numbers.b { - Err(TestError::Failure1) - } else { - Ok(numbers) - } - } -} - -/// Async version of `TestTraitInterface` -#[uniffi::export(with_foreign)] -#[async_trait::async_trait] -pub trait AsyncTestTraitInterface: Send + Sync { - /// No-op function, this tests if that we can make calls at all - async fn noop(&self); - /// Get the internal value - async fn get_value(&self) -> u32; - /// Set the internal value - async fn set_value(&self, value: u32); - /// Method aimed at maximizing the complexity - /// - /// This should return an error if `numbers.a == numbers.b` otherwise it should return numbers back - /// unchanged. - async fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result; -} - -#[uniffi::export] -pub fn create_async_test_trait_interface(value: u32) -> Arc { - Arc::new(TestTraitInterfaceImpl { - value: AtomicU32::new(value), - }) -} - -#[uniffi::export] -pub async fn invoke_async_test_trait_interface_noop(interface: Arc) { - interface.noop().await -} - -#[uniffi::export] -pub async fn invoke_async_test_trait_interface_get_value( - interface: Arc, -) -> u32 { - interface.get_value().await -} - -#[uniffi::export] -pub async fn invoke_async_test_trait_interface_set_value( - interface: Arc, - value: u32, -) { - interface.set_value(value).await -} - -#[uniffi::export] -pub async fn invoke_async_test_trait_interface_throw_if_equal( - interface: Arc, - numbers: CallbackInterfaceNumbers, -) -> Result { - interface.throw_if_equal(numbers).await -} - -#[async_trait::async_trait] -impl AsyncTestTraitInterface for TestTraitInterfaceImpl { - async fn noop(&self) {} - - async fn get_value(&self) -> u32 { - self.value.load(Ordering::Relaxed) - } - - async fn set_value(&self, value: u32) { - self.value.store(value, Ordering::Relaxed); - } - - async fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result { - if numbers.a == numbers.b { - Err(TestError::Failure1) - } else { - Ok(numbers) - } - } -} - -/// Rust-only trait interface: no foreign impl. -/// A single method is enough to smoke-test the foreign-only codegen path. -#[uniffi::export(rust)] -pub trait TestRustOnlyTraitInterface: Send + Sync { - fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result; -} - -/// Create an implementation of the interface in Rust -#[uniffi::export] -pub fn create_rust_only_test_trait_interface() -> Arc { - Arc::new(TestRustOnlyTraitInterfaceImpl) -} - -pub struct TestRustOnlyTraitInterfaceImpl; - -impl TestRustOnlyTraitInterface for TestRustOnlyTraitInterfaceImpl { - fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result { - if numbers.a == numbers.b { - Err(TestError::Failure1) - } else { - Ok(numbers) - } - } -} - -/// Foreign-only trait interface: no Rust impl, no `create_*` export. -/// A single method is enough to smoke-test the foreign-only codegen path. -#[uniffi::export(foreign)] -pub trait TestForeignOnlyTraitInterface: Send + Sync { - fn throw_if_equal( - &self, - numbers: CallbackInterfaceNumbers, - ) -> Result; -} - -#[uniffi::export] -pub fn invoke_test_foreign_only_trait_throw_if_equal( - interface: Arc, - numbers: CallbackInterfaceNumbers, -) -> Result { - interface.throw_if_equal(numbers) -} - -#[uniffi::export] -pub fn roundtrip_test_foreign_only_trait( - interface: Arc, -) -> Arc { - interface -} - -// Functions to round-trip trait interfaces across the FFI -// -// These are used to test that they still work after being lifted/lowered. -// The list versions are there to test them being passed via a `RustBuffer`. - -#[uniffi::export] -pub fn roundtrip_test_trait_interface( - interface: Arc, -) -> Arc { - interface -} - -#[uniffi::export] -pub fn roundtrip_test_trait_interface_list( - interfaces: Vec>, -) -> Vec> { - interfaces -} - -#[uniffi::export] -pub fn roundtrip_async_test_trait_interface( - interface: Arc, -) -> Arc { - interface -} - -#[uniffi::export] -pub fn roundtrip_async_test_trait_interface_list( - interfaces: Vec>, -) -> Vec> { - interfaces -} diff --git a/uniffi/bindgen-tests/lib/uniffi.toml b/uniffi/bindgen-tests/lib/uniffi.toml deleted file mode 100644 index 833149237..000000000 --- a/uniffi/bindgen-tests/lib/uniffi.toml +++ /dev/null @@ -1,115 +0,0 @@ -# -# Custom type configuration -# -[bindings.kotlin.custom_types.CustomType2] -# Use `dict` as our custom type wrapper, since we can use it without having to import any types -type_name = "Map" -lift = "mapOf(\"value\" to {})" -lower = "{}[\"value\"]!!" - -[bindings.python.custom_types.CustomType2] -# Use `dict` as our custom type wrapper, since we can use it without having to import any types -type_name = "dict[str, str]" -lift = "{\"value\": {}}" -lower = "{}[\"value\"]" - -[bindings.swift.custom_types.CustomType2] -# Use `Dictionary` as our custom type wrapper, since we can use it without having to import any -# types -type_name = "Dictionary" -lift = "[\"value\": {}]" -lower = "{}[\"value\"]!" - -# -# Rename configuration -# -[bindings.kotlin.rename] -# Rename a function and its args. -binding_function_to_rename = "ktFunction" -"binding_function_to_rename.record" = "ktRecord" - -# Rename a record and its items. -BindingRecordToRename = "KtRecord" -"BindingRecordToRename.item" = "ktItem" - -# Enum -BindingEnumToRename = "KtEnum" -"BindingEnumToRename.VariantA" = "KtVariantA" -"BindingEnumToRename.Record" = "KtRecord" - -BindingEnumWithFieldsToRename = "KtEnumWithFields" -"BindingEnumWithFieldsToRename.VariantA" = "KtVariantA" -"BindingEnumWithFieldsToRename.VariantA.binding_int" = "kt_int" - -# New error name still gets passed through normal Error->Exception processing. -BindingErrorToRename = "KtError" -"BindingErrorToRename.Simple" = "KtSimple" - -BindingTraitToRename = "KtTrait" -"BindingTraitToRename.trait_method" = "ktTraitMethod" - -BindingObjectToRename = "KtObject" -# Note "kt_method" vs "ktTraitMethod" above - equiv as we always do the case-change thing. -# Is this good or bad? :) Either way, is what actually happens -"BindingObjectToRename.method" = "kt_method" -"BindingObjectToRename.method.arg" = "ktArg" - -[bindings.python.rename] -binding_function_to_rename = "py_function" -"binding_function_to_rename.record" = "py_record" - -BindingRecordToRename = "PyRecord" -"BindingRecordToRename.item" = "py_item" - -BindingEnumToRename = "PyEnum" -"BindingEnumToRename.VariantA" = "PyVariantA" -"BindingEnumToRename.Record" = "PyRecord" - -BindingEnumWithFieldsToRename = "PyEnumWithFields" -"BindingEnumWithFieldsToRename.VariantA" = "PyVariantA" -"BindingEnumWithFieldsToRename.VariantA.binding_int" = "py_int" -"BindingEnumWithFieldsToRename.Record" = "PyRecord" -"BindingEnumWithFieldsToRename.Record.binding_record" = "py_record" -"BindingEnumWithFieldsToRename.Record.binding_int" = "py_int" - -BindingErrorToRename = "PyError" -"BindingErrorToRename.Simple" = "PySimple" - -BindingTraitToRename = "PyTrait" -"BindingTraitToRename.trait_method" = "py_trait_method" - -BindingObjectToRename = "PyObject" -"BindingObjectToRename.new.value" = "py_value" - -"BindingObjectToRename.method" = "py_method" -"BindingObjectToRename.method.arg" = "py_arg" - -[bindings.swift.rename] -# Rename a function and its args. -binding_function_to_rename = "swiftFunction" -"binding_function_to_rename.record" = "swiftRecord" - -# Rename a record and its items. -BindingRecordToRename = "SwiftRecord" -"BindingRecordToRename.item" = "swiftItem" - -# Enum -BindingEnumToRename = "SwiftEnum" -"BindingEnumToRename.VariantA" = "SwiftVariantA" -"BindingEnumToRename.Record" = "SwiftRecord" - -BindingEnumWithFieldsToRename = "SwiftEnumWithFields" -"BindingEnumWithFieldsToRename.VariantA" = "SwiftVariantA" -"BindingEnumWithFieldsToRename.VariantA.binding_int" = "swift_int" - -# New error name still gets passed through normal Error->Exception processing. -BindingErrorToRename = "SwiftError" -"BindingErrorToRename.Simple" = "SwiftSimple" - -BindingTraitToRename = "SwiftTrait" -"BindingTraitToRename.trait_method" = "swiftTraitMethod" - -BindingObjectToRename = "SwiftObject" -# Swift method and arg renaming -"BindingObjectToRename.method" = "swift_method" -"BindingObjectToRename.method.arg" = "swiftArg" diff --git a/uniffi/bindgen-tests/python/Cargo.toml b/uniffi/bindgen-tests/python/Cargo.toml deleted file mode 100644 index 6ae2a40e1..000000000 --- a/uniffi/bindgen-tests/python/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "uniffi-bindgen-tests-python" -version = "0.31.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["cdylib"] - -[dependencies] -camino = "1" -glob = "0.3" -uniffi = { path = "../../uniffi", features = ["bindgen"] } -uniffi-bindgen-tests = { path = "../lib" } diff --git a/uniffi/bindgen-tests/python/src/lib.rs b/uniffi/bindgen-tests/python/src/lib.rs deleted file mode 100644 index adecdfeda..000000000 --- a/uniffi/bindgen-tests/python/src/lib.rs +++ /dev/null @@ -1,164 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -extern crate uniffi_bindgen_tests; - -#[cfg(test)] -mod test { - use std::{ - env::{self}, - ffi::OsString, - fs, - io::Write, - process::Command, - sync::OnceLock, - }; - - use camino::{Utf8Path, Utf8PathBuf}; - - use uniffi::TargetLanguage; - use uniffi_bindgen_tests::test_util; - - #[test] - fn test_simple_fns() { - run_tests(test_dir(), "tests/simple_fns.py"); - } - - #[test] - fn test_primitive_types() { - run_tests(test_dir(), "tests/primitive_types.py"); - } - - #[test] - fn test_records() { - run_tests(test_dir(), "tests/records.py"); - } - - #[test] - fn test_collections() { - run_tests(test_dir(), "tests/collections_test.py"); - } - - #[test] - fn test_options() { - run_tests(test_dir(), "tests/options.py"); - } - - #[test] - fn test_enums() { - run_tests(test_dir(), "tests/enums.py"); - } - - #[test] - fn test_interfaces() { - run_tests(test_dir(), "tests/interfaces.py"); - } - - #[test] - fn test_errors() { - run_tests(test_dir(), "tests/errors.py"); - } - - #[test] - fn test_callback_interfaces() { - run_tests(test_dir(), "tests/callback_interfaces.py"); - } - - #[test] - fn test_futures() { - run_tests(test_dir(), "tests/futures.py"); - } - - #[test] - fn test_trait_interfaces() { - run_tests(test_dir(), "tests/trait_interfaces.py"); - } - - #[test] - fn test_defaults() { - run_tests(test_dir(), "tests/defaults.py"); - } - - #[test] - fn test_references() { - run_tests(test_dir(), "tests/references.py"); - } - - #[test] - fn test_custom_types() { - run_tests(test_dir(), "tests/custom_types.py"); - } - - #[test] - fn test_external_types() { - run_tests(test_dir(), "tests/external_types.py"); - } - - #[test] - fn test_renames() { - run_tests(test_dir(), "tests/renames.py"); - } - - #[test] - fn test_bytes() { - run_tests(test_dir(), "tests/bytes.py"); - } - - #[test] - fn test_recursive_types() { - run_tests(test_dir(), "tests/recursive_types.py"); - } - - #[test] - fn test_time() { - run_tests(test_dir(), "tests/time.py"); - } - - #[test] - fn test_rust_traits() { - run_tests(test_dir(), "tests/rust_traits.py"); - } - - fn test_dir() -> &'static Utf8Path { - static TEST_TEMPDIR: OnceLock = OnceLock::new(); - TEST_TEMPDIR.get_or_init(|| { - let temp_dir = test_util::setup_test_dir("python"); - let test_package = temp_dir.join("tests/test_package"); - fs::create_dir_all(&test_package).unwrap(); - let mut f = fs::File::create(test_package.join("__init__.py")).unwrap(); - write!(f, "").unwrap(); - test_util::build_library(&test_package); - test_util::copy_test_sources(&temp_dir, "tests/*.py"); - test_util::generate_sources(&test_package, TargetLanguage::Python); - - temp_dir - }) - } - - fn run_tests(tempdir: &Utf8Path, script_filename: &str) { - // Run the test script against compiled bindings - let pythonpath = env::var_os("PYTHONPATH").unwrap_or_else(|| OsString::from("")); - let pythonpath = env::join_paths( - env::split_paths(&pythonpath).chain(vec![tempdir.to_path_buf().into_std_path_buf()]), - ) - .unwrap(); - let mut command = Command::new("python3"); - command - .current_dir(tempdir) - .env("PYTHONPATH", pythonpath) - .arg(script_filename); - let output = command - .output() - .expect("Failed to spawn `python3` when running test script"); - // The `output()` call above sets up pipes to print stdout/stderr. This allows it to be - // integrated with the Rust test harness's output handling. - print!("{}", String::from_utf8_lossy(&output.stdout)); - if !output.status.success() { - println!("---------------------------------------- STDERR ----------------------------------------"); - print!("{}", String::from_utf8_lossy(&output.stderr)); - println!("----------------------------------------------------------------------------------------"); - panic!("running `python` to run test script failed ({:?})", command); - } - } -} diff --git a/uniffi/bindgen-tests/python/tests/bytes.py b/uniffi/bindgen-tests/python/tests/bytes.py deleted file mode 100644 index 72190cb64..000000000 --- a/uniffi/bindgen-tests/python/tests/bytes.py +++ /dev/null @@ -1,18 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest -from datetime import datetime, timedelta, timezone - -class TestTime(unittest.TestCase): - def test_bytes(self): - self.assertEqual(roundtrip_bytes(b'test-data'), b'test-data') - - def test_zero_copy_bytes(self): - # Zero-copy &[u8] — proc-macro path - self.assertEqual(sum_bytes_procmacro(b""), 0) - self.assertEqual(sum_bytes_procmacro(b"\x01\x02\x03"), 6) - self.assertIsNone(first_byte_procmacro(b"")) - self.assertEqual(first_byte_procmacro(b"\x2a"), 42) - -if __name__ == '__main__': - unittest.main() - diff --git a/uniffi/bindgen-tests/python/tests/callback_interfaces.py b/uniffi/bindgen-tests/python/tests/callback_interfaces.py deleted file mode 100644 index 0aea29b12..000000000 --- a/uniffi/bindgen-tests/python/tests/callback_interfaces.py +++ /dev/null @@ -1,48 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class CallbackImpl(TestCallbackInterface): - callback_ref_count = 0 - - def __init__(self, value): - self.value = value - CallbackImpl.callback_ref_count += 1 - - def __del__(self): - CallbackImpl.callback_ref_count -= 1 - - def noop(self): - pass - - def get_value(self): - return self.value - - def set_value(self, value): - self.value = value - - def throw_if_equal(self, numbers): - if numbers.a == numbers.b: - raise TestError.Failure1() - return numbers - - def echo(self, s): - return s - -class TestCallbackInterfaces(unittest.TestCase): - def test_callback_interfaces(self): - # Construct a callback interface to pass to rust - cbi = CallbackImpl(42) - # Test calling callback interface methods, which we can only do indirectly. - # Each of these Rust functions inputs a callback interface, calls a method on it, then returns the result. - invoke_test_callback_interface_noop(cbi) - assert(invoke_test_callback_interface_get_value(cbi) == 42) - invoke_test_callback_interface_set_value(cbi, 43) - assert(invoke_test_callback_interface_get_value(cbi) == 43) - assert(invoke_test_callback_interface_echo(cbi, "test-string") == "test-string") - - # The previous calls created a bunch of callback interface references. Make sure they've been cleaned - # up and the only remaining reference is for our `cbi` variable. - assert(CallbackImpl.callback_ref_count == 1) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/collections_test.py b/uniffi/bindgen-tests/python/tests/collections_test.py deleted file mode 100644 index 224e49778..000000000 --- a/uniffi/bindgen-tests/python/tests/collections_test.py +++ /dev/null @@ -1,63 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestCollections(unittest.TestCase): - def test_vecs(self): - self.assertEqual(roundtrip_vec_i8([1, 2, 3]), [1, 2, 3]) - self.assertEqual(roundtrip_vec_u16([1, 2, 3]), [1, 2, 3]) - self.assertEqual(roundtrip_vec_i16([1, 2, 3]), [1, 2, 3]) - self.assertEqual(roundtrip_vec_u32([1, 2, 3]), [1, 2, 3]) - self.assertEqual(roundtrip_vec_i32([1, 2, 3]), [1, 2, 3]) - self.assertEqual(roundtrip_vec_u64([1, 2, 3]), [1, 2, 3]) - self.assertEqual(roundtrip_vec_i64([1, 2, 3]), [1, 2, 3]) - self.assertEqual(roundtrip_vec_string(["test-string"]), ["test-string"]) - self.assertEqual(roundtrip_vec_bool([True, False]), [True, False]) - self.assertEqual(roundtrip_vec_rec([CollectionsRec(a=67)]), [CollectionsRec(a=67)]) - - def test_hash_maps(self): - self.assertEqual(roundtrip_hash_map({ "a": 1, "b": 2 }), { "a": 1, "b": 2 }) - self.assertEqual(roundtrip_hash_set({"a", "b", "c"}), {"a", "b", "c"}) - self.assertEqual(roundtrip_hash_map_u32_key({ 1: 2, 2: 4 }), { 1: 2, 2: 4}) - - def test_rec_with_collections(self): - self.assertEqual( - roundtrip_rec_with_collections( - RecWithCollections( - a=EnumWithCollections.A(None), - b=None, - c=[True, False], - d={ - "a": 10, - "b": 20, - }, - ), - ), - RecWithCollections( - a=EnumWithCollections.A(None), - b=None, - c=[True, False], - d={ - "a": 10, - "b": 20, - }, - ), - ) - - def test_complex(self): - self.assertEqual(roundtrip_vec_hash_set([{"a", "b"}]), [{"a", "b"}]) - self.assertEqual(roundtrip_vec_hash_set(None), None) - self.assertEqual(roundtrip_complex_collection_type([ - { - "a": CollectionsComplexRec(a=10, b="Test", c=CollectionsEnum.A(100)), - "b": CollectionsComplexRec(a=20, b="Test2", c=CollectionsEnum.B(a=1.0, b=True)), - } - ]), [ - { - "a": CollectionsComplexRec(a=10, b="Test", c=CollectionsEnum.A(100)), - "b": CollectionsComplexRec(a=20, b="Test2", c=CollectionsEnum.B(a=1.0, b=True)), - } - ]) - self.assertEqual(roundtrip_complex_collection_type(None), None) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/custom_types.py b/uniffi/bindgen-tests/python/tests/custom_types.py deleted file mode 100644 index f84199b9b..000000000 --- a/uniffi/bindgen-tests/python/tests/custom_types.py +++ /dev/null @@ -1,13 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestCustomTypes(unittest.TestCase): - def test_custom_type(self): - assert(roundtrip_custom_type1(100) == 100) - - def test_custom_type_with_config(self): - assert(roundtrip_custom_type2({ "value": 200 }) == { "value": 200 }) - - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/defaults.py b/uniffi/bindgen-tests/python/tests/defaults.py deleted file mode 100644 index 7b59b5259..000000000 --- a/uniffi/bindgen-tests/python/tests/defaults.py +++ /dev/null @@ -1,23 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestDefaults(unittest.TestCase): - def test_records(self): - r = RecWithDefault() - self.assertEqual(r.n, 42) - self.assertEqual(r.v, []) - - def test_enums(self): - e = EnumWithDefault.OTHER_VARIANT() - self.assertEqual(e.a, "default") - - def test_arguments(self): - self.assertEqual(func_with_default(), "DEFAULT") - self.assertEqual(func_with_default("NON-DEFAULT"), "NON-DEFAULT") - - i = InterfaceWithDefaults() - self.assertEqual(i.method_with_default(), "DEFAULT") - self.assertEqual(i.method_with_default("NON-DEFAULT"), "NON-DEFAULT") - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/enums.py b/uniffi/bindgen-tests/python/tests/enums.py deleted file mode 100644 index 8be08b5a0..000000000 --- a/uniffi/bindgen-tests/python/tests/enums.py +++ /dev/null @@ -1,56 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestEnums(unittest.TestCase): - def test_simple_enums(self): - self.assertEqual( - roundtrip_enum_with_data(EnumWithData.A(10, 20)), - EnumWithData.A(10, 20)) - self.assertEqual( - roundtrip_enum_with_data(EnumWithData.B("Ten", 10)), - EnumWithData.B("Ten", 10)) - self.assertEqual( - roundtrip_enum_with_data(EnumWithData.C()) , - EnumWithData.C()) - - def test_enum_fields(self): - a = EnumWithData.A(10, 20) - self.assertEqual(a.value, 10) - self.assertEqual(a.value2, 20) - - b = EnumWithData.B("Ten", 10) - self.assertEqual(b[0], "Ten") - self.assertEqual(b[1], 10) - - def test_complex_enums(self): - self.assertEqual( - roundtrip_complex_enum(ComplexEnum.A(EnumNoData.C)), - ComplexEnum.A(EnumNoData.C)) - self.assertEqual( - roundtrip_complex_enum(ComplexEnum.B(EnumWithData.A(20, 40))), - ComplexEnum.B(EnumWithData.A(20, 40))) - self.assertEqual( - roundtrip_complex_enum(ComplexEnum.C(SimpleRec(a=30))), - ComplexEnum.C(SimpleRec(a=30))) - - def test_discriminents(self): - # Test that the enum discriminant values - - # All discriminants specified, use the specified values - self.assertEqual(ExplicitValuedEnum.FIRST.value, 1) - self.assertEqual(ExplicitValuedEnum.SECOND.value, 2) - self.assertEqual(ExplicitValuedEnum.FOURTH.value, 4) - self.assertEqual(ExplicitValuedEnum.TENTH.value, 10) - self.assertEqual(ExplicitValuedEnum.ELEVENTH.value, 11) - self.assertEqual(ExplicitValuedEnum.THIRTEENTH.value, 13) - - # Some discriminants specified, increment by one for any unspecified variants - self.assertEqual(GappedEnum.ONE.value, 10) - self.assertEqual(GappedEnum.TWO.value, 11) # Sequential value after ONE (10+1) - self.assertEqual(GappedEnum.THREE.value, 14) # Explicit value again - - def test_methods(self): - self.assertEqual(EnumWithData.A(1, 0).roundtrip(), EnumWithData.A(1, 0)) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/errors.py b/uniffi/bindgen-tests/python/tests/errors.py deleted file mode 100644 index 025c65e73..000000000 --- a/uniffi/bindgen-tests/python/tests/errors.py +++ /dev/null @@ -1,38 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestErrors(unittest.TestCase): - def test_rust_error_returns(self): - with self.assertRaises(TestError.Failure1): - func_with_error(0) - - with self.assertRaises(TestError.Failure2) as cm: - func_with_error(1) - self.assertEqual(cm.exception.data, "DATA") - - with self.assertRaises(TestError.Failure3) as cm: - func_with_error(50) - self.assertEqual(cm.exception[0], 50) - - with self.assertRaises(TestFlatError.IoError): - func_with_flat_error(0) - - # These shouldn't throw - func_with_error(200) - func_with_flat_error(1) - - def test_rust_error_no_data_returns(self): - with self.assertRaises(TestErrorNoData.Failure1): - func_with_error_no_data(0) - - with self.assertRaises(TestErrorNoData.Failure2): - func_with_error_no_data(1) - - with self.assertRaises(TestErrorNoData.Failure3): - func_with_error_no_data(2) - - # This shouldn't throw - func_with_error_no_data(200) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/external_types.py b/uniffi/bindgen-tests/python/tests/external_types.py deleted file mode 100644 index d59434c4b..000000000 --- a/uniffi/bindgen-tests/python/tests/external_types.py +++ /dev/null @@ -1,18 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -from test_package.uniffi_bindgen_tests_external_types_source import ( - ExternalRec, ExternalEnum, ExternalInterface) -import unittest - -class TestExternalTypes(unittest.TestCase): - def test_external_types(self): - self.assertEqual(roundtrip_ext_record(ExternalRec(a=42)), ExternalRec(a=42)) - - self.assertEqual(roundtrip_ext_enum( ExternalEnum.TWO), ExternalEnum.TWO) - - interface = ExternalInterface(20) - self.assertEqual(roundtrip_ext_interface(interface).get_value(), 20) - - self.assertEqual(roundtrip_ext_custom_type(100), 100) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/futures.py b/uniffi/bindgen-tests/python/tests/futures.py deleted file mode 100644 index c5f3b665a..000000000 --- a/uniffi/bindgen-tests/python/tests/futures.py +++ /dev/null @@ -1,89 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestFutures(unittest.IsolatedAsyncioTestCase): - async def test_simple_calls(self): - self.assertEqual(await async_roundtrip_u8(42), 42) - self.assertEqual(await async_roundtrip_i8(-42), -42) - self.assertEqual(await async_roundtrip_u16(42), 42) - self.assertEqual(await async_roundtrip_i16(-42), -42) - self.assertEqual(await async_roundtrip_u32(42), 42) - self.assertEqual(await async_roundtrip_i32(-42), -42) - self.assertEqual(await async_roundtrip_u64(42), 42) - self.assertEqual(await async_roundtrip_i64(-42), -42) - self.assertEqual(await async_roundtrip_f32(0.5), 0.5) - self.assertEqual(await async_roundtrip_f64(-0.5), -0.5) - self.assertEqual(await async_roundtrip_string("hi"), "hi") - self.assertEqual(await async_roundtrip_vec([42]), [42]) - self.assertEqual(await async_roundtrip_map({ "hello": "world" }), { "hello": "world" }) - - async def test_errors(self): - with self.assertRaises(TestError.Failure1): - await async_throw_error() - - async def test_methods(self): - obj = AsyncInterface("Alice") - self.assertEqual(await obj.name(), "Alice") - - obj2 = await async_roundtrip_obj(obj) - self.assertEqual(await obj2.name(), "Alice") - - rec = AsyncRecord(name="Bob") - assert(await rec.get_name() == "Bob") - - async def test_async_callback_interfaces(self): - class AsyncCallbackImpl: - ref_count = 0 - - def __init__(self, value): - self.value = value - AsyncCallbackImpl.ref_count += 1 - - def __del__(self): - AsyncCallbackImpl.ref_count -= 1 - - async def noop(self): - pass - - async def get_value(self): - return self.value - - async def set_value(self, value): - self.value = value - - async def throw_if_equal(self, numbers): - if numbers.a == numbers.b: - raise TestError.Failure1() - return numbers - - cbi = AsyncCallbackImpl(42) - await invoke_test_async_callback_interface_noop(cbi) - - self.assertEqual( - await invoke_test_async_callback_interface_get_value(cbi), - 42, - ) - - await invoke_test_async_callback_interface_set_value(cbi, 43) - self.assertEqual(await invoke_test_async_callback_interface_get_value(cbi), 43) - - with self.assertRaises(TestError.Failure1): - await invoke_test_async_callback_interface_throw_if_equal( - cbi, - CallbackInterfaceNumbers(a=10, b=10) - ) - - self.assertEqual( - await invoke_test_async_callback_interface_throw_if_equal( - cbi, - CallbackInterfaceNumbers(a=10, b=11) - ), - CallbackInterfaceNumbers(a=10, b=11) - ) - - # The previcalls created a bunch of callback interface references. Make sure they've been cleaned - # up and the only remaining reference is for our `cbi` variable. - self.assertEqual(AsyncCallbackImpl.ref_count, 1) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/interfaces.py b/uniffi/bindgen-tests/python/tests/interfaces.py deleted file mode 100644 index ba4f3c800..000000000 --- a/uniffi/bindgen-tests/python/tests/interfaces.py +++ /dev/null @@ -1,46 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestErrors(unittest.TestCase): - def test_interfaces(self): - interface = TestInterface(20) - self.assertEqual(interface.get_value(), 20) - self.assertEqual(clone_interface(interface).get_value(), 20) - - def test_optional_interface(self): - self.assertEqual(roundtrip_optional_interface(None), None) - interface = TestInterface(20) - self.assertEqual(roundtrip_optional_interface(interface).get_value(), 20) - - def test_secondary_constructor(self): - interface = TestInterface.secondary_constructor(20) - self.assertEqual(interface.get_value(), 40) - - def test_records_with_interface_fields(self): - two = TwoTestInterfaces(first=TestInterface(1), second=TestInterface(2)) - swapped = swap_test_interfaces(two) - self.assertEqual(swapped.first.get_value(), 2) - self.assertEqual(swapped.second.get_value(), 1) - - def test_enums_with_interfaces(self): - en = TestInterfaceEnum.ONE(TestInterface(1)) - self.assertEqual(en.i.get_value(), 1) - - def test_interface_refcounts(self): - interface = TestInterface(20) - interface2 = TestInterface(20) - def func_that_clones_interface(interface): - return clone_interface(interface) - - interface2_clone = func_that_clones_interface(clone_interface(interface)) - _ = interface.get_value() - # Check that only the 2 actual references remain after the dust clears - self.assertEqual(interface.ref_count(), 2) - - def test_argument_name_mapping(self): - interface = TestInterface(20) - # the following calls will fail if the argument name differs - interface.method_with_multi_word_arg(the_argument="test") - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/options.py b/uniffi/bindgen-tests/python/tests/options.py deleted file mode 100644 index 5f3b5d830..000000000 --- a/uniffi/bindgen-tests/python/tests/options.py +++ /dev/null @@ -1,30 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestOptions(unittest.TestCase): - def test_options(self): - self.assertEqual(roundtrip_option_u8(67), 67) - self.assertEqual(roundtrip_option_u8(None), None) - self.assertEqual(roundtrip_option_i8(67), 67) - self.assertEqual(roundtrip_option_i8(None), None) - self.assertEqual(roundtrip_option_u16(67), 67) - self.assertEqual(roundtrip_option_u16(None), None) - self.assertEqual(roundtrip_option_i16(67), 67) - self.assertEqual(roundtrip_option_i16(None), None) - self.assertEqual(roundtrip_option_u32(67), 67) - self.assertEqual(roundtrip_option_u32(None), None) - self.assertEqual(roundtrip_option_i32(67), 67) - self.assertEqual(roundtrip_option_i32(None), None) - self.assertEqual(roundtrip_option_u64(67), 67) - self.assertEqual(roundtrip_option_u64(None), None) - self.assertEqual(roundtrip_option_i64(67), 67) - self.assertEqual(roundtrip_option_i64(None), None) - self.assertEqual(roundtrip_option_string("test-string"), "test-string") - self.assertEqual(roundtrip_option_string(None), None) - self.assertEqual(roundtrip_option_bool(True), True) - self.assertEqual(roundtrip_option_bool(None), None) - self.assertEqual(roundtrip_option_rec(OptionsRec(a=67)), OptionsRec(a=67)) - self.assertEqual(roundtrip_option_rec(None), None) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/primitive_types.py b/uniffi/bindgen-tests/python/tests/primitive_types.py deleted file mode 100644 index 02e752cb6..000000000 --- a/uniffi/bindgen-tests/python/tests/primitive_types.py +++ /dev/null @@ -1,55 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestPrimitiveTypes(unittest.TestCase): - def test_input(self): - input_u8(42) - input_i8(-42) - input_u16(42) - input_i16(-42) - input_u32(42) - input_i32(-42) - input_u64(42) - input_i64(-42) - input_f32(0.5) - input_f64(-3.5) - input_bool(True) - input_string("ABC") - - def test_output(self): - self.assertEqual(output_u8(), 1) - self.assertEqual(output_i8(), 1) - self.assertEqual(output_u16(), 1) - self.assertEqual(output_i16(), 1) - self.assertEqual(output_u32(), 1) - self.assertEqual(output_i32(), 1) - self.assertEqual(output_u64(), 1) - self.assertEqual(output_i64(), 1) - self.assertEqual(output_f32(), 1.0) - self.assertEqual(output_f64(), 1.0) - self.assertEqual(output_bool(), True) - self.assertEqual(output_string(), "test-string") - - def test_roundtrip(self): - self.assertEqual(roundtrip_u8(42), 42) - self.assertEqual(roundtrip_i8(-42), -42) - self.assertEqual(roundtrip_u16(42), 42) - self.assertEqual(roundtrip_i16(-42), -42) - self.assertEqual(roundtrip_u32(42), 42) - self.assertEqual(roundtrip_i32(-42), -42) - self.assertEqual(roundtrip_u64(42), 42) - self.assertEqual(roundtrip_i64(-42), -42) - self.assertEqual(roundtrip_f32(0.5), 0.5) - self.assertEqual(roundtrip_f64(-3.5), -3.5) - self.assertEqual(roundtrip_bool(True), True) - self.assertEqual(roundtrip_string("ABC"), "ABC") - # Test calling a function with lots of args - # This function will sum up all the numbers, then negate the value since we passed in `true` - self.assertEqual(sum_with_many_types(1, -2, 3, -4, 5, -6, 7, -8, 9.5, -10.5, True), 5) - - def test_argument_name_mapping(self): - # the following calls will fail if the argument name differs - func_with_multi_word_arg(the_argument=16) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/records.py b/uniffi/bindgen-tests/python/tests/records.py deleted file mode 100644 index fd129a699..000000000 --- a/uniffi/bindgen-tests/python/tests/records.py +++ /dev/null @@ -1,48 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestRecords(unittest.TestCase): - def test_simple_record(self): - self.assertEqual(roundtrip_simple_rec(SimpleRec(a=42)), SimpleRec(a=42)) - - def test_unit_record(self): - self.assertEqual(UnitRec(), UnitRec()) - - def test_complex_record(self): - self.assertEqual( - roundtrip_complex_rec( - ComplexRec( - field_u8=0, - field_i8=-1, - field_u16=2, - field_i16=-3, - field_u32=4, - field_i32=-5, - field_u64=6, - field_i64=-7, - field_f32=8.5, - field_f64=9.5, - field_string="test", - field_rec=SimpleRec(a=42) - ) - ), ComplexRec( - field_u8=0, - field_i8=-1, - field_u16=2, - field_i16=-3, - field_u32=4, - field_i32=-5, - field_u64=6, - field_i64=-7, - field_f32=8.5, - field_f64=9.5, - field_string="test", - field_rec=SimpleRec(a=42) - ) - ) - - def test_methods(self): - self.assertEqual(SimpleRec(a=42).roundtrip(), SimpleRec(a=42)) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/recursive_types.py b/uniffi/bindgen-tests/python/tests/recursive_types.py deleted file mode 100644 index b4ca74389..000000000 --- a/uniffi/bindgen-tests/python/tests/recursive_types.py +++ /dev/null @@ -1,89 +0,0 @@ -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -from test_package.uniffi_bindgen_tests import * - -# --- Tree (self-recursive) --- - -# Leaf -assert sum_tree(Tree.LEAF(5)) == 5 - -# Node with two leaves -tree = Tree.NODE(left=Tree.LEAF(3), right=Tree.LEAF(4)) -assert sum_tree(tree) == 7 - -# Deeper tree -deep = Tree.NODE( - left=Tree.NODE(left=Tree.LEAF(1), right=Tree.LEAF(2)), - right=Tree.LEAF(10), -) -assert sum_tree(deep) == 13 - -# --- Expr / BoolExpr (mutually recursive) --- - -# Simple literal -assert eval_expr(Expr.LIT(42)) == 42 - -# IsZero true branch -# Note: then_ field becomes `then`, else_ becomes `_else` (else is a Python keyword) -expr = Expr.IF( - cond=BoolExpr.IS_ZERO(Expr.LIT(0)), - then=Expr.LIT(1), - _else=Expr.LIT(2), -) -assert eval_expr(expr) == 1 - -# IsZero false branch -expr = Expr.IF( - cond=BoolExpr.IS_ZERO(Expr.LIT(5)), - then=Expr.LIT(1), - _else=Expr.LIT(2), -) -assert eval_expr(expr) == 2 - -# Not -assert eval_bool(BoolExpr.NOT(BoolExpr.TRUE())) == False -assert eval_bool(BoolExpr.NOT(BoolExpr.FALSE())) == True - -# --- LinkedList (cycle through Optional: Cons.tail is Option) --- - -assert list_sum(LinkedList.NIL()) == 0 -assert list_sum(LinkedList.CONS(head=5, tail=None)) == 5 -assert list_sum(LinkedList.CONS(head=3, tail=LinkedList.CONS(head=4, tail=None))) == 7 - -# --- Trie (cycle through Map value: Branch.children is HashMap) --- - -assert trie_sum(Trie.LEAF(5)) == 5 -assert trie_sum(Trie.BRANCH(children={})) == 0 -assert trie_sum(Trie.BRANCH(children={"a": Trie.LEAF(1), "b": Trie.LEAF(2)})) == 3 -assert trie_sum(Trie.BRANCH(children={"x": Trie.BRANCH(children={"y": Trie.LEAF(7)})})) == 7 - -# --- RoseTree (cycle through a record: RoseTree → RoseData → Vec) --- - -assert sum_rose_tree(RoseTree.LEAF(7)) == 7 - -assert sum_rose_tree(RoseTree.BRANCH(RoseData(value=10, children=[]))) == 10 - -assert sum_rose_tree( - RoseTree.BRANCH(RoseData(value=1, children=[RoseTree.LEAF(2), RoseTree.LEAF(3)])) -) == 6 - -assert sum_rose_tree( - RoseTree.BRANCH(RoseData( - value=1, - children=[ - RoseTree.BRANCH(RoseData(value=2, children=[RoseTree.LEAF(3)])), - RoseTree.LEAF(4), - ], - )) -) == 10 - -# EvalError (recursive error enum: Nested wraps another EvalError) -assert maybe_throw_error(False) == 42 - -try: - maybe_throw_error(True) - assert False, "expected EvalError to be raised" -except EvalError: - pass # recursive error enum compiles and is throwable diff --git a/uniffi/bindgen-tests/python/tests/references.py b/uniffi/bindgen-tests/python/tests/references.py deleted file mode 100644 index b106c3c1f..000000000 --- a/uniffi/bindgen-tests/python/tests/references.py +++ /dev/null @@ -1,19 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestReferences(unittest.TestCase): - def test_value_ref(self): - self.assertEqual(roundtrip_u8_ref(2), 2) - - def test_interface_ref(self): - interface = ReferenceTestInterface() - self.assertEqual(interface.double_value(2), 4) - self.assertEqual(call_double_value(interface, 3), 6) - - def test_trait_interface_ref(self): - trait_interface = create_reference_test_trait_interface() - self.assertEqual(call_triple_value_trait_interface(trait_interface, 10), 30) - -if __name__ == '__main__': - unittest.main() - diff --git a/uniffi/bindgen-tests/python/tests/renames.py b/uniffi/bindgen-tests/python/tests/renames.py deleted file mode 100644 index 4efa28051..000000000 --- a/uniffi/bindgen-tests/python/tests/renames.py +++ /dev/null @@ -1,53 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestRenames(unittest.TestCase): - def test_rename_record(self): - rec = RenamedRecord(item=42) - self.assertEqual(rec.item, 42) - - def test_rename_enum(self): - rec = RenamedRecord(item=42) - enum1 = RenamedEnum.RENAMED_VARIANT - enum2 = RenamedEnum.RECORD(rec) - return_value = renamed_function(rec) - self.assertIsInstance(return_value, RenamedEnum.RECORD) - self.assertEqual(return_value[0], rec) - - def test_rename_obj(self): - obj = RenamedObject.renamed_constructor(123) - self.assertEqual(obj.renamed_method(), 123) - - def test_trait_method(self): - trait_impl = create_trait_impl(5) - self.assertEqual(trait_impl.renamed_trait_method(10), 50) - - def test_py_rename_record(self): - rec = PyRecord(py_item=100) - self.assertEqual(rec.py_item, 100) - - def test_py_rename_enum(self): - rec = PyRecord(py_item=100) - PyEnum.PY_VARIANT_A() - PyEnum.PY_RECORD(rec) - PyEnumWithFields.PY_VARIANT_A(1) - - def test_py_rename_functions(self): - rec = PyRecord(py_item=100) - return_value = py_function(rec) - self.assertIsInstance(return_value, PyEnum.PY_RECORD) - self.assertEqual(return_value[0], rec) - - with self.assertRaises(PyError.PySimple): - py_function(None) - - def test_py_rename_methods(self): - obj = PyObject(200) - self.assertEqual(obj.py_method(50), 250) - - def test_py_rename_trait(self): - trait_impl = create_binding_trait_to_rename_impl(3) - self.assertEqual(trait_impl.py_trait_method(7), 21) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/rust_traits.py b/uniffi/bindgen-tests/python/tests/rust_traits.py deleted file mode 100644 index bb80d1970..000000000 --- a/uniffi/bindgen-tests/python/tests/rust_traits.py +++ /dev/null @@ -1,33 +0,0 @@ -import unittest -from test_package.uniffi_bindgen_tests import * - -class TestRustTraits(unittest.TestCase): - def test_debug(self): - trait_test = RustTraitTest(a=1, b=2) - self.assertEqual(repr(trait_test), "debug-test-string") - - def test_display(self): - trait_test = RustTraitTest(a=1, b=2) - self.assertEqual(str(trait_test), "display-test-string") - - def test_eq(self): - # The Rust code only uses `a` for the equality - self.assertEqual(RustTraitTest(a=1, b=2), RustTraitTest(a=1, b=3)) - self.assertNotEqual(RustTraitTest(a=2, b=2), RustTraitTest(a=1, b=2)) - - def test_ord(self): - # The Rust code only uses `a` for the ordering - self.assertTrue(RustTraitTest(a=1, b=2) < RustTraitTest(a=2, b=3)) - self.assertTrue( - (RustTraitTest(a=1, b=2) <= RustTraitTest(a=1, b=3)) - and (RustTraitTest(a=1, b=2) >= RustTraitTest(a=1, b=3)) - ) - - def test_hash(self): - # The Rust code only uses `a` for the hash - self.assertEqual(hash(RustTraitTest(a=1, b=2)), hash(RustTraitTest(a=1, b=3))) - self.assertNotEqual(hash(RustTraitTest(a=2, b=2)), hash(RustTraitTest(a=1, b=2))) - -if __name__ == '__main__': - unittest.main() - diff --git a/uniffi/bindgen-tests/python/tests/simple_fns.py b/uniffi/bindgen-tests/python/tests/simple_fns.py deleted file mode 100644 index 076b21a07..000000000 --- a/uniffi/bindgen-tests/python/tests/simple_fns.py +++ /dev/null @@ -1,14 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - -class TestSimpleFns(unittest.TestCase): - def test_simple_function(self): - # the test here is just that we can successfully call a function across the FFI - test_func() - - def test_unexpected_error(self): - with self.assertRaises(InternalError): - test_unexpected_error_func() - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/python/tests/time.py b/uniffi/bindgen-tests/python/tests/time.py deleted file mode 100644 index 6e47a88df..000000000 --- a/uniffi/bindgen-tests/python/tests/time.py +++ /dev/null @@ -1,20 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest -from datetime import datetime, timedelta, timezone - -class TestTime(unittest.TestCase): - def test_duration(self): - self.assertEqual( - roundtrip_duration(timedelta(days=1, seconds=2)), - timedelta(days=1, seconds=2), - ) - - def test_systemtime(self): - self.assertEqual( - roundtrip_systemtime(datetime(2000, 1, 1, tzinfo=timezone.utc)), - datetime(2000, 1, 1, tzinfo=timezone.utc) - ) - -if __name__ == '__main__': - unittest.main() - diff --git a/uniffi/bindgen-tests/python/tests/trait_interfaces.py b/uniffi/bindgen-tests/python/tests/trait_interfaces.py deleted file mode 100644 index a9c761fd2..000000000 --- a/uniffi/bindgen-tests/python/tests/trait_interfaces.py +++ /dev/null @@ -1,226 +0,0 @@ -from test_package.uniffi_bindgen_tests import * -import unittest - - -class TraitImpl(TestTraitInterface): - ref_count = 0 - - def __init__(self, value): - self.value = value - TraitImpl.ref_count += 1 - - def __del__(self): - TraitImpl.ref_count -= 1 - - def noop(self): - pass - - def get_value(self): - return self.value - - def set_value(self, value): - self.value = value - - def throw_if_equal(self, numbers): - if numbers.a == numbers.b: - raise TestError.Failure1() - return numbers - - def roundtrip_record(self, value): - return value - - def roundtrip_enum(self, value): - return value - - def roundtrip_interface(self, value): - return value - -class TestTraitInterfaces(unittest.TestCase): - def check_rust_impl(self, rust_trait_impl): - rust_trait_impl.noop() - self.assertEqual(rust_trait_impl.get_value(), 42) - rust_trait_impl.set_value(43) - self.assertEqual(rust_trait_impl.get_value(), 43) - with self.assertRaises(TestError.Failure1): - rust_trait_impl.throw_if_equal(CallbackInterfaceNumbers(a=10, b=10)) - self.assertEqual( - rust_trait_impl.throw_if_equal(CallbackInterfaceNumbers(a=10, b=11)), - CallbackInterfaceNumbers(a=10, b=11)) - self.assertEqual(rust_trait_impl.roundtrip_record(SimpleRec(a=10)), SimpleRec(a=10)) - self.assertEqual( - rust_trait_impl.roundtrip_enum(EnumWithData.A(10, 20)), - EnumWithData.A(10, 20)) - self.assertEqual(rust_trait_impl.roundtrip_interface(TestInterface(20)).get_value(), 20) - - def check_py_impl(self, py_trait_impl): - invoke_test_trait_interface_noop(py_trait_impl) - self.assertEqual(invoke_test_trait_interface_get_value(py_trait_impl), 42) - invoke_test_trait_interface_set_value(py_trait_impl, 43) - self.assertEqual(invoke_test_trait_interface_get_value(py_trait_impl), 43) - with self.assertRaises(TestError.Failure1): - invoke_test_trait_interface_throw_if_equal( - py_trait_impl, - CallbackInterfaceNumbers(a=10, b=10) - ) - - self.assertEqual( - invoke_test_trait_interface_throw_if_equal( - py_trait_impl, - CallbackInterfaceNumbers(a=10, b=11) - ), - CallbackInterfaceNumbers(a=10, b=11) - ) - self.assertEqual( - invoke_test_trait_interface_roundtrip_record(py_trait_impl, SimpleRec(a=10)), - SimpleRec(a=10)) - self.assertEqual( - invoke_test_trait_interface_roundtrip_enum(py_trait_impl, EnumWithData.A(10, 20)), - EnumWithData.A(10, 20)) - self.assertEqual( - invoke_test_trait_interface_roundtrip_interface(py_trait_impl, TestInterface(20)).get_value(), - 20) - - def test_rust_impl(self): - self.check_rust_impl(create_test_trait_interface(42)) - - def test_rust_impl_roundtripped(self): - impl = roundtrip_test_trait_interface(create_test_trait_interface(42)) - self.check_rust_impl(impl) - - def test_rust_impl_roundtripped_list(self): - impl = roundtrip_test_trait_interface_list([create_test_trait_interface(42)])[0] - self.check_rust_impl(impl) - - def test_py_impl(self): - self.check_py_impl(TraitImpl(42)) - self.assertEqual(TraitImpl.ref_count, 0) - - def test_py_impl_roundtripped(self): - impl = roundtrip_test_trait_interface(TraitImpl(42)) - self.check_py_impl(impl) - del impl - self.assertEqual(TraitImpl.ref_count, 0) - - def test_py_impl_roundtripped_list(self): - impl = roundtrip_test_trait_interface_list([TraitImpl(42)])[0] - self.check_py_impl(impl) - del impl - self.assertEqual(TraitImpl.ref_count, 0) - -class AsyncTraitImpl(AsyncTestTraitInterface): - ref_count = 0 - - def __init__(self, value): - self.value = value - AsyncTraitImpl.ref_count += 1 - - def __del__(self): - AsyncTraitImpl.ref_count -= 1 - - async def noop(self): - pass - - async def get_value(self): - return self.value - - async def set_value(self, value): - self.value = value - - async def throw_if_equal(self, numbers): - if numbers.a == numbers.b: - raise TestError.Failure1() - return numbers - -class TestAsyncTraitInterfaces(unittest.IsolatedAsyncioTestCase): - async def check_async_rust_impl(self, async_rust_trait_impl): - await async_rust_trait_impl.noop() - self.assertEqual(await async_rust_trait_impl.get_value(), 42) - await async_rust_trait_impl.set_value(43) - self.assertEqual(await async_rust_trait_impl.get_value(), 43) - with self.assertRaises(TestError.Failure1): - await async_rust_trait_impl.throw_if_equal(CallbackInterfaceNumbers(a=10, b=10)) - self.assertEqual( - await async_rust_trait_impl.throw_if_equal(CallbackInterfaceNumbers(a=10, b=11)), - CallbackInterfaceNumbers(a=10, b=11)) - - async def check_async_py_impl(self, async_py_trait_impl): - await invoke_async_test_trait_interface_noop(async_py_trait_impl) - self.assertEqual(await invoke_async_test_trait_interface_get_value(async_py_trait_impl), 42) - await invoke_async_test_trait_interface_set_value(async_py_trait_impl, 43) - self.assertEqual(await invoke_async_test_trait_interface_get_value(async_py_trait_impl), 43) - with self.assertRaises(TestError.Failure1): - await invoke_async_test_trait_interface_throw_if_equal( - async_py_trait_impl, - CallbackInterfaceNumbers(a=10, b=10) - ) - - self.assertEqual( - await invoke_async_test_trait_interface_throw_if_equal( - async_py_trait_impl, - CallbackInterfaceNumbers(a=10, b=11) - ), - CallbackInterfaceNumbers(a=10, b=11) - ) - - async def test_async_rust_impl(self): - await self.check_async_rust_impl(create_async_test_trait_interface(42)) - - async def test_async_rust_impl_roundtripped(self): - impl = roundtrip_async_test_trait_interface(create_async_test_trait_interface(42)) - await self.check_async_rust_impl(impl) - - async def test_async_rust_impl_roundtripped_list(self): - impl = roundtrip_async_test_trait_interface_list([create_async_test_trait_interface(42)])[0] - await self.check_async_rust_impl(impl) - - async def test_async_py_impl(self): - await self.check_async_py_impl(AsyncTraitImpl(42)) - self.assertEqual(AsyncTraitImpl.ref_count, 0) - - async def test_async_py_impl_roundtripped(self): - impl = roundtrip_async_test_trait_interface(AsyncTraitImpl(42)) - await self.check_async_py_impl(impl) - del impl - self.assertEqual(AsyncTraitImpl.ref_count, 0) - - async def test_async_py_impl_roundtripped_list(self): - impl = roundtrip_async_test_trait_interface_list([AsyncTraitImpl(42)])[0] - await self.check_async_py_impl(impl) - del impl - self.assertEqual(AsyncTraitImpl.ref_count, 0) - -class TestRustOnlyTraitInterfaces(unittest.TestCase): - def check_rust_only_impl(self, impl): - with self.assertRaises(TestError.Failure1): - impl.throw_if_equal(CallbackInterfaceNumbers(a=10, b=10)) - self.assertEqual( - impl.throw_if_equal(CallbackInterfaceNumbers(a=10, b=11)), - CallbackInterfaceNumbers(a=10, b=11) - ) - - def test_rust_only_impl(self): - self.check_rust_only_impl(create_rust_only_test_trait_interface()) - -class ForeignOnlyImpl(TestForeignOnlyTraitInterface): - def throw_if_equal(self, numbers): - if numbers.a == numbers.b: - raise TestError.Failure1() - return numbers - -class TestForeignOnlyTraitInterfaces(unittest.TestCase): - def check_foreign_only_impl(self, impl): - with self.assertRaises(TestError.Failure1): - invoke_test_foreign_only_trait_throw_if_equal(impl, CallbackInterfaceNumbers(a=10, b=10)) - self.assertEqual( - invoke_test_foreign_only_trait_throw_if_equal(impl, CallbackInterfaceNumbers(a=10, b=11)), - CallbackInterfaceNumbers(a=10, b=11) - ) - - def test_foreign_only_impl(self): - self.check_foreign_only_impl(ForeignOnlyImpl()) - - def test_foreign_only_impl_roundtripped(self): - self.check_foreign_only_impl(roundtrip_test_foreign_only_trait(ForeignOnlyImpl())) - -if __name__ == '__main__': - unittest.main() diff --git a/uniffi/bindgen-tests/swift/Cargo.toml b/uniffi/bindgen-tests/swift/Cargo.toml deleted file mode 100644 index 21af3f412..000000000 --- a/uniffi/bindgen-tests/swift/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "uniffi-bindgen-tests-swift" -version = "0.31.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["cdylib"] - -[dependencies] -camino = "1" -glob = "0.3" -uniffi = { path = "../../uniffi", features = ["bindgen"] } -uniffi-bindgen-tests = { path = "../lib" } diff --git a/uniffi/bindgen-tests/swift/bridging-header-compile/Cargo.toml b/uniffi/bindgen-tests/swift/bridging-header-compile/Cargo.toml deleted file mode 100644 index 3d2c0fcd1..000000000 --- a/uniffi/bindgen-tests/swift/bridging-header-compile/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "swift-bridging-header-compile" -version = "0.1.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "uniffi_swift_bridging_header_compiler" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -camino = "1.0.8" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests", "cli"] } -uniffi_testing = { path = "../../../uniffi_testing" } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/bridging-header-compile/README.md b/uniffi/bindgen-tests/swift/bridging-header-compile/README.md deleted file mode 100644 index 5fe197899..000000000 --- a/uniffi/bindgen-tests/swift/bridging-header-compile/README.md +++ /dev/null @@ -1,2 +0,0 @@ -Test that the `nameFFI.h` bridging header can be compiler with a -reasonably strict set of compiler warnings enabled. diff --git a/uniffi/bindgen-tests/swift/bridging-header-compile/build.rs b/uniffi/bindgen-tests/swift/bridging-header-compile/build.rs deleted file mode 100644 index 50bc32f83..000000000 --- a/uniffi/bindgen-tests/swift/bridging-header-compile/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/swift-bridging-header-compile.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/swift/bridging-header-compile/src/lib.rs b/uniffi/bindgen-tests/swift/bridging-header-compile/src/lib.rs deleted file mode 100644 index fd71b5f96..000000000 --- a/uniffi/bindgen-tests/swift/bridging-header-compile/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub fn no_arguments() {} - -uniffi::include_scaffolding!("swift-bridging-header-compile"); diff --git a/uniffi/bindgen-tests/swift/bridging-header-compile/src/swift-bridging-header-compile.udl b/uniffi/bindgen-tests/swift/bridging-header-compile/src/swift-bridging-header-compile.udl deleted file mode 100644 index 256dc22d8..000000000 --- a/uniffi/bindgen-tests/swift/bridging-header-compile/src/swift-bridging-header-compile.udl +++ /dev/null @@ -1,3 +0,0 @@ -namespace swift_bridging_header_compile { - void no_arguments(); -}; diff --git a/uniffi/bindgen-tests/swift/bridging-header-compile/tests/clang.rs b/uniffi/bindgen-tests/swift/bridging-header-compile/tests/clang.rs deleted file mode 100644 index 551759d16..000000000 --- a/uniffi/bindgen-tests/swift/bridging-header-compile/tests/clang.rs +++ /dev/null @@ -1,54 +0,0 @@ -use camino::Utf8PathBuf; -use std::process::Command; -use uniffi::{generate, GenerateOptions, TargetLanguage}; -use uniffi_testing::UniFFITestHelper; - -#[test] -fn clang() -> Result<(), anyhow::Error> { - let tmp_dir = std::env!("CARGO_TARGET_TMPDIR"); - let crate_name = std::env!("CARGO_PKG_NAME"); - - let test_helper = UniFFITestHelper::new(crate_name)?; - let out_dir = test_helper.create_out_dir(tmp_dir, "clang.rs")?; - - generate(GenerateOptions { - languages: vec![TargetLanguage::Swift], - source: Utf8PathBuf::from("src/swift-bridging-header-compile.udl"), - out_dir: out_dir.clone(), - ..GenerateOptions::default() - })?; - - let bridging_h = out_dir.join("swift_bridging_header_compileFFI.h"); - - // Compile the header as objective-c with a pedantic set of warnings. - let o = Command::new("clang") - .args([ - "-c", - "-x", - "objective-c", - "-Wpedantic", - "-Werror", - "-Wstrict-prototypes", - "-Wno-pragma-once-outside-header", // We are compiling a header directly, so this is fine. - "-Wno-newline-eof", // If `swiftformat` were used this would be ok. - "-o", - "/dev/null", - bridging_h.as_str(), - ]) - .output()?; - - assert!( - o.status.success(), - r#"Failed to compile bridging header {}: -stdout: -{} - -stderr: -{} -"#, - o.status, - String::from_utf8_lossy(&o.stdout), - String::from_utf8_lossy(&o.stderr) - ); - Ok(()) -} diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/Cargo.toml b/uniffi/bindgen-tests/swift/callbacks-omit-labels/Cargo.toml deleted file mode 100644 index 031bd3606..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-regression-callbacks-omit-labels" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_regression_test_callbacks_omit_labels" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/README.md b/uniffi/bindgen-tests/swift/callbacks-omit-labels/README.md deleted file mode 100644 index 2cff77127..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Regression test for [issue 1312](https://github.com/mozilla/uniffi-rs/issues/1312) - -We didn't apply the same `omit_argument_labels` configuration to callbacks, -leading to a compilation error. - -We replicate the reported buggy code and turn that into a full blown test now. diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/build.rs b/uniffi/bindgen-tests/swift/callbacks-omit-labels/build.rs deleted file mode 100644 index 05b0af143..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/test.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/src/lib.rs b/uniffi/bindgen-tests/swift/callbacks-omit-labels/src/lib.rs deleted file mode 100644 index 9452eb099..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -pub struct UserModel { - name: String, -} - -pub trait ClientDelegate: Sync + Send { - fn did_receive_friend_request(&self, user: UserModel); -} - -#[derive(Debug, Clone)] -struct Client; - -impl Client { - fn new() -> Self { - Self - } - - fn friend_request(&self, delegate: Box) { - let user = UserModel { - name: "Alice".to_string(), - }; - delegate.did_receive_friend_request(user); - } -} - -uniffi::include_scaffolding!("test"); diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/src/test.udl b/uniffi/bindgen-tests/swift/callbacks-omit-labels/src/test.udl deleted file mode 100644 index e615fcd99..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/src/test.udl +++ /dev/null @@ -1,17 +0,0 @@ -// Regression test for https://github.com/mozilla/uniffi-rs/issues/1312 - -namespace regression_test_callbacks_omit_labels { }; - -dictionary UserModel { - string name; -}; - -interface Client { - constructor(); - - void friend_request(ClientDelegate delegate); -}; - -callback interface ClientDelegate { - void did_receive_friend_request(UserModel user); -}; diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/tests/bindings/test.swift b/uniffi/bindgen-tests/swift/callbacks-omit-labels/tests/bindings/test.swift deleted file mode 100644 index 1b286ab55..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/tests/bindings/test.swift +++ /dev/null @@ -1,26 +0,0 @@ -// Regression test for https://github.com/mozilla/uniffi-rs/issues/1312 -// -// Really this can be detected at compile time: -// We didn't apply the same `omit_argument_labels` configuration to callbacks, -// leading to a compilation error. -// To make sure everything gets called right though we write a full test here. - -import regression_test_callbacks_omit_labels - -final class ClientDelegateImpl: ClientDelegate, @unchecked Sendable { - var recvCount: Int = 0 - var lastFriend = "" - - func didReceiveFriendRequest(_ user: UserModel) { - recvCount += 1 - lastFriend = user.name - } -} - -let cd = ClientDelegateImpl() -let client = Client() - -client.friendRequest(cd) - -assert(cd.recvCount == 1, "delegate should be called once") -assert(cd.lastFriend == "Alice", "delegate should have received Alice's friend request") diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/swift/callbacks-omit-labels/tests/test_generated_bindings.rs deleted file mode 100644 index 29b23d4c2..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test.swift",); diff --git a/uniffi/bindgen-tests/swift/callbacks-omit-labels/uniffi.toml b/uniffi/bindgen-tests/swift/callbacks-omit-labels/uniffi.toml deleted file mode 100644 index 32b6d9978..000000000 --- a/uniffi/bindgen-tests/swift/callbacks-omit-labels/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.swift] -omit_argument_labels = true diff --git a/uniffi/bindgen-tests/swift/codable/Cargo.toml b/uniffi/bindgen-tests/swift/codable/Cargo.toml deleted file mode 100644 index 505fb9f5b..000000000 --- a/uniffi/bindgen-tests/swift/codable/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-swift-codable" -version = "0.22.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_swift_codable" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/codable/README.md b/uniffi/bindgen-tests/swift/codable/README.md deleted file mode 100644 index fff838486..000000000 --- a/uniffi/bindgen-tests/swift/codable/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# A Swift-only test for uniffi components - -Swift tests for checking `Codable` conformance diff --git a/uniffi/bindgen-tests/swift/codable/build.rs b/uniffi/bindgen-tests/swift/codable/build.rs deleted file mode 100644 index 1d5171e0c..000000000 --- a/uniffi/bindgen-tests/swift/codable/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/codable_test.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/swift/codable/src/codable_test.udl b/uniffi/bindgen-tests/swift/codable/src/codable_test.udl deleted file mode 100644 index 29e59299a..000000000 --- a/uniffi/bindgen-tests/swift/codable/src/codable_test.udl +++ /dev/null @@ -1 +0,0 @@ -namespace codable_test {}; diff --git a/uniffi/bindgen-tests/swift/codable/src/lib.rs b/uniffi/bindgen-tests/swift/codable/src/lib.rs deleted file mode 100644 index b82ed3566..000000000 --- a/uniffi/bindgen-tests/swift/codable/src/lib.rs +++ /dev/null @@ -1,58 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[derive(uniffi::Error, Debug)] -pub enum SimpleError { - InvalidInput, - OsError, -} - -#[derive(uniffi::Enum)] -pub enum SimpleEnum { - One, - Two, -} - -#[repr(u8)] -#[derive(uniffi::Enum)] -pub enum ReprU8 { - One = 1, - Two = 0x2, -} - -#[derive(uniffi::Enum)] -pub enum ComplexEnum { - None, - String(String), - Int(i64), - All { s: String, i: i64 }, - Vec(Vec), -} - -#[derive(uniffi::Record)] -pub struct SimpleRecord { - string: String, - boolean: bool, - integer: i32, - float_var: f64, - vec: Vec, -} - -#[derive(uniffi::Record)] -pub struct RecordWithOptionals { - string: Option, - boolean: Option, - integer: Option, - float_var: Option, - vec: Option>, -} - -#[derive(uniffi::Record)] -pub struct MultiLayerRecord { - simple_enum: SimpleEnum, - repr_u8: ReprU8, - simple_record: SimpleRecord, -} - -uniffi::include_scaffolding!("codable_test"); diff --git a/uniffi/bindgen-tests/swift/codable/tests/bindings/test_codable.swift b/uniffi/bindgen-tests/swift/codable/tests/bindings/test_codable.swift deleted file mode 100644 index 7d395f6ea..000000000 --- a/uniffi/bindgen-tests/swift/codable/tests/bindings/test_codable.swift +++ /dev/null @@ -1,60 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import codable_test - -// SimpleRecord -let simpleRecord = SimpleRecord( - string: "Test", - boolean: true, - integer: 1, - floatVar: 1.1, - vec: [true] -) - -let jsonSimpleRecord = try JSONEncoder().encode(simpleRecord) -let deserializedSimpleRecord = try JSONDecoder().decode(SimpleRecord.self, from: jsonSimpleRecord) -assert(deserializedSimpleRecord.string == "Test") -assert(deserializedSimpleRecord.boolean) -assert(deserializedSimpleRecord.integer == 1) -assert(deserializedSimpleRecord.floatVar == 1.1) -assert(deserializedSimpleRecord.vec == [true]) - -// MultiLayerRecord -let multilayer = MultiLayerRecord( - simpleEnum: SimpleEnum.one, - reprU8: ReprU8.two, - simpleRecord: simpleRecord -) - -let jsonMultiLayerRecord = try JSONEncoder().encode(multilayer) -let deserializedMultiLayerRecord = try JSONDecoder().decode(MultiLayerRecord.self, from: jsonMultiLayerRecord) -assert(deserializedMultiLayerRecord.simpleEnum == .one) -assert(deserializedMultiLayerRecord.reprU8 == .two) -assert(deserializedMultiLayerRecord.simpleRecord == simpleRecord) - -// RecordWithOptionals -let optionals = RecordWithOptionals( - string: nil, - boolean: nil, - integer: nil, - floatVar: nil, - vec: ["A", "B"] -) - -let jsonRecordWithOptionals = try JSONEncoder().encode(optionals) -assert(String(data: jsonRecordWithOptionals, encoding: .utf8) == "{\"vec\":[\"A\",\"B\"]}") - -// ComplexEnum -let complexEnum = ComplexEnum.string("test") -let jsonComplexEnum = try JSONEncoder().encode(complexEnum) -let deserializedComplexEnum = try JSONDecoder().decode(ComplexEnum.self, from: jsonComplexEnum) -assert(deserializedComplexEnum == .string("test")) - -// SimpleError -let simpleError = SimpleError.OsError -let jsonSimpleError = try JSONEncoder().encode(simpleError) -let deserializedSimpleError = try JSONDecoder().decode(SimpleError.self, from: jsonSimpleError) -assert(deserializedSimpleError == .OsError) diff --git a/uniffi/bindgen-tests/swift/codable/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/swift/codable/tests/test_generated_bindings.rs deleted file mode 100644 index b570f9207..000000000 --- a/uniffi/bindgen-tests/swift/codable/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test_codable.swift",); diff --git a/uniffi/bindgen-tests/swift/codable/uniffi.toml b/uniffi/bindgen-tests/swift/codable/uniffi.toml deleted file mode 100644 index 7f3df2ee1..000000000 --- a/uniffi/bindgen-tests/swift/codable/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.swift] -generate_codable_conformance = true diff --git a/uniffi/bindgen-tests/swift/dictionary-nesting/Cargo.toml b/uniffi/bindgen-tests/swift/dictionary-nesting/Cargo.toml deleted file mode 100644 index 261734369..000000000 --- a/uniffi/bindgen-tests/swift/dictionary-nesting/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-regression-swift-dictionary-nesting" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_regression_test_swift_dictionary_nesting" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/dictionary-nesting/README.md b/uniffi/bindgen-tests/swift/dictionary-nesting/README.md deleted file mode 100644 index 6e1a204bb..000000000 --- a/uniffi/bindgen-tests/swift/dictionary-nesting/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Regression test for ambiguous nested dictionaries in Swift - -Previously nested dictionary types, such as `[String: String]` and `[String: [String]]` would be exported under the same name (e.g. `FfiConverterDictionaryStringString`) leading to compilation issues. - -This test ensures that nested dictionaries can be disambiguated in roughly the following way: - -- `[String: String]` => `...DictionaryStringString` -- `[String: [String]]` => `...DictionaryStringSequenceString` -- `[String: [String: String]]` => `...DictionaryStringDictionaryStringString` -- `[String: [String: [String]]]` => `...DictionaryStringDictionaryStringSequenceString` -- etc diff --git a/uniffi/bindgen-tests/swift/dictionary-nesting/build.rs b/uniffi/bindgen-tests/swift/dictionary-nesting/build.rs deleted file mode 100644 index 05b0af143..000000000 --- a/uniffi/bindgen-tests/swift/dictionary-nesting/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/test.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/swift/dictionary-nesting/src/lib.rs b/uniffi/bindgen-tests/swift/dictionary-nesting/src/lib.rs deleted file mode 100644 index 26f22b304..000000000 --- a/uniffi/bindgen-tests/swift/dictionary-nesting/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::collections::HashMap; - -pub fn get_dict_1() -> HashMap { - HashMap::new() -} - -pub fn get_dict_2() -> HashMap> { - HashMap::new() -} - -pub fn get_dict_3() -> HashMap> { - HashMap::new() -} - -pub fn get_dict_4() -> HashMap>> { - HashMap::new() -} - -uniffi::include_scaffolding!("test"); diff --git a/uniffi/bindgen-tests/swift/dictionary-nesting/src/test.udl b/uniffi/bindgen-tests/swift/dictionary-nesting/src/test.udl deleted file mode 100644 index e2245b7fd..000000000 --- a/uniffi/bindgen-tests/swift/dictionary-nesting/src/test.udl +++ /dev/null @@ -1,8 +0,0 @@ -// Regression test for ... - -namespace regression_test_swift_dictionary_nesting { - record get_dict_1(); - record> get_dict_2(); - record> get_dict_3(); - record>> get_dict_4(); -}; \ No newline at end of file diff --git a/uniffi/bindgen-tests/swift/dictionary-nesting/tests/bindings/test.swift b/uniffi/bindgen-tests/swift/dictionary-nesting/tests/bindings/test.swift deleted file mode 100644 index 9a970a2e5..000000000 --- a/uniffi/bindgen-tests/swift/dictionary-nesting/tests/bindings/test.swift +++ /dev/null @@ -1,6 +0,0 @@ -import regression_test_swift_dictionary_nesting - -assert(getDict1() == [String: String]()) -assert(getDict2() == [String: [String]]()) -assert(getDict3() == [String: [String: String]]()) -assert(getDict4() == [String: [String: [String]]]()) diff --git a/uniffi/bindgen-tests/swift/dictionary-nesting/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/swift/dictionary-nesting/tests/test_generated_bindings.rs deleted file mode 100644 index 29b23d4c2..000000000 --- a/uniffi/bindgen-tests/swift/dictionary-nesting/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test.swift",); diff --git a/uniffi/bindgen-tests/swift/keywords/Cargo.toml b/uniffi/bindgen-tests/swift/keywords/Cargo.toml deleted file mode 100644 index 59bedebe0..000000000 --- a/uniffi/bindgen-tests/swift/keywords/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-keywords-swift" -version = "0.22.0" -edition = "2021" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_keywords_swift" - -[dependencies] -thiserror = "2" -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/keywords/build.rs b/uniffi/bindgen-tests/swift/keywords/build.rs deleted file mode 100644 index 58fc0ba0f..000000000 --- a/uniffi/bindgen-tests/swift/keywords/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/keywords.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/swift/keywords/src/keywords.udl b/uniffi/bindgen-tests/swift/keywords/src/keywords.udl deleted file mode 100644 index 8c1da062a..000000000 --- a/uniffi/bindgen-tests/swift/keywords/src/keywords.udl +++ /dev/null @@ -1,33 +0,0 @@ -namespace keywords_swift { - -}; - -enum case { - "internal", - "init", -}; - -[Enum] -interface for { - internal(u8 break); -}; - -dictionary return { - u8 class; - u8? switch; -}; - -interface break { - void class(u8 internal); - void internal(u8? class); -}; - -[Error] -enum class { - "internal", -}; - -[Error] -interface func { - class(u8 object); -}; diff --git a/uniffi/bindgen-tests/swift/keywords/src/lib.rs b/uniffi/bindgen-tests/swift/keywords/src/lib.rs deleted file mode 100644 index 6082ab05b..000000000 --- a/uniffi/bindgen-tests/swift/keywords/src/lib.rs +++ /dev/null @@ -1,56 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// pub fn r#if(_break: u8) {} - -#[allow(non_camel_case_types)] -pub enum r#case { - r#internal, - r#init, -} - -#[allow(non_camel_case_types)] -pub enum r#for { - #[allow(non_camel_case_types)] - r#internal { r#break: u8 }, -} - -#[allow(non_camel_case_types)] -pub struct r#return { - class: u8, - switch: Option, -} - -#[allow(non_camel_case_types)] -pub struct r#break {} - -impl r#break { - pub fn class(&self, _internal: u8) {} - pub fn internal(&self, _class: Option) {} -} - -#[allow(non_camel_case_types)] -#[derive(Debug, thiserror::Error)] -pub enum class { - #[error("internal error")] - internal, -} - -#[allow(non_camel_case_types)] -#[derive(Debug, thiserror::Error)] -pub enum func { - #[error("class?")] - class { object: u8 }, -} - -#[allow(non_camel_case_types)] -pub struct r#else(pub r#func); -uniffi::custom_newtype!(r#else, r#func); - -#[uniffi::export] -pub fn get_else(e: r#else) -> r#else { - e -} - -uniffi::include_scaffolding!("keywords"); diff --git a/uniffi/bindgen-tests/swift/keywords/tests/bindings/test_keywords.swift b/uniffi/bindgen-tests/swift/keywords/tests/bindings/test_keywords.swift deleted file mode 100644 index 435b483a7..000000000 --- a/uniffi/bindgen-tests/swift/keywords/tests/bindings/test_keywords.swift +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import keywords_swift - -// able to import is the real test, but might as well call something. -let case_internal = Case.internal; diff --git a/uniffi/bindgen-tests/swift/keywords/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/swift/keywords/tests/test_generated_bindings.rs deleted file mode 100644 index 6521d8642..000000000 --- a/uniffi/bindgen-tests/swift/keywords/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test_keywords.swift",); diff --git a/uniffi/bindgen-tests/swift/link-frameworks/Cargo.toml b/uniffi/bindgen-tests/swift/link-frameworks/Cargo.toml deleted file mode 100644 index b2a1c11ee..000000000 --- a/uniffi/bindgen-tests/swift/link-frameworks/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-swift-link-frameworks" -version = "0.1.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_swift_link_frameworks" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/link-frameworks/build.rs b/uniffi/bindgen-tests/swift/link-frameworks/build.rs deleted file mode 100644 index 5268fb4a5..000000000 --- a/uniffi/bindgen-tests/swift/link-frameworks/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/swift-link-frameworks.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/swift/link-frameworks/src/lib.rs b/uniffi/bindgen-tests/swift/link-frameworks/src/lib.rs deleted file mode 100644 index 27a9f57c2..000000000 --- a/uniffi/bindgen-tests/swift/link-frameworks/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub fn no_arguments() {} - -uniffi::include_scaffolding!("swift-link-frameworks"); diff --git a/uniffi/bindgen-tests/swift/link-frameworks/src/swift-link-frameworks.udl b/uniffi/bindgen-tests/swift/link-frameworks/src/swift-link-frameworks.udl deleted file mode 100644 index 7e78f8e93..000000000 --- a/uniffi/bindgen-tests/swift/link-frameworks/src/swift-link-frameworks.udl +++ /dev/null @@ -1,3 +0,0 @@ -namespace swift_link_frameworks { - void no_arguments(); -}; diff --git a/uniffi/bindgen-tests/swift/link-frameworks/uniffi.toml b/uniffi/bindgen-tests/swift/link-frameworks/uniffi.toml deleted file mode 100644 index fc6e6aaf4..000000000 --- a/uniffi/bindgen-tests/swift/link-frameworks/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.swift] -link_frameworks = ["CoreFoundation"] diff --git a/uniffi/bindgen-tests/swift/mock-objects/Cargo.toml b/uniffi/bindgen-tests/swift/mock-objects/Cargo.toml deleted file mode 100644 index ac2ee69b1..000000000 --- a/uniffi/bindgen-tests/swift/mock-objects/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "uniffi-fixture-swift-mock-objects" -version = "0.22.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_swift_mock_objects" - -[dependencies] -uniffi = { workspace = true } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/mock-objects/src/lib.rs b/uniffi/bindgen-tests/swift/mock-objects/src/lib.rs deleted file mode 100644 index e8f299f66..000000000 --- a/uniffi/bindgen-tests/swift/mock-objects/src/lib.rs +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[derive(uniffi::Object, Debug)] -pub struct TestObject; - -#[uniffi::export] -impl TestObject { - pub fn is_mock(&self) -> bool { - false - } -} - -uniffi::setup_scaffolding!("swift_mock_objects"); diff --git a/uniffi/bindgen-tests/swift/mock-objects/tests/bindings/test_mock_objects.swift b/uniffi/bindgen-tests/swift/mock-objects/tests/bindings/test_mock_objects.swift deleted file mode 100644 index 8caeb9046..000000000 --- a/uniffi/bindgen-tests/swift/mock-objects/tests/bindings/test_mock_objects.swift +++ /dev/null @@ -1,33 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import swift_mock_objects - -// Swift version 6 gives a warning that we must restate `@unchecked Sendable`, however earlier -// versions of Swift fail if we add that. Let's leave it out and accept the warning for now. -public class TestObjectMock: TestObject { - - required public init(unsafeFromHandle handle: UInt64) { - fatalError("Not supported") - } - - public init() { - super.init(noHandle: NoHandle.init()) - } - - // Override the "is_mock()" function - - override public func isMock() -> Bool { - return true; - } -} - -var mocked: TestObjectMock? = TestObjectMock() - -// Test that our mock object can override the functions of the real object -assert(mocked!.isMock()) - -// Test that we don't crash when deinitializing the mock object -mocked = nil diff --git a/uniffi/bindgen-tests/swift/mock-objects/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/swift/mock-objects/tests/test_generated_bindings.rs deleted file mode 100644 index 77dfdc656..000000000 --- a/uniffi/bindgen-tests/swift/mock-objects/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test_mock_objects.swift",); diff --git a/uniffi/bindgen-tests/swift/omit-labels/Cargo.toml b/uniffi/bindgen-tests/swift/omit-labels/Cargo.toml deleted file mode 100644 index 0fa757381..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-swift-omit-argument-labels" -version = "0.22.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_omit_argument_labels" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/bindgen-tests/swift/omit-labels/README.md b/uniffi/bindgen-tests/swift/omit-labels/README.md deleted file mode 100644 index 2a7192f42..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# A Swift-only test for uniffi components - -This tests that we can instruct UniFFI to define functions -so that the caller can omit argument labels. diff --git a/uniffi/bindgen-tests/swift/omit-labels/build.rs b/uniffi/bindgen-tests/swift/omit-labels/build.rs deleted file mode 100644 index 933eabcc6..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/omit_argument_labels.udl").unwrap(); -} diff --git a/uniffi/bindgen-tests/swift/omit-labels/src/lib.rs b/uniffi/bindgen-tests/swift/omit-labels/src/lib.rs deleted file mode 100644 index e42d4d544..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/src/lib.rs +++ /dev/null @@ -1,17 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn no_args() -> i32 { - 31 -} - -fn one_arg(amount: i32) -> i32 { - amount -} - -fn multiple_args(amount: i32, _msg: String) -> i32 { - amount -} - -uniffi::include_scaffolding!("omit_argument_labels"); diff --git a/uniffi/bindgen-tests/swift/omit-labels/src/omit_argument_labels.udl b/uniffi/bindgen-tests/swift/omit-labels/src/omit_argument_labels.udl deleted file mode 100644 index bfa81496e..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/src/omit_argument_labels.udl +++ /dev/null @@ -1,5 +0,0 @@ -namespace omit_argument_labels { - i32 no_args(); - i32 one_arg(i32 amount); - i32 multiple_args(i32 amount, string msg); -}; diff --git a/uniffi/bindgen-tests/swift/omit-labels/tests/bindings/test_omit_argument_labels.swift b/uniffi/bindgen-tests/swift/omit-labels/tests/bindings/test_omit_argument_labels.swift deleted file mode 100644 index a039af556..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/tests/bindings/test_omit_argument_labels.swift +++ /dev/null @@ -1,9 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import omit_argument_labels - -assert(31 == noArgs()) -assert(3 == oneArg(3)) -assert(7 == multipleArgs(7, "look, I can omit the labels")) diff --git a/uniffi/bindgen-tests/swift/omit-labels/tests/test_generated_bindings.rs b/uniffi/bindgen-tests/swift/omit-labels/tests/test_generated_bindings.rs deleted file mode 100644 index dfb420e0a..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test_omit_argument_labels.swift",); diff --git a/uniffi/bindgen-tests/swift/omit-labels/uniffi.toml b/uniffi/bindgen-tests/swift/omit-labels/uniffi.toml deleted file mode 100644 index 32b6d9978..000000000 --- a/uniffi/bindgen-tests/swift/omit-labels/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.swift] -omit_argument_labels = true diff --git a/uniffi/bindgen-tests/swift/src/lib.rs b/uniffi/bindgen-tests/swift/src/lib.rs deleted file mode 100644 index 69cc09ee7..000000000 --- a/uniffi/bindgen-tests/swift/src/lib.rs +++ /dev/null @@ -1,223 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -extern crate uniffi_bindgen_tests; - -#[cfg(test)] -mod test { - use std::{ - env::consts::{DLL_PREFIX, DLL_SUFFIX}, - fs, - io::Write, - process::Command, - sync::OnceLock, - }; - - use camino::{Utf8Path, Utf8PathBuf}; - - use uniffi::TargetLanguage; - use uniffi_bindgen_tests::test_util; - - #[test] - fn test_simple_fns() { - run_tests(test_dir(), "tests/simple_fns.swift"); - } - - #[test] - fn test_primitive_types() { - run_tests(test_dir(), "tests/primitive_types.swift"); - } - - #[test] - fn test_records() { - run_tests(test_dir(), "tests/records.swift"); - } - - #[test] - fn test_collections() { - run_tests(test_dir(), "tests/collections.swift"); - } - - #[test] - fn test_options() { - run_tests(test_dir(), "tests/options.swift"); - } - - #[test] - fn test_enums() { - run_tests(test_dir(), "tests/enums.swift"); - } - - #[test] - fn test_interfaces() { - run_tests(test_dir(), "tests/interfaces.swift"); - } - - #[test] - fn test_errors() { - run_tests(test_dir(), "tests/errors.swift"); - } - - #[test] - fn test_callback_interfaces() { - run_tests(test_dir(), "tests/callback_interfaces.swift"); - } - - #[test] - fn test_futures() { - run_tests(test_dir(), "tests/futures.swift"); - } - - #[test] - fn test_trait_interfaces() { - run_tests(test_dir(), "tests/trait_interfaces.swift"); - } - - #[test] - fn test_defaults() { - run_tests(test_dir(), "tests/defaults.swift"); - } - - #[test] - fn test_references() { - run_tests(test_dir(), "tests/references.swift"); - } - - #[test] - fn test_custom_types() { - run_tests(test_dir(), "tests/custom_types.swift"); - } - - #[test] - fn test_external_types() { - run_tests(test_dir(), "tests/external_types.swift"); - } - - #[test] - fn test_renames() { - run_tests(test_dir(), "tests/renames.swift"); - } - - #[test] - fn test_bytes() { - run_tests(test_dir(), "tests/bytes.swift"); - } - - #[test] - fn test_recursive_types() { - run_tests(test_dir(), "tests/recursive_types.swift"); - } - - #[test] - fn test_time() { - run_tests(test_dir(), "tests/time.swift"); - } - - #[test] - fn test_rust_traits() { - run_tests(test_dir(), "tests/rust_traits.swift"); - } - - fn test_dir() -> &'static Utf8Path { - static TEST_TEMPDIR: OnceLock = OnceLock::new(); - TEST_TEMPDIR.get_or_init(|| { - let temp_dir = test_util::setup_test_dir("swift"); - test_util::build_library(&temp_dir); - test_util::generate_sources(&temp_dir, TargetLanguage::Swift); - test_util::copy_test_sources(&temp_dir, "tests/*.swift"); - combine_module_maps(&temp_dir); - compile_sources(&temp_dir); - temp_dir - }) - } - - // We need something better than this env var, but it's a reasonable start. - fn swift_version() -> String { - std::env::var("UNIFFI_TEST_SWIFT_VERSION").unwrap_or("5".to_string()) - } - - // uniffi-bindgen creates a separate modulemap for each Rust crate. - // - // Combine all of these into a single modulemap so that the tests will run - fn combine_module_maps(tempdir: &Utf8Path) { - let mut f = fs::File::create(tempdir.join("combined.modulemap")).unwrap(); - let source_filenames = [ - "uniffi_bindgen_testsFFI.modulemap", - "uniffi_bindgen_tests_external_types_sourceFFI.modulemap", - ]; - for filename in source_filenames { - let path = tempdir.join(filename); - let contents = fs::read_to_string(&path) - .unwrap_or_else(|e| panic!("Error reading modulemap: {path} ({e})")); - write!(f, "{contents}").unwrap(); - } - } - - fn compile_sources(tempdir: &Utf8Path) { - let mut command = Command::new("swiftc"); - command - .current_dir(tempdir) - .arg("-module-name") - .arg("uniffi_bindgen_tests") - .arg("-emit-module") - .arg("-parse-as-library") - // TODO(2279): Fix concurrency issues and uncomment this - //.arg("-strict-concurrency=complete") - .arg("-o") - .arg(format!("{DLL_PREFIX}test_library{DLL_SUFFIX}")) - .arg("-emit-library") - .arg("-swift-version") - .arg(swift_version()) - .arg("-Xcc") - .arg(format!("-fmodule-map-file={tempdir}/combined.modulemap")) - .arg("-L") - .arg(tempdir) - .arg("uniffi_bindgen_tests.swift") - .arg("uniffi_bindgen_tests_external_types_source.swift"); - let status = command - .spawn() - .expect("Failed to spawn `swiftc` when compiling bindings") - .wait() - .expect("Failed to wait for `swiftc` when compiling bindings"); - if !status.success() { - panic!( - "running `swiftc` to compile bindings failed ({:?})", - command - ) - }; - } - - fn run_tests(tempdir: &Utf8Path, script_filename: &str) { - // Run the test script against compiled bindings - let mut command = Command::new("swift"); - let output = command - .current_dir(tempdir) - .env("SWIFT_BACKTRACE", "interactive=no") - .arg("-I") - .arg(tempdir) - .arg("-L") - .arg(tempdir) - .arg("-ltest_library") - .arg("-luniffi_bindgen_tests") - .arg("-swift-version") - .arg(swift_version()) - .arg("-Xcc") - .arg(format!("-fmodule-map-file={tempdir}/combined.modulemap")) - .arg(script_filename) - .output() - .expect("Failed to spawn `swiftc` when running test script"); - // The `output()` call above sets up pipes to print stdout/stderr. This allows it to be - // integrated with the Rust test harness's output handling. - if !output.stderr.is_empty() { - println!("---------------------------------------- STDERR ----------------------------------------"); - print!("{}", String::from_utf8_lossy(&output.stderr)); - println!("----------------------------------------------------------------------------------------"); - panic!("swift outputed standard error"); - } - print!("{}", String::from_utf8_lossy(&output.stdout)); - if !output.status.success() { - panic!("running `swift` to run test script failed ({:?})", command) - } - } -} diff --git a/uniffi/bindgen-tests/swift/tests/bytes.swift b/uniffi/bindgen-tests/swift/tests/bytes.swift deleted file mode 100644 index 03f2c9239..000000000 --- a/uniffi/bindgen-tests/swift/tests/bytes.swift +++ /dev/null @@ -1,16 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests -import Foundation - -var data = Data.init() -data.append(contentsOf: [1, 2, 3, 4]) -assert(roundtripBytes(a: data) == data); - -// Zero-copy &[u8] — proc-macro path -assert(sumBytesProcmacro(buf: Data()) == 0) -assert(sumBytesProcmacro(buf: Data([1, 2, 3])) == 6) -assert(firstByteProcmacro(buf: Data()) == nil) -assert(firstByteProcmacro(buf: Data([42])) == 42) diff --git a/uniffi/bindgen-tests/swift/tests/callback_interfaces.swift b/uniffi/bindgen-tests/swift/tests/callback_interfaces.swift deleted file mode 100644 index a4e02d42c..000000000 --- a/uniffi/bindgen-tests/swift/tests/callback_interfaces.swift +++ /dev/null @@ -1,55 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -var callbackRefCount = 0; - -final class Callback: TestCallbackInterface, @unchecked Sendable { - var value: UInt32; - - init(value: UInt32) { - self.value = value; - callbackRefCount += 1 - } - - deinit { - callbackRefCount -= 1 - } - - func noop() {} - - func getValue() -> UInt32 { - return self.value; - } - - func setValue(value: UInt32) { - self.value = value; - } - - func throwIfEqual(numbers: CallbackInterfaceNumbers) throws -> CallbackInterfaceNumbers { - if numbers.a == numbers.b { - throw TestError.Failure1 - } - return numbers - } - - func echo(s: String) -> String { - return s - } -} - -// Construct a callback interface to pass to rust -let cbi = Callback(value: 42); -// Test calling callback interface methods, which we can only do indirectly. -// Each of these Rust functions inputs a callback interface, calls a method on it, then returns the result. -invokeTestCallbackInterfaceNoop(cbi: cbi); -assert(invokeTestCallbackInterfaceGetValue(cbi: cbi) == 42); -invokeTestCallbackInterfaceSetValue(cbi: cbi, value: 43); -assert(invokeTestCallbackInterfaceGetValue(cbi: cbi) == 43); -assert(invokeTestCallbackInterfaceEcho(cbi: cbi, s: "test-string") == "test-string"); - -// The previcalls created a bunch of callback interface references. Make sure they've been cleaned -// up and the only remaining reference is for our `cbi` variable. -assert(callbackRefCount == 1) diff --git a/uniffi/bindgen-tests/swift/tests/collections.swift b/uniffi/bindgen-tests/swift/tests/collections.swift deleted file mode 100644 index 405312b15..000000000 --- a/uniffi/bindgen-tests/swift/tests/collections.swift +++ /dev/null @@ -1,57 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -assert(roundtripVecI8(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecU16(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecI16(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecU32(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecI32(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecU64(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecI64(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecF32(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecF64(a: [1, 2, 3]) == [1, 2, 3]); -assert(roundtripVecBool(a: [true, false]) == [true, false]); -assert(roundtripVecString(a: ["test-string"]) == ["test-string"]); -assert(roundtripVecRec(a: [CollectionsRec(a: 67)]) == [CollectionsRec(a: 67)]) - -assert(roundtripHashMap(a: ["a": 1, "b": 2]) == ["a": 1, "b": 2]) -assert(roundtripHashSet(a: ["a", "b", "c"]) == ["a", "b", "c"]) -assert(roundtripHashMapU32Key(a: [1: 2, 2: 4]) == [1: 2, 2: 4]) - -assert( - roundtripRecWithCollections(a: RecWithCollections( - a: EnumWithCollections.a(nil), - b: nil, - c: [true, false], - d: [ - "a": 10, - "b": 20, - ] - ) - ) == RecWithCollections( - a: EnumWithCollections.a(nil), - b: nil, - c: [true, false], - d: [ - "a": 10, - "b": 20, - ] - ) -) -assert(roundtripVecHashSet(a: [["a", "b"]]) == [["a", "b"]]) -assert(roundtripVecHashSet(a: nil) == nil) -assert(roundtripComplexCollectionType(a: [ - [ - "a": CollectionsComplexRec(a: 10, b: "Test", c: CollectionsEnum.a(100)), - "b": CollectionsComplexRec(a: 20, b: "Test2", c: CollectionsEnum.b(a: 1.0, b: true)) - ] -]) == [ - [ - "a": CollectionsComplexRec(a: 10, b: "Test", c: CollectionsEnum.a(100)), - "b": CollectionsComplexRec(a: 20, b: "Test2", c: CollectionsEnum.b(a: 1.0, b: true)) - ] -]) -assert(roundtripComplexCollectionType(a: nil) == nil); diff --git a/uniffi/bindgen-tests/swift/tests/custom_types.swift b/uniffi/bindgen-tests/swift/tests/custom_types.swift deleted file mode 100644 index e449df125..000000000 --- a/uniffi/bindgen-tests/swift/tests/custom_types.swift +++ /dev/null @@ -1,12 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -// CustomType1 doesn't have any Swift custom type associated with it -assert(roundtripCustomType1(custom1: 100) == 100) - -// CustomType2 is a dict in swift. See `uniffi.toml` for the configuration that does this. -assert(roundtripCustomType2(custom2: ["value": 200]) == ["value": 200]) - diff --git a/uniffi/bindgen-tests/swift/tests/defaults.swift b/uniffi/bindgen-tests/swift/tests/defaults.swift deleted file mode 100644 index 860232257..000000000 --- a/uniffi/bindgen-tests/swift/tests/defaults.swift +++ /dev/null @@ -1,23 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -// Records -let r = RecWithDefault() -assert(r.n == 42) -assert(r.v == []) - -// Enums -let e = EnumWithDefault.otherVariant() -assert(e == EnumWithDefault.otherVariant(a: "default")) - -// Default arguments -assert(funcWithDefault() == "DEFAULT"); -assert(funcWithDefault(arg: "NON-DEFAULT") == "NON-DEFAULT"); - -let i = InterfaceWithDefaults(); -assert(i.methodWithDefault() == "DEFAULT") -assert(i.methodWithDefault(arg: "NON-DEFAULT") == "NON-DEFAULT") - diff --git a/uniffi/bindgen-tests/swift/tests/enums.swift b/uniffi/bindgen-tests/swift/tests/enums.swift deleted file mode 100644 index 58e2d5cd9..000000000 --- a/uniffi/bindgen-tests/swift/tests/enums.swift +++ /dev/null @@ -1,42 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -assert( - roundtripEnumWithData(en: EnumWithData.a(value: 10, value2: 20)) == - EnumWithData.a(value: 10, value2: 20)); -assert( - roundtripEnumWithData(en: EnumWithData.b("Ten", 10)) == - EnumWithData.b("Ten", 10)); -assert( - roundtripEnumWithData(en: EnumWithData.c) == - EnumWithData.c); - -assert( - roundtripComplexEnum(en: ComplexEnum.a(value: EnumNoData.c)) == - ComplexEnum.a(value: EnumNoData.c)) -assert( - roundtripComplexEnum(en: ComplexEnum.b(value: EnumWithData.a(value: 20, value2: 40))) == - ComplexEnum.b(value: EnumWithData.a(value: 20, value2: 40))) -assert( - roundtripComplexEnum(en: ComplexEnum.c(value: SimpleRec(a: 30))) == - ComplexEnum.c(value: SimpleRec(a: 30))) - -// Test that the enum discriminant values - -// All discriminants specified, use the specified values -assert(ExplicitValuedEnum.first.rawValue == 1); -assert(ExplicitValuedEnum.second.rawValue == 2); -assert(ExplicitValuedEnum.fourth.rawValue == 4); -assert(ExplicitValuedEnum.tenth.rawValue == 10); -assert(ExplicitValuedEnum.eleventh.rawValue == 11); -assert(ExplicitValuedEnum.thirteenth.rawValue == 13); - -// Some discriminants specified, increment by one for any unspecified variants -assert(GappedEnum.one.rawValue == 10); -assert(GappedEnum.two.rawValue == 11); // Sequential value after ONE (10+1) -assert(GappedEnum.three.rawValue == 14); // Explicit value again -// Enum methods -assert(EnumWithData.a(value: 20, value2: 40).roundtrip() == EnumWithData.a(value: 20, value2: 40)) diff --git a/uniffi/bindgen-tests/swift/tests/errors.swift b/uniffi/bindgen-tests/swift/tests/errors.swift deleted file mode 100644 index 5f6c911e2..000000000 --- a/uniffi/bindgen-tests/swift/tests/errors.swift +++ /dev/null @@ -1,65 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -// `funcWithError` throws when 0 or 1 is passed to it -do { - try funcWithError(input: 0); - fatalError("funcWithError should have thrown") -} catch TestError.Failure1 { - // Expected -} - -do { - try funcWithError(input: 1); - fatalError("funcWithError should have thrown") -} catch TestError.Failure2(let data) { - // Expected - assert(data == "DATA") -} - -do { - try funcWithError(input: 40); - fatalError("funcWithError should have thrown") -} catch TestError.Failure3(let code) { - // Expected - assert(code == 40) -} - -do { - try funcWithFlatError(input: 0); - fatalError("funcWithError should have thrown") -} catch TestFlatError.IoError { - // Expected -} - -// These shouldn't throw -try! funcWithError(input: 200); -try! funcWithFlatError(input: 1); - -// Error enum with no data -do { - try funcWithErrorNoData(input: 0); - fatalError("funcWithErrorNoData should have thrown") -} catch TestErrorNoData.Failure1 { - // Expected -} - -do { - try funcWithErrorNoData(input: 1); - fatalError("funcWithErrorNoData should have thrown") -} catch TestErrorNoData.Failure2 { - // Expected -} - -do { - try funcWithErrorNoData(input: 2); - fatalError("funcWithErrorNoData should have thrown") -} catch TestErrorNoData.Failure3 { - // Expected -} - -// This shouldn't throw -try! funcWithErrorNoData(input: 200); diff --git a/uniffi/bindgen-tests/swift/tests/external_types.swift b/uniffi/bindgen-tests/swift/tests/external_types.swift deleted file mode 100644 index fede9e816..000000000 --- a/uniffi/bindgen-tests/swift/tests/external_types.swift +++ /dev/null @@ -1,14 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -assert(roundtripExtRecord(rec: ExternalRec(a: 42)) == ExternalRec(a: 42)) - -assert(roundtripExtEnum(en: ExternalEnum.two) == ExternalEnum.two) - -let interface = ExternalInterface(value: 20) -assert(roundtripExtInterface(interface: interface).getValue() == 20) - -assert(roundtripExtCustomType(custom: 100) == 100); diff --git a/uniffi/bindgen-tests/swift/tests/futures.swift b/uniffi/bindgen-tests/swift/tests/futures.swift deleted file mode 100644 index c23f29e7c..000000000 --- a/uniffi/bindgen-tests/swift/tests/futures.swift +++ /dev/null @@ -1,154 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import uniffi_bindgen_tests - -var dispatchGroup = DispatchGroup() - -// Primitive types -dispatchGroup.enter() -Task { - let returnedU8 = await asyncRoundtripU8(v: 42) - assert(returnedU8 == 42) - - let returnedI8 = await asyncRoundtripI8(v: -42) - assert(returnedI8 == -42) - - let returnedU16 = await asyncRoundtripU16(v: 42) - assert(returnedU16 == 42) - - let returnedI16 = await asyncRoundtripI16(v: -42) - assert(returnedI16 == -42) - - let returnedU32 = await asyncRoundtripU32(v: 42) - assert(returnedU32 == 42) - - let returnedI32 = await asyncRoundtripI32(v: -42) - assert(returnedI32 == -42) - - let returnedU64 = await asyncRoundtripU64(v: 42) - assert(returnedU64 == 42) - - let returnedI64 = await asyncRoundtripI64(v: -42) - assert(returnedI64 == -42) - - let returnedF32 = await asyncRoundtripF32(v: 0.5) - assert(returnedF32 == 0.5) - - let returnedF64 = await asyncRoundtripF64(v: -0.5) - assert(returnedF64 == -0.5) - - let returnedString = await asyncRoundtripString(v: "hi") - assert(returnedString == "hi") - - let returnedList = await asyncRoundtripVec(v: [42]) - assert(returnedList == [42]) - - let returnedMap = await asyncRoundtripMap(v: ["hello": "world"]) - assert(returnedMap == ["hello": "world"]) - - dispatchGroup.leave() -} -dispatchGroup.wait() - -// Errors -dispatchGroup.enter() -Task { - do { - try await asyncThrowError() - fatalError("expected asyncThrowError to throw") - } catch TestError.Failure1 { - // Expected - } catch { - fatalError("unexpected error \(error)") - } - dispatchGroup.leave() -} -dispatchGroup.wait() - -// Interfaces/methods -dispatchGroup.enter() -Task { - let obj = AsyncInterface(name: "Alice") - let objName = await obj.name() - assert(objName == "Alice") - - let obj2 = await asyncRoundtripObj(v: obj) - let obj2Name = await obj2.name() - assert(obj2Name == "Alice") - - let rec = AsyncRecord(name: "Bob") - let recName = await rec.getName() - assert(recName == "Bob") - - dispatchGroup.leave() -} -dispatchGroup.wait() - -// Callback interfaces -var asyncCallbackRefCount = 0 -class AsyncCallbackImpl: TestAsyncCallbackInterface, @unchecked Sendable { - var value: UInt32; - - init(value: UInt32) { - self.value = value; - asyncCallbackRefCount += 1 - } - - deinit { - asyncCallbackRefCount -= 1 - } - - func noop() async { } - - func getValue() async -> UInt32 { - return self.value; - } - - func setValue(value: UInt32) async { - self.value = value; - } - - func throwIfEqual(numbers: CallbackInterfaceNumbers) async throws -> CallbackInterfaceNumbers { - if numbers.a == numbers.b { - throw TestError.Failure1 - } - return numbers - } -} - -dispatchGroup.enter() -Task { - let cbi = AsyncCallbackImpl(value: 42); - await invokeTestAsyncCallbackInterfaceNoop(cbi: cbi); - - var value = await invokeTestAsyncCallbackInterfaceGetValue(cbi: cbi) - assert(value == 42) - - await invokeTestAsyncCallbackInterfaceSetValue(cbi: cbi, value: 43); - value = await invokeTestAsyncCallbackInterfaceGetValue(cbi: cbi) - assert(value == 43) - - do { - let _ = try await invokeTestAsyncCallbackInterfaceThrowIfEqual( - cbi: cbi, - numbers: CallbackInterfaceNumbers(a: 10, b: 10) - ) - } catch TestError.Failure1 { - // expected - } catch { - fatalError("unexpected error \(error)") - } - - let returnedNumbers = try! await invokeTestAsyncCallbackInterfaceThrowIfEqual( - cbi: cbi, - numbers: CallbackInterfaceNumbers(a: 10, b: 11) - ) - assert(returnedNumbers == CallbackInterfaceNumbers(a: 10, b: 11)) - - dispatchGroup.leave() -} -dispatchGroup.wait() - diff --git a/uniffi/bindgen-tests/swift/tests/interfaces.swift b/uniffi/bindgen-tests/swift/tests/interfaces.swift deleted file mode 100644 index f39a3b8be..000000000 --- a/uniffi/bindgen-tests/swift/tests/interfaces.swift +++ /dev/null @@ -1,54 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -let interface = TestInterface.init(value: 20); -assert(interface.getValue() == 20); -assert(cloneInterface(interface: interface).getValue() == 20); - -// Test optional interfaces -assert(roundtripOptionalInterface(interface: nil) == nil); -assert(roundtripOptionalInterface(interface: TestInterface.init(value: 20))?.getValue() == 20); - -assert(TestInterface.secondaryConstructor(value: 20).getValue() == 40) - -// Test records that store interfaces -// -// The goal is to test if we can read/write interface handles to RustBuffers -let two = TwoTestInterfaces( - first: TestInterface.init(value: 1), - second: TestInterface.init(value: 2) -); -let swapped = swapTestInterfaces(interfaces: two); -assert(swapped.first.getValue() == 2); -assert(swapped.second.getValue() == 1); - -// Test enums that store interfaces -let en = TestInterfaceEnum.one(i: TestInterface.init(value: 1)) -switch en { - case TestInterfaceEnum.one(let i): - assert(i.getValue() == 1) - default: - fatalError("`en` has invalid type: \(en)") -} - -// Create 2 references to an interface using a bunch of intermediary objects: -// * The one passed to `funcThatClonesInterface` -// * The clones created for each method call - -let interface2 = TestInterface.init(value: 20); -func funcThatClonesInterface(interface: TestInterface) -> TestInterface { - return cloneInterface(interface: interface); -} -let interface2Clone = funcThatClonesInterface( - interface: cloneInterface(interface: interface) -); -let _ = interface.getValue(); -// Check that only the 2 actual references remain after the dust clears -assert(interface.refCount() == 2); - -// Test that the argument names get mapped to camelCase -let _ = interface.methodWithMultiWordArg(theArgument: "test") - diff --git a/uniffi/bindgen-tests/swift/tests/options.swift b/uniffi/bindgen-tests/swift/tests/options.swift deleted file mode 100644 index a9e484dbf..000000000 --- a/uniffi/bindgen-tests/swift/tests/options.swift +++ /dev/null @@ -1,32 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -assert(roundtripOptionU8(a: 67) == 67); -assert(roundtripOptionU8(a: nil) == nil); -assert(roundtripOptionI8(a: 67) == 67); -assert(roundtripOptionI8(a: nil) == nil); -assert(roundtripOptionU16(a: 67) == 67); -assert(roundtripOptionU16(a: nil) == nil); -assert(roundtripOptionI16(a: 67) == 67); -assert(roundtripOptionI16(a: nil) == nil); -assert(roundtripOptionU32(a: 67) == 67); -assert(roundtripOptionU32(a: nil) == nil); -assert(roundtripOptionI32(a: 67) == 67); -assert(roundtripOptionI32(a: nil) == nil); -assert(roundtripOptionU64(a: 67) == 67); -assert(roundtripOptionU64(a: nil) == nil); -assert(roundtripOptionI64(a: 67) == 67); -assert(roundtripOptionI64(a: nil) == nil); -assert(roundtripOptionF32(a: 67.0) == 67.0); -assert(roundtripOptionF32(a: nil) == nil); -assert(roundtripOptionF64(a: 67.0) == 67.0); -assert(roundtripOptionF64(a: nil) == nil); -assert(roundtripOptionBool(a: true) == true); -assert(roundtripOptionBool(a: nil) == nil); -assert(roundtripOptionString(a: "test-string") == "test-string"); -assert(roundtripOptionString(a: nil) == nil); -assert(roundtripOptionRec(a: OptionsRec(a: 67)) == OptionsRec(a: 67)) -assert(roundtripOptionRec(a: nil) == nil); diff --git a/uniffi/bindgen-tests/swift/tests/primitive_types.swift b/uniffi/bindgen-tests/swift/tests/primitive_types.swift deleted file mode 100644 index e2a2807e2..000000000 --- a/uniffi/bindgen-tests/swift/tests/primitive_types.swift +++ /dev/null @@ -1,55 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -// Test passing values to Rust -inputU8(a: 42) -inputI8(a: -42) -inputU16(a: 42) -inputI16(a: -42) -inputU32(a: 42) -inputI32(a: -42) -inputU64(a: 42) -inputI64(a: -42) -inputF32(a: 0.5) -inputF64(a: -3.5) -inputBool(a: true) -inputString(a: "ABC") -// Test returning values to Swift -assert(outputU8() == 1); -assert(outputI8() == 1); -assert(outputU16() == 1); -assert(outputI16() == 1); -assert(outputU32() == 1); -assert(outputI32() == 1); -assert(outputU64() == 1); -assert(outputI64() == 1); -assert(outputF32() == 1.0); -assert(outputF64() == 1.0); -assert(outputBool() == true); -assert(outputString() == "test-string"); -// Test calling and returning a single argument -assert(roundtripU8(a: 42) == 42); -assert(roundtripI8(a: -42) == -42); -assert(roundtripU16(a: 42) == 42); -assert(roundtripI16(a: -42) == -42); -assert(roundtripU32(a: 42) == 42); -assert(roundtripI32(a: -42) == -42); -assert(roundtripU64(a: 42) == 42); -assert(roundtripI64(a: -42) == -42); -assert(roundtripF32(a: 0.5) == 0.5); -assert(roundtripF64(a: -3.5) == -3.5); -assert(roundtripBool(a: true) == true); -assert(roundtripString(a: "ABC") == "ABC"); -// Test calling a function with lots of args -// This function will sum up all the numbers, then negate the value since we passed in `true` -assert(sumWithManyTypes(a: 1, b: -2, c: 3, d: -4, e: 5, f: -6, g: 7, h: -8, i: 9.5, j: -10.5, negate: true) == 5); - -// Test that the argument names get mapped to camelCase -let _ = funcWithMultiWordArg(theArgument: 16) - -// `String(bytes:encoding:.utf8)` strips a leading U+FEFF via Foundation's -// NSString decoder; assert the lift/read paths preserve it instead. -assert(stringWithBom() == "\u{feff}hello") diff --git a/uniffi/bindgen-tests/swift/tests/records.swift b/uniffi/bindgen-tests/swift/tests/records.swift deleted file mode 100644 index 1dd39c230..000000000 --- a/uniffi/bindgen-tests/swift/tests/records.swift +++ /dev/null @@ -1,41 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -assert(roundtripSimpleRec(rec: SimpleRec(a: 42)) == SimpleRec(a: 42)) -assert(UnitRec() == UnitRec()) -assert( - roundtripComplexRec( - rec: ComplexRec( - fieldU8: 0, - fieldI8: -1, - fieldU16: 2, - fieldI16: -3, - fieldU32: 4, - fieldI32: -5, - fieldU64: 6, - fieldI64: -7, - fieldF32: 8.5, - fieldF64: 9.5, - fieldString: "test", - fieldRec: SimpleRec(a: 42) - ) - ) == ComplexRec( - fieldU8: 0, - fieldI8: -1, - fieldU16: 2, - fieldI16: -3, - fieldU32: 4, - fieldI32: -5, - fieldU64: 6, - fieldI64: -7, - fieldF32: 8.5, - fieldF64: 9.5, - fieldString: "test", - fieldRec: SimpleRec(a: 42) - ) -) -// methods -assert(SimpleRec(a: 42).roundtrip() == SimpleRec(a: 42)) diff --git a/uniffi/bindgen-tests/swift/tests/recursive_types.swift b/uniffi/bindgen-tests/swift/tests/recursive_types.swift deleted file mode 100644 index 079e9b9ef..000000000 --- a/uniffi/bindgen-tests/swift/tests/recursive_types.swift +++ /dev/null @@ -1,78 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -// Tree (self-recursive) -let leaf = Tree.leaf(5) -assert(sumTree(tree: leaf) == 5) - -let node = Tree.node(left: Tree.leaf(3), right: Tree.leaf(4)) -assert(sumTree(tree: node) == 7) - -let deep = Tree.node( - left: Tree.node(left: Tree.leaf(1), right: Tree.leaf(2)), - right: Tree.leaf(10) -) -assert(sumTree(tree: deep) == 13) - -// Expr / BoolExpr (mutually recursive) -assert(evalExpr(expr: Expr.lit(42)) == 42) - -// BoolExpr.isZero is true when expr evaluates to zero — takes the `then` branch -let ifTrue = Expr.`if`( - cond: BoolExpr.isZero(Expr.lit(0)), - then: Expr.lit(1), - else: Expr.lit(2) -) -assert(evalExpr(expr: ifTrue) == 1) - -// BoolExpr.isZero is false when expr is nonzero — takes the `else` branch -let ifFalse = Expr.`if`( - cond: BoolExpr.isZero(Expr.lit(5)), - then: Expr.lit(1), - else: Expr.lit(2) -) -assert(evalExpr(expr: ifFalse) == 2) - -// BoolExpr.not wraps another BoolExpr -assert(evalBool(expr: BoolExpr.not(BoolExpr.`true`)) == false) -assert(evalBool(expr: BoolExpr.not(BoolExpr.`false`)) == true) - -// LinkedList (cycle through Optional: Cons.tail is LinkedList?) -assert(listSum(list: .`nil`) == 0) -assert(listSum(list: .cons(head: 5, tail: nil)) == 5) -assert(listSum(list: .cons(head: 3, tail: .cons(head: 4, tail: nil))) == 7) - -// Trie (cycle through Map value: Branch.children is [String: Trie]) -assert(trieSum(trie: .leaf(5)) == 5) -assert(trieSum(trie: .branch(children: [:])) == 0) -assert(trieSum(trie: .branch(children: ["a": .leaf(1), "b": .leaf(2)])) == 3) -assert(trieSum(trie: .branch(children: ["x": .branch(children: ["y": .leaf(7)])])) == 7) - -// RoseTree (cycle through a record: RoseTree → RoseData → [RoseTree]) -assert(sumRoseTree(tree: RoseTree.leaf(7)) == 7) - -assert(sumRoseTree(tree: RoseTree.branch(RoseData(value: 10, children: []))) == 10) - -assert(sumRoseTree(tree: RoseTree.branch( - RoseData(value: 1, children: [RoseTree.leaf(2), RoseTree.leaf(3)]) -)) == 6) - -assert(sumRoseTree(tree: RoseTree.branch(RoseData( - value: 1, - children: [ - RoseTree.branch(RoseData(value: 2, children: [RoseTree.leaf(3)])), - RoseTree.leaf(4), - ] -))) == 10) - -// EvalError (recursive error enum) -assert((try? maybeThrowError(shouldThrow: false)) == 42) -do { - _ = try maybeThrowError(shouldThrow: true) - assert(false, "expected EvalError to be thrown") -} catch { - // recursive error enum compiled and is throwable -} diff --git a/uniffi/bindgen-tests/swift/tests/references.swift b/uniffi/bindgen-tests/swift/tests/references.swift deleted file mode 100644 index 9c23c7b80..000000000 --- a/uniffi/bindgen-tests/swift/tests/references.swift +++ /dev/null @@ -1,14 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -assert(roundtripU8Ref(a: 2) == 2) - -let interface = ReferenceTestInterface() -assert(interface.doubleValue(a: 2) == 4) -assert(callDoubleValue(i: interface, a: 3) == 6) - -let traitInterface = createReferenceTestTraitInterface() -assert(callTripleValueTraitInterface(t: traitInterface, a: 10) == 30) diff --git a/uniffi/bindgen-tests/swift/tests/renames.swift b/uniffi/bindgen-tests/swift/tests/renames.swift deleted file mode 100644 index 36928ab15..000000000 --- a/uniffi/bindgen-tests/swift/tests/renames.swift +++ /dev/null @@ -1,70 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -// Test renamed types - should be accessible by their custom names -let record = RenamedRecord(item: 42) -assert(record.item == 42) - -let enum1 = RenamedEnum.renamedVariant -let enum2 = RenamedEnum.record(record) - -// Test renamed function -let result = renamedFunction(record: record) -if case .record(let recordResult) = result { - assert(recordResult.item == 42) -} - -// Test renamed object with renamed constructor and method -let obj = RenamedObject.renamedConstructor(value: 123) -let methodResult = obj.renamedMethod() -assert(methodResult == 123) - -// Test trait method renaming (trait itself keeps original name) -let traitImpl = createTraitImpl(multiplier: 5) -assert(traitImpl.renamedTraitMethod(value: 10) == 50) // 10 * 5 - -// Test TOML-based renaming for Swift -// These use the Swift-specific renames from uniffi.toml - -// Test renamed record via TOML -let swiftRecord = SwiftRecord(swiftItem: 100) -assert(swiftRecord.swiftItem == 100) - -// Test renamed enum via TOML -let swiftEnum1 = SwiftEnum.swiftVariantA -let swiftEnum2 = SwiftEnum.swiftRecord(swiftRecord) -let swiftEnum3 = SwiftEnumWithFields.swiftVariantA(swiftInt: 1) - -// Test renamed function with renamed argument via TOML -let swiftResult = try swiftFunction(swiftRecord: swiftRecord) -if case .swiftRecord(let recordResult) = swiftResult { - assert(recordResult.swiftItem == 100) -} - -// Test that we can also get an error from the function -do { - let _ = try swiftFunction(swiftRecord: nil) - fatalError("Should have thrown an error") -} catch let error as SwiftError { - if case .SwiftSimple = error { - // Expected - } else { - fatalError("Wrong error type") - } -} - -// Test renamed object with renamed method and argument via TOML -let swiftObj = SwiftObject(value: 200) -do { - let swiftMethodResult = try swiftObj.swiftMethod(swiftArg: 50) - assert(swiftMethodResult == 250) // 200 + 50 -} catch { - fatalError("Should not have thrown an error") -} - -// Test renamed trait with renamed method via TOML -let swiftTraitImpl = createBindingTraitToRenameImpl(multiplier: 3) -assert(swiftTraitImpl.swiftTraitMethod(value: 7) == 21) // 7 * 3 diff --git a/uniffi/bindgen-tests/swift/tests/rust_traits.swift b/uniffi/bindgen-tests/swift/tests/rust_traits.swift deleted file mode 100644 index f61891414..000000000 --- a/uniffi/bindgen-tests/swift/tests/rust_traits.swift +++ /dev/null @@ -1,21 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -assert(RustTraitTest(a: 1, b: 2).debugDescription == "debug-test-string") -assert(RustTraitTest(a: 1, b: 2).description == "display-test-string") - -// The Rust code only uses `a` for the equality -assert(RustTraitTest(a: 1, b: 2) == RustTraitTest(a: 1, b: 3)) -assert(RustTraitTest(a: 1, b: 2) != RustTraitTest(a: 2, b: 2)) - -// The Rust code only uses `a` for the ordering -assert(RustTraitTest(a: 1, b: 2) < RustTraitTest(a: 2, b: 3)) -assert(RustTraitTest(a: 1, b: 2) <= RustTraitTest(a: 1, b: 3) - && RustTraitTest(a: 1, b: 2) >= RustTraitTest(a: 1, b: 3)) - -// The Rust code only uses `a` for the hash -assert(RustTraitTest(a: 1, b: 2).hashValue == RustTraitTest(a: 1, b: 3).hashValue) -assert(RustTraitTest(a: 2, b: 2).hashValue != RustTraitTest(a: 1, b: 2).hashValue) diff --git a/uniffi/bindgen-tests/swift/tests/simple_fns.swift b/uniffi/bindgen-tests/swift/tests/simple_fns.swift deleted file mode 100644 index c3c34ca5c..000000000 --- a/uniffi/bindgen-tests/swift/tests/simple_fns.swift +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests - -testFunc() - -// Unfortunately there's no way to test unexpected errors. -// In swift, they're always fatal. diff --git a/uniffi/bindgen-tests/swift/tests/time.swift b/uniffi/bindgen-tests/swift/tests/time.swift deleted file mode 100644 index 9eed4f0e8..000000000 --- a/uniffi/bindgen-tests/swift/tests/time.swift +++ /dev/null @@ -1,12 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi_bindgen_tests -import Foundation - -let now = Date() -assert( - abs(roundtripSystemtime(a: now).timeIntervalSinceReferenceDate - now.timeIntervalSinceReferenceDate) < 1 -); -assert(roundtripDuration(a: TimeInterval(100)) == TimeInterval(100)); diff --git a/uniffi/bindgen-tests/swift/tests/trait_interfaces.swift b/uniffi/bindgen-tests/swift/tests/trait_interfaces.swift deleted file mode 100644 index 3a690c213..000000000 --- a/uniffi/bindgen-tests/swift/tests/trait_interfaces.swift +++ /dev/null @@ -1,261 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation -import uniffi_bindgen_tests - -var dispatchGroup = DispatchGroup() -var traitRefCount = 0; - -class TraitImpl: TestTraitInterface, @unchecked Sendable { - var value: UInt32; - - init(value: UInt32) { - self.value = value; - traitRefCount += 1 - } - - deinit { - traitRefCount -= 1 - } - - func noop() { } - - func getValue() -> UInt32 { - return self.value; - } - - func setValue(value: UInt32) { - self.value = value; - } - - func throwIfEqual(numbers: CallbackInterfaceNumbers) throws -> CallbackInterfaceNumbers { - if numbers.a == numbers.b { - throw TestError.Failure1 - } - return numbers - } - - func roundtripRecord(value: SimpleRec) -> SimpleRec { value } - - func roundtripEnum(value: EnumWithData) -> EnumWithData { value } - - func roundtripInterface(value: TestInterface) -> TestInterface { value } -} - -// Test calling the Rust impl from Swift -func testRustImpl(traitImpl: TestTraitInterface) { - traitImpl.noop(); - assert(traitImpl.getValue() == 42) - traitImpl.setValue(value: 43); - assert(traitImpl.getValue() == 43) - do { - let _ = try traitImpl.throwIfEqual(numbers: CallbackInterfaceNumbers(a: 10, b: 10)) - fatalError("expected throwIfEqual to throw") - } catch TestError.Failure1 { - // expected - } catch { - fatalError("unexpected error \(error)") - } - - assert( - try! traitImpl.throwIfEqual(numbers: CallbackInterfaceNumbers(a: 10, b: 11)) == - CallbackInterfaceNumbers(a: 10, b: 11)) - - assert(traitImpl.roundtripRecord(value: SimpleRec(a: 10)) == SimpleRec(a: 10)) - assert( - traitImpl.roundtripEnum(value: EnumWithData.a(value: 10, value2: 20)) == - EnumWithData.a(value: 10, value2: 20)) - assert(traitImpl.roundtripInterface(value: TestInterface(value: 20)).getValue() == 20) -} - -testRustImpl(traitImpl: createTestTraitInterface(value: 42)) -testRustImpl(traitImpl: roundtripTestTraitInterface(interface: createTestTraitInterface(value: 42))) -testRustImpl(traitImpl: roundtripTestTraitInterfaceList(interfaces: [createTestTraitInterface(value: 42)])[0]) - -// Test calling the Swift impl by roundtripping it through a Rust function -func testSwiftImpl(traitImpl: TestTraitInterface) { - invokeTestTraitInterfaceNoop(interface: traitImpl) - assert(invokeTestTraitInterfaceGetValue(interface: traitImpl) == 42) - invokeTestTraitInterfaceSetValue(interface: traitImpl, value: 43) - assert(invokeTestTraitInterfaceGetValue(interface: traitImpl) == 43) - do { - let _ = try invokeTestTraitInterfaceThrowIfEqual( - interface: traitImpl, - numbers: CallbackInterfaceNumbers(a: 10, b: 10) - ) - fatalError("expected throwIfEqual to throw") - } catch TestError.Failure1 { - // expected - } catch { - fatalError("unexpected error \(error)") - } - - assert( - try! invokeTestTraitInterfaceThrowIfEqual( - interface: traitImpl, - numbers: CallbackInterfaceNumbers(a: 10, b: 11) - ) == CallbackInterfaceNumbers(a: 10, b: 11)) - - assert( - invokeTestTraitInterfaceRoundtripRecord(interface: traitImpl, rec: SimpleRec(a: 10)) == - SimpleRec(a: 10)) - assert( - invokeTestTraitInterfaceRoundtripEnum(interface: traitImpl, en: EnumWithData.a(value: 10, value2: 20)) == - EnumWithData.a(value: 10, value2: 20)) - assert(invokeTestTraitInterfaceRoundtripInterface(interface: traitImpl, iface: TestInterface(value: 20)).getValue() == 20) -} - -testSwiftImpl(traitImpl: TraitImpl(value: 42)) -testSwiftImpl(traitImpl: roundtripTestTraitInterface(interface: TraitImpl(value: 42))) -testSwiftImpl(traitImpl: roundtripTestTraitInterfaceList(interfaces: [TraitImpl(value: 42)])[0]) - -var asyncTraitRefCount = 0; - -class AsyncTraitImpl: AsyncTestTraitInterface, @unchecked Sendable { - var value: UInt32; - - init(value: UInt32) { - self.value = value; - asyncTraitRefCount += 1 - } - - deinit { - asyncTraitRefCount -= 1 - } - - func noop() async { } - - func getValue() async -> UInt32 { - return self.value; - } - - func setValue(value: UInt32) async { - self.value = value; - } - - func throwIfEqual(numbers: CallbackInterfaceNumbers) async throws -> CallbackInterfaceNumbers { - if numbers.a == numbers.b { - throw TestError.Failure1 - } - return numbers - } -} - -func testAsyncRustImpl(traitImpl: AsyncTestTraitInterface) async { - await traitImpl.noop(); - var valueReturn = await traitImpl.getValue(); - assert(valueReturn == 42) - await traitImpl.setValue(value: 43); - valueReturn = await traitImpl.getValue(); - assert(valueReturn == 43) - do { - let _ = try await traitImpl.throwIfEqual(numbers: CallbackInterfaceNumbers(a: 10, b: 10)) - fatalError("expected throwIfEqual to throw") - } catch TestError.Failure1 { - // expected - } catch { - fatalError("unexpected error \(error)") - } - - let numbersReturn = try! await traitImpl.throwIfEqual(numbers: CallbackInterfaceNumbers(a: 10, b: 11)) - assert(numbersReturn == CallbackInterfaceNumbers(a: 10, b: 11)) -} - -dispatchGroup.enter() -Task { - await testAsyncRustImpl(traitImpl: createAsyncTestTraitInterface(value: 42)) - await testAsyncRustImpl(traitImpl: roundtripAsyncTestTraitInterface(interface: createAsyncTestTraitInterface(value: 42))) - await testAsyncRustImpl(traitImpl: roundtripAsyncTestTraitInterfaceList(interfaces: [createAsyncTestTraitInterface(value: 42)])[0]) - dispatchGroup.leave() -} -dispatchGroup.wait() - -func testAsyncSwiftImpl(traitImpl: AsyncTestTraitInterface) async { - await invokeAsyncTestTraitInterfaceNoop(interface: traitImpl) - var val = await invokeAsyncTestTraitInterfaceGetValue(interface: traitImpl) - assert(val == 42) - await invokeAsyncTestTraitInterfaceSetValue(interface: traitImpl, value: 43) - val = await invokeAsyncTestTraitInterfaceGetValue(interface: traitImpl) - assert(val == 43) - do { - let _ = try await invokeAsyncTestTraitInterfaceThrowIfEqual( - interface: traitImpl, - numbers: CallbackInterfaceNumbers(a: 10, b: 10) - ) - fatalError("expected throwIfEqual to throw") - } catch TestError.Failure1 { - // expected - } catch { - fatalError("unexpected error \(error)") - } - - let numbersReturn = try! await invokeAsyncTestTraitInterfaceThrowIfEqual( - interface: traitImpl, - numbers: CallbackInterfaceNumbers(a: 10, b: 11) - ) - assert(numbersReturn == CallbackInterfaceNumbers(a: 10, b: 11)) -} - -dispatchGroup.enter() -Task { - await testAsyncSwiftImpl(traitImpl: AsyncTraitImpl(value: 42)) - await testAsyncSwiftImpl(traitImpl: roundtripAsyncTestTraitInterface(interface: AsyncTraitImpl(value: 42))) - await testAsyncSwiftImpl(traitImpl: roundtripAsyncTestTraitInterfaceList(interfaces: [AsyncTraitImpl(value: 42)])[0]) - dispatchGroup.leave() -} -dispatchGroup.wait() - -// The previous calls created and destroyed a ton of references to the Swift-implemented trait -// interfaces, check that the refcounts have gone back to 0. -assert(traitRefCount == 0) -assert(asyncTraitRefCount == 0) - -// Rust-only trait: smoke-test for the #[uniffi::export(rust)] codegen path -func testRustOnlyImpl(impl: TestRustOnlyTraitInterface) { - do { - let _ = try impl.throwIfEqual(numbers: CallbackInterfaceNumbers(a: 10, b: 10)) - fatalError("expected throwIfEqual to throw") - } catch TestError.Failure1 { - // expected - } catch { - fatalError("unexpected error \(error)") - } - assert( - try! impl.throwIfEqual(numbers: CallbackInterfaceNumbers(a: 10, b: 11)) == CallbackInterfaceNumbers(a: 10, b: 11)) -} - -testRustOnlyImpl(impl: createRustOnlyTestTraitInterface()) - -// Foreign-only trait: smoke-test for the #[uniffi::export(foreign)] codegen path -class ForeignOnlyImpl: TestForeignOnlyTraitInterface, @unchecked Sendable { - func throwIfEqual(numbers: CallbackInterfaceNumbers) throws -> CallbackInterfaceNumbers { - if numbers.a == numbers.b { - throw TestError.Failure1 - } - return numbers - } -} - -func testForeignOnlyImpl(impl: TestForeignOnlyTraitInterface) { - do { - let _ = try invokeTestForeignOnlyTraitThrowIfEqual( - interface: impl, - numbers: CallbackInterfaceNumbers(a: 10, b: 10) - ) - fatalError("expected throwIfEqual to throw") - } catch TestError.Failure1 { - // expected - } catch { - fatalError("unexpected error \(error)") - } - assert( - try! invokeTestForeignOnlyTraitThrowIfEqual( - interface: impl, - numbers: CallbackInterfaceNumbers(a: 10, b: 11) - ) == CallbackInterfaceNumbers(a: 10, b: 11)) -} - -testForeignOnlyImpl(impl: ForeignOnlyImpl()) -testForeignOnlyImpl(impl: roundtripTestForeignOnlyTrait(interface: ForeignOnlyImpl())) diff --git a/uniffi/cpp/LICENSE b/uniffi/cpp/LICENSE deleted file mode 100644 index fa0086a95..000000000 --- a/uniffi/cpp/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. \ No newline at end of file diff --git a/uniffi/cpp/README.md b/uniffi/cpp/README.md deleted file mode 100644 index a125e7fdb..000000000 --- a/uniffi/cpp/README.md +++ /dev/null @@ -1,102 +0,0 @@ -# uniffi-bindgen-cpp - UniFFI C++ and C bindings generator - -Generate bindings for C++, or C with `--lang c`. See [the fork's README](../README.md) for how to -build it and where it came from. - -# How to generate bindings - -## Generating with a single UDL file - -```bash -uniffi-bindgen-cpp path/to/definitions.udl -``` - -## Generating using a library file - -```bash -uniffi-bindgen-cpp --library your_rust_library.so --out-dir output_directory -``` - -Regardless of the generation method, these files are produced: - -* `path/to/definitions.hpp` -* `path/to/definitions.cpp` -* `path/to/definitions_scaffolding.hpp` - -# How to integrate bindings - -To integrate the bindings into your projects, simply add the generated bindings files to your project. -C++17 or newer is required to compile the bindings. - -Async calls need `error_style = "expected"` (see [the configuration](docs/CONFIGURATION.md)); the -default exceptions style refuses to generate them. An async call returns a move-only -`uniffi::Future`. It supports `get()`, `wait()`, `wait_for()`, and `cancel()`. Destroying an -incomplete future cancels it and releases the Rust future. - -To adapt without a blocking waiter thread, consume the future with -`std::move(future).then(executor, callback)`. The returned `uniffi::FutureContinuation` owns -cancellation until completion. Destroying that token early cancels the Rust operation. - -Rust-future continuations use one background dispatcher by default. Before making any async -call, applications can call `uniffi::set_async_dispatcher(dispatch, shutdown)` to use their own -executor. Before unloading the executor or generated bindings, call -`uniffi::shutdown_async_dispatcher()`; it rejects new continuations and waits for the registered -shutdown function to drain accepted work. - -# C bindings - -`--lang c` generates a C11 header, `.h`, over the C++ bindings. It writes the -C++ bindings in the `error_style = "expected"` style too, plus `_c.cpp`, which -converts between the two. Compile `.cpp` and `_c.cpp` as C++17 (exceptions -and RTTI may be off) and include only `.h` from C. - -```bash -uniffi-bindgen-cpp --lang c --library your_rust_library.so --out-dir output_directory -``` - -Names follow GLib: functions are snake_case and types CamelCase, both starting with the -namespace unless the uniffi name already does, since every crate's C API shares one scope. In -namespace `app`, `MyObject` is `AppMyObject *`, created with `app_my_object_new` and released -with `app_my_object_free`, and its method `do_thing` is `app_my_object_do_thing`, which a record -`MyObjectDoThing` (`AppMyObjectDoThing`) never meets. `AppObject` stays `AppObject`, and types are -re-cased from snake case, so `HTTPServer` is `AppHttpServer`. Two items that still render one -name, such as `AppObject` and `Object`, or a method `free` and the release function, are refused -with both named. The rest follows from a few rules: - -* A call that can fail returns an error struct, or NULL on success, and writes its result to a - trailing `out` pointer. An error is a tagged union with a `message`; free it with `_free`. -* Records are plain structs, data-carrying enums are a `tag` plus an anonymous union of - `` structs (`shape->circle.radius`), and flat enums are C enums. A record - with `#[uniffi(default)]` fields gets `_default()`. -* Arguments are borrowed for the call. Everything returned is owned by the caller and freed with - the matching `_free` (`_string_free` for strings). -* Optional strings, objects, and structs are pointers that are NULL when absent; optional scalars - are `{ has_value, value }` structs. Bytes, lists, and maps are pointer and length structs. -* An async call takes a callback, typed as the function's name in CamelCase plus `Callback` - (`AppMyObjectDoThingCallback`), and `user_data`, and returns a `Task *`, never NULL. - The callback runs exactly once on the dispatcher, with the result, which it owns, or with - `cancelled` set and no result when the task was freed first, so `user_data` is released in - one place. Free every task: freeing one whose callback has not started cancels the Rust - future. A dispatcher that refuses the work or has shut down abandons the call, and its - callback never runs. -* Callbacks run on the default dispatcher thread unless `_set_dispatcher` installs a - host's own, which receives `Work *` items to run with `_work_run`. -* A type from another crate keeps that crate's C name and `_free`, and its header is included. - Generate the C API of every crate involved (one `--crate` each, or all at once) and compile - each one's `.cpp` and `_c.cpp`; a crate's implementation converts its - own types for the others. - -The C backend refuses what it cannot render faithfully, such as callback interfaces, custom -types, timestamps, durations, and exported traits other than `Display` on errors, including in -another crate whose types it uses. - -# Configuration options - -It's possible to [configure some settings](docs/CONFIGURATION.md) by passing `--config` -argument to the generator. - -Note: configuration is not supported when using library mode - -```bash -uniffi-bindgen-cpp path/to/definitions.udl --config path/to/uniffi.toml -``` diff --git a/uniffi/cpp/bindgen/Cargo.toml b/uniffi/cpp/bindgen/Cargo.toml deleted file mode 100644 index bd9f223e1..000000000 --- a/uniffi/cpp/bindgen/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "uniffi-bindgen-cpp" -version = "0.1.0" -publish = false -edition = "2021" - -[dependencies] -anyhow = "1.0.75" -askama = "0.13.0" -camino = "1.1.6" -clap = { version = "4.4.2", features = ["derive"] } -heck = "0.4.1" -paste = "1" -serde = "1" -topological-sort = "0.2.2" -textwrap = "0.16.0" -toml = "1" -uniffi_bindgen = { workspace = true } diff --git a/uniffi/cpp/bindgen/askama.toml b/uniffi/cpp/bindgen/askama.toml deleted file mode 100644 index da62cf27a..000000000 --- a/uniffi/cpp/bindgen/askama.toml +++ /dev/null @@ -1,5 +0,0 @@ -[general] -dirs = ["src/bindings/cpp/templates", "src/bindings/c/templates"] - -[[syntax]] -name = "cpp" diff --git a/uniffi/cpp/bindgen/src/bindings/c/gen_c.rs b/uniffi/cpp/bindgen/src/bindings/c/gen_c.rs deleted file mode 100644 index b0c07872a..000000000 --- a/uniffi/cpp/bindgen/src/bindings/c/gen_c.rs +++ /dev/null @@ -1,1799 +0,0 @@ -//! Renders the C header and its C++ implementation. -//! -//! Every uniffi type maps to one C "field" type, used in struct members and lists, plus how it -//! is passed in (borrowed) and handed back (owned). Each type also gets three internal C++ -//! converters named after its canonical name: `to_c_X` builds the owned C value from the C++ -//! one, `from_c_X` builds the C++ value from a borrowed C one, and `free_c_X` releases what -//! `to_c_X` allocated. - -use std::collections::{BTreeMap, BTreeSet}; -use std::fmt::Write; - -use anyhow::{bail, Context, Result}; -use askama::Template; -use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase}; -use uniffi_bindgen::{ - interface::{ - AsType, Callable, DefaultValue, Enum, Field, Literal, Object, Radix, Record, Type, - }, - ComponentInterface, -}; - -use crate::bindings::cpp::gen_cpp::{ - filters::{self, CppCodeOracle}, - Config, -}; - -pub(crate) struct Bindings { - pub(crate) header: String, - pub(crate) source: String, -} - -#[derive(Template)] -#[template(syntax = "cpp", escape = "none", path = "c_header.h")] -struct Header<'a> { - ns: &'a str, - /// The namespace in CamelCase, which starts the runtime's type names. - ty: &'a str, - guard: String, - /// The namespaces whose headers declare the external types this one uses. - includes: Vec, - body: &'a str, -} - -#[derive(Template)] -#[template(syntax = "cpp", escape = "none", path = "c_source.cpp")] -struct Source<'a> { - ns: &'a str, - ty: &'a str, - namespace: &'a str, - objects: &'a str, - externals: &'a str, - converters: &'a str, - body: &'a str, -} - -/// Refuses whatever the C backend cannot render correctly, before anything is written. -pub(crate) fn check_supported(ci: &ComponentInterface, config: &Config) -> Result<()> { - Gen::new(ci, config).check_supported() -} - -/// Renders the C API. Must run after the C++ bindings were rendered in the expected style -/// on this thread, because the C++ type labels it reuses depend on that style. -pub(crate) fn generate(ci: &ComponentInterface, config: &Config) -> Result { - let mut gen = Gen::new(ci, config); - - let mut header = String::new(); - let mut source = String::new(); - gen.render(&mut header, &mut source)?; - - let mut objects = String::new(); - for obj in ci.object_definitions() { - let c = type_name(&prefixed(&gen.ns, obj.name())); - let class = CppCodeOracle.class_name(obj.name()); - writeln!( - objects, - "struct {c} {{\n std::shared_ptr<::{}::{class}> inner;\n}};", - ci.namespace() - )?; - } - - let mut converters = String::new(); - let mut externals = String::new(); - gen.render_converters(&mut converters, &mut externals)?; - - let ns = gen.ns.clone(); - let ty = type_name(&ns); - let header = Header { - ns: &ns, - ty: &ty, - guard: format!("UNIFFI_{}_H", ns.to_shouty_snake_case()), - includes: gen.external_namespaces(), - body: header.trim_end(), - } - .render() - .context("rendering the C header failed")?; - let source = Source { - ns: &ns, - ty: &ty, - namespace: ci.namespace(), - objects: objects.trim_end(), - externals: externals.trim_end(), - converters: converters.trim_end(), - body: source.trim_end(), - } - .render() - .context("rendering the C implementation failed")?; - - // Askama drops the final newline. - Ok(Bindings { - header: header + "\n", - source: source + "\n", - }) -} - -#[derive(Clone, Debug)] -enum Kind { - Scalar, - FlatEnum, - String, - Bytes, - Record, - DataEnum, - Object, - /// An optional string, object, or struct: a pointer that is NULL when absent. - Optional(Box), - /// An optional scalar or flat enum: a `{ has_value, value }` struct. - OptionalValue(Box), - List(Box), - Map(Box, Box), -} - -#[derive(Clone, Debug)] -struct CType { - ty: Type, - kind: Kind, - /// The C type name: the scalar, or the struct or enum name in CamelCase. - c: String, - /// The snake-case prefix of the functions this type gets, such as its `_free`. - snake: String, - /// The C++ type the bindings use, relative to their namespace. - cpp: String, - /// Unique per type; names the converters. - canon: String, - /// Names the type inside a compound type's C name. - slug: String, - /// For a type from another crate, that crate's namespace and the canonical name its own - /// converters use: that crate's C API declares the type, and its C implementation converts it. - external: Option<(String, String)>, -} - -impl CType { - /// The owned representation, used for struct members and list items. - fn field(&self) -> String { - match &self.kind { - Kind::Scalar | Kind::FlatEnum | Kind::OptionalValue(_) => self.c.clone(), - Kind::String => "const char *".into(), - Kind::Bytes | Kind::Record | Kind::DataEnum | Kind::List(_) | Kind::Map(..) => { - self.c.clone() - } - Kind::Object => format!("{} *", self.c), - Kind::Optional(inner) => match inner.kind { - Kind::String | Kind::Object => inner.field(), - _ => format!("{} *", inner.field()), - }, - } - } - - /// The borrowed representation the `from_c_X` converter takes. - fn view(&self) -> String { - match &self.kind { - Kind::Scalar - | Kind::FlatEnum - | Kind::OptionalValue(_) - | Kind::String - | Kind::Object => self.field(), - Kind::Bytes | Kind::Record | Kind::DataEnum | Kind::List(_) | Kind::Map(..) => { - format!("const {} &", self.c) - } - Kind::Optional(inner) => match inner.kind { - Kind::String | Kind::Object => inner.field(), - _ => format!("const {} *", inner.field()), - }, - } - } - - /// A struct passed by pointer as an argument, so it must not be NULL. - fn by_pointer(&self) -> bool { - matches!( - self.kind, - Kind::Bytes | Kind::Record | Kind::DataEnum | Kind::List(_) | Kind::Map(..) - ) - } - - /// How an argument of this type is declared. - fn param(&self, name: &str) -> String { - let ty = if self.by_pointer() { - format!("const {} *", self.c) - } else { - self.view() - }; - decl(&ty, name) - } - - /// An argument the C API rejects when NULL. - fn required_pointer(&self) -> bool { - self.by_pointer() || matches!(self.kind, Kind::String | Kind::Object) - } - - /// How a returned value is handed to the caller, who owns it. - fn ret(&self) -> String { - match &self.kind { - Kind::Scalar | Kind::FlatEnum | Kind::OptionalValue(_) => self.c.clone(), - Kind::String => "char *".into(), - Kind::Optional(inner) => match inner.kind { - Kind::String => "char *".into(), - Kind::Object => inner.field(), - _ => format!("{} *", inner.field()), - }, - _ => format!("{} *", self.c), - } - } - - /// This type with its C name qualified from the global namespace, for the converters: they - /// sit in the crate's C++ namespace, whose classes share the C types' CamelCase names. - fn qualified(&self) -> CType { - let mut ct = self.clone(); - ct.kind = match ct.kind { - Kind::Optional(inner) => Kind::Optional(Box::new(inner.qualified())), - Kind::OptionalValue(inner) => Kind::OptionalValue(Box::new(inner.qualified())), - Kind::List(inner) => Kind::List(Box::new(inner.qualified())), - Kind::Map(key, value) => { - Kind::Map(Box::new(key.qualified()), Box::new(value.qualified())) - } - kind => kind, - }; - if !ct.snake.is_empty() { - ct.c = format!("::{}", ct.c); - } - ct - } - - /// The uniffi item this type renders, for errors. - fn item(&self) -> String { - match &self.ty { - Type::Record { name, .. } => format!("record `{name}`"), - Type::Enum { name, .. } => format!("enum `{name}`"), - Type::Object { name, .. } => format!("object `{name}`"), - _ => format!("type `{}`", self.cpp), - } - } - - /// The function that frees a returned value, when the caller owns an allocation. - fn free_fn(&self, ns: &str) -> Option { - match &self.kind { - Kind::Scalar | Kind::FlatEnum | Kind::OptionalValue(_) => None, - Kind::String => Some(format!("{ns}_string_free")), - Kind::Optional(inner) => inner.free_fn(ns), - _ => Some(format!("{}_free", self.snake)), - } - } - - /// Converts a C++ value to what [`Self::ret`] declares. - fn ret_expr(&self, ns: &str, expr: &str) -> String { - let convert = format!("::{ns}::c_detail::to_c_{}({expr})", self.canon); - match &self.kind { - Kind::String => format!("const_cast({convert})"), - Kind::Optional(inner) if matches!(inner.kind, Kind::String) => { - format!("const_cast({convert})") - } - Kind::Bytes | Kind::Record | Kind::DataEnum | Kind::List(_) | Kind::Map(..) => { - format!("::{ns}::c_detail::box({convert})") - } - _ => convert, - } - } -} - -/// Joins a C type and a name, without a space after a pointer. -fn decl(ty: &str, name: &str) -> String { - if ty.ends_with('*') || ty.ends_with('&') { - format!("{ty}{name}") - } else { - format!("{ty} {name}") - } -} - -/// A uniffi name in snake case. -fn c_name(name: &str) -> String { - name.to_snake_case() -} - -/// The snake-case C name of a function, or the base of a type's: its name in snake case, -/// prefixed with the snake-case namespace unless it already is, since every crate's C API shares -/// one global scope. -fn prefixed(ns: &str, name: &str) -> String { - let c = c_name(name); - if c.starts_with(&format!("{ns}_")) { - c - } else { - format!("{ns}_{c}") - } -} - -/// The C name of a type, from its snake-case name: CamelCase, so it never meets a function's. -fn type_name(snake: &str) -> String { - snake.to_upper_camel_case() -} - -fn c_field_name(field: &Field, index: usize) -> String { - if field.name().is_empty() { - format!("v{index}") - } else { - filters::var_name(field.name()).unwrap() - } -} - -fn doc(docstring: Option<&str>, indent: i32) -> String { - match docstring { - Some(docstring) => format!("{}\n", filters::docstring(docstring, &indent).unwrap()), - None => String::new(), - } -} - -/// A one-line comment for something the generator adds. -fn line_doc(text: &str) -> String { - format!("/** {text} */\n") -} - -struct Gen<'a> { - ci: &'a ComponentInterface, - config: &'a Config, - /// The prefix of the runtime symbols: the namespace in snake case. - ns: String, - /// Every type a converter is emitted for, by canonical name. - types: BTreeMap, - /// Every global C identifier and the item that claimed it, to refuse a collision instead of - /// emitting one. - names: BTreeMap, - /// The crates whose types this one uses, each checked once for C support. - externals: BTreeSet, -} - -impl<'a> Gen<'a> { - fn new(ci: &'a ComponentInterface, config: &'a Config) -> Self { - Self { - ci, - config, - ns: ci.namespace().to_snake_case(), - types: BTreeMap::new(), - names: BTreeMap::new(), - externals: BTreeSet::new(), - } - } - - /// The namespaces of the crates whose types this one uses. - fn external_namespaces(&self) -> Vec { - self.types - .values() - .filter_map(|ct| ct.external.as_ref()) - .map(|(namespace, _)| namespace.clone()) - .collect::>() - .into_iter() - .collect() - } - - /// Registers `name` for `item`, which describes the uniffi item the name renders. - fn claim(&mut self, name: &str, item: &str) -> Result<()> { - if let Some(other) = self.names.insert(name.to_string(), item.to_string()) { - bail!("the C backend names both {other} and {item} `{name}`; rename one of them"); - } - Ok(()) - } - - /// Refuses whatever this backend cannot render correctly, before rendering anything. - fn check_supported(&self) -> Result<()> { - if let Some(cbi) = self.ci.callback_interface_definitions().first() { - bail!( - "the C backend does not support callback interfaces, but `{}` is one", - cbi.name() - ); - } - for obj in self.ci.object_definitions() { - if obj.has_callback_interface() { - bail!( - "the C backend does not support foreign-implemented traits, but `{}` is one", - obj.name() - ); - } - if let Some(t) = obj.uniffi_traits().first() { - bail!( - "the C backend does not support exported traits on objects yet, but `{}` exports {t:?}", - obj.name() - ); - } - if self.ci.is_used_as_error(obj) { - bail!( - "the C backend does not support objects as errors, but `{}` is one", - obj.name() - ); - } - } - for rec in self.ci.record_definitions() { - if !rec.methods().is_empty() || !rec.constructors().is_empty() { - bail!( - "the C backend does not support methods on records yet, but `{}` has some", - rec.name() - ); - } - if !rec.has_fields() { - bail!( - "the C backend does not support empty records, but `{}` is one", - rec.name() - ); - } - let traits = rec.uniffi_trait_methods(); - if traits.display_fmt.is_some() - || traits.debug_fmt.is_some() - || traits.eq_eq.is_some() - || traits.hash_hash.is_some() - || traits.ord_cmp.is_some() - { - bail!( - "the C backend does not support exported traits on records yet, but `{}` exports some", - rec.name() - ); - } - } - for e in self.ci.enum_definitions() { - if !e.methods().is_empty() || !e.constructors().is_empty() { - bail!( - "the C backend does not support methods on enums yet, but `{}` has some", - e.name() - ); - } - let traits = e.uniffi_trait_methods(); - // An error's Display output is its message; nothing else is rendered. - let display_ok = self.ci.is_used_as_error(e); - if (traits.display_fmt.is_some() && !display_ok) - || traits.debug_fmt.is_some() - || traits.eq_eq.is_some() - || traits.hash_hash.is_some() - || traits.ord_cmp.is_some() - { - bail!( - "the C backend does not support exported traits on enums yet, but `{}` exports some", - e.name() - ); - } - } - Ok(()) - } - - /// Maps a uniffi type, registering it and everything it contains for converters. - fn ctype(&mut self, ty: &Type) -> Result { - let code = CppCodeOracle.find(ty); - let canon = code.canonical_name(self.ci); - if let Some(ct) = self.types.get(&canon) { - return Ok(ct.clone()); - } - let cpp = code.type_label(self.ci); - if self.ci.is_external(ty) { - return self.external_ctype(ty, canon, cpp); - } - let ns = self.ns.clone(); - let named = |name: &str| { - let snake = prefixed(&ns, name); - let slug = snake - .strip_prefix(&format!("{ns}_")) - .unwrap_or(&snake) - .to_string(); - (snake, slug) - }; - let scalar = |c: &str, slug: &str| (Kind::Scalar, c.to_string(), slug.to_string()); - - let (kind, c, slug) = match ty { - Type::UInt8 => scalar("uint8_t", "u8"), - Type::Int8 => scalar("int8_t", "i8"), - Type::UInt16 => scalar("uint16_t", "u16"), - Type::Int16 => scalar("int16_t", "i16"), - Type::UInt32 => scalar("uint32_t", "u32"), - Type::Int32 => scalar("int32_t", "i32"), - Type::UInt64 => scalar("uint64_t", "u64"), - Type::Int64 => scalar("int64_t", "i64"), - Type::Float32 => scalar("float", "f32"), - Type::Float64 => scalar("double", "f64"), - Type::Boolean => scalar("bool", "bool"), - Type::String => (Kind::String, "const char *".into(), "string".into()), - Type::Bytes => (Kind::Bytes, format!("{ns}_bytes"), "bytes".into()), - Type::Record { name, .. } => { - let (c, slug) = named(name); - (Kind::Record, c, slug) - } - Type::Enum { name, .. } => { - let e = self - .ci - .get_enum_definition(name) - .with_context(|| format!("enum `{name}` not found"))?; - let kind = if filters::is_enum_struct(self.ci, ty) { - Kind::DataEnum - } else { - Kind::FlatEnum - }; - if e.variants().is_empty() { - bail!("the C backend does not support empty enums, but `{name}` is one"); - } - let (c, slug) = named(name); - (kind, c, slug) - } - Type::Object { name, .. } => { - let (c, slug) = named(name); - (Kind::Object, c, slug) - } - Type::Optional { inner_type } => { - let inner = self.ctype(inner_type)?; - let slug = format!("optional_{}", inner.slug); - match inner.kind { - Kind::Optional(_) | Kind::OptionalValue(_) => { - bail!("the C backend does not support nested optionals (`{cpp}`)") - } - Kind::Scalar | Kind::FlatEnum => ( - Kind::OptionalValue(Box::new(inner)), - format!("{ns}_{slug}"), - slug, - ), - _ => (Kind::Optional(Box::new(inner)), String::new(), slug), - } - } - Type::Sequence { inner_type } => { - let inner = self.ctype(inner_type)?; - let slug = format!("{}_list", inner.slug); - (Kind::List(Box::new(inner)), format!("{ns}_{slug}"), slug) - } - Type::Map { - key_type, - value_type, - } => { - let key = self.ctype(key_type)?; - let value = self.ctype(value_type)?; - let slug = format!("{}_{}_map", key.slug, value.slug); - ( - Kind::Map(Box::new(key), Box::new(value)), - format!("{ns}_{slug}"), - slug, - ) - } - Type::Box { inner_type } => return self.ctype(inner_type), - Type::Timestamp | Type::Duration | Type::Set { .. } | Type::Custom { .. } => { - bail!("the C backend does not support `{cpp}` yet") - } - Type::CallbackInterface { name, .. } => { - bail!("the C backend does not support callback interfaces, but `{name}` is one") - } - }; - - // Scalars and strings keep their C spelling; every other type is named from its snake case. - let (c, snake) = match kind { - Kind::Scalar | Kind::String | Kind::Optional(_) => (c, String::new()), - _ => (type_name(&c), c), - }; - let ct = CType { - ty: ty.clone(), - kind, - c, - snake, - cpp, - canon: canon.clone(), - slug, - external: None, - }; - self.types.insert(canon, ct.clone()); - Ok(ct) - } - - /// Maps a type from another crate to the C type that crate's API declares, after checking - /// that its C API can be generated at all. - fn external_ctype(&mut self, ty: &Type, canon: String, cpp: String) -> Result { - let ext = filters::defining_interface(self.ci, ty); - let mut own = Gen::new(ext, self.config); - if self.externals.insert(ext.crate_name().to_string()) { - own.check_supported().with_context(|| { - format!( - "`{}` uses types from `{}`", - self.ci.namespace(), - ext.namespace() - ) - })?; - } - let own = own.ctype(ty)?; - let ct = CType { - ty: ty.clone(), - kind: own.kind, - c: own.c, - snake: own.snake.clone(), - cpp, - canon: canon.clone(), - // The whole C name, so a compound of it never matches one of a local namesake. - slug: own.snake, - external: Some((ext.namespace().to_string(), own.canon)), - }; - self.types.insert(canon, ct.clone()); - Ok(ct) - } - - fn render(&mut self, h: &mut String, s: &mut String) -> Result<()> { - let ns = self.ns.clone(); - for name in [ - "task_free", - "work_run", - "set_dispatcher", - "shutdown_dispatcher", - "string_free", - ] { - self.claim(&format!("{ns}_{name}"), &format!("the runtime's `{name}`"))?; - } - for name in ["task", "work", "dispatcher"] { - self.claim( - &type_name(&format!("{ns}_{name}")), - &format!("the runtime's `{name}`"), - )?; - } - - // Register every reachable type before rendering any of them. - let local: Vec = self.ci.iter_local_types().cloned().collect(); - for ty in &local { - self.ctype(ty)?; - } - - let types: Vec = self.types.values().cloned().collect(); - - // Another crate's header defines its types, and its implementation converts them. - let types: Vec = types - .into_iter() - .filter(|ct| ct.external.is_none()) - .collect(); - - // Flat enums first: C cannot forward-declare an enum. - for ct in types.iter().filter(|ct| matches!(ct.kind, Kind::FlatEnum)) { - self.render_flat_enum(h, ct)?; - } - - // Then every struct name, so lists and pointers can refer to any of them. - let mut forwards = String::new(); - for ct in &types { - if matches!( - ct.kind, - Kind::Bytes - | Kind::Record - | Kind::DataEnum - | Kind::Object - | Kind::OptionalValue(_) - | Kind::List(_) - | Kind::Map(..) - ) { - self.claim(&ct.c, &ct.item())?; - writeln!(forwards, "typedef struct {0} {0};", ct.c)?; - } - } - if !forwards.is_empty() { - writeln!(h, "{forwards}")?; - } - - // Compound types hold only pointers, so they can precede the records they list. - for ct in types.iter() { - match &ct.kind { - Kind::OptionalValue(inner) => { - h.push_str(&line_doc( - "An optional value: `value` is meaningful only when `has_value` is true.", - )); - writeln!( - h, - "struct {} {{\n bool has_value;\n {};\n}};\n", - ct.c, - decl(&inner.field(), "value") - )?; - } - Kind::Bytes => { - h.push_str(&line_doc( - "Bytes: `len` bytes at `data`, which is NULL when empty.", - )); - writeln!( - h, - "struct {} {{\n const uint8_t *data;\n size_t len;\n}};\n", - ct.c - )?; - self.render_free(h, s, ct, "these bytes")?; - } - Kind::List(inner) => { - h.push_str(&line_doc( - "A list of `len` items at `data`, which is NULL when empty.", - )); - writeln!( - h, - "struct {} {{\n {}data;\n size_t len;\n}};\n", - ct.c, - const_ptr(&inner.field()) - )?; - self.render_free(h, s, ct, "this list and its items")?; - } - Kind::Map(key, value) => { - h.push_str(&line_doc( - "A map: `len` entries, the i-th key at `keys[i]` and its value at `values[i]`.", - )); - writeln!( - h, - "struct {} {{\n {}keys;\n {}values;\n size_t len;\n}};\n", - ct.c, - const_ptr(&key.field()), - const_ptr(&value.field()) - )?; - self.render_free(h, s, ct, "this map and its entries")?; - } - _ => {} - } - } - - // Records and data enums embed each other by value, so define dependencies first. - for ct in self.sorted_structs(&types)? { - match ct.kind { - Kind::Record => self.render_record(h, s, &ct)?, - Kind::DataEnum => self.render_data_enum(h, s, &ct)?, - _ => unreachable!(), - } - } - - for obj in self.ci.object_definitions() { - self.render_object(h, s, obj)?; - } - - for func in self.ci.function_definitions() { - let name = prefixed(&self.ns, func.name()); - let call = format!( - "::{}::{}", - self.ci.namespace(), - filters::fn_name(func.name()).unwrap() - ); - self.claim(&name, &format!("function `{}`", func.name()))?; - self.render_callable(h, s, func, &name, None, &call)?; - } - - // The header declared the types known up front; one found later would lack its struct. - let local = self.types.values().filter(|ct| ct.external.is_none()); - if local.count() != types.len() { - bail!("the C backend found a type the interface does not list; this is a bug"); - } - Ok(()) - } - - fn render_flat_enum(&mut self, h: &mut String, ct: &CType) -> Result<()> { - let e = self.enum_def(&ct.ty)?; - self.claim(&ct.c, &ct.item())?; - h.push_str(&doc(e.docstring(), 0)); - writeln!(h, "typedef enum {} {{", ct.c)?; - for (i, variant) in e.variants().iter().enumerate() { - let constant = variant_constant(&ct.snake, variant.name()); - self.claim( - &constant, - &format!("variant `{}::{}`", e.name(), variant.name()), - )?; - h.push_str(&doc(variant.docstring(), 4)); - let comma = if i + 1 < e.variants().len() { "," } else { "" }; - writeln!(h, " {constant}{comma}")?; - } - writeln!(h, "}} {};\n", ct.c)?; - Ok(()) - } - - fn enum_def(&self, ty: &Type) -> Result<&'a Enum> { - match ty { - Type::Enum { name, .. } => self - .ci - .get_enum_definition(name) - .with_context(|| format!("enum `{name}` not found")), - _ => bail!("not an enum: {ty:?}"), - } - } - - fn record_def(&self, ty: &Type) -> Result<&'a Record> { - match ty { - Type::Record { name, .. } => self - .ci - .get_record_definition(name) - .with_context(|| format!("record `{name}` not found")), - _ => bail!("not a record: {ty:?}"), - } - } - - /// Records and data enums ordered so each follows the ones it embeds by value. - fn sorted_structs(&self, types: &[CType]) -> Result> { - let structs: BTreeMap = types - .iter() - .filter(|ct| matches!(ct.kind, Kind::Record | Kind::DataEnum)) - .map(|ct| (ct.canon.clone(), ct.clone())) - .collect(); - - let mut sorted = Vec::new(); - let mut done = BTreeSet::new(); - let mut visiting = BTreeSet::new(); - for canon in structs.keys() { - self.visit(canon, &structs, &mut done, &mut visiting, &mut sorted)?; - } - Ok(sorted) - } - - fn visit( - &self, - canon: &str, - structs: &BTreeMap, - done: &mut BTreeSet, - visiting: &mut BTreeSet, - sorted: &mut Vec, - ) -> Result<()> { - if done.contains(canon) { - return Ok(()); - } - if !visiting.insert(canon.to_string()) { - bail!("`{canon}` contains itself by value, which C cannot represent"); - } - let ct = &structs[canon]; - let fields: Vec<&Field> = match ct.kind { - Kind::Record => self.record_def(&ct.ty)?.fields().iter().collect(), - _ => self - .enum_def(&ct.ty)? - .variants() - .iter() - .flat_map(|v| v.fields()) - .collect(), - }; - for field in fields { - let dep = CppCodeOracle.find(&field.as_type()).canonical_name(self.ci); - if structs.contains_key(&dep) { - self.visit(&dep, structs, done, visiting, sorted)?; - } - } - visiting.remove(canon); - done.insert(canon.to_string()); - sorted.push(ct.clone()); - Ok(()) - } - - fn render_record(&mut self, h: &mut String, s: &mut String, ct: &CType) -> Result<()> { - let rec = self.record_def(&ct.ty)?; - h.push_str(&doc(rec.docstring(), 0)); - writeln!(h, "struct {} {{", ct.c)?; - for field in rec.fields() { - let fct = self.ctype(&field.as_type())?; - h.push_str(&doc(field.docstring(), 4)); - let nullable = if matches!(fct.kind, Kind::Optional(_)) { - " /* NULL when absent */" - } else { - "" - }; - writeln!( - h, - " {};{nullable}", - decl(&fct.field(), &filters::var_name(field.name()).unwrap()) - )?; - } - writeln!(h, "}};\n")?; - self.render_free(h, s, ct, "this record's fields and the record")?; - - if rec.fields().iter().any(|f| f.default_value().is_some()) { - let name = format!("{}_default", ct.snake); - self.claim(&name, &format!("the defaults of {}", ct.item()))?; - h.push_str(&line_doc( - "A record with every defaulted field set and the rest zeroed, to fill in before passing it.", - )); - writeln!(h, "{} {name}(void);\n", ct.c)?; - - writeln!(s, "{} {name}(void) {{", ct.c)?; - writeln!( - s, - " {} out;\n std::memset(&out, 0, sizeof out);", - ct.c - )?; - for field in rec.fields() { - if let Some(default) = field.default_value() { - let fct = self.ctype(&field.as_type())?; - if let Some(value) = self.default_literal(&fct, default)? { - writeln!( - s, - " out.{} = {value};", - filters::var_name(field.name()).unwrap() - )?; - } - } - } - writeln!(s, " return out;\n}}\n")?; - } - Ok(()) - } - - /// The C expression for a field default, or None when zero already is the default. - fn default_literal(&self, ct: &CType, default: &DefaultValue) -> Result> { - let literal = match default { - DefaultValue::Default => { - return Ok(match &ct.kind { - Kind::String => Some("\"\"".into()), - Kind::Scalar - | Kind::Optional(_) - | Kind::OptionalValue(_) - | Kind::Bytes - | Kind::List(_) - | Kind::Map(..) => None, - Kind::Record if self.has_default(&ct.ty)? => { - Some(format!("{}_default()", ct.snake)) - } - Kind::Record => None, - _ => bail!("the C backend cannot render a default `{}`", ct.cpp), - }) - } - DefaultValue::Literal(literal) => literal, - }; - Ok(match literal { - Literal::Boolean(true) => Some("true".into()), - Literal::Boolean(false) - | Literal::None - | Literal::EmptySequence - | Literal::EmptyMap => None, - Literal::String(value) => Some(filters::string_literal(value)), - Literal::UInt(0, ..) | Literal::Int(0, ..) => None, - Literal::UInt(value, radix, _) => Some(match radix { - Radix::Hexadecimal => format!("{value:#x}ULL"), - Radix::Octal => format!("0{value:o}ULL"), - Radix::Decimal => format!("{value}ULL"), - }), - Literal::Int(value, ..) => Some(format!("{value}LL")), - Literal::Float(value, _) => Some(value.clone()), - Literal::Enum(variant, _) if matches!(ct.kind, Kind::FlatEnum) => { - Some(variant_constant(&ct.snake, variant)) - } - _ => bail!( - "the C backend cannot render the default {literal:?} for `{}`", - ct.cpp - ), - }) - } - - fn has_default(&self, ty: &Type) -> Result { - Ok(self - .record_def(ty)? - .fields() - .iter() - .any(|f| f.default_value().is_some())) - } - - fn render_data_enum(&mut self, h: &mut String, s: &mut String, ct: &CType) -> Result<()> { - let e = self.enum_def(&ct.ty)?; - let error = self.ci.is_used_as_error(e); - let tag = format!("{}Tag", ct.c); - self.claim(&tag, &format!("the tag of {}", ct.item()))?; - - h.push_str(&line_doc(&format!("Which variant a `{}` holds.", ct.c))); - writeln!(h, "typedef enum {tag} {{")?; - for (i, variant) in e.variants().iter().enumerate() { - let constant = variant_constant(&ct.snake, variant.name()); - self.claim( - &constant, - &format!("variant `{}::{}`", e.name(), variant.name()), - )?; - h.push_str(&doc(variant.docstring(), 4)); - let comma = if i + 1 < e.variants().len() { "," } else { "" }; - writeln!(h, " {constant}{comma}")?; - } - writeln!(h, "}} {tag};\n")?; - - // C++ forbids types declared inside an anonymous union, so each variant's fields get a - // named struct, declared first. - let mut members = Vec::new(); - for variant in e.variants().iter().filter(|v| v.has_fields()) { - // The anonymous union shares the struct's members, so a variant can't reuse one. - let member = variant_member(variant.name()); - if member == "tag" || (error && member == "message") { - bail!( - "the C backend cannot name `{}`'s variant `{}` `{member}`, which the struct already uses", - e.name(), - variant.name() - ); - } - let fields = type_name(&format!("{}_{member}", ct.snake)); - self.claim( - &fields, - &format!("the fields of variant `{}::{}`", e.name(), variant.name()), - )?; - h.push_str(&line_doc(&format!( - "The fields of a `{}` holding `{}`.", - ct.c, - variant_constant(&ct.snake, variant.name()) - ))); - writeln!(h, "typedef struct {fields} {{")?; - for (i, field) in variant.fields().iter().enumerate() { - let fct = self.ctype(&field.as_type())?; - h.push_str(&doc(field.docstring(), 4)); - writeln!( - h, - " {};", - decl(&fct.field(), &c_field_name(field, i + 1)) - )?; - } - writeln!(h, "}} {fields};\n")?; - members.push((fields, member)); - } - - h.push_str(&doc(e.docstring(), 0)); - writeln!(h, "struct {} {{", ct.c)?; - writeln!(h, " {tag} tag;")?; - if !members.is_empty() { - writeln!( - h, - " /** The fields of the variant `tag` names; variants without fields have no member. */" - )?; - writeln!(h, " union {{")?; - for (fields, member) in &members { - writeln!(h, " {fields} {member};")?; - } - writeln!(h, " }};")?; - } - if error { - writeln!(h, " /** Describes the error, for logs. */")?; - writeln!(h, " const char *message;")?; - } - writeln!(h, "}};\n")?; - - if error { - self.render_free(h, s, ct, "this error")?; - let name = format!("{}_message", ct.snake); - self.claim(&name, &format!("the message of {}", ct.item()))?; - h.push_str(&line_doc("The error's message, owned by the error.")); - writeln!(h, "const char *{name}(const {} *error);\n", ct.c)?; - writeln!( - s, - "const char *{name}(const {} *error) {{\n if (!error) {{\n ::{}::c_detail::fail(\"{name}: error must not be NULL\");\n }}\n return error->message;\n}}\n", - ct.c, - self.ci.namespace() - )?; - } else { - self.render_free(h, s, ct, "this value's fields and the value")?; - } - Ok(()) - } - - /// Declares and defines `_free`, which releases a heap value the API returned. - fn render_free( - &mut self, - h: &mut String, - s: &mut String, - ct: &CType, - what: &str, - ) -> Result<()> { - let name = format!("{}_free", ct.snake); - self.claim(&name, &format!("the release function of {}", ct.item()))?; - h.push_str(&line_doc(&format!( - "Frees {what}, as returned by this API; NULL is ignored." - ))); - writeln!(h, "void {name}({} *value);\n", ct.c)?; - writeln!( - s, - "void {name}({} *value) {{\n if (!value) {{\n return;\n }}\n ::{ns}::c_detail::free_c_{canon}(*value);\n std::free(value);\n}}\n", - ct.c, - ns = self.ci.namespace(), - canon = ct.canon - )?; - Ok(()) - } - - fn render_object(&mut self, h: &mut String, s: &mut String, obj: &Object) -> Result<()> { - let snake = prefixed(&self.ns, obj.name()); - let c = type_name(&snake); - let class = CppCodeOracle.class_name(obj.name()); - let namespace = self.ci.namespace(); - - // The object's docstring heads its section, since its typedef sits with the others. - writeln!(h, "/* {c} */\n")?; - if let Some(docstring) = obj.docstring() { - writeln!(h, "{}", doc(Some(docstring), 0))?; - } - - let free = format!("{snake}_free"); - self.claim( - &free, - &format!("the release function of object `{}`", obj.name()), - )?; - h.push_str(&line_doc(&format!( - "Releases this `{c}` handle; NULL is ignored. Other handles to the same object stay valid." - ))); - writeln!(h, "void {free}({c} *self);\n")?; - writeln!(s, "void {free}({c} *self) {{\n delete self;\n}}\n")?; - - for ctor in obj.constructors() { - let item = format!("constructor `{}::{}`", obj.name(), ctor.name()); - let (name, call) = if ctor.is_primary_constructor() { - ( - format!("{snake}_new"), - format!("::{namespace}::{class}::init"), - ) - } else { - ( - format!("{snake}_{}", c_name(ctor.name())), - format!("::{namespace}::{class}::{}", ctor.name()), - ) - }; - self.claim(&name, &item)?; - self.render_callable(h, s, ctor, &name, None, &call)?; - } - - for method in obj.methods() { - let item = format!("method `{}::{}`", obj.name(), method.name()); - let name = format!("{snake}_{}", c_name(method.name())); - let call = format!("self->inner->{}", filters::fn_name(method.name()).unwrap()); - self.claim(&name, &item)?; - self.render_callable(h, s, method, &name, Some(&c), &call)?; - } - Ok(()) - } - - /// Renders one function, constructor, or method, after the caller claimed its `name`. - /// `call` names the C++ callee. - fn render_callable( - &mut self, - h: &mut String, - s: &mut String, - callable: &impl Callable, - name: &str, - receiver: Option<&str>, - call: &str, - ) -> Result<()> { - let namespace = self.ci.namespace().to_string(); - let ns = self.ns.clone(); - - let mut params = Vec::new(); - let mut checks = String::new(); - let mut args = Vec::new(); - let mut names = BTreeSet::new(); - - let null_check = |checks: &mut String, param: &str| { - writeln!( - checks, - " if (!{param}) {{\n ::{namespace}::c_detail::fail(\"{name}: {param} must not be NULL\");\n }}" - ) - .unwrap(); - }; - - if let Some(receiver) = receiver { - params.push(format!("{receiver} *self")); - names.insert("self".to_string()); - null_check(&mut checks, "self"); - } - - let mut nullable = Vec::new(); - for arg in callable.arguments() { - let ct = self.ctype(&arg.as_type())?; - let pname = filters::var_name(arg.name()).unwrap(); - names.insert(pname.clone()); - if matches!(ct.kind, Kind::Optional(_)) { - nullable.push(format!("`{pname}`")); - } - params.push(ct.param(&pname)); - if ct.required_pointer() { - null_check(&mut checks, &pname); - } - let value = if ct.by_pointer() { - format!("*{pname}") - } else { - pname.clone() - }; - args.push(format!( - "::{namespace}::c_detail::from_c_{}({value})", - ct.canon - )); - } - - let ret = match callable.return_type() { - Some(ty) => Some(self.ctype(ty)?), - None => None, - }; - let err = match callable.throws_type() { - Some(ty) => { - let ct = self.ctype(ty)?; - if !matches!(ct.kind, Kind::DataEnum) { - bail!( - "the C backend supports only enum errors, but `{name}` throws `{}`", - ct.cpp - ); - } - Some(ct) - } - None => None, - }; - let ret_c = ret.as_ref().map(CType::ret); - - let call = format!("{call}({})", args.join(", ")); - let box_err = |err: &CType, expr: &str| { - format!( - "::{namespace}::c_detail::box(::{namespace}::c_detail::to_c_{}({expr}))", - err.canon - ) - }; - - // Generated notes on nullability and ownership, after the uniffi docstring. - let mut notes = Vec::new(); - if !nullable.is_empty() { - notes.push(format!("{} may be NULL.", nullable.join(", "))); - } - let ret_free = ret.as_ref().and_then(|ret| ret.free_fn(&ns)); - let absent = ret - .as_ref() - .is_some_and(|ret| matches!(ret.kind, Kind::Optional(_))); - - if callable.is_async() { - for reserved in ["callback", "user_data"] { - if names.contains(reserved) { - bail!( - "`{name}` has an argument named `{reserved}`, which the C backend reserves" - ); - } - } - let callback = type_name(&format!("{name}_callback")); - self.claim(&callback, &format!("the callback of `{name}`"))?; - - let mut cb_params = vec!["void *user_data".to_string(), "bool cancelled".to_string()]; - // What the callback gets when cancelled: no error and no value. - let mut empty = vec!["user_data", "true"]; - if let Some(err) = &err { - cb_params.push(format!("{} *error", err.c)); - empty.push("nullptr"); - } - if let Some(ret_c) = &ret_c { - cb_params.push(decl(ret_c, "value")); - empty.push("{}"); - } - let mut cb_doc = vec![match (&err, &ret) { - (None, None) => format!( - "Called exactly once on the dispatcher when `{name}` completes, or with `cancelled` set when its task was freed first; release `user_data` here." - ), - _ => format!( - "Receives the result of `{name}` exactly once on the dispatcher, or `cancelled` with no error or value when its task was freed first; release `user_data` here." - ), - }]; - if let Some(err) = &err { - cb_doc.push(format!( - "`error` is NULL on success, or freed with `{}_free`.", - err.snake - )); - } - if let Some(free) = &ret_free { - cb_doc.push(format!( - "`value` is freed with `{free}`{}.", - if absent { - "; it is NULL when absent" - } else { - "" - } - )); - } - h.push_str(&line_doc(&cb_doc.join(" "))); - writeln!(h, "typedef void (*{callback})({});\n", cb_params.join(", "))?; - - params.push(format!("{callback} callback")); - params.push("void *user_data".to_string()); - null_check(&mut checks, "callback"); - - let deliver = match (&err, &ret) { - (Some(err), Some(ret)) => format!( - "[callback, user_data](auto output) {{\n if (!output) {{\n callback(user_data, false, {}, {{}});\n return;\n }}\n callback(user_data, false, nullptr, {});\n }}", - box_err(err, "output.error()"), - ret.ret_expr(&namespace, "*output") - ), - (Some(err), None) => format!( - "[callback, user_data](auto output) {{\n if (!output) {{\n callback(user_data, false, {});\n return;\n }}\n callback(user_data, false, nullptr);\n }}", - box_err(err, "output.error()") - ), - (None, Some(ret)) => format!( - "[callback, user_data](auto output) {{\n callback(user_data, false, {});\n }}", - ret.ret_expr(&namespace, "output") - ), - (None, None) => { - "[callback, user_data]() {\n callback(user_data, false);\n }".to_string() - } - }; - let cancel = format!( - "[callback, user_data]() {{\n callback({});\n }}", - empty.join(", ") - ); - - let signature = format!( - "{} *{name}({})", - type_name(&format!("{ns}_task")), - params.join(", ") - ); - notes.push("Returns a task, never NULL.".into()); - h.push_str(&doc(callable.docstring(), 0)); - h.push_str(&line_doc(¬es.join(" "))); - writeln!(h, "{signature};\n")?; - writeln!( - s, - "{signature} {{\n{checks} return ::{namespace}::c_detail::spawn({call}, {deliver}, {cancel});\n}}\n" - )?; - return Ok(()); - } - - let (ret_decl, body) = match (&err, &ret) { - (Some(err), Some(ret)) => { - if names.contains("out") { - bail!("`{name}` has an argument named `out`, which the C backend reserves"); - } - params.push(decl(&pointer(ret_c.as_ref().unwrap()), "out")); - null_check(&mut checks, "out"); - ( - format!("{} *", err.c), - format!( - " auto result = {call};\n if (!result) {{\n *out = {{}};\n return {};\n }}\n *out = {};\n return nullptr;\n", - box_err(err, "result.error()"), - ret.ret_expr(&namespace, "*result") - ), - ) - } - (Some(err), None) => ( - format!("{} *", err.c), - format!( - " auto result = {call};\n if (!result) {{\n return {};\n }}\n return nullptr;\n", - box_err(err, "result.error()") - ), - ), - (None, Some(ret)) => ( - ret_c.clone().unwrap(), - format!(" return {};\n", ret.ret_expr(&namespace, &call)), - ), - (None, None) => ("void".to_string(), format!(" {call};\n")), - }; - - if let Some(err) = &err { - let out = if ret.is_some() { " and sets `out`" } else { "" }; - notes.push(format!( - "Returns NULL on success{out}, or an error the caller frees with `{}_free`.", - err.snake - )); - } - if let Some(free) = &ret_free { - let result = if err.is_some() { "`out`" } else { "the result" }; - notes.push(format!( - "The caller frees {result} with `{free}`{}.", - if absent { - "; it is NULL when absent" - } else { - "" - } - )); - } - h.push_str(&doc(callable.docstring(), 0)); - if !notes.is_empty() { - h.push_str(&line_doc(¬es.join(" "))); - } - let params = if params.is_empty() { - "void".to_string() - } else { - params.join(", ") - }; - let signature = decl(&ret_decl, &format!("{name}({params})")); - writeln!(h, "{signature};\n")?; - writeln!(s, "{signature} {{\n{checks}{body}}}\n")?; - Ok(()) - } - - /// Declares every converter, then defines them, so their order does not matter. An external - /// type's converters forward to its own crate's, which `externals` declares. - fn render_converters(&self, out: &mut String, externals: &mut String) -> Result<()> { - let types: Vec = self.types.values().map(CType::qualified).collect(); - let mut by_namespace: BTreeMap<&str, String> = BTreeMap::new(); - for ct in &types { - if let Some((namespace, canon)) = &ct.external { - let decls = by_namespace.entry(namespace).or_default(); - let field = ct.field(); - writeln!( - decls, - "{};", - decl(&field, &format!("to_c_{canon}(const {} &value)", ct.cpp)) - )?; - writeln!( - decls, - "{} from_c_{canon}({});", - ct.cpp, - decl(&ct.view(), "value") - )?; - writeln!( - decls, - "void free_c_{canon}({});", - decl(&format!("{field} &"), "value") - )?; - } - } - for (namespace, decls) in by_namespace { - writeln!( - externals, - "namespace {namespace}::c_detail {{ -{decls}}} // namespace {namespace}::c_detail -" - )?; - } - - for ct in &types { - let field = ct.field(); - writeln!( - out, - "{};", - decl( - &field, - &format!("to_c_{}(const {} &value)", ct.canon, ct.cpp) - ) - )?; - writeln!( - out, - "{} from_c_{}({});", - ct.cpp, - ct.canon, - decl(&ct.view(), "value") - )?; - writeln!( - out, - "void free_c_{}({});", - ct.canon, - decl(&format!("{field} &"), "value") - )?; - } - out.push('\n'); - for ct in &types { - self.render_converter(out, ct)?; - } - Ok(()) - } - - fn render_converter(&self, out: &mut String, ct: &CType) -> Result<()> { - let field = ct.field(); - let to = decl( - &field, - &format!("to_c_{}(const {} &value)", ct.canon, ct.cpp), - ); - let from = format!( - "{} from_c_{}({})", - ct.cpp, - ct.canon, - decl(&ct.view(), "value") - ); - let free = format!( - "void free_c_{}({})", - ct.canon, - decl(&format!("{field} &"), "value") - ); - if let Some((namespace, canon)) = &ct.external { - let own = format!("::{namespace}::c_detail"); - writeln!(out, "{to} {{\n return {own}::to_c_{canon}(value);\n}}\n")?; - writeln!( - out, - "{from} {{\n return {own}::from_c_{canon}(value);\n}}\n" - )?; - writeln!(out, "{free} {{\n {own}::free_c_{canon}(value);\n}}\n")?; - return Ok(()); - } - match &ct.kind { - Kind::Scalar => { - writeln!(out, "{to} {{\n return value;\n}}\n")?; - writeln!(out, "{from} {{\n return value;\n}}\n")?; - writeln!(out, "{free} {{\n (void)value;\n}}\n")?; - } - Kind::FlatEnum => { - let e = self.enum_def(&ct.ty)?; - let mut to_cases = String::new(); - let mut from_cases = String::new(); - for variant in e.variants() { - let cpp_variant = format!( - "{}::{}", - ct.cpp, - CppCodeOracle.enum_variant_name(variant.name(), self.config.enum_style()) - ); - let constant = variant_constant(&ct.snake, variant.name()); - writeln!( - to_cases, - " case {cpp_variant}:\n return {constant};" - )?; - writeln!( - from_cases, - " case {constant}:\n return {cpp_variant};" - )?; - } - writeln!( - out, - "{to} {{\n switch (value) {{\n{to_cases} }}\n fail(\"unknown {} variant\");\n}}\n", - ct.c - )?; - writeln!( - out, - "{from} {{\n switch (value) {{\n{from_cases} }}\n fail(\"invalid {} value\");\n}}\n", - ct.c - )?; - writeln!(out, "{free} {{\n (void)value;\n}}\n")?; - } - Kind::String => { - writeln!(out, "{to} {{\n return copy_string(value);\n}}\n")?; - writeln!( - out, - "{from} {{\n if (!value) {{\n fail(\"a string must not be NULL\");\n }}\n return std::string(value);\n}}\n" - )?; - writeln!(out, "{free} {{\n std::free(const_cast(value));\n value = nullptr;\n}}\n")?; - } - Kind::Bytes => { - writeln!( - out, - "{to} {{\n {field} out{{}};\n out.len = value.size();\n if (!value.empty()) {{\n auto *data = static_cast(alloc(value.size()));\n std::memcpy(data, value.data(), value.size());\n out.data = data;\n }}\n return out;\n}}\n" - )?; - writeln!( - out, - "{from} {{\n if (!value.data && value.len) {{\n fail(\"bytes with a length must have data\");\n }}\n if (!value.len) {{\n return {{}};\n }}\n return {}(value.data, value.data + value.len);\n}}\n", - ct.cpp - )?; - writeln!(out, "{free} {{\n std::free(const_cast(value.data));\n value = {{}};\n}}\n")?; - } - Kind::Record => { - let rec = self.record_def(&ct.ty)?; - let mut to_body = String::new(); - let mut from_items = Vec::new(); - let mut free_body = String::new(); - for field in rec.fields() { - let fcanon = CppCodeOracle.find(&field.as_type()).canonical_name(self.ci); - let name = filters::var_name(field.name()).unwrap(); - writeln!(to_body, " out.{name} = to_c_{fcanon}(value.{name});")?; - from_items.push(format!(" from_c_{fcanon}(value.{name})")); - writeln!(free_body, " free_c_{fcanon}(value.{name});")?; - } - writeln!( - out, - "{to} {{\n {field} out{{}};\n{to_body} return out;\n}}\n" - )?; - writeln!( - out, - "{from} {{\n return {}{{\n{}\n }};\n}}\n", - ct.cpp, - from_items.join(",\n") - )?; - writeln!(out, "{free} {{\n{free_body}}}\n")?; - } - Kind::DataEnum => self.render_data_enum_converter(out, ct, &to, &from, &free)?, - Kind::Object => { - writeln!( - out, - "{to} {{\n if (!value) {{\n fail(\"unexpected null {}\");\n }}\n return new {}{{value}};\n}}\n", - ct.c, ct.c - )?; - writeln!( - out, - "{from} {{\n if (!value) {{\n fail(\"a {} must not be NULL\");\n }}\n return value->inner;\n}}\n", - ct.c - )?; - writeln!( - out, - "{free} {{\n delete value;\n value = nullptr;\n}}\n" - )?; - } - Kind::Optional(inner) => { - let icanon = &inner.canon; - match inner.kind { - // Another crate's object struct is private to its implementation. - Kind::Object if inner.external.is_some() => { - writeln!( - out, - "{to} {{\n return value ? to_c_{icanon}(value) : nullptr;\n}}\n" - )?; - writeln!( - out, - "{from} {{\n return value ? from_c_{icanon}(value) : nullptr;\n}}\n" - )?; - writeln!(out, "{free} {{\n free_c_{icanon}(value);\n}}\n")?; - } - // A null shared_ptr is the C++ binding's empty optional object. - Kind::Object => { - writeln!( - out, - "{to} {{\n return value ? new {}{{value}} : nullptr;\n}}\n", - inner.c - )?; - writeln!( - out, - "{from} {{\n return value ? value->inner : nullptr;\n}}\n" - )?; - writeln!(out, "{free} {{\n free_c_{icanon}(value);\n}}\n")?; - } - Kind::String => { - writeln!( - out, - "{to} {{\n return value ? to_c_{icanon}(*value) : nullptr;\n}}\n" - )?; - writeln!( - out, - "{from} {{\n if (!value) {{\n return std::nullopt;\n }}\n return std::string(value);\n}}\n" - )?; - writeln!(out, "{free} {{\n free_c_{icanon}(value);\n}}\n")?; - } - _ => { - writeln!( - out, - "{to} {{\n if (!value) {{\n return nullptr;\n }}\n return box(to_c_{icanon}(*value));\n}}\n" - )?; - writeln!( - out, - "{from} {{\n if (!value) {{\n return std::nullopt;\n }}\n return from_c_{icanon}(*value);\n}}\n" - )?; - writeln!( - out, - "{free} {{\n if (value) {{\n free_c_{icanon}(*value);\n std::free(value);\n value = nullptr;\n }}\n}}\n" - )?; - } - } - } - Kind::OptionalValue(inner) => { - let icanon = &inner.canon; - writeln!( - out, - "{to} {{\n {field} out{{}};\n if (value) {{\n out.has_value = true;\n out.value = to_c_{icanon}(*value);\n }}\n return out;\n}}\n" - )?; - writeln!( - out, - "{from} {{\n if (!value.has_value) {{\n return std::nullopt;\n }}\n return from_c_{icanon}(value.value);\n}}\n" - )?; - writeln!(out, "{free} {{\n (void)value;\n}}\n")?; - } - Kind::List(inner) => { - let item = inner.field(); - let icanon = &inner.canon; - writeln!( - out, - "{to} {{\n using Item = {item};\n {field} out{{}};\n out.len = value.size();\n if (!value.empty()) {{\n auto *data = static_cast(alloc(sizeof(Item) * value.size()));\n for (size_t i = 0; i < value.size(); ++i) {{\n data[i] = to_c_{icanon}(value[i]);\n }}\n out.data = data;\n }}\n return out;\n}}\n" - )?; - writeln!( - out, - "{from} {{\n if (!value.data && value.len) {{\n fail(\"a list with a length must have data\");\n }}\n {} out;\n out.reserve(value.len);\n for (size_t i = 0; i < value.len; ++i) {{\n out.push_back(from_c_{icanon}(value.data[i]));\n }}\n return out;\n}}\n", - ct.cpp - )?; - writeln!( - out, - "{free} {{\n using Item = {item};\n auto *data = const_cast(value.data);\n for (size_t i = 0; i < value.len; ++i) {{\n free_c_{icanon}(data[i]);\n }}\n std::free(data);\n value = {{}};\n}}\n" - )?; - } - Kind::Map(key, val) => { - let (kitem, vitem) = (key.field(), val.field()); - let (kcanon, vcanon) = (&key.canon, &val.canon); - writeln!( - out, - "{to} {{\n using Key = {kitem};\n using Value = {vitem};\n {field} out{{}};\n out.len = value.size();\n if (!value.empty()) {{\n auto *keys = static_cast(alloc(sizeof(Key) * value.size()));\n auto *values = static_cast(alloc(sizeof(Value) * value.size()));\n size_t i = 0;\n for (const auto &entry : value) {{\n keys[i] = to_c_{kcanon}(entry.first);\n values[i] = to_c_{vcanon}(entry.second);\n ++i;\n }}\n out.keys = keys;\n out.values = values;\n }}\n return out;\n}}\n" - )?; - writeln!( - out, - "{from} {{\n if ((!value.keys || !value.values) && value.len) {{\n fail(\"a map with a length must have keys and values\");\n }}\n {} out;\n for (size_t i = 0; i < value.len; ++i) {{\n if (!out.emplace(from_c_{kcanon}(value.keys[i]), from_c_{vcanon}(value.values[i])).second) {{\n fail(\"a map must not repeat a key\");\n }}\n }}\n return out;\n}}\n", - ct.cpp - )?; - writeln!( - out, - "{free} {{\n using Key = {kitem};\n using Value = {vitem};\n auto *keys = const_cast(value.keys);\n auto *values = const_cast(value.values);\n for (size_t i = 0; i < value.len; ++i) {{\n free_c_{kcanon}(keys[i]);\n free_c_{vcanon}(values[i]);\n }}\n std::free(keys);\n std::free(values);\n value = {{}};\n}}\n" - )?; - } - } - Ok(()) - } - - fn render_data_enum_converter( - &self, - out: &mut String, - ct: &CType, - to: &str, - from: &str, - free: &str, - ) -> Result<()> { - let e = self.enum_def(&ct.ty)?; - let error = self.ci.is_used_as_error(e); - let display = e.uniffi_trait_methods().display_fmt.is_some(); - // Under the expected style each variant of a flat error carries its message. - let flat_error = error && e.is_flat(); - let field = ct.field(); - - let mut to_cases = String::new(); - let mut from_cases = String::new(); - let mut free_cases = String::new(); - for (index, variant) in e.variants().iter().enumerate() { - let constant = variant_constant(&ct.snake, variant.name()); - let cpp_variant = format!( - "{}::{}", - ct.cpp, - CppCodeOracle.enum_variant_name(variant.name(), self.config.enum_style()) - ); - let member = variant_member(variant.name()); - - writeln!( - to_cases, - " case {index}: {{\n out.tag = {constant};" - )?; - if variant.has_fields() || flat_error { - writeln!( - to_cases, - " const auto &inner = std::get<{index}>(variant);" - )?; - } - let mut from_items = Vec::new(); - let mut free_case = String::new(); - for (i, f) in variant.fields().iter().enumerate() { - let fcanon = CppCodeOracle.find(&f.as_type()).canonical_name(self.ci); - let name = c_field_name(f, i + 1); - writeln!( - to_cases, - " out.{member}.{name} = to_c_{fcanon}(inner.{name});" - )?; - from_items.push(format!("from_c_{fcanon}(value.{member}.{name})")); - writeln!(free_case, " free_c_{fcanon}(value.{member}.{name});")?; - } - if error && !display { - let message = if flat_error { - "inner.message".to_string() - } else { - filters::string_literal(variant.name()) - }; - writeln!(to_cases, " out.message = copy_string({message});")?; - } - writeln!(to_cases, " break;\n }}")?; - - if flat_error { - from_items - .push("value.message ? std::string(value.message) : std::string()".into()); - } - writeln!( - from_cases, - " case {constant}:\n return {}({cpp_variant}{{{}}});", - ct.cpp, - from_items.join(", ") - )?; - if !free_case.is_empty() { - writeln!( - free_cases, - " case {constant}:\n{free_case} break;" - )?; - } - } - - let message = if error && display { - " out.message = copy_string(value.to_string());\n" - } else { - "" - }; - writeln!( - out, - "{to} {{\n {field} out{{}};\n const auto &variant = value.get_variant();\n switch (variant.index()) {{\n{to_cases} default:\n fail(\"unknown {} variant\");\n }}\n{message} return out;\n}}\n", - ct.c - )?; - writeln!( - out, - "{from} {{\n switch (value.tag) {{\n{from_cases} }}\n fail(\"invalid {} tag\");\n}}\n", - ct.c - )?; - let free_message = if error { - " std::free(const_cast(value.message));\n value.message = nullptr;\n" - } else { - "" - }; - let switch = if free_cases.is_empty() { - String::new() - } else { - format!(" switch (value.tag) {{\n{free_cases} default:\n break;\n }}\n") - }; - writeln!(out, "{free} {{\n{switch}{free_message}}}\n")?; - Ok(()) - } -} - -/// A pointer to const items, `const T *`, or `T const *` when `T` is itself a pointer. -fn const_ptr(item: &str) -> String { - if item.ends_with('*') { - format!("{item} const *") - } else { - format!("const {item} *") - } -} - -/// A pointer to `ty`. -fn pointer(ty: &str) -> String { - if ty.ends_with('*') { - format!("{ty}*") - } else { - format!("{ty} *") - } -} - -/// The constant naming one variant of a C enum, from the enum's snake-case name, like -/// `MOQ_TRANSPORT_QUIC`. -fn variant_constant(snake: &str, variant: &str) -> String { - format!( - "{}_{}", - snake.to_shouty_snake_case(), - variant.to_shouty_snake_case() - ) -} - -/// The union member holding one variant's fields. -fn variant_member(variant: &str) -> String { - filters::var_name(&variant.to_snake_case()).unwrap() -} diff --git a/uniffi/cpp/bindgen/src/bindings/c/mod.rs b/uniffi/cpp/bindgen/src/bindings/c/mod.rs deleted file mode 100644 index 325955d82..000000000 --- a/uniffi/cpp/bindgen/src/bindings/c/mod.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! A plain C API over the generated C++ bindings. -//! -//! The C++ backend already lifts and lowers every type, drives Rust futures, and owns the -//! async dispatcher, so the C backend renders it in the expected error style and wraps it: -//! `.h` is the C11 header, and `_c.cpp` converts between its structs -//! and the C++ types. Consumers compile `.cpp` and `_c.cpp` as C++17, for -//! this crate and every crate whose types it uses: each crate's `_c.cpp` converts its own types. - -mod gen_c; - -use std::fs; - -use anyhow::Result; -use uniffi_bindgen::{BindingGenerator, Component, GenerationSettings}; - -use super::cpp::{gen_cpp, write_cpp_bindings}; - -pub(crate) struct CBindingGenerator; - -impl BindingGenerator for CBindingGenerator { - // The C API inherits the C++ settings (enum style, custom types) its implementation uses. - type Config = gen_cpp::Config; - - fn new_config(&self, root_toml: &toml::Value) -> Result { - Ok(match root_toml.get("bindings").and_then(|b| b.get("cpp")) { - Some(v) => v.clone().try_into()?, - None => Default::default(), - }) - } - - fn update_component_configs( - &self, - _settings: &GenerationSettings, - _components: &mut Vec>, - ) -> Result<()> { - Ok(()) - } - - fn write_bindings( - &self, - settings: &GenerationSettings, - components: &[Component], - ) -> Result<()> { - for Component { ci, config, .. } in components { - // C has no exceptions to catch, so the implementation returns errors as values. - let config = config.with_expected(); - gen_c::check_supported(ci, &config)?; - write_cpp_bindings(&settings.out_dir, ci, &config)?; - - let gen_c::Bindings { header, source } = gen_c::generate(ci, &config)?; - let namespace = ci.namespace(); - fs::write(settings.out_dir.join(format!("{namespace}.h")), header)?; - fs::write(settings.out_dir.join(format!("{namespace}_c.cpp")), source)?; - } - - Ok(()) - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/c/templates/c_header.h b/uniffi/cpp/bindgen/src/bindings/c/templates/c_header.h deleted file mode 100644 index 6caadb418..000000000 --- a/uniffi/cpp/bindgen/src/bindings/c/templates/c_header.h +++ /dev/null @@ -1,74 +0,0 @@ -/* This file was generated by uniffi-bindgen-cpp. C11. */ -#ifndef {{ guard }} -#define {{ guard }} - -#include -#include -#include -{%- for namespace in includes %} -#include "{{ namespace }}.h" -{%- endfor %} - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Conventions: - * - A call that can fail returns an error, or NULL on success, and writes its result to `out`. - * - Strings are NUL-terminated UTF-8. Arguments are borrowed for the call. - * - Everything returned is owned by the caller and released with the matching `_free`. - * - Async calls always return a task, and later call `callback` exactly once on the dispatcher: - * with the result, or with `cancelled` set if the task was freed first. Release `user_data` there. - * - A Rust panic aborts the process. - */ - -/** - * A pending async call. Free every task, including completed ones, from any thread or callback. - * Freeing it before its callback starts cancels the call, and the callback then runs with - * `cancelled` set. A dispatcher that refuses work or has shut down abandons the calls that work - * would finish, and their callbacks never run. - */ -typedef struct {{ ty }}Task {{ ty }}Task; - -/** Cancels the call if its callback has not started, and releases the task; NULL is ignored. */ -void {{ ns }}_task_free({{ ty }}Task *task); - -/** One unit of async work handed to a custom dispatcher. */ -typedef struct {{ ty }}Work {{ ty }}Work; - -/** Runs the work and releases it. Call it exactly once for every work item accepted. */ -void {{ ns }}_work_run({{ ty }}Work *work); - -/** - * Runs async work, and so every callback, somewhere the host chooses, such as its own loop. - * Both functions may be called from any thread. - */ -typedef struct {{ ty }}Dispatcher { - /** Queues the work to run later with `{{ ns }}_work_run` and returns true, or returns false to refuse it. */ - bool (*dispatch)(void *user_data, {{ ty }}Work *work); - /** Stops accepting work, runs what was accepted, and returns once none can still run. */ - void (*shutdown)(void *user_data); - /** Passed to both functions. */ - void *user_data; -} {{ ty }}Dispatcher; - -/** - * Replaces the default dispatcher thread, before the first async call. The struct is copied. - * Aborts when called after an async call or a shutdown, or with a NULL function. - */ -void {{ ns }}_set_dispatcher(const {{ ty }}Dispatcher *dispatcher); - -/** Stops dispatching for good: pending calls never call back. Call it before unloading. */ -void {{ ns }}_shutdown_dispatcher(void); - -/** Frees a string returned by this API; NULL is ignored. */ -void {{ ns }}_string_free(char *string); - -{{ body }} - -#ifdef __cplusplus -} -#endif - -#endif /* {{ guard }} */ \ No newline at end of file diff --git a/uniffi/cpp/bindgen/src/bindings/c/templates/c_source.cpp b/uniffi/cpp/bindgen/src/bindings/c/templates/c_source.cpp deleted file mode 100644 index 26f4e44ca..000000000 --- a/uniffi/cpp/bindgen/src/bindings/c/templates/c_source.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* This file was generated by uniffi-bindgen-cpp. Compile it as C++17 with {{ namespace }}.cpp. */ -#include "{{ namespace }}.h" -#include "{{ namespace }}.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace {{ namespace }}::c_detail { - -// Misuse of the C API, such as a NULL argument, has no error value, so it aborts. -[[noreturn]] inline void fail(const char *message) noexcept { - ::uniffi::detail::fatal(message); -} - -inline void *alloc(size_t size) { - void *data = std::malloc(size ? size : 1); - if (!data) { - fail("out of memory"); - } - return data; -} - -// Moves a C value to the heap, where its `_free` function releases it. -template -T *box(T value) { - static_assert(std::is_trivially_copyable_v, "only C values are boxed"); - auto *out = static_cast(alloc(sizeof(T))); - *out = value; - return out; -} - -inline const char *copy_string(const std::string &value) { - auto *out = static_cast(alloc(value.size() + 1)); - std::memcpy(out, value.data(), value.size()); - out[value.size()] = '\0'; - return out; -} - -} // namespace {{ namespace }}::c_detail - -struct {{ ty }}Task { - // Set by whichever runs the callback first, the result or the cancel, so it runs once. - std::shared_ptr> claimed; - // Destroying it cancels the Rust future, which is a no-op once it completed. - ::uniffi::FutureContinuation continuation; - // Runs the callback with `cancelled` set. - std::function cancel; -}; - -struct {{ ty }}Work { - ::uniffi::AsyncTask task; -}; - -{{ objects }} -{%- if !externals.is_empty() %} - -{{ externals }} -{%- endif %} - -namespace {{ namespace }}::c_detail { - -// Delivers a future's output to `deliver` on the dispatcher, never on the calling thread, -// so a callback cannot run before the call that started it returns its task. -template -::{{ ty }}Task *spawn(Future future, Deliver deliver, Cancel cancel) { - auto claimed = std::make_shared>(false); - auto executor = [](::uniffi::AsyncTask task) { - return ::uniffi::detail::dispatch_async(std::move(task)); - }; - using Output = typename Future::Output; - if constexpr (std::is_void_v) { - auto continuation = std::move(future).then(executor, [claimed, deliver]() { - if (!claimed->exchange(true)) { - deliver(); - } - }); - return new ::{{ ty }}Task{std::move(claimed), std::move(continuation), std::move(cancel)}; - } else { - auto continuation = std::move(future).then(executor, [claimed, deliver](Output output) { - if (!claimed->exchange(true)) { - deliver(std::move(output)); - } - }); - return new ::{{ ty }}Task{std::move(claimed), std::move(continuation), std::move(cancel)}; - } -} - -{{ converters }} - -} // namespace {{ namespace }}::c_detail - -void {{ ns }}_task_free({{ ty }}Task *task) { - if (!task) { - return; - } - auto cancel = std::move(task->cancel); - const bool pending = !task->claimed->exchange(true); - delete task; - // Dispatched like a result, so it never runs inside a call; a refusal drops it. - if (pending) { - (void)::uniffi::detail::dispatch_async(std::move(cancel)); - } -} - -void {{ ns }}_work_run({{ ty }}Work *work) { - if (!work) { - ::{{ namespace }}::c_detail::fail("{{ ns }}_work_run: work must not be NULL"); - } - auto task = std::move(work->task); - delete work; - task(); -} - -void {{ ns }}_set_dispatcher(const {{ ty }}Dispatcher *dispatcher) { - if (!dispatcher || !dispatcher->dispatch || !dispatcher->shutdown) { - ::{{ namespace }}::c_detail::fail("{{ ns }}_set_dispatcher: dispatch and shutdown must not be NULL"); - } - const {{ ty }}Dispatcher copy = *dispatcher; - ::uniffi::set_async_dispatcher( - [copy](::uniffi::AsyncTask task) { - auto *work = new {{ ty }}Work{std::move(task)}; - if (copy.dispatch(copy.user_data, work)) { - return true; - } - delete work; - return false; - }, - [copy]() { copy.shutdown(copy.user_data); } - ); -} - -void {{ ns }}_shutdown_dispatcher(void) { - ::uniffi::shutdown_async_dispatcher(); -} - -void {{ ns }}_string_free(char *string) { - std::free(string); -} - -{{ body }} \ No newline at end of file diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/expected.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/expected.hpp deleted file mode 100644 index caa10994b..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/expected.hpp +++ /dev/null @@ -1,11 +0,0 @@ -// Generated by uniffi-bindgen-cpp for `error_style = "expected"`. -// -// `uniffi::expected` is the bundled `tl::expected` at every C++ standard, never `std::expected`, -// so bindings built at one standard link with code built at another. -#pragma once - -{tl_expected} -namespace uniffi { -using tl::expected; -using tl::unexpected; -} // namespace uniffi diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/callback_interface.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/callback_interface.rs deleted file mode 100644 index cf059e706..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/callback_interface.rs +++ /dev/null @@ -1,50 +0,0 @@ -use uniffi_bindgen::{interface::Literal, ComponentInterface}; - -use crate::bindings::cpp::{ - gen_cpp::filters::{ - callback_interface_name, external_canonical_prefix, external_namespace_prefix, - CppCodeOracle, - }, - CodeType, -}; - -#[derive(Debug)] -pub(crate) struct CallbackInterfaceCodeType { - id: String, - module_path: String, -} - -impl CallbackInterfaceCodeType { - pub(crate) fn new(id: String, module_path: String) -> Self { - Self { id, module_path } - } -} - -impl CodeType for CallbackInterfaceCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - format!( - "std::shared_ptr<{}{}>", - external_namespace_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "{}{}", - external_canonical_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } - - fn literal(&self, _literal: &Literal, _ci: &ComponentInterface) -> String { - unreachable!(); - } - - fn initialization_fn(&self) -> Option { - Some(format!( - "uniffi::{}::init", - callback_interface_name(&self.id).unwrap() - )) - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/compounds.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/compounds.rs deleted file mode 100644 index 62a37328e..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/compounds.rs +++ /dev/null @@ -1,138 +0,0 @@ -use crate::bindings::cpp::CodeType; -use uniffi_bindgen::{ - interface::{Literal, Type}, - ComponentInterface, -}; - -use crate::bindings::cpp::gen_cpp::filters::{is_error_class, CppCodeOracle}; - -#[derive(Debug)] -pub(crate) struct OptionalCodeType { - inner: Type, -} - -impl OptionalCodeType { - pub(crate) fn new(inner: Type) -> Self { - Self { inner } - } - - pub(crate) fn can_dereference(inner_type: &Type, ci: &ComponentInterface) -> bool { - match inner_type { - Type::Object { .. } | Type::CallbackInterface { .. } => true, - Type::Enum { .. } => is_error_class(ci, inner_type), - _ => false, - } - } -} - -impl CodeType for OptionalCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - if OptionalCodeType::can_dereference(&self.inner, ci) { - CppCodeOracle.find(&self.inner).type_label(ci) - } else { - format!( - "std::optional<{}>", - CppCodeOracle.find(&self.inner).type_label(ci) - ) - } - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "Optional{}", - CppCodeOracle.find(&self.inner).canonical_name(ci), - ) - } - - fn literal(&self, literal: &Literal, ci: &ComponentInterface) -> String { - match literal { - Literal::None => { - if OptionalCodeType::can_dereference(&self.inner, ci) { - "nullptr".into() - } else { - "std::nullopt".into() - } - } - _ => CppCodeOracle.find(&self.inner).literal(literal, ci), - } - } -} - -#[derive(Debug)] -pub(crate) struct SequenceCodeType { - inner: Type, -} - -impl SequenceCodeType { - pub(crate) fn new(inner: Type) -> Self { - Self { inner } - } -} - -impl CodeType for SequenceCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - format!( - "std::vector<{}>", - CppCodeOracle.find(&self.inner).type_label(ci) - ) - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "Sequence{}", - CppCodeOracle.find(&self.inner).canonical_name(ci), - ) - } - - fn literal(&self, literal: &Literal, ci: &ComponentInterface) -> String { - match literal { - Literal::EmptySequence => "{}".into(), - _ => CppCodeOracle.find(&self.inner).literal(literal, ci), - } - } -} - -#[derive(Debug)] -pub(crate) struct MapCodeType { - key: Type, - value: Type, -} - -impl MapCodeType { - pub(crate) fn new(key: Type, value: Type) -> Self { - Self { key, value } - } - - fn key(&self) -> &Type { - &self.key - } - - fn value(&self) -> &Type { - &self.value - } -} - -impl CodeType for MapCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - format!( - "std::unordered_map<{}, {}>", - CppCodeOracle.find(self.key()).type_label(ci), - CppCodeOracle.find(self.value()).type_label(ci), - ) - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "Map{}{}", - CppCodeOracle.find(self.key()).canonical_name(ci), - CppCodeOracle.find(self.value()).canonical_name(ci), - ) - } - - fn literal(&self, literal: &Literal, ci: &ComponentInterface) -> String { - match literal { - Literal::EmptyMap => "{}".into(), - _ => CppCodeOracle.find(&self.value).literal(literal, ci), - } - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/custom.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/custom.rs deleted file mode 100644 index 221e7b5c6..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/custom.rs +++ /dev/null @@ -1,36 +0,0 @@ -use uniffi_bindgen::ComponentInterface; - -use crate::bindings::cpp::{ - gen_cpp::filters::{external_canonical_prefix, external_namespace_prefix}, - CodeType, -}; - -#[derive(Debug)] -pub struct CustomCodeType { - name: String, - module_path: String, -} - -impl CustomCodeType { - pub fn new(name: String, module_path: String) -> Self { - CustomCodeType { name, module_path } - } -} - -impl CodeType for CustomCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - format!( - "{}{}", - external_namespace_prefix(ci, &self.module_path), - self.name - ) - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "{}Type{}", - external_canonical_prefix(ci, &self.module_path), - self.name - ) - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/enum_.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/enum_.rs deleted file mode 100644 index a3945034e..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/enum_.rs +++ /dev/null @@ -1,59 +0,0 @@ -use uniffi_bindgen::{ - interface::{Literal, Type}, - ComponentInterface, -}; - -use crate::bindings::cpp::{ - gen_cpp::filters::{ - external_canonical_prefix, external_namespace_prefix, is_error_class, CppCodeOracle, - }, - CodeType, -}; -#[derive(Debug)] -pub(crate) struct EnumCodeType { - id: String, - module_path: String, -} - -impl EnumCodeType { - pub(crate) fn new(id: String, module_path: String) -> Self { - Self { id, module_path } - } - - fn as_type(&self) -> Type { - Type::Enum { - name: self.id.clone(), - module_path: self.module_path.clone(), - } - } -} - -impl CodeType for EnumCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - if is_error_class(ci, &self.as_type()) { - format!( - "std::shared_ptr<{}{}>", - external_namespace_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } else { - format!( - "{}{}", - external_namespace_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "{}{}", - external_canonical_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } - - fn literal(&self, _: &Literal, _ci: &ComponentInterface) -> String { - unreachable!(); - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs deleted file mode 100644 index 6e96e0c0a..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs +++ /dev/null @@ -1,525 +0,0 @@ -use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase}; -use uniffi_bindgen::{ - interface::{Argument, AsType, DefaultValue, Enum, FfiType, Literal, Object, Type, Variant}, - ComponentInterface, -}; - -use crate::bindings::cpp::{ - gen_cpp::{ - callback_interface, compounds, custom, enum_, miscellany, object, primitives, record, - }, - CodeType, -}; - -use super::{error_style, renamed, EnumStyle, ErrorStyle}; - -type Result = std::result::Result; - -// Keywords and other commonly used words that are in fact macros that -// expand to expressions (like `errno`). -const RESERVED_CPP_WORDS: [&str; 100] = [ - // Keywords - "alignas", - "alignof", - "and", - "and_eq", - "asm", - "atomic_cancel", - "atomic_commit", - "atomic_noexcept", - "auto", - "bitand", - "bitor", - "bool", - "break", - "case", - "catch", - "char", - "char8_t", - "char16_t", - "char32_t", - "class", - "compl", - "concept", - "const", - "consteval", - "constexpr", - "constinit", - "const_cast", - "continue", - "contract_assert", - "co_await", - "co_return", - "co_yield", - "decltype", - "default", - "delete", - "do", - "double", - "dynamic_cast", - "else", - "enum", - "explicit", - "export", - "extern", - "false", - "float", - "for", - "friend", - "goto", - "if", - "inline", - "int", - "long", - "mutable", - "namespace", - "new", - "noexcept", - "not", - "not_eq", - "nullptr", - "operator", - "or", - "or_eq", - "private", - "protected", - "public", - "reflexpr", - "register", - "reinterpret_cast", - "requires", - "return", - "short", - "signed", - "sizeof", - "static", - "static_assert", - "static_cast", - "struct", - "switch", - "synchronized", - "template", - "this", - "thread_local", - "throw", - "true", - "try", - "typedef", - "typeid", - "typename", - "union", - "unsigned", - "using", - "virtual", - "void", - "volatile", - "wchar_t", - "while", - "xor", - "xor_eq", - // Macros - "errno", - "assert", -]; - -#[derive(Clone)] -pub(crate) struct CppCodeOracle; - -impl CppCodeOracle { - pub(crate) fn find(&self, typ: &Type) -> Box { - typ.clone().as_type().as_codetype() - } - - pub(crate) fn class_name(&self, nm: &str) -> String { - nm.to_string().to_upper_camel_case() - } - - pub(crate) fn enum_variant_name(&self, nm: &str, style: &EnumStyle) -> String { - match style { - EnumStyle::Capitalized => nm.to_string().to_shouty_snake_case(), - EnumStyle::Google => format!("k{}", nm.to_string().to_upper_camel_case()), - } - } - - pub(crate) fn fn_name(&self, nm: &str) -> String { - nm.to_string().to_snake_case() - } - - pub(crate) fn var_name(&self, nm: &str) -> String { - let mut name = nm.to_string().to_snake_case(); - if RESERVED_CPP_WORDS.contains(&&*name) { - name.push('_'); - } - name - } - - pub(crate) fn object_names(&self, obj: &Object) -> (String, String) { - let class_name = self.class_name(obj.name()); - if obj.has_callback_interface() { - (class_name.clone(), format!("{class_name}Impl")) - } else { - (format!("I{class_name}"), class_name) - } - } -} - -pub(crate) trait AsCodeType { - fn as_codetype(&self) -> Box; -} - -impl AsCodeType for T { - fn as_codetype(&self) -> Box { - match renamed(self.as_type()) { - Type::UInt8 => Box::new(primitives::UInt8CodeType), - Type::Int8 => Box::new(primitives::Int8CodeType), - Type::UInt16 => Box::new(primitives::UInt16CodeType), - Type::Int16 => Box::new(primitives::Int16CodeType), - Type::UInt32 => Box::new(primitives::UInt32CodeType), - Type::Int32 => Box::new(primitives::Int32CodeType), - Type::UInt64 => Box::new(primitives::UInt64CodeType), - Type::Int64 => Box::new(primitives::Int64CodeType), - Type::Float32 => Box::new(primitives::Float32CodeType), - Type::Float64 => Box::new(primitives::Float64CodeType), - Type::Boolean => Box::new(primitives::BooleanCodeType), - Type::String => Box::new(primitives::StringCodeType), - Type::Bytes => Box::new(primitives::BytesCodeType), - Type::Timestamp => Box::new(miscellany::TimestampCodeType), - Type::Duration => Box::new(miscellany::DurationCodeType), - Type::Object { - name, - imp, - module_path, - } => Box::new(object::ObjectCodeType::new(name, imp, module_path)), - Type::Record { name, module_path } => { - Box::new(record::RecordCodeType::new(name, module_path)) - } - Type::Enum { name, module_path } => { - Box::new(enum_::EnumCodeType::new(name, module_path)) - } - Type::CallbackInterface { name, module_path } => Box::new( - callback_interface::CallbackInterfaceCodeType::new(name, module_path), - ), - Type::Optional { inner_type } => { - Box::new(compounds::OptionalCodeType::new(*inner_type)) - } - Type::Sequence { inner_type } => { - Box::new(compounds::SequenceCodeType::new(*inner_type)) - } - Type::Map { - key_type, - value_type, - } => Box::new(compounds::MapCodeType::new(*key_type, *value_type)), - // `Box` only exists for scaffolding; it crosses the FFI as a plain `T`. - Type::Box { inner_type } => inner_type.as_codetype(), - Type::Set { .. } => unimplemented!("HashSet is not supported by the C++ bindings yet"), - Type::Custom { - name, module_path, .. - } => Box::new(custom::CustomCodeType::new(name, module_path)), - } - } -} - -pub(crate) fn to_lower_snake_case(s: &str) -> Result { - Ok(s.to_string().to_snake_case()) -} - -pub(crate) fn type_name(as_ct: &impl AsCodeType, ci: &ComponentInterface) -> Result { - Ok(as_ct.as_codetype().type_label(ci)) -} - -/// The class an error is thrown as, qualified when another crate defines it. -pub(crate) fn thrown_class(as_type: &impl AsType, ci: &ComponentInterface) -> Result { - let ty = renamed(as_type.as_type()); - match (ty.name(), ty.module_path()) { - (Some(name), Some(module_path)) => Ok(format!( - "{}{}", - external_namespace_prefix(ci, module_path), - CppCodeOracle.class_name(name) - )), - _ => Err(askama::Error::Custom( - format!("{ty:?} cannot be thrown").into(), - )), - } -} - -/// How a type from another crate is qualified. From the global namespace, since a member or -/// variant of a local type may share the other crate's namespace name. -pub(crate) fn external_namespace_prefix(ci: &ComponentInterface, module_path: &str) -> String { - match external_namespace(ci, module_path) { - Some(namespace) => format!("::{namespace}::"), - None => String::new(), - } -} - -/// What an external type's canonical name starts with: its namespace in UpperCamelCase. -pub(crate) fn external_canonical_prefix(ci: &ComponentInterface, module_path: &str) -> String { - external_namespace(ci, module_path) - .map(|namespace| namespace.to_upper_camel_case()) - .unwrap_or_default() -} - -/// The namespace of a type from another crate, or `None` for a local one. -fn external_namespace<'a>(ci: &'a ComponentInterface, module_path: &str) -> Option<&'a str> { - match ci.namespace_for_module_path(module_path) { - Ok(namespace) if namespace != ci.namespace() => Some(namespace), - Ok(_) => None, - Err(e) => std::panic!("could not resolve external namespace: {e}"), - } -} - -pub(crate) fn ffi_converter_name( - as_ct: &impl AsCodeType, - ci: &ComponentInterface, -) -> Result { - Ok(as_ct.as_codetype().ffi_converter_name(ci)) -} - -pub(crate) fn ffi_error_converter_name( - as_type: &impl AsType, - ci: &ComponentInterface, -) -> Result { - let mut name = ffi_converter_name(as_type, ci)?; - - if matches!(&as_type.as_type(), Type::Object { .. }) { - name.push_str("__as_error"); - } - - Ok(name) -} - -pub(crate) fn ffi_struct_name(nm: &str) -> Result { - Ok(format!("Uniffi{}", nm)) -} - -pub(crate) fn callback_interface_name(nm: &str) -> Result { - Ok(format!("UniffiCallbackInterface{}", nm)) -} - -pub(crate) fn canonical_name(as_ct: &impl AsCodeType, ci: &ComponentInterface) -> Result { - Ok(as_ct.as_codetype().canonical_name(ci)) -} - -pub(crate) fn fn_name(nm: &str) -> Result { - Ok(CppCodeOracle.fn_name(nm)) -} - -pub(crate) fn var_name(nm: &str) -> Result { - Ok(CppCodeOracle.var_name(nm)) -} - -pub(crate) fn object_names(obj: &Object) -> Result<(String, String)> { - Ok(CppCodeOracle.object_names(obj)) -} - -pub(crate) fn literal_cpp( - default: &DefaultValue, - as_ct: &impl AsCodeType, - enum_style: &EnumStyle, - ci: &ComponentInterface, -) -> Result { - let literal = match default { - DefaultValue::Default => return Ok("{}".into()), - DefaultValue::Literal(Literal::Some { inner }) => { - return literal_cpp(inner, as_ct, enum_style, ci) - } - DefaultValue::Literal(literal) => literal, - }; - - match literal { - Literal::Enum(name, _) => Ok(format!( - "{}::{}", - as_ct.as_codetype().type_label(ci), - CppCodeOracle.enum_variant_name(name, enum_style), - )), - _ => Ok(as_ct.as_codetype().literal(literal, ci)), - } -} - -pub(crate) fn lift_fn(as_ct: &impl AsCodeType, ci: &ComponentInterface) -> Result { - Ok(format!( - "{}::lift", - as_ct.as_codetype().ffi_converter_name(ci) - )) -} - -pub(crate) fn lower_fn(as_ct: &impl AsCodeType, ci: &ComponentInterface) -> Result { - Ok(format!( - "{}::lower", - as_ct.as_codetype().ffi_converter_name(ci) - )) -} - -pub(crate) fn read_fn(as_ct: &impl AsCodeType, ci: &ComponentInterface) -> Result { - Ok(format!( - "{}::read", - as_ct.as_codetype().ffi_converter_name(ci) - )) -} - -pub(crate) fn write_fn(as_ct: &impl AsCodeType, ci: &ComponentInterface) -> Result { - Ok(format!( - "{}::write", - as_ct.as_codetype().ffi_converter_name(ci) - )) -} - -pub(crate) fn allocation_size_fn( - as_ct: &impl AsCodeType, - ci: &ComponentInterface, -) -> Result { - Ok(format!( - "{}::allocation_size", - as_ct.as_codetype().ffi_converter_name(ci) - )) -} - -pub(crate) fn variant_name(v: &Variant, enum_style: &EnumStyle) -> Result { - Ok(CppCodeOracle.enum_variant_name(v.name(), enum_style)) -} - -pub(crate) fn ffi_type_name(ffi_type: &FfiType) -> Result { - Ok(match ffi_type { - FfiType::UInt8 => "uint8_t".into(), - FfiType::Int8 => "int8_t".into(), - FfiType::UInt16 => "uint16_t".into(), - FfiType::Int16 => "int16_t".into(), - FfiType::UInt32 => "uint32_t".into(), - FfiType::Int32 => "int32_t".into(), - FfiType::UInt64 | FfiType::Handle => "uint64_t".into(), - FfiType::Int64 => "int64_t".into(), - FfiType::Float32 => "float".into(), - FfiType::Float64 => "double".into(), - FfiType::VoidPointer => "void *".into(), - FfiType::RustBuffer(_) => "RustBuffer".into(), - FfiType::ForeignBytes => "ForeignBytes".into(), - FfiType::Callback(name) if name == "RustFutureContinuationCallback" => name.clone(), - FfiType::Callback(_) => "void *".into(), - FfiType::Struct(name) => ffi_struct_name(name)?, - FfiType::RustCallStatus => "RustCallStatus*".into(), - FfiType::Reference(typ) => format!("const {} &", ffi_type_name(typ)?), - FfiType::MutReference(typ) => format!("{} &", ffi_type_name(typ)?), - }) -} - -pub(crate) fn ffi_field_type_name(ffi_type: &FfiType) -> Result { - if matches!(ffi_type, FfiType::RustCallStatus) { - Ok("RustCallStatus".into()) - } else { - ffi_type_name(ffi_type) - } -} - -pub(crate) fn class_name(nm: &str) -> Result { - Ok(CppCodeOracle.class_name(nm)) -} - -pub(crate) fn by_ref(ci: &ComponentInterface, arg: &Argument) -> bool { - match arg.as_type() { - Type::UInt8 - | Type::Int8 - | Type::UInt16 - | Type::Int16 - | Type::UInt32 - | Type::Int32 - | Type::UInt64 - | Type::Int64 - | Type::Float32 - | Type::Float64 - | Type::Boolean - | Type::Optional { .. } => false, - ty @ Type::Enum { .. } => !is_enum_struct(ci, &ty), - _ => true, - } -} - -pub(crate) fn parameter(arg: &Argument, ci: &ComponentInterface) -> Result { - Ok(match by_ref(ci, arg) { - true => format!("const {} &{}", arg.as_codetype().type_label(ci), arg.name()), - false => format!("{} {}", arg.as_codetype().type_label(ci), arg.name()), - }) -} - -pub(crate) fn docstring(docstring: &str, spaces: &i32) -> Result { - let middle = textwrap::indent(&textwrap::dedent(docstring), " * "); - let wrapped = format!("/**\n{middle}\n */"); - - Ok(textwrap::indent(&wrapped, &" ".repeat(*spaces as usize))) -} - -pub(crate) fn can_dereference_optional(type_: &Type, ci: &ComponentInterface) -> Result { - let result = match type_ { - Type::Optional { inner_type } => { - compounds::OptionalCodeType::can_dereference(inner_type, ci) - } - _ => false, - }; - Ok(result) -} - -/// Whether an error enum renders as an exception class held by `std::shared_ptr`. Under the -/// expected style it is a plain value type like any other enum. -pub(crate) fn is_error_class(ci: &ComponentInterface, ty: &Type) -> bool { - ci.is_used_as_error(ty) && error_style() == ErrorStyle::Exceptions -} - -/// Whether an enum renders as a struct holding a `std::variant` rather than an `enum class`. -/// A flat error is a struct under the expected style because each variant carries a message. -pub(crate) fn is_enum_struct(ci: &ComponentInterface, ty: &Type) -> bool { - let flat = enum_definition(ci, ty).is_some_and(|e| e.is_flat()); - !flat || (ci.is_used_as_error(ty) && error_style() == ErrorStyle::Expected) -} - -/// The definition of an enum, from whichever crate defines it. -pub(crate) fn enum_definition<'a>(ci: &'a ComponentInterface, ty: &Type) -> Option<&'a Enum> { - let Type::Enum { name, .. } = ty else { - return None; - }; - defining_interface(ci, ty).get_enum_definition(name) -} - -/// The interface of the crate that defines a named type. -pub(crate) fn defining_interface<'a>( - ci: &'a ComponentInterface, - ty: &Type, -) -> &'a ComponentInterface { - match ty.crate_name() { - Some(crate_name) if crate_name != ci.crate_name() => ci - .find_component_interface(crate_name) - .unwrap_or_else(|| panic!("no interface for crate {crate_name}")), - _ => ci, - } -} - -pub(crate) fn error_class(ty: &Type, ci: &ComponentInterface) -> Result { - Ok(is_error_class(ci, ty)) -} - -pub(crate) fn enum_struct(ty: &Type, ci: &ComponentInterface) -> Result { - Ok(is_enum_struct(ci, ty)) -} - -pub(crate) fn cpp_deref(type_: Type, ci: &ComponentInterface) -> Result { - if matches!(type_, Type::Enum { .. }) && is_error_class(ci, &type_) { - return Ok("*".to_string()); - } - Ok("".to_string()) -} - -/// A C or C++ string literal holding `value`. -pub(crate) fn string_literal(value: &str) -> String { - let mut out = String::from("\""); - for c in value.chars() { - match c { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - // Octal, which unlike `\x` cannot swallow the characters after it. - c if (c as u32) < 0x20 => out.push_str(&format!("\\{:03o}", c as u32)), - c => out.push(c), - } - } - out.push('"'); - out -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/miscellany.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/miscellany.rs deleted file mode 100644 index 0422d62a8..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/miscellany.rs +++ /dev/null @@ -1,37 +0,0 @@ -use crate::bindings::cpp::CodeType; -use paste::paste; -use uniffi_bindgen::{interface::Literal, ComponentInterface}; - -macro_rules! impl_code_type_for_miscellany { - ($T:ty, $label:literal, $canonical_name:literal) => { - paste! { - #[derive(Debug)] - pub(crate) struct $T; - - impl CodeType for $T { - fn type_label(&self, _ci: &ComponentInterface) -> String { - format!("{}", $label) - } - - fn canonical_name(&self, _ci: &ComponentInterface) -> String { - format!("{}", $canonical_name) - } - - fn literal(&self, _literal: &Literal, _ci: &ComponentInterface) -> String { - unreachable!() - } - } - } - }; -} - -impl_code_type_for_miscellany!( - TimestampCodeType, - "std::chrono::time_point", - "Timestamp" -); -impl_code_type_for_miscellany!( - DurationCodeType, - "std::chrono::duration", - "Duration" -); diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/mod.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/mod.rs deleted file mode 100644 index deaaec49b..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/mod.rs +++ /dev/null @@ -1,542 +0,0 @@ -mod callback_interface; -mod compounds; -mod custom; -mod enum_; -pub(crate) mod filters; -mod miscellany; -mod object; -mod primitives; -mod record; - -use std::{ - borrow::Borrow, - cell::{Cell, RefCell}, - collections::{BTreeSet, HashMap}, - format, -}; - -use anyhow::{Context, Result}; -use askama::Template; -use filters::CppCodeOracle; -use serde::{Deserialize, Serialize}; -use topological_sort::{DependencyLink, TopologicalSort}; -use uniffi_bindgen::{interface::*, ComponentInterface}; - -use crate::bindings::cpp::gen_cpp::filters::{callback_interface_name, defining_interface}; - -#[derive(Serialize, Deserialize, Clone, Debug, Default)] -pub enum EnumStyle { - Capitalized, - #[default] - Google, -} - -#[derive(Clone, Deserialize, Serialize, Debug, Default)] -struct CustomTypesConfig { - imports: Option>, - type_name: Option, - into_custom: String, - from_custom: String, -} - -impl CustomTypesConfig { - fn lift(&self, name: &str) -> String { - self.into_custom.replace("{}", name) - } - fn lower(&self, name: &str) -> String { - self.from_custom.replace("{}", name) - } -} - -/// How generated functions report a Rust error. -#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ErrorStyle { - /// Throw the error as a C++ exception. - #[default] - Exceptions, - /// Return `uniffi::expected` and never throw, so the bindings build with - /// exceptions disabled. - Expected, -} - -thread_local! { - // The type oracle renders type labels without access to the config, and the error style - // changes how an error type is spelled, so generation publishes it here. - static ERROR_STYLE: Cell = const { Cell::new(ErrorStyle::Exceptions) }; - - // uniffi's `rename` misses some types, such as a constructor's error, so the oracle renames - // each type it renders as well. - static RENAMES: RefCell = RefCell::default(); -} - -pub(crate) fn error_style() -> ErrorStyle { - ERROR_STYLE.with(Cell::get) -} - -/// New type names by crate and old name, since another crate may use the old name for a type -/// of its own. -pub(crate) type Renames = HashMap<(String, String), String>; - -/// `ty` with every type it names under its new name. -pub(crate) fn renamed(mut ty: Type) -> Type { - RENAMES.with(|renames| { - let renames = renames.borrow(); - if !renames.is_empty() { - rename_type(&mut ty, &renames); - } - }); - ty -} - -fn rename_type(ty: &mut Type, renames: &Renames) { - let crate_name = ty.crate_name().map(str::to_string); - match ty { - Type::Object { name, .. } - | Type::Record { name, .. } - | Type::Enum { name, .. } - | Type::CallbackInterface { name, .. } - | Type::Custom { name, .. } => { - if let Some(new) = renames.get(&(crate_name.unwrap_or_default(), name.clone())) { - *name = new.clone(); - } - } - _ => {} - } - match ty { - Type::Optional { inner_type } - | Type::Sequence { inner_type } - | Type::Set { inner_type } - | Type::Box { inner_type } => rename_type(inner_type, renames), - Type::Map { - key_type, - value_type, - } => { - rename_type(key_type, renames); - rename_type(value_type, renames); - } - Type::Custom { builtin, .. } => rename_type(builtin, renames), - _ => {} - } -} - -#[derive(Clone, Deserialize, Serialize, Debug, Default)] -pub(crate) struct Config { - #[serde(default)] - custom_types: HashMap, - #[serde(default)] - enum_style: EnumStyle, - #[serde(default)] - error_style: ErrorStyle, - #[serde(default)] - strip_type_prefix: Option, - /// Every type renamed by `strip_type_prefix`, across all components. - #[serde(skip)] - pub(crate) renames: Renames, -} - -impl Config { - pub(crate) fn expected(&self) -> bool { - self.error_style == ErrorStyle::Expected - } - - /// This configuration with errors returned rather than thrown. - pub(crate) fn with_expected(&self) -> Self { - Self { - error_style: ErrorStyle::Expected, - ..self.clone() - } - } - - pub(crate) fn enum_style(&self) -> &EnumStyle { - &self.enum_style - } - - pub(crate) fn strip_type_prefix(&self) -> Option<&str> { - self.strip_type_prefix.as_deref() - } -} - -#[derive(Template)] -#[template(syntax = "cpp", escape = "none", path = "internal_types.cpp")] -struct InternalTypeRenderer<'a> { - ci: &'a ComponentInterface, -} - -#[derive(Template)] -#[template(syntax = "cpp", escape = "none", path = "types.cpp")] -struct TypeRenderer<'a> { - ci: &'a ComponentInterface, - config: &'a Config, -} - -#[derive(Template)] -#[template(syntax = "cpp", escape = "none", path = "scaffolding.hpp")] -struct ScaffoldingHeader<'a> { - ci: &'a ComponentInterface, -} - -impl<'a> ScaffoldingHeader<'a> { - fn new(ci: &'a ComponentInterface) -> Self { - Self { ci } - } - - pub fn scaffolding_definitions(&self) -> impl Iterator + '_ { - self.ci - .callback_interface_definitions() - .iter() - .map(|cb| cb.vtable_definition()) - .chain( - self.ci - .object_definitions() - .iter() - .flat_map(|o| o.vtable_definition()), - ) - .map(Into::into) - .chain(self.ci.iter_ffi_function_definitions().map(Into::into)) - } - - pub fn foreign_future_struct_definitions(&self) -> impl Iterator + '_ { - self.ci - .ffi_definitions() - .filter_map(|definition| match definition { - FfiDefinition::Struct(ffi_struct) - if ffi_struct.name().starts_with("ForeignFuture") => - { - Some(ffi_struct) - } - _ => None, - }) - } -} - -#[derive(Template)] -#[template(syntax = "cpp", escape = "none", path = "wrapper.hpp")] -struct CppWrapperHeader<'a> { - ci: &'a ComponentInterface, - config: &'a Config, - includes: RefCell>, -} - -impl<'a> CppWrapperHeader<'a> { - fn new(ci: &'a ComponentInterface, config: &'a Config) -> Self { - let includes = config.custom_types.values().fold( - BTreeSet::new(), - |mut acc: BTreeSet, custom_type| { - if let Some(imports) = &custom_type.imports { - acc.extend(imports.iter().cloned()); - } - acc - }, - ); - - Self { - ci, - config, - includes: includes.into(), - } - } - - // XXX: This is somewhat evil, but necessary. - // Context: C++. - // - // Certain types (e.g. records or objects) may depend on other types - // defined within the same interface definition, yet they have to be - // defined so in a specific order. This here method sorts types in - // different ways as required by different types. - pub(crate) fn sorted_types( - &self, - types: impl Iterator, - ) -> impl Iterator { - let mut definition_topology = self - .ci - .iter_local_types() - .filter_map(|type_| { - // We take into account only the Record and Enum types, as they are the - // only types that can have member variables that reference other structures - match type_ { - Type::Record { name, .. } => self - .ci - .get_record_definition(name.as_str()) - .map(|record| (name, record.iter_types())), - Type::Enum { name, .. } => self - .ci - .get_enum_definition(name.as_str()) - .map(|enum_| (name, enum_.iter_types())), - _ => None, - } - }) - .flat_map(|(name, types)| { - // An external type is defined in its own namespace's header, which we - // `#include`, so it never orders a local definition. It may also share its - // bare name with a local type. - types - .filter(|t| !self.ci.is_external(t)) - .filter_map(type_name) - .map(|field_name| DependencyLink { - prec: field_name, - succ: name, - }) - }) - .collect::>(); - - let mut sorted: Vec = Vec::new(); - let mut emitted_names = BTreeSet::new(); - while !definition_topology.peek_all().is_empty() { - let mut list = definition_topology.pop_all(); - list.sort(); - for name in list { - // TopologicalSort preserves duplicate dependency links. A record or - // rich enum can mention the same named type more than once, causing - // that type to be returned once per link. Definitions, however, - // must be emitted exactly once. - if !emitted_names.insert(name) { - continue; - } - // Not `ci.get_type`: uniffi's `rename` leaves that index under the old names. - let found = self - .ci - .iter_local_types() - .find(|t| type_name(t) == Some(name)); - match found { - Some(type_) => sorted.push(type_.clone()), - None => { - panic!("Type {} not found", name) - } - } - } - } - - if !definition_topology.is_empty() { - panic!("Cyclic dependency detected"); - } - - let rest = types - .filter(|t| type_name(t).is_none_or(|name| !emitted_names.contains(name))) - .cloned() - .collect::>(); - - sorted.into_iter().chain(rest) - } - - pub(crate) fn external_namespaces(&self) -> Vec { - self.ci - .iter_external_types() - .filter_map(|ty| self.ci.namespace_for_type(ty).ok()) - .filter(|namespace| *namespace != self.ci.namespace()) - .map(str::to_string) - .collect::>() - .into_iter() - .collect() - } - - /// Each external converter as `(local name, its own namespace's name)`. The local name - /// carries the namespace, so it never shadows the converter of a local namesake. - pub(crate) fn external_ffi_converters(&self) -> Vec<(String, String)> { - let mut converters = BTreeSet::new(); - for ty in self.ci.iter_external_types() { - let Ok(namespace) = self.ci.namespace_for_type(ty) else { - continue; - }; - if namespace == self.ci.namespace() { - continue; - } - let code = CppCodeOracle.find(ty); - let own = code.ffi_converter_name(defining_interface(self.ci, ty)); - let local = code.ffi_converter_name(self.ci); - if matches!(ty, Type::Object { .. }) && self.ci.is_used_as_error(ty) { - converters.insert(( - format!("{local}__as_error"), - format!("::{namespace}::uniffi::{own}__as_error"), - )); - } - converters.insert((local, format!("::{namespace}::uniffi::{own}"))); - } - converters.into_iter().collect() - } - - pub(crate) fn includes(&self) -> Vec { - self.includes.borrow().iter().cloned().collect() - } -} - -fn type_name(ty: &Type) -> Option<&str> { - match ty { - Type::Record { name, .. } - | Type::Object { name, .. } - | Type::Enum { name, .. } - | Type::Custom { name, .. } => Some(name), - _ => None, - } -} - -#[allow(dead_code)] -#[derive(Template)] -#[template(syntax = "cpp", escape = "none", path = "wrapper.cpp")] -struct CppWrapper<'a> { - ci: &'a ComponentInterface, - config: &'a Config, - internal_type_helper_code: String, - type_helper_code: String, -} - -impl<'a> CppWrapper<'a> { - pub(crate) fn new(ci: &'a ComponentInterface, config: &'a Config) -> Self { - Self { - ci, - config, - internal_type_helper_code: InternalTypeRenderer { ci }.render().unwrap(), - type_helper_code: TypeRenderer { ci, config }.render().unwrap(), - } - } - - pub(crate) fn initialization_fns(&self) -> Vec { - // Local callback/trait interfaces register their own vtable init. - let local_types = self - .ci - .iter_local_types() - .map(|t| CppCodeOracle.find(t)) - .filter_map(|ct| ct.initialization_fn()); - - // External foreign-implementable callback/trait interfaces' vtable is registered in - // the defining namespace, but the consuming namespace must still call its `init()` so Rust - // can call back into a foreign implementation passed across - let external_types = self - .ci - .iter_external_types() - .filter(|t| match t { - Type::Object { imp, .. } => imp.has_callback_interface(), - Type::CallbackInterface { .. } => true, - _ => false, - }) - .filter_map(|t| { - let namespace = self.ci.namespace_for_type(t).ok()?; - let canonical = CppCodeOracle - .find(t) - .canonical_name(defining_interface(self.ci, t)); - Some(format!( - "{}::uniffi::{}::init", - namespace, - callback_interface_name(&canonical).ok()? - )) - }); - - local_types.chain(external_types).collect() - } -} - -/// The first async function, constructor, or method, including those a foreign -/// implementation provides. -fn first_async(ci: &ComponentInterface) -> Option { - let functions = ci - .function_definitions() - .iter() - .filter(|func| func.is_async()) - .map(|func| func.name().to_string()); - let objects = ci.object_definitions().iter().flat_map(|obj| { - let constructors = obj - .constructors() - .into_iter() - .filter(|ctor| ctor.is_async()) - .map(|ctor| ctor.name()); - let methods = obj - .methods() - .into_iter() - .filter(|method| method.is_async()) - .map(|method| method.name()); - constructors - .chain(methods) - .map(move |name| format!("{}::{name}", obj.name())) - }); - let callbacks = ci.callback_interface_definitions().iter().flat_map(|cbi| { - cbi.methods() - .into_iter() - .filter(|method| method.is_async()) - .map(move |method| format!("{}::{}", cbi.name(), method.name())) - }); - functions.chain(objects).chain(callbacks).next() -} - -pub(crate) struct Bindings { - pub(crate) scaffolding_header: String, - pub(crate) header: String, - pub(crate) source: String, -} - -pub(crate) fn generate_cpp_bindings(ci: &ComponentInterface, config: &Config) -> Result { - if config.expected() { - // Foreign implementations report failure by throwing, which has no expected-style - // design yet. - if let Some(name) = ci - .callback_interface_definitions() - .iter() - .map(|cbi| cbi.name()) - .chain( - ci.object_definitions() - .iter() - .filter(|obj| obj.has_callback_interface()) - .map(|obj| obj.name()), - ) - .next() - { - anyhow::bail!( - "error_style = \"expected\" does not support callback interfaces yet, but `{name}` is one" - ); - } - } else if let Some(name) = first_async(ci) { - anyhow::bail!("async needs error_style = \"expected\", but `{name}` is async"); - } - ERROR_STYLE.with(|style| style.set(config.error_style)); - RENAMES.with(|renames| renames.replace(config.renames.clone())); - - let scaffolding_header = ScaffoldingHeader::new(ci) - .render() - .context("generating scaffolding header failed")?; - let header = CppWrapperHeader::new(ci, config) - .render() - .context("generating C++ bindings header failed")?; - let source = CppWrapper::new(ci, config) - .render() - .context("generating C++ bindings failed")?; - - Ok(Bindings { - scaffolding_header, - header, - source, - }) -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn renames_only_the_crate_that_stripped() { - let record = |module_path: &str, name: &str| Type::Record { - module_path: module_path.to_string(), - name: name.to_string(), - }; - let renames: Renames = [(("net".into(), "MoqFrame".into()), "Frame".into())].into(); - let mut ty = Type::Map { - key_type: Box::new(Type::String), - value_type: Box::new(Type::Optional { - inner_type: Box::new(record("net::frame", "MoqFrame")), - }), - }; - rename_type(&mut ty, &renames); - let Type::Map { value_type, .. } = &ty else { - unreachable!() - }; - assert_eq!( - **value_type, - Type::Optional { - inner_type: Box::new(record("net::frame", "Frame")) - } - ); - - // `media` did not strip its prefix, so its own `MoqFrame` keeps the name. - let mut ty = record("media", "MoqFrame"); - rename_type(&mut ty, &renames); - assert_eq!(ty, record("media", "MoqFrame")); - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/object.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/object.rs deleted file mode 100644 index c15d39ac8..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/object.rs +++ /dev/null @@ -1,60 +0,0 @@ -use uniffi_bindgen::{ - interface::{Literal, ObjectImpl}, - ComponentInterface, -}; - -use crate::bindings::cpp::{ - gen_cpp::filters::{ - callback_interface_name, external_canonical_prefix, external_namespace_prefix, - CppCodeOracle, - }, - CodeType, -}; - -#[derive(Debug)] -pub(crate) struct ObjectCodeType { - id: String, - imp: ObjectImpl, - module_path: String, -} - -impl ObjectCodeType { - pub(crate) fn new(id: String, imp: ObjectImpl, module_path: String) -> Self { - Self { - id, - imp, - module_path, - } - } -} - -impl CodeType for ObjectCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - format!( - "std::shared_ptr<{}{}>", - external_namespace_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "{}{}", - external_canonical_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } - - fn literal(&self, _literal: &Literal, _ci: &ComponentInterface) -> String { - unreachable!(); - } - - fn initialization_fn(&self) -> Option { - self.imp.has_callback_interface().then(|| { - format!( - "uniffi::{}::init", - callback_interface_name(&CppCodeOracle.class_name(&self.id)).unwrap() - ) - }) - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/primitives.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/primitives.rs deleted file mode 100644 index c5827fc86..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/primitives.rs +++ /dev/null @@ -1,68 +0,0 @@ -use crate::bindings::cpp::CodeType; -use paste::paste; -use uniffi_bindgen::{ - interface::{Literal, Radix}, - ComponentInterface, -}; - -fn render_literal(literal: &Literal) -> String { - match literal { - Literal::Boolean(v) => { - if *v { - "true".into() - } else { - "false".into() - } - } - Literal::String(s) => super::filters::string_literal(s), - Literal::Int(i, radix, _) => match radix { - Radix::Octal => format!("{i:o}"), - Radix::Decimal => format!("{i}"), - Radix::Hexadecimal => format!("{i:#x}"), - }, - Literal::UInt(i, radix, _) => match radix { - Radix::Octal => format!("{i:o}U"), - Radix::Decimal => format!("{i}U"), - Radix::Hexadecimal => format!("{i:#x}U"), - }, - Literal::Float(string, _type_) => string.clone(), - - _ => unreachable!("Literal"), - } -} - -macro_rules! impl_code_type_for_primitive { - ($T:ty, $cpp_name:literal, $canonical_name:literal) => { - paste! { - #[derive(Debug)] - pub(crate) struct $T; - impl CodeType for $T { - fn type_label(&self, _ci: &ComponentInterface) -> String { - $cpp_name.into() - } - - fn canonical_name(&self, _ci: &ComponentInterface) -> String { - $canonical_name.into() - } - - fn literal(&self, literal: &Literal, _ci: &ComponentInterface) -> String { - render_literal(&literal) - } - } - } - }; -} - -impl_code_type_for_primitive!(BooleanCodeType, "bool", "Bool"); -impl_code_type_for_primitive!(StringCodeType, "std::string", "String"); -impl_code_type_for_primitive!(BytesCodeType, "std::vector", "Bytes"); -impl_code_type_for_primitive!(Int8CodeType, "int8_t", "Int8"); -impl_code_type_for_primitive!(Int16CodeType, "int16_t", "Int16"); -impl_code_type_for_primitive!(Int32CodeType, "int32_t", "Int32"); -impl_code_type_for_primitive!(Int64CodeType, "int64_t", "Int64"); -impl_code_type_for_primitive!(UInt8CodeType, "uint8_t", "UInt8"); -impl_code_type_for_primitive!(UInt16CodeType, "uint16_t", "UInt16"); -impl_code_type_for_primitive!(UInt32CodeType, "uint32_t", "UInt32"); -impl_code_type_for_primitive!(UInt64CodeType, "uint64_t", "UInt64"); -impl_code_type_for_primitive!(Float32CodeType, "float", "Float"); -impl_code_type_for_primitive!(Float64CodeType, "double", "Double"); diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/record.rs b/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/record.rs deleted file mode 100644 index f34d854e1..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/gen_cpp/record.rs +++ /dev/null @@ -1,40 +0,0 @@ -use uniffi_bindgen::{interface::Literal, ComponentInterface}; - -use crate::bindings::cpp::{ - gen_cpp::filters::{external_canonical_prefix, external_namespace_prefix, CppCodeOracle}, - CodeType, -}; - -#[derive(Debug)] -pub(crate) struct RecordCodeType { - id: String, - module_path: String, -} - -impl RecordCodeType { - pub(crate) fn new(id: String, module_path: String) -> Self { - Self { id, module_path } - } -} - -impl CodeType for RecordCodeType { - fn type_label(&self, ci: &ComponentInterface) -> String { - format!( - "{}{}", - external_namespace_prefix(ci, &self.module_path), - CppCodeOracle.class_name(&self.id) - ) - } - - fn canonical_name(&self, ci: &ComponentInterface) -> String { - format!( - "{}Type{}", - external_canonical_prefix(ci, &self.module_path), - self.id - ) - } - - fn literal(&self, _literal: &Literal, _ci: &ComponentInterface) -> String { - unreachable!(); - } -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/mod.rs b/uniffi/cpp/bindgen/src/bindings/cpp/mod.rs deleted file mode 100644 index c3ff36cf9..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/mod.rs +++ /dev/null @@ -1,169 +0,0 @@ -pub(crate) mod gen_cpp; - -use std::{ - collections::{BTreeSet, HashMap}, - fmt::Debug, - fs, -}; - -use anyhow::Result; -use camino::Utf8Path; -use uniffi_bindgen::{ - interface::{rename, Literal, Type}, - BindingGenerator, Component, ComponentInterface, GenerationSettings, -}; - -use self::gen_cpp::{generate_cpp_bindings, Bindings}; - -pub(crate) struct CppBindingGenerator; - -/// A Trait to help render types in a language specific format. -pub trait CodeType: Debug { - /// The language specific label used to reference this type. This will be used in - /// method signatures and property declarations. - fn type_label(&self, ci: &ComponentInterface) -> String; - - /// A representation of this type label that can be used as part of another - /// identifier. e.g. `read_foo()`, or `FooInternals`. - /// - /// This is especially useful when creating specialized objects or methods to deal - /// with this type only. Another crate's type is spelled with its namespace in front, so - /// the helpers for it never collide with those for a local type of the same name. - fn canonical_name(&self, ci: &ComponentInterface) -> String; - - fn literal(&self, _literal: &Literal, ci: &ComponentInterface) -> String { - unimplemented!("Unimplemented for {}", self.type_label(ci)) - } - - /// Name of the FfiConverter - fn ffi_converter_name(&self, ci: &ComponentInterface) -> String { - format!("FfiConverter{}", self.canonical_name(ci)) - } - - /// A list of imports that are needed if this type is in use. - /// Classes are imported exactly once. - #[allow(dead_code)] - fn imports(&self) -> Option> { - None - } - - /// Function to run at startup - fn initialization_fn(&self) -> Option { - None - } -} - -impl BindingGenerator for CppBindingGenerator { - type Config = gen_cpp::Config; - - fn new_config(&self, root_toml: &toml::Value) -> Result { - Ok(match root_toml.get("bindings").and_then(|b| b.get("cpp")) { - Some(v) => v.clone().try_into()?, - None => Default::default(), - }) - } - - fn update_component_configs( - &self, - _settings: &GenerationSettings, - components: &mut Vec>, - ) -> Result<()> { - // Keyed by crate, so a component that imports a renamed type sees the new name too. - let mut renames = HashMap::new(); - for Component { ci, config, .. } in components.iter() { - if let Some(prefix) = config.strip_type_prefix() { - renames.insert(ci.crate_name().to_string(), strip_type_prefix(ci, prefix)?); - } - } - if renames.is_empty() { - return Ok(()); - } - - let flat: HashMap<(String, String), String> = renames - .iter() - .flat_map(|(crate_name, table)| { - table.iter().filter_map(move |(old, new)| { - Some(((crate_name.clone(), old.clone()), new.as_str()?.to_string())) - }) - }) - .collect(); - for component in components.iter_mut() { - rename(&mut component.ci, &renames); - component.config.renames = flat.clone(); - } - Ok(()) - } - - fn write_bindings( - &self, - settings: &GenerationSettings, - components: &[uniffi_bindgen::Component], - ) -> Result<()> { - for Component { ci, config, .. } in components { - write_cpp_bindings(&settings.out_dir, ci, config)?; - } - - Ok(()) - } -} - -/// Renames each local record, object, enum, and callback interface named `` to -/// ``, where `` starts with an uppercase letter. Custom types keep their names, since -/// `custom_types` is keyed by them. Refuses a rename onto a name that is already a type. -fn strip_type_prefix(ci: &ComponentInterface, prefix: &str) -> Result { - let names: BTreeSet<&str> = ci.iter_local_types().filter_map(Type::name).collect(); - - let mut renames = toml::Table::new(); - for ty in ci.iter_local_types() { - let name = match ty { - Type::Record { name, .. } - | Type::Object { name, .. } - | Type::Enum { name, .. } - | Type::CallbackInterface { name, .. } => name, - _ => continue, - }; - let Some(stripped) = name.strip_prefix(prefix) else { - continue; - }; - if !stripped.starts_with(|c: char| c.is_ascii_uppercase()) { - continue; - } - anyhow::ensure!( - !names.contains(stripped), - "strip_type_prefix = \"{prefix}\" renames `{name}` to `{stripped}`, which is already a type" - ); - renames.insert(name.clone(), stripped.into()); - } - Ok(renames) -} - -/// Writes `.hpp`, `.cpp`, and `_scaffolding.hpp`, plus -/// `uniffi_expected.hpp` under the expected error style. -pub(crate) fn write_cpp_bindings( - out_dir: &Utf8Path, - ci: &ComponentInterface, - config: &gen_cpp::Config, -) -> Result<()> { - let Bindings { - scaffolding_header, - header, - source, - } = generate_cpp_bindings(ci, config)?; - let namespace = ci.namespace(); - - // Askama drops each template's final newline, which trips `-Wnewline-eof`. - fs::write( - out_dir.join(format!("{namespace}_scaffolding.hpp")), - scaffolding_header + "\n", - )?; - fs::write(out_dir.join(format!("{namespace}.hpp")), header + "\n")?; - fs::write(out_dir.join(format!("{namespace}.cpp")), source + "\n")?; - - if config.expected() { - let expected = include_str!("expected.hpp") - .replace("{tl_expected}", include_str!("vendor/tl_expected.hpp")); - fs::write(out_dir.join("uniffi_expected.hpp"), expected)?; - } - - Ok(()) -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/arith_conv.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/arith_conv.cpp deleted file mode 100644 index 336a9812d..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/arith_conv.cpp +++ /dev/null @@ -1,22 +0,0 @@ -{{ type_name }} {{ ffi_converter_name }}::lift({{ type_name }} val) { - return val; -} - -{{ type_name }} {{ ffi_converter_name }}::lower({{ type_name }} val) { - return val; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - {{ type_name }} ret; - stream >> ret; - - return ret; -} - -void {{ ffi_converter_name }}::write(RustStream &stream, {{ type_name }} val) { - stream << val; -} - -uint64_t {{ ffi_converter_name }}::allocation_size({{ type_name }}) { - return static_cast(sizeof({{ type_name }})); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/arith_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/arith_conv.hpp deleted file mode 100644 index fe682c488..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/arith_conv.hpp +++ /dev/null @@ -1,7 +0,0 @@ -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift({{ type_name }}); - static {{ type_name }} lower({{ type_name }}); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, {{ type_name }}); - static uint64_t allocation_size({{ type_name }}); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/async.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/async.cpp deleted file mode 100644 index dcb84b492..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/async.cpp +++ /dev/null @@ -1,190 +0,0 @@ -constexpr int8_t UNIFFI_RUST_FUTURE_POLL_READY = 0; -constexpr int8_t UNIFFI_RUST_FUTURE_POLL_WAKE = 1; -constexpr int8_t UNIFFI_RUST_CALL_ERROR = 1; -constexpr int8_t UNIFFI_RUST_CALL_CANCELLED = 3; - -// Completes a Rust future whose result nobody will collect, then drops that result. -// `rust_future_free` alone discards a ready result without releasing it, which leaks -// its buffer or object handle. Completing a future that is not ready yields `Cancelled`. -template -void release_uncollected(uint64_t handle, Complete &complete, Lift &lift, ErrorHandler &error_handler) noexcept { - RustCallStatus status{}; - if constexpr (std::is_null_pointer_v) { - complete(handle, &status); - } else { - auto value = complete(handle, &status); - if (status.code == 0) { - (void)lift(value); - } - } - if (status.code == UNIFFI_RUST_CALL_ERROR) { - if constexpr (!std::is_null_pointer_v) { - (void)error_handler(status.error_buf); - } else { - rustbuffer_free(status.error_buf); - } - } else if (status.code != 0 && status.code != UNIFFI_RUST_CALL_CANCELLED) { - rustbuffer_free(status.error_buf); - } -} -// Drives one Rust future. The handle is freed only when the last reference to this state -// drops: a pending poll and an in-progress `cancel()` each hold one, so neither can race -// the free. -template -class RustFutureState: public std::enable_shared_from_this> { -public: - using Output = ::uniffi::FutureOutput; - using Completion = ::uniffi::detail::FutureCompletionState; - - RustFutureState( - uint64_t handle, - Poll poll, - Cancel cancel, - Complete complete, - Free free, - Lift lift, - ErrorHandler error_handler, - std::shared_ptr completion_state - ): - handle_(handle), - poll_(std::move(poll)), - cancel_(std::move(cancel)), - complete_(std::move(complete)), - free_(std::move(free)), - lift_(std::move(lift)), - error_handler_(std::move(error_handler)), - completion_state_(std::move(completion_state)) {} - - RustFutureState(const RustFutureState &) = delete; - RustFutureState &operator=(const RustFutureState &) = delete; - - ~RustFutureState() { - if (!finished_.load()) { - release_uncollected(handle_, complete_, lift_, error_handler_); - } - free_(handle_); - } - - void poll() noexcept { - using State = RustFutureState; - auto *callback_state = new std::shared_ptr(this->shared_from_this()); - poll_(handle_, &RustFutureState::continuation, reinterpret_cast(callback_state)); - } - - void cancel() noexcept { - if (!finished_.load()) { - cancelled_.store(true); - cancel_(handle_); - } - } - -private: - static void continuation(uint64_t callback_data, int8_t poll_result) noexcept { - using State = RustFutureState; - auto callback_state = std::unique_ptr>( - reinterpret_cast *>(callback_data) - ); - auto state = *callback_state; - - if (!::uniffi::detail::dispatch_async( - [state, poll_result]() { - state->resume(poll_result); - } - )) { - // Nothing will poll again, so drop the Rust future with the last reference. - state->abandon(); - } - } - - void resume(int8_t poll_result) noexcept { - if (poll_result == UNIFFI_RUST_FUTURE_POLL_WAKE) { - poll(); - } else if (poll_result == UNIFFI_RUST_FUTURE_POLL_READY) { - complete(); - } else { - ::uniffi::detail::fatal("Unexpected UniFFI Rust future poll result"); - } - } - - void complete() noexcept { - if (finished_.exchange(true)) { - return; - } - - RustCallStatus status{}; - using Stored = typename Completion::Stored; - std::optional result; - if constexpr (std::is_void_v) { - complete_(handle_, &status); - if (status.code == 0) { - result.emplace(); - } - } else { - auto value = complete_(handle_, &status); - if (status.code == 0) { - // Lifted even when cancelled, so the value's buffer or handle is released. - result.emplace(lift_(value)); - } - } - - if (status.code == UNIFFI_RUST_CALL_CANCELLED) { - completion_state_->abandon(); - return; - } - if (status.code == UNIFFI_RUST_CALL_ERROR) { - if constexpr (!std::is_void_v) { - result.emplace(::uniffi::unexpected(error_handler_(status.error_buf))); - } - } - check_rust_call(status, error_handler_); - - if (cancelled_.load()) { - completion_state_->abandon(); - } else { - completion_state_->complete(std::move(*result)); - } - } - - // Leaves `finished_` unset so the destructor releases the Rust result. - void abandon() noexcept { - completion_state_->abandon(); - } - - uint64_t handle_; - Poll poll_; - Cancel cancel_; - Complete complete_; - Free free_; - Lift lift_; - ErrorHandler error_handler_; - std::shared_ptr completion_state_; - std::atomic cancelled_ = false; - std::atomic finished_ = false; -}; - -template -::uniffi::Future rust_call_async( - RustFuture rust_future, - Poll poll, - Cancel cancel, - Complete complete, - Free free, - Lift lift, - ErrorHandler error_handler -) { - initialize(); - const auto handle = rust_future(); - using State = RustFutureState; - - auto completion_state = std::make_shared(); - auto state = std::make_shared( - handle, poll, cancel, complete, free, lift, error_handler, completion_state - ); - state->poll(); - - return ::uniffi::Future(std::move(completion_state), [weak_state = std::weak_ptr(state)]() { - if (auto state = weak_state.lock()) { - state->cancel(); - } - }); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/async.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/async.hpp deleted file mode 100644 index f9dc7ee45..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/async.hpp +++ /dev/null @@ -1,445 +0,0 @@ - -namespace detail { - -// Reports a bug the expected style has no error value for, such as a Rust panic, and aborts. -[[noreturn]] inline void fatal(const char *message) noexcept { - std::fprintf(stderr, "uniffi: %s\n", message); - std::fflush(stderr); - std::abort(); -} - -} // namespace detail - -using AsyncTask = std::function; -using AsyncDispatcher = std::function; -using AsyncDispatcherShutdown = std::function; - -namespace detail { - -class DefaultAsyncDispatcher { -public: - DefaultAsyncDispatcher(): worker_([this] { run(); }) {} - - DefaultAsyncDispatcher(const DefaultAsyncDispatcher &) = delete; - DefaultAsyncDispatcher &operator=(const DefaultAsyncDispatcher &) = delete; - - ~DefaultAsyncDispatcher() { - shutdown(); - } - - bool dispatch(AsyncTask task) { - std::lock_guard guard(mutex_); - // Unbounded: a rejected poll drops its future, which only shutdown may do. - if (!accepting_) { - return false; - } - tasks_.push_back(std::move(task)); - ready_.notify_one(); - return true; - } - - void shutdown() noexcept { - { - std::lock_guard guard(mutex_); - accepting_ = false; - } - ready_.notify_all(); - if (worker_.joinable()) { - worker_.join(); - } - } - -private: - void run() noexcept { - for (;;) { - AsyncTask task; - { - std::unique_lock lock(mutex_); - ready_.wait(lock, [this] { return !tasks_.empty() || !accepting_; }); - if (tasks_.empty()) { - return; - } - task = std::move(tasks_.front()); - tasks_.pop_front(); - } - task(); - } - } - - std::mutex mutex_; - std::condition_variable ready_; - std::deque tasks_; - bool accepting_ = true; - std::thread worker_; -}; - -inline DefaultAsyncDispatcher &default_async_dispatcher() { - static DefaultAsyncDispatcher dispatcher; - return dispatcher; -} - -struct AsyncDispatcherState { - AsyncDispatcherState(): - dispatch([](AsyncTask task) { - return default_async_dispatcher().dispatch(std::move(task)); - }), - shutdown([] { default_async_dispatcher().shutdown(); }) {} - - std::mutex mutex; - bool accepting = true; - bool started = false; - AsyncDispatcher dispatch; - AsyncDispatcherShutdown shutdown; -}; - -inline AsyncDispatcherState &async_dispatcher_state() { - static AsyncDispatcherState state; - return state; -} - -inline bool dispatch_async(AsyncTask task) noexcept { - auto &state = async_dispatcher_state(); - AsyncDispatcher dispatch; - { - std::lock_guard guard(state.mutex); - if (!state.accepting) { - return false; - } - state.started = true; - dispatch = state.dispatch; - } - return dispatch(std::move(task)); -} - -} // namespace detail -// Installs the process-wide continuation dispatcher. The dispatcher returns true only -// when it has accepted the task; rejecting a task drops the future it would have polled. -// shutdown must stop accepting work, drain accepted tasks, and return only when they can -// no longer call generated code. Aborts when either function is empty, or when called -// after shutdown or after the first async call. -inline void set_async_dispatcher( - AsyncDispatcher dispatcher, - AsyncDispatcherShutdown shutdown -) noexcept { - if (!dispatcher || !shutdown) { - detail::fatal("UniFFI async dispatcher and shutdown function must not be empty"); - } - auto &state = detail::async_dispatcher_state(); - std::lock_guard guard(state.mutex); - if (!state.accepting) { - detail::fatal("UniFFI async dispatcher has already shut down"); - } - if (state.started) { - detail::fatal("UniFFI async dispatcher must be installed before the first async call"); - } - state.dispatch = std::move(dispatcher); - state.shutdown = std::move(shutdown); -} - -// Permanently stops continuation dispatch for this process. Call this before unloading -// code used by a custom dispatcher or generated bindings. -inline void shutdown_async_dispatcher() noexcept { - AsyncDispatcher dispatch; - AsyncDispatcherShutdown shutdown; - { - auto &state = detail::async_dispatcher_state(); - std::lock_guard guard(state.mutex); - if (!state.accepting) { - return; - } - state.accepting = false; - dispatch = std::move(state.dispatch); - shutdown = std::move(state.shutdown); - state.dispatch = {}; - state.shutdown = {}; - } - if (shutdown) { - shutdown(); - } - shutdown = {}; - dispatch = {}; -} -namespace detail { - -template -struct FutureOutput { - using type = expected; -}; - -template -struct FutureOutput { - using type = T; -}; - -// `std::function` rejects a dependent `void` parameter. -template -struct FutureCallback { - using type = std::function; -}; - -template <> -struct FutureCallback { - using type = std::function; -}; - -// Holds one async result until a blocking `get()` or a continuation claims it. A future -// whose Rust side was cancelled or dropped is abandoned instead: its continuation never -// runs, and a `get()` on it aborts. -template -class FutureCompletionState { -public: - using Stored = std::conditional_t, std::monostate, Output>; - using Callback = typename detail::FutureCallback::type; - - void complete(Stored result) noexcept { - Callback callback; - AsyncDispatcher executor; - { - std::lock_guard guard(mutex_); - if (status_ != Status::Pending) { - return; - } - status_ = Status::Ready; - result_.emplace(std::move(result)); - callback = std::move(callback_); - executor = std::move(executor_); - } - ready_.notify_all(); - if (callback) { - dispatch_continuation(std::move(executor), std::move(callback)); - } - } - - void abandon() noexcept { - Callback callback; - { - std::lock_guard guard(mutex_); - if (status_ != Status::Pending) { - return; - } - status_ = Status::Abandoned; - // Released outside the lock: the callback's captures may own anything. - callback = std::move(callback_); - executor_ = nullptr; - } - ready_.notify_all(); - } - - Output get() noexcept { - std::unique_lock lock(mutex_); - claim_locked(); - ready_.wait(lock, [this] { return status_ != Status::Pending; }); - if (status_ == Status::Abandoned) { - fatal("UniFFI future abandoned: its dispatcher shut down or rejected a poll"); - } - auto result = std::move(*result_); - result_.reset(); - lock.unlock(); - if constexpr (std::is_void_v) { - (void)result; - } else { - return result; - } - } - - void wait() const noexcept { - std::unique_lock lock(mutex_); - ready_.wait(lock, [this] { return status_ != Status::Pending; }); - } - - template - std::future_status wait_for(const std::chrono::duration &timeout) const noexcept { - std::unique_lock lock(mutex_); - return ready_.wait_for(lock, timeout, [this] { return status_ != Status::Pending; }) - ? std::future_status::ready - : std::future_status::timeout; - } - - void then(AsyncDispatcher executor, Callback callback) noexcept { - { - std::lock_guard guard(mutex_); - claim_locked(); - if (status_ == Status::Pending) { - executor_ = std::move(executor); - callback_ = std::move(callback); - return; - } - if (status_ == Status::Abandoned) { - return; - } - } - dispatch_continuation(std::move(executor), std::move(callback)); - } - -private: - enum class Status { Pending, Ready, Abandoned }; - - void claim_locked() noexcept { - if (claimed_) { - fatal("UniFFI future result has already been consumed"); - } - claimed_ = true; - } - - // An executor that rejects the task drops the continuation along with the result. - void dispatch_continuation(AsyncDispatcher executor, Callback callback) noexcept { - auto result = [&] { - std::lock_guard guard(mutex_); - auto result = std::make_shared(std::move(*result_)); - result_.reset(); - return result; - }(); - executor([callback = std::move(callback), result]() mutable { - if constexpr (std::is_void_v) { - callback(); - } else { - callback(std::move(*result)); - } - }); - } - - mutable std::mutex mutex_; - mutable std::condition_variable ready_; - Status status_ = Status::Pending; - std::optional result_; - bool claimed_ = false; - AsyncDispatcher executor_; - Callback callback_; -}; - -} // namespace detail - -// What an async call delivers: `expected` when the Rust function returns a `Result`, -// otherwise `T`. -template -using FutureOutput = typename detail::FutureOutput::type; - -// Owns a continuation attached with `Future::then`. Destroying or cancelling it cancels the -// Rust future, and the continuation does not run. -class FutureContinuation { -public: - explicit FutureContinuation(std::function cancel): cancel_(std::move(cancel)) {} - FutureContinuation(const FutureContinuation &) = delete; - FutureContinuation &operator=(const FutureContinuation &) = delete; - FutureContinuation(FutureContinuation &&other) noexcept: - cancel_(std::move(other.cancel_)) { - other.cancel_ = nullptr; - } - FutureContinuation &operator=(FutureContinuation &&other) noexcept { - if (this != &other) { - cancel(); - cancel_ = std::move(other.cancel_); - other.cancel_ = nullptr; - } - return *this; - } - - ~FutureContinuation() { cancel(); } - - // Cancels the Rust future; the continuation will not run. - void cancel() noexcept { - if (cancel_) { - auto cancel = std::move(cancel_); - cancel_ = nullptr; - cancel(); - } - } - -private: - std::function cancel_; -}; - -// A pending Rust async call. Block on it with `get()`, or attach a continuation with -// `std::move(future).then(executor, callback)`. Destroying or cancelling an incomplete -// future drops the Rust future, which aborts its work, so discarding one warns. -template -class [[nodiscard]] Future { -public: - using Output = FutureOutput; - using Callback = typename detail::FutureCallback::type; - - Future(std::shared_ptr> state, std::function cancel): - state_(std::move(state)), cancel_(std::move(cancel)) {} - - Future(const Future &) = delete; - Future &operator=(const Future &) = delete; - - Future(Future &&other) noexcept: - state_(std::move(other.state_)), cancel_(std::move(other.cancel_)) { - other.cancel_ = nullptr; - } - - Future &operator=(Future &&other) noexcept { - if (this != &other) { - cancel(); - state_ = std::move(other.state_); - cancel_ = std::move(other.cancel_); - other.cancel_ = nullptr; - } - return *this; - } - - ~Future() { - cancel(); - } - - // False once the result was claimed by `get()` or `then()`, or the future was cancelled. - bool valid() const noexcept { - return state_ != nullptr; - } - - // Blocks until the result is ready and returns it, leaving the future invalid. - Output get() noexcept { - require_state(); - auto state = std::move(state_); - cancel_ = nullptr; - return state->get(); - } - - // Blocks until the result is ready. - void wait() const noexcept { - require_state(); - state_->wait(); - } - - // Blocks until the result is ready or the timeout elapses. - template - std::future_status wait_for(const std::chrono::duration &timeout) const noexcept { - require_state(); - return state_->wait_for(timeout); - } - - // Runs `callback` with the result on `executor`. The returned handle owns the Rust - // future: destroying it cancels the call and the callback does not run. - [[nodiscard]] FutureContinuation then(AsyncDispatcher executor, Callback callback) && noexcept { - require_state(); - if (!executor || !callback) { - detail::fatal("UniFFI future continuation must not be empty"); - } - state_->then(std::move(executor), std::move(callback)); - auto cancel = std::move(cancel_); - cancel_ = nullptr; - state_.reset(); - return FutureContinuation(std::move(cancel)); - } - - // Drops the Rust future, aborting its work, and leaves this future invalid. - void cancel() noexcept { - state_.reset(); - if (cancel_) { - auto cancel = std::move(cancel_); - cancel_ = nullptr; - cancel(); - } - } - -private: - void require_state() const noexcept { - if (!state_) { - detail::fatal("UniFFI future has no state: it was consumed or cancelled"); - } - } - - std::shared_ptr> state_; - std::function cancel_; -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bool_conv.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/bool_conv.cpp deleted file mode 100644 index 42a62f51d..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bool_conv.cpp +++ /dev/null @@ -1,23 +0,0 @@ -{%- let class_name = ffi_converter_name|class_name %} -bool {{ class_name }}::lift(uint8_t val) { - return !!val; -} - -uint8_t {{ class_name }}::lower(bool val) { - return val; -} - -{{ type_name }} {{ class_name }}::read(RustStream &stream) { - uint8_t val; - stream >> val; - - return val; -} - -void {{ class_name }}::write(RustStream &stream, bool val) { - stream << val; -} - -uint64_t {{ class_name }}::allocation_size(bool) { - return 1; -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bool_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/bool_conv.hpp deleted file mode 100644 index c7e44a219..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bool_conv.hpp +++ /dev/null @@ -1,7 +0,0 @@ -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(uint8_t); - static uint8_t lower({{ type_name }}); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, {{ type_name }}); - static uint64_t allocation_size({{ type_name }}); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bytes_conv.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/bytes_conv.cpp deleted file mode 100644 index c66851e20..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bytes_conv.cpp +++ /dev/null @@ -1,45 +0,0 @@ -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { - auto buf = rustbuffer_alloc(allocation_size(val)); - auto stream = RustStream(&buf); - - write(stream, val); - - return buf; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - {{ type_name }} ret; - int32_t count; - stream >> count; - - ret.reserve(count); - - for (decltype(count) i = 0; i < count; i++) { - uint8_t elem; - stream >> elem; - ret.push_back(elem); - } - - return ret; -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) { - stream << static_cast(val.size()); - - for (auto &elem : val) { - stream << elem; - } -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &val) { - return static_cast(sizeof(int32_t) + sizeof(uint8_t) * val.size()); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bytes_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/bytes_conv.hpp deleted file mode 100644 index 8612ec672..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/bytes_conv.hpp +++ /dev/null @@ -1,8 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -struct {{ ffi_converter_name|class_name }} { - static {{ type_name }} lift(RustBuffer); - static RustBuffer lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback.hpp deleted file mode 100644 index 65f236db0..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback.hpp +++ /dev/null @@ -1,37 +0,0 @@ -{%- let class_name = type_name|class_name %} -{%- let canonical_type_name = typ|canonical_name(ci) %} -{%- let trait_impl = canonical_type_name|callback_interface_name %} - -{% call macros::docstring_value(interface_docstring, 0) %} -struct {{ interface_name }} { - virtual ~{{ interface_name }}() {} - - {%- for method in methods.iter() %} - {%- call macros::docstring(method, 4) %} - virtual - {% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }}{% else %}void{% endmatch %}{{ " " }} - {{- method.name()|fn_name }}({% call macros::param_list(method) %}) = 0; - {%- endfor %} -}; - -namespace uniffi { - struct {{ trait_impl }} { - {%- for (ffi_callback, method) in vtable_methods.iter() %} - static {% call macros::ffi_return_type(ffi_callback) %} {{ method.name()|var_name }}({% call macros::arg_list_ffi_decl_xx(ffi_callback) %}); - {%- endfor %} - - static void uniffi_free(uint64_t uniffi_handle); - static uint64_t uniffi_clone(uint64_t uniffi_handle); - static void init(); - private: - static inline {{ vtable|ffi_type_name }} vtable = [] { - {{ vtable|ffi_type_name }} value{}; - value.uniffi_free = reinterpret_cast(&uniffi_free); - value.uniffi_clone = reinterpret_cast(&uniffi_clone); - {%- for (ffi_callback, meth) in vtable_methods.iter() %} - value.{{ meth.name()|var_name }} = reinterpret_cast(&{{ meth.name()|var_name }}); - {%- endfor %} - return value; - }(); - }; -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_conv.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_conv.cpp deleted file mode 100644 index 69d38de1a..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_conv.cpp +++ /dev/null @@ -1,25 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let class_name = ffi_converter_name|class_name %} - -{{ type_name }} {{ class_name }}::lift(uint64_t handle) { - return handle_map.at(handle); -} - -uint64_t {{ class_name }}::lower(const {{type_name}}& impl) { - return handle_map.insert(impl); -} - -{{ type_name }} uniffi::{{ class_name }}::read(RustStream &stream) { - uint64_t handle; - stream >> handle; - - return lift(handle); -} - -void uniffi::{{ class_name }}::write(RustStream &stream, const {{ type_name }} &impl) { - stream << lower(impl); -} - -uint64_t uniffi::{{ class_name }}::allocation_size(const {{ type_name }} &impl) { - return static_cast(sizeof(uint64_t)); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_conv.hpp deleted file mode 100644 index 05ab0ac56..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_conv.hpp +++ /dev/null @@ -1,12 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let canonical_type_name = typ|canonical_name(ci) %} - -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(uint64_t); - static uint64_t lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); - - inline static HandleMap<{{ canonical_type_name }}> handle_map = {}; -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp deleted file mode 100644 index e2c09b771..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp +++ /dev/null @@ -1,54 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let class_name = ffi_converter_name|class_name %} -{%- let canonical_type_name = typ|canonical_name(ci) %} -{%- let trait_impl = canonical_type_name|callback_interface_name %} - -{%- for (ffi_callback, method) in vtable_methods.iter() %} - {% call macros::ffi_return_type(ffi_callback) %} {{ trait_impl}}::{{ method.name()|var_name }}({% call macros::arg_list_ffi_decl_xx(ffi_callback) %}) { - auto obj = {{ ffi_converter_name }}::handle_map.at(uniffi_handle); - - auto make_call = [&]() {% match method.return_type() %}{% when Some(t) %}-> {{ t|type_name(ci) }}{% when None %}{% endmatch %} { - {%- for arg in method.arguments() %} - auto arg{{ loop.index0 }} = {{- arg|lift_fn(ci) }}({{ arg.name()|var_name }}); - {%- endfor -%} - - {%- if method.return_type().is_some() %}return {% endif -%} - obj->{{ method.name()|var_name }}( - {%- for arg in method.arguments() %} - arg{{ loop.index0 }}{%- if !loop.last %}, {% else %}{% endif %} - {%- endfor -%} - ); - }; - - {% match method.return_type() %} - {% when Some(t) %} - auto write_value = [&]({{ t|type_name(ci) }} v) { - uniffi_out_return = {{ t|lower_fn(ci) }}(v); - }; - {% when None %} - (void)uniffi_out_return; - auto write_value = [](){}; - {% endmatch %} - - {% match method.throws_type() %} - {% when Some(error) %} - rust_call_trait_interface_with_error<{{ error|thrown_class(ci) }}>(out_status, make_call, write_value, {{ error|lower_fn(ci) }}); - {% when None %} - rust_call_trait_interface(out_status, make_call, write_value); - {% endmatch %} -} -{%- endfor %} - -void {{ trait_impl }}::uniffi_free(uint64_t uniffi_handle) { - {{ ffi_converter_name }}::handle_map.erase(uniffi_handle); -} - -uint64_t {{ trait_impl }}::uniffi_clone(uint64_t uniffi_handle) { - return {{ ffi_converter_name }}::handle_map.insert( - {{ ffi_converter_name }}::handle_map.at(uniffi_handle) - ); -} - -void {{ trait_impl }}::init() { - {{ ffi_init_callback.name() }}(vtable); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/custom.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/custom.cpp deleted file mode 100644 index 487ec1705..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/custom.cpp +++ /dev/null @@ -1,37 +0,0 @@ -{%- match config.custom_types.get(name.as_str()) %} -{%- when Some with (type_config) %} -{%- match type_config.type_name %} -{%- when Some with (type_name) %} -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buff) { - auto builtin_val = {{ builtin|lift_fn(ci) }}(buff); - - return {{ type_config.lift("builtin_val") }}; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { - auto builtin_val = {{ type_config.lower("val") }}; - - return {{ builtin|lower_fn(ci) }}(builtin_val); -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - auto builtin_val = {{ builtin|read_fn(ci) }}(stream); - - return {{ type_config.lift("builtin_val") }}; -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) { - auto builtin_val = {{ type_config.lower("val") }}; - - {{ builtin|write_fn(ci) }}(stream, builtin_val); -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &val) { - auto builtin_val = {{ type_config.lower("val") }}; - - return {{ builtin|allocation_size_fn(ci) }}(builtin_val); -} -{%- else %} -{%- endmatch %} -{%- else %} -{%- endmatch %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/custom.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/custom.hpp deleted file mode 100644 index 9e8a4615a..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/custom.hpp +++ /dev/null @@ -1,16 +0,0 @@ -{%- match config.custom_types.get(name.as_str()) %} -{%- when Some with (type_config) %} -{%- match type_config.type_name %} -{%- when Some with (type_name) %} -struct {{ typ|ffi_converter_name(ci) }} { - static {{ name }} lift(RustBuffer); - static RustBuffer lower(const {{ name }} &); - static {{ name }} read(RustStream &); - static void write(RustStream &, const {{ name }} &); - static uint64_t allocation_size(const {{ name }} &); -}; -{%- else %} -{%- endmatch %} -{%- else -%} -typedef struct {{ builtin|ffi_converter_name(ci) }} {{ typ|ffi_converter_name(ci) }}; -{%- endmatch %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/duration_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/duration_conv.hpp deleted file mode 100644 index adc8e1ec8..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/duration_conv.hpp +++ /dev/null @@ -1,7 +0,0 @@ -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(RustBuffer); - static RustBuffer lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/duration_helper.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/duration_helper.cpp deleted file mode 100644 index 9bb69bc9b..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/duration_helper.cpp +++ /dev/null @@ -1,38 +0,0 @@ -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto val = {{ ffi_converter_name }}::read(stream); - - rustbuffer_free(buf); - - return val; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { - auto buf = rustbuffer_alloc(allocation_size(val)); - auto stream = RustStream(&buf); - - {{ ffi_converter_name }}::write(stream, val); - - return buf; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - uint64_t secs; - uint32_t nanos; - - stream >> secs; - stream >> nanos; - - return std::chrono::seconds(secs) + std::chrono::nanoseconds(nanos); -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) { - auto secs = std::chrono::duration_cast>(val); - auto nanos = (val - secs).count(); - - stream << secs.count() << static_cast(nanos); -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &) { - return static_cast(sizeof(uint64_t) + sizeof(uint32_t)); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum.cpp deleted file mode 100644 index ea431323a..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum.cpp +++ /dev/null @@ -1,17 +0,0 @@ -{%- if typ|enum_struct(ci) && !(typ|error_class(ci)) %} -{%- let trait_methods = e.uniffi_trait_methods() %} -{%- match trait_methods.display_fmt %} -{%- when Some with (fmt) %} -std::string {{ type_name }}::to_string() const { - return uniffi::{{ Type::String.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("uniffi::" ~ ffi_converter_name ~ "::lower(*this)", fmt) %}); -} -{%- else %} -{%- endmatch %} -{%- match trait_methods.debug_fmt %} -{%- when Some with (fmt) %} -std::string {{ type_name }}::to_debug_string() const { - return uniffi::{{ Type::String.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("uniffi::" ~ ffi_converter_name ~ "::lower(*this)", fmt) %}); -} -{%- else %} -{%- endmatch %} -{%- endif %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum.hpp deleted file mode 100644 index 82b989725..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum.hpp +++ /dev/null @@ -1,84 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let ffi_converter_name = ffi_converter_name|class_name %} -{%- let as_struct = typ|enum_struct(ci) %} -{%- let flat_error = e.is_flat() && as_struct %} -{%- if !as_struct %} -{% call macros::docstring(e, 0) %} -enum class {{ type_name }}: int32_t { - {%- for variant in e.variants() %} - {%- call macros::docstring(variant, 4) %} - {{ variant|variant_name(config.enum_style) }} = {{ loop.index }} - {%- if !loop.last %}, - {%- endif %} - {%- endfor %} -}; -{%- else %} -namespace uniffi { -struct {{ ffi_converter_name }}; -} // namespace uniffi - -{%~ call macros::docstring(e, 0) %} -struct {{ type_name }} { - friend uniffi::{{ ffi_converter_name }}; - - {%- for variant in e.variants() %} - {%- call macros::docstring(variant, 4) %} - struct {{ variant|variant_name(config.enum_style) }} { - {%- for field in variant.fields() %} - {%- call macros::docstring(field, 8) %} - {{ field|type_name(ci) }} {% call macros::field_name(field, loop.index) %} - {%- match field.default_value() %} - {%- when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style, ci) }};{%- else -%}; - {%- endmatch %} - {%- endfor %} - {%- if flat_error %} - std::string message; - {%- endif %} - }; - {%- endfor %} - - {%- for variant in e.variants() %} - {{ type_name }}({{ variant|variant_name(config.enum_style) }} variant): variant(variant) {} - {%- endfor %} - - {{ type_name }}(const {{ type_name }} &other): variant(other.variant) {} - {{ type_name }}({{ type_name }} &&other): variant(std::move(other.variant)) {} - - {{ type_name }} &operator=(const {{ type_name }} &other) { - variant = other.variant; - return *this; - } - - {{ type_name }} &operator=({{ type_name }} &&other) { - variant = std::move(other.variant); - return *this; - } - - /** - * Returns the variant of this enum - */ - const std::variant<{% for variant in e.variants() %}{{ variant|variant_name(config.enum_style) }}{% if !loop.last %}, {% endif %}{% endfor %}> &get_variant() const { - return variant; - } - {%- let trait_methods = e.uniffi_trait_methods() %} - {%- if trait_methods.display_fmt.is_some() %} - - /** - * Returns a string representation of the value, internally calls Rust's `Display` trait. - */ - std::string to_string() const; - {%- endif %} - {%- if trait_methods.debug_fmt.is_some() %} - - /** - * Returns a string representation of the value, internally calls Rust's `Debug` trait. - */ - std::string to_debug_string() const; - {%- endif %} - -private: - std::variant<{% for variant in e.variants() %}{{ variant|variant_name(config.enum_style) }}{% if !loop.last %}, {% endif %}{% endfor %}> variant; - - {{ type_name }}(); -}; -{%- endif %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum_conv.hpp deleted file mode 100644 index adc8e1ec8..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum_conv.hpp +++ /dev/null @@ -1,7 +0,0 @@ -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(RustBuffer); - static RustBuffer lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum_tmpl.cpp deleted file mode 100644 index 801ff204a..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/enum_tmpl.cpp +++ /dev/null @@ -1,143 +0,0 @@ -{%- let as_struct = typ|enum_struct(ci) %} -{%- let flat_error = e.is_flat() && as_struct %} -{%- if !as_struct %} -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = {{ ffi_converter_name }}::read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { - auto buf = rustbuffer_alloc({{ ffi_converter_name }}::allocation_size(val)); - auto stream = RustStream(&buf); - - {{ ffi_converter_name }}::write(stream, val); - - return buf; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - int32_t variant; - stream >> variant; - - switch (variant) { - {% for variant in e.variants() %} - case {{ loop.index }}: - return {{ type_name }}::{{ variant|variant_name(config.enum_style) }}; - {% endfor %} - default: - {% call macros::fail("No matching " ~ type_name ~ " variant") %} - } -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) { - switch (val) { - {% for variant in e.variants() %} - case {{ type_name }}::{{ variant|variant_name(config.enum_style) }}: - stream << static_cast({{ loop.index }}); - break; - {% endfor %} - default: - {% call macros::fail("No matching " ~ type_name ~ " variant") %} - } -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name|class_name }} &) { - return static_cast(sizeof(int32_t)); -} -{%- else %} -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = {{ ffi_converter_name }}::read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { - auto buf = rustbuffer_alloc({{ ffi_converter_name }}::allocation_size(val)); - auto stream = RustStream(&buf); - - {{ ffi_converter_name }}::write(stream, val); - - return buf; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - int32_t variant_id; - stream >> variant_id; - - switch (variant_id) { - {% for variant in e.variants() %} - case {{ loop.index }}: - return {{ type_name }}::{{ variant|variant_name(config.enum_style) }} { - {%- for field in variant.fields() %} - {{ field|read_fn(ci) }}(stream), - {%- endfor %} - {%- if flat_error %} - {{ Type::String.borrow()|read_fn(ci) }}(stream), - {%- endif %} - }; - {% endfor %} - default: - {% call macros::fail("No matching " ~ type_name ~ " variant") %} - } -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) { - int32_t variant_id = static_cast(val.variant.index() + 1); - - stream << variant_id; - - std::visit([&](auto &&arg) { - using T = std::decay_t; - {%- for variant in e.variants() %} - {% if !loop.first %}else {% endif %}if constexpr (std::is_same_v) { - {%- for field in variant.fields() %} - {{ field|write_fn(ci) }}(stream, {{ field.as_type()|cpp_deref(ci) }}arg.{% call macros::field_name(field, loop.index) %}); - {%- endfor %} - {%- if flat_error %} - {{ Type::String.borrow()|write_fn(ci) }}(stream, arg.message); - {%- endif %} - } - {%- endfor %} - {%- if e.variants().len() != 0 %} - else { - static_assert(always_false_v, "non-exhaustive {{ type_name }} visitor"); - } - {%- endif %} - }, val.variant); -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name|class_name }} &val) { - uint64_t size = sizeof(int32_t); - - size += std::visit([&](auto &&arg) { - (void)arg; - using T = std::decay_t; - {%- for variant in e.variants() %} - {% if !loop.first %}else {% endif %}if constexpr (std::is_same_v) { - uint64_t size = 0; - {%- for field in variant.fields() %} - size += {{ field|allocation_size_fn(ci) }}({{ field.as_type()|cpp_deref(ci) }}arg.{% call macros::field_name(field, loop.index) %}); - {%- endfor %} - {%- if flat_error %} - size += {{ Type::String.borrow()|allocation_size_fn(ci) }}(arg.message); - {%- endif %} - return size; - } - {%- endfor %} - {%- if e.variants().len() != 0 %} - else { - static_assert(always_false_v, "non-exhaustive {{ type_name }} visitor"); - } - {%- endif %} - }, val.variant); - - return size; -} -{%- endif %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/err.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/err.hpp deleted file mode 100644 index bc5605e47..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/err.hpp +++ /dev/null @@ -1,56 +0,0 @@ -{%- let class_name = typ|canonical_name(ci) %} -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let ffi_converter_name = ffi_converter_name|class_name %} -namespace uniffi { -struct {{ ffi_converter_name }}; -} // namespace uniffi - -{%~ call macros::docstring(e, 0) %} -struct {{ class_name }}: std::runtime_error { - friend uniffi::{{ ffi_converter_name }}; - - {{ class_name }}() : std::runtime_error("") {} - {{ class_name }}(const std::string &what_arg) : std::runtime_error(what_arg) {} - - virtual ~{{ class_name }}() = default; - - virtual void throw_underlying() { - throw *this; - } - -protected: - virtual int32_t get_variant_idx() const { - return 0; - }; -}; - -{%- if e.variants().len() != 0 %} -/** - * Contains variants of {{ class_name }} - */ -namespace {{ class_name|to_lower_snake_case }} { -{%- for variant in e.variants() %} -{% call macros::docstring(variant, 0) %} -struct {{ variant.name()|class_name }}: {{ class_name }} { - {%- for field in variant.fields() %} - {{ field|type_name(ci) }} {% call macros::field_name(field, loop.index) %} - {%- match field.default_value() %} - {% when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style, ci) }};{% else %}; - {%- endmatch %} - {%- endfor %} - - {{ variant.name()|class_name }}() : {{ class_name }}("") {} - {{ variant.name()|class_name }}(const std::string &what_arg) : {{ class_name }}(what_arg) {} - - void throw_underlying() override { - throw *this; - } - -protected: - int32_t get_variant_idx() const override { - return {{ loop.index }}; - } -}; -{%- endfor %} -} // namespace {{ class_name|to_lower_snake_case }} -{%- endif %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/err_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/err_conv.hpp deleted file mode 100644 index 65f2c7df0..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/err_conv.hpp +++ /dev/null @@ -1,8 +0,0 @@ -{%- let class_name = typ|canonical_name(ci) %} -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(RustBuffer buf); - static RustBuffer lower(const {{ class_name }} &); - static {{ type_name }} read(RustStream &stream); - static void write(RustStream &stream, const {{ class_name }} &); - static uint64_t allocation_size(const {{ class_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/err_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/err_tmpl.cpp deleted file mode 100644 index 4efe56deb..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/err_tmpl.cpp +++ /dev/null @@ -1,86 +0,0 @@ -{%- let class_name = typ|canonical_name(ci) %} -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = {{ ffi_converter_name }}::read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ class_name }} &val) { - auto buf = rustbuffer_alloc(allocation_size(val)); - auto stream = RustStream(&buf); - - {{ ffi_converter_name }}::write(stream, val); - - return buf; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - int32_t v; - stream >> v; - - switch (v) { - {%- for variant in e.variants() %} - {%- if e.is_flat() %} - case {{ loop.index }}: - return std::make_shared<{{ class_name|to_lower_snake_case }}::{{ variant.name()|class_name }}>({{ Type::String.borrow()|read_fn(ci) }}(stream)); - {% else %} - case {{ loop.index }}: - { - {{ class_name|to_lower_snake_case }}::{{ variant.name() }} var; - {%- for field in variant.fields() %} - var.{% call macros::field_name(field, loop.index) %} = {{ field|read_fn(ci) }}(stream); - {%- endfor %} - return std::make_shared<{{ class_name|to_lower_snake_case }}::{{ variant.name() }}>(var); - } - {%- endif %} - {%- endfor %} - default: - throw std::runtime_error("Unexpected error variant"); - } -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ class_name }} &val) { - stream << val.get_variant_idx(); - - {%- if e.is_flat() %} - {{ Type::String.borrow()|write_fn(ci) }}(stream, val.what()); - {%- else %} - switch (val.get_variant_idx()) { - {%- for variant in e.variants() %} - case {{ loop.index }}: - { - auto var = static_cast(val); - {%- for field in variant.fields() %} - {{ field|write_fn(ci) }}(stream, {{ field.as_type()|cpp_deref(ci) }}var.{% call macros::field_name(field, loop.index) %}); - {%- endfor %} - break; - } - {%- endfor %} - } - {%- endif %} -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ class_name }} &val) { - {%- if e.is_flat() %} - (void)val; - return static_cast(sizeof(int32_t)); - {%- else %} - switch (val.get_variant_idx()) { - {%- for variant in e.variants() %} - case {{ loop.index }}: - { - auto var = static_cast(val); - return static_cast(sizeof(int32_t) - {%- for field in variant.fields() %} - + {{ field|allocation_size_fn(ci) }}({{ field.as_type()|cpp_deref(ci) }}var.{% call macros::field_name(field, loop.index) %}) - {%- endfor %}); - } - {%- endfor %} - default: - throw std::runtime_error("Unexpected error variant"); - } - {%- endif %} -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/ext_typ_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/ext_typ_tmpl.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/fn_def.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/fn_def.cpp deleted file mode 100644 index 1fea45e3c..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/fn_def.cpp +++ /dev/null @@ -1,27 +0,0 @@ -{%- let fallible = config.expected() && func.throws_type().is_some() %} -{%- match func.return_type() %} -{%- when Some with (return_type) %} -{% call macros::result_type(func, return_type|type_name(ci)) %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { - {%- if func.is_async() %} - return {% call macros::rust_call_async(func, return_type|type_name(ci)) %}; - {%- else if fallible %} - return uniffi::lift_expected<{{ return_type|type_name(ci) }}>({% call macros::rust_call(func) %}, [](auto ret) { - return uniffi::{{ return_type|lift_fn(ci) }}(ret); - }); - {%- else %} - auto ret = {% call macros::rust_call(func) %}; - - return uniffi::{{ return_type|lift_fn(ci) }}(ret); - {%- endif %} -} -{%- when None -%} -{% call macros::result_type(func, "void") %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { - {%- if func.is_async() %} - return {% call macros::rust_call_async_void(func) %}; - {%- else if fallible %} - return {% call macros::rust_call(func) %}; - {%- else %} - {% call macros::rust_call(func) %}; - {%- endif %} -} -{%- endmatch -%} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/handle_map.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/handle_map.cpp deleted file mode 100644 index 289e90051..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/handle_map.cpp +++ /dev/null @@ -1,45 +0,0 @@ - -template struct HandleMap { - HandleMap() = default; - - std::shared_ptr at(uint64_t handle) { - std::lock_guard guard(this->mutex); - - return this->map.at(handle); - } - - uint64_t insert(std::shared_ptr impl) { - std::lock_guard guard(this->mutex); - - auto handle = this->cur_handle; - - this->map.insert({ handle, impl }); - // UniFFI reserves odd values for handles created by foreign bindings. - this->cur_handle += 2; - - return handle; - } - - void erase(uint64_t handle) { - // We store the object here to avoid re-entrant locking - std::shared_ptr cleanup; - { - std::lock_guard guard(this->mutex); - auto it = this->map.find(handle); - if (it != this->map.end()) { - cleanup = it->second; - this->map.erase(it); - } - } - } - private: - HandleMap(const HandleMap &) = delete; - HandleMap(HandleMap &&) = delete; - - HandleMap &operator=(const HandleMap &) = delete; - HandleMap &operator=(HandleMap &&) = delete; - - std::mutex mutex; - uint64_t cur_handle = 1; - std::map> map; -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/internal_types.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/internal_types.cpp deleted file mode 100644 index 17692dbd2..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/internal_types.cpp +++ /dev/null @@ -1,40 +0,0 @@ -{%- import "macros.cpp" as macros %} - -{%- for typ in ci.iter_local_types() %} -{%- let type_name = typ|type_name(ci) %} -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let canonical_type_name = typ|canonical_name(ci) %} -{%- let contains_object_references = ci.item_contains_object_references(typ) %} -{%- let namespace = ci.namespace() %} - -{%- match typ %} - -{%- when Type::Boolean %} -{% include "bool_conv.cpp" %} -{%- when Type::UInt8 %} -{% include "arith_conv.cpp" %} -{%- when Type::Int8 %} -{% include "arith_conv.cpp" %} -{%- when Type::UInt16 %} -{% include "arith_conv.cpp" %} -{%- when Type::Int16 %} -{% include "arith_conv.cpp" %} -{%- when Type::UInt32 %} -{% include "arith_conv.cpp" %} -{%- when Type::Int32 %} -{% include "arith_conv.cpp" %} -{%- when Type::UInt64 %} -{% include "arith_conv.cpp" %} -{%- when Type::Int64 %} -{% include "arith_conv.cpp" %} -{%- when Type::Float32 %} -{% include "arith_conv.cpp" %} -{%- when Type::Float64 %} -{% include "arith_conv.cpp" %} -{%- when Type::Bytes %} -{% include "bytes_conv.cpp" %} -{%- when Type::String %} -{% include "str_conv.cpp" %} -{%- else %} -{%- endmatch %} -{%- endfor %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/macros.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/macros.cpp deleted file mode 100644 index baf6627a6..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/macros.cpp +++ /dev/null @@ -1,186 +0,0 @@ -{% macro rust_call(func) -%} - uniffi::rust_call( - {{ func.ffi_func().name() }}, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name(ci) }}::lift -{%- else %} - nullptr -{%- endmatch %} -{%- if !func.arguments().is_empty() %}, {% else %}{% endif %} - {%- call arg_list_lowered(func) -%}) -{%- endmacro %} - -{% macro rust_call_with_prefix(prefix, func) -%} - uniffi::rust_call( - {{ func.ffi_func().name() }}, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name(ci) }}::lift, -{%- else %} - nullptr, -{%- endmatch %} - {{ prefix }} -{%- if !func.arguments().is_empty() %}, {% else %}{% endif %} - {%- call arg_list_lowered(func) -%}) -{%- endmacro %} - -{% macro rust_call_async(func, return_type) -%} - uniffi::rust_call_async<{{ return_type }}{% call async_error_arg(func) %}>( - [&]() { - return {{ func.ffi_func().name() }}( - {%- call arg_list_lowered(func) -%} - ); - }, - {{ func.ffi_rust_future_poll(ci) }}, - {{ func.ffi_rust_future_cancel(ci) }}, - {{ func.ffi_rust_future_complete(ci) }}, - {{ func.ffi_rust_future_free(ci) }}, - [](auto value) { return uniffi::{{ func.return_type().unwrap()|lift_fn(ci) }}(value); }, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name(ci) }}::lift -{%- else %} - nullptr -{%- endmatch %} - ) -{%- endmacro %} - -{% macro rust_call_async_void(func) -%} - uniffi::rust_call_async( - [&]() { - return {{ func.ffi_func().name() }}( - {%- call arg_list_lowered(func) -%} - ); - }, - {{ func.ffi_rust_future_poll(ci) }}, - {{ func.ffi_rust_future_cancel(ci) }}, - {{ func.ffi_rust_future_complete(ci) }}, - {{ func.ffi_rust_future_free(ci) }}, - nullptr, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name(ci) }}::lift -{%- else %} - nullptr -{%- endmatch %} - ) -{%- endmacro %} - -{% macro rust_call_async_with_prefix(prefix, func, return_type) -%} - uniffi::rust_call_async<{{ return_type }}{% call async_error_arg(func) %}>( - [&]() { - return {{ func.ffi_func().name() }}( - {{ prefix }}{% if !func.arguments().is_empty() %}, {% endif %} - {%- call arg_list_lowered(func) -%} - ); - }, - {{ func.ffi_rust_future_poll(ci) }}, - {{ func.ffi_rust_future_cancel(ci) }}, - {{ func.ffi_rust_future_complete(ci) }}, - {{ func.ffi_rust_future_free(ci) }}, - [](auto value) { return uniffi::{{ func.return_type().unwrap()|lift_fn(ci) }}(value); }, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name(ci) }}::lift -{%- else %} - nullptr -{%- endmatch %} - ) -{%- endmacro %} - -{% macro rust_call_async_void_with_prefix(prefix, func) -%} - uniffi::rust_call_async( - [&]() { - return {{ func.ffi_func().name() }}( - {{ prefix }}{% if !func.arguments().is_empty() %}, {% endif %} - {%- call arg_list_lowered(func) -%} - ); - }, - {{ func.ffi_rust_future_poll(ci) }}, - {{ func.ffi_rust_future_cancel(ci) }}, - {{ func.ffi_rust_future_complete(ci) }}, - {{ func.ffi_rust_future_free(ci) }}, - nullptr, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name(ci) }}::lift -{%- else %} - nullptr -{%- endmatch %} - ) -{%- endmacro %} - -{% macro param_list(func) %} -{%- for arg in func.arguments() -%} -{{ arg|parameter(ci) }} -{%- if !loop.last -%}, {% endif -%} -{% endfor -%} -{% endmacro %} - -{% macro field_name(field, field_num) %} -{%- if field.name().is_empty() -%} -v{{- field_num -}} -{%- else -%} -{{ field.name()|var_name }} -{%- endif -%} -{%- endmacro %} - -{% macro arg_list_lowered(func) %} -{%- for arg in func.arguments() -%} -uniffi::{{ arg|lower_fn(ci) }}({{ arg.name()|var_name }}) -{%- if !loop.last -%}, {% endif -%} -{% endfor -%} -{% endmacro %} - -{%- macro arg_list_ffi_decl_xx(func) %} - {%- for arg in func.arguments() %} - {{- arg.type_().borrow()|ffi_type_name }} {{ arg.name()|var_name -}}{%- if !loop.last || func.has_rust_call_status_arg() -%},{%- endif -%} - {%- endfor %} - {%- if func.has_rust_call_status_arg() %}RustCallStatus *out_status{% endif %} -{%- endmacro -%} - -{%- macro ffi_return_type(func) %} - {%- match func.return_type() %} - {%- when Some(return_type) %}{{ return_type|ffi_type_name }} - {%- when None %}{{ "void" }} - {%- endmatch %} -{%- endmacro %} - -{%- macro docstring_value(maybe_docstring, indent_spaces) %} -{%- match maybe_docstring %} -{%- when Some(docstring) %} -{{ docstring|docstring(indent_spaces) }} -{%- else %} -{%- endmatch %} -{%- endmacro %} - -{%- macro docstring(defn, indent_spaces) %} -{%- call docstring_value(defn.docstring(), indent_spaces) %} -{%- endmacro %} - -{#- Reports a bug: a throw under the exceptions style, an abort under the expected style. #} -{%- macro fail(message) -%} -{%- if config.expected() -%} -::uniffi::detail::fatal("{{ message }}"); -{%- else -%} -throw std::runtime_error("{{ message }}"); -{%- endif -%} -{%- endmacro %} - -{#- The error type argument of a future, present when the call can fail. #} -{%- macro async_error_arg(func) -%} -{%- match func.throws_type() %}{% when Some with (e) %}, {{ e|type_name(ci) }}{% else %}{% endmatch -%} -{%- endmacro %} - -{#- What a callable returns, given the type of its value: a future when async, and - `expected` when it can fail under the expected style. #} -{%- macro result_type(func, value_type) -%} -{%- if func.is_async() -%} -::uniffi::Future<{{ value_type }}{% call async_error_arg(func) %}> -{%- else if config.expected() && func.throws_type().is_some() -%} -::uniffi::expected<{{ value_type }}, {{ func.throws_type().unwrap()|type_name(ci) }}> -{%- else -%} -{{ value_type }} -{%- endif -%} -{%- endmacro %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/map_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/map_conv.hpp deleted file mode 100644 index 8612ec672..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/map_conv.hpp +++ /dev/null @@ -1,8 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -struct {{ ffi_converter_name|class_name }} { - static {{ type_name }} lift(RustBuffer); - static RustBuffer lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/map_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/map_tmpl.cpp deleted file mode 100644 index 05537fe70..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/map_tmpl.cpp +++ /dev/null @@ -1,53 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let class_name = ffi_converter_name|class_name %} -{{ type_name }} {{ class_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ class_name }}::lower(const {{ type_name }} &val) { - auto buf = rustbuffer_alloc(allocation_size(val)); - auto stream = RustStream(&buf); - - write(stream, val); - - return buf; -} - -{{ type_name }} {{ class_name }}::read(RustStream &stream) { - {{ type_name }} ret; - int32_t count; - stream >> count; - - ret.reserve(count); - - for (decltype(count) i = 0; i < count; i++) { - ret.insert({ {{ key_type|read_fn(ci) }}(stream), {{ value_type|read_fn(ci) }}(stream) }); - } - - return ret; -} - -void {{ class_name }}::write(RustStream &stream, const {{ type_name }} &val) { - stream << static_cast(val.size()); - - for (auto &entry : val) { - {{ key_type|write_fn(ci) }}(stream, {{ key_type.as_type()|cpp_deref(ci) }}entry.first); - {{ value_type|write_fn(ci) }}(stream, {{ value_type.as_type()|cpp_deref(ci) }}entry.second); - } -} - -uint64_t {{ class_name }}::allocation_size(const {{ type_name }} &val) { - uint64_t size = sizeof(int32_t); - - for (auto &entry : val) { - size += {{ key_type|allocation_size_fn(ci) }}({{ key_type.as_type()|cpp_deref(ci) }}entry.first); - size += {{ value_type|allocation_size_fn(ci) }}({{ value_type.as_type()|cpp_deref(ci) }}entry.second); - } - - return size; -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj.cpp deleted file mode 100644 index e4e0808e1..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj.cpp +++ /dev/null @@ -1,132 +0,0 @@ -{%- let obj = ci.get_object_definition(name).unwrap() %} -{%- let (interface_name, impl_class_name) = obj|object_names %} -{%- let class_name = type_name|class_name %} -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let canonical_type_name = typ|canonical_name(ci) %} - -{%- if obj.has_callback_interface() %} -{%- let vtable = obj.vtable().expect("trait interface should have a vtable") %} -{%- let vtable_methods = obj.vtable_methods() %} -{%- let ffi_init_callback = obj.ffi_init_callback() %} -namespace uniffi { -{% include "callback_iface_tmpl.cpp" %} -} // namespace uniffi -{%- endif %} - - -{{ impl_class_name }}::{{ impl_class_name }}(uint64_t handle): instance(handle) {} - -{{ impl_class_name }}::{{ impl_class_name }}(const {{ impl_class_name }} &other) : instance(0) { - if (other.instance) { - instance = other._uniffi_internal_clone_pointer(); - } -} - -{% if ci.is_used_as_error(typ) && !config.expected() %} - void {{ impl_class_name }}::throw_underlying() { - throw *this; - } -{% endif %} - -{% match obj.primary_constructor() -%} -{%- when Some with (ctor) %} -{% call macros::result_type(ctor, type_name) %} {{ impl_class_name }}::init({% call macros::param_list(ctor) %}) { - {%- if ctor.is_async() %} - return {% call macros::rust_call_async(ctor, type_name) %}; - {%- else if config.expected() && ctor.throws_type().is_some() %} - return uniffi::lift_expected<{{ type_name }}>({% call macros::rust_call(ctor) %}, [](uint64_t handle) { - return {{ type_name }}(new {{ impl_class_name }}(handle)); - }); - {%- else %} - return {{ type_name }}( - new {{ impl_class_name }}({%- call macros::rust_call(ctor) -%}) - ); - {%- endif %} -} -{% else -%} -{% endmatch -%} - -{% for ctor in obj.alternate_constructors() %} -{% call macros::result_type(ctor, type_name) %} {{ impl_class_name }}::{{ ctor.name() }}({% call macros::param_list(ctor) %}) { - {%- if ctor.is_async() %} - return {% call macros::rust_call_async(ctor, type_name) %}; - {%- else if config.expected() && ctor.throws_type().is_some() %} - return uniffi::lift_expected<{{ type_name }}>({% call macros::rust_call(ctor) %}, [](uint64_t handle) { - return {{ type_name }}(new {{ impl_class_name }}(handle)); - }); - {%- else %} - return {{ type_name }}(new {{ impl_class_name }}({% call macros::rust_call(ctor) %})); - {%- endif %} -} -{% endfor %} - -{%- for method in obj.methods() %} -{% match method.return_type() %}{% when Some with (return_type) %}{% call macros::result_type(method, return_type|type_name(ci)) %}{% else %}{% call macros::result_type(method, "void") %}{% endmatch %} -{{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { - auto ptr = this->_uniffi_internal_clone_pointer(); - {%- match method.return_type() %} - {% when Some with (return_type) %} - {%- if method.is_async() %} - return {% call macros::rust_call_async_with_prefix("ptr", method, return_type|type_name(ci)) %}; - {%- else if config.expected() && method.throws_type().is_some() %} - return uniffi::lift_expected<{{ return_type|type_name(ci) }}>({% call macros::rust_call_with_prefix("ptr", method) %}, [](auto ret) { - return uniffi::{{ return_type|lift_fn(ci) }}(ret); - }); - {%- else %} - return uniffi::{{ return_type|lift_fn(ci) }}({% call macros::rust_call_with_prefix("ptr", method) %}); - {%- endif %} - {%- else %} - {%- if method.is_async() %} - return {% call macros::rust_call_async_void_with_prefix("ptr", method) %}; - {%- else if config.expected() && method.throws_type().is_some() %} - return {% call macros::rust_call_with_prefix("ptr", method) %}; - {%- else %} - {% call macros::rust_call_with_prefix("ptr", method) -%}; - {%- endif %} - {%- endmatch %} -} -{%- endfor %} - -{{ impl_class_name }}::~{{ impl_class_name }}() { - uniffi::rust_call( - {{ obj.ffi_object_free().name() }}, - nullptr, - this->instance - ); -} - -uint64_t {{ impl_class_name }}::_uniffi_internal_clone_pointer() const { - return uniffi::rust_call( - {{ obj.ffi_object_clone().name() }}, - nullptr, - this->instance - ); -} - -{%- for method in obj.uniffi_traits() %} -{% match method %} -{% when UniffiTrait::Display { fmt } %} -std::string {{ impl_class_name }}::to_string() const { - return uniffi::{{ Type::String.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", fmt) %}); -} -{% when UniffiTrait::Debug { fmt } %} -std::string {{ impl_class_name }}::to_debug_string() const { - return uniffi::{{ Type::String.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", fmt) %}); -} -{% when UniffiTrait::Eq { eq, ne } %} -bool {{ impl_class_name }}::eq(const {{ type_name }} &other) const { - return uniffi::{{ Type::Boolean.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", eq) %}); -} -bool {{ impl_class_name }}::ne(const {{ type_name }} &other) const { - return uniffi::{{ Type::Boolean.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", ne) %}); -} -{% when UniffiTrait::Hash { hash } %} -uint64_t {{ impl_class_name }}::hash() const { - return uniffi::{{ Type::UInt64.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", hash) %}); -} -{% when UniffiTrait::Ord { cmp } %} -int8_t {{ impl_class_name }}::cmp(const {{ type_name }} &other) const { - return uniffi::{{ Type::Int8.borrow()|lift_fn(ci) }}({% call macros::rust_call_with_prefix("this->_uniffi_internal_clone_pointer()", cmp) %}); -} -{% endmatch %} -{%- endfor %} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj.hpp deleted file mode 100644 index e5e5abae6..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj.hpp +++ /dev/null @@ -1,100 +0,0 @@ -{%- let obj = ci.get_object_definition(name).unwrap() %} -{%- let (interface_name, impl_class_name) = obj|object_names %} -{%- let class_name = type_name|class_name %} -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- if obj.has_callback_interface() %} -{%- let vtable = obj.vtable().expect("trait interface should have a vtable") %} -{%- let vtable_methods = obj.vtable_methods() %} -{%- let methods = obj.methods() %} -{%- let ffi_init_callback = obj.ffi_init_callback() %} -{%- let interface_docstring = obj.docstring() %} -{% include "callback.hpp" %} -{%- endif %} - -namespace uniffi { - struct {{ ffi_converter_name|class_name }}; -} // namespace uniffi - -{%~ call macros::docstring(obj, 0) %} -struct {{ impl_class_name }} -{# - Since an interface being a callback interface or an error is mutually exclusive, - we don't need to complex branching for multiple inheritance -#} -{% if obj.has_callback_interface() %} : public {{ interface_name }} {% endif %} -{% if ci.is_used_as_error(typ) %} : public std::exception {% endif %} -{ - friend uniffi::{{ ffi_converter_name|class_name }}; - - {{ impl_class_name }}() = delete; - - {{ impl_class_name }}({{ impl_class_name }} &&) = delete; - - {{ impl_class_name }} &operator=(const {{ impl_class_name }} &) = delete; - {{ impl_class_name }} &operator=({{ impl_class_name }} &&) = delete; - - ~{{ impl_class_name }}(); - - {%- match obj.primary_constructor() %} - {%- when Some with (ctor) %} - {%- call macros::docstring(ctor, 4) %} - static {% call macros::result_type(ctor, type_name) %} init({% call macros::param_list(ctor) %}); - {%- else %} - {%- endmatch %} - - {%- for ctor in obj.alternate_constructors() %} - {%- call macros::docstring(ctor, 4) %} - static {% call macros::result_type(ctor, type_name) %} {{ ctor.name() }}({% call macros::param_list(ctor) %}); - {%- endfor %} - - {%- for method in obj.methods() %} - {%- call macros::docstring(method, 4) %} - {% match method.return_type() %}{% when Some with (return_type) %}{% call macros::result_type(method, return_type|type_name(ci)) %}{% else %}{% call macros::result_type(method, "void") %}{% endmatch %} {{ method.name()|fn_name }}({% call macros::param_list(method) %}); - {%- endfor %} - - {%- for method in obj.uniffi_traits() %} - {%- match method %} - {%- when UniffiTrait::Display { fmt } %} - /** - * Returns a string representation of the object, internally calls Rust's `Display` trait. - */ - std::string to_string() const; - {%- when UniffiTrait::Debug { fmt } %} - /** - * Returns a string representation of the object, internally calls Rust's `Debug` trait. - */ - std::string to_debug_string() const; - {%- when UniffiTrait::Eq { eq, ne } %} - /** - * Equality check, internally calls Rust's `Eq` trait. - */ - bool eq(const {{ type_name }} &other) const; - /** - * Inequality check, internally calls Rust's `Ne` trait. - */ - bool ne(const {{ type_name }} &other) const; - {%- when UniffiTrait::Hash { hash } %} - /** - * Returns a hash of the object, internally calls Rust's `Hash` trait. - */ - uint64_t hash() const; - {%- when UniffiTrait::Ord { cmp } %} - /** - * Three-way comparison, internally calls Rust's `Ord` trait. - */ - int8_t cmp(const {{ type_name }} &other) const; - {%- endmatch %} - {%- endfor %} - - {% if ci.is_used_as_error(typ) && !config.expected() %} - void throw_underlying(); - {%- endif -%} -private: - {{ impl_class_name }}(const {{ impl_class_name }} &); - - {{ impl_class_name }}(uint64_t); - - uint64_t _uniffi_internal_clone_pointer() const; - - uint64_t instance = 0; -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj_conv.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj_conv.cpp deleted file mode 100644 index ff9df1755..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj_conv.cpp +++ /dev/null @@ -1,50 +0,0 @@ -{%- let obj = ci.get_object_definition(name).unwrap() %} -{%- let (interface_name, impl_class_name) = obj|object_names %} - -{%- let is_error = ci.is_used_as_error(typ) %} -{%- if is_error %} -{{ type_name }} {{ typ|ffi_error_converter_name(ci)}}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto val = {{ ffi_converter_name }}::read(stream); - rustbuffer_free(buf); - - return val; -} -{% endif %} - -{{ type_name }} {{ ffi_converter_name }}::lift(uint64_t handle) { - {%- if obj.has_callback_interface() %} - if ((handle & 1) == 1) { - auto obj = handle_map.at(handle); - handle_map.erase(handle); - return obj; - } - {%- endif %} - return {{ type_name }}(new {{ impl_class_name }}(handle)); -} - -uint64_t {{ ffi_converter_name }}::lower(const {{ type_name }} &obj) { - {%- if obj.has_callback_interface() %} - if (auto rust_obj = std::dynamic_pointer_cast<{{ impl_class_name }}>(obj)) { - return rust_obj->_uniffi_internal_clone_pointer(); - } - return handle_map.insert(obj); - {%- else %} - return reinterpret_cast<{{ impl_class_name}}*>(obj.get())->_uniffi_internal_clone_pointer(); - {%- endif %} -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - uint64_t handle; - stream >> handle; - - return {{ ffi_converter_name}}::lift(handle); -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &obj) { - stream << {{ ffi_converter_name }}::lower(obj); -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &) { - return 8; -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj_conv.hpp deleted file mode 100644 index 9a132e23d..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/obj_conv.hpp +++ /dev/null @@ -1,23 +0,0 @@ -{%- let obj = ci.get_object_definition(name).unwrap() %} -{%- let canonical_type_name = typ|canonical_name(ci) %} -{%- let trait_impl = canonical_type_name|callback_interface_name %} - -{%- let is_error = ci.is_used_as_error(typ) %} -{%- if is_error %} -struct {{ typ|ffi_error_converter_name(ci)}} { - static {{ type_name }} lift(RustBuffer); -}; -{% endif %} - -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(uint64_t); - static uint64_t lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); -private: - {%- if obj.has_callback_interface() %} - friend struct {{ trait_impl }}; - inline static HandleMap<{{ canonical_type_name }}> handle_map = {}; - {%- endif %} -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/opt_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/opt_conv.hpp deleted file mode 100644 index 5629b60f6..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/opt_conv.hpp +++ /dev/null @@ -1,7 +0,0 @@ -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(RustBuffer buf); - static RustBuffer lower(const {{ type_name }}& val); - static {{ type_name }} read(RustStream &stream); - static void write(RustStream &stream, const {{ type_name }}& value); - static uint64_t allocation_size(const {{ type_name }} &val); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/opt_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/opt_tmpl.cpp deleted file mode 100644 index dc1f4b016..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/opt_tmpl.cpp +++ /dev/null @@ -1,63 +0,0 @@ -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = {{ ffi_converter_name }}::read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }}& val) { - auto buf = rustbuffer_alloc({{ ffi_converter_name }}::allocation_size(val)); - auto stream = RustStream(&buf); - - {{ ffi_converter_name }}::write(stream, val); - - return buf; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - char has_value; - - stream.get(has_value); - - {%- if typ|can_dereference_optional(ci) %} - if (has_value) { - return {{ inner_type|read_fn(ci) }}(stream); - } else { - return nullptr; - } - {%- else %} - if (has_value) { - return std::make_optional({{ inner_type|read_fn(ci) }}(stream)); - } else { - return std::nullopt; - } - {%- endif %} -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }}& value) { - stream.put(static_cast(!!value)); - - if (value) { - {%- if typ|can_dereference_optional(ci) %} - {{ inner_type|write_fn(ci) }}(stream, {{ inner_type.as_type()|cpp_deref(ci) }}value); - {%- else %} - {{ inner_type|write_fn(ci) }}(stream, value.value()); - {%- endif %} - } -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &val) { - uint64_t ret = 1; - - if (val) { - {%- if typ|can_dereference_optional(ci) %} - ret += {{ inner_type|allocation_size_fn(ci) }}({{ inner_type.as_type()|cpp_deref(ci) }}val); - {%- else %} - ret += {{ inner_type|allocation_size_fn(ci) }}(val.value()); - {%- endif %} - } - - return ret; -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec.cpp deleted file mode 100644 index 1f3e19a0e..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec.cpp +++ /dev/null @@ -1,44 +0,0 @@ -{%- let rec = ci.get_record_definition(name).unwrap() %} -{%- let class_name = type_name|class_name %} -{{ class_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = {{ ffi_converter_name }}::read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ class_name }} &val) { - auto buf = rustbuffer_alloc(allocation_size(val)); - auto stream = RustStream(&buf); - - {{ ffi_converter_name }}::write(stream, val); - - return buf; -} - -{{ class_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - return { - {%- for field in rec.fields() %} - {{ field|read_fn(ci) }}(stream){% if !loop.last %},{% endif %} - {%- endfor %} - }; -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ class_name }} &val) { - {%- for field in rec.fields() %} - {{ field|write_fn(ci) }}(stream, {{ field.as_type()|cpp_deref(ci) }}val.{{ field.name()|var_name }}); - {%- endfor %} -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ class_name }} &val) { - {% if rec.fields().is_empty() %} - (void)val; - return 0; - {% else %} - return {% for field in rec.fields() %} - {{ field|allocation_size_fn(ci)}}({{ field.as_type()|cpp_deref(ci) }}val.{{ field.name()|var_name() }}){% if !loop.last %} +{% else -%};{%- endif %} - {%- endfor %} - {% endif %} -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec.hpp deleted file mode 100644 index e0e290207..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec.hpp +++ /dev/null @@ -1,11 +0,0 @@ -{%- let rec = ci.get_record_definition(name).unwrap() %} -{% call macros::docstring(rec, 0) %} -struct {{ type_name }} { - {%- for field in rec.fields() %} - {%- call macros::docstring(field, 4) %} - {{ field|type_name(ci) }} {{ field.name()|var_name }} - {%- match field.default_value() %} - {%- when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style, ci) }};{%- else -%}; - {%- endmatch %} - {%- endfor %} -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec_conv.hpp deleted file mode 100644 index 8146c4c59..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rec_conv.hpp +++ /dev/null @@ -1,8 +0,0 @@ -{%- let class_name = type_name|class_name %} -struct {{ typ|ffi_converter_name(ci) }} { - static {{ class_name }} lift(RustBuffer); - static RustBuffer lower(const {{ class_name }} &); - static {{ class_name }} read(RustStream &); - static void write(RustStream &, const {{ class_name }} &); - static uint64_t allocation_size(const {{ class_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rust_buf_stream.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/rust_buf_stream.cpp deleted file mode 100644 index 0846a5ea8..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rust_buf_stream.cpp +++ /dev/null @@ -1,57 +0,0 @@ -struct RustStreamBuffer: std::basic_streambuf { - RustStreamBuffer(RustBuffer *buf) { - char* data = reinterpret_cast(buf->data); - this->setg(data, data, data + buf->len); - this->setp(data, data + buf->capacity); - } - ~RustStreamBuffer() = default; - -private: - RustStreamBuffer() = delete; - RustStreamBuffer(const RustStreamBuffer &) = delete; - RustStreamBuffer(RustStreamBuffer &&) = delete; - - RustStreamBuffer &operator=(const RustStreamBuffer &) = delete; - RustStreamBuffer &operator=(RustStreamBuffer &&) = delete; -}; - -struct RustStream: std::basic_iostream { - RustStream(RustBuffer *buf): - std::basic_iostream(&streambuf), streambuf(RustStreamBuffer(buf)) { } - - template >> - RustStream &operator>>(T &val) { - read(reinterpret_cast(&val), sizeof(T)); - - if (native_byte_order_is_little_endian()) { - auto bytes = reinterpret_cast(&val); - - std::reverse(bytes, bytes + sizeof(T)); - } - - return *this; - } - - template >> - RustStream &operator<<(T val) { - if (native_byte_order_is_little_endian()) { - auto bytes = reinterpret_cast(&val); - - std::reverse(bytes, bytes + sizeof(T)); - } - - write(reinterpret_cast(&val), sizeof(T)); - - return *this; - } -private: - // Note (AG): Intentionally not calling into platform-specific endian checkers and - // using a simple utility here. Also not public API to avoid bloat for now. - // If another part of the bindgen needs this, can move it. - static bool native_byte_order_is_little_endian() { - const uint16_t value = 1; - return *reinterpret_cast(&value) == 1; - } - - RustStreamBuffer streambuf; -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rust_buf_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/rust_buf_tmpl.cpp deleted file mode 100644 index b428bb468..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/rust_buf_tmpl.cpp +++ /dev/null @@ -1,24 +0,0 @@ -RustBuffer rustbuffer_alloc(uint64_t len) { - RustCallStatus status{}; - auto buffer = {{ ci.ffi_rustbuffer_alloc().name() }}(len, &status); - - check_rust_call(status, nullptr); - - return buffer; -} - -RustBuffer rustbuffer_from_bytes(const ForeignBytes &bytes) { - RustCallStatus status{}; - auto buffer = {{ ci.ffi_rustbuffer_from_bytes().name() }}(bytes, &status); - - check_rust_call(status, nullptr); - - return buffer; -} - -void rustbuffer_free(RustBuffer buf) { - RustCallStatus status{}; - - {{ ci.ffi_rustbuffer_free().name() }}(std::move(buf), &status); - check_rust_call(status, nullptr); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/scaffolding.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/scaffolding.hpp deleted file mode 100644 index 7cf2c45c6..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/scaffolding.hpp +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once - -{%- import "macros.cpp" as macros %} - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef UNIFFI_CPP_INTERNALSTRUCTS -#define UNIFFI_CPP_INTERNALSTRUCTS -struct ForeignBytes { - int32_t len; - uint8_t *data; -}; - -struct RustBuffer { - uint64_t capacity; - uint64_t len; - uint8_t *data; -}; - -struct RustCallStatus { - int8_t code; - RustBuffer error_buf; -}; - -typedef void (*RustFutureContinuationCallback)(uint64_t callback_data, int8_t poll_result); - -{%- for ffi_struct in self.foreign_future_struct_definitions() %} -struct {{ ffi_struct.name()|ffi_struct_name }} { - {%- for field in ffi_struct.fields() %} - {{ field.type_().borrow()|ffi_field_type_name }} {{ field.name()|var_name }}; - {%- endfor %} -}; -{%- endfor %} - -#endif - -{%- for def in self.scaffolding_definitions() %} -{%- match def %} -{%- when FfiDefinition::CallbackFunction(callback) %} -{% call macros::ffi_return_type(callback) %} {{ callback.name()}}( - {% call macros::arg_list_ffi_decl_xx(callback) %} -); -{%- when FfiDefinition::Struct(ffi_struct) %} -struct {{ ffi_struct.name()|ffi_struct_name }} { - {%- for field in ffi_struct.fields() %} - {{ field.type_().borrow()|ffi_field_type_name }} {{ field.name()|var_name }}; - {%- endfor %} -}; -{%- when FfiDefinition::Function(func) %} -{% match func.return_type() -%} -{% when Some with (return_type) %}{{ return_type|ffi_type_name }} {% when None %}void {% endmatch %}{{ func.name() }}( -{%- for arg in func.arguments() %} -{{- arg.type_().borrow()|ffi_type_name }} {{ arg.name() }}{% if !loop.last || func.has_rust_call_status_arg() %}, {% endif -%} -{% endfor %} -{%- if func.has_rust_call_status_arg() %}RustCallStatus *out_status{% endif -%} -); -{%- endmatch %} -{%- endfor %} -#ifdef __cplusplus -} -#endif diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/seq_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/seq_conv.hpp deleted file mode 100644 index 8612ec672..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/seq_conv.hpp +++ /dev/null @@ -1,8 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -struct {{ ffi_converter_name|class_name }} { - static {{ type_name }} lift(RustBuffer); - static RustBuffer lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/seq_tmpl.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/seq_tmpl.cpp deleted file mode 100644 index 484592910..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/seq_tmpl.cpp +++ /dev/null @@ -1,51 +0,0 @@ -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let class_name = ffi_converter_name|class_name %} -{{ type_name }} {{ class_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto ret = read(stream); - - rustbuffer_free(buf); - - return ret; -} - -RustBuffer {{ class_name }}::lower(const {{ type_name }} &val) { - auto buf = rustbuffer_alloc(allocation_size(val)); - auto stream = RustStream(&buf); - - write(stream, val); - - return buf; -} - -{{ type_name }} {{ class_name }}::read(RustStream &stream) { - {{ type_name }} ret; - int32_t count; - stream >> count; - - ret.reserve(count); - - for (decltype(count) i = 0; i < count; i++) { - ret.push_back({{ inner_type|read_fn(ci) }}(stream)); - } - - return ret; -} - -void {{ class_name }}::write(RustStream &stream, const {{ type_name }} &val) { - stream << static_cast(val.size()); - - for (auto &elem : val) { - {{ inner_type|write_fn(ci) }}(stream, {{ inner_type.as_type()|cpp_deref(ci) }}elem); - } -} - -uint64_t {{ class_name }}::allocation_size(const {{ type_name }} &val) { - uint64_t size = sizeof(int32_t); - - for (auto &elem : val) { - size += {{ inner_type|allocation_size_fn(ci) }}({{inner_type.as_type()|cpp_deref(ci) }}elem); - } - - return size; -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/str_conv.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/str_conv.cpp deleted file mode 100644 index b8665ea48..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/str_conv.cpp +++ /dev/null @@ -1,35 +0,0 @@ -std::string {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto string = std::string(reinterpret_cast(buf.data), buf.len); - - rustbuffer_free(buf); - - return string; -} - -RustBuffer {{ ffi_converter_name }}::lower(const std::string &val) { - auto len = static_cast(val.length()); - auto bytes = ForeignBytes { len, reinterpret_cast(const_cast(val.data())) }; - - return rustbuffer_from_bytes(bytes); -} - -std::string {{ ffi_converter_name }}::read(RustStream &stream) { - int32_t len; - std::string string; - - stream >> len; - - string.resize(len); - stream.read(string.data(), len); - - return string; -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const std::string &val) { - stream << static_cast(val.length()); - stream.write(val.data(), val.length()); -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const std::string &val) { - return static_cast(sizeof(int32_t) + val.length()); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/str_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/str_conv.hpp deleted file mode 100644 index ca614499d..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/str_conv.hpp +++ /dev/null @@ -1,7 +0,0 @@ -struct {{ typ|ffi_converter_name(ci) }} { - static std::string lift(RustBuffer buf); - static RustBuffer lower(const std::string &); - static std::string read(RustStream &); - static void write(RustStream &, const std::string &); - static uint64_t allocation_size(const std::string &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/timestamp_conv.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/timestamp_conv.hpp deleted file mode 100644 index adc8e1ec8..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/timestamp_conv.hpp +++ /dev/null @@ -1,7 +0,0 @@ -struct {{ typ|ffi_converter_name(ci) }} { - static {{ type_name }} lift(RustBuffer); - static RustBuffer lower(const {{ type_name }} &); - static {{ type_name }} read(RustStream &); - static void write(RustStream &, const {{ type_name }} &); - static uint64_t allocation_size(const {{ type_name }} &); -}; diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/timestamp_helper.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/timestamp_helper.cpp deleted file mode 100644 index 72045d563..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/timestamp_helper.cpp +++ /dev/null @@ -1,45 +0,0 @@ -{{ type_name }} {{ ffi_converter_name }}::lift(RustBuffer buf) { - auto stream = RustStream(&buf); - auto val = {{ ffi_converter_name }}::read(stream); - - rustbuffer_free(buf); - - return val; -} - -RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) { - auto buf = rustbuffer_alloc(allocation_size(val)); - auto stream = RustStream(&buf); - - {{ ffi_converter_name }}::write(stream, val); - - return buf; -} - -{{ type_name }} {{ ffi_converter_name }}::read(RustStream &stream) { - int64_t secs; - uint32_t nanos; - - stream >> secs; - stream >> nanos; - - auto sign = secs < 0 ? -1 : 1; - - auto duration = std::chrono::duration_cast<{{ type_name }}::duration>(std::chrono::seconds(secs) + (sign * std::chrono::nanoseconds(nanos))); - - return {{ type_name }}(duration); -} - -void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) { - auto duration = val.time_since_epoch(); - auto secs = std::chrono::duration_cast>(duration); - auto nanos = (duration - secs).count(); - - auto sign = secs.count() < 0 ? -1 : 1; - - stream << secs.count() << static_cast(sign * nanos); -} - -uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &) { - return static_cast(sizeof(int64_t) + sizeof(uint32_t)); -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/types.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/types.cpp deleted file mode 100644 index 9b1b77658..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/types.cpp +++ /dev/null @@ -1,65 +0,0 @@ -{%- import "macros.cpp" as macros %} - -{%- for typ in ci.iter_local_types() %} -{%- let type_name = typ|type_name(ci) %} -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let canonical_type_name = typ|canonical_name(ci) %} -{%- let contains_object_references = ci.item_contains_object_references(typ) %} -{%- let namespace = ci.namespace() %} - -{%- match typ %} -{%- when Type::Object { module_path, name, imp } %} -{% include "obj.cpp" %} -{%- when Type::Enum { name, module_path } %} -{%- let e = ci.get_enum_definition(name).unwrap() %} -{% include "enum.cpp" %} -{%- else %} -{%- endmatch %} -{% endfor ~%} - -namespace uniffi { -{%- for typ in ci.iter_local_types() %} -{%- let type_name = typ|type_name(ci) %} -{%- let ffi_converter_name = typ|ffi_converter_name(ci) %} -{%- let canonical_type_name = typ|canonical_name(ci) %} -{%- let contains_object_references = ci.item_contains_object_references(typ) %} -{%- let namespace = ci.namespace() %} - -{%- match typ %} -{%- when Type::Enum { name, module_path } %} -{%- let e = ci.get_enum_definition(name).unwrap() %} -{%- if typ|error_class(ci) %} -{% include "err_tmpl.cpp" %} -{%- else %} -{% include "enum_tmpl.cpp" %} -{%- endif %} -{%- when Type::Object { module_path, name, imp } %} -{% include "obj_conv.cpp" %} -{%- when Type::Record { module_path, name } %} -{% include "rec.cpp" %} -{%- when Type::Optional { inner_type } %} -{% include "opt_tmpl.cpp" %} -{%- when Type::Sequence { inner_type } %} -{% include "seq_tmpl.cpp" %} -{%- when Type::Map { key_type, value_type } %} -{% include "map_tmpl.cpp" %} -{%- when Type::CallbackInterface { module_path, name } %} -{%- let cbi = ci.get_callback_interface_definition(name).unwrap() %} -{%- let ffi_init_callback = cbi.ffi_init_callback() %} -{%- let interface_name = name %} -{%- let methods = cbi.methods() %} -{%- let vtable = cbi.vtable() %} -{%- let vtable_methods = cbi.vtable_methods() %} -{% include "callback_conv.cpp" %} -{% include "callback_iface_tmpl.cpp" %} -{%- when Type::Timestamp %} -{% include "timestamp_helper.cpp" %} -{%- when Type::Duration %} -{% include "duration_helper.cpp" %} -{%- when Type::Custom { module_path, name, builtin } %} -{%- include "custom.cpp" %} -{%- else %} -{%- endmatch %} -{% endfor ~%} - -} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/wrapper.cpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/wrapper.cpp deleted file mode 100644 index fa007d16e..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/wrapper.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* This file was generated by uniffi-bindgen-cpp. */ -{%- let namespace = ci.namespace() %} -{%- import "macros.cpp" as macros %} -#include - -#include "{{ ci.namespace() }}.hpp" - -namespace {{ namespace }} { -namespace uniffi { -template inline constexpr bool always_false_v = false; - -namespace { -void ensure_initialized() { - const uint32_t bindings_contract_version = {{ ci.uniffi_contract_version() }}; - const uint32_t scaffolding_contract_version = {{ ci.ffi_uniffi_contract_version().name() }}(); - - if (bindings_contract_version != scaffolding_contract_version) { - {% call macros::fail("UniFFI contract version mismatch: try cleaning and rebuilding your project") %} - } - - {%- for (name, expected_checksum) in ci.iter_checksums() %} - if ({{ name }}() != {{ expected_checksum }}) { - {% call macros::fail("UniFFI API checksum mismatch: try cleaning and rebuilding your project") %} - } - {%- endfor %} - - {% for func in self.initialization_fns() -%} - {{ func }}(); - {% endfor -%} -} - -// Note: we need this indirection here and can't inline this code in the rust_call function -// as it's a templated function -[[maybe_unused]] void initialize() { - static std::once_flag init_flag; - std::call_once(init_flag, ensure_initialized); -} -} - -{%- if config.expected() %} -// Returns when the call succeeded, or failed with an error the caller lifts through a -// non-null `error_cb`. Anything else is a bug the expected style has no value for, so it -// aborts: a Rust panic, or an error from a function that declares none. -template -void check_rust_call(const RustCallStatus &status, F) { - switch (status.code) { - case 0: - return; - - case 1: - if constexpr (!std::is_null_pointer_v) { - return; - } - break; - - case 2: - if (status.error_buf.len > 0) { - auto message = "Rust panic: " + {{ Type::String.borrow()|lift_fn(ci) }}(status.error_buf); - ::uniffi::detail::fatal(message.c_str()); - } - - ::uniffi::detail::fatal("A Rust panic has occurred"); - } - - ::uniffi::detail::fatal("Unexpected Rust call status"); -} - -// Calls `f`, returning `expected` when `error_cb` lifts the function's error type `E`, -// otherwise `R`. -template > -auto rust_call(F f, EF error_cb, Args... args) { - initialize(); - - RustCallStatus status{}; - - if constexpr (std::is_null_pointer_v) { - if constexpr (std::is_void_v) { - f(args..., &status); - check_rust_call(status, error_cb); - } else { - auto ret = f(args..., &status); - check_rust_call(status, error_cb); - - return ret; - } - } else { - using E = std::invoke_result_t; - using Result = ::uniffi::expected; - - if constexpr (std::is_void_v) { - f(args..., &status); - check_rust_call(status, error_cb); - if (status.code == 1) { - return Result(::uniffi::unexpected(error_cb(status.error_buf))); - } - - return Result(); - } else { - auto ret = f(args..., &status); - check_rust_call(status, error_cb); - if (status.code == 1) { - return Result(::uniffi::unexpected(error_cb(status.error_buf))); - } - - return Result(ret); - } - } -} - -// Lifts the value of a successful fallible call and passes an error through. -template -::uniffi::expected lift_expected(::uniffi::expected ret, L lift) { - if (!ret) { - return ::uniffi::unexpected(std::move(ret.error())); - } - - return lift(std::move(*ret)); -} -{%- else %} -template -void check_rust_call(const RustCallStatus &status, F error_cb) { - switch (status.code) { - case 0: - return; - - case 1: - if constexpr (!std::is_null_pointer_v) { - error_cb(status.error_buf)->throw_underlying(); - } - break; - - case 2: - if (status.error_buf.len > 0) { - throw std::runtime_error({{ Type::String.borrow()|lift_fn(ci) }}(status.error_buf)); - } - - throw std::runtime_error("A Rust panic has occurred"); - } - - throw std::runtime_error("Unexpected Rust call status"); -} - -template > -R rust_call(F f, EF error_cb, Args... args) { - initialize(); - - RustCallStatus status{}; - - if constexpr (std::is_void_v) { - f(args..., &status); - check_rust_call(status, error_cb); - } else { - auto ret = f(args..., &status); - check_rust_call(status, error_cb); - - return ret; - } -} -{%- endif %} -{%- if config.expected() %} - -{% include "async.cpp" %} -{%- else %} - -template -void rust_call_trait_interface(RustCallStatus* status, F make_call, W write_value) { - initialize(); - - constexpr bool has_return_type = std::negation>>::value; - - try { - if constexpr(has_return_type) { - write_value(make_call()); - } else { - make_call(); - } - } catch (std::exception &e) { - status->code = 2; - status->error_buf = {{ Type::String.borrow()|lower_fn(ci) }}(e.what()); - } -} - -template -void rust_call_trait_interface_with_error(RustCallStatus* status, F make_call, W write_value, EF error_cb) { - initialize(); - - constexpr bool has_return_type = std::negation>>::value; - - try { - try { - if constexpr(has_return_type) { - write_value(make_call()); - } else { - make_call(); - } - } catch (E &e) { - status->code = 1; - status->error_buf = error_cb(e); - } - } catch (std::exception &e) { - status->code = 2; - status->error_buf = {{ Type::String.borrow()|lower_fn(ci) }}(e.what()); - } -} -{%- endif %} - - -{% include "rust_buf_tmpl.cpp" %} - -{{ internal_type_helper_code }} -} // namespace uniffi - -{{ type_helper_code }} - -{%- for func in ci.function_definitions() %} -{% include "fn_def.cpp" %} -{% endfor -%} -} // namespace {{ namespace }} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/templates/wrapper.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/templates/wrapper.hpp deleted file mode 100644 index 2b93045ea..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ /dev/null @@ -1,202 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -{%- for include in self.includes() %} -#include <{{ include }}> -{%- endfor %} - - -{%~ let namespace = ci.namespace() %} -#include "{{ namespace }}_scaffolding.hpp" - -{%- for namespace in self.external_namespaces() %} -#include "{{ namespace }}.hpp" -{%- endfor %} - -#ifndef UNIFFI_CPP_RUST_STREAM -#define UNIFFI_CPP_RUST_STREAM -namespace uniffi { -{% include "rust_buf_stream.cpp" %} -} -#endif - -{%- if config.expected() %} -#include -#include -#include "uniffi_expected.hpp" - -#ifndef UNIFFI_CPP_ASYNC_FUTURE -#define UNIFFI_CPP_ASYNC_FUTURE -namespace uniffi { -{% include "async.hpp" %} -} -#endif -{%- endif %} - -{%- import "macros.cpp" as macros %} -{% call macros::docstring_value(ci.namespace_docstring(), 0) %} -namespace {{ namespace }} { -{%- for typ in ci.iter_local_types() %} -{%- let type_name = typ|type_name(ci) %} -{%- match typ %} -{%- when Type::Enum { module_path, name } %} -{%- let e = ci.get_enum_definition(name).unwrap() %} -{%- if ci.is_used_as_error(typ) || !e.is_flat() %} -struct {{ name }}; -{%- else %} -enum class {{ name }}; -{%- endif %} -{%- when Type::Record { module_path, name } %} -struct {{ name }}; -{%- when Type::Object { module_path, name, imp } %} -struct {{ name }}; -{%- when Type::CallbackInterface { module_path, name } %} -struct {{ name }}; -{%- when Type::Custom { module_path, name, builtin } %} -{%- match config.custom_types.get(name.as_str()) %} -{%- when None %} -typedef {{ builtin|type_name(ci) }} {{ name }}; -{%- when Some with (type_config) %} -{%- match type_config.type_name %} -{%- when Some with (type_name) %} -typedef {{ type_name }} {{ name }}; -{%- else %} -{%- endmatch %} -{%- endmatch %} -{%- else %} -{%- endmatch %} -{%- endfor %} - -{%- for typ in self.sorted_types(ci.iter_local_types()) %} -{%- let type_name = typ|type_name(ci) %} -{%- match typ %} -{%- when Type::Enum { module_path, name } %} -{%- let e = ci.get_enum_definition(name).unwrap() %} -{%- if typ|error_class(ci) %} -{% include "err.hpp" %} -{%- else %} -{% include "enum.hpp" %} -{%- endif %} -{%- when Type::Record { module_path, name } %} -{% include "rec.hpp" %} -{%- when Type::CallbackInterface { module_path, name } %} -{%- let cbi = ci.get_callback_interface_definition(name).unwrap() %} -{%- let ffi_init_callback = cbi.ffi_init_callback() %} -{%- let interface_name = name %} -{%- let methods = cbi.methods() %} -{%- let vtable = cbi.vtable() %} -{%- let vtable_methods = cbi.vtable_methods() %} -{%- let interface_docstring = cbi.docstring() %} -{% include "callback.hpp" %} -{%- when Type::Object { module_path, name, imp } %} -{% include "obj.hpp" %} -{%- else %} -{%- endmatch %} -{%- endfor %} - -namespace uniffi { -using ::uniffi::RustStream; -using ::uniffi::RustStreamBuffer; -{%- if config.expected() %} -using ::uniffi::Future; -{%- endif %} -{%- for (converter, external) in self.external_ffi_converters() %} -using {{ converter }} = {{ external }}; -{%- endfor %} - -RustBuffer rustbuffer_alloc(uint64_t); -RustBuffer rustbuffer_from_bytes(const ForeignBytes &); -void rustbuffer_free(RustBuffer); - -{%- include "handle_map.cpp" %} - -{%- for typ in ci.iter_local_types() %} -{%- let type_name = typ|type_name(ci) %} -{%- match typ %} -{%- when Type::Boolean %} -{% include "bool_conv.hpp" %} -{%- when Type::UInt8 %} -{% include "arith_conv.hpp" %} -{%- when Type::Int8 %} -{% include "arith_conv.hpp" %} -{%- when Type::UInt16 %} -{% include "arith_conv.hpp" %} -{%- when Type::Int16 %} -{% include "arith_conv.hpp" %} -{%- when Type::UInt32 %} -{% include "arith_conv.hpp" %} -{%- when Type::Int32 %} -{% include "arith_conv.hpp" %} -{%- when Type::UInt64 %} -{% include "arith_conv.hpp" %} -{%- when Type::Int64 %} -{% include "arith_conv.hpp" %} -{%- when Type::Float32 %} -{% include "arith_conv.hpp" %} -{%- when Type::Float64 %} -{% include "arith_conv.hpp" %} -{%- when Type::Bytes %} -{% include "bytes_conv.hpp" %} -{%- when Type::String %} -{% include "str_conv.hpp" %} -{%- when Type::Timestamp %} -{% include "timestamp_conv.hpp" %} -{%- when Type::Duration %} -{% include "duration_conv.hpp" %} -{%- when Type::Enum { module_path, name } %} -{%- let e = ci.get_enum_definition(name).unwrap() %} -{%- if typ|error_class(ci) %} -{% include "err_conv.hpp" %} -{%- else %} -{% include "enum_conv.hpp" %} -{%- endif %} -{%- when Type::Object { module_path, name, imp } %} -{% include "obj_conv.hpp" %} -{%- when Type::Record { module_path, name } %} -{% include "rec_conv.hpp" %} -{%- when Type::Optional { inner_type } %} -{% include "opt_conv.hpp" %} -{%- when Type::Sequence { inner_type } %} -{% include "seq_conv.hpp" %} -{%- when Type::Map { key_type, value_type } %} -{% include "map_conv.hpp" %} -{%- when Type::CallbackInterface { module_path, name } %} -{% include "callback_conv.hpp" %} -{%- when Type::Custom { module_path, name, builtin } %} -{% include "custom.hpp" %} -{%- else %} -{%- endmatch %} -{%- endfor %} -} // namespace uniffi - -{% for func in ci.function_definitions() %} -{%- call macros::docstring(func, 0) %} -{% match func.return_type() %} -{%- when Some with (return_type) %} -{%- call macros::result_type(func, return_type|type_name(ci)) %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- when None %} -{%- call macros::result_type(func, "void") %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- endmatch %} -{%- endfor %} -} // namespace {{ namespace }} diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/vendor/README.md b/uniffi/cpp/bindgen/src/bindings/cpp/vendor/README.md deleted file mode 100644 index a9197ea6d..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/vendor/README.md +++ /dev/null @@ -1,4 +0,0 @@ -`tl_expected.hpp` is [TartanLlama/expected](https://github.com/TartanLlama/expected) v1.1.0 -(`include/tl/expected.hpp`) under CC0. The `error_style = "expected"` bindings ship it as their -`expected` type at every C++ standard. One change: with exceptions disabled, `value()` on an error -prints a message and aborts instead of being `__builtin_unreachable()`. diff --git a/uniffi/cpp/bindgen/src/bindings/cpp/vendor/tl_expected.hpp b/uniffi/cpp/bindgen/src/bindings/cpp/vendor/tl_expected.hpp deleted file mode 100644 index 5b9f23ebc..000000000 --- a/uniffi/cpp/bindgen/src/bindings/cpp/vendor/tl_expected.hpp +++ /dev/null @@ -1,2444 +0,0 @@ -/// -// expected - An implementation of std::expected with extensions -// Written in 2017 by Sy Brand (tartanllama@gmail.com, @TartanLlama) -// -// Documentation available at http://tl.tartanllama.xyz/ -// -// To the extent possible under law, the author(s) have dedicated all -// copyright and related and neighboring rights to this software to the -// public domain worldwide. This software is distributed without any warranty. -// -// You should have received a copy of the CC0 Public Domain Dedication -// along with this software. If not, see -// . -/// - -#ifndef TL_EXPECTED_HPP -#define TL_EXPECTED_HPP - -#define TL_EXPECTED_VERSION_MAJOR 1 -#define TL_EXPECTED_VERSION_MINOR 1 -#define TL_EXPECTED_VERSION_PATCH 0 - -#include -#include -#include -#include -#include -#include - -#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) -#define TL_EXPECTED_EXCEPTIONS_ENABLED -#endif - -#if (defined(_MSC_VER) && _MSC_VER == 1900) -#define TL_EXPECTED_MSVC2015 -#define TL_EXPECTED_MSVC2015_CONSTEXPR -#else -#define TL_EXPECTED_MSVC2015_CONSTEXPR constexpr -#endif - -#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ - !defined(__clang__)) -#define TL_EXPECTED_GCC49 -#endif - -#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 4 && \ - !defined(__clang__)) -#define TL_EXPECTED_GCC54 -#endif - -#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 5 && \ - !defined(__clang__)) -#define TL_EXPECTED_GCC55 -#endif - -#if !defined(TL_ASSERT) -//can't have assert in constexpr in C++11 and GCC 4.9 has a compiler bug -#if (__cplusplus > 201103L) && !defined(TL_EXPECTED_GCC49) -#include -#define TL_ASSERT(x) assert(x) -#else -#define TL_ASSERT(x) -#endif -#endif - -#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ - !defined(__clang__)) -// GCC < 5 doesn't support overloading on const&& for member functions - -#define TL_EXPECTED_NO_CONSTRR -// GCC < 5 doesn't support some standard C++11 type traits -#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ - std::has_trivial_copy_constructor -#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ - std::has_trivial_copy_assign - -// This one will be different for GCC 5.7 if it's ever supported -#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ - std::is_trivially_destructible - -// GCC 5 < v < 8 has a bug in is_trivially_copy_constructible which breaks -// std::vector for non-copyable types -#elif (defined(__GNUC__) && __GNUC__ < 8 && !defined(__clang__)) -#ifndef TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX -#define TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX -namespace tl { -namespace detail { -template -struct is_trivially_copy_constructible - : std::is_trivially_copy_constructible {}; -#ifdef _GLIBCXX_VECTOR -template -struct is_trivially_copy_constructible> : std::false_type {}; -#endif -} // namespace detail -} // namespace tl -#endif - -#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ - tl::detail::is_trivially_copy_constructible -#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ - std::is_trivially_copy_assignable -#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ - std::is_trivially_destructible -#else -#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ - std::is_trivially_copy_constructible -#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ - std::is_trivially_copy_assignable -#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ - std::is_trivially_destructible -#endif - -#if __cplusplus > 201103L -#define TL_EXPECTED_CXX14 -#endif - -#ifdef TL_EXPECTED_GCC49 -#define TL_EXPECTED_GCC49_CONSTEXPR -#else -#define TL_EXPECTED_GCC49_CONSTEXPR constexpr -#endif - -#if (__cplusplus == 201103L || defined(TL_EXPECTED_MSVC2015) || \ - defined(TL_EXPECTED_GCC49)) -#define TL_EXPECTED_11_CONSTEXPR -#else -#define TL_EXPECTED_11_CONSTEXPR constexpr -#endif - -namespace tl { -template class expected; - -#ifndef TL_MONOSTATE_INPLACE_MUTEX -#define TL_MONOSTATE_INPLACE_MUTEX -class monostate {}; - -struct in_place_t { - explicit in_place_t() = default; -}; -static constexpr in_place_t in_place{}; -#endif - -template class unexpected { -public: - static_assert(!std::is_same::value, "E must not be void"); - - unexpected() = delete; - constexpr explicit unexpected(const E &e) : m_val(e) {} - - constexpr explicit unexpected(E &&e) : m_val(std::move(e)) {} - - template ::value>::type * = nullptr> - constexpr explicit unexpected(Args &&...args) - : m_val(std::forward(args)...) {} - template < - class U, class... Args, - typename std::enable_if &, Args &&...>::value>::type * = nullptr> - constexpr explicit unexpected(std::initializer_list l, Args &&...args) - : m_val(l, std::forward(args)...) {} - - constexpr const E &value() const & { return m_val; } - TL_EXPECTED_11_CONSTEXPR E &value() & { return m_val; } - TL_EXPECTED_11_CONSTEXPR E &&value() && { return std::move(m_val); } - constexpr const E &&value() const && { return std::move(m_val); } - -private: - E m_val; -}; - -#ifdef __cpp_deduction_guides -template unexpected(E) -> unexpected; -#endif - -template -constexpr bool operator==(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() == rhs.value(); -} -template -constexpr bool operator!=(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() != rhs.value(); -} -template -constexpr bool operator<(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() < rhs.value(); -} -template -constexpr bool operator<=(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() <= rhs.value(); -} -template -constexpr bool operator>(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() > rhs.value(); -} -template -constexpr bool operator>=(const unexpected &lhs, const unexpected &rhs) { - return lhs.value() >= rhs.value(); -} - -template -unexpected::type> make_unexpected(E &&e) { - return unexpected::type>(std::forward(e)); -} - -struct unexpect_t { - unexpect_t() = default; -}; -static constexpr unexpect_t unexpect{}; - -namespace detail { -template -[[noreturn]] TL_EXPECTED_11_CONSTEXPR void throw_exception(E &&e) { -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - throw std::forward(e); -#else - (void)e; - std::fputs("uniffi: expected::value() called on an error\n", stderr); - std::fflush(stderr); - std::abort(); -#endif -} - -#ifndef TL_TRAITS_MUTEX -#define TL_TRAITS_MUTEX -// C++14-style aliases for brevity -template using remove_const_t = typename std::remove_const::type; -template -using remove_reference_t = typename std::remove_reference::type; -template using decay_t = typename std::decay::type; -template -using enable_if_t = typename std::enable_if::type; -template -using conditional_t = typename std::conditional::type; - -// std::conjunction from C++17 -template struct conjunction : std::true_type {}; -template struct conjunction : B {}; -template -struct conjunction - : std::conditional, B>::type {}; - -#if defined(_LIBCPP_VERSION) && __cplusplus == 201103L -#define TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND -#endif - -// In C++11 mode, there's an issue in libc++'s std::mem_fn -// which results in a hard-error when using it in a noexcept expression -// in some cases. This is a check to workaround the common failing case. -#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND -template -struct is_pointer_to_non_const_member_func : std::false_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; -template -struct is_pointer_to_non_const_member_func - : std::true_type {}; - -template struct is_const_or_const_ref : std::false_type {}; -template struct is_const_or_const_ref : std::true_type {}; -template struct is_const_or_const_ref : std::true_type {}; -#endif - -// std::invoke from C++17 -// https://stackoverflow.com/questions/38288042/c11-14-invoke-workaround -template < - typename Fn, typename... Args, -#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND - typename = enable_if_t::value && - is_const_or_const_ref::value)>, -#endif - typename = enable_if_t>::value>, int = 0> -constexpr auto invoke(Fn &&f, Args &&...args) noexcept( - noexcept(std::mem_fn(f)(std::forward(args)...))) - -> decltype(std::mem_fn(f)(std::forward(args)...)) { - return std::mem_fn(f)(std::forward(args)...); -} - -template >::value>> -constexpr auto invoke(Fn &&f, Args &&...args) noexcept( - noexcept(std::forward(f)(std::forward(args)...))) - -> decltype(std::forward(f)(std::forward(args)...)) { - return std::forward(f)(std::forward(args)...); -} - -// std::invoke_result from C++17 -template struct invoke_result_impl; - -template -struct invoke_result_impl< - F, - decltype(detail::invoke(std::declval(), std::declval()...), void()), - Us...> { - using type = - decltype(detail::invoke(std::declval(), std::declval()...)); -}; - -template -using invoke_result = invoke_result_impl; - -template -using invoke_result_t = typename invoke_result::type; - -#if defined(_MSC_VER) && _MSC_VER <= 1900 -// TODO make a version which works with MSVC 2015 -template struct is_swappable : std::true_type {}; - -template struct is_nothrow_swappable : std::true_type {}; -#else -// https://stackoverflow.com/questions/26744589/what-is-a-proper-way-to-implement-is-swappable-to-test-for-the-swappable-concept -namespace swap_adl_tests { -// if swap ADL finds this then it would call std::swap otherwise (same -// signature) -struct tag {}; - -template tag swap(T &, T &); -template tag swap(T (&a)[N], T (&b)[N]); - -// helper functions to test if an unqualified swap is possible, and if it -// becomes std::swap -template std::false_type can_swap(...) noexcept(false); -template (), std::declval()))> -std::true_type can_swap(int) noexcept(noexcept(swap(std::declval(), - std::declval()))); - -template std::false_type uses_std(...); -template -std::is_same(), std::declval())), tag> -uses_std(int); - -template -struct is_std_swap_noexcept - : std::integral_constant::value && - std::is_nothrow_move_assignable::value> {}; - -template -struct is_std_swap_noexcept : is_std_swap_noexcept {}; - -template -struct is_adl_swap_noexcept - : std::integral_constant(0))> {}; -} // namespace swap_adl_tests - -template -struct is_swappable - : std::integral_constant< - bool, - decltype(detail::swap_adl_tests::can_swap(0))::value && - (!decltype(detail::swap_adl_tests::uses_std(0))::value || - (std::is_move_assignable::value && - std::is_move_constructible::value))> {}; - -template -struct is_swappable - : std::integral_constant< - bool, - decltype(detail::swap_adl_tests::can_swap(0))::value && - (!decltype(detail::swap_adl_tests::uses_std( - 0))::value || - is_swappable::value)> {}; - -template -struct is_nothrow_swappable - : std::integral_constant< - bool, - is_swappable::value && - ((decltype(detail::swap_adl_tests::uses_std(0))::value && - detail::swap_adl_tests::is_std_swap_noexcept::value) || - (!decltype(detail::swap_adl_tests::uses_std(0))::value && - detail::swap_adl_tests::is_adl_swap_noexcept::value))> {}; -#endif -#endif - -// Trait for checking if a type is a tl::expected -template struct is_expected_impl : std::false_type {}; -template -struct is_expected_impl> : std::true_type {}; -template using is_expected = is_expected_impl>; - -template -using expected_enable_forward_value = detail::enable_if_t< - std::is_constructible::value && - !std::is_same, in_place_t>::value && - !std::is_same, detail::decay_t>::value && - !std::is_same, detail::decay_t>::value>; - -template -using expected_enable_from_other = detail::enable_if_t< - std::is_constructible::value && - std::is_constructible::value && - !std::is_constructible &>::value && - !std::is_constructible &&>::value && - !std::is_constructible &>::value && - !std::is_constructible &&>::value && - !std::is_convertible &, T>::value && - !std::is_convertible &&, T>::value && - !std::is_convertible &, T>::value && - !std::is_convertible &&, T>::value>; - -template -using is_void_or = conditional_t::value, std::true_type, U>; - -template -using is_copy_constructible_or_void = - is_void_or>; - -template -using is_move_constructible_or_void = - is_void_or>; - -template -using is_copy_assignable_or_void = is_void_or>; - -template -using is_move_assignable_or_void = is_void_or>; - -} // namespace detail - -namespace detail { -struct no_init_t {}; -static constexpr no_init_t no_init{}; - -// Implements the storage of the values, and ensures that the destructor is -// trivial if it can be. -// -// This specialization is for where neither `T` or `E` is trivially -// destructible, so the destructors must be called on destruction of the -// `expected` -template ::value, - bool = std::is_trivially_destructible::value> -struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (m_has_val) { - m_val.~T(); - } else { - m_unexpect.~unexpected(); - } - } - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// This specialization is for when both `T` and `E` are trivially-destructible, -// so the destructor of the `expected` can be trivial. -template struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() = default; - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// T is trivial, E is not. -template struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - TL_EXPECTED_MSVC2015_CONSTEXPR expected_storage_base(no_init_t) - : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (!m_has_val) { - m_unexpect.~unexpected(); - } - } - - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// E is trivial, T is not. -template struct expected_storage_base { - constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} - - template ::value> * = - nullptr> - constexpr expected_storage_base(in_place_t, Args &&...args) - : m_val(std::forward(args)...), m_has_val(true) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected_storage_base(in_place_t, std::initializer_list il, - Args &&...args) - : m_val(il, std::forward(args)...), m_has_val(true) {} - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (m_has_val) { - m_val.~T(); - } - } - union { - T m_val; - unexpected m_unexpect; - char m_no_init; - }; - bool m_has_val; -}; - -// `T` is `void`, `E` is trivially-destructible -template struct expected_storage_base { - #if __GNUC__ <= 5 - //no constexpr for GCC 4/5 bug - #else - TL_EXPECTED_MSVC2015_CONSTEXPR - #endif - expected_storage_base() : m_has_val(true) {} - - constexpr expected_storage_base(no_init_t) : m_val(), m_has_val(false) {} - - constexpr expected_storage_base(in_place_t) : m_has_val(true) {} - - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() = default; - struct dummy {}; - union { - unexpected m_unexpect; - dummy m_val; - }; - bool m_has_val; -}; - -// `T` is `void`, `E` is not trivially-destructible -template struct expected_storage_base { - constexpr expected_storage_base() : m_dummy(), m_has_val(true) {} - constexpr expected_storage_base(no_init_t) : m_dummy(), m_has_val(false) {} - - constexpr expected_storage_base(in_place_t) : m_dummy(), m_has_val(true) {} - - template ::value> * = - nullptr> - constexpr explicit expected_storage_base(unexpect_t, Args &&...args) - : m_unexpect(std::forward(args)...), m_has_val(false) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected_storage_base(unexpect_t, - std::initializer_list il, - Args &&...args) - : m_unexpect(il, std::forward(args)...), m_has_val(false) {} - - ~expected_storage_base() { - if (!m_has_val) { - m_unexpect.~unexpected(); - } - } - - union { - unexpected m_unexpect; - char m_dummy; - }; - bool m_has_val; -}; - -// This base class provides some handy member functions which can be used in -// further derived classes -template -struct expected_operations_base : expected_storage_base { - using expected_storage_base::expected_storage_base; - - template void construct(Args &&...args) noexcept { - new (std::addressof(this->m_val)) T(std::forward(args)...); - this->m_has_val = true; - } - - template void construct_with(Rhs &&rhs) noexcept { - new (std::addressof(this->m_val)) T(std::forward(rhs).get()); - this->m_has_val = true; - } - - template void construct_error(Args &&...args) noexcept { - new (std::addressof(this->m_unexpect)) - unexpected(std::forward(args)...); - this->m_has_val = false; - } - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - - // These assign overloads ensure that the most efficient assignment - // implementation is used while maintaining the strong exception guarantee. - // The problematic case is where rhs has a value, but *this does not. - // - // This overload handles the case where we can just copy-construct `T` - // directly into place without throwing. - template ::value> - * = nullptr> - void assign(const expected_operations_base &rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(rhs.get()); - } else { - assign_common(rhs); - } - } - - // This overload handles the case where we can attempt to create a copy of - // `T`, then no-throw move it into place if the copy was successful. - template ::value && - std::is_nothrow_move_constructible::value> - * = nullptr> - void assign(const expected_operations_base &rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - T tmp = rhs.get(); - geterr().~unexpected(); - construct(std::move(tmp)); - } else { - assign_common(rhs); - } - } - - // This overload is the worst-case, where we have to move-construct the - // unexpected value into temporary storage, then try to copy the T into place. - // If the construction succeeds, then everything is fine, but if it throws, - // then we move the old unexpected value back into place before rethrowing the - // exception. - template ::value && - !std::is_nothrow_move_constructible::value> - * = nullptr> - void assign(const expected_operations_base &rhs) { - if (!this->m_has_val && rhs.m_has_val) { - auto tmp = std::move(geterr()); - geterr().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - construct(rhs.get()); - } catch (...) { - geterr() = std::move(tmp); - throw; - } -#else - construct(rhs.get()); -#endif - } else { - assign_common(rhs); - } - } - - // These overloads do the same as above, but for rvalues - template ::value> - * = nullptr> - void assign(expected_operations_base &&rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(std::move(rhs).get()); - } else { - assign_common(std::move(rhs)); - } - } - - template ::value> - * = nullptr> - void assign(expected_operations_base &&rhs) { - if (!this->m_has_val && rhs.m_has_val) { - auto tmp = std::move(geterr()); - geterr().~unexpected(); -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - construct(std::move(rhs).get()); - } catch (...) { - geterr() = std::move(tmp); - throw; - } -#else - construct(std::move(rhs).get()); -#endif - } else { - assign_common(std::move(rhs)); - } - } - -#else - - // If exceptions are disabled then we can just copy-construct - void assign(const expected_operations_base &rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(rhs.get()); - } else { - assign_common(rhs); - } - } - - void assign(expected_operations_base &&rhs) noexcept { - if (!this->m_has_val && rhs.m_has_val) { - geterr().~unexpected(); - construct(std::move(rhs).get()); - } else { - assign_common(std::move(rhs)); - } - } - -#endif - - // The common part of move/copy assigning - template void assign_common(Rhs &&rhs) { - if (this->m_has_val) { - if (rhs.m_has_val) { - get() = std::forward(rhs).get(); - } else { - destroy_val(); - construct_error(std::forward(rhs).geterr()); - } - } else { - if (!rhs.m_has_val) { - geterr() = std::forward(rhs).geterr(); - } - } - } - - bool has_value() const { return this->m_has_val; } - - TL_EXPECTED_11_CONSTEXPR T &get() & { return this->m_val; } - constexpr const T &get() const & { return this->m_val; } - TL_EXPECTED_11_CONSTEXPR T &&get() && { return std::move(this->m_val); } -#ifndef TL_EXPECTED_NO_CONSTRR - constexpr const T &&get() const && { return std::move(this->m_val); } -#endif - - TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { - return this->m_unexpect; - } - constexpr const unexpected &geterr() const & { return this->m_unexpect; } - TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { - return std::move(this->m_unexpect); - } -#ifndef TL_EXPECTED_NO_CONSTRR - constexpr const unexpected &&geterr() const && { - return std::move(this->m_unexpect); - } -#endif - - TL_EXPECTED_11_CONSTEXPR void destroy_val() { get().~T(); } -}; - -// This base class provides some handy member functions which can be used in -// further derived classes -template -struct expected_operations_base : expected_storage_base { - using expected_storage_base::expected_storage_base; - - template void construct() noexcept { this->m_has_val = true; } - - // This function doesn't use its argument, but needs it so that code in - // levels above this can work independently of whether T is void - template void construct_with(Rhs &&) noexcept { - this->m_has_val = true; - } - - template void construct_error(Args &&...args) noexcept { - new (std::addressof(this->m_unexpect)) - unexpected(std::forward(args)...); - this->m_has_val = false; - } - - template void assign(Rhs &&rhs) noexcept { - if (!this->m_has_val) { - if (rhs.m_has_val) { - geterr().~unexpected(); - construct(); - } else { - geterr() = std::forward(rhs).geterr(); - } - } else { - if (!rhs.m_has_val) { - construct_error(std::forward(rhs).geterr()); - } - } - } - - bool has_value() const { return this->m_has_val; } - - TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { - return this->m_unexpect; - } - constexpr const unexpected &geterr() const & { return this->m_unexpect; } - TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { - return std::move(this->m_unexpect); - } -#ifndef TL_EXPECTED_NO_CONSTRR - constexpr const unexpected &&geterr() const && { - return std::move(this->m_unexpect); - } -#endif - - TL_EXPECTED_11_CONSTEXPR void destroy_val() { - // no-op - } -}; - -// This class manages conditionally having a trivial copy constructor -// This specialization is for when T and E are trivially copy constructible -template :: - value &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value> -struct expected_copy_base : expected_operations_base { - using expected_operations_base::expected_operations_base; -}; - -// This specialization is for when T or E are not trivially copy constructible -template -struct expected_copy_base : expected_operations_base { - using expected_operations_base::expected_operations_base; - - expected_copy_base() = default; - expected_copy_base(const expected_copy_base &rhs) - : expected_operations_base(no_init) { - if (rhs.has_value()) { - this->construct_with(rhs); - } else { - this->construct_error(rhs.geterr()); - } - } - - expected_copy_base(expected_copy_base &&rhs) = default; - expected_copy_base &operator=(const expected_copy_base &rhs) = default; - expected_copy_base &operator=(expected_copy_base &&rhs) = default; -}; - -// This class manages conditionally having a trivial move constructor -// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it -// doesn't implement an analogue to std::is_trivially_move_constructible. We -// have to make do with a non-trivial move constructor even if T is trivially -// move constructible -#ifndef TL_EXPECTED_GCC49 -template >::value - &&std::is_trivially_move_constructible::value> -struct expected_move_base : expected_copy_base { - using expected_copy_base::expected_copy_base; -}; -#else -template struct expected_move_base; -#endif -template -struct expected_move_base : expected_copy_base { - using expected_copy_base::expected_copy_base; - - expected_move_base() = default; - expected_move_base(const expected_move_base &rhs) = default; - - expected_move_base(expected_move_base &&rhs) noexcept( - std::is_nothrow_move_constructible::value) - : expected_copy_base(no_init) { - if (rhs.has_value()) { - this->construct_with(std::move(rhs)); - } else { - this->construct_error(std::move(rhs.geterr())); - } - } - expected_move_base &operator=(const expected_move_base &rhs) = default; - expected_move_base &operator=(expected_move_base &&rhs) = default; -}; - -// This class manages conditionally having a trivial copy assignment operator -template >::value - &&TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(E)::value - &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value - &&TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(E)::value> -struct expected_copy_assign_base : expected_move_base { - using expected_move_base::expected_move_base; -}; - -template -struct expected_copy_assign_base : expected_move_base { - using expected_move_base::expected_move_base; - - expected_copy_assign_base() = default; - expected_copy_assign_base(const expected_copy_assign_base &rhs) = default; - - expected_copy_assign_base(expected_copy_assign_base &&rhs) = default; - expected_copy_assign_base &operator=(const expected_copy_assign_base &rhs) { - this->assign(rhs); - return *this; - } - expected_copy_assign_base & - operator=(expected_copy_assign_base &&rhs) = default; -}; - -// This class manages conditionally having a trivial move assignment operator -// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it -// doesn't implement an analogue to std::is_trivially_move_assignable. We have -// to make do with a non-trivial move assignment operator even if T is trivially -// move assignable -#ifndef TL_EXPECTED_GCC49 -template , - std::is_trivially_move_constructible, - std::is_trivially_move_assignable>>:: - value &&std::is_trivially_destructible::value - &&std::is_trivially_move_constructible::value - &&std::is_trivially_move_assignable::value> -struct expected_move_assign_base : expected_copy_assign_base { - using expected_copy_assign_base::expected_copy_assign_base; -}; -#else -template struct expected_move_assign_base; -#endif - -template -struct expected_move_assign_base - : expected_copy_assign_base { - using expected_copy_assign_base::expected_copy_assign_base; - - expected_move_assign_base() = default; - expected_move_assign_base(const expected_move_assign_base &rhs) = default; - - expected_move_assign_base(expected_move_assign_base &&rhs) = default; - - expected_move_assign_base & - operator=(const expected_move_assign_base &rhs) = default; - - expected_move_assign_base & - operator=(expected_move_assign_base &&rhs) noexcept( - std::is_nothrow_move_constructible::value - &&std::is_nothrow_move_assignable::value) { - this->assign(std::move(rhs)); - return *this; - } -}; - -// expected_delete_ctor_base will conditionally delete copy and move -// constructors depending on whether T is copy/move constructible -template ::value && - std::is_copy_constructible::value), - bool EnableMove = (is_move_constructible_or_void::value && - std::is_move_constructible::value)> -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -template -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -template -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -template -struct expected_delete_ctor_base { - expected_delete_ctor_base() = default; - expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; - expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; - expected_delete_ctor_base & - operator=(const expected_delete_ctor_base &) = default; - expected_delete_ctor_base & - operator=(expected_delete_ctor_base &&) noexcept = default; -}; - -// expected_delete_assign_base will conditionally delete copy and move -// constructors depending on whether T and E are copy/move constructible + -// assignable -template ::value && - std::is_copy_constructible::value && - is_copy_assignable_or_void::value && - std::is_copy_assignable::value), - bool EnableMove = (is_move_constructible_or_void::value && - std::is_move_constructible::value && - is_move_assignable_or_void::value && - std::is_move_assignable::value)> -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = default; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = default; -}; - -template -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = default; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = delete; -}; - -template -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = delete; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = default; -}; - -template -struct expected_delete_assign_base { - expected_delete_assign_base() = default; - expected_delete_assign_base(const expected_delete_assign_base &) = default; - expected_delete_assign_base(expected_delete_assign_base &&) noexcept = - default; - expected_delete_assign_base & - operator=(const expected_delete_assign_base &) = delete; - expected_delete_assign_base & - operator=(expected_delete_assign_base &&) noexcept = delete; -}; - -// This is needed to be able to construct the expected_default_ctor_base which -// follows, while still conditionally deleting the default constructor. -struct default_constructor_tag { - explicit constexpr default_constructor_tag() = default; -}; - -// expected_default_ctor_base will ensure that expected has a deleted default -// consturctor if T is not default constructible. -// This specialization is for when T is default constructible -template ::value || std::is_void::value> -struct expected_default_ctor_base { - constexpr expected_default_ctor_base() noexcept = default; - constexpr expected_default_ctor_base( - expected_default_ctor_base const &) noexcept = default; - constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = - default; - expected_default_ctor_base & - operator=(expected_default_ctor_base const &) noexcept = default; - expected_default_ctor_base & - operator=(expected_default_ctor_base &&) noexcept = default; - - constexpr explicit expected_default_ctor_base(default_constructor_tag) {} -}; - -// This specialization is for when T is not default constructible -template struct expected_default_ctor_base { - constexpr expected_default_ctor_base() noexcept = delete; - constexpr expected_default_ctor_base( - expected_default_ctor_base const &) noexcept = default; - constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = - default; - expected_default_ctor_base & - operator=(expected_default_ctor_base const &) noexcept = default; - expected_default_ctor_base & - operator=(expected_default_ctor_base &&) noexcept = default; - - constexpr explicit expected_default_ctor_base(default_constructor_tag) {} -}; -} // namespace detail - -template class bad_expected_access : public std::exception { -public: - explicit bad_expected_access(E e) : m_val(std::move(e)) {} - - virtual const char *what() const noexcept override { - return "Bad expected access"; - } - - const E &error() const & { return m_val; } - E &error() & { return m_val; } - const E &&error() const && { return std::move(m_val); } - E &&error() && { return std::move(m_val); } - -private: - E m_val; -}; - -/// An `expected` object is an object that contains the storage for -/// another object and manages the lifetime of this contained object `T`. -/// Alternatively it could contain the storage for another unexpected object -/// `E`. The contained object may not be initialized after the expected object -/// has been initialized, and may not be destroyed before the expected object -/// has been destroyed. The initialization state of the contained object is -/// tracked by the expected object. -template -class expected : private detail::expected_move_assign_base, - private detail::expected_delete_ctor_base, - private detail::expected_delete_assign_base, - private detail::expected_default_ctor_base { - static_assert(!std::is_reference::value, "T must not be a reference"); - static_assert(!std::is_same::type>::value, - "T must not be in_place_t"); - static_assert(!std::is_same::type>::value, - "T must not be unexpect_t"); - static_assert( - !std::is_same>::type>::value, - "T must not be unexpected"); - static_assert(!std::is_reference::value, "E must not be a reference"); - - T *valptr() { return std::addressof(this->m_val); } - const T *valptr() const { return std::addressof(this->m_val); } - unexpected *errptr() { return std::addressof(this->m_unexpect); } - const unexpected *errptr() const { - return std::addressof(this->m_unexpect); - } - - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &val() { - return this->m_val; - } - TL_EXPECTED_11_CONSTEXPR unexpected &err() { return this->m_unexpect; } - - template ::value> * = nullptr> - constexpr const U &val() const { - return this->m_val; - } - constexpr const unexpected &err() const { return this->m_unexpect; } - - using impl_base = detail::expected_move_assign_base; - using ctor_base = detail::expected_default_ctor_base; - -public: - typedef T value_type; - typedef E error_type; - typedef unexpected unexpected_type; - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) & { - return and_then_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) && { - return and_then_impl(std::move(*this), std::forward(f)); - } - template constexpr auto and_then(F &&f) const & { - return and_then_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template constexpr auto and_then(F &&f) const && { - return and_then_impl(std::move(*this), std::forward(f)); - } -#endif - -#else - template - TL_EXPECTED_11_CONSTEXPR auto - and_then(F &&f) & -> decltype(and_then_impl(std::declval(), - std::forward(f))) { - return and_then_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR auto - and_then(F &&f) && -> decltype(and_then_impl(std::declval(), - std::forward(f))) { - return and_then_impl(std::move(*this), std::forward(f)); - } - template - constexpr auto and_then(F &&f) const & -> decltype(and_then_impl( - std::declval(), std::forward(f))) { - return and_then_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr auto and_then(F &&f) const && -> decltype(and_then_impl( - std::declval(), std::forward(f))) { - return and_then_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template constexpr auto map(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - template constexpr auto map(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl( - std::declval(), std::declval())) - map(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval(), - std::declval())) - map(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - map(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - map(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template constexpr auto transform(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - template constexpr auto transform(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl( - std::declval(), std::declval())) - transform(F &&f) & { - return expected_map_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval(), - std::declval())) - transform(F &&f) && { - return expected_map_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - transform(F &&f) const & { - return expected_map_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(expected_map_impl(std::declval(), - std::declval())) - transform(F &&f) const && { - return expected_map_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto map_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto map_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template constexpr auto map_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - template constexpr auto map_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - map_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#endif -#endif -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) - template TL_EXPECTED_11_CONSTEXPR auto transform_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template TL_EXPECTED_11_CONSTEXPR auto transform_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template constexpr auto transform_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - template constexpr auto transform_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#else - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) & { - return map_error_impl(*this, std::forward(f)); - } - template - TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) && { - return map_error_impl(std::move(*this), std::forward(f)); - } - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) const & { - return map_error_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template - constexpr decltype(map_error_impl(std::declval(), - std::declval())) - transform_error(F &&f) const && { - return map_error_impl(std::move(*this), std::forward(f)); - } -#endif -#endif - template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) & { - return or_else_impl(*this, std::forward(f)); - } - - template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) && { - return or_else_impl(std::move(*this), std::forward(f)); - } - - template expected constexpr or_else(F &&f) const & { - return or_else_impl(*this, std::forward(f)); - } - -#ifndef TL_EXPECTED_NO_CONSTRR - template expected constexpr or_else(F &&f) const && { - return or_else_impl(std::move(*this), std::forward(f)); - } -#endif - constexpr expected() = default; - constexpr expected(const expected &rhs) = default; - constexpr expected(expected &&rhs) = default; - expected &operator=(const expected &rhs) = default; - expected &operator=(expected &&rhs) = default; - - template ::value> * = - nullptr> - constexpr expected(in_place_t, Args &&...args) - : impl_base(in_place, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template &, Args &&...>::value> * = nullptr> - constexpr expected(in_place_t, std::initializer_list il, Args &&...args) - : impl_base(in_place, il, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template ::value> * = - nullptr, - detail::enable_if_t::value> * = - nullptr> - explicit constexpr expected(const unexpected &e) - : impl_base(unexpect, e.value()), - ctor_base(detail::default_constructor_tag{}) {} - - template < - class G = E, - detail::enable_if_t::value> * = - nullptr, - detail::enable_if_t::value> * = nullptr> - constexpr expected(unexpected const &e) - : impl_base(unexpect, e.value()), - ctor_base(detail::default_constructor_tag{}) {} - - template < - class G = E, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t::value> * = nullptr> - explicit constexpr expected(unexpected &&e) noexcept( - std::is_nothrow_constructible::value) - : impl_base(unexpect, std::move(e.value())), - ctor_base(detail::default_constructor_tag{}) {} - - template < - class G = E, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t::value> * = nullptr> - constexpr expected(unexpected &&e) noexcept( - std::is_nothrow_constructible::value) - : impl_base(unexpect, std::move(e.value())), - ctor_base(detail::default_constructor_tag{}) {} - - template ::value> * = - nullptr> - constexpr explicit expected(unexpect_t, Args &&...args) - : impl_base(unexpect, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template &, Args &&...>::value> * = nullptr> - constexpr explicit expected(unexpect_t, std::initializer_list il, - Args &&...args) - : impl_base(unexpect, il, std::forward(args)...), - ctor_base(detail::default_constructor_tag{}) {} - - template ::value && - std::is_convertible::value)> * = - nullptr, - detail::expected_enable_from_other - * = nullptr> - explicit TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(*rhs); - } else { - this->construct_error(rhs.error()); - } - } - - template ::value && - std::is_convertible::value)> * = - nullptr, - detail::expected_enable_from_other - * = nullptr> - TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(*rhs); - } else { - this->construct_error(rhs.error()); - } - } - - template < - class U, class G, - detail::enable_if_t::value && - std::is_convertible::value)> * = nullptr, - detail::expected_enable_from_other * = nullptr> - explicit TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(std::move(*rhs)); - } else { - this->construct_error(std::move(rhs.error())); - } - } - - template < - class U, class G, - detail::enable_if_t<(std::is_convertible::value && - std::is_convertible::value)> * = nullptr, - detail::expected_enable_from_other * = nullptr> - TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) - : ctor_base(detail::default_constructor_tag{}) { - if (rhs.has_value()) { - this->construct(std::move(*rhs)); - } else { - this->construct_error(std::move(rhs.error())); - } - } - - template < - class U = T, - detail::enable_if_t::value> * = nullptr, - detail::expected_enable_forward_value * = nullptr> - explicit TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) - : expected(in_place, std::forward(v)) {} - - template < - class U = T, - detail::enable_if_t::value> * = nullptr, - detail::expected_enable_forward_value * = nullptr> - TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) - : expected(in_place, std::forward(v)) {} - - template < - class U = T, class G = T, - detail::enable_if_t::value> * = - nullptr, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t< - (!std::is_same, detail::decay_t>::value && - !detail::conjunction, - std::is_same>>::value && - std::is_constructible::value && - std::is_assignable::value && - std::is_nothrow_move_constructible::value)> * = nullptr> - expected &operator=(U &&v) { - if (has_value()) { - val() = std::forward(v); - } else { - err().~unexpected(); - ::new (valptr()) T(std::forward(v)); - this->m_has_val = true; - } - - return *this; - } - - template < - class U = T, class G = T, - detail::enable_if_t::value> * = - nullptr, - detail::enable_if_t::value> * = nullptr, - detail::enable_if_t< - (!std::is_same, detail::decay_t>::value && - !detail::conjunction, - std::is_same>>::value && - std::is_constructible::value && - std::is_assignable::value && - std::is_nothrow_move_constructible::value)> * = nullptr> - expected &operator=(U &&v) { - if (has_value()) { - val() = std::forward(v); - } else { - auto tmp = std::move(err()); - err().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (valptr()) T(std::forward(v)); - this->m_has_val = true; - } catch (...) { - err() = std::move(tmp); - throw; - } -#else - ::new (valptr()) T(std::forward(v)); - this->m_has_val = true; -#endif - } - - return *this; - } - - template ::value && - std::is_assignable::value> * = nullptr> - expected &operator=(const unexpected &rhs) { - if (!has_value()) { - err() = rhs; - } else { - this->destroy_val(); - ::new (errptr()) unexpected(rhs); - this->m_has_val = false; - } - - return *this; - } - - template ::value && - std::is_move_assignable::value> * = nullptr> - expected &operator=(unexpected &&rhs) noexcept { - if (!has_value()) { - err() = std::move(rhs); - } else { - this->destroy_val(); - ::new (errptr()) unexpected(std::move(rhs)); - this->m_has_val = false; - } - - return *this; - } - - template ::value> * = nullptr> - void emplace(Args &&...args) { - if (has_value()) { - val().~T(); - } else { - err().~unexpected(); - this->m_has_val = true; - } - ::new (valptr()) T(std::forward(args)...); - } - - template ::value> * = nullptr> - void emplace(Args &&...args) { - if (has_value()) { - val().~T(); - ::new (valptr()) T(std::forward(args)...); - } else { - auto tmp = std::move(err()); - err().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (valptr()) T(std::forward(args)...); - this->m_has_val = true; - } catch (...) { - err() = std::move(tmp); - throw; - } -#else - ::new (valptr()) T(std::forward(args)...); - this->m_has_val = true; -#endif - } - } - - template &, Args &&...>::value> * = nullptr> - void emplace(std::initializer_list il, Args &&...args) { - if (has_value()) { - T t(il, std::forward(args)...); - val() = std::move(t); - } else { - err().~unexpected(); - ::new (valptr()) T(il, std::forward(args)...); - this->m_has_val = true; - } - } - - template &, Args &&...>::value> * = nullptr> - void emplace(std::initializer_list il, Args &&...args) { - if (has_value()) { - T t(il, std::forward(args)...); - val() = std::move(t); - } else { - auto tmp = std::move(err()); - err().~unexpected(); - -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (valptr()) T(il, std::forward(args)...); - this->m_has_val = true; - } catch (...) { - err() = std::move(tmp); - throw; - } -#else - ::new (valptr()) T(il, std::forward(args)...); - this->m_has_val = true; -#endif - } - } - -private: - using t_is_void = std::true_type; - using t_is_not_void = std::false_type; - using t_is_nothrow_move_constructible = std::true_type; - using move_constructing_t_can_throw = std::false_type; - using e_is_nothrow_move_constructible = std::true_type; - using move_constructing_e_can_throw = std::false_type; - - void swap_where_both_have_value(expected & /*rhs*/, t_is_void) noexcept { - // swapping void is a no-op - } - - void swap_where_both_have_value(expected &rhs, t_is_not_void) { - using std::swap; - swap(val(), rhs.val()); - } - - void swap_where_only_one_has_value(expected &rhs, t_is_void) noexcept( - std::is_nothrow_move_constructible::value) { - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - std::swap(this->m_has_val, rhs.m_has_val); - } - - void swap_where_only_one_has_value(expected &rhs, t_is_not_void) { - swap_where_only_one_has_value_and_t_is_not_void( - rhs, typename std::is_nothrow_move_constructible::type{}, - typename std::is_nothrow_move_constructible::type{}); - } - - void swap_where_only_one_has_value_and_t_is_not_void( - expected &rhs, t_is_nothrow_move_constructible, - e_is_nothrow_move_constructible) noexcept { - auto temp = std::move(val()); - val().~T(); - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - ::new (rhs.valptr()) T(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); - } - - void swap_where_only_one_has_value_and_t_is_not_void( - expected &rhs, t_is_nothrow_move_constructible, - move_constructing_e_can_throw) { - auto temp = std::move(val()); - val().~T(); -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - ::new (rhs.valptr()) T(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); - } catch (...) { - val() = std::move(temp); - throw; - } -#else - ::new (errptr()) unexpected_type(std::move(rhs.err())); - rhs.err().~unexpected_type(); - ::new (rhs.valptr()) T(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); -#endif - } - - void swap_where_only_one_has_value_and_t_is_not_void( - expected &rhs, move_constructing_t_can_throw, - e_is_nothrow_move_constructible) { - auto temp = std::move(rhs.err()); - rhs.err().~unexpected_type(); -#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED - try { - ::new (rhs.valptr()) T(std::move(val())); - val().~T(); - ::new (errptr()) unexpected_type(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); - } catch (...) { - rhs.err() = std::move(temp); - throw; - } -#else - ::new (rhs.valptr()) T(std::move(val())); - val().~T(); - ::new (errptr()) unexpected_type(std::move(temp)); - std::swap(this->m_has_val, rhs.m_has_val); -#endif - } - -public: - template - detail::enable_if_t::value && - detail::is_swappable::value && - (std::is_nothrow_move_constructible::value || - std::is_nothrow_move_constructible::value)> - swap(expected &rhs) noexcept( - std::is_nothrow_move_constructible::value - &&detail::is_nothrow_swappable::value - &&std::is_nothrow_move_constructible::value - &&detail::is_nothrow_swappable::value) { - if (has_value() && rhs.has_value()) { - swap_where_both_have_value(rhs, typename std::is_void::type{}); - } else if (!has_value() && rhs.has_value()) { - rhs.swap(*this); - } else if (has_value()) { - swap_where_only_one_has_value(rhs, typename std::is_void::type{}); - } else { - using std::swap; - swap(err(), rhs.err()); - } - } - - constexpr const T *operator->() const { - TL_ASSERT(has_value()); - return valptr(); - } - TL_EXPECTED_11_CONSTEXPR T *operator->() { - TL_ASSERT(has_value()); - return valptr(); - } - - template ::value> * = nullptr> - constexpr const U &operator*() const & { - TL_ASSERT(has_value()); - return val(); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &operator*() & { - TL_ASSERT(has_value()); - return val(); - } - template ::value> * = nullptr> - constexpr const U &&operator*() const && { - TL_ASSERT(has_value()); - return std::move(val()); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &&operator*() && { - TL_ASSERT(has_value()); - return std::move(val()); - } - - constexpr bool has_value() const noexcept { return this->m_has_val; } - constexpr explicit operator bool() const noexcept { return this->m_has_val; } - - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR const U &value() const & { - if (!has_value()) - detail::throw_exception(bad_expected_access(err().value())); - return val(); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &value() & { - if (!has_value()) - detail::throw_exception(bad_expected_access(err().value())); - return val(); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR const U &&value() const && { - if (!has_value()) - detail::throw_exception(bad_expected_access(std::move(err()).value())); - return std::move(val()); - } - template ::value> * = nullptr> - TL_EXPECTED_11_CONSTEXPR U &&value() && { - if (!has_value()) - detail::throw_exception(bad_expected_access(std::move(err()).value())); - return std::move(val()); - } - - constexpr const E &error() const & { - TL_ASSERT(!has_value()); - return err().value(); - } - TL_EXPECTED_11_CONSTEXPR E &error() & { - TL_ASSERT(!has_value()); - return err().value(); - } - constexpr const E &&error() const && { - TL_ASSERT(!has_value()); - return std::move(err().value()); - } - TL_EXPECTED_11_CONSTEXPR E &&error() && { - TL_ASSERT(!has_value()); - return std::move(err().value()); - } - - template constexpr T value_or(U &&v) const & { - static_assert(std::is_copy_constructible::value && - std::is_convertible::value, - "T must be copy-constructible and convertible to from U&&"); - return bool(*this) ? **this : static_cast(std::forward(v)); - } - template TL_EXPECTED_11_CONSTEXPR T value_or(U &&v) && { - static_assert(std::is_move_constructible::value && - std::is_convertible::value, - "T must be move-constructible and convertible to from U&&"); - return bool(*this) ? std::move(**this) : static_cast(std::forward(v)); - } -}; - -namespace detail { -template using exp_t = typename detail::decay_t::value_type; -template using err_t = typename detail::decay_t::error_type; -template using ret_t = expected>; - -#ifdef TL_EXPECTED_CXX14 -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval()))> -constexpr auto and_then_impl(Exp &&exp, F &&f) { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() - ? detail::invoke(std::forward(f), *std::forward(exp)) - : Ret(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval()))> -constexpr auto and_then_impl(Exp &&exp, F &&f) { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() ? detail::invoke(std::forward(f)) - : Ret(unexpect, std::forward(exp).error()); -} -#else -template struct TC; -template (), - *std::declval())), - detail::enable_if_t>::value> * = nullptr> -auto and_then_impl(Exp &&exp, F &&f) -> Ret { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() - ? detail::invoke(std::forward(f), *std::forward(exp)) - : Ret(unexpect, std::forward(exp).error()); -} - -template ())), - detail::enable_if_t>::value> * = nullptr> -constexpr auto and_then_impl(Exp &&exp, F &&f) -> Ret { - static_assert(detail::is_expected::value, "F must return an expected"); - - return exp.has_value() ? detail::invoke(std::forward(f)) - : Ret(unexpect, std::forward(exp).error()); -} -#endif - -#ifdef TL_EXPECTED_CXX14 -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> -constexpr auto expected_map_impl(Exp &&exp, F &&f) { - using result = ret_t>; - return exp.has_value() ? result(detail::invoke(std::forward(f), - *std::forward(exp))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> -auto expected_map_impl(Exp &&exp, F &&f) { - using result = expected>; - if (exp.has_value()) { - detail::invoke(std::forward(f), *std::forward(exp)); - return result(); - } - - return result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> -constexpr auto expected_map_impl(Exp &&exp, F &&f) { - using result = ret_t>; - return exp.has_value() ? result(detail::invoke(std::forward(f))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> -auto expected_map_impl(Exp &&exp, F &&f) { - using result = expected>; - if (exp.has_value()) { - detail::invoke(std::forward(f)); - return result(); - } - - return result(unexpect, std::forward(exp).error()); -} -#else -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> - -constexpr auto expected_map_impl(Exp &&exp, F &&f) - -> ret_t> { - using result = ret_t>; - - return exp.has_value() ? result(detail::invoke(std::forward(f), - *std::forward(exp))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - *std::declval())), - detail::enable_if_t::value> * = nullptr> - -auto expected_map_impl(Exp &&exp, F &&f) -> expected> { - if (exp.has_value()) { - detail::invoke(std::forward(f), *std::forward(exp)); - return {}; - } - - return unexpected>(std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> - -constexpr auto expected_map_impl(Exp &&exp, F &&f) - -> ret_t> { - using result = ret_t>; - - return exp.has_value() ? result(detail::invoke(std::forward(f))) - : result(unexpect, std::forward(exp).error()); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval())), - detail::enable_if_t::value> * = nullptr> - -auto expected_map_impl(Exp &&exp, F &&f) -> expected> { - if (exp.has_value()) { - detail::invoke(std::forward(f)); - return {}; - } - - return unexpected>(std::forward(exp).error()); -} -#endif - -#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ - !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, detail::decay_t>; - return exp.has_value() - ? result(*std::forward(exp)) - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, monostate>; - if (exp.has_value()) { - return result(*std::forward(exp)); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, detail::decay_t>; - return exp.has_value() - ? result() - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) { - using result = expected, monostate>; - if (exp.has_value()) { - return result(); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} -#else -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) - -> expected, detail::decay_t> { - using result = expected, detail::decay_t>; - - return exp.has_value() - ? result(*std::forward(exp)) - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) -> expected, monostate> { - using result = expected, monostate>; - if (exp.has_value()) { - return result(*std::forward(exp)); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto map_error_impl(Exp &&exp, F &&f) - -> expected, detail::decay_t> { - using result = expected, detail::decay_t>; - - return exp.has_value() - ? result() - : result(unexpect, detail::invoke(std::forward(f), - std::forward(exp).error())); -} - -template >::value> * = nullptr, - class Ret = decltype(detail::invoke(std::declval(), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto map_error_impl(Exp &&exp, F &&f) -> expected, monostate> { - using result = expected, monostate>; - if (exp.has_value()) { - return result(); - } - - detail::invoke(std::forward(f), std::forward(exp).error()); - return result(unexpect, monostate{}); -} -#endif - -#ifdef TL_EXPECTED_CXX14 -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -constexpr auto or_else_impl(Exp &&exp, F &&f) { - static_assert(detail::is_expected::value, "F must return an expected"); - return exp.has_value() ? std::forward(exp) - : detail::invoke(std::forward(f), - std::forward(exp).error()); -} - -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -detail::decay_t or_else_impl(Exp &&exp, F &&f) { - return exp.has_value() ? std::forward(exp) - : (detail::invoke(std::forward(f), - std::forward(exp).error()), - std::forward(exp)); -} -#else -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -auto or_else_impl(Exp &&exp, F &&f) -> Ret { - static_assert(detail::is_expected::value, "F must return an expected"); - return exp.has_value() ? std::forward(exp) - : detail::invoke(std::forward(f), - std::forward(exp).error()); -} - -template (), - std::declval().error())), - detail::enable_if_t::value> * = nullptr> -detail::decay_t or_else_impl(Exp &&exp, F &&f) { - return exp.has_value() ? std::forward(exp) - : (detail::invoke(std::forward(f), - std::forward(exp).error()), - std::forward(exp)); -} -#endif -} // namespace detail - -template -constexpr bool operator==(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? false - : (!lhs.has_value() ? lhs.error() == rhs.error() : *lhs == *rhs); -} -template -constexpr bool operator!=(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? true - : (!lhs.has_value() ? lhs.error() != rhs.error() : *lhs != *rhs); -} -template -constexpr bool operator==(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? false - : (!lhs.has_value() ? lhs.error() == rhs.error() : true); -} -template -constexpr bool operator!=(const expected &lhs, - const expected &rhs) { - return (lhs.has_value() != rhs.has_value()) - ? true - : (!lhs.has_value() ? lhs.error() == rhs.error() : false); -} - -template -constexpr bool operator==(const expected &x, const U &v) { - return x.has_value() ? *x == v : false; -} -template -constexpr bool operator==(const U &v, const expected &x) { - return x.has_value() ? *x == v : false; -} -template -constexpr bool operator!=(const expected &x, const U &v) { - return x.has_value() ? *x != v : true; -} -template -constexpr bool operator!=(const U &v, const expected &x) { - return x.has_value() ? *x != v : true; -} - -template -constexpr bool operator==(const expected &x, const unexpected &e) { - return x.has_value() ? false : x.error() == e.value(); -} -template -constexpr bool operator==(const unexpected &e, const expected &x) { - return x.has_value() ? false : x.error() == e.value(); -} -template -constexpr bool operator!=(const expected &x, const unexpected &e) { - return x.has_value() ? true : x.error() != e.value(); -} -template -constexpr bool operator!=(const unexpected &e, const expected &x) { - return x.has_value() ? true : x.error() != e.value(); -} - -template ::value || - std::is_move_constructible::value) && - detail::is_swappable::value && - std::is_move_constructible::value && - detail::is_swappable::value> * = nullptr> -void swap(expected &lhs, - expected &rhs) noexcept(noexcept(lhs.swap(rhs))) { - lhs.swap(rhs); -} -} // namespace tl - -#endif diff --git a/uniffi/cpp/bindgen/src/bindings/mod.rs b/uniffi/cpp/bindgen/src/bindings/mod.rs deleted file mode 100644 index 989fe15a0..000000000 --- a/uniffi/cpp/bindgen/src/bindings/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub(crate) mod c; -pub(crate) mod cpp; diff --git a/uniffi/cpp/bindgen/src/main.rs b/uniffi/cpp/bindgen/src/main.rs deleted file mode 100644 index 342f2ab85..000000000 --- a/uniffi/cpp/bindgen/src/main.rs +++ /dev/null @@ -1,74 +0,0 @@ -mod bindings; - -use anyhow::Context; -use camino::Utf8PathBuf; -use clap::{Parser, ValueEnum}; -use uniffi_bindgen::BindingGenerator; - -use bindings::{c::CBindingGenerator, cpp::CppBindingGenerator}; - -/// The language of the generated bindings. -#[derive(Clone, Copy, Debug, ValueEnum)] -enum Lang { - Cpp, - /// A C header and its C++ implementation, built on the C++ bindings. - C, -} - -#[derive(Parser)] -struct Args { - #[clap(long, short)] - config: Option, - #[clap(long, short)] - out_dir: Option, - #[clap(long)] - lib_file: Option, - #[clap(long = "library", conflicts_with = "lib_file", requires = "out_dir")] - library_mode: bool, - #[clap(long = "crate")] - crate_name: Option, - #[clap(long, value_enum, default_value_t = Lang::Cpp)] - lang: Lang, - source: Utf8PathBuf, -} - -fn main() { - let args = Args::parse(); - - match args.lang { - Lang::Cpp => generate(&CppBindingGenerator, args), - Lang::C => generate(&CBindingGenerator, args), - } -} - -fn generate(generator: &impl BindingGenerator, args: Args) { - if args.library_mode { - let config_supplier = - uniffi_bindgen::cargo_metadata::CrateConfigSupplier::from_cargo_metadata_command(false) - .unwrap(); - - uniffi_bindgen::library_mode::generate_bindings( - &args.source, - args.crate_name, - generator, - &config_supplier, - args.config.as_deref(), - &args.out_dir.unwrap(), - false, - ) - .context("Failed to generate bindings using library mode") - .unwrap(); - } else { - uniffi_bindgen::generate_external_bindings( - generator, - args.source, - args.config.as_deref(), - args.out_dir, - args.lib_file, - args.crate_name.as_deref(), - false, - ) - .context("Failed to generate external bindings") - .unwrap(); - } -} diff --git a/uniffi/cpp/cpp-tests/CMakeLists.txt b/uniffi/cpp/cpp-tests/CMakeLists.txt deleted file mode 100644 index 68a909533..000000000 --- a/uniffi/cpp/cpp-tests/CMakeLists.txt +++ /dev/null @@ -1,303 +0,0 @@ -cmake_minimum_required(VERSION 3.10) -project(binding-tests VERSION 1.0.0 LANGUAGES C CXX) -# The bindings promise C++17; a cache entry so CI can also build at a newer standard. -set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard") -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -# The C backend's header promises C11. -set(CMAKE_C_STANDARD 11) -set(CMAKE_C_STANDARD_REQUIRED ON) -set(CMAKE_C_EXTENSIONS OFF) - -if (MSVC) - add_compile_options(/permissive-) -else() - add_compile_options(-pedantic-errors) -endif() -# Generated files must end with a newline; consumers build with this as an error. CI picks -# only the C++ compiler, so the C one can be GCC, which lacks the flag. -if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options($<$:-Werror=newline-eof>) -endif() -if (CMAKE_C_COMPILER_ID MATCHES "Clang") - add_compile_options($<$:-Werror=newline-eof>) -endif() - -include(CTest) -enable_testing() - -find_package(Threads REQUIRED) - -# The fixtures build in the repository's root workspace, whose target directory is at its root. -set(BINDINGS_BUILD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../target/debug CACHE PATH "Cargo output directory") -set(BINDINGS_SRC_DIR ${BINDINGS_BUILD_DIR}/bindings) - -if (WIN32) - set(UNIFFI_FIXTURES_LIB uniffi_bindgen_cpp_fixtures.dll) - set(ADDITIONAL_LIBS ws2_32 userenv advapi32 ntdll crypt32 Bcrypt) -elseif(UNIX AND NOT APPLE) - set(UNIFFI_FIXTURES_LIB libuniffi_bindgen_cpp_fixtures.so) - set(ADDITIONAL_LIBS) -else() - set(UNIFFI_FIXTURES_LIB libuniffi_bindgen_cpp_fixtures.dylib) - set(ADDITIONAL_LIBS) -endif() - -find_program(VALGRIND "valgrind") -macro(memcheck_test TEST_NAME) -if (VALGRIND) - add_test(NAME ${TEST_NAME}-test-memcheck - COMMAND valgrind - --error-exitcode=1 - --tool=memcheck - --leak-check=full - --errors-for-leak-kinds=definite - --show-leak-kinds=definite $) -endif() -endmacro(memcheck_test) - -# Add a bindings test case -macro(test_case TEST_NAME) -add_executable(${TEST_NAME}-test tests/${TEST_NAME}/main.cpp ${BINDINGS_SRC_DIR}/${TEST_NAME}.cpp) - -target_include_directories(${TEST_NAME}-test PRIVATE ${BINDINGS_SRC_DIR} include) -target_link_directories(${TEST_NAME}-test PRIVATE ${BINDINGS_BUILD_DIR}) -target_link_libraries(${TEST_NAME}-test uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) -target_compile_definitions(${TEST_NAME}-test PRIVATE UNIFFI_BINDING_DIR="${BINDINGS_SRC_DIR}") - -add_test(NAME ${TEST_NAME}-test COMMAND ${TEST_NAME}-test) -memcheck_test(${TEST_NAME}-test) - -add_dependencies(${TEST_NAME}-test bindings) - -list(APPEND BINDING_FILES ${BINDINGS_SRC_DIR}/${TEST_NAME}.cpp) - -endmacro(test_case) - -test_case(arithmetic) -test_case(callbacks) -test_case(fixture_callbacks) -test_case(chronological) -test_case(custom_types) -test_case(geometry) -test_case(rondpoint) -test_case(sprites) -test_case(todolist) -test_case(traits) -test_case(uniffi_docstring) -test_case(trait_methods) -test_case(custom_types_builtin) -test_case(enum_style_test) -test_case(empty_type) -test_case(error_types_builtin) -test_case(reserved_field_name) -test_case(type_flattening) - -add_executable(ext_types_import-test - tests/ext_types_import/main.cpp - ${BINDINGS_SRC_DIR}/ext_types_export.cpp - ${BINDINGS_SRC_DIR}/ext_types_import.cpp) -target_include_directories(ext_types_import-test PRIVATE ${BINDINGS_SRC_DIR} include) -target_link_directories(ext_types_import-test PRIVATE ${BINDINGS_BUILD_DIR}) -target_link_libraries(ext_types_import-test uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) -add_test(NAME ext_types_import-test COMMAND ext_types_import-test) -memcheck_test(ext_types_import-test) -add_dependencies(ext_types_import-test bindings) -list(APPEND BINDING_FILES - ${BINDINGS_SRC_DIR}/ext_types_export.cpp - ${BINDINGS_SRC_DIR}/ext_types_import.cpp) - -# `error_style = "expected"` bindings, built the way Unreal builds: no exceptions, no RTTI. -set(EXPECTED_BINDINGS_DIR ${BINDINGS_BUILD_DIR}/bindings-expected) -add_executable(expected-test - tests/expected/main.cpp - ${EXPECTED_BINDINGS_DIR}/futures.cpp - ${EXPECTED_BINDINGS_DIR}/error_types_builtin.cpp - ${EXPECTED_BINDINGS_DIR}/trait_methods.cpp - ${EXPECTED_BINDINGS_DIR}/capi.cpp) -target_include_directories(expected-test PRIVATE ${EXPECTED_BINDINGS_DIR}) -target_link_directories(expected-test PRIVATE ${BINDINGS_BUILD_DIR}) -target_link_libraries(expected-test uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) -if (MSVC) - target_compile_options(expected-test PRIVATE /EHs-c- /GR-) - target_compile_definitions(expected-test PRIVATE _HAS_EXCEPTIONS=0) -else() - target_compile_options(expected-test PRIVATE -fno-exceptions -fno-rtti) -endif() -add_dependencies(expected-test bindings-expected) -add_test(NAME expected-test COMMAND expected-test) -set_tests_properties(expected-test PROPERTIES TIMEOUT 30) -memcheck_test(expected-test) -# Reading the value of an error aborts with a message, rather than being undefined. -add_test(NAME expected-value-on-error-test COMMAND expected-test value-on-error) -set_tests_properties(expected-value-on-error-test PROPERTIES - TIMEOUT 30 - PASS_REGULAR_EXPRESSION "uniffi: expected::value\\(\\) called on an error") -list(APPEND EXPECTED_BINDING_FILES - ${EXPECTED_BINDINGS_DIR}/futures.cpp - ${EXPECTED_BINDINGS_DIR}/error_types_builtin.cpp - ${EXPECTED_BINDINGS_DIR}/trait_methods.cpp - ${EXPECTED_BINDINGS_DIR}/capi.cpp) - -add_executable(async-dispatcher-test - tests/async_dispatcher/main.cpp - ${EXPECTED_BINDINGS_DIR}/futures.cpp) -target_include_directories(async-dispatcher-test PRIVATE ${EXPECTED_BINDINGS_DIR} include) -target_link_directories(async-dispatcher-test PRIVATE ${BINDINGS_BUILD_DIR}) -target_link_libraries(async-dispatcher-test - uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) -add_dependencies(async-dispatcher-test bindings-expected) - -foreach(SCENARIO IN ITEMS inline rejection lifetime) - add_test(NAME async-dispatcher-${SCENARIO}-test - COMMAND async-dispatcher-test ${SCENARIO}) - set_tests_properties(async-dispatcher-${SCENARIO}-test PROPERTIES TIMEOUT 15) -endforeach() - -# Two crates that share their type names, one using the other's. -add_executable(namespaces-test - tests/namespaces/main.cpp - ${EXPECTED_BINDINGS_DIR}/net.cpp - ${EXPECTED_BINDINGS_DIR}/media.cpp) -target_include_directories(namespaces-test PRIVATE ${EXPECTED_BINDINGS_DIR} include) -target_link_directories(namespaces-test PRIVATE ${BINDINGS_BUILD_DIR}) -target_link_libraries(namespaces-test uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) -add_test(NAME namespaces-test COMMAND namespaces-test) -memcheck_test(namespaces-test) -add_dependencies(namespaces-test bindings-expected) -list(APPEND EXPECTED_BINDING_FILES - ${EXPECTED_BINDINGS_DIR}/net.cpp - ${EXPECTED_BINDINGS_DIR}/media.cpp) - -# `strip_type_prefix` refuses to rename a type onto one that already exists. -add_test(NAME strip-type-prefix-collision-test - COMMAND ${BINDINGS_BUILD_DIR}/uniffi-bindgen-cpp${CMAKE_EXECUTABLE_SUFFIX} - --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_cpp_error_types_builtin - --config ${CMAKE_CURRENT_SOURCE_DIR}/collision.toml - --out-dir ${CMAKE_CURRENT_BINARY_DIR}/collision - WORKING_DIRECTORY ${BINDINGS_BUILD_DIR}) -set_tests_properties(strip-type-prefix-collision-test PROPERTIES - PASS_REGULAR_EXPRESSION "renames `Flat[A-Za-z]+` to `[A-Za-z]+`, which is already a type") - -# Async needs the expected style; the default exceptions style refuses it. -add_test(NAME exceptions-refuse-async-test - COMMAND ${BINDINGS_BUILD_DIR}/uniffi-bindgen-cpp${CMAKE_EXECUTABLE_SUFFIX} - --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_namespaces_media - --out-dir ${CMAKE_CURRENT_BINARY_DIR}/exceptions-refused - WORKING_DIRECTORY ${BINDINGS_BUILD_DIR}) -set_tests_properties(exceptions-refuse-async-test PROPERTIES - PASS_REGULAR_EXPRESSION "async needs error_style = \"expected\", but `GroupConsumer::next_frame` is async") - -# The C backend: a C11 header over expected-style C++ bindings, built without exceptions. -set(C_BINDINGS_DIR ${BINDINGS_BUILD_DIR}/bindings-c) -set(C_BINDING_FILES ${C_BINDINGS_DIR}/capi.cpp ${C_BINDINGS_DIR}/capi_c.cpp) -# A crate's C API needs the C and C++ files of every crate whose types it uses. -set(C_NAMESPACES_BINDING_FILES - ${C_BINDINGS_DIR}/net.cpp ${C_BINDINGS_DIR}/net_c.cpp - ${C_BINDINGS_DIR}/media.cpp ${C_BINDINGS_DIR}/media_c.cpp) -# The arguments after the test name are the generated files it compiles. -macro(c_test_case TEST_NAME) -add_executable(${TEST_NAME}-test - tests/${TEST_NAME}/main.c - tests/c_support/support.cpp - ${ARGN}) -target_include_directories(${TEST_NAME}-test PRIVATE ${C_BINDINGS_DIR} include) -target_link_directories(${TEST_NAME}-test PRIVATE ${BINDINGS_BUILD_DIR}) -target_link_libraries(${TEST_NAME}-test uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) -if (MSVC) - target_compile_options(${TEST_NAME}-test PRIVATE $<$:/EHs-c- /GR->) - target_compile_definitions(${TEST_NAME}-test PRIVATE $<$:_HAS_EXCEPTIONS=0>) -else() - target_compile_options(${TEST_NAME}-test PRIVATE - $<$:-Wall -Wextra -Werror> - $<$:-fno-exceptions -fno-rtti>) -endif() -add_dependencies(${TEST_NAME}-test bindings-c) -add_test(NAME ${TEST_NAME}-test COMMAND ${TEST_NAME}-test) -set_tests_properties(${TEST_NAME}-test PROPERTIES TIMEOUT 30) -memcheck_test(${TEST_NAME}-test) -endmacro(c_test_case) - -c_test_case(c_api ${C_BINDING_FILES}) -c_test_case(c_dispatcher ${C_BINDING_FILES}) -c_test_case(c_namespaces ${C_NAMESPACES_BINDING_FILES}) - -# The C backend refuses what it cannot render instead of emitting half of it. -add_test(NAME c-refuses-callbacks-test - COMMAND ${BINDINGS_BUILD_DIR}/uniffi-bindgen-cpp${CMAKE_EXECUTABLE_SUFFIX} - --lang c --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_callbacks - --out-dir ${CMAKE_CURRENT_BINARY_DIR}/c-refused - WORKING_DIRECTORY ${BINDINGS_BUILD_DIR}) -set_tests_properties(c-refuses-callbacks-test PROPERTIES - PASS_REGULAR_EXPRESSION "the C backend does not support callback interfaces") - -# Special multilib test that only needs to compile to check for potential symbol clashes -add_executable(multilib-test - tests/multilib/main.cpp - ${BINDINGS_SRC_DIR}/arithmetic.cpp - ${BINDINGS_SRC_DIR}/geometry.cpp - ${BINDINGS_SRC_DIR}/sprites.cpp -) -target_include_directories(multilib-test PRIVATE ${BINDINGS_SRC_DIR} include) -target_link_directories(multilib-test PRIVATE ${BINDINGS_BUILD_DIR}) -target_link_libraries(multilib-test uniffi_bindgen_cpp_fixtures Threads::Threads ${ADDITIONAL_LIBS}) -add_dependencies(multilib-test bindings) - -add_custom_target(libs ALL - BYPRODUCTS ${BINDING_FILES} - COMMAND cargo build --package uniffi-bindgen-cpp --package uniffi-bindgen-cpp-fixtures - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../ - COMMENT "Generating libs" -) - -# Async needs the expected style, so the default style generates only crates without it. -set(EXCEPTIONS_CRATES - arithmetical custom_types uniffi_callbacks uniffi_chronological uniffi_cpp_custom_types_builtin - uniffi_cpp_error_types_builtin uniffi_empty_type uniffi_enum_style_test uniffi_ext_types_export - uniffi_ext_types_import uniffi_fixture_callbacks uniffi_fixture_docstring uniffi_geometry - uniffi_reserved_field_name uniffi_rondpoint uniffi_sprites uniffi_todolist uniffi_trait_methods - uniffi_traits uniffi_type_flattening) -set(EXCEPTIONS_COMMANDS) -foreach(CRATE IN LISTS EXCEPTIONS_CRATES) - list(APPEND EXCEPTIONS_COMMANDS - COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate ${CRATE} --out-dir bindings) -endforeach() -add_custom_target(bindings ALL - DEPENDS libs - ${EXCEPTIONS_COMMANDS} - WORKING_DIRECTORY ${BINDINGS_BUILD_DIR} - COMMENT "Generating bindings" -) - -add_custom_target(bindings-c ALL - DEPENDS libs - BYPRODUCTS ${C_BINDING_FILES} ${C_NAMESPACES_BINDING_FILES} - COMMAND ./uniffi-bindgen-cpp --lang c --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_c_api - --out-dir bindings-c - COMMAND ./uniffi-bindgen-cpp --lang c --library ${UNIFFI_FIXTURES_LIB} - --crate uniffi_namespaces_net --out-dir bindings-c - COMMAND ./uniffi-bindgen-cpp --lang c --library ${UNIFFI_FIXTURES_LIB} - --crate uniffi_namespaces_media --out-dir bindings-c - WORKING_DIRECTORY ${BINDINGS_BUILD_DIR} - COMMENT "Generating C bindings" -) - -# The expected style refuses callback interfaces, so only generate crates without them. -add_custom_target(bindings-expected ALL - DEPENDS libs - BYPRODUCTS ${EXPECTED_BINDING_FILES} - COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_fixture_async_calls - --config ${CMAKE_CURRENT_SOURCE_DIR}/expected.toml --out-dir bindings-expected - COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_cpp_error_types_builtin - --config ${CMAKE_CURRENT_SOURCE_DIR}/expected.toml --out-dir bindings-expected - COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_trait_methods - --config ${CMAKE_CURRENT_SOURCE_DIR}/expected.toml --out-dir bindings-expected - COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_c_api - --config ${CMAKE_CURRENT_SOURCE_DIR}/renamed.toml --out-dir bindings-expected - COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_namespaces_net - --config ${CMAKE_CURRENT_SOURCE_DIR}/expected.toml --out-dir bindings-expected - COMMAND ./uniffi-bindgen-cpp --library ${UNIFFI_FIXTURES_LIB} --crate uniffi_namespaces_media - --config ${CMAKE_CURRENT_SOURCE_DIR}/expected.toml --out-dir bindings-expected - WORKING_DIRECTORY ${BINDINGS_BUILD_DIR} - COMMENT "Generating expected-style bindings" -) diff --git a/uniffi/cpp/cpp-tests/collision.toml b/uniffi/cpp/cpp-tests/collision.toml deleted file mode 100644 index ccf2a892d..000000000 --- a/uniffi/cpp/cpp-tests/collision.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.cpp] -strip_type_prefix = "Flat" diff --git a/uniffi/cpp/cpp-tests/expected.toml b/uniffi/cpp/cpp-tests/expected.toml deleted file mode 100644 index a8ad3f5db..000000000 --- a/uniffi/cpp/cpp-tests/expected.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.cpp] -error_style = "expected" diff --git a/uniffi/cpp/cpp-tests/include/c_test_support.h b/uniffi/cpp/cpp-tests/include/c_test_support.h deleted file mode 100644 index ba0798440..000000000 --- a/uniffi/cpp/cpp-tests/include/c_test_support.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Helpers for the C API tests: an always-on CHECK and a latch, since C11 threads are optional. */ -#ifndef C_TEST_SUPPORT_H -#define C_TEST_SUPPORT_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Unlike assert, also checks in Release builds. */ -#define CHECK(cond) \ - do { \ - if (!(cond)) { \ - fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #cond); \ - abort(); \ - } \ - } while (0) - -/* Counts signals; each wait consumes one, blocking until it arrives. */ -typedef struct test_latch test_latch; - -test_latch *test_latch_new(void); -void test_latch_signal(test_latch *latch); -void test_latch_wait(test_latch *latch); -void test_latch_free(test_latch *latch); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/uniffi/cpp/cpp-tests/include/custom_string.hpp b/uniffi/cpp/cpp-tests/include/custom_string.hpp deleted file mode 100644 index 6e563567f..000000000 --- a/uniffi/cpp/cpp-tests/include/custom_string.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -struct CustomString { - std::string string; - - CustomString(const std::string &string): string(string) { } - - std::string to_string() const { - return this->string; - } -}; diff --git a/uniffi/cpp/cpp-tests/include/test_common.hpp b/uniffi/cpp/cpp-tests/include/test_common.hpp deleted file mode 100644 index c92b56553..000000000 --- a/uniffi/cpp/cpp-tests/include/test_common.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#include -#include -#include -#include - -#define ASSERT_EQ(a, b) assert((a) == (b)) -#define ASSERT_NE(a, b) assert((a) != (b)) -#define ASSERT_TRUE(a) assert((a)) -#define ASSERT_FALSE(a) assert(!(a)) - -#define EXPECT_EXCEPTION(expr, exception) \ - try { \ - expr; \ - assert(false && "Didn't throw an exception"); \ - } catch (exception const &) { \ - } catch (...) { \ - assert(false && "Exception didn't match" #exception); \ - } diff --git a/uniffi/cpp/cpp-tests/renamed.toml b/uniffi/cpp/cpp-tests/renamed.toml deleted file mode 100644 index 8caf688a1..000000000 --- a/uniffi/cpp/cpp-tests/renamed.toml +++ /dev/null @@ -1,3 +0,0 @@ -[bindings.cpp] -error_style = "expected" -strip_type_prefix = "Capi" diff --git a/uniffi/cpp/cpp-tests/tests/arithmetic/main.cpp b/uniffi/cpp/cpp-tests/tests/arithmetic/main.cpp deleted file mode 100644 index 6663d7409..000000000 --- a/uniffi/cpp/cpp-tests/tests/arithmetic/main.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include - -#include - -int main() { - EXPECT_EXCEPTION(arithmetic::add(18446744073709551615ul, 1), arithmetic::arithmetic_error::IntegerOverflow); - - ASSERT_EQ(arithmetic::add(2, 4), 6ul); - ASSERT_EQ(arithmetic::add(4, 8), 12ul); - - ASSERT_EQ(2ul, arithmetic::sub(4, 2)); - ASSERT_EQ(4ul, arithmetic::sub(8, 4)); - - EXPECT_EXCEPTION(arithmetic::sub(2, 4), arithmetic::arithmetic_error::IntegerOverflow); - - ASSERT_EQ(4ul, arithmetic::div(8, 2)); - - EXPECT_EXCEPTION(arithmetic::div(8, 0), std::runtime_error); - - ASSERT_TRUE(arithmetic::equal(2, 2)); - ASSERT_TRUE(arithmetic::equal(4, 4)); - - ASSERT_FALSE(arithmetic::equal(2, 4)); - ASSERT_FALSE(arithmetic::equal(4, 8)); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/async_dispatcher/main.cpp b/uniffi/cpp/cpp-tests/tests/async_dispatcher/main.cpp deleted file mode 100644 index dc22e0076..000000000 --- a/uniffi/cpp/cpp-tests/tests/async_dispatcher/main.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include - -#include - -#include -#include -#include - -namespace { - -struct ExecutorState { - explicit ExecutorState(std::shared_ptr> destroyed): - destroyed(std::move(destroyed)) {} - - ~ExecutorState() { - destroyed->store(true); - } - - std::shared_ptr> destroyed; - std::atomic dispatch_count = 0; -}; - -void test_inline_reentrant_dispatch() { - auto state = std::make_shared(std::make_shared>(false)); - uniffi::set_async_dispatcher( - [state](uniffi::AsyncTask task) { - state->dispatch_count.fetch_add(1); - task(); - return true; - }, - [] {} - ); - - bool nested_ran = false; - ASSERT_TRUE(uniffi::detail::dispatch_async([&nested_ran] { - ASSERT_TRUE(uniffi::detail::dispatch_async([&nested_ran] { nested_ran = true; })); - })); - ASSERT_TRUE(nested_ran); - ASSERT_EQ(2, state->dispatch_count.load()); - uniffi::shutdown_async_dispatcher(); -} - -void test_rejected_dispatch() { - auto shutdown_count = std::make_shared>(0); - uniffi::set_async_dispatcher( - [](uniffi::AsyncTask) { return false; }, - [shutdown_count] { shutdown_count->fetch_add(1); } - ); - - ASSERT_FALSE(uniffi::detail::dispatch_async([] {})); - uniffi::shutdown_async_dispatcher(); - uniffi::shutdown_async_dispatcher(); - ASSERT_EQ(1, shutdown_count->load()); -} - -void test_dispatcher_lifetime() { - auto destroyed = std::make_shared>(false); - auto state = std::make_shared(destroyed); - std::weak_ptr weak_state = state; - uniffi::set_async_dispatcher( - [state](uniffi::AsyncTask task) { - state->dispatch_count.fetch_add(1); - task(); - return true; - }, - [state] {} - ); - state.reset(); - - ASSERT_TRUE(futures::always_ready().get()); - ASSERT_FALSE(weak_state.expired()); - uniffi::shutdown_async_dispatcher(); - ASSERT_TRUE(weak_state.expired()); - ASSERT_TRUE(destroyed->load()); -} - -} // namespace - -int main(int argc, char **argv) { - ASSERT_EQ(2, argc); - const std::string scenario(argv[1]); - if (scenario == "inline") { - test_inline_reentrant_dispatch(); - } else if (scenario == "rejection") { - test_rejected_dispatch(); - } else if (scenario == "lifetime") { - test_dispatcher_lifetime(); - } else { - ASSERT_TRUE(false && "unknown async dispatcher scenario"); - } - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/c_api/main.c b/uniffi/cpp/cpp-tests/tests/c_api/main.c deleted file mode 100644 index 37a79c874..000000000 --- a/uniffi/cpp/cpp-tests/tests/c_api/main.c +++ /dev/null @@ -1,503 +0,0 @@ -/* The generated C API on the default dispatcher thread. */ -#include - -#include - -#include - -static int streq(const char *a, const char *b) { - return a && b && strcmp(a, b) == 0; -} - -/* The value a map holds for `key`, or NULL. */ -static const char *lookup(const CapiStringStringMap *map, const char *key) { - size_t i; - for (i = 0; i < map->len; i++) { - if (streq(map->keys[i], key)) { - return map->values[i]; - } - } - return NULL; -} - -static void defaults(void) { - CapiItem item = capi_item_default(); - CHECK(item.name == NULL); - CHECK(item.count == 7); - CHECK(streq(item.title, "untitled \"draft\"")); - CHECK(item.scale == 1.5); - CHECK(item.visible); - CHECK(item.offset == -3); - CHECK(item.note == NULL); - CHECK(!item.limit.has_value); - CHECK(!item.tint.has_value); - CHECK(item.target == NULL); - CHECK(item.extra == NULL); - CHECK(item.owner == NULL); - CHECK(item.tags.len == 0 && item.tags.data == NULL); -} - -/* Every field kind survives a round trip through Rust. */ -static void records(void) { - static const uint8_t payload[] = {1, 2, 3}; - static const uint8_t extra_data[] = {9}; - const char *tags[] = {"a", "b"}; - const char *label_keys[] = {"k1", "k2"}; - const char *label_values[] = {"v1", "v2"}; - const char *point_keys[] = {"p"}; - const CapiPoint point_values[] = {{5, 6}}; - const uint64_t values[] = {10, 20, 30}; - CapiOptionalU32 maybes[2]; - CapiPoint path[2]; - CapiPoint target; - CapiBytes extra; - CapiStore *owner = capi_store_new("owner"); - CapiItem item = capi_item_default(); - CapiItem *echo; - CapiStringStringMap labels; - char *owner_name; - - maybes[0].has_value = true; - maybes[0].value = 4; - maybes[1].has_value = false; - maybes[1].value = 0; - path[0].x = 1; - path[0].y = 1; - path[1].x = 2; - path[1].y = 2; - target.x = 7; - target.y = 8; - extra.data = extra_data; - extra.len = 1; - - item.name = "first"; - item.note = "a note"; - item.limit.has_value = true; - item.limit.value = 99; - item.tint.has_value = true; - item.tint.value = CAPI_COLOR_BLUE; - item.target = ⌖ - item.extra = &extra; - item.owner = owner; - item.tags.data = tags; - item.tags.len = 2; - item.payload.data = payload; - item.payload.len = 3; - item.origin.x = -1; - item.origin.y = -2; - item.color = CAPI_COLOR_GREEN; - item.shape.tag = CAPI_SHAPE_PATH; - item.shape.path.points.data = path; - item.shape.path.points.len = 2; - item.labels.keys = label_keys; - item.labels.values = label_values; - item.labels.len = 2; - item.points.keys = point_keys; - item.points.values = point_values; - item.points.len = 1; - item.values.data = values; - item.values.len = 3; - item.maybes.data = maybes; - item.maybes.len = 2; - - echo = capi_echo(&item); - CHECK(echo != NULL); - CHECK(streq(echo->name, "first")); - CHECK(echo->count == 7); - CHECK(streq(echo->title, "untitled \"draft\"")); - CHECK(echo->scale == 1.5); - CHECK(echo->visible); - CHECK(echo->offset == -3); - CHECK(streq(echo->note, "a note")); - CHECK(echo->limit.has_value && echo->limit.value == 99); - CHECK(echo->tint.has_value && echo->tint.value == CAPI_COLOR_BLUE); - CHECK(echo->target && echo->target->x == 7 && echo->target->y == 8); - CHECK(echo->extra && echo->extra->len == 1 && echo->extra->data[0] == 9); - CHECK(echo->tags.len == 2 && streq(echo->tags.data[0], "a") && streq(echo->tags.data[1], "b")); - CHECK(echo->payload.len == 3 && memcmp(echo->payload.data, payload, 3) == 0); - CHECK(echo->origin.x == -1 && echo->origin.y == -2); - CHECK(echo->color == CAPI_COLOR_GREEN); - CHECK(echo->shape.tag == CAPI_SHAPE_PATH); - CHECK(echo->shape.path.points.len == 2); - CHECK(echo->shape.path.points.data[1].x == 2); - labels = echo->labels; - CHECK(labels.len == 2); - CHECK(streq(lookup(&labels, "k1"), "v1")); - CHECK(streq(lookup(&labels, "k2"), "v2")); - CHECK(echo->points.len == 1 && streq(echo->points.keys[0], "p")); - CHECK(echo->points.values[0].x == 5 && echo->points.values[0].y == 6); - CHECK(echo->values.len == 3 && echo->values.data[2] == 30); - CHECK(echo->maybes.len == 2); - CHECK(echo->maybes.data[0].has_value && echo->maybes.data[0].value == 4); - CHECK(!echo->maybes.data[1].has_value); - - /* The echoed record owns a new handle to the same store. */ - CHECK(echo->owner != NULL && echo->owner != owner); - owner_name = capi_store_name(echo->owner); - CHECK(streq(owner_name, "owner")); - capi_string_free(owner_name); - - capi_item_free(echo); - capi_store_free(owner); - - /* Empty optionals and collections round-trip as empty. */ - item = capi_item_default(); - item.name = "empty"; - echo = capi_echo(&item); - CHECK(echo->note == NULL && echo->target == NULL && echo->extra == NULL); - CHECK(echo->owner == NULL && !echo->limit.has_value); - CHECK(echo->payload.len == 0 && echo->payload.data == NULL); - CHECK(echo->shape.tag == CAPI_SHAPE_DOT); - CHECK(echo->labels.len == 0 && echo->labels.keys == NULL); - capi_item_free(echo); - - capi_item_free(NULL); -} - -static void enums(void) { - CapiShape *shape = capi_make_shape(0); - CHECK(shape->tag == CAPI_SHAPE_DOT); - capi_shape_free(shape); - - shape = capi_make_shape(1); - CHECK(shape->tag == CAPI_SHAPE_CIRCLE && shape->circle.radius == 2.5); - capi_shape_free(shape); - - shape = capi_make_shape(2); - CHECK(shape->tag == CAPI_SHAPE_LABEL && streq(shape->label.v1, "two")); - capi_shape_free(shape); - - shape = capi_make_shape(3); - CHECK(shape->tag == CAPI_SHAPE_PATH && shape->path.points.len == 3); - CHECK(shape->path.points.data[2].x == 2 && shape->path.points.data[2].y == -2); - capi_shape_free(shape); -} - -static void scalars(void) { - static const uint8_t data[] = {1, 2, 3}; - CapiBytes payload; - CapiOptionalU64 value; - CapiOptionalColor color; - CapiPoint point; - char *text; - - payload.data = data; - payload.len = 3; - CHECK(capi_checksum(&payload) == 6); - payload.data = NULL; - payload.len = 0; - CHECK(capi_checksum(&payload) == 0); - - value.has_value = false; - value.value = 0; - color.has_value = false; - color.value = CAPI_COLOR_RED; - text = capi_describe(value, color, NULL, NULL, NULL); - CHECK(streq(text, "None None None None None")); - capi_string_free(text); - - value.has_value = true; - value.value = 3; - color.has_value = true; - color.value = CAPI_COLOR_BLUE; - point.x = 1; - point.y = 2; - payload.data = data; - payload.len = 2; - text = capi_describe(value, color, "hi", &point, &payload); - CHECK(streq(text, "Some(3) Some(Blue) Some(\"hi\") Some(CapiPoint { x: 1, y: 2 }) Some([1, 2])")); - capi_string_free(text); -} - -static void errors(void) { - CapiError *error; - CapiFlatError *flat; - - CHECK(capi_fail(0) == NULL); - - error = capi_fail(1); - CHECK(error && error->tag == CAPI_ERROR_NOT_FOUND); - CHECK(streq(capi_error_message(error), "not found")); - capi_error_free(error); - - error = capi_fail(2); - CHECK(error && error->tag == CAPI_ERROR_INVALID); - CHECK(streq(error->invalid.v1, "two")); - CHECK(streq(capi_error_message(error), "invalid: two")); - capi_error_free(error); - - error = capi_fail(9); - CHECK(error && error->tag == CAPI_ERROR_CODE); - CHECK(error->code.code == 9); - CHECK(error->code.at.x == 3 && error->code.at.y == 4); - CHECK(streq(capi_error_message(error), "code 9 at 3,4")); - capi_error_free(error); - - flat = capi_flat_fail(false); - CHECK(flat && flat->tag == CAPI_FLAT_ERROR_BUSY); - CHECK(streq(capi_flat_error_message(flat), "busy: later")); - capi_flat_error_free(flat); - - flat = capi_flat_fail(true); - CHECK(flat && flat->tag == CAPI_FLAT_ERROR_GONE); - CHECK(streq(capi_flat_error_message(flat), "gone")); - capi_flat_error_free(flat); - - capi_error_free(NULL); -} - -static void objects(void) { - CapiStore *store = NULL; - CapiStore *fork; - CapiStore *renamed; - CapiStore *filled; - CapiError *error; - CapiItem item; - CapiItem items[2]; - CapiItemList list; - CapiItem *got = NULL; - CapiStringList *names; - CapiStoreStats *stats; - CapiOptionalU64 limit; - uint32_t index; - char *text; - - error = capi_store_open("", &store); - CHECK(error && error->tag == CAPI_ERROR_INVALID && store == NULL); - capi_error_free(error); - - CHECK(capi_store_open("main", &store) == NULL && store != NULL); - CHECK(capi_store_len(store) == 0); - - item = capi_item_default(); - item.name = "one"; - item.note = "n1"; - item.limit.has_value = true; - item.limit.value = 5; - index = 99; - CHECK(capi_store_add(store, &item, &index) == NULL && index == 0); - - /* A failed call clears its out-param. */ - item.name = ""; - index = 99; - error = capi_store_add(store, &item, &index); - CHECK(error && error->tag == CAPI_ERROR_INVALID && index == 0); - capi_error_free(error); - - item.name = "two"; - item.note = NULL; - item.limit.has_value = false; - CHECK(capi_store_add(store, &item, &index) == NULL && index == 1); - CHECK(capi_store_len(store) == 2); - - CHECK(capi_store_get(store, 1, &got) == NULL); - CHECK(streq(got->name, "two") && got->note == NULL); - capi_item_free(got); - - error = capi_store_get(store, 5, &got); - CHECK(error && error->tag == CAPI_ERROR_CODE && error->code.code == 5 && got == NULL); - capi_error_free(error); - - got = capi_store_find(store, "one"); - CHECK(got && got->count == 7); - capi_item_free(got); - CHECK(capi_store_find(store, "nope") == NULL); - - text = capi_store_note(store, 0); - CHECK(streq(text, "n1")); - capi_string_free(text); - CHECK(capi_store_note(store, 1) == NULL); - - limit = capi_store_limit(store, 0); - CHECK(limit.has_value && limit.value == 5); - limit = capi_store_limit(store, 1); - CHECK(!limit.has_value); - - names = capi_store_names(store); - CHECK(names->len == 2 && streq(names->data[0], "one") && streq(names->data[1], "two")); - capi_string_list_free(names); - - fork = capi_store_fork(store, NULL); - text = capi_store_name(fork); - CHECK(streq(text, "main")); - capi_string_free(text); - renamed = capi_store_fork(store, "other"); - text = capi_store_name(renamed); - CHECK(streq(text, "other")); - capi_string_free(text); - - CHECK(capi_store_total(store, fork, NULL) == 4); - CHECK(capi_store_total(store, fork, renamed) == 6); - - /* The method and the record it returns differ only in case. */ - stats = capi_store_stats(store); - CHECK(stats->items == 2 && stats->queued == 0); - capi_store_stats_free(stats); - - capi_store_clear(store); - CHECK(capi_store_len(store) == 0 && capi_store_len(fork) == 2); - - items[0] = capi_item_default(); - items[0].name = "x"; - items[1] = capi_item_default(); - items[1].name = "y"; - list.data = items; - list.len = 2; - filled = capi_store_with_items("filled", &list); - CHECK(capi_store_len(filled) == 2); - - capi_store_free(filled); - capi_store_free(renamed); - capi_store_free(fork); - capi_store_free(store); - capi_store_free(NULL); -} - -typedef struct { - test_latch *done; - CapiError *error; - uint64_t value; - char *text; - int calls; - int cancels; - /* For the free-while-running test. */ - test_latch *entered; - test_latch *release; -} result; - -static void on_sum(void *user_data, bool cancelled, uint64_t value) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; - r->value = value; - test_latch_signal(r->done); -} - -static void on_greet(void *user_data, bool cancelled, CapiError *error, char *value) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; - r->error = error; - r->text = value; - test_latch_signal(r->done); -} - -static void on_next(void *user_data, bool cancelled, CapiError *error, uint64_t value) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; - r->error = error; - r->value = value; - test_latch_signal(r->done); -} - -static void on_next_slow(void *user_data, bool cancelled, CapiError *error, uint64_t value) { - result *r = (result *)user_data; - (void)error; - r->calls++; - r->cancels += cancelled; - r->value = value; - test_latch_signal(r->entered); - test_latch_wait(r->release); - test_latch_signal(r->done); -} - -static void on_wait(void *user_data, bool cancelled) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; - test_latch_signal(r->done); -} - -static void async_calls(void) { - const uint64_t values[] = {10, 20, 30}; - CapiU64List list; - CapiStore *store = capi_store_new("async"); - CapiTask *task; - test_latch *done = test_latch_new(); - result r; - result flush; - - memset(&r, 0, sizeof r); - r.done = done; - memset(&flush, 0, sizeof flush); - flush.done = test_latch_new(); - - /* Ready on its first poll, yet still delivered on the dispatcher. */ - list.data = values; - list.len = 3; - task = capi_sum(&list, on_sum, &r); - test_latch_wait(r.done); - CHECK(r.value == 60); - capi_task_free(task); - - task = capi_greet("bob", on_greet, &r); - test_latch_wait(r.done); - CHECK(r.error == NULL && streq(r.text, "hello, bob")); - capi_string_free(r.text); - capi_task_free(task); - - task = capi_greet("", on_greet, &r); - test_latch_wait(r.done); - CHECK(r.error && r.error->tag == CAPI_ERROR_INVALID && r.text == NULL); - capi_error_free(r.error); - capi_task_free(task); - - /* Pending until another call wakes it. */ - task = capi_store_next(store, on_next, &r); - capi_store_push(store, 42); - test_latch_wait(r.done); - CHECK(r.error == NULL && r.value == 42); - capi_task_free(task); - - /* Freeing a task whose callback is running elsewhere returns without a cancel. The - * dispatcher runs in order, so a cancel would arrive before the flush's result. */ - memset(&r, 0, sizeof r); - r.done = done; - r.entered = test_latch_new(); - r.release = test_latch_new(); - task = capi_store_next(store, on_next_slow, &r); - capi_store_push(store, 7); - test_latch_wait(r.entered); - capi_task_free(task); - test_latch_signal(r.release); - test_latch_wait(r.done); - task = capi_sum(&list, on_sum, &flush); - test_latch_wait(flush.done); - capi_task_free(task); - CHECK(r.calls == 1 && r.cancels == 0 && r.value == 7); - test_latch_free(r.entered); - test_latch_free(r.release); - - /* Freeing a pending task calls back once, cancelled. */ - memset(&r, 0, sizeof r); - r.done = done; - task = capi_store_wait_forever(store, on_wait, &r); - capi_task_free(task); - test_latch_wait(r.done); - CHECK(r.calls == 1 && r.cancels == 1); - - capi_store_close(store); - task = capi_store_next(store, on_next, &r); - test_latch_wait(r.done); - CHECK(r.error && r.error->tag == CAPI_ERROR_NOT_FOUND); - capi_error_free(r.error); - capi_task_free(task); - - capi_task_free(NULL); - capi_store_free(store); - test_latch_free(done); - test_latch_free(flush.done); -} - -int main(void) { - defaults(); - records(); - enums(); - scalars(); - errors(); - objects(); - async_calls(); - capi_shutdown_dispatcher(); - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/c_dispatcher/main.c b/uniffi/cpp/cpp-tests/tests/c_dispatcher/main.c deleted file mode 100644 index ec1d8aad3..000000000 --- a/uniffi/cpp/cpp-tests/tests/c_dispatcher/main.c +++ /dev/null @@ -1,213 +0,0 @@ -/* - * The generated C API on a host-owned dispatcher: work only runs when the test drains its - * queue, so cancellation and delivery are checked without timing. This fixture wakes every - * future from a call on this thread, so the queue needs no lock. - */ -#include - -#include - -#include - -#define QUEUE_CAPACITY 64 - -static CapiWork *queue[QUEUE_CAPACITY]; -static size_t queued; -static bool accepting = true; -static int shutdowns; - -static bool dispatch(void *user_data, CapiWork *work) { - CHECK(user_data == &queued); - if (!accepting) { - return false; - } - CHECK(queued < QUEUE_CAPACITY); - queue[queued++] = work; - return true; -} - -/* Runs the oldest queued work. */ -static void run_one(void) { - CapiWork *work; - CHECK(queued > 0); - work = queue[0]; - queued--; - memmove(queue, queue + 1, queued * sizeof queue[0]); - capi_work_run(work); -} - -/* Runs queued work, including work that running it queues. Returns how many ran. */ -static size_t drain(void) { - size_t ran = 0; - while (queued > 0) { - run_one(); - ran++; - } - return ran; -} - -static void stop(void *user_data) { - CHECK(user_data == &queued); - accepting = false; - drain(); - shutdowns++; -} - -typedef struct { - int calls; - int cancels; - uint64_t value; - CapiError *error; - CapiTask *task; - /* Another call's task, which the callback frees. */ - CapiTask *other; -} result; - -static void on_sum(void *user_data, bool cancelled, uint64_t value) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; - r->value = value; -} - -static void on_next(void *user_data, bool cancelled, CapiError *error, uint64_t value) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; - r->error = error; - r->value = value; -} - -static void on_wait(void *user_data, bool cancelled) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; -} - -/* Frees its own task, and the other one, from inside the callback. */ -static void on_sum_free(void *user_data, bool cancelled, uint64_t value) { - result *r = (result *)user_data; - r->calls++; - r->cancels += cancelled; - r->value = value; - capi_task_free(r->task); - r->task = NULL; - capi_task_free(r->other); - r->other = NULL; -} - -int main(void) { - const uint64_t values[] = {1, 2, 3}; - CapiU64List list; - CapiDispatcher dispatcher; - CapiStore *store; - result r; - - dispatcher.dispatch = dispatch; - dispatcher.shutdown = stop; - dispatcher.user_data = &queued; - capi_set_dispatcher(&dispatcher); - - store = capi_store_new("loop"); - list.data = values; - list.len = 3; - - /* A future ready on its first poll still calls back only from the host's loop. */ - memset(&r, 0, sizeof r); - r.task = capi_sum(&list, on_sum, &r); - CHECK(r.calls == 0); - CHECK(drain() > 0); - CHECK(r.calls == 1 && r.value == 6); - capi_task_free(r.task); - - /* A pending future calls back once woken and drained. */ - memset(&r, 0, sizeof r); - r.task = capi_store_next(store, on_next, &r); - drain(); - CHECK(r.calls == 0); - capi_store_push(store, 11); - CHECK(r.calls == 0); - drain(); - CHECK(r.calls == 1 && r.error == NULL && r.value == 11); - capi_task_free(r.task); - - /* Freeing a pending task drops the Rust future, then calls back once, cancelled, from the - * host's loop. */ - memset(&r, 0, sizeof r); - r.task = capi_store_wait_forever(store, on_wait, &r); - CHECK(capi_pending_count() == 1); - capi_task_free(r.task); - CHECK(r.calls == 0); - drain(); - CHECK(capi_pending_count() == 0); - CHECK(r.calls == 1 && r.cancels == 1); - - /* Freeing a task whose result is ready but not yet delivered cancels it instead. */ - memset(&r, 0, sizeof r); - r.task = capi_sum(&list, on_sum, &r); - capi_task_free(r.task); - drain(); - CHECK(r.calls == 1 && r.cancels == 1 && r.value == 0); - - /* Freeing a task after its callback was queued, but before it ran, cancels it once. */ - memset(&r, 0, sizeof r); - r.task = capi_sum(&list, on_sum, &r); - CHECK(queued == 1); - run_one(); - CHECK(queued == 1 && r.calls == 0); - capi_task_free(r.task); - drain(); - CHECK(r.calls == 1 && r.cancels == 1 && r.value == 0); - - /* A callback may free its own task, which is no cancel, and another pending task, whose - * cancel runs later on the loop rather than inside the callback. */ - { - result other; - memset(&other, 0, sizeof other); - memset(&r, 0, sizeof r); - r.other = capi_store_wait_forever(store, on_wait, &other); - drain(); - r.task = capi_sum(&list, on_sum_free, &r); - CHECK(queued == 1); - run_one(); - CHECK(queued == 1 && r.calls == 0 && other.calls == 0); - run_one(); - CHECK(r.calls == 1 && r.cancels == 0 && r.value == 6 && r.task == NULL && r.other == NULL); - CHECK(other.calls == 0); - drain(); - CHECK(r.calls == 1 && other.calls == 1 && other.cancels == 1); - CHECK(capi_pending_count() == 0); - } - - /* Rejected work abandons the result, so freeing the task cancels it. */ - memset(&r, 0, sizeof r); - accepting = false; - r.task = capi_sum(&list, on_sum, &r); - accepting = true; - CHECK(queued == 0); - CHECK(r.calls == 0); - capi_task_free(r.task); - drain(); - CHECK(r.calls == 1 && r.cancels == 1); - - /* Shutdown drains through the host, then no call calls back, not even cancelled. */ - memset(&r, 0, sizeof r); - r.task = capi_store_next(store, on_next, &r); - capi_shutdown_dispatcher(); - CHECK(shutdowns == 1); - capi_store_push(store, 5); - CHECK(queued == 0); - CHECK(r.calls == 0); - capi_task_free(r.task); - - memset(&r, 0, sizeof r); - r.task = capi_sum(&list, on_sum, &r); - CHECK(queued == 0 && r.calls == 0); - capi_task_free(r.task); - - capi_shutdown_dispatcher(); - CHECK(shutdowns == 1); - - capi_store_free(store); - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/c_namespaces/main.c b/uniffi/cpp/cpp-tests/tests/c_namespaces/main.c deleted file mode 100644 index fb57f1e3e..000000000 --- a/uniffi/cpp/cpp-tests/tests/c_namespaces/main.c +++ /dev/null @@ -1,189 +0,0 @@ -/* The namespaces fixture through the C API: `media`'s types hold or refer to `net`'s, and - * both crates name their types alike. */ -#include -#include -#include - -static NetGroupConsumer *net_group(uint64_t sequence, NetPriority priority, const NetFrame *frames, size_t len) { - NetFrameList list = {frames, len}; - return net_group_consumer_new(sequence, priority, &list); -} - -static NetFrame frame_of(const uint8_t *data, size_t len) { - NetFrame frame; - frame.payload.data = data; - frame.payload.len = len; - return frame; -} - -static bool payload_is(const NetFrame *frame, const uint8_t *data, size_t len) { - return frame->payload.len == len && (len == 0 || memcmp(frame->payload.data, data, len) == 0); -} - -static void object_wraps_its_namesake(void) { - const uint8_t first[] = {1, 'a'}; - const uint8_t second[] = {0, 'b'}; - NetFrame frames[] = {frame_of(first, 2), frame_of(second, 2)}; - NetGroupConsumer *inner = net_group(3, NET_PRIORITY_LOW, frames, 2); - MediaGroupConsumer *group = media_group_consumer_new(inner); - net_group_consumer_free(inner); - - NetGroupConsumer *held = media_group_consumer_group(group); - CHECK(net_group_consumer_sequence(held) == 3); - net_group_consumer_free(held); - - MediaPriority *priority = media_group_consumer_priority(group); - CHECK(priority->tag == MEDIA_PRIORITY_NET); - CHECK(priority->net.priority == NET_PRIORITY_LOW); - media_priority_free(priority); - - MediaFrame *frame = NULL; - CHECK(media_group_consumer_read_frame(group, &frame) == NULL); - CHECK(payload_is(&frame->raw, first, 2)); - CHECK(frame->keyframe); - media_frame_free(frame); - CHECK(media_group_consumer_read_frame(group, &frame) == NULL); - CHECK(!frame->keyframe); - media_frame_free(frame); - - /* Each layer's error, both named `GroupError`. */ - MediaGroupError *error = media_group_consumer_read_frame(group, &frame); - CHECK(error != NULL); - CHECK(frame == NULL); - CHECK(error->tag == MEDIA_GROUP_ERROR_NET); - CHECK(error->net.source.tag == NET_GROUP_ERROR_CLOSED); - CHECK(error->net.source.closed.code == 7); - CHECK(media_group_error_message(error) != NULL); - media_group_error_free(error); - - NetFrame empty = frame_of(NULL, 0); - error = media_decode(&empty, &frame); - CHECK(error != NULL); - CHECK(error->tag == MEDIA_GROUP_ERROR_EMPTY); - media_group_error_free(error); - - media_group_consumer_free(group); -} - -typedef struct { - test_latch *done; - NetGroupError *error; - MediaFrame *frame; -} next_result; - -static void on_next(void *user_data, bool cancelled, NetGroupError *error, MediaFrame *value) { - next_result *r = (next_result *)user_data; - CHECK(!cancelled); - r->error = error; - r->frame = value; - test_latch_signal(r->done); -} - -static void async_throws_the_net_error(void) { - const uint8_t only[] = {1}; - NetFrame frames[] = {frame_of(only, 1)}; - NetGroupConsumer *inner = net_group(1, NET_PRIORITY_HIGH, frames, 1); - MediaGroupConsumer *group = media_group_consumer_new(inner); - net_group_consumer_free(inner); - - MediaPriority *priority = media_group_consumer_priority(group); - CHECK(priority->tag == MEDIA_PRIORITY_REALTIME); - media_priority_free(priority); - - next_result r = {test_latch_new(), NULL, NULL}; - MediaTask *task = media_group_consumer_next_frame(group, on_next, &r); - test_latch_wait(r.done); - media_task_free(task); - CHECK(r.error == NULL); - CHECK(payload_is(&r.frame->raw, only, 1)); - media_frame_free(r.frame); - - r.frame = NULL; - task = media_group_consumer_next_frame(group, on_next, &r); - test_latch_wait(r.done); - media_task_free(task); - CHECK(r.frame == NULL); - CHECK(r.error != NULL); - CHECK(r.error->tag == NET_GROUP_ERROR_CLOSED); - CHECK(r.error->closed.code == 7); - net_group_error_free(r.error); - - test_latch_free(r.done); - media_group_consumer_free(group); -} - -static void containers_of_both(void) { - const uint8_t z[] = {0, 'z'}; - NetFrame raw = frame_of(z, 2); - MediaFrame *frame = NULL; - CHECK(media_decode(&raw, &frame) == NULL); - NetFrame *encoded = media_encode(frame); - CHECK(payload_is(encoded, z, 2)); - net_frame_free(encoded); - media_frame_free(frame); - - const uint8_t a[] = {0, 'a'}; - const uint8_t b[] = {1, 'b'}; - NetFrame raws[] = {frame_of(a, 2), frame_of(NULL, 0), frame_of(b, 2)}; - MediaNetFrameList raw_list = {raws, 3}; - MediaFrameList *frames = media_decode_all(&raw_list); - CHECK(frames->len == 2); - CHECK(!frames->data[0].keyframe); - CHECK(frames->data[1].keyframe); - - MediaBounds *bounds = media_find_bounds(frames); - CHECK(bounds->keyframe != NULL); - CHECK(payload_is(&bounds->keyframe->raw, b, 2)); - CHECK(bounds->last != NULL); - CHECK(payload_is(bounds->last, b, 2)); - media_bounds_free(bounds); - media_frame_list_free(frames); - - MediaFrameList none = {NULL, 0}; - bounds = media_find_bounds(&none); - CHECK(bounds->keyframe == NULL); - CHECK(bounds->last == NULL); - media_bounds_free(bounds); - - NetGroupConsumer *inners[] = { - net_group(1, NET_PRIORITY_LOW, NULL, 0), - net_group(2, NET_PRIORITY_HIGH, NULL, 0), - }; - MediaNetGroupConsumerList inner_list = {inners, 2}; - MediaGroups *groups = media_wrap_all(&inner_list); - net_group_consumer_free(inners[0]); - net_group_consumer_free(inners[1]); - - CHECK(groups->groups.len == 2); - for (size_t i = 0; i < 2; ++i) { - NetGroupConsumer *held = media_group_consumer_group(groups->groups.data[i]); - CHECK(net_group_consumer_sequence(held) == i + 1); - net_group_consumer_free(held); - } - CHECK(groups->net.len == 2); - CHECK(groups->media.len == 2); - for (size_t i = 0; i < 2; ++i) { - uint64_t sequence = groups->net.keys[i]; - NetPriority net = groups->net.values[i]; - CHECK(net == (sequence == 1 ? NET_PRIORITY_LOW : NET_PRIORITY_HIGH)); - } - for (size_t i = 0; i < 2; ++i) { - uint64_t sequence = groups->media.keys[i]; - const MediaPriority *media = &groups->media.values[i]; - if (sequence == 1) { - CHECK(media->tag == MEDIA_PRIORITY_NET); - CHECK(media->net.priority == NET_PRIORITY_LOW); - } else { - CHECK(media->tag == MEDIA_PRIORITY_REALTIME); - } - } - media_groups_free(groups); -} - -int main(void) { - object_wraps_its_namesake(); - async_throws_the_net_error(); - containers_of_both(); - media_shutdown_dispatcher(); - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/c_support/support.cpp b/uniffi/cpp/cpp-tests/tests/c_support/support.cpp deleted file mode 100644 index dbd472d8c..000000000 --- a/uniffi/cpp/cpp-tests/tests/c_support/support.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include - -#include -#include - -struct test_latch { - std::mutex mutex; - std::condition_variable signalled; - int count = 0; -}; - -test_latch *test_latch_new(void) { - return new test_latch(); -} - -void test_latch_signal(test_latch *latch) { - { - std::lock_guard guard(latch->mutex); - latch->count++; - } - latch->signalled.notify_all(); -} - -void test_latch_wait(test_latch *latch) { - std::unique_lock lock(latch->mutex); - latch->signalled.wait(lock, [latch] { return latch->count > 0; }); - latch->count--; -} - -void test_latch_free(test_latch *latch) { - delete latch; -} diff --git a/uniffi/cpp/cpp-tests/tests/callbacks/main.cpp b/uniffi/cpp/cpp-tests/tests/callbacks/main.cpp deleted file mode 100644 index d0da1d722..000000000 --- a/uniffi/cpp/cpp-tests/tests/callbacks/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include - -#include - -class CallAnswererImpl: public callbacks::CallAnswerer { -public: - std::string mode; - - CallAnswererImpl(const std::string& mode) : mode(std::move(mode)) {} - - std::string answer() override { - if (mode.compare("normal") == 0) { - return "Hello"; - } else if (mode.compare("busy") == 0) { - throw callbacks::telephone_error::Busy("I'm busy"); - } else { - throw std::runtime_error("Unknown mode"); - } - } -}; - -class DiscountSim: public callbacks::SimCard { -public: - std::string name() { - return "C++"; - } -}; - -int main() { - { - auto telephone = callbacks::Telephone::init(); - auto default_sim = callbacks::get_sim_cards()[0]; - - ASSERT_EQ(telephone->call(default_sim, std::make_shared("normal")), "Hello"); - EXPECT_EXCEPTION(telephone->call(default_sim, std::make_shared("busy")), callbacks::telephone_error::Busy); - EXPECT_EXCEPTION(telephone->call(default_sim, std::make_shared("unknown")), callbacks::telephone_error::InternalTelephoneError); - ASSERT_EQ(telephone->call(std::make_shared(), std::make_shared("normal")), "C++ est bon marché"); - } - - // Technically not required to test this, as it's the same implementation in Rust, but done with proc macros - { - auto telephone = callbacks::FancyTelephone::init(); - auto default_sim = callbacks::get_sim_cards()[0]; - - ASSERT_EQ(telephone->call(default_sim, std::make_shared("normal")), "Hello"); - EXPECT_EXCEPTION(telephone->call(default_sim, std::make_shared("busy")), callbacks::telephone_error::Busy); - EXPECT_EXCEPTION(telephone->call(default_sim, std::make_shared("unknown")), callbacks::telephone_error::InternalTelephoneError); - ASSERT_EQ(telephone->call(std::make_shared(), std::make_shared("normal")), "C++ est bon marché"); - } - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/chronological/main.cpp b/uniffi/cpp/cpp-tests/tests/chronological/main.cpp deleted file mode 100644 index 744443c5a..000000000 --- a/uniffi/cpp/cpp-tests/tests/chronological/main.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include - -#include -#include -#include -#include -#include - -using namespace std::chrono_literals; - -std::chrono::time_point epoch_second(int seconds, int nanoseconds) { - return std::chrono::time_point(std::chrono::seconds(seconds)) + std::chrono::nanoseconds(nanoseconds); -} - - -std::chrono::duration time_span_seconds(int seconds, int nanoseconds) { - return std::chrono::seconds(seconds) + std::chrono::nanoseconds(nanoseconds); -} - -std::chrono::time_point time_from_string(const std::string& time) { - std::tm tm = {}; - auto ss = std::stringstream(time); - ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S"); - -#ifdef _WIN32 - return std::chrono::system_clock::from_time_t(_mkgmtime(&tm)); -#else - return std::chrono::system_clock::from_time_t(timegm(&tm)); -#endif -} - -void test_string_timestamps() { - // Test post-epoch timestamps - { - auto time_str = "1970-12-12T00:00:00.000000000Z"; - auto time = time_from_string(time_str); - - ASSERT_EQ(time_str, chronological::to_string_timestamp(time)); - } - - { - // get_time doesn't support nanoseconds, so we have to add them manually - auto time_str = "1970-12-31T23:59:58.999999900Z"; - auto time = time_from_string(time_str) + 999999900ns; - - ASSERT_EQ(time_str, chronological::to_string_timestamp(time)); - } - - { - // get_time doesn't support nanoseconds, so we have to add them manually - auto time = time_from_string("2024-11-05T00:06:01.283000200Z") + 283000200ns; - auto time2 = time_from_string("2024-11-05T00:06:00.283000100Z") + 283000100ns; - - ASSERT_EQ( - time, - chronological::add(time2, time_span_seconds(1, 100)) - ); - } - -#ifdef _WIN32 - // _mkgmtime doesn't support dates before 1970, so we skip these tests - return; -#endif - - // Test pre-epoch timestamps - { - auto time_str = "1969-12-12T00:00:00.000000000Z"; - auto time = time_from_string(time_str); - - ASSERT_EQ(time_str, chronological::to_string_timestamp(time)); - } - - { - // get_time doesn't support nanoseconds, so we have to add them manually - auto time_str = "1969-12-31T23:59:58.999999900Z"; - auto time = time_from_string(time_str) + 999999900ns; - - ASSERT_EQ(time_str, chronological::to_string_timestamp(time)); - } - - { - // get_time doesn't support nanoseconds, so we have to add them manually - auto time = time_from_string("1955-11-05T00:06:01.283000200Z") + 283000200ns; - auto time2 = time_from_string("1955-11-05T00:06:00.283000100Z") + 283000100ns; - - ASSERT_EQ( - time, - chronological::add(time2, time_span_seconds(1, 100)) - ); - } -} - -int main() { - ASSERT_EQ( - epoch_second(101, 200), - chronological::add(epoch_second(100, 100), time_span_seconds(1, 100)) - ); - - ASSERT_EQ( - time_span_seconds(1, 100), - chronological::diff(epoch_second(101, 200), epoch_second(100, 100)) - ); - - EXPECT_EXCEPTION( - chronological::diff(epoch_second(100, 0), epoch_second(101, 0)), - chronological::ChronologicalError - ); - - - // When testing the min and max values, we need to round them to the nearest 100 ns, as on Windows one tick is 100 ns - auto min = std::chrono::time_point::min().time_since_epoch().count() / 100 * 100; - auto min_timepoint = std::chrono::time_point(std::chrono::nanoseconds(min)); - ASSERT_EQ( - min_timepoint, - chronological::return_timestamp(min_timepoint) - ); - - auto max = std::chrono::time_point::max().time_since_epoch().count() / 100 * 100; - auto max_timepoint = std::chrono::time_point(std::chrono::nanoseconds(max)); - ASSERT_EQ( - max_timepoint, - chronological::return_timestamp(max_timepoint) - ); - - ASSERT_EQ( - std::chrono::nanoseconds::max(), - chronological::return_duration(std::chrono::nanoseconds::max()) - ); - - test_string_timestamps(); - - auto before = std::chrono::system_clock::now(); - std::this_thread::sleep_for(1s); - auto after = chronological::now(); - std::this_thread::sleep_for(1s); - auto after2 = std::chrono::system_clock::now(); - ASSERT_EQ(-1, std::chrono::duration_cast(before - after).count()); - ASSERT_EQ(1, std::chrono::duration_cast(after2 - after).count()); - - ASSERT_TRUE(chronological::optional(std::chrono::time_point::max(), time_span_seconds(0, 0))); - ASSERT_FALSE(chronological::optional(std::nullopt, time_span_seconds(0, 0))); - ASSERT_FALSE(chronological::optional(std::chrono::time_point::min(), std::nullopt)); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/custom_types/main.cpp b/uniffi/cpp/cpp-tests/tests/custom_types/main.cpp deleted file mode 100644 index 3228f36c3..000000000 --- a/uniffi/cpp/cpp-tests/tests/custom_types/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include - -#include - -int main() { - auto demo = custom_types::get_custom_types_demo(std::nullopt); - ASSERT_EQ("http://example.com/", demo.url); - ASSERT_EQ(123, demo.handle); - ASSERT_EQ(456000, demo.time_interval_ms); - ASSERT_EQ(456.0, demo.time_interval_sec_dbl); - ASSERT_EQ(777.0f, demo.time_interval_sec_flt); - - auto demo2 = custom_types::CustomTypesDemo { - "http://example.com/2", - 456, - 532000, - 532.0, - 333.0f - }; - auto ret = custom_types::get_custom_types_demo(demo2); - ASSERT_EQ(demo2.url, ret.url); - ASSERT_EQ(demo2.handle, ret.handle); - ASSERT_EQ(demo2.time_interval_ms, ret.time_interval_ms); - ASSERT_EQ(demo2.time_interval_sec_dbl, ret.time_interval_sec_dbl); - ASSERT_EQ(demo2.time_interval_sec_flt, ret.time_interval_sec_flt); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/custom_types_builtin/main.cpp b/uniffi/cpp/cpp-tests/tests/custom_types_builtin/main.cpp deleted file mode 100644 index cab48ec7c..000000000 --- a/uniffi/cpp/cpp-tests/tests/custom_types_builtin/main.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include - -#include - -void assert_custom_type(custom_types_builtin::CustomTypesBuiltin& type) { - auto table = std::unordered_map{{"hello", "world"}}; - auto bytes = std::vector{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - - ASSERT_EQ(type.string, "Hello, world!"); - ASSERT_EQ(type.custom_string.string, "Custom string"); - ASSERT_EQ(type.array, std::vector{"Hello, world!"}); - ASSERT_EQ(type.bytes, bytes); - ASSERT_EQ(type.table, table); - ASSERT_EQ(type.boolean, true); - ASSERT_EQ(type.int8, std::numeric_limits::max()); - ASSERT_EQ(type.int16, std::numeric_limits::max()); - ASSERT_EQ(type.int32, std::numeric_limits::max()); - ASSERT_EQ(type.int64, std::numeric_limits::max()); - ASSERT_EQ(type.uint8, std::numeric_limits::max()); - ASSERT_EQ(type.uint16, std::numeric_limits::max()); - ASSERT_EQ(type.uint32, std::numeric_limits::max()); - ASSERT_EQ(type.uint64, std::numeric_limits::max()); - ASSERT_EQ(type.flt, std::numeric_limits::max()); - ASSERT_EQ(type.dbl, std::numeric_limits::max()); -} - -int main() { - auto custom_type = custom_types_builtin::get_custom_types_builtin(); - assert_custom_type(custom_type); - - custom_type = custom_types_builtin::return_custom_types_builtin(custom_type); - assert_custom_type(custom_type); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/empty_type/main.cpp b/uniffi/cpp/cpp-tests/tests/empty_type/main.cpp deleted file mode 100644 index 446a4f2a8..000000000 --- a/uniffi/cpp/cpp-tests/tests/empty_type/main.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "test_common.hpp" - -#include - -int main() { - auto empty = empty_type::get_empty_type(); - - empty_type::send_empty_type(empty); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/enum_style_test/main.cpp b/uniffi/cpp/cpp-tests/tests/enum_style_test/main.cpp deleted file mode 100644 index 1848ba2f2..000000000 --- a/uniffi/cpp/cpp-tests/tests/enum_style_test/main.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include - -#include - -int main() { - auto simple = enum_style_test::get_simple_enum(); - enum_style_test::set_simple_enum(simple); - - auto complex = enum_style_test::get_complex_enum(); - enum_style_test::set_complex_enum(complex); - - auto repeated = enum_style_test::roundtrip_repeated_dependencies({ - enum_style_test::SimpleEnum::VARIANT_ONE, - enum_style_test::SimpleEnum::VARIANT_TWO, - }); - ASSERT_EQ(repeated.first, enum_style_test::SimpleEnum::VARIANT_ONE); - ASSERT_EQ(repeated.second, enum_style_test::SimpleEnum::VARIANT_TWO); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/error_types_builtin/main.cpp b/uniffi/cpp/cpp-tests/tests/error_types_builtin/main.cpp deleted file mode 100644 index 0a79f0ff7..000000000 --- a/uniffi/cpp/cpp-tests/tests/error_types_builtin/main.cpp +++ /dev/null @@ -1,185 +0,0 @@ -#include - -#include - -int main() { - try { - error_types_builtin::oops(); - ASSERT_TRUE(false); - } catch (error_types_builtin::ErrorInterface& e) { - ASSERT_EQ(e.to_string(), "because uniffi told me so\n\nCaused by:\n oops"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops(); - ASSERT_TRUE(false); - } catch (error_types_builtin::ErrorInterface& e) { - ASSERT_EQ(e.to_string(), "because uniffi told me so\n\nCaused by:\n oops"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops(); - ASSERT_TRUE(false); - } catch (error_types_builtin::ErrorInterface& e) { - auto expected_chain = std::vector{ "because uniffi told me so", "oops" }; - ASSERT_EQ(e.chain(), expected_chain); - ASSERT_EQ(e.link(0), "because uniffi told me so"); - ASSERT_EQ(e.to_debug_string(), "ErrorInterface { e: because uniffi told me so\n\nCaused by:\n oops }"); - ASSERT_EQ(e.to_string(), "because uniffi told me so\n\nCaused by:\n oops"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::toops(); - ASSERT_TRUE(false); - } catch (error_types_builtin::ErrorTrait& e) { - ASSERT_EQ(e.msg(), "trait-oops"); - } catch (...) { - ASSERT_TRUE(false); - } - - { - auto e = error_types_builtin::get_error("the error"); - auto expected_chain = std::vector{ "the error" }; - ASSERT_EQ(e->chain(), expected_chain); - ASSERT_EQ(e->to_debug_string(), "ErrorInterface { e: the error }"); - ASSERT_EQ(e->to_string(), "the error"); - } - - try { - error_types_builtin::throw_rich("oh no"); - ASSERT_TRUE(false); - } catch (error_types_builtin::RichError& e) { - ASSERT_EQ(e.to_debug_string(), "RichError { e: \"oh no\" }"); - ASSERT_EQ(e.to_string(), "RichError: \"oh no\""); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::TestInterface::fallible_new(); - ASSERT_TRUE(false); - } catch (error_types_builtin::ErrorInterface& e) { - ASSERT_EQ(e.to_string(), "fallible_new"); - } catch (...) { - ASSERT_TRUE(false); - } - - { - auto interface = error_types_builtin::TestInterface::init(); - try { - interface->oops(); - ASSERT_TRUE(false); - } catch (error_types_builtin::ErrorInterface& e) { - ASSERT_EQ(e.to_string(), "because the interface told me so\n\nCaused by:\n oops"); - } catch (...) { - ASSERT_TRUE(false); - } - } - - try { - error_types_builtin::throw_proc_error("eek"); - ASSERT_TRUE(false); - } catch (error_types_builtin::ProcErrorInterface& e) { - ASSERT_EQ(e.message(), "eek"); - ASSERT_EQ(e.to_string(), "ProcErrorInterface(eek)"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops_enum(0); - ASSERT_TRUE(false); - } catch (error_types_builtin::error::Oops& e) { - ASSERT_EQ(e.what(), std::string("")); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops_enum(1); - ASSERT_TRUE(false); - } catch (error_types_builtin::error::Value& e) { - ASSERT_EQ(e.value, "value"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops_enum(2); - ASSERT_TRUE(false); - } catch (error_types_builtin::error::IntValue& e) { - ASSERT_EQ(e.value, 2); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops_enum(3); - ASSERT_TRUE(false); - } catch (error_types_builtin::error::FlatInnerError& e) { - auto subtype = dynamic_cast(e.error.get()); - ASSERT_TRUE(subtype != nullptr); - ASSERT_EQ(std::string(e.error->what()), "inner"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops_enum(4); - ASSERT_TRUE(false); - } catch (error_types_builtin::error::FlatInnerError& e) { - auto subtype = dynamic_cast(e.error.get()); - ASSERT_TRUE(subtype != nullptr); - ASSERT_EQ(std::string(e.error->what()), "NonUniffiTypeValue: value"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops_enum(5); - ASSERT_TRUE(false); - } catch (error_types_builtin::error::InnerError& e) { - auto subtype = dynamic_cast(e.error.get()); - ASSERT_TRUE(subtype != nullptr); - ASSERT_EQ(subtype->v1, "inner"); - } catch (...) { - ASSERT_TRUE(false); - } - - { - auto r = error_types_builtin::get_tuple(nullptr); - auto subtype = dynamic_cast(r.get()); - ASSERT_TRUE(subtype != nullptr); - ASSERT_EQ(subtype->v1, "oops"); - } - - try { - error_types_builtin::oops_tuple(0); - ASSERT_TRUE(false); - } catch (error_types_builtin::TupleError& e) { - auto subtype = dynamic_cast(&e); - ASSERT_TRUE(subtype != nullptr); - ASSERT_EQ(subtype->v1, "oops"); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - error_types_builtin::oops_tuple(1); - ASSERT_TRUE(false); - } catch (error_types_builtin::TupleError& e) { - auto subtype = dynamic_cast(&e); - ASSERT_TRUE(subtype != nullptr); - ASSERT_EQ(subtype->v1, 1); - } catch (...) { - ASSERT_TRUE(false); - } - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/expected/main.cpp b/uniffi/cpp/cpp-tests/tests/expected/main.cpp deleted file mode 100644 index 388deeeca..000000000 --- a/uniffi/cpp/cpp-tests/tests/expected/main.cpp +++ /dev/null @@ -1,238 +0,0 @@ -// Bindings generated with `error_style = "expected"`, built with exceptions and RTTI disabled. - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std::chrono_literals; - -// Unlike assert, this survives a release build. -#define CHECK(expr) \ - do { \ - if (!(expr)) { \ - std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #expr); \ - std::abort(); \ - } \ - } while (0) - -namespace errors = error_types_builtin; - -template -const V *variant_of(const E &error) { - return std::get_if(&error.get_variant()); -} - -void sync_errors() { - auto oops = errors::oops_enum(0); - CHECK(!oops); - CHECK(variant_of(oops.error())); - - auto value = errors::oops_enum(1); - CHECK(!value); - auto value_variant = variant_of(value.error()); - CHECK(value_variant && value_variant->value == "value"); - - auto int_value = errors::oops_enum(2); - auto int_variant = variant_of(int_value.error()); - CHECK(int_variant && int_variant->value == 2); - - // A flat error carries only its message, one per variant. - auto flat_a = errors::oops_enum(3); - auto flat_a_variant = variant_of(flat_a.error()); - CHECK(flat_a_variant); - auto case_a = variant_of(flat_a_variant->error); - CHECK(case_a && case_a->message == "inner"); - - auto flat_b = errors::oops_enum(4); - auto flat_b_variant = variant_of(flat_b.error()); - CHECK(flat_b_variant); - auto case_b = variant_of(flat_b_variant->error); - CHECK(case_b && case_b->message == "NonUniffiTypeValue: value"); - - auto tuple = errors::oops_tuple(1); - auto tuple_variant = variant_of(tuple.error()); - CHECK(tuple_variant && tuple_variant->v1 == 1); - - // Errors are plain values, so they cross the boundary as arguments too. - auto echoed = errors::get_tuple(errors::TupleError(errors::TupleError::kValue{7})); - auto echoed_variant = variant_of(echoed); - CHECK(echoed_variant && echoed_variant->v1 == 7); - - // An object used as an error arrives as the object. - auto object = errors::oops(); - CHECK(!object); - CHECK(object.error()->chain().size() == 2); - - auto fallible = errors::TestInterface::fallible_new(); - CHECK(!fallible); - auto infallible = errors::TestInterface::init(); - CHECK(infallible != nullptr); - CHECK(!infallible->oops()); -} - -void error_display() { - // An error exporting Display and Debug prints what Rust would. - auto no_data = trait_methods::throw_multiple_trait_error(0); - CHECK(!no_data); - CHECK(no_data.error().to_string() == "MultipleTraitError::NoData"); - - auto nested = trait_methods::throw_multiple_trait_error(1); - CHECK(!nested); - CHECK(nested.error().to_string() == "nested error: error: not found"); - CHECK(nested.error().to_debug_string() == "Nested(NotFound)"); -} - -void renamed_types() { - // `strip_type_prefix = "Capi"` names every type without the prefix, in signatures too. - auto store = capi::Store::open("store"); - CHECK(store && (*store)->name() == "store"); - - // uniffi's own rename skips a constructor's error type. - auto empty = capi::Store::open(""); - CHECK(!empty); - auto invalid = variant_of(empty.error()); - CHECK(invalid && invalid->v1 == "empty name"); - CHECK(empty.error().to_string() == "invalid: empty name"); -} - -void async_results() { - CHECK(futures::greet("C++") == "Hello, C++"); - CHECK(futures::always_ready().get()); - futures::void_return().get(); - futures::sleep_no_return(1).get(); - CHECK(futures::say_after(1, "Future").get() == "Hello, Future!"); - - auto ok = futures::fallible_me(false).get(); - CHECK(ok && *ok == 42); - - auto failed = futures::fallible_me(true).get(); - CHECK(!failed); - CHECK(variant_of(failed.error())); - - auto megaphone = futures::new_megaphone(); - CHECK(megaphone->say_after(1, "World").get() == "HELLO, WORLD!"); - CHECK(!megaphone->fallible_me(true).get()); - CHECK(*megaphone->fallible_me(false).get() == 42); - - auto made = futures::fallible_struct(false).get(); - CHECK(made && *made != nullptr); - CHECK(!futures::fallible_struct(true).get()); - CHECK(!futures::FallibleMegaphone::init().get()); - CHECK(futures::Megaphone::init().get() != nullptr); - - // The fixture exposes no "acquired" signal, so give the holder a wide margin to take the - // resource first; valgrind slows it by an order of magnitude. - auto holding = futures::use_shared_resource({1000, 100}); - std::this_thread::sleep_for(200ms); - auto timeout = futures::use_shared_resource({0, 5}).get(); - CHECK(!timeout); - CHECK(variant_of(timeout.error())); - CHECK(holding.get()); -} - -void continuations() { - auto inline_executor = [](uniffi::AsyncTask task) { - task(); - return true; - }; - - std::atomic value{0}; - auto continuation = std::move(futures::fallible_me(false)) - .then(inline_executor, [&](uniffi::expected result) { - value = result ? *result : -1; - }); - for (int i = 0; i < 500 && value == 0; i++) { - std::this_thread::sleep_for(1ms); - } - CHECK(value == 42); - - std::atomic finished{false}; - auto void_continuation = std::move(futures::sleep_no_return(1)) - .then(inline_executor, [&]() { finished = true; }); - for (int i = 0; i < 500 && !finished; i++) { - std::this_thread::sleep_for(1ms); - } - CHECK(finished); -} - -void cancellation() { - auto pending = futures::sleep(10000); - CHECK(pending.wait_for(10ms) == std::future_status::timeout); - pending.cancel(); - CHECK(!pending.valid()); - - // A cancelled continuation never runs. - std::atomic ran{false}; - auto continuation = std::move(futures::sleep(20)).then( - [](uniffi::AsyncTask task) { - task(); - return true; - }, - [&](bool) { ran = true; } - ); - continuation.cancel(); - std::this_thread::sleep_for(100ms); - CHECK(!ran); - - // Dropping an incomplete future cancels it rather than blocking. - auto start = std::chrono::steady_clock::now(); - { - auto dropped = futures::say_after(10000, "never"); - } - CHECK(std::chrono::steady_clock::now() - start < 1s); -} - -void shutdown() { - // A future still pending when the dispatcher shuts down is abandoned: its - // continuation does not run and nothing calls back into unloaded code. - std::atomic ran{false}; - auto continuation = std::move(futures::sleep(50)).then( - [](uniffi::AsyncTask task) { - task(); - return true; - }, - [&](bool) { ran = true; } - ); - uniffi::shutdown_async_dispatcher(); - std::this_thread::sleep_for(200ms); - CHECK(!ran); - - // A future ready on its first poll has its result lowered before the rejected dispatch - // abandons it. That result is released rather than leaked; the memcheck run of this - // test catches a record buffer nobody collected. - auto late = futures::new_my_record("late", 1); - CHECK(late.wait_for(0ms) == std::future_status::ready); -} - -int main(int argc, char **argv) { - if (argc > 1 && std::strcmp(argv[1], "value-on-error") == 0) { - // The abort is the expected outcome; the test matches the message printed before it. - std::signal(SIGABRT, [](int) { std::_Exit(0); }); -#ifdef _MSC_VER - // The debug CRT's abort() otherwise waits on a dialog before raising SIGABRT. - _set_abort_behavior(0, _WRITE_ABORT_MSG); -#endif - auto empty = capi::Store::open(""); - (void)empty.value(); - return 1; - } - - sync_errors(); - error_display(); - renamed_types(); - async_results(); - continuations(); - cancellation(); - shutdown(); - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/ext_types_import/main.cpp b/uniffi/cpp/cpp-tests/tests/ext_types_import/main.cpp deleted file mode 100644 index 3c67fd3f9..000000000 --- a/uniffi/cpp/cpp-tests/tests/ext_types_import/main.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include -#include - -struct Salutator : public ext_types_export::Greeter -{ - std::string greet() override - { - return "Hello, World!"; - } -}; - -int main() -{ - auto greeter = std::make_shared(); - ASSERT_EQ(ext_types_import::call_greeter(greeter), "Hello, World!"); - - ext_types_export::Coordinates coord{3, 4}; - auto rc = ext_types_import::roundtrip_coord(coord); - ASSERT_EQ(rc.x, 3); - ASSERT_EQ(rc.y, 4); - - std::vector coords{{1, 2}, {5, 6}}; - auto rcs = ext_types_import::roundtrip_coords(coords); - ASSERT_EQ(rcs.size(), 2); - ASSERT_EQ(rcs[0].x, 1); - ASSERT_EQ(rcs[1].y, 6); - - auto rd = ext_types_import::roundtrip_direction(ext_types_export::Direction::kNorth); - ASSERT_TRUE(rd == ext_types_export::Direction::kNorth); - - ext_types_export::Handle handle = 42; - auto rh = ext_types_import::roundtrip_handle(handle); - ASSERT_EQ(rh, 42); - - auto counter = ext_types_export::Counter::init(); - counter->increment(); - counter->increment(); - auto r_counter = ext_types_import::roundtrip_counter(counter); - ASSERT_EQ(r_counter->get(), 2); - r_counter->increment(); - ASSERT_EQ(r_counter->get(), 3); - - auto held = ext_types_export::Counter::init(); - held->increment(); - ext_types_import::Counters holder{held, 7}; - auto r_holder = ext_types_import::roundtrip_counters(holder); - ASSERT_EQ(r_holder.label, 7); - ASSERT_EQ(r_holder.counter->get(), 1); - - auto opt_coord = ext_types_import::roundtrip_opt_coord(ext_types_export::Coordinates{7, 8}); - ASSERT_TRUE(opt_coord.has_value()); - ASSERT_EQ(opt_coord->x, 7); - ASSERT_FALSE(ext_types_import::roundtrip_opt_coord(std::nullopt).has_value()); - - auto opt_counter = ext_types_export::Counter::init(); - opt_counter->increment(); - auto r_opt_counter = ext_types_import::roundtrip_opt_counter(opt_counter); - ASSERT_TRUE(r_opt_counter != nullptr); - ASSERT_EQ(r_opt_counter->get(), 1); - ASSERT_TRUE(ext_types_import::roundtrip_opt_counter(nullptr) == nullptr); - - auto circle_shape = ext_types_export::Shape(ext_types_export::Shape::kCircle{3.14}); - auto circle = ext_types_import::roundtrip_shape(circle_shape); - ASSERT_EQ(std::get(circle.get_variant()).radius, 3.14); - - auto inner_shape = ext_types_import::InnerShape(ext_types_import::InnerShape::kHold{ext_types_export::Shape::kRectangle{4.0, 8.0}}); - auto rectangle = ext_types_import::roundtrip_inner(inner_shape); - auto hold_rectangle = std::get(rectangle.get_variant()).shape; - ASSERT_EQ(std::get(hold_rectangle.get_variant()).width, 4.0); - ASSERT_EQ(std::get(hold_rectangle.get_variant()).height, 8.0); - - std::unordered_map locations; - locations["blood falls"] = ext_types_export::Coordinates{77, 162}; - locations["uluru"] = ext_types_export::Coordinates{15, 131}; - auto r_locations = ext_types_import::roundtrip_coord_map(locations); - ASSERT_EQ(r_locations.size(), 2); - ASSERT_EQ(r_locations["blood falls"].x, 77); - ASSERT_EQ(r_locations["uluru"].y, 131); - - std::vector> counters; - auto counter_a = ext_types_export::Counter::init(); - counter_a->increment(); - auto counter_b = ext_types_export::Counter::init(); - counter_b->increment(); - counter_b->increment(); - counters.push_back(counter_a); - counters.push_back(counter_b); - auto r_counters = ext_types_import::roundtrip_counter_list(counters); - ASSERT_EQ(r_counters.size(), 2); - ASSERT_EQ(r_counters[0]->get(), 1); - ASSERT_EQ(r_counters[1]->get(), 2); - - auto car = ext_types_export::to_car(); - ASSERT_EQ(car->year(), 1984); - ASSERT_EQ(ext_types_import::vehicle_year(car), 1984); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/fixture_callbacks/main.cpp b/uniffi/cpp/cpp-tests/tests/fixture_callbacks/main.cpp deleted file mode 100644 index fec081d1e..000000000 --- a/uniffi/cpp/cpp-tests/tests/fixture_callbacks/main.cpp +++ /dev/null @@ -1,162 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -struct CppGetters : public fixture_callbacks::ForeignGetters { - bool get_bool(bool v, bool argument_two) override { return v ^ argument_two; } - - std::string get_string(const std::string &v, bool arg2) override { - if (v.compare("bad-argument") == 0) { - throw fixture_callbacks::simple_error::BadArgument("bard argument"); - } - - if (v.compare("unexpected-error") == 0) { - throw std::runtime_error("something failed"); - } - - return arg2 ? "1234567890123" : v; - } - - std::optional get_option(std::optional v, bool arg2) override { - if (v.has_value()) { - if (v.value().compare("bad-argument") == 0) { - auto e = fixture_callbacks::complex_error::ReallyBadArgument(); - e.code = 20; - throw e; - } - - if (v.value().compare("unexpected-error") == 0) { - throw std::runtime_error("something failed"); - } - } - - if (arg2 && v.has_value()) { - std::transform(v.value().begin(), v.value().end(), v.value().begin(), [](char c) { return ::toupper(c); }); - } - - return v; - } - - std::vector get_list(const std::vector &v, bool arg2) override { return arg2 ? v : std::vector(); } - - void get_nothing(const std::string &v) override { - if (v.compare("bad-argument") == 0) { - throw fixture_callbacks::simple_error::BadArgument("bad argument"); - } - - if (v.compare("unexpected-error") == 0) { - throw std::runtime_error("something failed"); - } - } -}; - -struct CppStringifier : public fixture_callbacks::StoredForeignStringifier { - std::string from_simple_type(int32_t value) override { return "C++: " + std::to_string(value); } - - // This is not getting directly tested in the UniFFI tests, it's used to check for compilation errors - std::string from_complex_type(std::optional>> values) override { return "C++"; } -}; - -void test_callback_roundtrip() { - auto callback = std::make_shared(); - auto rust_callback = fixture_callbacks::RustGetters::init(); - - bool flag = true; - - ASSERT_EQ(callback->get_string("test", flag), rust_callback->get_string(callback, "test", flag)); - ASSERT_EQ(callback->get_bool(true, flag), rust_callback->get_bool(callback, true, flag)); - ASSERT_EQ(callback->get_bool(false, flag), rust_callback->get_bool(callback, false, flag)); - - for (auto list : {std::vector{1, 2}, std::vector{0, 1}}) { - ASSERT_EQ(callback->get_list(list, flag), rust_callback->get_list(callback, list, flag)); - } - - for (auto str : {"Hello", "World"}) { - ASSERT_EQ(callback->get_string(str, flag), rust_callback->get_string(callback, str, flag)); - } - - for (auto opt : {std::optional("Hello"), std::optional(std::nullopt)}) { - ASSERT_EQ(callback->get_option(opt, flag), rust_callback->get_option(callback, opt, flag)); - } - - ASSERT_EQ("TestString", rust_callback->get_string_optional_callback(callback, "TestString", false)); - ASSERT_EQ(rust_callback->get_string_optional_callback(nullptr, "TestString", false), std::nullopt); -} - -void test_callback_roundtrip_errors() { - auto callback = std::make_shared(); - auto rust_callback = fixture_callbacks::RustGetters::init(); - - bool flag = true; - - EXPECT_EXCEPTION(rust_callback->get_string_optional_callback(callback, "bad-argument", flag), fixture_callbacks::simple_error::BadArgument); - EXPECT_EXCEPTION(rust_callback->get_string(callback, "unexpected-error", flag), fixture_callbacks::simple_error::UnexpectedError); - - try { - rust_callback->get_option(callback, "bad-argument", flag); - } catch (fixture_callbacks::complex_error::ReallyBadArgument &e) { - ASSERT_EQ(e.code, 20); - } catch (...) { - ASSERT_TRUE(false); - } - - try { - rust_callback->get_option(callback, "unexpected-error", flag); - } catch (fixture_callbacks::complex_error::UnexpectedErrorWithReason &e) { - ASSERT_EQ(e.reason.compare("something failed"), 0); - } catch (...) { - ASSERT_TRUE(false); - } -} - -void test_callback_stored_in_object() { - auto stringifier = std::make_shared(); - auto rust_stringifier = fixture_callbacks::RustStringifier::init(stringifier); - - for (auto num : {1, 2}) { - ASSERT_EQ(stringifier->from_simple_type(num), rust_stringifier->from_simple_type(num)); - } -} - -void test_void_callback_exceptions() { - auto callback = std::make_shared(); - auto rust_callback = fixture_callbacks::RustGetters::init(); - - try { - rust_callback->get_nothing(callback, "foo"); - } catch (...) { - ASSERT_TRUE(false); - } - - EXPECT_EXCEPTION(rust_callback->get_nothing(callback, "bad-argument"), fixture_callbacks::simple_error::BadArgument); - EXPECT_EXCEPTION(rust_callback->get_nothing(callback, "unexpected-error"), fixture_callbacks::simple_error::UnexpectedError); -} - -void test_callback_lifetime() { - auto stringifier = std::make_shared(); - auto rust_stringifier1 = fixture_callbacks::RustStringifier::init(stringifier); - { - auto rust_stringifier2 = fixture_callbacks::RustStringifier::init(stringifier); - ASSERT_EQ("C++: 123", rust_stringifier2->from_simple_type(123)); - } - ASSERT_EQ("C++: 123", rust_stringifier1->from_simple_type(123)); -} - -int main() { - test_callback_roundtrip(); - test_callback_roundtrip_errors(); - test_callback_stored_in_object(); - test_void_callback_exceptions(); - test_callback_lifetime(); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/geometry/main.cpp b/uniffi/cpp/cpp-tests/tests/geometry/main.cpp deleted file mode 100644 index 65c50f9cd..000000000 --- a/uniffi/cpp/cpp-tests/tests/geometry/main.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include - -#include - -int main() { - auto line1 = geometry::Line { - geometry::Point { 0.0, 0.0 }, - geometry::Point { 1.0, 2.0 } - }; - - auto line2 = geometry::Line { - geometry::Point { 1.0, 1.0 }, - geometry::Point { 2.0, 2.0 } - }; - - ASSERT_EQ(geometry::gradient(line1), 2.0); - ASSERT_EQ(geometry::gradient(line2), 1.0); - - auto point = geometry::Point { 0.0, 0.0 }; - auto intersection = geometry::intersection(line1, line2); - ASSERT_TRUE(intersection.has_value()); - auto intersection_value = intersection.value(); - ASSERT_EQ(intersection_value.coord_x, 0); - ASSERT_EQ(intersection_value.coord_y, 0); - - ASSERT_EQ(std::nullopt, geometry::intersection(line1, line1)); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/multilib/main.cpp b/uniffi/cpp/cpp-tests/tests/multilib/main.cpp deleted file mode 100644 index ce92b1de9..000000000 --- a/uniffi/cpp/cpp-tests/tests/multilib/main.cpp +++ /dev/null @@ -1,5 +0,0 @@ -#include -#include -#include - -int main() { return 0; } diff --git a/uniffi/cpp/cpp-tests/tests/namespaces/main.cpp b/uniffi/cpp/cpp-tests/tests/namespaces/main.cpp deleted file mode 100644 index bb3be83dd..000000000 --- a/uniffi/cpp/cpp-tests/tests/namespaces/main.cpp +++ /dev/null @@ -1,105 +0,0 @@ -// Two crates that each export `GroupConsumer`, `Frame`, `Priority`, and `GroupError`, where -// `media`'s types hold or refer to `net`'s. Generated with `error_style = "expected"`. -#include -#include - -namespace { - -std::shared_ptr net_group( - uint64_t sequence, - net::Priority priority, - std::vector> payloads -) { - std::vector frames; - for (auto &payload : payloads) { - frames.push_back(net::Frame{std::move(payload)}); - } - return net::GroupConsumer::init(sequence, priority, frames); -} - -bool is_net(const media::Priority &priority, net::Priority expected) { - auto *inner = std::get_if(&priority.get_variant()); - return inner && inner->priority == expected; -} - -bool is_realtime(const media::Priority &priority) { - return std::holds_alternative(priority.get_variant()); -} - -bool is_closed(const net::GroupError &error, uint32_t code) { - auto *closed = std::get_if(&error.get_variant()); - return closed && closed->code == code; -} - -void object_wraps_its_namesake() { - auto inner = net_group(3, net::Priority::kLow, {{1, 'a'}, {0, 'b'}}); - auto group = media::GroupConsumer::init(inner); - ASSERT_EQ(group->group()->sequence(), 3); - ASSERT_TRUE(is_net(group->priority(), net::Priority::kLow)); - - auto frame = group->read_frame(); - ASSERT_TRUE(frame && frame->raw.payload == (std::vector{1, 'a'})); - ASSERT_TRUE(frame->keyframe); - ASSERT_FALSE(group->read_frame()->keyframe); - - // Each layer's error, both named `GroupError`. - auto closed = group->read_frame(); - ASSERT_FALSE(closed); - auto *net_error = std::get_if(&closed.error().get_variant()); - ASSERT_TRUE(net_error && is_closed(net_error->source, 7)); - - auto empty = media::decode(net::Frame{{}}); - ASSERT_FALSE(empty); - ASSERT_TRUE(std::holds_alternative(empty.error().get_variant())); -} - -void async_returns_the_net_error() { - auto group = media::GroupConsumer::init(net_group(1, net::Priority::kHigh, {{1}})); - ASSERT_TRUE(is_realtime(group->priority())); - - auto frame = group->next_frame().get(); - ASSERT_TRUE(frame && frame->raw.payload == (std::vector{1})); - auto closed = group->next_frame().get(); - ASSERT_FALSE(closed); - ASSERT_TRUE(is_closed(closed.error(), 7)); -} - -void containers_of_both() { - auto frame = *media::decode(net::Frame{{0, 'z'}}); - ASSERT_TRUE(media::encode(frame).payload == (std::vector{0, 'z'})); - - auto frames = media::decode_all({net::Frame{{0, 'a'}}, net::Frame{{}}, net::Frame{{1, 'b'}}}); - ASSERT_EQ(frames.size(), 2); - ASSERT_FALSE(frames[0].keyframe); - ASSERT_TRUE(frames[1].keyframe); - - auto bounds = media::find_bounds(frames); - ASSERT_TRUE(bounds.keyframe.has_value()); - ASSERT_TRUE(bounds.keyframe->raw.payload == frames[1].raw.payload); - ASSERT_TRUE(bounds.last.has_value()); - ASSERT_TRUE(bounds.last->payload == (std::vector{1, 'b'})); - auto empty = media::find_bounds({}); - ASSERT_FALSE(empty.keyframe.has_value()); - ASSERT_FALSE(empty.last.has_value()); - - auto groups = media::wrap_all({ - net_group(1, net::Priority::kLow, {}), - net_group(2, net::Priority::kHigh, {}), - }); - ASSERT_EQ(groups.groups.size(), 2); - ASSERT_EQ(groups.groups[0]->group()->sequence(), 1); - ASSERT_EQ(groups.groups[1]->group()->sequence(), 2); - ASSERT_TRUE(groups.net.at(1) == net::Priority::kLow); - ASSERT_TRUE(groups.net.at(2) == net::Priority::kHigh); - ASSERT_TRUE(is_net(groups.media.at(1), net::Priority::kLow)); - ASSERT_TRUE(is_realtime(groups.media.at(2))); -} - -} // namespace - -int main() { - object_wraps_its_namesake(); - async_returns_the_net_error(); - containers_of_both(); - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/reserved_field_name/main.cpp b/uniffi/cpp/cpp-tests/tests/reserved_field_name/main.cpp deleted file mode 100644 index 4f803e6b0..000000000 --- a/uniffi/cpp/cpp-tests/tests/reserved_field_name/main.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "test_common.hpp" - -#include - -int main() { - reserved_field_name::Foo foo = {42, 42, 42}; - reserved_field_name::assert_fields_are_42(foo); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/rondpoint/main.cpp b/uniffi/cpp/cpp-tests/tests/rondpoint/main.cpp deleted file mode 100644 index 2fa9e13d7..000000000 --- a/uniffi/cpp/cpp-tests/tests/rondpoint/main.cpp +++ /dev/null @@ -1,225 +0,0 @@ -#include -#include - -#include -#include -#include - -template -void affirm_aller_retour(const T& c, const F& func, Args&& ...arg) { - auto fn = std::mem_fn(func); - for (auto&& arg : {std::forward(arg)...}) { - ASSERT_EQ(arg, fn(c, arg)); - } -} - -template -void affirm_enchaine(const T& c, const F& func, Args&& ...arg) { - auto fn = std::mem_fn(func); - for (auto&& arg : {std::forward(arg)...}) { - std::string arg_str = std::to_string(arg); - std::string ret_str = fn(c, arg); - - ASSERT_TRUE((arg_str == ret_str)); - } -} - -void test_copy() { - auto dict = rondpoint::Dictionnaire { - rondpoint::Enumeration::kDeux, - true, - 0, - 123456789u - }; - auto copied_dict = rondpoint::copie_dictionnaire(dict); - ASSERT_EQ(dict.un, copied_dict.un); - ASSERT_EQ(dict.deux, copied_dict.deux); - ASSERT_EQ(dict.petit_nombre, copied_dict.petit_nombre); - ASSERT_EQ(dict.gros_nombre, copied_dict.gros_nombre); - - auto list = std::vector { rondpoint::Enumeration::kUn, rondpoint::Enumeration::kDeux}; - auto copied_list = rondpoint::copie_enumerations(list); - ASSERT_EQ(list.size(), copied_list.size()); - ASSERT_TRUE(std::equal(list.begin(), list.end(), copied_list.begin())); - - auto map = std::unordered_map { - { "zero", rondpoint::EnumerationAvecDonnees::kZero {}}, - { "un", rondpoint::EnumerationAvecDonnees::kUn {2}}, - { "deux", rondpoint::EnumerationAvecDonnees::kDeux {1, "test"}} - }; - auto copied_map = rondpoint::copie_carte(map); - ASSERT_EQ(map.size(), copied_map.size()); - for (auto& [key, value] : map) { - ASSERT_EQ(value.get_variant().index(), copied_map.at(key).get_variant().index()); - auto v = value; - std::visit([&v](auto&& arg) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - } else if constexpr (std::is_same_v) { - ASSERT_EQ(2, arg.premier); - } else if constexpr (std::is_same_v) { - ASSERT_EQ(1, arg.premier); - ASSERT_EQ("test", arg.second); - } - }, value.get_variant()); - } - - ASSERT_TRUE(rondpoint::switcheroo(false)); -} - -void test_roundtrip() { - auto rt = rondpoint::Retourneur::init(); - - auto mean_value = 0x1234'5678'9123'4567; - - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_boolean, true, false); - - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_i8, std::numeric_limits::min(), std::numeric_limits::max(), (int8_t)mean_value); - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_u8, std::numeric_limits::min(), std::numeric_limits::max(), (uint8_t)mean_value); - - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_i16, std::numeric_limits::min(), std::numeric_limits::max(), (int16_t)mean_value); - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_u16, std::numeric_limits::min(), std::numeric_limits::max(), (uint16_t)mean_value); - - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_i32, std::numeric_limits::min(), std::numeric_limits::max(), (int32_t)mean_value); - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_u32, std::numeric_limits::min(), std::numeric_limits::max(), (uint32_t)mean_value); - - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_i64, std::numeric_limits::min(), std::numeric_limits::max(), (int64_t)mean_value); - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_u64, std::numeric_limits::min(), std::numeric_limits::max(), (uint64_t)mean_value); - - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_float, std::numeric_limits::min(), std::numeric_limits::max(), std::numeric_limits::epsilon()); - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_double, std::numeric_limits::min(), std::numeric_limits::max(), std::numeric_limits::epsilon()); - - affirm_aller_retour(rt, &rondpoint::Retourneur::identique_string, - "", - "abc", - "null\u0000byte", - "été", - "ښي لاس ته لوستلو لوستل", - "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama" - ); - - for (auto i : {-1, 0, 1}) { - auto nombres_signes = rondpoint::DictionnaireNombresSignes { - (int8_t)i, - (int16_t)i, - (int32_t)i, - (int64_t)i, - }; - auto ret = rt->identique_nombres_signes(nombres_signes); - - ASSERT_EQ(nombres_signes.petit_nombre, ret.petit_nombre); - ASSERT_EQ(nombres_signes.court_nombre, ret.court_nombre); - ASSERT_EQ(nombres_signes.nombre_simple, ret.nombre_simple); - ASSERT_EQ(nombres_signes.gros_nombre, ret.gros_nombre); - } - - for (auto i : {0, 1}) { - auto nombres = rondpoint::DictionnaireNombres { - (uint8_t)i, - (uint16_t)i, - (uint32_t)i, - (uint64_t)i, - }; - auto ret = rt->identique_nombres(nombres); - - ASSERT_EQ(nombres.petit_nombre, ret.petit_nombre); - ASSERT_EQ(nombres.court_nombre, ret.court_nombre); - ASSERT_EQ(nombres.nombre_simple, ret.nombre_simple); - ASSERT_EQ(nombres.gros_nombre, ret.gros_nombre); - } -} - -void test_stringifier() { - auto st = rondpoint::Stringifier::init(); - - auto mean_value = 0x1234'5678'9123'4567; - - ASSERT_EQ("uniffi 💚 cpp!", st->well_known_string("cpp")); - - // to_string doesn't work on booleans - ASSERT_EQ("true", st->to_string_boolean(true)); - ASSERT_EQ("false", st->to_string_boolean(false)); - - affirm_enchaine(st, &rondpoint::Stringifier::to_string_i8, std::numeric_limits::min(), std::numeric_limits::max(), (int8_t)mean_value); - affirm_enchaine(st, &rondpoint::Stringifier::to_string_u8, std::numeric_limits::min(), std::numeric_limits::max(), (uint8_t)mean_value); - - affirm_enchaine(st, &rondpoint::Stringifier::to_string_i16, std::numeric_limits::min(), std::numeric_limits::max(), (int16_t)mean_value); - affirm_enchaine(st, &rondpoint::Stringifier::to_string_u16, std::numeric_limits::min(), std::numeric_limits::max(), (uint16_t)mean_value); - - affirm_enchaine(st, &rondpoint::Stringifier::to_string_i32, std::numeric_limits::min(), std::numeric_limits::max(), (int32_t)mean_value); - affirm_enchaine(st, &rondpoint::Stringifier::to_string_u32, std::numeric_limits::min(), std::numeric_limits::max(), (uint32_t)mean_value); - - affirm_enchaine(st, &rondpoint::Stringifier::to_string_i64, std::numeric_limits::min(), std::numeric_limits::max(), (int64_t)mean_value); - affirm_enchaine(st, &rondpoint::Stringifier::to_string_u64, std::numeric_limits::min(), std::numeric_limits::max(), (uint64_t)mean_value); - - for (float f : {std::numeric_limits::min(), std::numeric_limits::max(), std::numeric_limits::epsilon()}) { - ASSERT_TRUE((std::abs(f - std::stof(st->to_string_float(f))) <= std::numeric_limits::epsilon())); - } - - for (double d : {std::numeric_limits::min(), std::numeric_limits::max(), std::numeric_limits::epsilon()}) { - ASSERT_TRUE((std::abs(d - std::stod(st->to_string_double(d))) <= std::numeric_limits::epsilon())); - } -} - -void test_default_parameter_literals_in_record() { - auto default_dict = rondpoint::OptionneurDictionnaire {}; - ASSERT_EQ(default_dict.i8_var, -8); - ASSERT_EQ(default_dict.u8_var, 8); - ASSERT_EQ(default_dict.i16_var, -16); - ASSERT_EQ(default_dict.u16_var, 0x10); - ASSERT_EQ(default_dict.i32_var, -32); - ASSERT_EQ(default_dict.u32_var, 32); - ASSERT_EQ(default_dict.i64_var, -64); - ASSERT_EQ(default_dict.u64_var, 64); - ASSERT_EQ(default_dict.float_var, 4.0f); - ASSERT_EQ(default_dict.double_var, 8.0); - ASSERT_EQ(default_dict.boolean_var, true); - ASSERT_EQ(default_dict.string_var, "default"); - ASSERT_EQ(default_dict.list_var, std::vector{}); - ASSERT_EQ(default_dict.enumeration_var, rondpoint::Enumeration::kDeux); - ASSERT_EQ(default_dict.dictionnaire_var, std::nullopt); - - auto rt = rondpoint::Retourneur::init(); - auto dict = rondpoint::OptionneurDictionnaire { - -8, - 8, - -16, - 0x10, - -32, - 32, - -64, - 64, - 4.0f, - 8.0, - true, - "default", - std::vector{}, - rondpoint::Enumeration::kDeux, - std::nullopt - }; - auto copied_dict = rt->identique_optionneur_dictionnaire(dict); - ASSERT_EQ(dict.i8_var, copied_dict.i8_var); - ASSERT_EQ(dict.u8_var, copied_dict.u8_var); - ASSERT_EQ(dict.i16_var, copied_dict.i16_var); - ASSERT_EQ(dict.u16_var, copied_dict.u16_var); - ASSERT_EQ(dict.i32_var, copied_dict.i32_var); - ASSERT_EQ(dict.u32_var, copied_dict.u32_var); - ASSERT_EQ(dict.i64_var, copied_dict.i64_var); - ASSERT_EQ(dict.u64_var, copied_dict.u64_var); - ASSERT_EQ(dict.float_var, copied_dict.float_var); - ASSERT_EQ(dict.double_var, copied_dict.double_var); - ASSERT_EQ(dict.boolean_var, copied_dict.boolean_var); - ASSERT_EQ(dict.string_var, copied_dict.string_var); - ASSERT_EQ(dict.list_var, copied_dict.list_var); - ASSERT_EQ(dict.enumeration_var, copied_dict.enumeration_var); - ASSERT_EQ(dict.dictionnaire_var, copied_dict.dictionnaire_var); -} - -int main() { - test_copy(); - test_roundtrip(); - test_stringifier(); - test_default_parameter_literals_in_record(); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/sprites/main.cpp b/uniffi/cpp/cpp-tests/tests/sprites/main.cpp deleted file mode 100644 index 20454ec83..000000000 --- a/uniffi/cpp/cpp-tests/tests/sprites/main.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include - -#include - -int main() { - auto sprite = sprites::Sprite::init(std::nullopt); - ASSERT_EQ(sprite->get_position().x, 0.0); - ASSERT_EQ(sprite->get_position().y, 0.0); - - auto s = sprites::Sprite::init(sprites::Point { 1.0, 2.0 }); - ASSERT_EQ(s->get_position().x, 1.0); - ASSERT_EQ(s->get_position().y, 2.0); - - s->move_to(sprites::Point { 3.0, 4.0 }); - ASSERT_EQ(s->get_position().x, 3.0); - ASSERT_EQ(s->get_position().y, 4.0); - - s->move_by(sprites::Vector { -4.0, 2.0 }); - ASSERT_EQ(s->get_position().x, -1.0); - ASSERT_EQ(s->get_position().y, 6.0); - - auto rel = sprites::Sprite::new_relative_to(sprites::Point {0.0, 1.0}, sprites::Vector { 1.0, 1.5}); - ASSERT_EQ(rel->get_position().x, 1.0); - ASSERT_EQ(rel->get_position().y, 2.5); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/todolist/main.cpp b/uniffi/cpp/cpp-tests/tests/todolist/main.cpp deleted file mode 100644 index 0133b2886..000000000 --- a/uniffi/cpp/cpp-tests/tests/todolist/main.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include - -#include - -bool compare_lists(std::vector a, std::vector b) { - if (a.size() != b.size()) { - return false; - } - - for (size_t i = 0; i < a.size(); ++i) { - if (a[i].text.compare(b[i].text) != 0) { - return false; - } - } - - return true; -} - -int main() { - auto todo = todolist::TodoList::init(); - - EXPECT_EXCEPTION(todo->get_last(), todolist::TodoError); - EXPECT_EXCEPTION(todolist::create_entry_with(""), todolist::todo_error::EmptyString); - - todo->add_item("Write test"); - ASSERT_EQ("Write test", todo->get_last()); - - todo->add_item("Write test 2"); - ASSERT_EQ("Write test 2", todo->get_last()); - - auto entry = todolist::create_entry_with("Write test with entry"); - todo->add_entry(entry); - ASSERT_EQ("Write test with entry", todo->get_last()); - ASSERT_EQ("Write test with entry", todo->get_last_entry().text); - - todo->add_item("Test Ünicode hàndling without an entry 🤣"); - ASSERT_EQ("Test Ünicode hàndling without an entry 🤣", todo->get_last()); - - auto entry2 = todolist::create_entry_with("Test Ünicode hàndling with an entry 🤣"); - todo->add_entry(entry2); - ASSERT_EQ("Test Ünicode hàndling with an entry 🤣", todo->get_last()); - ASSERT_EQ(5, todo->get_entries().size()); - - todo->add_entries({ todolist::create_entry_with("List entry 1"), todolist::create_entry_with("List entry 2") }); - ASSERT_EQ(7, todo->get_entries().size()); - ASSERT_EQ("List entry 2", todo->get_last_entry().text); - - todo->add_items({"List 1", "List 2"}); - ASSERT_EQ(9, todo->get_entries().size()); - ASSERT_EQ("List 1", todo->get_items()[7]); - - ASSERT_EQ(nullptr, todolist::get_default_list()); - - auto todo2 = todolist::TodoList::init(); - { - todolist::set_default_list(todo); - auto default_list = todolist::get_default_list(); - ASSERT_TRUE(default_list); - - ASSERT_TRUE(compare_lists(todo->get_entries(), default_list->get_entries())); - ASSERT_FALSE(compare_lists(todo2->get_entries(), default_list->get_entries())); - } - - { - todo2->make_default(); - auto default_list = todolist::get_default_list(); - - ASSERT_FALSE(compare_lists(todo->get_entries(), default_list->get_entries())); - ASSERT_TRUE(compare_lists(todo2->get_entries(), default_list->get_entries())); - } - - todo->add_item("Entry after default list change"); - ASSERT_EQ("Entry after default list change", todo->get_last()); - - todo2->add_item("New default entry"); - ASSERT_EQ("New default entry", todolist::get_default_list()->get_last()); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/trait_methods/main.cpp b/uniffi/cpp/cpp-tests/tests/trait_methods/main.cpp deleted file mode 100644 index 491877001..000000000 --- a/uniffi/cpp/cpp-tests/tests/trait_methods/main.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include "test_common.hpp" - -#include - -void test_trait_methods() { - auto trait = trait_methods::TraitMethods::init("trait1"); - ASSERT_EQ(trait->to_string(), "TraitMethods(trait1)"); - ASSERT_EQ(trait->to_debug_string(), "TraitMethods { val: \"trait1\" }"); - ASSERT_EQ(trait->hash(), 8148112548604738188); - - auto ptr_copy = trait; - auto trait_copy = trait_methods::TraitMethods::init("trait1"); - ASSERT_EQ(trait->to_string(), trait_copy->to_string()); - ASSERT_EQ(trait->to_debug_string(), trait_copy->to_debug_string()); - ASSERT_EQ(trait->hash(), trait_copy->hash()); - - // Two different shared ptr's should differ - ASSERT_NE(trait, trait_copy); - - // Two shared ptr's pointing to the same object should be equal - ASSERT_EQ(trait, ptr_copy); - - // Internal equality check should work - ASSERT_TRUE(trait->eq(trait_copy)); - ASSERT_FALSE(trait->ne(trait_copy)); - - auto trait2 = trait_methods::TraitMethods::init("trait2"); - ASSERT_NE(trait, trait2); - ASSERT_FALSE(trait->eq(trait2)); - ASSERT_TRUE(trait->ne(trait2)); - - ASSERT_NE(trait->hash(), trait2->hash()); - ASSERT_NE(trait->to_string(), trait2->to_string()); - ASSERT_NE(trait->to_debug_string(), trait2->to_debug_string()); -} - -void test_proc_methods() { - auto trait = trait_methods::ProcTraitMethods::init("trait1"); - ASSERT_EQ(trait->to_string(), "ProcTraitMethods(trait1)"); - ASSERT_EQ(trait->to_debug_string(), "ProcTraitMethods { val: \"trait1\" }"); - ASSERT_EQ(trait->hash(), 8148112548604738188); - - auto ptr_copy = trait; - auto trait_copy = trait_methods::ProcTraitMethods::init("trait1"); - ASSERT_EQ(trait->to_string(), trait_copy->to_string()); - ASSERT_EQ(trait->to_debug_string(), trait_copy->to_debug_string()); - ASSERT_EQ(trait->hash(), trait_copy->hash()); - - // Two different shared ptr's should differ - ASSERT_NE(trait, trait_copy); - - // Two shared ptr's pointing to the same object should be equal - ASSERT_EQ(trait, ptr_copy); - - // Internal equality check should work - ASSERT_TRUE(trait->eq(trait_copy)); - ASSERT_FALSE(trait->ne(trait_copy)); - - auto trait2 = trait_methods::ProcTraitMethods::init("trait2"); - ASSERT_NE(trait, trait2); - ASSERT_FALSE(trait->eq(trait2)); - ASSERT_TRUE(trait->ne(trait2)); - - ASSERT_NE(trait->hash(), trait2->hash()); - ASSERT_NE(trait->to_string(), trait2->to_string()); - ASSERT_NE(trait->to_debug_string(), trait2->to_debug_string()); -} - -void test_enum_methods() { - auto s = trait_methods::TraitEnum(trait_methods::TraitEnum::kS{"s1"}); - ASSERT_EQ(s.to_string(), "TraitEnum::S(\"s1\")"); - ASSERT_EQ(s.to_debug_string(), "S(\"s1\")"); - - auto i = trait_methods::TraitEnum(trait_methods::TraitEnum::kI{7}); - ASSERT_EQ(i.to_string(), "TraitEnum::I(7)"); -} - -int main() { - test_trait_methods(); - test_proc_methods(); - test_enum_methods(); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/traits/main.cpp b/uniffi/cpp/cpp-tests/tests/traits/main.cpp deleted file mode 100644 index 9d1d68288..000000000 --- a/uniffi/cpp/cpp-tests/tests/traits/main.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include - -#include - -struct CppButton : public traits::Button { - public: - virtual std::string name() override { - return "C++ Button"; - } -}; - -int main() { - auto buttons = traits::get_buttons(); - auto expected_names = {"go", "stop"}; - - for (auto button : buttons) { - auto name = button->name(); - - ASSERT_TRUE(std::find(expected_names.begin(), expected_names.end(), name) != expected_names.end()); - ASSERT_EQ(traits::press(button)->name(), name); - } - - auto native_button = std::make_shared(); - ASSERT_EQ(traits::press(native_button)->name(), "C++ Button"); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/type_flattening/main.cpp b/uniffi/cpp/cpp-tests/tests/type_flattening/main.cpp deleted file mode 100644 index 7069da34a..000000000 --- a/uniffi/cpp/cpp-tests/tests/type_flattening/main.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "test_common.hpp" - -#include - -int main() { - int value = 42; - - auto structure = type_flattening::get_struct(value); - ASSERT_NE(structure.optional_arc, nullptr); - ASSERT_EQ(structure.optional_arc->get_value(), value); - - auto roundtrip = type_flattening::struct_roundtrip(structure); - ASSERT_NE(roundtrip.optional_arc, nullptr); - ASSERT_EQ(roundtrip.optional_arc->get_value(), value); - - return 0; -} diff --git a/uniffi/cpp/cpp-tests/tests/uniffi_docstring/main.cpp b/uniffi/cpp/cpp-tests/tests/uniffi_docstring/main.cpp deleted file mode 100644 index 1e17f4c20..000000000 --- a/uniffi/cpp/cpp-tests/tests/uniffi_docstring/main.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include "test_common.hpp" - -#include -#include - -#include - -const std::vector expected_docstrings = { - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", -}; - -int main() { - auto stream = std::ifstream(UNIFFI_BINDING_DIR "/uniffi_docstring.hpp"); - ASSERT_TRUE(stream.is_open()); - - auto source = std::string(std::istreambuf_iterator(stream), std::istreambuf_iterator()); - ASSERT_FALSE(source.empty()); - - std::regex docstring_reg("\\*\\s(\\<[\\s\\S]*?\\>)"); - std::smatch match; - std::vector extracted_docstrings; - - while (std::regex_search(source, match, docstring_reg)) { - if (match.size() >= 2) { - extracted_docstrings.push_back(match[1].str()); - } - source = match.suffix().str(); - } - - for (const auto& docstring : expected_docstrings) { - if (std::find(extracted_docstrings.begin(), extracted_docstrings.end(), docstring) == extracted_docstrings.end()) { - std::cerr << "Could not find expected docstring: " << docstring << std::endl; - ASSERT_TRUE(false); - } - } - - for (const auto& docstring : extracted_docstrings) { - if (std::find(expected_docstrings.begin(), expected_docstrings.end(), docstring) == expected_docstrings.end()) { - std::cerr << "Unexpected docstring found: " << docstring << std::endl; - ASSERT_TRUE(false); - } - } - - return 0; -} diff --git a/uniffi/cpp/docs/CONFIGURATION.md b/uniffi/cpp/docs/CONFIGURATION.md deleted file mode 100644 index 7e3142186..000000000 --- a/uniffi/cpp/docs/CONFIGURATION.md +++ /dev/null @@ -1,78 +0,0 @@ -# Configuration options - -It's possible to configure some settings by passing `--config` argument to the generator. All -configuration keys are defined in `bindings.cpp` section. - -```bash -uniffi-bindgen-cpp path/to/definitions.udl --config path/to/uniffi.toml -``` - -- `custom_types` - properties for custom type defined in UDL with `[Custom] typedef string Url;`. - - ```toml - # Represent MyString as a C++ native `CustomString` class. The underlying type of MyString is a string. - [bindings.cpp.custom_types.MyString] - imports = ["CustomString.hpp"] - type_name = "CustomString" - into_custom = "CustomString({})" - from_custom = "{}.to_string()" - ``` - - - `imports` (optional) - any imports required to satisfy this type. - - - `type_name` (optional) - the name to represent the type in generated bindings. Default is the - type alias name from UDL, e.g. `Url`. - - - `into_custom` (required) - an expression to convert from the underlying type into custom type. `{}` will - will be expanded into variable containing the underlying value. The expression is used in a - return statement, i.e. `return ;`. - - - `from_custom` (required) - an expression to convert from the custom type into underlying type. `{}` will - will be expanded into variable containing the custom value. The expression is used in a - return statement, i.e. `return `. - -- `enum_style` - style for enum variant naming, possible options are: - - `"Capitalized"` - producing enum variants named `ENUM_VARIANT` - - `"Google"` - producing enum variants name `kEnumVariant` (default) - -- `error_style` - how a Rust `Result` error reaches C++, possible options are: - - `"exceptions"` - throw the error (default). Generation fails if the component has an async - function, constructor, or method. - - `"expected"` - return it, and never throw, so the bindings build with `-fno-exceptions` - -- `strip_type_prefix` - a prefix to drop from type names, for crates that prefix their exported - types to keep them unique in languages without namespaces. With `strip_type_prefix = "Foo"`, the - records, objects, enums, and callback interfaces `FooClient` and `FooError` become - `Client` and `Error`. A name continues only after an uppercase letter, so `Foobar` stays as is, - and custom types keep their names. Generation fails if a stripped name is already a type. - - ```toml - [bindings.cpp] - strip_type_prefix = "Foo" - ``` - -### `error_style = "expected"` - -A fallible function returns `uniffi::expected`, and an async one returns -`uniffi::Future` whose `get()` and `then()` continuation deliver the same `expected`. An -infallible async function returns `uniffi::Future`, which delivers a plain `T`. -`uniffi::expected` is a bundled [`tl::expected`](https://github.com/TartanLlama/expected), written -next to the bindings as `uniffi_expected.hpp`. It is never `std::expected`, even at C++23, so -generated sources built at one standard link with code built at another. With exceptions disabled, -`value()` on an error aborts with a message. - -Error enums are plain values rather than exception classes: every error enum becomes a struct -holding a `std::variant` of its variants, like any other enum with fields. A flat error -(`#[uniffi(flat_error)]`, or a UDL `[Error] enum`) gives each variant a -`message` field holding the Rust `Display` text. - -Failures that have no error value abort with a message on `stderr` instead of throwing: a Rust -panic, a contract or checksum mismatch, an unknown enum variant, consuming a future twice, and -misusing the dispatcher. Cancelling a future or dropping it abandons it: its continuation never -runs, and a later `get()` on it aborts. A dispatcher that rejects a task abandons the future the -same way, so the default dispatcher's queue is unbounded under this style; after -`shutdown_async_dispatcher()` every pending future is abandoned. - -Callback interfaces and trait interfaces implemented in C++ are not supported yet under this style, -and generation fails if the component declares one. - diff --git a/uniffi/cpp/fixtures/Cargo.toml b/uniffi/cpp/fixtures/Cargo.toml deleted file mode 100644 index 3d8db3444..000000000 --- a/uniffi/cpp/fixtures/Cargo.toml +++ /dev/null @@ -1,38 +0,0 @@ -[package] -name = "uniffi-bindgen-cpp-fixtures" -version = "1.0.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["cdylib", "lib", "staticlib"] - -[dependencies] -uniffi = { workspace = true } -uniffi-example-arithmetic = { path = "../../examples/arithmetic" } -uniffi-example-callbacks = { path = "../../examples/callbacks" } -uniffi-example-custom-types = { path = "../../examples/custom-types" } -uniffi-example-geometry = { path = "../../examples/geometry" } -uniffi-example-rondpoint = { path = "../../examples/rondpoint" } -uniffi-example-sprites = { path = "../../examples/sprites" } -uniffi-example-todolist = { path = "../../examples/todolist" } -uniffi-example-traits = { path = "../../examples/traits" } -uniffi-fixture-callbacks = { path = "../../fixtures/callbacks" } -uniffi-fixture-coverall = { path = "../../fixtures/coverall" } -uniffi-fixture-docstring = { path = "../../fixtures/docstring" } -uniffi-fixture-time = { path = "../../fixtures/uniffi-fixture-time" } -uniffi-fixture-trait-methods = { path = "../../fixtures/trait-methods" } -uniffi-fixture-namespaces-media = { path = "../../fixtures/namespaces/media" } -uniffi-fixture-namespaces-net = { path = "../../fixtures/namespaces/net" } - -uniffi-async-calls = { path = "async-calls" } -uniffi-c-api = { path = "c-api" } -uniffi-error-types-builtin = { path = "error-types-builtin" } -uniffi-custom-types-builtin = { path = "custom-types-builtin" } -uniffi-enum-style-test = { path = "enum-style-test" } -uniffi-empty-type = { path = "empty-type" } -uniffi-reserved-field-name = { path = "reserved-field-name" } -uniffi-type-flattening = { path = "type-flattening" } - -uniffi-ext-types-export = { path = "ext-types-export" } -uniffi-ext-types-import = { path = "ext-types-import" } diff --git a/uniffi/cpp/fixtures/async-calls/Cargo.toml b/uniffi/cpp/fixtures/async-calls/Cargo.toml deleted file mode 100644 index e03383d3c..000000000 --- a/uniffi/cpp/fixtures/async-calls/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "uniffi-async-calls" -version = "0.21.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "uniffi_fixture_async_calls" -crate-type = ["lib"] - -[dependencies] -once_cell = "1.18.0" -futures-timer = "3.0" -thiserror = "1.0" -tokio = { version = "1.24.1", features = ["time", "sync"] } -uniffi = { workspace = true, features = ["tokio"] } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/uniffi/cpp/fixtures/async-calls/README.md b/uniffi/cpp/fixtures/async-calls/README.md deleted file mode 100644 index 368a5f5e7..000000000 --- a/uniffi/cpp/fixtures/async-calls/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Async calls fixture - -This fixture is adapted from the MPL-2.0 licensed -[`async-calls` fixture](https://github.com/jhugman/uniffi-bindgen-react-native/tree/main/fixtures/async-calls) -in `uniffi-bindgen-react-native`. - -The public async cases are retained, including the hybrid UDL/proc-macro API, functions, -constructors, object methods, records, optional objects, errors, and timeouts. The adaptation: - -- uses `futures-timer` in place of the upstream repository's private timer service; -- includes only the native shared-resource implementation needed by the C++ tests; and -- exports the upstream `void` function as `void_return`, since `void` is a C++ keyword. diff --git a/uniffi/cpp/fixtures/async-calls/build.rs b/uniffi/cpp/fixtures/async-calls/build.rs deleted file mode 100644 index 9a673b0b8..000000000 --- a/uniffi/cpp/fixtures/async-calls/build.rs +++ /dev/null @@ -1,9 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -fn main() { - uniffi::generate_scaffolding("src/async-calls.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/async-calls/src/async-calls.udl b/uniffi/cpp/fixtures/async-calls/src/async-calls.udl deleted file mode 100644 index e56738607..000000000 --- a/uniffi/cpp/fixtures/async-calls/src/async-calls.udl +++ /dev/null @@ -1,15 +0,0 @@ -namespace futures { - [Async] - boolean always_ready(); -}; - -interface UdlMegaphone { - [Async] - constructor(); - - [Async, Name="secondary"] - constructor(); - - [Async] - string say_after(u16 ms, string who); -}; diff --git a/uniffi/cpp/fixtures/async-calls/src/lib.rs b/uniffi/cpp/fixtures/async-calls/src/lib.rs deleted file mode 100644 index ae3829611..000000000 --- a/uniffi/cpp/fixtures/async-calls/src/lib.rs +++ /dev/null @@ -1,177 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -mod platform_specific; -use platform_specific::acquire_with_timeout; - -use futures_timer::Delay; -use std::{sync::Arc, time::Duration}; - -#[uniffi::export] -pub fn greet(who: String) -> String { - format!("Hello, {who}") -} - -pub async fn always_ready() -> bool { - true -} - -#[uniffi::export] -pub async fn void_return() {} - -#[uniffi::export] -pub async fn say() -> String { - Delay::new(Duration::from_secs(2)).await; - "Hello, Future!".to_string() -} - -#[uniffi::export] -pub async fn say_after(ms: u16, who: String) -> String { - Delay::new(Duration::from_millis(ms.into())).await; - format!("Hello, {who}!") -} - -#[uniffi::export] -pub async fn sleep(ms: u16) -> bool { - Delay::new(Duration::from_millis(ms.into())).await; - true -} - -#[uniffi::export] -pub async fn sleep_no_return(ms: u16) { - Delay::new(Duration::from_millis(ms.into())).await; -} - -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum MyError { - #[error("Foo")] - Foo, -} - -#[uniffi::export] -pub async fn fallible_me(do_fail: bool) -> Result { - if do_fail { - Err(MyError::Foo) - } else { - Ok(42) - } -} - -#[uniffi::export] -pub async fn fallible_struct(do_fail: bool) -> Result, MyError> { - if do_fail { - Err(MyError::Foo) - } else { - Ok(new_megaphone()) - } -} - -#[uniffi::export] -pub fn new_megaphone() -> Arc { - Arc::new(Megaphone) -} - -#[uniffi::export] -pub async fn async_new_megaphone() -> Arc { - new_megaphone() -} - -#[uniffi::export] -pub async fn async_maybe_new_megaphone(value: bool) -> Option> { - value.then(new_megaphone) -} - -#[uniffi::export] -pub async fn say_after_with_megaphone(megaphone: Arc, ms: u16, who: String) -> String { - megaphone.say_after(ms, who).await -} - -#[derive(uniffi::Object)] -pub struct Megaphone; - -#[uniffi::export] -impl Megaphone { - #[uniffi::constructor] - pub async fn new() -> Arc { - Delay::new(Duration::from_millis(0)).await; - Arc::new(Self) - } - - #[uniffi::constructor] - pub async fn secondary() -> Arc { - Delay::new(Duration::from_millis(0)).await; - Arc::new(Self) - } - - pub async fn say_after(self: Arc, ms: u16, who: String) -> String { - say_after(ms, who).await.to_uppercase() - } - - pub async fn silence(&self) -> String { - String::new() - } - - pub async fn fallible_me(self: Arc, do_fail: bool) -> Result { - fallible_me(do_fail).await - } -} - -#[derive(uniffi::Object)] -pub struct FallibleMegaphone; - -#[uniffi::export] -impl FallibleMegaphone { - #[uniffi::constructor] - pub async fn new() -> Result, MyError> { - Err(MyError::Foo) - } -} - -pub struct UdlMegaphone; - -impl UdlMegaphone { - pub async fn new() -> Self { - Self - } - - pub async fn secondary() -> Self { - Self - } - - pub async fn say_after(self: Arc, ms: u16, who: String) -> String { - say_after(ms, who).await.to_uppercase() - } -} - -#[derive(uniffi::Record)] -pub struct MyRecord { - pub a: String, - pub b: u32, -} - -#[uniffi::export] -pub async fn new_my_record(a: String, b: u32) -> MyRecord { - MyRecord { a, b } -} - -#[derive(uniffi::Record)] -pub struct SharedResourceOptions { - pub release_after_ms: u16, - pub timeout_ms: u16, -} - -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum AsyncError { - #[error("Timeout")] - Timeout, -} - -#[uniffi::export(async_runtime = "tokio")] -pub async fn use_shared_resource(options: SharedResourceOptions) -> Result<(), AsyncError> { - acquire_with_timeout(options).await -} - -uniffi::include_scaffolding!("async-calls"); diff --git a/uniffi/cpp/fixtures/async-calls/src/platform_specific/mod.rs b/uniffi/cpp/fixtures/async-calls/src/platform_specific/mod.rs deleted file mode 100644 index 226fa5149..000000000 --- a/uniffi/cpp/fixtures/async-calls/src/platform_specific/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -mod native; -pub(crate) use native::*; diff --git a/uniffi/cpp/fixtures/async-calls/src/platform_specific/native.rs b/uniffi/cpp/fixtures/async-calls/src/platform_specific/native.rs deleted file mode 100644 index 975086909..000000000 --- a/uniffi/cpp/fixtures/async-calls/src/platform_specific/native.rs +++ /dev/null @@ -1,29 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -use std::time::Duration; - -use crate::{AsyncError, SharedResourceOptions}; - -pub(crate) async fn acquire_with_timeout(options: SharedResourceOptions) -> Result<(), AsyncError> { - use once_cell::sync::Lazy; - use tokio::{ - sync::Mutex, - time::{sleep, timeout}, - }; - - static MUTEX: Lazy> = Lazy::new(|| Mutex::new(())); - - let _guard = timeout( - Duration::from_millis(options.timeout_ms.into()), - MUTEX.lock(), - ) - .await - .map_err(|_| AsyncError::Timeout)?; - - sleep(Duration::from_millis(options.release_after_ms.into())).await; - Ok(()) -} diff --git a/uniffi/cpp/fixtures/c-api/Cargo.toml b/uniffi/cpp/fixtures/c-api/Cargo.toml deleted file mode 100644 index 2959e8fa6..000000000 --- a/uniffi/cpp/fixtures/c-api/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "uniffi-c-api" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -crate-type = ["lib"] -name = "uniffi_c_api" - -[dependencies] -thiserror = "1.0" -uniffi = { workspace = true } diff --git a/uniffi/cpp/fixtures/c-api/src/lib.rs b/uniffi/cpp/fixtures/c-api/src/lib.rs deleted file mode 100644 index 29317a35c..000000000 --- a/uniffi/cpp/fixtures/c-api/src/lib.rs +++ /dev/null @@ -1,366 +0,0 @@ -//! Every construct the C backend renders: objects, records with defaults, flat and data -//! enums, errors with and without `Display`, bytes, optionals, lists, maps, and async calls -//! that complete, fail, or stay pending until cancelled. - -use std::{ - collections::{HashMap, VecDeque}, - future::Future, - pin::Pin, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, Mutex, - }, - task::{Context, Poll, Waker}, -}; - -uniffi::setup_scaffolding!("capi"); - -/// A primary color. -#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)] -pub enum CapiColor { - Red, - Green, - Blue, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Record)] -pub struct CapiPoint { - pub x: i32, - pub y: i32, -} - -/// A shape, with data on some variants. -#[derive(Clone, Debug, PartialEq, uniffi::Enum)] -pub enum CapiShape { - Dot, - Circle { radius: f64 }, - Label(String), - Path { points: Vec }, -} - -/// One item, with a field of every kind. -#[derive(Clone, uniffi::Record)] -pub struct CapiItem { - pub name: String, - #[uniffi(default = 7)] - pub count: u32, - #[uniffi(default = "untitled \"draft\"")] - pub title: String, - #[uniffi(default = 1.5)] - pub scale: f64, - #[uniffi(default = true)] - pub visible: bool, - #[uniffi(default = -3)] - pub offset: i64, - #[uniffi(default = None)] - pub note: Option, - #[uniffi(default = None)] - pub limit: Option, - #[uniffi(default = None)] - pub tint: Option, - #[uniffi(default = None)] - pub target: Option, - #[uniffi(default = None)] - pub extra: Option>, - #[uniffi(default = None)] - pub owner: Option>, - #[uniffi(default = [])] - pub tags: Vec, - pub payload: Vec, - pub origin: CapiPoint, - pub color: CapiColor, - pub shape: CapiShape, - pub labels: HashMap, - pub points: HashMap, - pub values: Vec, - pub maybes: Vec>, -} - -/// What `CapiStore::stats` returns: the C type and method spell the same words. -#[derive(Clone, uniffi::Record)] -pub struct CapiStoreStats { - pub items: u64, - pub queued: u64, -} - -#[derive(Debug, thiserror::Error, uniffi::Error)] -#[uniffi::export(Display)] -pub enum CapiError { - #[error("not found")] - NotFound, - #[error("invalid: {0}")] - Invalid(String), - #[error("code {code} at {},{}", at.x, at.y)] - Code { code: u32, at: CapiPoint }, -} - -/// Variants carry only their message. -#[derive(Debug, thiserror::Error, uniffi::Error)] -#[uniffi(flat_error)] -pub enum CapiFlatError { - #[error("busy: {0}")] - Busy(String), - #[error("gone")] - Gone, -} - -#[derive(Default)] -struct Queue { - values: VecDeque, - wakers: Vec, - closed: bool, -} - -/// A named list of items, plus a queue that async readers wait on. -#[derive(uniffi::Object)] -pub struct CapiStore { - name: String, - items: Mutex>, - queue: Mutex, -} - -#[uniffi::export] -impl CapiStore { - #[uniffi::constructor] - pub fn new(name: String) -> Arc { - Self::with_items(name, Vec::new()) - } - - #[uniffi::constructor] - pub fn with_items(name: String, items: Vec) -> Arc { - Arc::new(Self { - name, - items: Mutex::new(items), - queue: Mutex::default(), - }) - } - - /// Fails on an empty name. - #[uniffi::constructor] - pub fn open(name: String) -> Result, CapiError> { - if name.is_empty() { - return Err(CapiError::Invalid("empty name".into())); - } - Ok(Self::new(name)) - } - - pub fn name(&self) -> String { - self.name.clone() - } - - #[allow( - clippy::len_without_is_empty, - reason = "the fixture exports only the C API under test" - )] - pub fn len(&self) -> u64 { - self.items.lock().unwrap().len() as u64 - } - - /// Returns the new item's index, or fails on an empty name. - pub fn add(&self, item: CapiItem) -> Result { - if item.name.is_empty() { - return Err(CapiError::Invalid("empty item name".into())); - } - let mut items = self.items.lock().unwrap(); - items.push(item); - Ok(items.len() as u32 - 1) - } - - pub fn get(&self, index: u32) -> Result { - self.items - .lock() - .unwrap() - .get(index as usize) - .cloned() - .ok_or(CapiError::Code { - code: index, - at: CapiPoint { x: 1, y: 2 }, - }) - } - - pub fn find(&self, name: String) -> Option { - self.items - .lock() - .unwrap() - .iter() - .find(|item| item.name == name) - .cloned() - } - - pub fn note(&self, index: u32) -> Option { - self.items.lock().unwrap().get(index as usize)?.note.clone() - } - - pub fn limit(&self, index: u32) -> Option { - self.items.lock().unwrap().get(index as usize)?.limit - } - - pub fn stats(&self) -> CapiStoreStats { - CapiStoreStats { - items: self.len(), - queued: self.queue.lock().unwrap().values.len() as u64, - } - } - - pub fn names(&self) -> Vec { - self.items - .lock() - .unwrap() - .iter() - .map(|item| item.name.clone()) - .collect() - } - - pub fn clear(&self) { - self.items.lock().unwrap().clear(); - } - - /// A new store with the same items, named `name` or this store's name. - pub fn fork(&self, name: Option) -> Arc { - Self::with_items( - name.unwrap_or_else(|| self.name.clone()), - self.items.lock().unwrap().clone(), - ) - } - - /// The total number of items in this store, `other`, and `extra`. - pub fn total(&self, other: Arc, extra: Option>) -> u64 { - self.len() + other.len() + extra.map_or(0, |extra| extra.len()) - } - - /// Wakes one `next` call with `value`. - pub fn push(&self, value: u64) { - let mut queue = self.queue.lock().unwrap(); - queue.values.push_back(value); - for waker in queue.wakers.drain(..) { - waker.wake(); - } - } - - /// Fails every pending and later `next` call. - pub fn close(&self) { - let mut queue = self.queue.lock().unwrap(); - queue.closed = true; - for waker in queue.wakers.drain(..) { - waker.wake(); - } - } - - /// Waits for a pushed value, or fails once the store is closed. - pub async fn next(&self) -> Result { - Next { store: self }.await - } - - /// Never completes; `capi_pending_count` counts the calls not yet dropped. - pub async fn wait_forever(&self) { - PENDING.fetch_add(1, Ordering::SeqCst); - let _guard = PendingGuard; - std::future::pending::<()>().await; - } -} - -struct Next<'a> { - store: &'a CapiStore, -} - -impl Future for Next<'_> { - type Output = Result; - - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - let mut queue = self.store.queue.lock().unwrap(); - if let Some(value) = queue.values.pop_front() { - Poll::Ready(Ok(value)) - } else if queue.closed { - Poll::Ready(Err(CapiError::NotFound)) - } else { - queue.wakers.push(cx.waker().clone()); - Poll::Pending - } - } -} - -static PENDING: AtomicU64 = AtomicU64::new(0); - -struct PendingGuard; - -impl Drop for PendingGuard { - fn drop(&mut self) { - PENDING.fetch_sub(1, Ordering::SeqCst); - } -} - -/// How many `wait_forever` calls are still alive. -#[uniffi::export] -pub fn capi_pending_count() -> u64 { - PENDING.load(Ordering::SeqCst) -} - -#[uniffi::export] -pub fn capi_echo(item: CapiItem) -> CapiItem { - item -} - -#[uniffi::export] -pub fn capi_checksum(payload: Vec) -> u32 { - payload.iter().map(|&b| b as u32).sum() -} - -/// Describes which optionals are present. -#[uniffi::export] -pub fn capi_describe( - value: Option, - color: Option, - text: Option, - point: Option, - bytes: Option>, -) -> String { - format!("{value:?} {color:?} {text:?} {point:?} {bytes:?}") -} - -#[uniffi::export] -pub fn capi_make_shape(sides: u32) -> CapiShape { - match sides { - 0 => CapiShape::Dot, - 1 => CapiShape::Circle { radius: 2.5 }, - 2 => CapiShape::Label("two".into()), - _ => CapiShape::Path { - points: (0..sides as i32).map(|x| CapiPoint { x, y: -x }).collect(), - }, - } -} - -#[uniffi::export] -pub fn capi_fail(code: u32) -> Result<(), CapiError> { - match code { - 0 => Ok(()), - 1 => Err(CapiError::NotFound), - 2 => Err(CapiError::Invalid("two".into())), - _ => Err(CapiError::Code { - code, - at: CapiPoint { x: 3, y: 4 }, - }), - } -} - -#[uniffi::export] -pub fn capi_flat_fail(gone: bool) -> Result<(), CapiFlatError> { - Err(if gone { - CapiFlatError::Gone - } else { - CapiFlatError::Busy("later".into()) - }) -} - -/// Ready on its first poll. -#[uniffi::export] -pub async fn capi_sum(values: Vec) -> u64 { - values.iter().sum() -} - -#[uniffi::export] -pub async fn capi_greet(name: String) -> Result { - if name.is_empty() { - return Err(CapiError::Invalid("nobody".into())); - } - Ok(format!("hello, {name}")) -} diff --git a/uniffi/cpp/fixtures/custom-types-builtin/Cargo.toml b/uniffi/cpp/fixtures/custom-types-builtin/Cargo.toml deleted file mode 100644 index d942784e9..000000000 --- a/uniffi/cpp/fixtures/custom-types-builtin/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "uniffi-custom-types-builtin" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_cpp_custom_types_builtin" - -[dependencies] -uniffi = { workspace = true } -once_cell = "1.12" -paste = "1.0" -thiserror = "1.0" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/uniffi/cpp/fixtures/custom-types-builtin/build.rs b/uniffi/cpp/fixtures/custom-types-builtin/build.rs deleted file mode 100644 index 14325d826..000000000 --- a/uniffi/cpp/fixtures/custom-types-builtin/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/custom_types_builtin.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/custom-types-builtin/src/custom_types_builtin.udl b/uniffi/cpp/fixtures/custom-types-builtin/src/custom_types_builtin.udl deleted file mode 100644 index 91402b18a..000000000 --- a/uniffi/cpp/fixtures/custom-types-builtin/src/custom_types_builtin.udl +++ /dev/null @@ -1,71 +0,0 @@ -[Custom] -typedef string MyString; - -[Custom] -typedef string CustomString; - -[Custom] -typedef bytes Bytes; - -[Custom] -typedef sequence Array; - -[Custom] -typedef record Table; - -[Custom] -typedef boolean Boolean; - -[Custom] -typedef i8 Int8; - -[Custom] -typedef i16 Int16; - -[Custom] -typedef i32 Int32; - -[Custom] -typedef i64 Int64; - -[Custom] -typedef u8 UInt8; - -[Custom] -typedef u16 UInt16; - -[Custom] -typedef u32 UInt32; - -[Custom] -typedef u64 UInt64; - -[Custom] -typedef float Float; - -[Custom] -typedef double Double; - -dictionary CustomTypesBuiltin { - MyString string; - CustomString custom_string; - Array array; - Bytes bytes; - Table table; - Boolean boolean; - Int8 int8; - Int16 int16; - Int32 int32; - Int64 int64; - UInt8 uint8; - UInt16 uint16; - UInt32 uint32; - UInt64 uint64; - Float flt; - Double dbl; -}; - -namespace custom_types_builtin { - CustomTypesBuiltin get_custom_types_builtin(); - CustomTypesBuiltin return_custom_types_builtin(CustomTypesBuiltin custom_types); -}; diff --git a/uniffi/cpp/fixtures/custom-types-builtin/src/lib.rs b/uniffi/cpp/fixtures/custom-types-builtin/src/lib.rs deleted file mode 100644 index cb009dc55..000000000 --- a/uniffi/cpp/fixtures/custom-types-builtin/src/lib.rs +++ /dev/null @@ -1,83 +0,0 @@ -use std::collections::HashMap; - -// Define the custom type structs -pub struct MyString(pub String); -pub struct CustomString(pub String); -pub struct Array(pub Vec); -pub struct Bytes(pub Vec); -pub struct Table(pub HashMap); -pub struct Boolean(pub bool); -pub struct Int8(pub i8); -pub struct Int16(pub i16); -pub struct Int32(pub i32); -pub struct Int64(pub i64); -pub struct UInt8(pub u8); -pub struct UInt16(pub u16); -pub struct UInt32(pub u32); -pub struct UInt64(pub u64); -pub struct Float(pub f32); -pub struct Double(pub f64); - -// Define custom types using the new uniFFI 0.29.3 macro approach -uniffi::custom_newtype!(MyString, String); -uniffi::custom_newtype!(CustomString, String); -uniffi::custom_newtype!(Array, Vec); -uniffi::custom_newtype!(Bytes, Vec); -uniffi::custom_newtype!(Table, HashMap); -uniffi::custom_newtype!(Boolean, bool); -uniffi::custom_newtype!(Int8, i8); -uniffi::custom_newtype!(Int16, i16); -uniffi::custom_newtype!(Int32, i32); -uniffi::custom_newtype!(Int64, i64); -uniffi::custom_newtype!(UInt8, u8); -uniffi::custom_newtype!(UInt16, u16); -uniffi::custom_newtype!(UInt32, u32); -uniffi::custom_newtype!(UInt64, u64); -uniffi::custom_newtype!(Float, f32); -uniffi::custom_newtype!(Double, f64); - -pub struct CustomTypesBuiltin { - string: MyString, - custom_string: CustomString, - array: Array, - bytes: Bytes, - table: Table, - boolean: Boolean, - int8: Int8, - int16: Int16, - int32: Int32, - int64: Int64, - uint8: UInt8, - uint16: UInt16, - uint32: UInt32, - uint64: UInt64, - flt: Float, - dbl: Double, -} - -pub fn get_custom_types_builtin() -> CustomTypesBuiltin { - CustomTypesBuiltin { - string: MyString("Hello, world!".to_string()), - custom_string: CustomString("Custom string".to_string()), - array: Array(vec!["Hello, world!".to_string()]), - bytes: Bytes(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), - table: Table(HashMap::from([("hello".to_string(), "world".to_string())])), - boolean: Boolean(true), - int8: Int8(i8::MAX), - int16: Int16(i16::MAX), - int32: Int32(i32::MAX), - int64: Int64(i64::MAX), - uint8: UInt8(u8::MAX), - uint16: UInt16(u16::MAX), - uint32: UInt32(u32::MAX), - uint64: UInt64(u64::MAX), - flt: Float(f32::MAX), - dbl: Double(f64::MAX), - } -} - -pub fn return_custom_types_builtin(custom_types: CustomTypesBuiltin) -> CustomTypesBuiltin { - custom_types -} - -uniffi::include_scaffolding!("custom_types_builtin"); diff --git a/uniffi/cpp/fixtures/custom-types-builtin/uniffi.toml b/uniffi/cpp/fixtures/custom-types-builtin/uniffi.toml deleted file mode 100644 index 72dafa7aa..000000000 --- a/uniffi/cpp/fixtures/custom-types-builtin/uniffi.toml +++ /dev/null @@ -1,5 +0,0 @@ -[bindings.cpp.custom_types.CustomString] -imports = ["custom_string.hpp"] -type_name = "CustomString" -into_custom = "CustomString({})" -from_custom = "{}.to_string()" \ No newline at end of file diff --git a/uniffi/cpp/fixtures/empty-type/Cargo.toml b/uniffi/cpp/fixtures/empty-type/Cargo.toml deleted file mode 100644 index 637ba9285..000000000 --- a/uniffi/cpp/fixtures/empty-type/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "uniffi-empty-type" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_empty_type" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/uniffi/cpp/fixtures/empty-type/build.rs b/uniffi/cpp/fixtures/empty-type/build.rs deleted file mode 100644 index e698baadb..000000000 --- a/uniffi/cpp/fixtures/empty-type/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/empty_type.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/empty-type/src/empty_type.udl b/uniffi/cpp/fixtures/empty-type/src/empty_type.udl deleted file mode 100644 index da304eeb0..000000000 --- a/uniffi/cpp/fixtures/empty-type/src/empty_type.udl +++ /dev/null @@ -1,6 +0,0 @@ -dictionary Empty {}; - -namespace empty_type{ - Empty get_empty_type(); - void send_empty_type(Empty e); -}; diff --git a/uniffi/cpp/fixtures/empty-type/src/lib.rs b/uniffi/cpp/fixtures/empty-type/src/lib.rs deleted file mode 100644 index 564556021..000000000 --- a/uniffi/cpp/fixtures/empty-type/src/lib.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub struct Empty {} - -pub fn get_empty_type() -> Empty { - Empty {} -} - -pub fn send_empty_type(_empty: Empty) {} - -uniffi::include_scaffolding!("empty_type"); diff --git a/uniffi/cpp/fixtures/enum-style-test/Cargo.toml b/uniffi/cpp/fixtures/enum-style-test/Cargo.toml deleted file mode 100644 index 6782b1af0..000000000 --- a/uniffi/cpp/fixtures/enum-style-test/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "uniffi-enum-style-test" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_enum_style_test" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/uniffi/cpp/fixtures/enum-style-test/build.rs b/uniffi/cpp/fixtures/enum-style-test/build.rs deleted file mode 100644 index c357e91a0..000000000 --- a/uniffi/cpp/fixtures/enum-style-test/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/enum_style_test.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/enum-style-test/src/enum_style_test.udl b/uniffi/cpp/fixtures/enum-style-test/src/enum_style_test.udl deleted file mode 100644 index d12e633cf..000000000 --- a/uniffi/cpp/fixtures/enum-style-test/src/enum_style_test.udl +++ /dev/null @@ -1,28 +0,0 @@ -enum SimpleEnum { - "VariantOne", - "VariantTwo", - "VariantThree", -}; - -[Enum] -interface ComplexEnum { - VariantOne(u32 num); - VariantTwo(f32 flt); -}; - -// Repeating the same named dependency used to make the C++ topological sorter -// emit that dependency's definition more than once. -dictionary RepeatedDependencies { - SimpleEnum first; - SimpleEnum second; -}; - -namespace enum_style_test { - SimpleEnum get_simple_enum(); - void set_simple_enum(SimpleEnum e); - - ComplexEnum get_complex_enum(); - void set_complex_enum(ComplexEnum e); - - RepeatedDependencies roundtrip_repeated_dependencies(RepeatedDependencies value); -}; diff --git a/uniffi/cpp/fixtures/enum-style-test/src/lib.rs b/uniffi/cpp/fixtures/enum-style-test/src/lib.rs deleted file mode 100644 index 7d1c9af81..000000000 --- a/uniffi/cpp/fixtures/enum-style-test/src/lib.rs +++ /dev/null @@ -1,37 +0,0 @@ -#[allow( - clippy::enum_variant_names, - reason = "the shared prefix is what the style test renders" -)] -enum SimpleEnum { - VariantOne, - VariantTwo, - VariantThree, -} - -enum ComplexEnum { - VariantOne { num: u32 }, - VariantTwo { flt: f32 }, -} - -struct RepeatedDependencies { - first: SimpleEnum, - second: SimpleEnum, -} - -fn get_simple_enum() -> SimpleEnum { - SimpleEnum::VariantOne -} - -fn set_simple_enum(_: SimpleEnum) {} - -fn get_complex_enum() -> ComplexEnum { - ComplexEnum::VariantOne { num: 42 } -} - -fn set_complex_enum(_: ComplexEnum) {} - -fn roundtrip_repeated_dependencies(value: RepeatedDependencies) -> RepeatedDependencies { - value -} - -uniffi::include_scaffolding!("enum_style_test"); diff --git a/uniffi/cpp/fixtures/enum-style-test/uniffi.toml b/uniffi/cpp/fixtures/enum-style-test/uniffi.toml deleted file mode 100644 index d56a29c9e..000000000 --- a/uniffi/cpp/fixtures/enum-style-test/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.cpp] -enum_style = "Capitalized" diff --git a/uniffi/cpp/fixtures/error-types-builtin/Cargo.toml b/uniffi/cpp/fixtures/error-types-builtin/Cargo.toml deleted file mode 100644 index ee0062a25..000000000 --- a/uniffi/cpp/fixtures/error-types-builtin/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "uniffi-error-types-builtin" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_cpp_error_types_builtin" - -[dependencies] -uniffi = { workspace = true } -anyhow = "1" -thiserror = "1.0" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/uniffi/cpp/fixtures/error-types-builtin/build.rs b/uniffi/cpp/fixtures/error-types-builtin/build.rs deleted file mode 100644 index 330c577a8..000000000 --- a/uniffi/cpp/fixtures/error-types-builtin/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/error_types_builtin.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/error-types-builtin/src/error_types_builtin.udl b/uniffi/cpp/fixtures/error-types-builtin/src/error_types_builtin.udl deleted file mode 100644 index 0e1d7a268..000000000 --- a/uniffi/cpp/fixtures/error-types-builtin/src/error_types_builtin.udl +++ /dev/null @@ -1,34 +0,0 @@ -namespace error_types_builtin { - [Throws=ErrorInterface] - void oops(); - - [Throws=ErrorInterface] - void oops_nowrap(); - - ErrorInterface get_error(string message); - - [Throws=RichError] - void throw_rich(string message); -}; - -interface TestInterface { - constructor(); - - [Throws=ErrorInterface, Name="fallible_new"] - constructor(); - - [Throws=ErrorInterface] - void oops(); -}; - -[Traits=(Debug, Display)] -interface ErrorInterface { - sequence chain(); - string? link(u64 index); -}; - -// Kotlin replaces a trailing "Error" with "Exception" -// for enums, so we should check it does for objects too. -[Traits=(Debug, Display)] -interface RichError { -}; diff --git a/uniffi/cpp/fixtures/error-types-builtin/src/lib.rs b/uniffi/cpp/fixtures/error-types-builtin/src/lib.rs deleted file mode 100644 index 66b2f0ae8..000000000 --- a/uniffi/cpp/fixtures/error-types-builtin/src/lib.rs +++ /dev/null @@ -1,236 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -#[derive(Debug, thiserror::Error)] -#[error("{e:?}")] -pub struct ErrorInterface { - e: anyhow::Error, -} - -impl ErrorInterface { - fn chain(&self) -> Vec { - self.e.chain().map(ToString::to_string).collect() - } - fn link(&self, ndx: u64) -> Option { - self.e.chain().nth(ndx as usize).map(ToString::to_string) - } -} - -// A conversion into our ErrorInterface from anyhow::Error. -// We can't use this implicitly yet, but it still helps. -impl From for ErrorInterface { - fn from(e: anyhow::Error) -> Self { - Self { e } - } -} - -// Test an interface as the error type -fn oops() -> Result<(), Arc> { - // must do explicit conversion to convert anyhow::Error into ErrorInterface - Err(Arc::new( - anyhow::Error::msg("oops") - .context("because uniffi told me so") - .into(), - )) -} - -// Like `oops`, but let UniFFI handle wrapping the interface with an arc -fn oops_nowrap() -> Result<(), ErrorInterface> { - // must do explicit conversion to convert anyhow::Error into ErrorInterface - Err(anyhow::Error::msg("oops") - .context("because uniffi told me so") - .into()) -} - -#[uniffi::export] -fn toops() -> Result<(), Arc> { - Err(Arc::new(ErrorTraitImpl { - m: "trait-oops".to_string(), - })) -} - -fn get_error(message: String) -> std::sync::Arc { - Arc::new(anyhow::Error::msg(message).into()) -} - -#[uniffi::export] -pub trait ErrorTrait: Send + Sync + std::fmt::Debug + std::error::Error { - fn msg(&self) -> String; -} - -#[derive(Debug, thiserror::Error)] -#[error("{m:?}")] -struct ErrorTraitImpl { - m: String, -} - -impl ErrorTrait for ErrorTraitImpl { - fn msg(&self) -> String { - self.m.clone() - } -} - -fn throw_rich(e: String) -> Result<(), RichError> { - Err(RichError { e }) -} - -// Exists to test trailing "Error" mapping in bindings -#[derive(Debug, thiserror::Error)] -#[error("RichError: {e:?}")] -pub struct RichError { - e: String, -} - -impl RichError {} - -pub struct TestInterface {} - -impl TestInterface { - fn new() -> Self { - TestInterface {} - } - - fn fallible_new() -> Result> { - Err(Arc::new(anyhow::Error::msg("fallible_new").into())) - } - - fn oops(&self) -> Result<(), Arc> { - Err(Arc::new( - anyhow::Error::msg("oops") - .context("because the interface told me so") - .into(), - )) - } -} - -// A procmacro as an error -#[derive(Debug, uniffi::Object, thiserror::Error)] -#[uniffi::export(Debug, Display)] -pub struct ProcErrorInterface { - e: String, -} - -#[uniffi::export] -impl ProcErrorInterface { - fn message(&self) -> String { - self.e.clone() - } -} - -impl std::fmt::Display for ProcErrorInterface { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "ProcErrorInterface({})", self.e) - } -} - -#[uniffi::export] -fn throw_proc_error(e: String) -> Result<(), Arc> { - Err(Arc::new(ProcErrorInterface { e })) -} - -#[uniffi::export] -fn return_proc_error(e: String) -> Arc { - Arc::new(ProcErrorInterface { e }) -} - -#[derive(thiserror::Error, Debug)] -#[error("NonUniffiTypeValue: {v}")] -pub struct NonUniffiType { - v: String, -} - -// Note: It's important for this test that this error -// *not* be used directly as the `Err` for any functions etc. -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum Inner { - #[error("{0}")] - CaseA(String), -} - -// Note: It's important for this test that this error -// *not* be used directly as the `Err` for any functions etc. -#[derive(thiserror::Error, uniffi::Error, Debug)] -#[uniffi(flat_error)] -pub enum FlatInner { - #[error("{0}")] - CaseA(String), - #[error("{0}")] - CaseB(NonUniffiType), -} - -// Enums have good coverage elsewhere, but simple coverage here is good. -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum Error { - #[error("Oops")] - Oops, - #[error("Value: {value}")] - Value { value: String }, - #[error("IntValue: {value}")] - IntValue { value: u16 }, - #[error(transparent)] - FlatInnerError { - #[from] - error: FlatInner, - }, - #[error(transparent)] - InnerError { error: Inner }, -} - -#[uniffi::export] -fn oops_enum(i: u16) -> Result<(), Error> { - if i == 0 { - Err(Error::Oops) - } else if i == 1 { - Err(Error::Value { - value: "value".to_string(), - }) - } else if i == 2 { - Err(Error::IntValue { value: i }) - } else if i == 3 { - Err(Error::FlatInnerError { - error: FlatInner::CaseA("inner".to_string()), - }) - } else if i == 4 { - Err(Error::FlatInnerError { - error: FlatInner::CaseB(NonUniffiType { - v: "value".to_string(), - }), - }) - } else if i == 5 { - Err(Error::InnerError { - error: Inner::CaseA("inner".to_string()), - }) - } else { - panic!("unknown variant {i}") - } -} - -// tuple enum as an error. -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum TupleError { - #[error("Oops")] - Oops(String), - #[error("Value {0}")] - Value(u16), -} - -#[uniffi::export] -fn oops_tuple(i: u16) -> Result<(), TupleError> { - if i == 0 { - Err(TupleError::Oops("oops".to_string())) - } else if i == 1 { - Err(TupleError::Value(i)) - } else { - panic!("unknown variant {i}") - } -} - -#[uniffi::export(default(t = None))] -fn get_tuple(t: Option) -> TupleError { - t.unwrap_or_else(|| TupleError::Oops("oops".to_string())) -} - -uniffi::include_scaffolding!("error_types_builtin"); diff --git a/uniffi/cpp/fixtures/ext-types-export/Cargo.toml b/uniffi/cpp/fixtures/ext-types-export/Cargo.toml deleted file mode 100644 index 4f2d63766..000000000 --- a/uniffi/cpp/fixtures/ext-types-export/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "uniffi-ext-types-export" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_ext_types_export" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } \ No newline at end of file diff --git a/uniffi/cpp/fixtures/ext-types-export/build.rs b/uniffi/cpp/fixtures/ext-types-export/build.rs deleted file mode 100644 index cd5fe6fa8..000000000 --- a/uniffi/cpp/fixtures/ext-types-export/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/ext_types_export.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/ext-types-export/src/ext_types_export.udl b/uniffi/cpp/fixtures/ext-types-export/src/ext_types_export.udl deleted file mode 100644 index bb2aaae31..000000000 --- a/uniffi/cpp/fixtures/ext-types-export/src/ext_types_export.udl +++ /dev/null @@ -1,38 +0,0 @@ -[Trait] -interface Vehicle { - i32 year(); -}; - -namespace ext_types_export { - Vehicle to_car(); -}; - -dictionary Coordinates { - i32 x; - i32 y; -}; - -enum Direction { - "North", - "South", -}; - -[Custom] -typedef i64 Handle; - -interface Counter { - constructor(); - void increment(); - u32 get(); -}; - -[Trait, WithForeign] -interface Greeter { - string greet(); -}; - -[Enum] -interface Shape { - Circle(f64 radius); - Rectangle(f64 width, f64 height); -}; \ No newline at end of file diff --git a/uniffi/cpp/fixtures/ext-types-export/src/lib.rs b/uniffi/cpp/fixtures/ext-types-export/src/lib.rs deleted file mode 100644 index b411b96d0..000000000 --- a/uniffi/cpp/fixtures/ext-types-export/src/lib.rs +++ /dev/null @@ -1,62 +0,0 @@ -#[derive(Debug, Clone)] -pub struct Coordinates { - pub x: i32, - pub y: i32, -} - -#[derive(Debug, Clone)] -pub enum Direction { - North, - South, -} - -pub struct Handle(pub i64); -uniffi::custom_newtype!(Handle, i64); - -pub struct Counter { - value: std::sync::atomic::AtomicU32, -} - -impl Counter { - fn new() -> Self { - Counter { - value: std::sync::atomic::AtomicU32::new(0), - } - } - - fn increment(&self) { - self.value.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } - - fn get(&self) -> u32 { - self.value.load(std::sync::atomic::Ordering::SeqCst) - } -} -#[uniffi::trait_interface] -pub trait Greeter: Send + Sync { - fn greet(&self) -> String; -} - -pub enum Shape { - Circle { radius: f64 }, - Rectangle { width: f64, height: f64 }, -} - -#[uniffi::trait_interface] -pub trait Vehicle: Send + Sync { - fn year(&self) -> i32; -} - -pub struct Car {} - -impl Vehicle for Car { - fn year(&self) -> i32 { - 1984 - } -} - -pub fn to_car() -> std::sync::Arc { - std::sync::Arc::new(Car {}) -} - -uniffi::include_scaffolding!("ext_types_export"); diff --git a/uniffi/cpp/fixtures/ext-types-import/Cargo.toml b/uniffi/cpp/fixtures/ext-types-import/Cargo.toml deleted file mode 100644 index 6cd3bd389..000000000 --- a/uniffi/cpp/fixtures/ext-types-import/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "uniffi-ext-types-import" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_ext_types_import" - -[dependencies] -uniffi = { workspace = true } -uniffi-ext-types-export = { path = "../ext-types-export" } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } \ No newline at end of file diff --git a/uniffi/cpp/fixtures/ext-types-import/build.rs b/uniffi/cpp/fixtures/ext-types-import/build.rs deleted file mode 100644 index b1e9e0219..000000000 --- a/uniffi/cpp/fixtures/ext-types-import/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/ext_types_import.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/ext-types-import/src/ext_types_import.udl b/uniffi/cpp/fixtures/ext-types-import/src/ext_types_import.udl deleted file mode 100644 index 8e2879860..000000000 --- a/uniffi/cpp/fixtures/ext-types-import/src/ext_types_import.udl +++ /dev/null @@ -1,48 +0,0 @@ -[External="uniffi_ext_types_export"] -typedef dictionary Coordinates; - -[External="uniffi_ext_types_export"] -typedef enum Direction; - -[Custom="uniffi_ext_types_export"] -typedef i64 Handle; - -[External="uniffi_ext_types_export"] -typedef interface Counter; - -dictionary Counters { - Counter counter; - u32 label; -}; - -[External="uniffi_ext_types_export"] -typedef trait_with_foreign Greeter; - -[External="uniffi_ext_types_export"] -typedef enum Shape; - -[Enum] -interface InnerShape { - Empty(); - Hold(Shape shape); -}; - -[External="uniffi_ext_types_export"] -typedef trait Vehicle; - -namespace ext_types_import { - Coordinates roundtrip_coord(Coordinates c); - sequence roundtrip_coords(sequence cs); - Direction roundtrip_direction(Direction d); - Handle roundtrip_handle(Handle h); - Counter roundtrip_counter(Counter c); - Counters roundtrip_counters(Counters c); - string call_greeter(Greeter g); - Coordinates? roundtrip_opt_coord(Coordinates? c); - Counter? roundtrip_opt_counter(Counter? c); - Shape roundtrip_shape(Shape s); - InnerShape roundtrip_inner(InnerShape i); - record roundtrip_coord_map(record locations); - sequence roundtrip_counter_list(sequence cs); - i32 vehicle_year(Vehicle v); -}; diff --git a/uniffi/cpp/fixtures/ext-types-import/src/lib.rs b/uniffi/cpp/fixtures/ext-types-import/src/lib.rs deleted file mode 100644 index 913a735bd..000000000 --- a/uniffi/cpp/fixtures/ext-types-import/src/lib.rs +++ /dev/null @@ -1,73 +0,0 @@ -use std::{collections::HashMap, sync::Arc}; - -use uniffi_ext_types_export::{Coordinates, Counter, Direction, Greeter, Handle, Shape, Vehicle}; - -pub fn roundtrip_coord(coord: Coordinates) -> Coordinates { - coord -} - -pub fn roundtrip_coords(coords: Vec) -> Vec { - coords -} - -pub fn roundtrip_direction(dir: Direction) -> Direction { - dir -} - -pub fn roundtrip_handle(h: Handle) -> Handle { - h -} - -pub fn roundtrip_counter(c: Arc) -> Arc { - c -} - -pub struct Counters { - pub counter: Arc, - pub label: u32, -} - -pub fn roundtrip_counters(c: Counters) -> Counters { - c -} - -pub fn call_greeter(g: Arc) -> String { - g.greet() -} - -pub fn roundtrip_opt_coord(c: Option) -> Option { - c -} - -pub fn roundtrip_opt_counter(c: Option>) -> Option> { - c -} - -pub fn roundtrip_shape(s: Shape) -> Shape { - s -} - -pub enum InnerShape { - Empty, - Hold { shape: Shape }, -} - -pub fn roundtrip_inner(i: InnerShape) -> InnerShape { - i -} - -pub fn roundtrip_coord_map( - locations: HashMap, -) -> HashMap { - locations -} - -pub fn roundtrip_counter_list(cs: Vec>) -> Vec> { - cs -} - -pub fn vehicle_year(v: Arc) -> i32 { - v.year() -} - -uniffi::include_scaffolding!("ext_types_import"); diff --git a/uniffi/cpp/fixtures/reserved-field-name/Cargo.toml b/uniffi/cpp/fixtures/reserved-field-name/Cargo.toml deleted file mode 100644 index 4dc6b4067..000000000 --- a/uniffi/cpp/fixtures/reserved-field-name/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "uniffi-reserved-field-name" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_reserved_field_name" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/uniffi/cpp/fixtures/reserved-field-name/build.rs b/uniffi/cpp/fixtures/reserved-field-name/build.rs deleted file mode 100644 index 3066bb68e..000000000 --- a/uniffi/cpp/fixtures/reserved-field-name/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/reserved_field_name.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/reserved-field-name/src/lib.rs b/uniffi/cpp/fixtures/reserved-field-name/src/lib.rs deleted file mode 100644 index 82d95a59a..000000000 --- a/uniffi/cpp/fixtures/reserved-field-name/src/lib.rs +++ /dev/null @@ -1,13 +0,0 @@ -struct Foo { - this: u32, - errno: u32, - assert: u32, -} - -fn assert_fields_are_42(value: Foo) { - assert_eq!(42, value.this); - assert_eq!(42, value.errno); - assert_eq!(42, value.assert); -} - -uniffi::include_scaffolding!("reserved_field_name"); diff --git a/uniffi/cpp/fixtures/reserved-field-name/src/reserved_field_name.udl b/uniffi/cpp/fixtures/reserved-field-name/src/reserved_field_name.udl deleted file mode 100644 index a8bac5616..000000000 --- a/uniffi/cpp/fixtures/reserved-field-name/src/reserved_field_name.udl +++ /dev/null @@ -1,9 +0,0 @@ -dictionary Foo { - u32 this; - u32 errno; - u32 assert; -}; - -namespace reserved_field_name { - void assert_fields_are_42(Foo foo); -}; diff --git a/uniffi/cpp/fixtures/src/lib.rs b/uniffi/cpp/fixtures/src/lib.rs deleted file mode 100644 index b56146b7a..000000000 --- a/uniffi/cpp/fixtures/src/lib.rs +++ /dev/null @@ -1,30 +0,0 @@ -mod uniffi_fixtures { - arithmetical::uniffi_reexport_scaffolding!(); - uniffi_callbacks::uniffi_reexport_scaffolding!(); - custom_types::uniffi_reexport_scaffolding!(); - uniffi_geometry::uniffi_reexport_scaffolding!(); - uniffi_rondpoint::uniffi_reexport_scaffolding!(); - uniffi_sprites::uniffi_reexport_scaffolding!(); - uniffi_todolist::uniffi_reexport_scaffolding!(); - uniffi_traits::uniffi_reexport_scaffolding!(); - uniffi_chronological::uniffi_reexport_scaffolding!(); - uniffi_trait_methods::uniffi_reexport_scaffolding!(); - uniffi_coverall::uniffi_reexport_scaffolding!(); - uniffi_fixture_docstring::uniffi_reexport_scaffolding!(); - uniffi_fixture_callbacks::uniffi_reexport_scaffolding!(); - uniffi_cpp_error_types_builtin::uniffi_reexport_scaffolding!(); - - uniffi_cpp_custom_types_builtin::uniffi_reexport_scaffolding!(); - uniffi_enum_style_test::uniffi_reexport_scaffolding!(); - uniffi_empty_type::uniffi_reexport_scaffolding!(); - uniffi_reserved_field_name::uniffi_reexport_scaffolding!(); - uniffi_type_flattening::uniffi_reexport_scaffolding!(); - uniffi_fixture_async_calls::uniffi_reexport_scaffolding!(); - uniffi_c_api::uniffi_reexport_scaffolding!(); - - uniffi_ext_types_export::uniffi_reexport_scaffolding!(); - uniffi_ext_types_import::uniffi_reexport_scaffolding!(); - - uniffi_namespaces_net::uniffi_reexport_scaffolding!(); - uniffi_namespaces_media::uniffi_reexport_scaffolding!(); -} diff --git a/uniffi/cpp/fixtures/type-flattening/Cargo.toml b/uniffi/cpp/fixtures/type-flattening/Cargo.toml deleted file mode 100644 index 16afcd844..000000000 --- a/uniffi/cpp/fixtures/type-flattening/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "uniffi-type-flattening" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_type_flattening" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/uniffi/cpp/fixtures/type-flattening/build.rs b/uniffi/cpp/fixtures/type-flattening/build.rs deleted file mode 100644 index ef77fdb5d..000000000 --- a/uniffi/cpp/fixtures/type-flattening/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi::generate_scaffolding("src/type_flattening.udl").unwrap(); -} diff --git a/uniffi/cpp/fixtures/type-flattening/src/lib.rs b/uniffi/cpp/fixtures/type-flattening/src/lib.rs deleted file mode 100644 index ce669399c..000000000 --- a/uniffi/cpp/fixtures/type-flattening/src/lib.rs +++ /dev/null @@ -1,33 +0,0 @@ -use std::sync::Arc; - -#[derive(uniffi::Object)] -pub struct Object { - pub value: i32, -} - -#[uniffi::export] -impl Object { - pub fn get_value(&self) -> i32 { - self.value - } -} - -#[derive(uniffi::Record)] -pub struct Structure { - #[uniffi(default = None)] - pub optional_arc: Option>, -} - -#[uniffi::export] -pub fn get_struct(value: i32) -> Structure { - Structure { - optional_arc: Some(Arc::new(Object { value })), - } -} - -#[uniffi::export] -pub fn struct_roundtrip(structure: Structure) -> Structure { - structure -} - -uniffi::include_scaffolding!("type_flattening"); diff --git a/uniffi/cpp/fixtures/type-flattening/src/type_flattening.udl b/uniffi/cpp/fixtures/type-flattening/src/type_flattening.udl deleted file mode 100644 index ec043557b..000000000 --- a/uniffi/cpp/fixtures/type-flattening/src/type_flattening.udl +++ /dev/null @@ -1,3 +0,0 @@ -namespace type_flattening { - -}; diff --git a/uniffi/dart/Cargo.toml b/uniffi/dart/Cargo.toml deleted file mode 100644 index 09bf265c4..000000000 --- a/uniffi/dart/Cargo.toml +++ /dev/null @@ -1,56 +0,0 @@ -[package] -name = "uniffi-dart" -version = "0.1.0" -publish = false -edition = "2021" -license = "Apache-2 or MIT" -homepage = "https://github.com/acterglobal/uniffi-dart" -description = "Dart Frontend for UniFFI" -rust-version = "1.91" - -[features] -defaults = [] -binary = [] -build = ["dep:uniffi_build"] -bindgen-tests = [ - "dep:uniffi_testing", - "dep:camino-tempfile", - "dep:fs_extra", - "dep:glob", -] - -[lib] -name = "uniffi_dart" -path = "src/lib.rs" - -[[bin]] -name = "uniffi_bindgen_dart" -path = "src/bin.rs" -required-features = ["binary"] -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -anyhow = "1" -paste = "1" -heck = "0.5" -uniffi = { workspace = true, features = ["build", "tokio"] } -uniffi_dart_macro = { path = "./uniffi_dart_macro" } -uniffi_bindgen = { workspace = true } -camino = "1" -cargo_metadata = "0.18" -serde = "1" -toml = "1" -genco = "0.17.5" -proc-macro2 = "1.0.66" - -# feature specific stuff -uniffi_build = { workspace = true, optional = true } - -# optional for testint -uniffi_testing = { workspace = true, optional = true } - -fs_extra = { version = "1.3.0", optional = true } -camino-tempfile = { version = "1.0.2", optional = true } -glob = { version = "0.3.1", optional = true } -lazy_static = "1.5.0" -stringcase = "0.4.0" diff --git a/uniffi/dart/LICENSE b/uniffi/dart/LICENSE deleted file mode 100644 index 1d75b11b1..000000000 --- a/uniffi/dart/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023-2024 Acter - -Permission 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. diff --git a/uniffi/dart/fixtures/arithmetic/Cargo.toml b/uniffi/dart/fixtures/arithmetic/Cargo.toml deleted file mode 100644 index 4368bbdb4..000000000 --- a/uniffi/dart/fixtures/arithmetic/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "simple_arithmetic" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "simple_arithmetic" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -thiserror = "2.0" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/arithmetic/build.rs b/uniffi/dart/fixtures/arithmetic/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/arithmetic/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/arithmetic/src/api.udl b/uniffi/dart/fixtures/arithmetic/src/api.udl deleted file mode 100644 index 939a5a989..000000000 --- a/uniffi/dart/fixtures/arithmetic/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace simple_arithmetic { }; diff --git a/uniffi/dart/fixtures/arithmetic/src/lib.rs b/uniffi/dart/fixtures/arithmetic/src/lib.rs deleted file mode 100644 index 148d1e314..000000000 --- a/uniffi/dart/fixtures/arithmetic/src/lib.rs +++ /dev/null @@ -1,105 +0,0 @@ -#[derive(Debug, thiserror::Error, uniffi::Error)] -pub enum MathError { - #[error("Division by zero")] - DivisionByZero, - #[error("Invalid input: {message}")] - InvalidInput { message: String }, -} - -#[uniffi::export] -pub fn add(left: u32, right: u32) -> u32 { - left + right -} - -#[uniffi::export] -pub fn multiply(left: u32, right: u32) -> u32 { - left * right -} - -#[uniffi::export] -pub fn divide(left: u32, right: u32) -> Option { - Some(left / right) -} - -#[uniffi::export] -pub fn can_divide(left: u32, right: u32) -> Option { - Some(left > right) -} - -#[uniffi::export] -pub fn divide_checked(left: u32, right: u32) -> Option { - left.checked_div(right) -} - -#[uniffi::export] -pub fn add_u8(left: u8, right: u8) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_u16(left: u16, right: u16) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_u64(left: u64, right: u64) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_i8(left: i8, right: i8) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_i16(left: i16, right: i16) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_i32(left: i32, right: i32) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_i64(left: i64, right: i64) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_f32(left: f32, right: f32) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn add_f64(left: f64, right: f64) -> Option { - Some(left + right) -} - -#[uniffi::export] -pub fn divide_by_zero(numerator: u64, denominator: u64) -> Result { - numerator.checked_div(denominator).ok_or(MathError::DivisionByZero) -} - -macro_rules! get_back { - ($T:ty, $n:ident ) => { - #[uniffi::export] - pub fn $n(value: $T) -> Option<$T> { - Some(value) - } - }; -} - -// Make sure optional types behave correctly -get_back!(u8, get_back_u8); -get_back!(u16, get_back_u16); -get_back!(u32, get_back_u32); -get_back!(u64, get_back_u64); -get_back!(i8, get_back_i8); -get_back!(i16, get_back_i16); -get_back!(i32, get_back_i32); -get_back!(i64, get_back_i64); -get_back!(f64, get_back_f64); -get_back!(f32, get_back_f32); - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/arithmetic/test/simple_arithmetic_test.dart b/uniffi/dart/fixtures/arithmetic/test/simple_arithmetic_test.dart deleted file mode 100644 index bd40334bc..000000000 --- a/uniffi/dart/fixtures/arithmetic/test/simple_arithmetic_test.dart +++ /dev/null @@ -1,86 +0,0 @@ -import 'package:test/test.dart'; -import '../simple_arithmetic.dart'; - -void main() { - test('2 + 2 = 4', () { - expect(add(left: 2, right: 2), 4); - }); - test('2 * 8 = 16', () { - expect(multiply(left: 2, right: 8), 16); - }); - test('2 / 8 = 0', () { - expect(divideChecked(left: 2, right: 8), 0); - }); - test('8 / 0 = null', () { - expect(divideChecked(left: 8, right: 0), null); - }); - test('8 / 2 = 4', () { - expect(divide(left: 8, right: 2), 4); - }); - test('u8', () { - expect(addU8(left: 2, right: 2), 4); - }); - test('u16', () { - expect(addU16(left: 2, right: 2), 4); - }); - test('u64', () { - expect(addU64(left: 2, right: 2), 4); - }); - - test('i8', () { - expect(addI8(left: 2, right: 2), 4); - }); - test('i16', () { - expect(addI16(left: 2, right: 2), 4); - }); - test('i32', () { - expect(addI32(left: 2, right: 2), 4); - }); - test('i64', () { - expect(addI64(left: 2, right: 2), 4); - }); - test('f32', () { - expect(addF32(left: 2.0, right: 2.0), 4.0); - }); - test('f64', () { - expect(addF64(left: 2.0, right: 2.9), 4.9); - }); - - test('get back u8', () { - expect(getBackU8(value: 4), 4); - }); - test('get back u16', () { - expect(getBackU16(value: 4), 4); - }); - test('get back u64', () { - expect(getBackU64(value: 4), 4); - }); - - test('get back i8', () { - expect(getBackI8(value: 4), 4); - }); - test('get back f32', () { - expect(getBackF32(value: 4.0), 4.0); - }); - test('get back f64', () { - expect(getBackF64(value: 4.9), 4.9); - }); - - test('divide by zero - success case', () { - expect(divideByZero(numerator: 10, denominator: 2), 5); - }); - - test('divide by zero - error case', () { - expect( - () => divideByZero(numerator: 10, denominator: 0), - throwsA(isA()), - ); - }); - - test('divide by zero - specific error type', () { - expect( - () => divideByZero(numerator: 10, denominator: 0), - throwsA(isA()), - ); - }); -} diff --git a/uniffi/dart/fixtures/arithmetic/tests/mod.rs b/uniffi/dart/fixtures/arithmetic/tests/mod.rs deleted file mode 100644 index afdb40946..000000000 --- a/uniffi/dart/fixtures/arithmetic/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn simple_arithmetic() -> Result<()> { - uniffi_dart::testing::run_test("simple_arithmetic", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/benchmarks/Cargo.toml b/uniffi/dart/fixtures/benchmarks/Cargo.toml deleted file mode 100644 index bb952a0aa..000000000 --- a/uniffi/dart/fixtures/benchmarks/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "benchmarks" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -name = "benchmarks" -crate-type = ["lib", "cdylib"] -bench = false - -[dependencies] -uniffi = { workspace = true } -clap = { version = "4", features = ["cargo", "std", "derive"] } -criterion = "0.5.1" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } -camino = "1" - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/benchmarks/build.rs b/uniffi/dart/fixtures/benchmarks/build.rs deleted file mode 100644 index 797041d85..000000000 --- a/uniffi/dart/fixtures/benchmarks/build.rs +++ /dev/null @@ -1,5 +0,0 @@ -use camino::Utf8Path; - -fn main() { - uniffi_dart::generate_scaffolding(Utf8Path::new("src/api.udl")).unwrap(); -} diff --git a/uniffi/dart/fixtures/benchmarks/src/api.udl b/uniffi/dart/fixtures/benchmarks/src/api.udl deleted file mode 100644 index febb1ee70..000000000 --- a/uniffi/dart/fixtures/benchmarks/src/api.udl +++ /dev/null @@ -1,40 +0,0 @@ -namespace benchmarks { - // Run all benchmarks and print the results to stdout - void run_benchmarks(string language_name, TestCallbackInterface cb); - - // Test functions - // - // These are intended to test the overhead of Rust function calls including: - // popping arguments from the stack, unpacking RustBuffers, pushing return - // values back to the stack, etc. - - string test_function(i32 a, i32 b, TestData data); // Should return data.bar - void test_void_return(i32 a, i32 b, TestData data); - void test_no_args_void_return(); -}; - -dictionary TestData { - string foo; - string bar; -}; - -enum TestCase { - "Function", - "VoidReturn", - "NoArgsVoidReturn", -}; - -callback interface TestCallbackInterface { - // Test callback methods. - // - // These are intended to test the overhead of callback interface calls - // including: popping arguments from the stack, unpacking RustBuffers, - // pushing return values back to the stack, etc. - - string method(i32 a, i32 b, TestData data); // Should return data.bar - void method_with_void_return(i32 a, i32 b, TestData data); - void method_with_no_args_and_void_return(); - - // Run a performance test N times and return the elapsed time in nanoseconds - u64 run_test(TestCase test_case, u64 count); -}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/benchmarks/src/lib.rs b/uniffi/dart/fixtures/benchmarks/src/lib.rs deleted file mode 100644 index 5dcfaeb61..000000000 --- a/uniffi/dart/fixtures/benchmarks/src/lib.rs +++ /dev/null @@ -1,105 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::time::Instant; - -pub struct TestData { - pub foo: String, - pub bar: String, -} - -pub enum TestCase { - Function, - VoidReturn, - NoArgsVoidReturn, -} - -pub trait TestCallbackInterface: Send + Sync { - fn method(&self, a: i32, b: i32, data: TestData) -> String; - fn method_with_void_return(&self, a: i32, b: i32, data: TestData); - fn method_with_no_args_and_void_return(&self); - fn run_test(&self, test_case: TestCase, count: u64) -> u64; -} - -// Test functions for benchmarking FFI call overhead -pub fn test_function(_a: i32, _b: i32, data: TestData) -> String { - data.bar -} - -pub fn test_void_return(_a: i32, _b: i32, _data: TestData) { - // Intentionally does nothing - testing void return overhead -} - -pub fn test_no_args_void_return() { - // Intentionally does nothing - testing minimal call overhead -} - -pub fn run_benchmarks(language: String, cb: Box) { - println!("Running benchmarks for {language}"); - - let test_data = - TestData { foo: "SomeStringData".to_string(), bar: "SomeMoreStringData".to_string() }; - - // Simple timing-based benchmarks (not using Criterion for now to avoid complexity) - - // Test function calls - let start = Instant::now(); - for _ in 0..1000 { - test_function(10, 100, TestData { foo: test_data.foo.clone(), bar: test_data.bar.clone() }); - } - let function_time = start.elapsed(); - println!("{language}-functions-basic: {:?}", function_time); - - // Test void return - let start = Instant::now(); - for _ in 0..1000 { - test_void_return( - 10, - 100, - TestData { foo: test_data.foo.clone(), bar: test_data.bar.clone() }, - ); - } - let void_time = start.elapsed(); - println!("{language}-functions-void-return: {:?}", void_time); - - // Test no-args void return - let start = Instant::now(); - for _ in 0..1000 { - test_no_args_void_return(); - } - let no_args_time = start.elapsed(); - println!("{language}-functions-no-args-void-return: {:?}", no_args_time); - - // Test callbacks - let start = Instant::now(); - for _ in 0..1000 { - cb.method(10, 100, TestData { foo: test_data.foo.clone(), bar: test_data.bar.clone() }); - } - let callback_time = start.elapsed(); - println!("{language}-callbacks-basic: {:?}", callback_time); - - // Test callback void return - let start = Instant::now(); - for _ in 0..1000 { - cb.method_with_void_return( - 10, - 100, - TestData { foo: test_data.foo.clone(), bar: test_data.bar.clone() }, - ); - } - let callback_void_time = start.elapsed(); - println!("{language}-callbacks-void-return: {:?}", callback_void_time); - - // Test callback no args void return - let start = Instant::now(); - for _ in 0..1000 { - cb.method_with_no_args_and_void_return(); - } - let callback_no_args_time = start.elapsed(); - println!("{language}-callbacks-no-args-void-return: {:?}", callback_no_args_time); - - println!("Benchmarks complete for {language}!"); -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/benchmarks/test/benchmarks_test.dart b/uniffi/dart/fixtures/benchmarks/test/benchmarks_test.dart deleted file mode 100644 index 7bba6e37e..000000000 --- a/uniffi/dart/fixtures/benchmarks/test/benchmarks_test.dart +++ /dev/null @@ -1,122 +0,0 @@ -import 'package:test/test.dart'; -import '../benchmarks.dart'; - -class DartTestCallbackInterface implements TestCallbackInterface { - @override - String method(int a, int b, TestData data) { - // Return the bar field as expected by the benchmark - return data.bar; - } - - @override - void methodWithVoidReturn(int a, int b, TestData data) { - // Intentionally does nothing - testing void return callback overhead - } - - @override - void methodWithNoArgsAndVoidReturn() { - // Intentionally does nothing - testing minimal callback overhead - } - - @override - int runTest(TestCase testCase, int count) { - final stopwatch = Stopwatch()..start(); - - switch (testCase) { - case TestCase.function: - for (int i = 0; i < count; i++) { - testFunction( - a: 10, - b: 100, - data: TestData(foo: 'SomeStringData', bar: 'SomeMoreStringData'), - ); - } - break; - case TestCase.voidReturn: - for (int i = 0; i < count; i++) { - testVoidReturn( - a: 10, - b: 100, - data: TestData(foo: 'SomeStringData', bar: 'SomeMoreStringData'), - ); - } - break; - case TestCase.noArgsVoidReturn: - for (int i = 0; i < count; i++) { - testNoArgsVoidReturn(); - } - break; - } - - stopwatch.stop(); - return stopwatch.elapsedMicroseconds * 1000; // Convert to nanoseconds - } -} - -void main() { - group('Benchmarks', () { - test('basic function benchmarking', () { - final result = testFunction( - a: 10, - b: 100, - data: TestData(foo: 'TestFoo', bar: 'TestBar'), - ); - expect(result, equals('TestBar')); - - // Test void return - testVoidReturn( - a: 10, - b: 100, - data: TestData(foo: 'TestFoo', bar: 'TestBar'), - ); - - // Test no args void return - testNoArgsVoidReturn(); - }); - - test('callback interface benchmarking', () { - final callback = DartTestCallbackInterface(); - - // Test callback methods - final result = callback.method( - 10, - 100, - TestData(foo: 'TestFoo', bar: 'TestBar'), - ); - expect(result, equals('TestBar')); - - // Test void callback - callback.methodWithVoidReturn( - 10, - 100, - TestData(foo: 'TestFoo', bar: 'TestBar'), - ); - - // Test no-args void callback - callback.methodWithNoArgsAndVoidReturn(); - }); - - test('performance test runner', () { - final callback = DartTestCallbackInterface(); - - // Run small performance tests - final functionTime = callback.runTest(TestCase.function, 10); - expect(functionTime, greaterThan(0)); - - final voidTime = callback.runTest(TestCase.voidReturn, 10); - expect(voidTime, greaterThan(0)); - - final noArgsTime = callback.runTest(TestCase.noArgsVoidReturn, 10); - expect(noArgsTime, greaterThan(0)); - }); - - test('full benchmark suite', () { - final callback = DartTestCallbackInterface(); - - expect( - () => runBenchmarks(languageName: 'Dart', cb: callback), - returnsNormally, - ); - }); - }); -} diff --git a/uniffi/dart/fixtures/benchmarks/tests/mod.rs b/uniffi/dart/fixtures/benchmarks/tests/mod.rs deleted file mode 100644 index 229cdcff5..000000000 --- a/uniffi/dart/fixtures/benchmarks/tests/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[cfg(test)] -mod tests { - #[test] - fn test_benchmarks() { - uniffi_dart::testing::run_test("benchmarks", "src/api.udl", None).unwrap(); - } -} diff --git a/uniffi/dart/fixtures/bytes_types/Cargo.toml b/uniffi/dart/fixtures/bytes_types/Cargo.toml deleted file mode 100644 index 2a7d502da..000000000 --- a/uniffi/dart/fixtures/bytes_types/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "bytes_types" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "bytes_types" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -thiserror = "2.0" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/bytes_types/build.rs b/uniffi/dart/fixtures/bytes_types/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/bytes_types/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/bytes_types/src/api.udl b/uniffi/dart/fixtures/bytes_types/src/api.udl deleted file mode 100644 index 2e6b4494c..000000000 --- a/uniffi/dart/fixtures/bytes_types/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace bytes_types { }; diff --git a/uniffi/dart/fixtures/bytes_types/src/full api.udl b/uniffi/dart/fixtures/bytes_types/src/full api.udl deleted file mode 100644 index 3a6dc55c2..000000000 --- a/uniffi/dart/fixtures/bytes_types/src/full api.udl +++ /dev/null @@ -1,101 +0,0 @@ -namespace bytes_types { - // Basic bytes functions - sequence take_bytes(sequence v); - sequence take_bytes_with_validation(sequence v); - sequence take_empty_bytes(); - sequence get_test_bytes(); - sequence get_binary_bytes(); - - // Record functions - RecordWithBytes make_record_with_bytes(); - sequence take_record_with_bytes(RecordWithBytes rwb); - ComplexBytesRecord create_complex_bytes_record(); - ComplexBytesRecord create_empty_bytes_record(); - - // Enum functions - sequence create_bytes_enum_variants(); - sequence process_bytes_enum(BytesEnum variant); - - // Error handling functions - [Throws=BytesError] - sequence validate_bytes_length(sequence data, u32 min_length); - [Throws=BytesError] - sequence validate_bytes_content(sequence data); - [Throws=BytesError] - sequence fallible_bytes_processing(sequence data); - - // Utility functions - record> test_bytes_encodings(); - record> test_bytes_sizes(); - ComplexBytesRecord comprehensive_bytes_test(); - - // Callback testing - void call_bytes_callback_interface(BytesCallbackInterface cb); -}; - -// Records -dictionary RecordWithBytes { - sequence some_bytes; -}; - -dictionary ComplexBytesRecord { - string name; - sequence required_bytes; - sequence? optional_bytes; - sequence> bytes_list; - record> bytes_map; - u32 id; -}; - -dictionary RecordWithBytesDefaults { - string name; - sequence data; - sequence? optional_data; -}; - -// Object interface -interface BytesProcessor { - constructor(string name); - - string get_name(); - sequence reverse(sequence value); - sequence concat(sequence> arrays); - sequence> split_bytes(sequence data, u8 delimiter); - void store_bytes(sequence data); - sequence retrieve_bytes(); - RecordWithBytes process_to_record(sequence data); - sequence xor_bytes(sequence data, u8 key); - record get_stats(sequence data); -}; - -// Error enum -[Error] -enum BytesError { - "InvalidLength", - "InvalidValue", - "ProcessingFailed", -}; - -// Bytes enum -[Enum] -interface BytesEnum { - Empty(); - Small(sequence data); - Large(sequence data, string metadata); - Multiple(sequence> arrays); -}; - -// Callback interfaces -callback interface BytesCallbackInterface { - void do_nothing(); - sequence process_bytes(sequence data); - sequence with_bytes_record(RecordWithBytes record); - sequence combine_bytes(sequence first, sequence second); - boolean validate_bytes(sequence data); - record> get_bytes_info(); -}; - -callback interface BytesAsyncCallbackInterface { - sequence process_bytes_async(sequence data); - sequence> batch_process(sequence> batches); -}; diff --git a/uniffi/dart/fixtures/bytes_types/src/lib.rs b/uniffi/dart/fixtures/bytes_types/src/lib.rs deleted file mode 100644 index 4adb72a69..000000000 --- a/uniffi/dart/fixtures/bytes_types/src/lib.rs +++ /dev/null @@ -1,395 +0,0 @@ -#[uniffi::export] -fn take_bytes(v: Vec) -> Vec { - v -} - -// Borrowed `&[u8]` argument: uniffi 0.32 lowers this through the zero-copy -// `ForeignBytes` FFI path rather than the owned `RustBuffer` path. -#[uniffi::export] -fn take_bytes_by_ref(v: &[u8]) -> Vec { - v.to_vec() -} - -#[uniffi::export] -fn take_bytes_with_validation(v: Vec) -> Vec { - // Validate that it's valid UTF-8 if it should be - if let Ok(s) = std::str::from_utf8(&v) { - println!("Valid UTF-8 string: {}", s); - } - v -} - -#[uniffi::export] -fn take_empty_bytes() -> Vec { - Vec::new() -} - -#[uniffi::export] -fn get_test_bytes() -> Vec { - b"Hello, UniFFI bytes!".to_vec() -} - -#[uniffi::export] -fn get_binary_bytes() -> Vec { - vec![0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD, 0xFC] -} - -// #[derive(Debug, PartialEq)] -// pub struct RecordWithBytes { -// pub some_bytes: Vec, -// } - -// #[derive(Debug, Clone)] -// pub struct ComplexBytesRecord { -// pub name: String, -// pub required_bytes: Vec, -// pub optional_bytes: Option>, -// pub bytes_list: Vec>, -// pub bytes_map: HashMap>, -// pub id: u32, -// } - -// impl Default for ComplexBytesRecord { -// fn default() -> Self { -// Self { -// name: "default".to_string(), -// required_bytes: Vec::new(), -// optional_bytes: None, -// bytes_list: Vec::new(), -// bytes_map: HashMap::new(), -// id: 0, -// } -// } -// } - -// #[derive(Debug, Clone)] -// pub struct RecordWithBytesDefaults { -// pub name: String, -// pub data: Vec, -// pub optional_data: Option>, -// } - -// impl Default for RecordWithBytesDefaults { -// fn default() -> Self { -// Self { -// name: "default".to_string(), -// data: b"default_data".to_vec(), -// optional_data: Some(b"default_optional".to_vec()), -// } -// } -// } - -// #[uniffi::export] -// fn make_record_with_bytes() -> RecordWithBytes { -// RecordWithBytes { -// some_bytes: vec![0, 1, 2, 3, 4], -// } -// } - -// #[uniffi::export] -// fn take_record_with_bytes(rwb: RecordWithBytes) -> Vec { -// rwb.some_bytes -// } - -// #[uniffi::export] -// fn create_complex_bytes_record() -> ComplexBytesRecord { -// ComplexBytesRecord { -// name: "test_record".to_string(), -// required_bytes: b"required_data".to_vec(), -// optional_bytes: Some(b"optional_data".to_vec()), -// bytes_list: vec![ -// b"first".to_vec(), -// b"second".to_vec(), -// vec![0x01, 0x02, 0x03], -// ], -// bytes_map: [ -// ("key1".to_string(), b"value1".to_vec()), -// ("key2".to_string(), b"value2".to_vec()), -// ("binary".to_string(), vec![0xFF, 0xFE, 0xFD]), -// ] -// .into_iter() -// .collect(), -// id: 42, -// } -// } - -// #[uniffi::export] -// fn create_empty_bytes_record() -> ComplexBytesRecord { -// ComplexBytesRecord { -// name: "empty_record".to_string(), -// required_bytes: Vec::new(), -// optional_bytes: None, -// bytes_list: Vec::new(), -// bytes_map: HashMap::new(), -// id: 0, -// } -// } - -// pub struct BytesProcessor { -// name: String, -// buffer: Mutex>, -// } - -// impl BytesProcessor { -// pub fn new(name: String) -> Self { -// Self { -// name, -// buffer: Mutex::new(Vec::new()), -// } -// } - -// pub fn get_name(&self) -> String { -// self.name.clone() -// } - -// /// Reverses the bytes - equivalent to coverall fixture -// pub fn reverse(&self, mut value: Vec) -> Vec { -// value.reverse(); -// value -// } - -// /// Concatenates multiple byte arrays -// pub fn concat(&self, arrays: Vec>) -> Vec { -// arrays.into_iter().flatten().collect() -// } - -// /// Splits bytes at delimiter -// pub fn split_bytes(&self, data: Vec, delimiter: u8) -> Vec> { -// let mut result = Vec::new(); -// let mut current = Vec::new(); - -// for byte in data { -// if byte == delimiter { -// result.push(current); -// current = Vec::new(); -// } else { -// current.push(byte); -// } -// } - -// if !current.is_empty() { -// result.push(current); -// } - -// result -// } - -// /// Stores bytes in internal buffer -// pub fn store_bytes(&self, data: Vec) { -// *self.buffer.lock().unwrap() = data; -// } - -// /// Retrieves bytes from internal buffer -// pub fn retrieve_bytes(&self) -> Vec { -// self.buffer.lock().unwrap().clone() -// } - -// /// Processes bytes and returns a record -// pub fn process_to_record(&self, data: Vec) -> RecordWithBytes { -// let mut processed = data; -// processed.reverse(); -// RecordWithBytes { -// some_bytes: processed, -// } -// } - -// /// XOR operation on bytes -// pub fn xor_bytes(&self, data: Vec, key: u8) -> Vec { -// data.into_iter().map(|b| b ^ key).collect() -// } - -// /// Get bytes statistics -// pub fn get_stats(&self, data: Vec) -> HashMap { -// let mut stats = HashMap::new(); -// stats.insert("length".to_string(), data.len() as u64); -// stats.insert("sum".to_string(), data.iter().map(|&b| b as u64).sum()); -// stats.insert("max".to_string(), data.iter().map(|&b| b as u64).max().unwrap_or(0)); -// stats.insert("min".to_string(), data.iter().map(|&b| b as u64).min().unwrap_or(0)); -// stats -// } -// } - -// // ============================================================================ -// // Callback Interface with Bytes -// // ============================================================================ - -// pub trait BytesCallbackInterface { -// fn do_nothing(&self); -// fn process_bytes(&self, data: Vec) -> Vec; -// fn with_bytes_record(&self, record: RecordWithBytes) -> Vec; -// fn combine_bytes(&self, first: Vec, second: Vec) -> Vec; -// fn validate_bytes(&self, data: Vec) -> bool; -// fn get_bytes_info(&self) -> HashMap>; -// } - -// pub trait BytesAsyncCallbackInterface { -// fn process_bytes_async(&self, data: Vec) -> Vec; -// fn batch_process(&self, batches: Vec>) -> Vec>; -// } - -// // ============================================================================ -// // Functions Testing Callback Interfaces -// // ============================================================================ - -// fn call_bytes_callback_interface(cb: Box) { -// cb.do_nothing(); - -// // Test basic bytes processing -// let test_data = vec![1, 2, 3, 4, 5]; -// let result = cb.process_bytes(test_data.clone()); -// assert_eq!(result.len(), test_data.len()); - -// // Test with record -// let record = RecordWithBytes { -// some_bytes: vec![9, 8, 7], -// }; -// let record_result = cb.with_bytes_record(record); -// assert_eq!(record_result, vec![9, 8, 7]); - -// // Test combining bytes -// let combined = cb.combine_bytes(vec![1, 2], vec![3, 4]); -// assert_eq!(combined, vec![1, 2, 3, 4]); - -// // Test validation -// assert!(cb.validate_bytes(vec![1, 2, 3])); - -// // Test info retrieval -// let info = cb.get_bytes_info(); -// assert!(!info.is_empty()); -// } - -// // ============================================================================ -// // Error Handling with Bytes -// // ============================================================================ - -// #[derive(Debug, thiserror::Error)] -// pub enum BytesError { -// #[error("Invalid bytes length: {length}")] -// InvalidLength { length: usize }, -// #[error("Invalid byte value: {value}")] -// InvalidValue { value: u8 }, -// #[error("Processing failed")] -// ProcessingFailed, -// } - -// fn validate_bytes_length(data: Vec, min_length: usize) -> Result, BytesError> { -// if data.len() < min_length { -// Err(BytesError::InvalidLength { length: data.len() }) -// } else { -// Ok(data) -// } -// } - -// fn validate_bytes_content(data: Vec) -> Result, BytesError> { -// if data.iter().any(|&b| b > 127) { -// Err(BytesError::InvalidValue { value: *data.iter().find(|&&b| b > 127).unwrap() }) -// } else { -// Ok(data) -// } -// } - -// fn fallible_bytes_processing(data: Vec) -> Result, BytesError> { -// if data.is_empty() { -// Err(BytesError::ProcessingFailed) -// } else { -// Ok(data.into_iter().map(|b| b.wrapping_add(1)).collect()) -// } -// } - -// // ============================================================================ -// // Enum with Bytes -// // ============================================================================ - -// #[derive(Debug, Clone)] -// pub enum BytesEnum { -// Empty, -// Small(Vec), -// Large { data: Vec, metadata: String }, -// Multiple(Vec>), -// } - -// fn create_bytes_enum_variants() -> Vec { -// vec![ -// BytesEnum::Empty, -// BytesEnum::Small(vec![1, 2, 3]), -// BytesEnum::Large { -// data: b"large_data".to_vec(), -// metadata: "metadata".to_string(), -// }, -// BytesEnum::Multiple(vec![ -// vec![1, 2], -// vec![3, 4], -// vec![5, 6], -// ]), -// ] -// } - -// fn process_bytes_enum(variant: BytesEnum) -> Vec { -// match variant { -// BytesEnum::Empty => Vec::new(), -// BytesEnum::Small(data) => data, -// BytesEnum::Large { data, .. } => data, -// BytesEnum::Multiple(arrays) => arrays.into_iter().flatten().collect(), -// } -// } - -// // ============================================================================ -// // Utility Functions -// // ============================================================================ - -// /// Test bytes with various encodings -// fn test_bytes_encodings() -> HashMap> { -// let mut encodings = HashMap::new(); - -// encodings.insert("utf8".to_string(), "Hello, 世界!".as_bytes().to_vec()); -// encodings.insert("ascii".to_string(), b"Hello, World!".to_vec()); -// encodings.insert("binary".to_string(), vec![0x00, 0x01, 0x02, 0xFF, 0xFE, 0xFD]); -// encodings.insert("empty".to_string(), Vec::new()); -// encodings.insert("single".to_string(), vec![42]); -// encodings.insert("large".to_string(), vec![0x55; 1024]); - -// encodings -// } - -// /// Test bytes with extreme sizes -// fn test_bytes_sizes() -> HashMap> { -// let mut sizes = HashMap::new(); - -// sizes.insert("empty".to_string(), Vec::new()); -// sizes.insert("tiny".to_string(), vec![1]); -// sizes.insert("small".to_string(), vec![1; 10]); -// sizes.insert("medium".to_string(), vec![2; 1000]); -// sizes.insert("large".to_string(), vec![3; 100000]); - -// sizes -// } - -// /// Comprehensive bytes test that combines multiple patterns -// fn comprehensive_bytes_test() -> ComplexBytesRecord { -// let record = create_complex_bytes_record(); - -// // Test processing -// let processor = BytesProcessor::new("test_processor".to_string()); -// let reversed = processor.reverse(record.required_bytes.clone()); -// let concatenated = processor.concat(record.bytes_list.clone()); - -// // Create result record -// ComplexBytesRecord { -// name: "comprehensive_test".to_string(), -// required_bytes: reversed, -// optional_bytes: Some(concatenated), -// bytes_list: vec![ -// b"test1".to_vec(), -// b"test2".to_vec(), -// ], -// bytes_map: [ -// ("reversed".to_string(), reversed), -// ("concatenated".to_string(), concatenated), -// ] -// .into_iter() -// .collect(), -// id: 999, -// } -// } - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/bytes_types/test/bytes_types_test.dart b/uniffi/dart/fixtures/bytes_types/test/bytes_types_test.dart deleted file mode 100644 index fc7676fb8..000000000 --- a/uniffi/dart/fixtures/bytes_types/test/bytes_types_test.dart +++ /dev/null @@ -1,397 +0,0 @@ -import 'dart:typed_data'; - -import 'package:test/test.dart'; -import '../bytes_types.dart'; - -void main() { - group('Basic Bytes Functions', () { - test('take_bytes returns same data', () { - final input = [1, 2, 3, 4, 5]; - final result = takeBytes(v: Uint8List.fromList(input)); - expect(result, equals(input)); - }); - - test('take_bytes_by_ref (&[u8], ForeignBytes path) returns same data', () { - final input = [10, 20, 30, 40, 50]; - final result = takeBytesByRef(v: Uint8List.fromList(input)); - expect(result, equals(input)); - }); - - test('take_bytes_by_ref handles empty bytes', () { - final result = takeBytesByRef(v: Uint8List.fromList([])); - expect(result, isEmpty); - }); - - // test('take_bytes_with_validation handles UTF-8', () { - // final utf8Input = 'Hello, 世界!'.codeUnits; - // final result = takeBytesWithValidation(utf8Input); - // expect(result, equals(utf8Input)); - // }); - - // test('take_empty_bytes returns empty list', () { - // final result = takeEmptyBytes(); - // expect(result, isEmpty); - // }); - - // test('get_test_bytes returns expected content', () { - // final result = getTestBytes(); - // final expected = 'Hello, UniFFI bytes!'.codeUnits; - // expect(result, equals(expected)); - // }); - - // test('get_binary_bytes returns binary data', () { - // final result = getBinaryBytes(); - // final expected = [0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD, 0xFC]; - // expect(result, equals(expected)); - // }); - }); - - // group('Records with Bytes', () { - // test('make_record_with_bytes creates correct record', () { - // final record = makeRecordWithBytes(); - // expect(record.someBytes, equals([0, 1, 2, 3, 4])); - // }); - - // test('take_record_with_bytes extracts bytes', () { - // final record = RecordWithBytes(someBytes: [10, 20, 30]); - // final result = takeRecordWithBytes(record); - // expect(result, equals([10, 20, 30])); - // }); - - // test('create_complex_bytes_record creates complex structure', () { - // final record = createComplexBytesRecord(); - // expect(record.name, equals('test_record')); - // expect(record.requiredBytes, equals('required_data'.codeUnits)); - // expect(record.optionalBytes, equals('optional_data'.codeUnits)); - // expect(record.bytesList, hasLength(3)); - // expect(record.bytesList[0], equals('first'.codeUnits)); - // expect(record.bytesList[1], equals('second'.codeUnits)); - // expect(record.bytesList[2], equals([0x01, 0x02, 0x03])); - // expect(record.bytesMap['key1'], equals('value1'.codeUnits)); - // expect(record.bytesMap['key2'], equals('value2'.codeUnits)); - // expect(record.bytesMap['binary'], equals([0xFF, 0xFE, 0xFD])); - // expect(record.id, equals(42)); - // }); - - // test('create_empty_bytes_record creates empty structure', () { - // final record = createEmptyBytesRecord(); - // expect(record.name, equals('empty_record')); - // expect(record.requiredBytes, isEmpty); - // expect(record.optionalBytes, isNull); - // expect(record.bytesList, isEmpty); - // expect(record.bytesMap, isEmpty); - // expect(record.id, equals(0)); - // }); - // }); - - // group('BytesProcessor Object', () { - // late BytesProcessor processor; - - // setUp(() { - // processor = BytesProcessor('test_processor'); - // }); - - // test('get_name returns correct name', () { - // expect(processor.getName(), equals('test_processor')); - // }); - - // test('reverse reverses bytes correctly', () { - // final input = [1, 2, 3, 4, 5]; - // final result = processor.reverse(input); - // expect(result, equals([5, 4, 3, 2, 1])); - // }); - - // test('concat concatenates byte arrays', () { - // final input = [ - // [1, 2, 3], - // [4, 5], - // [6, 7, 8, 9], - // ]; - // final result = processor.concat(input); - // expect(result, equals([1, 2, 3, 4, 5, 6, 7, 8, 9])); - // }); - - // test('split_bytes splits on delimiter', () { - // final input = [1, 2, 0, 3, 4, 0, 5]; - // final result = processor.splitBytes(input, 0); - // expect(result, hasLength(3)); - // expect(result[0], equals([1, 2])); - // expect(result[1], equals([3, 4])); - // expect(result[2], equals([5])); - // }); - - // test('store_bytes and retrieve_bytes work together', () { - // final testData = [10, 20, 30, 40]; - // processor.storeBytes(testData); - // final retrieved = processor.retrieveBytes(); - // expect(retrieved, equals(testData)); - // }); - - // test('process_to_record creates record with reversed bytes', () { - // final input = [1, 2, 3, 4]; - // final record = processor.processToRecord(input); - // expect(record.someBytes, equals([4, 3, 2, 1])); - // }); - - // test('xor_bytes applies XOR operation', () { - // final input = [0x0F, 0xF0, 0x55, 0xAA]; - // final key = 0xFF; - // final result = processor.xorBytes(input, key); - // expect(result, equals([0xF0, 0x0F, 0xAA, 0x55])); - // }); - - // test('get_stats calculates correct statistics', () { - // final input = [1, 2, 3, 4, 5]; - // final stats = processor.getStats(input); - // expect(stats['length'], equals(5)); - // expect(stats['sum'], equals(15)); // 1+2+3+4+5 - // expect(stats['max'], equals(5)); - // expect(stats['min'], equals(1)); - // }); - - // test('get_stats handles empty array', () { - // final input = []; - // final stats = processor.getStats(input); - // expect(stats['length'], equals(0)); - // expect(stats['sum'], equals(0)); - // expect(stats['max'], equals(0)); - // expect(stats['min'], equals(0)); - // }); - // }); - - // group('Bytes Enum', () { - // test('create_bytes_enum_variants creates all variants', () { - // final variants = createBytesEnumVariants(); - // expect(variants, hasLength(4)); - - // expect(variants[0], isA()); - // expect(variants[1], isA()); - // expect(variants[2], isA()); - // expect(variants[3], isA()); - // }); - - // test('process_bytes_enum handles Empty variant', () { - // final empty = BytesEnum.empty(); - // final result = processBytesEnum(empty); - // expect(result, isEmpty); - // }); - - // test('process_bytes_enum handles Small variant', () { - // final small = BytesEnum.small([1, 2, 3]); - // final result = processBytesEnum(small); - // expect(result, equals([1, 2, 3])); - // }); - - // test('process_bytes_enum handles Large variant', () { - // final large = BytesEnum.large([10, 20, 30], 'metadata'); - // final result = processBytesEnum(large); - // expect(result, equals([10, 20, 30])); - // }); - - // test('process_bytes_enum handles Multiple variant', () { - // final multiple = BytesEnum.multiple([ - // [1, 2], - // [3, 4], - // [5, 6], - // ]); - // final result = processBytesEnum(multiple); - // expect(result, equals([1, 2, 3, 4, 5, 6])); - // }); - // }); - - // group('Error Handling', () { - // test('validate_bytes_length accepts valid length', () { - // final input = [1, 2, 3, 4, 5]; - // final result = validateBytesLength(input, 3); - // expect(result, equals(input)); - // }); - - // test('validate_bytes_length rejects short length', () { - // final input = [1, 2]; - // expect(() => validateBytesLength(input, 5), throwsA(isA())); - // }); - - // test('validate_bytes_content accepts valid content', () { - // final input = [1, 2, 3, 65, 66, 67]; // Valid ASCII - // final result = validateBytesContent(input); - // expect(result, equals(input)); - // }); - - // test('validate_bytes_content rejects invalid content', () { - // final input = [1, 2, 200]; // 200 > 127, invalid - // expect(() => validateBytesContent(input), throwsA(isA())); - // }); - - // test('fallible_bytes_processing processes non-empty data', () { - // final input = [1, 2, 3]; - // final result = fallibleBytesProcessing(input); - // expect(result, equals([2, 3, 4])); // Each byte incremented by 1 - // }); - - // test('fallible_bytes_processing rejects empty data', () { - // final input = []; - // expect(() => fallibleBytesProcessing(input), throwsA(isA())); - // }); - // }); - - // group('Utility Functions', () { - // test('test_bytes_encodings returns various encodings', () { - // final encodings = testBytesEncodings(); - // expect(encodings.containsKey('utf8'), isTrue); - // expect(encodings.containsKey('ascii'), isTrue); - // expect(encodings.containsKey('binary'), isTrue); - // expect(encodings.containsKey('empty'), isTrue); - // expect(encodings.containsKey('single'), isTrue); - // expect(encodings.containsKey('large'), isTrue); - - // expect(encodings['utf8'], equals('Hello, 世界!'.codeUnits)); - // expect(encodings['ascii'], equals('Hello, World!'.codeUnits)); - // expect(encodings['binary'], equals([0x00, 0x01, 0x02, 0xFF, 0xFE, 0xFD])); - // expect(encodings['empty'], isEmpty); - // expect(encodings['single'], equals([42])); - // expect(encodings['large'], hasLength(1024)); - // }); - - // test('test_bytes_sizes returns various sizes', () { - // final sizes = testBytesSizes(); - // expect(sizes.containsKey('empty'), isTrue); - // expect(sizes.containsKey('tiny'), isTrue); - // expect(sizes.containsKey('small'), isTrue); - // expect(sizes.containsKey('medium'), isTrue); - // expect(sizes.containsKey('large'), isTrue); - - // expect(sizes['empty'], isEmpty); - // expect(sizes['tiny'], hasLength(1)); - // expect(sizes['small'], hasLength(10)); - // expect(sizes['medium'], hasLength(1000)); - // expect(sizes['large'], hasLength(100000)); - // }); - - // test('comprehensive_bytes_test creates complex result', () { - // final result = comprehensiveBytesTest(); - // expect(result.name, equals('comprehensive_test')); - // expect(result.requiredBytes, isNotEmpty); - // expect(result.optionalBytes, isNotNull); - // expect(result.bytesList, hasLength(2)); - // expect(result.bytesMap.containsKey('reversed'), isTrue); - // expect(result.bytesMap.containsKey('concatenated'), isTrue); - // expect(result.id, equals(999)); - // }); - // }); - - // group('Callback Interface', () { - // test('call_bytes_callback_interface calls callback methods', () { - // final callback = TestBytesCallback(); - - // // This should not throw - // expect(() => callBytesCallbackInterface(callback), returnsNormally); - - // // Verify callback was called - // expect(callback.doNothingCalled, isTrue); - // expect(callback.processBytesCalled, isTrue); - // expect(callback.withBytesRecordCalled, isTrue); - // expect(callback.combineBytesCalled, isTrue); - // expect(callback.validateBytesCalled, isTrue); - // expect(callback.getBytesInfoCalled, isTrue); - // }); - // }); - - // group('Edge Cases and Performance', () { - // test('handles very large byte arrays', () { - // final largeArray = List.filled(1000000, 42); - // final result = takeBytes(largeArray); - // expect(result.length, equals(1000000)); - // expect(result.every((b) => b == 42), isTrue); - // }); - - // test('handles bytes with all possible values', () { - // final allBytes = List.generate(256, (i) => i); - // final result = takeBytes(allBytes); - // expect(result.length, equals(256)); - // expect(result, equals(allBytes)); - // }); - - // test('BytesProcessor handles rapid operations', () { - // final processor = BytesProcessor('performance_test'); - // final testData = [1, 2, 3, 4, 5]; - - // // Perform multiple operations rapidly - // for (int i = 0; i < 100; i++) { - // final reversed = processor.reverse(testData); - // expect(reversed, equals([5, 4, 3, 2, 1])); - // } - // }); - - // test('complex record with deeply nested bytes', () { - // final complexRecord = ComplexBytesRecord( - // name: 'complex_test', - // requiredBytes: List.generate(1000, (i) => i % 256), - // optionalBytes: List.generate(500, (i) => (i * 2) % 256), - // bytesList: List.generate( - // 10, - // (i) => List.generate(100, (j) => (i + j) % 256), - // ), - // bytesMap: Map.fromEntries( - // List.generate( - // 5, - // (i) => MapEntry('key$i', List.generate(200, (j) => (i * j) % 256)), - // ), - // ), - // id: 12345, - // ); - - // final extractedBytes = takeRecordWithBytes( - // RecordWithBytes(someBytes: complexRecord.requiredBytes), - // ); - // expect(extractedBytes.length, equals(1000)); - // }); - // }); -} - -// // Test implementation of BytesCallbackInterface -// class TestBytesCallback implements BytesCallbackInterface { -// bool doNothingCalled = false; -// bool processBytesCalled = false; -// bool withBytesRecordCalled = false; -// bool combineBytesCalled = false; -// bool validateBytesCalled = false; -// bool getBytesInfoCalled = false; - -// @override -// void doNothing() { -// doNothingCalled = true; -// } - -// @override -// List processBytes(List data) { -// processBytesCalled = true; -// return data.reversed.toList(); -// } - -// @override -// List withBytesRecord(RecordWithBytes record) { -// withBytesRecordCalled = true; -// return record.someBytes; -// } - -// @override -// List combineBytes(List first, List second) { -// combineBytesCalled = true; -// return [...first, ...second]; -// } - -// @override -// bool validateBytes(List data) { -// validateBytesCalled = true; -// return data.isNotEmpty; -// } - -// @override -// Map> getBytesInfo() { -// getBytesInfoCalled = true; -// return { -// 'test_key': [1, 2, 3], -// 'another_key': [4, 5, 6], -// }; -// } -// } diff --git a/uniffi/dart/fixtures/bytes_types/tests/mod.rs b/uniffi/dart/fixtures/bytes_types/tests/mod.rs deleted file mode 100644 index 0b66228cd..000000000 --- a/uniffi/dart/fixtures/bytes_types/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn bytes_types() -> Result<()> { - uniffi_dart::testing::run_test("bytes_types", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/callbacks/Cargo.toml b/uniffi/dart/fixtures/callbacks/Cargo.toml deleted file mode 100644 index 5a3d036de..000000000 --- a/uniffi/dart/fixtures/callbacks/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "callbacks" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "callbacks" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -uniffi-dart = { path = "../../" } -thiserror = "1.0" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/callbacks/build.rs b/uniffi/dart/fixtures/callbacks/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/callbacks/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/callbacks/src/api.udl b/uniffi/dart/fixtures/callbacks/src/api.udl deleted file mode 100644 index 60dbc5840..000000000 --- a/uniffi/dart/fixtures/callbacks/src/api.udl +++ /dev/null @@ -1,88 +0,0 @@ -namespace callbacks { }; - -// Record types used only in callback interface compound positions -// (sequence and Record?) to test FfiConverter generation. -dictionary Item { - string name; - u64 value; -}; - -dictionary Tag { - u32 id; - string label; -}; - -[Error] -enum SimpleError { - "BadArgument", - "UnexpectedError", -}; - -[Error] -interface ComplexError { - ReallyBadArgument(i32 code); - UnexpectedErrorWithReason(string reason); -}; - -/// These objects are implemented by the foreign language and passed -/// to Rust. Rust then calls methods on it when it needs to. -/// -/// Some methods throw SimpleError and some throw ComplexError so that we can test both field-less and fielded errors -callback interface ForeignGetters { - [Throws=SimpleError] - boolean get_bool(boolean v, boolean argument_two); - [Throws=SimpleError] - string get_string(string v, boolean arg2); - [Throws=ComplexError] - string? get_option(string? v, boolean arg2); - [Throws=SimpleError] - sequence get_list(sequence v, boolean arg2); - [Throws=SimpleError] - void get_nothing(string v); - // Test compound types wrapping records in callback signatures - sequence get_items(sequence v); - Tag? get_tag(Tag? v); -}; - -/// These objects are implemented in Rust, and call out to `ForeignGetters` -/// to get the value. -interface RustGetters { - constructor(); - [Throws=SimpleError] - boolean get_bool(ForeignGetters callback, boolean v, boolean argument_two); - [Throws=SimpleError] - string get_string(ForeignGetters callback, string v, boolean arg2); - [Throws=ComplexError] - string? get_option(ForeignGetters callback, string? v, boolean arg2); - [Throws=SimpleError] - sequence get_list(ForeignGetters callback, sequence v, boolean arg2); - [Throws=SimpleError] - string? get_string_optional_callback(ForeignGetters? callback, string v, boolean arg2); - [Throws=SimpleError] - void get_nothing(ForeignGetters callback, string v); - // Test compound types wrapping records - sequence get_items(ForeignGetters callback, sequence v); - Tag? get_tag(ForeignGetters callback, Tag? v); -}; - -/// These objects are implemented by the foreign language and passed -/// to Rust. Rust then calls methods on it when it needs to. -/// Rust developers need to declare these traits extending `Send` so -/// they can be stored in Rust— i.e. not passed in as an argument to -/// be used immediately. -/// -/// These methods don't throw any error so that we can test older callback -//interfaces that don't support them. -callback interface StoredForeignStringifier { - string from_simple_type(i32 value); - // Test if types are collected from callback interfaces. - // Dart compile-time error if not. - string from_complex_type(sequence? values); -}; - -/// Rust object that uses the StoredForeignStringifier to produce string representations -/// of passed arguments. -interface RustStringifier { - constructor(StoredForeignStringifier callback); - string from_simple_type(i32 value); -}; diff --git a/uniffi/dart/fixtures/callbacks/src/lib.rs b/uniffi/dart/fixtures/callbacks/src/lib.rs deleted file mode 100644 index affdbe18b..000000000 --- a/uniffi/dart/fixtures/callbacks/src/lib.rs +++ /dev/null @@ -1,205 +0,0 @@ -use std::sync::{Arc, Mutex}; - -pub struct Item { - pub name: String, - pub value: u64, -} - -pub struct Tag { - pub id: u32, - pub label: String, -} - -trait ForeignGetters: Send + Sync { - fn get_bool(&self, v: bool, argument_two: bool) -> Result; - fn get_string(&self, v: String, arg2: bool) -> Result; - fn get_option(&self, v: Option, arg2: bool) -> Result, ComplexError>; - fn get_list(&self, v: Vec, arg2: bool) -> Result, SimpleError>; - fn get_nothing(&self, v: String) -> Result<(), SimpleError>; - fn get_items(&self, v: Vec) -> Vec; - fn get_tag(&self, v: Option) -> Option; -} - -#[derive(Debug, thiserror::Error)] -pub enum SimpleError { - #[error("BadArgument")] - BadArgument, - #[error("InternalTelephoneError")] - UnexpectedError, -} - -#[derive(Debug, thiserror::Error)] -pub enum ComplexError { - #[error("ReallyBadArgument")] - ReallyBadArgument { code: i32 }, - #[error("InternalTelephoneError")] - UnexpectedErrorWithReason { reason: String }, -} - -impl From for SimpleError { - fn from(_: uniffi::UnexpectedUniFFICallbackError) -> SimpleError { - SimpleError::UnexpectedError - } -} - -impl From for ComplexError { - fn from(e: uniffi::UnexpectedUniFFICallbackError) -> ComplexError { - ComplexError::UnexpectedErrorWithReason { reason: e.reason } - } -} - -#[derive(Debug, Clone)] -pub struct RustGetters; - -impl RustGetters { - pub fn new() -> Self { - RustGetters - } - fn get_bool( - &self, - callback: Box, - v: bool, - argument_two: bool, - ) -> Result { - callback.get_bool(v, argument_two) - } - fn get_string( - &self, - callback: Box, - v: String, - arg2: bool, - ) -> Result { - callback.get_string(v, arg2) - } - fn get_option( - &self, - callback: Box, - v: Option, - arg2: bool, - ) -> Result, ComplexError> { - callback.get_option(v, arg2) - } - fn get_list( - &self, - callback: Box, - v: Vec, - arg2: bool, - ) -> Result, SimpleError> { - callback.get_list(v, arg2) - } - - fn get_string_optional_callback( - &self, - callback: Option>, - v: String, - arg2: bool, - ) -> Result, SimpleError> { - callback.map(|c| c.get_string(v, arg2)).transpose() - } - - fn get_nothing(&self, callback: Box, v: String) -> Result<(), SimpleError> { - callback.get_nothing(v) - } - - fn get_items(&self, callback: Box, v: Vec) -> Vec { - callback.get_items(v) - } - - fn get_tag(&self, callback: Box, v: Option) -> Option { - callback.get_tag(v) - } -} - -// TODO: Add error cases to test that the error is returned - -impl Default for RustGetters { - fn default() -> Self { - Self::new() - } -} - -// Use `Send+Send` because we want to store the callback in an exposed -// `Send+Sync` object. -#[allow(clippy::wrong_self_convention)] -trait StoredForeignStringifier: Send + Sync + std::fmt::Debug { - fn from_simple_type(&self, value: i32) -> String; - #[allow(dead_code, reason = "the fixture keeps the upstream callback shape")] - fn from_complex_type(&self, values: Option>>) -> String; -} - -#[derive(Debug)] -pub struct RustStringifier { - callback: Box, -} - -impl RustStringifier { - fn new(callback: Box) -> Self { - RustStringifier { callback } - } - - #[allow(clippy::wrong_self_convention)] - fn from_simple_type(&self, value: i32) -> String { - self.callback.from_simple_type(value) - } -} - -#[uniffi::export(with_foreign)] -pub trait JsonEventPersister: Send + Sync { - fn save(&self, event: String); - fn load(&self) -> Vec; - fn close(&self); -} - -#[derive(Debug, Default, uniffi::Object)] -pub struct InMemoryEventPersister { - events: Mutex>, -} - -static PERSISTER_DROP_COUNT: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -impl Drop for InMemoryEventPersister { - fn drop(&mut self) { - PERSISTER_DROP_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } -} - -#[uniffi::export] -pub fn persister_drop_count() -> u64 { - PERSISTER_DROP_COUNT.load(std::sync::atomic::Ordering::SeqCst) as u64 -} - -#[uniffi::export] -impl InMemoryEventPersister { - #[uniffi::constructor] - pub fn new() -> Arc { - Arc::new(Self::default()) - } - - pub fn as_persister(self: Arc) -> Arc { - self - } -} - -impl JsonEventPersister for InMemoryEventPersister { - fn save(&self, event: String) { - self.events.lock().expect("event persister lock poisoned").push(event); - } - - fn load(&self) -> Vec { - self.events.lock().expect("event persister lock poisoned").clone() - } - - fn close(&self) {} -} - -#[uniffi::export] -pub fn save_and_load_persister( - persister: Arc, - event: String, -) -> Vec { - persister.save(event); - persister.load() -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/callbacks/test/callbacks_test.dart b/uniffi/dart/fixtures/callbacks/test/callbacks_test.dart deleted file mode 100644 index 99d0cd309..000000000 --- a/uniffi/dart/fixtures/callbacks/test/callbacks_test.dart +++ /dev/null @@ -1,273 +0,0 @@ -import 'package:test/test.dart'; -import '../callbacks.dart'; // Adjust import to your generated code and/or callback interfaces. - -class DartGetters extends ForeignGetters { - @override - bool getBool(bool v, bool argumentTwo) => v ^ argumentTwo; - - @override - String getString(String v, bool arg2) { - if (v == 'BadArgument') { - // Throw a UniFFI-generated exception type corresponding to BadArgument - throw SimpleException.badArgument; - } - if (v == 'UnexpectedError') { - throw StateError('unexpected value'); - } - return arg2 ? v : '1234567890123'; - } - - @override - String? getOption(String? v, bool arg2) { - if (v == 'BadArgument') { - throw ReallyBadArgumentComplexException(20); // Example of a complex error - } - if (v == 'UnexpectedError') { - throw StateError('unexpected value'); - } - return arg2 ? v?.toUpperCase() : v; - } - - @override - List getList(List v, bool arg2) => arg2 ? v : []; - - @override - void getNothing(String v) { - if (v == 'BadArgument') { - throw SimpleException.badArgument; - } - if (v == 'UnexpectedError') { - throw StateError('unexpected value'); - } - } - - @override - List getItems(List v) => v; - - @override - Tag? getTag(Tag? v) => v; -} - -class StoredDartStringifier extends StoredForeignStringifier { - @override - String fromSimpleType(int value) => 'dart: $value'; - - @override - String fromComplexType(List? values) => 'dart: $values'; -} - -void main() { - ensureInitialized(); - // Initialize all VTables - initForeignGettersVTable(); - initStoredForeignStringifierVTable(); - - final callback = DartGetters(); - final rustGetters = RustGetters(); - final rustStringifier = RustStringifier(callback: StoredDartStringifier()); - - test('roundtrip getBool through callback', () { - final flag = true; - for (final v in [true, false]) { - final expected = callback.getBool(v, flag); - final observed = rustGetters.getBool( - callback: callback, - v: v, - argumentTwo: flag, - ); - expect(observed, equals(expected)); - } - }); - - test('roundtrip getList through callback', () { - final flag = true; - for (final v in [ - [1, 2], - [0, 1], - ]) { - final expected = callback.getList(v, flag); - final observed = rustGetters.getList( - callback: callback, - v: v, - arg2: flag, - ); - expect(observed, equals(expected)); - } - }); - - test('roundtrip getString through callback', () { - final flag = true; - for (final v in ["Hello", "world"]) { - final expected = callback.getString(v, flag); - final observed = rustGetters.getString( - callback: callback, - v: v, - arg2: flag, - ); - expect(observed, equals(expected)); - } - }); - - test('roundtrip getOption through callback', () { - final flag = true; - for (final v in ["Some"]) { - final expected = callback.getOption(v, flag); - final observed = rustGetters.getOption( - callback: callback, - v: v, - arg2: flag, - ); - expect(observed, equals(expected)); - } - }); - - test('getStringOptionalCallback works', () { - expect( - rustGetters.getStringOptionalCallback( - callback: callback, - v: "1234567890123", - arg2: false, - ), - equals("1234567890123"), - ); - // Passing null as the callback - expect( - rustGetters.getStringOptionalCallback( - callback: null, - v: "1234567890123", - arg2: false, - ), - isNull, - ); - }); - - test('getNothing should not throw with normal argument', () { - // Should not throw - rustGetters.getNothing(callback: callback, v: "1234567890123"); - }); - - test('roundtrip getItems (sequence) through callback', () { - final items = [ - Item(name: 'foo', value: 100), - Item(name: 'bar', value: 200), - ]; - final result = rustGetters.getItems(callback: callback, v: items); - expect(result.length, equals(2)); - expect(result[0].name, equals('foo')); - expect(result[0].value, equals(100)); - expect(result[1].name, equals('bar')); - expect(result[1].value, equals(200)); - }); - - test('roundtrip getTag (Optional) through callback', () { - final tag = Tag(id: 42, label: 'test'); - final result = rustGetters.getTag(callback: callback, v: tag); - expect(result, isNotNull); - expect(result!.id, equals(42)); - expect(result.label, equals('test')); - - // Also test with null - final nullResult = rustGetters.getTag(callback: callback, v: null); - expect(nullResult, isNull); - }); - - test( - 'Rust-owned with_foreign callback can be lifted and called from Dart', - () { - final persister = InMemoryEventPersister().asPersister(); - - persister.save('receiver-created'); - persister.save('receiver-saved'); - - expect(persister.load(), equals(['receiver-created', 'receiver-saved'])); - persister.close(); - }, - ); - - test('Rust-owned with_foreign callback can be passed back into Rust', () { - final persister = InMemoryEventPersister().asPersister(); - - expect( - saveAndLoadPersister(persister: persister, event: 'payjoin-session'), - equals(['payjoin-session']), - ); - }); - - test('getString preserves expected SimpleException.BadArgument', () { - expect( - () => rustGetters.getString( - callback: callback, - v: "BadArgument", - arg2: true, - ), - throwsA(SimpleException.badArgument), - ); - }); - - test('getString maps unexpected callback exception through SimpleError', () { - expect( - () => rustGetters.getString( - callback: callback, - v: "UnexpectedError", - arg2: false, - ), - throwsA(SimpleException.unexpectedError), - ); - }); - - test('getOption preserves expected ReallyBadArgumentComplexException', () { - expect( - () => rustGetters.getOption( - callback: callback, - v: "BadArgument", - arg2: false, - ), - throwsA( - predicate( - (e) => e is ReallyBadArgumentComplexException && e.code == 20, - ), - ), - ); - }); - - test('getOption maps unexpected callback exception through ComplexError', () { - expect( - () => rustGetters.getOption( - callback: callback, - v: "UnexpectedError", - arg2: false, - ), - throwsA(isA()), - ); - }); - - test('getNothing preserves expected SimpleException.BadArgument', () { - expect( - () => rustGetters.getNothing(callback: callback, v: "BadArgument"), - throwsA(SimpleException.badArgument), - ); - }); - - test('getNothing maps unexpected callback exception through SimpleError', () { - expect( - () => rustGetters.getNothing(callback: callback, v: "UnexpectedError"), - throwsA(SimpleException.unexpectedError), - ); - }); - - // test('destroy RustGetters', () { - // rustGetters.dispose(); - // // No assertions; just ensure no errors are thrown. - // }); - - test('RustStringifier constructed with callback', () { - for (final v in [1, 2]) { - expect(rustStringifier.fromSimpleType(value: v), equals('dart: $v')); - } - }); - - // // Clean up - // tearDownAll(() { - // rustStringifier.dispose(); - // }); -} diff --git a/uniffi/dart/fixtures/callbacks/test/disposal_allocation_cases.dart b/uniffi/dart/fixtures/callbacks/test/disposal_allocation_cases.dart deleted file mode 100644 index b355cebc9..000000000 --- a/uniffi/dart/fixtures/callbacks/test/disposal_allocation_cases.dart +++ /dev/null @@ -1,28 +0,0 @@ -import 'package:test/test.dart'; - -import '../callbacks.dart'; -import 'tracking_allocator.dart' as tracker; - -void main() { - tearDown(tracker.calloc.reset); - - test( - 'foreign trait disposal stays retryable when status allocation fails', - () { - final before = persisterDropCount(); - final owner = InMemoryEventPersister(); - final persister = owner.asPersister(); - tracker.calloc.failAfter = 0; - expect(() => (persister as dynamic).dispose(), throwsStateError); - tracker.calloc.failAfter = null; - (persister as dynamic).dispose(); - expect(() => persister.load(), throwsStateError); - (persister as dynamic).dispose(); - // The owner still holds its own reference. - expect(persisterDropCount(), before); - owner.dispose(); - expect(persisterDropCount(), before + 1); - expect(tracker.calloc.live, isEmpty); - }, - ); -} diff --git a/uniffi/dart/fixtures/callbacks/test/disposal_allocation_test.dart b/uniffi/dart/fixtures/callbacks/test/disposal_allocation_test.dart deleted file mode 100644 index 714881d3d..000000000 --- a/uniffi/dart/fixtures/callbacks/test/disposal_allocation_test.dart +++ /dev/null @@ -1,64 +0,0 @@ -import 'dart:io'; - -import 'package:test/test.dart'; - -void main() { - test('disposal survives injected status allocation failure', () async { - // Run a child suite in an isolated copy of this package with an - // instrumented allocator. The child's build hooks replace the native - // library, so it must not share this run's package directory. - final work = Directory.systemTemp.createTempSync('disposal_allocation'); - try { - await _copyPackage(Directory.current, work); - final pubGet = await Process.run(Platform.resolvedExecutable, [ - 'pub', - 'get', - '--offline', - ], workingDirectory: work.path); - print(pubGet.stdout); - print(pubGet.stderr); - expect(pubGet.exitCode, 0); - for (final name in ['callbacks.dart', 'uniffi_runtime.dart']) { - final file = File('${work.path}/$name'); - final source = file.readAsStringSync(); - final import = RegExp(r'''import ["']package:ffi/ffi.dart["'];'''); - expect(import.allMatches(source), hasLength(1)); - file.writeAsStringSync( - source.replaceFirst( - import, - 'import "package:ffi/ffi.dart" hide calloc;\n' - 'import "test/tracking_allocator.dart";', - ), - ); - } - final result = await Process.run(Platform.resolvedExecutable, [ - 'test', - 'test/disposal_allocation_cases.dart', - '--reporter', - 'expanded', - ], workingDirectory: work.path); - print(result.stdout); - print(result.stderr); - expect(result.exitCode, 0); - } finally { - work.deleteSync(recursive: true); - } - }, timeout: Timeout(Duration(minutes: 3))); -} - -Future _copyPackage(Directory from, Directory to) async { - to.createSync(recursive: true); - for (final entity in from.listSync()) { - final name = entity.uri.pathSegments - .where((segment) => segment.isNotEmpty) - .last; - if (name == '.dart_tool') { - continue; - } - if (entity is Directory) { - await _copyPackage(entity, Directory('${to.path}/$name')); - } else { - File(entity.path).copySync('${to.path}/$name'); - } - } -} diff --git a/uniffi/dart/fixtures/callbacks/test/tracking_allocator.dart b/uniffi/dart/fixtures/callbacks/test/tracking_allocator.dart deleted file mode 100644 index e661da86b..000000000 --- a/uniffi/dart/fixtures/callbacks/test/tracking_allocator.dart +++ /dev/null @@ -1,34 +0,0 @@ -import 'dart:ffi'; - -import 'package:ffi/ffi.dart' as ffi; - -class TrackingAllocator implements Allocator { - final live = {}; - int? failAfter; - - @override - Pointer allocate(int byteCount, {int? alignment}) { - if (failAfter == 0) throw StateError('injected allocation failure'); - if (failAfter != null) failAfter = failAfter! - 1; - final pointer = ffi.calloc.allocate(byteCount, alignment: alignment); - live[pointer.address] = byteCount; - return pointer; - } - - @override - void free(Pointer pointer) { - if (live.remove(pointer.address) == null) { - throw StateError('free of untracked pointer'); - } - ffi.calloc.free(pointer); - } - - void reset() { - failAfter = null; - for (final address in live.keys.toList()) { - free(Pointer.fromAddress(address)); - } - } -} - -final calloc = TrackingAllocator(); diff --git a/uniffi/dart/fixtures/callbacks/tests/mod.rs b/uniffi/dart/fixtures/callbacks/tests/mod.rs deleted file mode 100644 index 3e0132e7e..000000000 --- a/uniffi/dart/fixtures/callbacks/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn callbacks() -> Result<()> { - uniffi_dart::testing::run_test("callbacks", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/custom_types/Cargo.toml b/uniffi/dart/fixtures/custom_types/Cargo.toml deleted file mode 100644 index 62adb0c83..000000000 --- a/uniffi/dart/fixtures/custom_types/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "custom_types" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "dart_custom_types" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/custom_types/build.rs b/uniffi/dart/fixtures/custom_types/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/custom_types/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/custom_types/src/api.udl b/uniffi/dart/fixtures/custom_types/src/api.udl deleted file mode 100644 index 543bfa9ff..000000000 --- a/uniffi/dart/fixtures/custom_types/src/api.udl +++ /dev/null @@ -1,33 +0,0 @@ -[Custom] -typedef bytes JsonBuffer; - -dictionary ZenEngineTrace { - string id; - JsonBuffer value; -}; - -dictionary ZenEngineResponse { - string performance; - JsonBuffer result; - record? trace; -}; - -// Acronym-named custom type + records, to guard identifier-casing regressions. -[Custom] -typedef string URLString; - -dictionary HTTPMetadata { - URLString url; - u32 status; -}; - -dictionary APIResult { - HTTPMetadata primary; - HTTPMetadata? fallback; -}; - -namespace custom_types { - ZenEngineResponse get_zen_engine_response(); - ZenEngineResponse return_zen_engine_response(ZenEngineResponse response); - APIResult roundtrip_api_result(APIResult value); -}; diff --git a/uniffi/dart/fixtures/custom_types/src/lib.rs b/uniffi/dart/fixtures/custom_types/src/lib.rs deleted file mode 100644 index 80a61a9c6..000000000 --- a/uniffi/dart/fixtures/custom_types/src/lib.rs +++ /dev/null @@ -1,69 +0,0 @@ -// This fixture deliberately uses non-idiomatic, all-caps-acronym type names -// (`URLString`, `HTTPMetadata`, `APIResult`) to exercise identifier-casing in -// the Dart generator. That is exactly what `clippy::upper_case_acronyms` -// (in aggressive mode) would flag, so allow it here on purpose. -#![allow(clippy::upper_case_acronyms)] - -use std::collections::HashMap; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct JsonBuffer(pub Vec); - -uniffi::custom_newtype!(JsonBuffer, Vec); - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ZenEngineTrace { - pub id: String, - pub value: JsonBuffer, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ZenEngineResponse { - pub performance: String, - pub result: JsonBuffer, - pub trace: Option>, -} - -pub fn get_zen_engine_response() -> ZenEngineResponse { - ZenEngineResponse { - performance: "ready".to_string(), - result: JsonBuffer(vec![1, 2, 3]), - trace: Some(HashMap::from([( - "primary".to_string(), - ZenEngineTrace { id: "primary".to_string(), value: JsonBuffer(vec![4, 5, 6]) }, - )])), - } -} - -pub fn return_zen_engine_response(response: ZenEngineResponse) -> ZenEngineResponse { - response -} - -// Regression coverage for identifier casing of names containing all-caps -// acronyms, so `class_name()` normalizes `URLString` to `UrlString`, for example. -// Here we're testing several examples in different positions. -#[allow(clippy::upper_case_acronyms)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct URLString(pub String); - -uniffi::custom_newtype!(URLString, String); - -#[allow(clippy::upper_case_acronyms)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct HTTPMetadata { - pub url: URLString, - pub status: u32, -} - -#[allow(clippy::upper_case_acronyms)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct APIResult { - pub primary: HTTPMetadata, - pub fallback: Option, -} - -pub fn roundtrip_api_result(value: APIResult) -> APIResult { - value -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/custom_types/test/custom_types_test.dart b/uniffi/dart/fixtures/custom_types/test/custom_types_test.dart deleted file mode 100644 index 8f643f8fd..000000000 --- a/uniffi/dart/fixtures/custom_types/test/custom_types_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -import 'dart:typed_data'; - -import 'package:test/test.dart'; -import '../custom_types.dart'; - -void main() { - test('custom alias bytes and nested map helpers round trip', () { - final response = getZenEngineResponse(); - - expect(response.performance, equals('ready')); - expect(response.result, orderedEquals([1, 2, 3])); - expect(response.trace, isNotNull); - expect(response.trace!['primary']!.id, equals('primary')); - expect(response.trace!['primary']!.value, orderedEquals([4, 5, 6])); - - final manual = ZenEngineResponse( - performance: 'manual', - result: Uint8List.fromList([9, 8, 7]), - trace: { - 'manual': ZenEngineTrace( - id: 'manual', - value: Uint8List.fromList([6, 5, 4]), - ), - }, - ); - final roundTrip = returnZenEngineResponse(response: manual); - - expect(roundTrip.performance, equals('manual')); - expect(roundTrip.result, orderedEquals([9, 8, 7])); - expect(roundTrip.trace!['manual']!.id, equals('manual')); - expect(roundTrip.trace!['manual']!.value, orderedEquals([6, 5, 4])); - }); - - test('acronym-named custom and record types round trip', () { - final value = ApiResult( - primary: HttpMetadata(url: 'https://primary.example', status: 200), - fallback: HttpMetadata(url: 'https://fallback.example', status: 503), - ); - - final roundTrip = roundtripApiResult(value: value); - - expect(roundTrip.primary.url, equals('https://primary.example')); - expect(roundTrip.primary.status, equals(200)); - expect(roundTrip.fallback!.url, equals('https://fallback.example')); - expect(roundTrip.fallback!.status, equals(503)); - }); -} diff --git a/uniffi/dart/fixtures/custom_types/tests/mod.rs b/uniffi/dart/fixtures/custom_types/tests/mod.rs deleted file mode 100644 index b2d62db22..000000000 --- a/uniffi/dart/fixtures/custom_types/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn custom_types() -> Result<()> { - uniffi_dart::testing::run_test("custom_types", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/dart_async/Cargo.toml b/uniffi/dart/fixtures/dart_async/Cargo.toml deleted file mode 100644 index d5e8ffcc9..000000000 --- a/uniffi/dart/fixtures/dart_async/Cargo.toml +++ /dev/null @@ -1,31 +0,0 @@ -[package] -name = "dart_async" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "dart_async" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true, features = ["tokio", "cli", "scaffolding-ffi-buffer-fns"] } -async-trait = "0.1" -futures = "0.3" -tokio = { version = "1.38.2", features = ["time", "sync"] } -once_cell = "1.18.0" -thiserror = "2" - -[build-dependencies] -uniffi = { workspace = true, features = ["build", "scaffolding-ffi-buffer-fns"] } -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/dart_async/build.rs b/uniffi/dart/fixtures/dart_async/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/dart_async/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/dart_async/src/api.udl b/uniffi/dart/fixtures/dart_async/src/api.udl deleted file mode 100644 index d43c39b43..000000000 --- a/uniffi/dart/fixtures/dart_async/src/api.udl +++ /dev/null @@ -1,24 +0,0 @@ -namespace dart_async { - // UDL-defined async functions (testing UDL vs proc-macro async support) - [Async] - boolean always_ready(); -}; - -// UDL-defined async trait interface -[Trait] -interface SayAfterUdlTrait { - [Async] - string say_after(u16 ms, string who); -}; - -// UDL-defined async object interface -interface UdlMegaphone { - [Async] - constructor(); - - [Async, Name="secondary"] - constructor(); - - [Async] - string say_after(u16 ms, string who); -}; diff --git a/uniffi/dart/fixtures/dart_async/src/lib.rs b/uniffi/dart/fixtures/dart_async/src/lib.rs deleted file mode 100644 index 2f58965c1..000000000 --- a/uniffi/dart/fixtures/dart_async/src/lib.rs +++ /dev/null @@ -1,500 +0,0 @@ -use std::future::Future; -use std::pin::Pin; -use std::sync::{Arc, Mutex, MutexGuard}; -use std::task::{Context, Poll, Waker}; -use std::thread; -use std::time::Duration; - -use futures::future::{AbortHandle, Abortable, Aborted}; -use once_cell::sync::Lazy; - -/// Non-blocking timer future. -pub struct TimerFuture { - shared_state: Arc>, -} - -struct SharedState { - completed: bool, - waker: Option, -} - -impl Future for TimerFuture { - type Output = (); - - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - let mut shared_state = self.shared_state.lock().unwrap(); - if shared_state.completed { - Poll::Ready(()) - } else { - shared_state.waker = Some(cx.waker().clone()); - Poll::Pending - } - } -} - -impl TimerFuture { - pub fn new(duration: Duration) -> Self { - let shared_state = Arc::new(Mutex::new(SharedState { completed: false, waker: None })); - - let thread_shared_state = shared_state.clone(); - // Let's mimic an event coming from somewhere else, like the system. - thread::spawn(move || { - thread::sleep(duration); - let mut shared_state: MutexGuard<_> = thread_shared_state.lock().unwrap(); - shared_state.completed = true; - if let Some(waker) = shared_state.waker.take() { - waker.wake(); - } - }); - - Self { shared_state } - } -} - -/// Non-blocking timer future that intentionally misbehaves. -pub struct BrokenTimerFuture { - shared_state: Arc>, -} - -impl Future for BrokenTimerFuture { - type Output = (); - - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - let mut shared_state = self.shared_state.lock().unwrap(); - if shared_state.completed { - Poll::Ready(()) - } else { - shared_state.waker = Some(cx.waker().clone()); - Poll::Pending - } - } -} - -impl BrokenTimerFuture { - pub fn new(duration: Duration, fail_after: Duration) -> Self { - let shared_state = Arc::new(Mutex::new(SharedState { completed: false, waker: None })); - - let thread_shared_state = shared_state.clone(); - // Let's mimic an event coming from somewhere else, like the system. - thread::spawn(move || { - thread::sleep(duration); - let mut shared_state: MutexGuard<_> = thread_shared_state.lock().unwrap(); - shared_state.completed = true; - if let Some(waker) = shared_state.waker.take() { - // Do not consume `waker`. - waker.wake_by_ref(); - // And this is the important part. We are going to call `wake()` a second time. - if fail_after.is_zero() { - waker.wake(); - } else { - thread::spawn(move || { - thread::sleep(fail_after); - waker.wake(); - }); - } - } - }); - - Self { shared_state } - } -} - -#[uniffi::export] -pub fn greet(who: String) -> String { - format!("Hello, {who}") -} - -/// Async function that is immediately ready. Declared in the UDL to ensure UDL async works. -pub async fn always_ready() -> bool { - true -} - -#[uniffi::export] -pub async fn void() {} - -#[uniffi::export] -pub async fn say() -> String { - TimerFuture::new(Duration::from_secs(2)).await; - "Hello, Future!".to_string() -} - -#[uniffi::export] -pub async fn say_after(ms: u16, who: String) -> String { - TimerFuture::new(Duration::from_millis(ms.into())).await; - format!("Hello, {who}!") -} - -#[uniffi::export] -pub async fn sleep(ms: u16) -> bool { - TimerFuture::new(Duration::from_millis(ms.into())).await; - true -} - -#[uniffi::export] -pub async fn sleep_no_return(ms: u16) { - TimerFuture::new(Duration::from_millis(ms.into())).await; -} - -// Our error. -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum MyError { - #[error("Foo")] - Foo, -} - -// An async function that can throw. -#[uniffi::export] -pub async fn fallible_me(do_fail: bool) -> Result { - if do_fail { - Err(MyError::Foo) - } else { - Ok(42) - } -} - -// An async function returning a struct that can throw. -#[uniffi::export] -pub async fn fallible_struct(do_fail: bool) -> Result, MyError> { - if do_fail { - Err(MyError::Foo) - } else { - Ok(new_megaphone()) - } -} - -#[derive(uniffi::Record)] -pub struct MyRecord { - pub a: String, - pub b: u32, -} - -#[derive(uniffi::Enum)] -pub enum AsyncItemState { - Ready { timestamp_ms: u64 }, - Pending { reason: String }, -} - -#[derive(uniffi::Record)] -pub struct AsyncItem { - pub id: u64, - pub state: AsyncItemState, -} - -#[uniffi::export] -pub async fn new_my_record(a: String, b: u32) -> MyRecord { - MyRecord { a, b } -} - -#[uniffi::export] -pub fn list_async_items() -> Vec { - vec![ - AsyncItem { id: 1, state: AsyncItemState::Ready { timestamp_ms: 1111 } }, - AsyncItem { id: 2, state: AsyncItemState::Pending { reason: "syncing".to_string() } }, - ] -} - -/// Non-blocking timer future used to test callback cancellation. -#[uniffi::export] -pub async fn broken_sleep(ms: u16, fail_after: u16) { - BrokenTimerFuture::new( - Duration::from_millis(ms.into()), - Duration::from_millis(fail_after.into()), - ) - .await; -} - -/// Proc-macro-defined object with async methods (Megaphone) -#[derive(uniffi::Object)] -pub struct Megaphone; - -#[uniffi::export] -impl Megaphone { - /// Async constructor - #[uniffi::constructor] - pub async fn new() -> Arc { - TimerFuture::new(Duration::from_millis(0)).await; - Arc::new(Self) - } - - /// Alternative async constructor - #[uniffi::constructor] - pub async fn secondary() -> Arc { - TimerFuture::new(Duration::from_millis(0)).await; - Arc::new(Self) - } - - /// Async method that yells something after a certain time - pub async fn say_after(self: Arc, ms: u16, who: String) -> String { - say_after(ms, who).await.to_uppercase() - } - - /// Async method without any extra arguments - pub async fn silence(&self) -> String { - String::new() - } - - /// Async method that can throw - pub async fn fallible_me(self: Arc, do_fail: bool) -> Result { - if do_fail { - Err(MyError::Foo) - } else { - Ok(42) - } - } -} - -/// Mixed async/sync methods on the same object (using tokio runtime) -#[uniffi::export(async_runtime = "tokio")] -impl Megaphone { - /// Sync method that yells something immediately - pub fn say_now(&self, who: String) -> String { - format!("Hello, {who}!").to_uppercase() - } - - /// Async method using Tokio's timer - pub async fn say_after_with_tokio(self: Arc, ms: u16, who: String) -> String { - say_after_with_tokio(ms, who).await.to_uppercase() - } -} - -/// Sync function that generates a new `Megaphone`. -#[uniffi::export] -pub fn new_megaphone() -> Arc { - Arc::new(Megaphone) -} - -/// Async function that generates a new `Megaphone`. -#[uniffi::export] -pub async fn async_new_megaphone() -> Arc { - new_megaphone() -} - -/// Async function that possibly generates a new `Megaphone`. -#[uniffi::export] -pub async fn async_maybe_new_megaphone(y: bool) -> Option> { - if y { - Some(new_megaphone()) - } else { - None - } -} - -/// Async function that inputs `Megaphone`. -#[uniffi::export] -pub async fn say_after_with_megaphone(megaphone: Arc, ms: u16, who: String) -> String { - megaphone.say_after(ms, who).await -} - -/// Async function that uses tokio runtime. -#[uniffi::export(async_runtime = "tokio")] -pub async fn say_after_with_tokio(ms: u16, who: String) -> String { - tokio::time::sleep(Duration::from_millis(ms.into())).await; - format!("Hello, {who} (with Tokio)!") -} - -/// Fallible async constructor object -#[derive(uniffi::Object)] -pub struct FallibleMegaphone; - -#[uniffi::export] -impl FallibleMegaphone { - #[uniffi::constructor] - pub async fn new() -> Result, MyError> { - Err(MyError::Foo) - } -} - -/// Async runtime example that uses shared state to test timeouts. -#[derive(uniffi::Record)] -pub struct SharedResourceOptions { - pub release_after_ms: u16, - pub timeout_ms: u16, -} - -// Our error for async resource usage. -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum AsyncError { - #[error("Timeout")] - Timeout, -} - -#[uniffi::export(async_runtime = "tokio")] -pub async fn use_shared_resource(options: SharedResourceOptions) -> Result<(), AsyncError> { - use tokio::sync::Mutex; - use tokio::time::{sleep, timeout}; - - static MUTEX: Lazy> = Lazy::new(|| Mutex::new(())); - - let _guard = timeout(Duration::from_millis(options.timeout_ms.into()), MUTEX.lock()) - .await - .map_err(|_| AsyncError::Timeout)?; - - sleep(Duration::from_millis(options.release_after_ms.into())).await; - Ok(()) -} - -// Example of a trait with async methods. -#[uniffi::export] -#[async_trait::async_trait] -pub trait SayAfterTrait: Send + Sync { - async fn say_after(&self, ms: u16, who: String) -> String; -} - -// Example of async trait defined in the UDL file. -#[uniffi::trait_interface] -#[async_trait::async_trait] -pub trait SayAfterUdlTrait: Send + Sync { - async fn say_after(&self, ms: u16, who: String) -> String; -} - -struct SayAfterImpl1; -struct SayAfterImpl2; - -#[async_trait::async_trait] -impl SayAfterTrait for SayAfterImpl1 { - async fn say_after(&self, ms: u16, who: String) -> String { - say_after(ms, who).await - } -} - -#[async_trait::async_trait] -impl SayAfterTrait for SayAfterImpl2 { - async fn say_after(&self, ms: u16, who: String) -> String { - say_after(ms, who).await - } -} - -#[uniffi::export] -pub fn get_say_after_traits() -> Vec> { - vec![Arc::new(SayAfterImpl1), Arc::new(SayAfterImpl2)] -} - -#[async_trait::async_trait] -impl SayAfterUdlTrait for SayAfterImpl1 { - async fn say_after(&self, ms: u16, who: String) -> String { - say_after(ms, who).await - } -} - -#[async_trait::async_trait] -impl SayAfterUdlTrait for SayAfterImpl2 { - async fn say_after(&self, ms: u16, who: String) -> String { - say_after(ms, who).await - } -} - -#[uniffi::export] -pub fn get_say_after_udl_traits() -> Vec> { - vec![Arc::new(SayAfterImpl1), Arc::new(SayAfterImpl2)] -} - -/// UDL-defined object with async methods. -pub struct UdlMegaphone; - -impl UdlMegaphone { - pub async fn new() -> Self { - TimerFuture::new(Duration::from_millis(0)).await; - Self {} - } - - pub async fn secondary() -> Self { - TimerFuture::new(Duration::from_millis(0)).await; - Self {} - } - - pub async fn say_after(&self, ms: u16, who: String) -> String { - TimerFuture::new(Duration::from_millis(ms.into())).await; - format!("Hello, {who} (from UDL Megaphone)!").to_uppercase() - } -} - -// Async callback interface implemented in foreign code. -#[uniffi::export(with_foreign)] -#[async_trait::async_trait] -pub trait AsyncParser: Send + Sync { - // Simple async method - async fn as_string(&self, delay_ms: i32, value: i32) -> String; - // Async method that can throw - async fn try_from_string(&self, delay_ms: i32, value: String) -> Result; - // Void return, which requires special handling - async fn delay(&self, delay_ms: i32); - // Void return that can also throw - async fn try_delay(&self, delay_ms: String) -> Result<(), ParserError>; -} - -#[uniffi::export(with_foreign)] -#[async_trait::async_trait] -pub trait AsyncParserMirror: Send + Sync { - async fn mirror_string(&self, delay_ms: i32, value: i32) -> String; - async fn mirror_delay(&self, delay_ms: i32); -} - -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum ParserError { - #[error("NotAnInt")] - NotAnInt, - #[error("UnexpectedError")] - UnexpectedError, -} - -impl From for ParserError { - fn from(_: uniffi::UnexpectedUniFFICallbackError) -> Self { - Self::UnexpectedError - } -} - -#[uniffi::export] -pub async fn as_string_using_trait(obj: Arc, delay_ms: i32, value: i32) -> String { - obj.as_string(delay_ms, value).await -} - -#[uniffi::export] -pub async fn try_from_string_using_trait( - obj: Arc, - delay_ms: i32, - value: String, -) -> Result { - obj.try_from_string(delay_ms, value).await -} - -#[uniffi::export] -pub async fn delay_using_trait(obj: Arc, delay_ms: i32) { - obj.delay(delay_ms).await -} - -#[uniffi::export] -pub async fn try_delay_using_trait( - obj: Arc, - delay_ms: String, -) -> Result<(), ParserError> { - obj.try_delay(delay_ms).await -} - -#[uniffi::export] -pub async fn cancel_delay_using_trait(obj: Arc, delay_ms: i32) { - let (abort_handle, abort_registration) = AbortHandle::new_pair(); - thread::spawn(move || { - // Simulate a different thread aborting the process - thread::sleep(Duration::from_millis(1)); - abort_handle.abort(); - }); - - let future = Abortable::new(obj.delay(delay_ms), abort_registration); - assert_eq!(future.await, Err(Aborted)); -} - -#[uniffi::export] -pub async fn mirror_string_using_trait( - obj: Arc, - delay_ms: i32, - value: i32, -) -> String { - obj.mirror_string(delay_ms, value).await -} - -#[uniffi::export] -pub async fn mirror_delay_using_trait(obj: Arc, delay_ms: i32) { - obj.mirror_delay(delay_ms).await -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/dart_async/test/futures_test.dart b/uniffi/dart/fixtures/dart_async/test/futures_test.dart deleted file mode 100644 index 1ddc1459b..000000000 --- a/uniffi/dart/fixtures/dart_async/test/futures_test.dart +++ /dev/null @@ -1,419 +0,0 @@ -import 'package:test/test.dart'; -import '../dart_async.dart'; - -Future measureTime(Future Function() action) async { - final start = DateTime.now(); - await action(); - final end = DateTime.now(); - return end.difference(start); -} - -// The DELAY-based timing assertions below check a LOWER bound only: that an -// async operation waited at least its expected delay (proving the async -// plumbing actually suspends). They deliberately do not assert an upper bound — -// wall-clock upper bounds measure host/CI scheduling speed, not binding -// correctness, and are the source of the flaky failures tracked in #139. This -// mirrors uniffi-rs's own futures fixture (`test_futures.py`), which uses -// `assertGreater` with no upper bound. (Illustrative, not enforced: locally the -// whole suite runs in a few seconds with correct results; on a heavily loaded -// CI runner it can take vastly longer, which is what tripped the old two-sided -// per-operation bounds like `< 300ms`.) -// -// Two groups are intentionally different: -// - `concurrent_future` verifies concurrency structurally (completion order), -// not by comparing durations — see the note in that test for why a timing -// comparison can't reliably catch a serialization regression. -// - The immediate-operation checks (`always_ready`, `void`, sync methods, -// constructors) still assert an upper bound only. They have no lower bound -// to fall back on and share the same latent wall-clock fragility; tightening -// those is deliberately left for a separate change. - -class ErroringAsyncParser extends AsyncParser { - @override - Future asString(int delayMs, int value) async => value.toString(); - - @override - Future tryFromString(int delayMs, String value) async { - if (value == 'bad') { - throw NotAnIntParserException(); - } - if (value == 'unexpected') { - throw StateError('unexpected value'); - } - return int.parse(value); - } - - @override - Future delay(int delayMs) async {} - - @override - Future tryDelay(String delayMs) async { - if (delayMs == 'bad') { - throw NotAnIntParserException(); - } - } -} - -class DedupAsyncParser extends AsyncParserMirror { - @override - Future mirrorString(int delayMs, int value) async => 'mirror:$value'; - - @override - Future mirrorDelay(int delayMs) async {} -} - -void main() { - initialize(); - ensureInitialized(); - - test('greet', () async { - final result = greet(who: "Somebody"); - expect(result, "Hello, Somebody"); - }); - - test('always_ready', () async { - final time = await measureTime(() async { - final result = await alwaysReady(); - expect(result, true); - }); - - expect(time.inMilliseconds < 200, true); - }); - - test('void', () async { - final time = await measureTime(() async { - await void_(); - }); - // Less than or equal to time - expect(time.inMilliseconds <= 10, true); - }); - - test('sleep', () async { - final time = await measureTime(() async { - await sleep(ms: 200); - }); - - expect(time.inMilliseconds >= 200, true); - }); - - test('sequential_future', () async { - final time = await measureTime(() async { - final resultAlice = await sayAfter(ms: 100, who: 'Alice'); - final resultBob = await sayAfter(ms: 200, who: 'Bob'); - expect(resultAlice, 'Hello, Alice!'); - expect(resultBob, 'Hello, Bob!'); - }); - expect(time.inMilliseconds >= 300, true); - }); - - test('concurrent_future', () async { - // Comparing concurrent vs. sequential wall-clock time cannot reliably detect - // a serialization regression: a serialized `Future.wait` is structurally the - // same work as running the calls sequentially (100+200 either way), so the - // comparison becomes a coin flip, while any fixed margin or ratio re-adds the - // load-sensitive flakiness #139 is about (the Rust-side `thread::sleep` - // delays don't dilate under load, but scheduling jitter adds unbounded time). - // Instead assert two load-robust properties. - - // (1) Correct positional results + a lower bound. The lower bound is - // jitter-immune — sleeps only ever lengthen a run — and catches a future - // resolving before its delay elapsed. - final concurrentTime = await measureTime(() async { - final results = await Future.wait([ - sayAfter(ms: 100, who: 'Alice'), - sayAfter(ms: 200, who: 'Bob'), - ]); - - expect(results[0], 'Hello, Alice!'); - expect(results[1], 'Hello, Bob!'); - }); - expect(concurrentTime.inMilliseconds, greaterThanOrEqualTo(200)); - - // (2) Completion ORDER, not duration: start a slow future, then a fast one, - // and require the fast one to finish while the slow one is still pending. If - // the bindings serialized FFI futures, the slow call would have to complete - // before the fast one could even start, failing this deterministically — - // with ~2000ms of structural headroom (not a tuned threshold), so it can't - // reflake on a loaded runner. - var slowDone = false; - final slow = - sayAfter(ms: 2000, who: 'Slow').whenComplete(() => slowDone = true); - await sayAfter(ms: 1, who: 'Fast'); - expect( - slowDone, - isFalse, - reason: 'a 1ms future completed only after a 2000ms future that started ' - 'earlier — FFI futures appear to be serialized', - ); - await slow; // let the fixture call finish before the test ends - }); - - test('with_tokio_runtime', () async { - final time = await measureTime(() async { - final resultAlice = await sayAfterWithTokio(ms: 200, who: 'Alice'); - expect(resultAlice, 'Hello, Alice (with Tokio)!'); - }); - expect(time.inMilliseconds >= 200, true); - }); - - test('fallible_function_and_method', () async { - final time1 = await measureTime(() async { - try { - await fallibleMe(doFail: false); - expect(true, true); - } catch (exception) { - expect(false, true); // should never be reached - } - }); - expect(time1.inMilliseconds <= 100, true); - - final time2 = await measureTime(() async { - try { - await fallibleMe(doFail: true); - expect(false, true); // should never be reached - } catch (exception) { - expect(true, true); - } - }); - expect(time2.inMilliseconds <= 100, true); - }); - - test('record', () async { - final time = await measureTime(() async { - final result = await newMyRecord(a: 'foo', b: 42); - expect(result.a, 'foo'); - expect(result.b, 42); - }); - // Heads-up: Sometimes this test will fail if for whatever reason, something on the host system pauses the execution of the async funtions. - print('record: ${time.inMilliseconds}ms'); - expect(time.inMilliseconds <= 100, true); - }); - - test('broken_sleep', () async { - final time = await measureTime(() async { - await brokenSleep( - ms: 100, - failAfter: 0, - ); // calls the waker twice immediately - await sleep(ms: 100); // wait for possible failure - - await brokenSleep( - ms: 100, - failAfter: 100, - ); // calls the waker a second time after 1s - await sleep(ms: 200); // wait for possible failure - }); - expect(time.inMilliseconds >= 400, true); - }); - - test('udl_async_function', () async { - final time = await measureTime(() async { - final result = await alwaysReady(); - expect(result, true); - }); - expect(time.inMilliseconds < 100, true); - }); - - test('proc_macro_megaphone_async_constructor', () async { - final time = await measureTime(() async { - final megaphone = await Megaphone.new_(); - expect(megaphone, isNotNull); - }); - expect(time.inMilliseconds < 100, true); - }); - - test('proc_macro_megaphone_secondary_constructor', () async { - final time = await measureTime(() async { - final megaphone = await Megaphone.secondary(); - expect(megaphone, isNotNull); - }); - expect(time.inMilliseconds < 100, true); - }); - - test('proc_macro_megaphone_async_methods', () async { - final megaphone = await Megaphone.new_(); - - // Test async method with timing - final time = await measureTime(() async { - final result = await megaphone.sayAfter(ms: 100, who: 'Alice'); - expect(result, 'HELLO, ALICE!'); - }); - expect(time.inMilliseconds >= 100, true); - - // Test async silence method - final silenceTime = await measureTime(() async { - final result = await megaphone.silence(); - expect(result, ''); - }); - expect(silenceTime.inMilliseconds < 50, true); - }); - - test('proc_macro_megaphone_sync_method', () async { - final megaphone = await Megaphone.new_(); - - // Test sync method (should be immediate) - final time = await measureTime(() async { - final result = megaphone.sayNow(who: 'Bob'); - expect(result, 'HELLO, BOB!'); - }); - expect(time.inMilliseconds < 50, true); - }); - - test('proc_macro_megaphone_tokio_method', () async { - final megaphone = await Megaphone.new_(); - - final time = await measureTime(() async { - final result = await megaphone.sayAfterWithTokio(ms: 100, who: 'Charlie'); - expect(result, 'HELLO, CHARLIE (WITH TOKIO)!'); - }); - expect(time.inMilliseconds >= 100, true); - }); - - test('proc_macro_megaphone_fallible_method', () async { - final megaphone = await Megaphone.new_(); - - // Test success case - final result = await megaphone.fallibleMe(doFail: false); - expect(result, 42); - - // Test failure case - try { - await megaphone.fallibleMe(doFail: true); - expect(false, true); // Should never reach here - } catch (e) { - expect(true, true); // Expected to throw - } - }); - - test('udl_megaphone_async_constructors', () async { - // Test primary constructor - final time1 = await measureTime(() async { - final udlMegaphone = await UdlMegaphone.new_(); - expect(udlMegaphone, isNotNull); - }); - expect(time1.inMilliseconds < 100, true); - - // Test secondary constructor - final time2 = await measureTime(() async { - final udlMegaphone = await UdlMegaphone.secondary(); - expect(udlMegaphone, isNotNull); - }); - expect(time2.inMilliseconds < 100, true); - }); - - test('udl_megaphone_async_method', () async { - final udlMegaphone = await UdlMegaphone.new_(); - - final time = await measureTime(() async { - final result = await udlMegaphone.sayAfter(ms: 100, who: 'Dave'); - expect(result, 'HELLO, DAVE (FROM UDL MEGAPHONE)!'); - }); - expect(time.inMilliseconds >= 100, true); - }); - - test('async_object_creation_functions', () async { - // Test sync object creation - final syncMegaphone = newMegaphone(); - expect(syncMegaphone, isNotNull); - - // Test async object creation - final asyncMegaphone = await asyncNewMegaphone(); - expect(asyncMegaphone, isNotNull); - - // Test conditional async object creation - final maybeMegaphone1 = await asyncMaybeNewMegaphone(y: true); - expect(maybeMegaphone1, isNotNull); - - final maybeMegaphone2 = await asyncMaybeNewMegaphone(y: false); - expect(maybeMegaphone2, isNull); - }); - - test('async_function_with_object_parameter', () async { - final megaphone = await Megaphone.new_(); - - final time = await measureTime(() async { - final result = await sayAfterWithMegaphone( - megaphone: megaphone, - ms: 100, - who: 'Eve', - ); - expect(result, 'HELLO, EVE!'); - }); - expect(time.inMilliseconds >= 100, true); - }); - - test('fallible_struct_creation', () async { - // Test success case - final successResult = await fallibleStruct(doFail: false); - expect(successResult, isNotNull); - - // Test failure case - try { - await fallibleStruct(doFail: true); - expect(false, true); // Should never reach here - } catch (e) { - expect(true, true); // Expected to throw - } - }); - - test('fallible_async_constructor', () async { - // This constructor always fails - try { - await FallibleMegaphone.new_(); - expect(false, true); // Should never reach here - } catch (e) { - expect(true, true); // Expected to throw - } - }); - - test('decode sequence of records containing payload enums', () { - final items = listAsyncItems(); - expect(items.length, 2); - - final firstState = items[0].state as ReadyAsyncItemState; - expect(items[0].id, 1); - expect(firstState.timestampMs, 1111); - - final secondState = items[1].state as PendingAsyncItemState; - expect(items[1].id, 2); - expect(secondState.reason, 'syncing'); - }); - - test('async callback preserves expected parser error', () async { - final parser = ErroringAsyncParser(); - expect( - () => tryFromStringUsingTrait(obj: parser, delayMs: 0, value: 'bad'), - throwsA(isA()), - ); - }); - - test('async void callback preserves expected parser error', () async { - final parser = ErroringAsyncParser(); - expect( - () => tryDelayUsingTrait(obj: parser, delayMs: 'bad'), - throwsA(isA()), - ); - }); - - test('async callback maps unexpected parser exception', () async { - final parser = ErroringAsyncParser(); - expect( - () => - tryFromStringUsingTrait(obj: parser, delayMs: 0, value: 'unexpected'), - throwsA(isA()), - ); - }); - - test( - 'async callback helper definitions are shared across interfaces', - () async { - final parser = DedupAsyncParser(); - - expect( - await mirrorStringUsingTrait(obj: parser, delayMs: 0, value: 42), - equals('mirror:42'), - ); - await mirrorDelayUsingTrait(obj: parser, delayMs: 0); - }, - ); -} diff --git a/uniffi/dart/fixtures/dart_async/tests/mod.rs b/uniffi/dart/fixtures/dart_async/tests/mod.rs deleted file mode 100644 index dd12dcaeb..000000000 --- a/uniffi/dart/fixtures/dart_async/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn dart_async() -> Result<()> { - uniffi_dart::testing::run_test("dart_async", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/docstring-proc-macro/Cargo.toml b/uniffi/dart/fixtures/docstring-proc-macro/Cargo.toml deleted file mode 100644 index 2605e8bd6..000000000 --- a/uniffi/dart/fixtures/docstring-proc-macro/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "docstring-proc-macro" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -name = "docstring_proc_macro" -crate-type = ["lib", "cdylib"] - -[dependencies] -thiserror = "1.0" -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } -camino = "1" - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/docstring-proc-macro/build.rs b/uniffi/dart/fixtures/docstring-proc-macro/build.rs deleted file mode 100644 index 797041d85..000000000 --- a/uniffi/dart/fixtures/docstring-proc-macro/build.rs +++ /dev/null @@ -1,5 +0,0 @@ -use camino::Utf8Path; - -fn main() { - uniffi_dart::generate_scaffolding(Utf8Path::new("src/api.udl")).unwrap(); -} diff --git a/uniffi/dart/fixtures/docstring-proc-macro/src/api.udl b/uniffi/dart/fixtures/docstring-proc-macro/src/api.udl deleted file mode 100644 index d0de860ea..000000000 --- a/uniffi/dart/fixtures/docstring-proc-macro/src/api.udl +++ /dev/null @@ -1,2 +0,0 @@ -/// -namespace docstring_proc_macro {}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/docstring-proc-macro/src/lib.rs b/uniffi/dart/fixtures/docstring-proc-macro/src/lib.rs deleted file mode 100644 index eda91ccad..000000000 --- a/uniffi/dart/fixtures/docstring-proc-macro/src/lib.rs +++ /dev/null @@ -1,112 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -/// -#[derive(uniffi::Enum)] -enum EnumTest { - /// - One, - /// - Two, -} - -/// -#[derive(uniffi::Enum)] -pub enum AssociatedEnumTest { - /// - Test { - /// - code: i16, - }, - /// - Test2 { code: i16 }, -} - -/// -#[derive(uniffi::Error, Debug, thiserror::Error)] -#[uniffi(flat_error)] -pub enum ErrorTest { - /// - #[error("Test")] - One, - /// - #[error("Two")] - Two, -} - -/// -#[derive(uniffi::Error, Debug, thiserror::Error)] -pub enum AssociatedErrorTest { - /// - #[error("Test")] - Test { code: i16 }, - /// - #[error("Test2")] - Test2 { code: i16 }, -} - -/// -#[derive(uniffi::Object)] -pub struct ObjectTest {} - -#[uniffi::export] -impl ObjectTest { - /// - #[uniffi::constructor] - pub fn new() -> Arc { - Arc::new(ObjectTest {}) - } - - /// - #[uniffi::constructor] - pub fn new_alternate() -> Arc { - Arc::new(ObjectTest {}) - } - - /// - pub fn test(&self) {} -} - -/// -#[derive(uniffi::Record)] -struct RecordTest { - /// - test: i32, -} - -/// -#[uniffi::export] -pub fn test() -> Result<(), ErrorTest> { - let _ = ErrorTest::One; - let _ = ErrorTest::Two; - Ok(()) -} - -/// -/// -#[uniffi::export] -pub fn test_multiline() {} - -#[uniffi::export] -pub fn test_without_docstring() -> Result<(), AssociatedErrorTest> { - Ok(()) -} - -/// -#[uniffi::export(callback_interface)] -pub trait CallbackTest { - /// - fn test(&self); -} - -/// This is a very long multi line test docstring that exceeds 255 characters. -/// This is a very long multi line test docstring that exceeds 255 characters. -/// This is a very long multi line test docstring that exceeds 255 characters. -/// This is a very long multi line test docstring that exceeds 255 characters. -#[uniffi::export] -pub fn test_long_docstring() {} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/docstring-proc-macro/test/docstring_proc_macro_test.dart b/uniffi/dart/fixtures/docstring-proc-macro/test/docstring_proc_macro_test.dart deleted file mode 100644 index e418b0c01..000000000 --- a/uniffi/dart/fixtures/docstring-proc-macro/test/docstring_proc_macro_test.dart +++ /dev/null @@ -1,105 +0,0 @@ -import 'package:test/test.dart'; -import '../docstring_proc_macro.dart' as doc; - -class CallbackTestImpl extends doc.CallbackTest { - @override - void test() {} -} - -void main() { - group('Docstring Proc-Macro', () { - test('proc-macro enum with docstring', () { - final enumValue = doc.EnumTest.one; - expect(enumValue, equals(doc.EnumTest.one)); - - final enumValue2 = doc.EnumTest.two; - expect(enumValue2, equals(doc.EnumTest.two)); - }); - - test('proc-macro associated enum with docstring', () { - // This test will fail until proc-macro support is implemented - // Expected: Associated enums should have documentation for variants and fields - - final associatedEnum = doc.TestAssociatedEnumTest(42); - expect(associatedEnum, isA()); - - final associatedEnum2 = doc.Test2AssociatedEnumTest(43); - expect(associatedEnum2, isA()); - }); - - test('proc-macro error with docstring', () { - // This test will fail until proc-macro support is implemented - // Expected: Error enums should have documentation on variants - - expect(() => doc.test(), returnsNormally); - }); - - test('proc-macro associated error with docstring', () { - // This test will fail until proc-macro support is implemented - // Expected: Associated error enums should have documentation - - expect(() => doc.testWithoutDocstring(), returnsNormally); - }); - - test('proc-macro object with docstring', () { - // This test will fail until proc-macro support is implemented - // Expected: Objects should have documentation on constructors and methods - - final obj = doc.ObjectTest(); - obj.test(); - - final objAlt = doc.ObjectTest.newAlternate(); - objAlt.test(); - }); - - test('proc-macro record with docstring', () { - // This test will fail until proc-macro support is implemented - // Expected: Records should have documentation on fields - - final record = doc.RecordTest(test: 42); - expect(record.test, equals(42)); - }); - - test('proc-macro function with docstring', () { - // This test will fail until proc-macro support is implemented - // Expected: Functions should have proper documentation comments in generated Dart - - doc.test(); - doc.testMultiline(); - doc.testWithoutDocstring(); - }); - - test( - 'proc-macro callback interface with docstring', - () { - final callback = CallbackTestImpl(); - callback.test(); - }, - ); - - test('proc-macro long docstring', () { - // This test will fail until proc-macro support is implemented - // Expected: Long docstrings (>255 chars) should be properly handled - - doc.testLongDocstring(); - }); - - test('documentation generation comparison', () { - // This test compares proc-macro docs vs UDL docs - // Expected: Both should generate equivalent documentation in Dart - - // Test basic functionality to ensure proc-macro definitions work - final enumValue = doc.EnumTest.one; - expect(enumValue, equals(doc.EnumTest.one)); - - doc.test(); - doc.testMultiline(); - - final obj = doc.ObjectTest(); - obj.test(); - - final record = doc.RecordTest(test: 123); - expect(record.test, equals(123)); - }); - }); -} diff --git a/uniffi/dart/fixtures/docstring-proc-macro/tests/mod.rs b/uniffi/dart/fixtures/docstring-proc-macro/tests/mod.rs deleted file mode 100644 index 1f4553433..000000000 --- a/uniffi/dart/fixtures/docstring-proc-macro/tests/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[cfg(test)] -mod tests { - #[test] - fn test_docstring_proc_macro() { - uniffi_dart::testing::run_test("docstring-proc-macro", "src/api.udl", None).unwrap(); - } -} diff --git a/uniffi/dart/fixtures/duration_type_test/Cargo.toml b/uniffi/dart/fixtures/duration_type_test/Cargo.toml deleted file mode 100644 index e6781c407..000000000 --- a/uniffi/dart/fixtures/duration_type_test/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "duration_type_test" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "duration_type_test" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/duration_type_test/build.rs b/uniffi/dart/fixtures/duration_type_test/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/duration_type_test/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/duration_type_test/src/api.udl b/uniffi/dart/fixtures/duration_type_test/src/api.udl deleted file mode 100644 index c097a4414..000000000 --- a/uniffi/dart/fixtures/duration_type_test/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace duration_type_test { }; diff --git a/uniffi/dart/fixtures/duration_type_test/src/lib.rs b/uniffi/dart/fixtures/duration_type_test/src/lib.rs deleted file mode 100644 index db8caa5e9..000000000 --- a/uniffi/dart/fixtures/duration_type_test/src/lib.rs +++ /dev/null @@ -1,18 +0,0 @@ -use core::time::Duration; - -#[uniffi::export] -pub fn make_duration(seconds: u64, nanos: u32) -> Duration { - Duration::new(seconds, nanos) -} - -#[uniffi::export] -pub fn get_seconds(duration: Duration) -> u64 { - duration.as_secs() -} - -#[uniffi::export] -pub fn get_nanos(duration: Duration) -> u32 { - duration.subsec_nanos() -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/duration_type_test/test/duration_type_test.dart b/uniffi/dart/fixtures/duration_type_test/test/duration_type_test.dart deleted file mode 100644 index a4a798e8b..000000000 --- a/uniffi/dart/fixtures/duration_type_test/test/duration_type_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -import 'package:test/test.dart'; -import '../duration_type_test.dart'; - -void main() { - test('rust return value seconds check', () { - final duration = makeDuration(seconds: 5, nanos: 0); - - expect(duration.inSeconds, 5); - expect(getSeconds(duration: duration), 5); - expect(getNanos(duration: duration), 0); - }); - - test('seconds data check from dart', () { - final duration = Duration(seconds: 10); - expect(getSeconds(duration: duration), 10); - expect(getNanos(duration: duration), 0); - }); - - test('check nanos/micros', () { - final duration = makeDuration(seconds: 0, nanos: 3000); - expect(duration.inSeconds, 0); - expect(duration.inMicroseconds, 3); - expect(getSeconds(duration: duration), 0); - expect(getNanos(duration: duration), 3000); - }); - - test('check large values', () { - final duration = makeDuration(seconds: 123456789, nanos: 3000000); - expect(duration.inSeconds, 123456789); - expect(duration.inMicroseconds, 123456789003000); - expect(getSeconds(duration: duration), 123456789); - expect(getNanos(duration: duration), 3000000); - }); -} diff --git a/uniffi/dart/fixtures/duration_type_test/tests/mod.rs b/uniffi/dart/fixtures/duration_type_test/tests/mod.rs deleted file mode 100644 index 2695dc1b3..000000000 --- a/uniffi/dart/fixtures/duration_type_test/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn duration_type_test() -> Result<()> { - uniffi_dart::testing::run_test("duration_type_test", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/enum_variant_collision/Cargo.toml b/uniffi/dart/fixtures/enum_variant_collision/Cargo.toml deleted file mode 100644 index 293d97878..000000000 --- a/uniffi/dart/fixtures/enum_variant_collision/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "enum_variant_collision" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -name = "enum_variant_collision" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true, features = ["build"] } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/enum_variant_collision/build.rs b/uniffi/dart/fixtures/enum_variant_collision/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/enum_variant_collision/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/enum_variant_collision/src/api.udl b/uniffi/dart/fixtures/enum_variant_collision/src/api.udl deleted file mode 100644 index 1b957812e..000000000 --- a/uniffi/dart/fixtures/enum_variant_collision/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace enum_variant_collision { }; diff --git a/uniffi/dart/fixtures/enum_variant_collision/src/lib.rs b/uniffi/dart/fixtures/enum_variant_collision/src/lib.rs deleted file mode 100644 index 8904f6de4..000000000 --- a/uniffi/dart/fixtures/enum_variant_collision/src/lib.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Regression fixture: a data-carrying enum variant's Dart class is named -// `{Variant}{Enum}`. When that equals a real top-level type name, the generator -// used to emit two same-named Dart classes — a Dart compile error. The generator -// now disambiguates the variant class with a `Variant` suffix, looping past any -// further collision, against the names of every type that emits a top-level class -// (records, enums, objects, callback interfaces). - -#[derive(uniffi::Record, Clone, PartialEq, Debug)] -pub struct FieldCondition { - key: String, -} - -// Forces a SECOND-ORDER collision: the `Field` variant's base name -// `FieldCondition` clashes with the record above, so it is suffixed to -// `FieldConditionVariant` — which clashes with THIS record, so the generator must -// keep going (`FieldConditionVariant2`). A one-shot suffix would emit a duplicate. -#[derive(uniffi::Record, Clone, PartialEq, Debug)] -pub struct FieldConditionVariant { - note: String, -} - -// A flat enum whose name equals the `Kind` variant's `{Kind}{Condition}` class, -// exercising the enum branch of the reserved-name set. -#[derive(uniffi::Enum, PartialEq, Debug)] -pub enum KindCondition { - A, - B, -} - -#[derive(uniffi::Enum, PartialEq, Debug)] -pub enum Condition { - Field { condition: FieldCondition }, - Kind { kind: KindCondition }, - Plain { value: i32 }, -} - -#[uniffi::export] -pub fn roundtrip_condition(c: Condition) -> Condition { - c -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/enum_variant_collision/test/enum_variant_collision_test.dart b/uniffi/dart/fixtures/enum_variant_collision/test/enum_variant_collision_test.dart deleted file mode 100644 index cac301bc7..000000000 --- a/uniffi/dart/fixtures/enum_variant_collision/test/enum_variant_collision_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'package:test/test.dart'; -import '../enum_variant_collision.dart'; - -void main() { - test('record collision, looping past a second-order clash, round-trips', () { - // `Field` -> base `FieldCondition` (record) -> `FieldConditionVariant` - // (also a record) -> `FieldConditionVariant2`. Round-trips through both the - // variant class's lower/write and the FfiConverter's `read` dispatch. - final c = FieldConditionVariant2(FieldCondition(key: "k")); - final out = roundtripCondition(c: c); - expect(out, isA()); - expect((out as FieldConditionVariant2).condition.key, "k"); - }); - - test('collision with an enum type is disambiguated (enum branch of reserved set)', () { - // `Kind` -> base `KindCondition` (a flat enum) -> `KindConditionVariant`. - final c = KindConditionVariant(KindCondition.a); - final out = roundtripCondition(c: c); - expect(out, isA()); - expect((out as KindConditionVariant).kind, KindCondition.a); - }); - - test('non-colliding variant is unaffected', () { - final out = roundtripCondition(c: PlainCondition(42)); - expect((out as PlainCondition).value, 42); - }); -} diff --git a/uniffi/dart/fixtures/enum_variant_collision/tests/mod.rs b/uniffi/dart/fixtures/enum_variant_collision/tests/mod.rs deleted file mode 100644 index 4f20a686c..000000000 --- a/uniffi/dart/fixtures/enum_variant_collision/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn enum_variant_collision() -> Result<()> { - uniffi_dart::testing::run_test("enum_variant_collision", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/hello_world/Cargo.toml b/uniffi/dart/fixtures/hello_world/Cargo.toml deleted file mode 100644 index 6fa81be12..000000000 --- a/uniffi/dart/fixtures/hello_world/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "hello_world" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "hello_world" -crate-type = ["lib", "cdylib"] - - -[dependencies] -uniffi = { workspace = true, features = [ - "build", -] } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/hello_world/build.rs b/uniffi/dart/fixtures/hello_world/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/hello_world/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/hello_world/src/api.udl b/uniffi/dart/fixtures/hello_world/src/api.udl deleted file mode 100644 index 0e36ecfc4..000000000 --- a/uniffi/dart/fixtures/hello_world/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace hello_world { }; diff --git a/uniffi/dart/fixtures/hello_world/src/lib.rs b/uniffi/dart/fixtures/hello_world/src/lib.rs deleted file mode 100644 index 456020472..000000000 --- a/uniffi/dart/fixtures/hello_world/src/lib.rs +++ /dev/null @@ -1,78 +0,0 @@ -use std::sync::Arc; - -#[derive(uniffi::Record, Clone)] -pub struct WorldState { - inhabitants: u8, - name: Option, -} - -impl WorldState { - fn new(name: Option) -> WorldState { - WorldState { inhabitants: 0, name } - } -} - -#[derive(uniffi::Object, Clone)] -pub struct World(WorldState); - -impl World { - fn new(name: Option) -> World { - World(WorldState::new(name)) - } -} - -#[uniffi::export] -// original stayed the same -impl World { - fn is_there(&self) -> bool { - true - } - - fn name(&self) -> Option { - self.0.name.clone() - } - - fn state(&self) -> WorldState { - self.0.clone() - } - - fn inc_inhabitants(self: Arc) -> Arc { - let mut me = Arc::try_unwrap(self).unwrap_or_else(|x| (*x).clone()); - me.0.inhabitants += 1; - Arc::new(me) - } - - fn prefixed_name(&self, inp: Option) -> Option { - match (inp, &self.0.name) { - (Some(e), Some(f)) => Some(format!("{e} {f}")), - _ => None, - } - } - fn set_name(self: Arc, inp: Option) -> Arc { - let mut me = Arc::try_unwrap(self).unwrap_or_else(|x| (*x).clone()); - me.0.name = inp; - Arc::new(me) - } -} - -#[uniffi::export] -pub fn new_world() -> Arc { - Arc::new(World::new(None)) -} - -#[uniffi::export] -pub fn new_world_with_name(name: String) -> Arc { - Arc::new(World::new(Some(name))) -} - -#[uniffi::export] -pub fn hello_world() -> String { - "hello world".to_string() -} - -#[uniffi::export] -pub fn hello(input: String) -> String { - format!("hello {input}") -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/hello_world/test/hello_world_test.dart b/uniffi/dart/fixtures/hello_world/test/hello_world_test.dart deleted file mode 100644 index ae40b85b9..000000000 --- a/uniffi/dart/fixtures/hello_world/test/hello_world_test.dart +++ /dev/null @@ -1,45 +0,0 @@ -import 'package:test/test.dart'; -import '../hello_world.dart'; - -void main() { - test('hello world', () { - expect(helloWorld(), "hello world"); - }); - - test('hello mikka', () { - expect(hello(input: "mikka"), "hello mikka"); - }); - - test("object test", () { - final world = newWorld(); - expect(world.isThere(), true); - }); - - test("record test", () { - World world = newWorldWithName(name: "sarisa"); - final state = world.state(); - expect(state.name, "sarisa"); - expect(state.inhabitants, 0); - - world = world.incInhabitants(); - // original stayed the same - expect(state.inhabitants, 0); - expect(state.name, "sarisa"); - // object has increased - - final state2 = world.state(); - expect(state2.name, "sarisa"); - expect(state2.inhabitants, 1); - }); - - test("stringed world test", () { - var world = newWorldWithName(name: "sari"); - expect(world.name(), "sari"); - expect(world.prefixedName(inp: "mister"), "mister sari"); - expect(world.prefixedName(inp: null), null); - world = world.setName(inp: "new name"); - expect(world.name(), "new name"); - world = world.setName(inp: null); - expect(world.name(), null); - }); -} diff --git a/uniffi/dart/fixtures/hello_world/tests/mod.rs b/uniffi/dart/fixtures/hello_world/tests/mod.rs deleted file mode 100644 index e530640b0..000000000 --- a/uniffi/dart/fixtures/hello_world/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn hello_world() -> Result<()> { - uniffi_dart::testing::run_test("hello_world", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/input-scratch/Cargo.toml b/uniffi/dart/fixtures/input-scratch/Cargo.toml deleted file mode 100644 index 996e72c6b..000000000 --- a/uniffi/dart/fixtures/input-scratch/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "input_scratch" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "input_scratch" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" diff --git a/uniffi/dart/fixtures/input-scratch/build.rs b/uniffi/dart/fixtures/input-scratch/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/input-scratch/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/input-scratch/src/api.udl b/uniffi/dart/fixtures/input-scratch/src/api.udl deleted file mode 100644 index 430909683..000000000 --- a/uniffi/dart/fixtures/input-scratch/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace input_scratch {}; diff --git a/uniffi/dart/fixtures/input-scratch/src/lib.rs b/uniffi/dart/fixtures/input-scratch/src/lib.rs deleted file mode 100644 index 7736d82da..000000000 --- a/uniffi/dart/fixtures/input-scratch/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -#[uniffi::export] -pub fn owned_len(value: Vec) -> u64 { - value.len() as u64 -} - -#[uniffi::export] -pub fn optional_len(value: Option) -> u64 { - value.map_or(0, |s| s.len() as u64) -} - -#[uniffi::export] -pub fn optional_small(value: Option) -> u8 { - value.unwrap_or(0) -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/input-scratch/test/input_scratch_test.dart b/uniffi/dart/fixtures/input-scratch/test/input_scratch_test.dart deleted file mode 100644 index d6a138172..000000000 --- a/uniffi/dart/fixtures/input-scratch/test/input_scratch_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -import 'dart:io'; - -import 'package:test/test.dart'; - -void main() { - test('scratch allocations balance on success and injected failure', () async { - // Compile a child suite with an instrumented allocator. Keep the production - // API unchanged and restore the generated files even when a test fails. - final originals = {}; - try { - for (final name in ['input_scratch.dart', 'uniffi_runtime.dart']) { - final file = File(name); - final source = file.readAsStringSync(); - originals[file] = source; - final import = RegExp(r'''import ["']package:ffi/ffi.dart["'];'''); - expect(import.allMatches(source), hasLength(1)); - file.writeAsStringSync( - source.replaceFirst( - import, - 'import "package:ffi/ffi.dart" hide calloc;\n' - 'import "test/tracking_allocator.dart";', - ), - ); - } - final result = await Process.run(Platform.resolvedExecutable, [ - 'test', - 'test/scratch_cases.dart', - '--reporter', - 'expanded', - ]); - print(result.stdout); - print(result.stderr); - expect(result.exitCode, 0); - } finally { - for (final entry in originals.entries) { - entry.key.writeAsStringSync(entry.value); - } - } - }, timeout: Timeout(Duration(minutes: 3))); -} diff --git a/uniffi/dart/fixtures/input-scratch/test/scratch_cases.dart b/uniffi/dart/fixtures/input-scratch/test/scratch_cases.dart deleted file mode 100644 index 728210290..000000000 --- a/uniffi/dart/fixtures/input-scratch/test/scratch_cases.dart +++ /dev/null @@ -1,66 +0,0 @@ -import 'dart:typed_data'; - -import 'package:test/test.dart'; - -import '../input_scratch.dart'; -import 'tracking_allocator.dart' as tracker; - -void main() { - ensureInitialized(); - tearDown(tracker.calloc.reset); - - test( - 'owned and optional inputs release scratch after native consumption', - () { - for (var i = 0; i < 100; i++) { - expect(ownedLen(value: Uint8List.fromList([1, 2, 3])), 3); - expect(ownedLen(value: Uint8List(0)), 0); - expect(optionalLen(value: 'x' * 64), 64); - expect(optionalLen(value: ''), 0); - expect(optionalLen(value: null), 0); - expect(tracker.calloc.live, isEmpty); - } - }, - ); - - test('scratch cleanup preserves the copied RustBuffer', () { - final input = Uint8List.fromList([1, 2, 3]); - final buffer = toRustBuffer(input); - try { - expect(tracker.calloc.live, isEmpty); - input[0] = 99; - expect(buffer.asUint8List(), [1, 2, 3]); - } finally { - buffer.free(); - } - expect(tracker.calloc.live, isEmpty); - }); - - for (final optional in [false, true]) { - for (var failAt = 0; failAt < 3; failAt++) { - test( - 'partial allocation failure releases scratch: optional=$optional, allocation=$failAt', - () { - // Payload, ForeignBytes, and RustCallStatus are allocated in that order. - tracker.calloc.failAfter = failAt; - try { - expect( - () => optional - ? FfiConverterOptionalString.lower('x' * 64) - : toRustBuffer(Uint8List(64)), - throwsStateError, - ); - } finally { - tracker.calloc.failAfter = null; - } - expect(tracker.calloc.live, isEmpty); - }, - ); - } - } - - test('optional serialization failure retains no native scratch', () { - expect(() => optionalSmall(value: 256), throwsArgumentError); - expect(tracker.calloc.live, isEmpty); - }); -} diff --git a/uniffi/dart/fixtures/input-scratch/test/tracking_allocator.dart b/uniffi/dart/fixtures/input-scratch/test/tracking_allocator.dart deleted file mode 100644 index e661da86b..000000000 --- a/uniffi/dart/fixtures/input-scratch/test/tracking_allocator.dart +++ /dev/null @@ -1,34 +0,0 @@ -import 'dart:ffi'; - -import 'package:ffi/ffi.dart' as ffi; - -class TrackingAllocator implements Allocator { - final live = {}; - int? failAfter; - - @override - Pointer allocate(int byteCount, {int? alignment}) { - if (failAfter == 0) throw StateError('injected allocation failure'); - if (failAfter != null) failAfter = failAfter! - 1; - final pointer = ffi.calloc.allocate(byteCount, alignment: alignment); - live[pointer.address] = byteCount; - return pointer; - } - - @override - void free(Pointer pointer) { - if (live.remove(pointer.address) == null) { - throw StateError('free of untracked pointer'); - } - ffi.calloc.free(pointer); - } - - void reset() { - failAfter = null; - for (final address in live.keys.toList()) { - free(Pointer.fromAddress(address)); - } - } -} - -final calloc = TrackingAllocator(); diff --git a/uniffi/dart/fixtures/input-scratch/tests/mod.rs b/uniffi/dart/fixtures/input-scratch/tests/mod.rs deleted file mode 100644 index a3c33dbb9..000000000 --- a/uniffi/dart/fixtures/input-scratch/tests/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[test] -fn input_scratch() -> anyhow::Result<()> { - uniffi_dart::testing::run_test("input_scratch", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/library_config/Cargo.toml b/uniffi/dart/fixtures/library_config/Cargo.toml deleted file mode 100644 index 4e08bca6b..000000000 --- a/uniffi/dart/fixtures/library_config/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "library_config" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -name = "library_config" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/library_config/build.rs b/uniffi/dart/fixtures/library_config/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/library_config/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/library_config/src/api.udl b/uniffi/dart/fixtures/library_config/src/api.udl deleted file mode 100644 index 484d11f2a..000000000 --- a/uniffi/dart/fixtures/library_config/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace library_config { }; diff --git a/uniffi/dart/fixtures/library_config/src/lib.rs b/uniffi/dart/fixtures/library_config/src/lib.rs deleted file mode 100644 index 6d18d01bf..000000000 --- a/uniffi/dart/fixtures/library_config/src/lib.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Minimal library-mode fixture. Its committed `uniffi.toml` sets a non-default -// `package_name`, so the bindgen must read that config (via the cargo-metadata -// crate config supplier) for the generated asset id to be correct — see the -// library-mode test in `tests/mod.rs`. - -#[uniffi::export] -fn ping() -> String { - "pong".to_string() -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/library_config/tests/mod.rs b/uniffi/dart/fixtures/library_config/tests/mod.rs deleted file mode 100644 index c60c3d852..000000000 --- a/uniffi/dart/fixtures/library_config/tests/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -use anyhow::Result; - -/// Library mode must read the crate's committed `uniffi.toml` (no `--config` -/// given), so the generated asset id uses the custom `package_name` rather than -/// the default `uniffi`. Guards the CrateConfigSupplier fix — the only in-repo -/// test that exercises the library-mode generation path. -#[test] -fn library_mode_reads_uniffi_toml() -> Result<()> { - uniffi_dart::testing::assert_library_mode_asset_id("library_config", "custom_lib_pkg") -} diff --git a/uniffi/dart/fixtures/library_config/uniffi.toml b/uniffi/dart/fixtures/library_config/uniffi.toml deleted file mode 100644 index ecdb609ad..000000000 --- a/uniffi/dart/fixtures/library_config/uniffi.toml +++ /dev/null @@ -1,6 +0,0 @@ -# A non-default package_name so the library-mode test can prove the bindgen -# reads each crate's uniffi.toml (rather than defaulting, which would desync the -# generated asset id from the Native Assets build hook). -[bindings.dart] -package_name = "custom_lib_pkg" -cdylib_name = "library_config" diff --git a/uniffi/dart/fixtures/map_type/Cargo.toml b/uniffi/dart/fixtures/map_type/Cargo.toml deleted file mode 100644 index b305706b9..000000000 --- a/uniffi/dart/fixtures/map_type/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "map_type" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -name = "map_type" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true, features = [ - "build", -] } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/map_type/build.rs b/uniffi/dart/fixtures/map_type/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/map_type/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/map_type/src/api.udl b/uniffi/dart/fixtures/map_type/src/api.udl deleted file mode 100644 index 0c711997c..000000000 --- a/uniffi/dart/fixtures/map_type/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace map_type { }; diff --git a/uniffi/dart/fixtures/map_type/src/lib.rs b/uniffi/dart/fixtures/map_type/src/lib.rs deleted file mode 100644 index ccb326082..000000000 --- a/uniffi/dart/fixtures/map_type/src/lib.rs +++ /dev/null @@ -1,43 +0,0 @@ -use std::collections::HashMap; - -// Minimal Map round-trip surface. Mirrors how our qdrant-edge-ffi crate -// exposes payload/config maps: plain proc-macro exports over HashMap. - -#[uniffi::export] -pub fn roundtrip_map(m: HashMap) -> HashMap { - m -} - -#[uniffi::export] -pub fn count_entries(m: HashMap) -> u32 { - m.len() as u32 -} - -#[uniffi::export] -pub fn map_with_record_values(m: HashMap) -> HashMap { - m -} - -// Variable-length value converters (nested Map, Option) are what stress the Map -// FfiConverter's offset arithmetic — a fixed-size value (i32/Point) can't reveal -// a drifting offset. These mirror real payload shapes: string -> nested/nullable. - -#[uniffi::export] -pub fn roundtrip_nested_map( - m: HashMap>, -) -> HashMap> { - m -} - -#[uniffi::export] -pub fn roundtrip_optional_map(m: HashMap>) -> HashMap> { - m -} - -#[derive(uniffi::Record, Clone)] -pub struct Point { - x: i64, - y: i64, -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/map_type/test/map_type_test.dart b/uniffi/dart/fixtures/map_type/test/map_type_test.dart deleted file mode 100644 index 41b12988b..000000000 --- a/uniffi/dart/fixtures/map_type/test/map_type_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -import 'package:test/test.dart'; -import '../map_type.dart'; - -void main() { - test('map roundtrip preserves entries', () { - final m = {'a': 1, 'b': 2}; - final out = roundtripMap(m: m); - expect(out['a'], 1); - expect(out['b'], 2); - expect(out.length, 2); - }); - - test('map count', () { - expect(countEntries(m: {'x': 10, 'y': 20, 'z': 30}), 3); - }); - - test('map with record values', () { - final out = mapWithRecordValues(m: {'origin': Point(x: 0, y: 0), 'unit': Point(x: 1, y: 1)}); - expect(out['unit']!.x, 1); - expect(out['unit']!.y, 1); - expect(out.length, 2); - }); - - test('nested map round-trips (variable-length values)', () { - final out = roundtripNestedMap(m: { - 'a': {'x': 1, 'y': 2}, - 'b': {'z': 3}, - }); - expect(out['a']!['x'], 1); - expect(out['a']!['y'], 2); - expect(out['b']!['z'], 3); - expect(out.length, 2); - }); - - test('map with optional values round-trips (null preserved, distinct from absent)', () { - final out = roundtripOptionalMap(m: {'present': 7, 'absent': null}); - expect(out['present'], 7); - expect(out['absent'], null); - expect(out.containsKey('absent'), true); - expect(out.length, 2); - }); - - test('empty map round-trips at the length-0 boundary', () { - expect(roundtripMap(m: {}), isEmpty); - expect(countEntries(m: {}), 0); - }); -} diff --git a/uniffi/dart/fixtures/map_type/tests/mod.rs b/uniffi/dart/fixtures/map_type/tests/mod.rs deleted file mode 100644 index 2a8a2dc21..000000000 --- a/uniffi/dart/fixtures/map_type/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn map_type() -> Result<()> { - uniffi_dart::testing::run_test("map_type", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/metadata/Cargo.toml b/uniffi/dart/fixtures/metadata/Cargo.toml deleted file mode 100644 index 649a45da6..000000000 --- a/uniffi/dart/fixtures/metadata/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "metadata" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -name = "metadata" -crate-type = ["lib", "cdylib"] - -[dependencies] -thiserror = "1.0" -uniffi = { workspace = true } -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } -camino = "1.1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/metadata/build.rs b/uniffi/dart/fixtures/metadata/build.rs deleted file mode 100644 index 797041d85..000000000 --- a/uniffi/dart/fixtures/metadata/build.rs +++ /dev/null @@ -1,5 +0,0 @@ -use camino::Utf8Path; - -fn main() { - uniffi_dart::generate_scaffolding(Utf8Path::new("src/api.udl")).unwrap(); -} diff --git a/uniffi/dart/fixtures/metadata/src/api.udl b/uniffi/dart/fixtures/metadata/src/api.udl deleted file mode 100644 index 889825517..000000000 --- a/uniffi/dart/fixtures/metadata/src/api.udl +++ /dev/null @@ -1,23 +0,0 @@ -namespace metadata { - void test_metadata(); - MetadataStruct get_metadata_struct(); -}; - -dictionary MetadataStruct { - string name; - u32 version; - sequence features; -}; - -interface MetadataObject { - constructor(string name); - string get_name(); - void set_version(u32 version); - u32 get_version(); -}; - -enum MetadataType { - "Basic", - "Advanced", - "Experimental" -}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/metadata/src/lib.rs b/uniffi/dart/fixtures/metadata/src/lib.rs deleted file mode 100644 index eda81ea43..000000000 --- a/uniffi/dart/fixtures/metadata/src/lib.rs +++ /dev/null @@ -1,55 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Test metadata handling and type information generation - -pub struct MetadataStruct { - pub name: String, - pub version: u32, - pub features: Vec, -} - -pub struct MetadataObject { - name: String, - version: u32, -} - -impl MetadataObject { - pub fn new(name: String) -> Self { - MetadataObject { name, version: 0 } - } - - pub fn get_name(&self) -> String { - self.name.clone() - } - - pub fn set_version(&self, _version: u32) { - // In a real implementation, this would be mutable - // For testing purposes, we'll just validate the call works - } - - pub fn get_version(&self) -> u32 { - self.version - } -} - -pub enum MetadataType { - Basic, - Advanced, - Experimental, -} - -pub fn test_metadata() { - // Basic function to test metadata generation -} - -pub fn get_metadata_struct() -> MetadataStruct { - MetadataStruct { - name: "uniffi-dart".to_string(), - version: 1, - features: vec!["metadata".to_string(), "testing".to_string()], - } -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/metadata/test/metadata_test.dart b/uniffi/dart/fixtures/metadata/test/metadata_test.dart deleted file mode 100644 index 6472d07ca..000000000 --- a/uniffi/dart/fixtures/metadata/test/metadata_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -import 'package:test/test.dart'; -import '../metadata.dart'; - -void main() { - group('Metadata', () { - test('basic metadata functionality', () { - testMetadata(); - - final metadataStruct = getMetadataStruct(); - expect(metadataStruct.name, equals('uniffi-dart')); - expect(metadataStruct.version, equals(1)); - expect(metadataStruct.features, contains('metadata')); - expect(metadataStruct.features, contains('testing')); - }); - - test('metadata object functionality', () { - final obj = MetadataObject(name: 'test-object'); - expect(obj.getName(), equals('test-object')); - expect(obj.getVersion(), equals(0)); - - obj.setVersion(version: 42); - // Note: In real implementation, this should update the version - }); - - test('metadata enum functionality', () { - final basicType = MetadataType.basic; - expect(basicType, equals(MetadataType.basic)); - - final advancedType = MetadataType.advanced; - expect(advancedType, equals(MetadataType.advanced)); - - final experimentalType = MetadataType.experimental; - expect(experimentalType, equals(MetadataType.experimental)); - }); - }); -} diff --git a/uniffi/dart/fixtures/metadata/tests/mod.rs b/uniffi/dart/fixtures/metadata/tests/mod.rs deleted file mode 100644 index c4f53879c..000000000 --- a/uniffi/dart/fixtures/metadata/tests/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[cfg(test)] -mod tests { - #[test] - fn test_metadata() { - uniffi_dart::testing::run_test("metadata", "src/api.udl", None).unwrap(); - } -} diff --git a/uniffi/dart/fixtures/namespaces/Cargo.toml b/uniffi/dart/fixtures/namespaces/Cargo.toml deleted file mode 100644 index 8ec1eeeb5..000000000 --- a/uniffi/dart/fixtures/namespaces/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "dart_namespaces" -version = "0.1.0" -edition = "2021" -publish = false - -# One library holding both crates of the namespaces fixture, which share their type names. -[lib] -name = "dart_namespaces" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -uniffi-fixture-namespaces-media = { path = "../../../fixtures/namespaces/media" } -uniffi-fixture-namespaces-net = { path = "../../../fixtures/namespaces/net" } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = [ - "uniffi/ffi-trace", - "uniffi-fixture-namespaces-media/ffi-trace", - "uniffi-fixture-namespaces-net/ffi-trace", -] diff --git a/uniffi/dart/fixtures/namespaces/src/lib.rs b/uniffi/dart/fixtures/namespaces/src/lib.rs deleted file mode 100644 index 452e9b61b..000000000 --- a/uniffi/dart/fixtures/namespaces/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -// Link both crates' scaffolding into this library, as an application bundling them would. -uniffi_namespaces_media::uniffi_reexport_scaffolding!(); -uniffi_namespaces_net::uniffi_reexport_scaffolding!(); diff --git a/uniffi/dart/fixtures/namespaces/test/namespaces_test.dart b/uniffi/dart/fixtures/namespaces/test/namespaces_test.dart deleted file mode 100644 index 6bc337dd3..000000000 --- a/uniffi/dart/fixtures/namespaces/test/namespaces_test.dart +++ /dev/null @@ -1,98 +0,0 @@ -import 'dart:typed_data'; - -import 'package:test/test.dart'; -import '../media.dart' as media; -import '../net.dart' as net; - -net.Frame netFrame(List payload) => net.Frame(payload: Uint8List.fromList(payload)); - -net.GroupConsumer netGroup(int sequence, net.Priority priority, List> payloads) => - net.GroupConsumer( - sequence: sequence, - priority: priority, - frames: payloads.map(netFrame).toList(), - ); - -void main() { - test('an object wraps its namesake', () { - final inner = netGroup(3, net.Priority.low, [ - [1, 97], - [0, 98], - ]); - final group = media.GroupConsumer(group: inner); - expect(group.group(), isA()); - expect(group.group().sequence(), 3); - final priority = group.priority(); - expect(priority, isA()); - expect((priority as media.NetPriority).priority, net.Priority.low); - - final frame = group.readFrame(); - expect(frame, isA()); - expect(frame.raw.payload, [1, 97]); - expect(frame.keyframe, true); - expect(group.readFrame().keyframe, false); - - // Each layer's error, both named `GroupError`. - try { - group.readFrame(); - fail('expected media.NetGroupException'); - } on media.NetGroupException catch (e) { - expect(e.source, isA()); - expect((e.source as net.ClosedGroupException).code, 7); - } - expect(() => media.decode(raw: netFrame([])), throwsA(isA())); - }); - - test('async throws the net error', () async { - final group = media.GroupConsumer( - group: netGroup(1, net.Priority.high, [ - [1], - ]), - ); - expect(group.priority(), isA()); - - final frame = await group.nextFrame(); - expect(frame.raw.payload, [1]); - try { - await group.nextFrame(); - fail('expected net.ClosedGroupException'); - } on net.ClosedGroupException catch (e) { - expect(e.code, 7); - } - }); - - test('containers of both', () { - final frame = media.decode(raw: netFrame([0, 122])); - expect(media.encode(frame: frame).payload, [0, 122]); - - final frames = media.decodeAll(raw: [ - netFrame([0, 97]), - netFrame([]), - netFrame([1, 98]), - ]); - expect(frames.map((f) => f.keyframe).toList(), [false, true]); - final bounds = media.findBounds(frames: frames); - expect(bounds.keyframe!.raw.payload, [1, 98]); - expect(bounds.last!.payload, [1, 98]); - final empty = media.findBounds(frames: []); - expect(empty.keyframe, isNull); - expect(empty.last, isNull); - - final groups = media.wrapAll(groups: [ - netGroup(1, net.Priority.low, []), - netGroup(2, net.Priority.high, []), - ]); - expect(groups.groups.map((g) => g.group().sequence()).toList(), [1, 2]); - expect(groups.net, {1: net.Priority.low, 2: net.Priority.high}); - expect((groups.media[1] as media.NetPriority).priority, net.Priority.low); - expect(groups.media[2], isA()); - }); - - test('variants hold a data enum and its flat namesake', () { - final tracks = media.tracks(kind: net.VideoKind(640)); - expect(tracks.length, 2); - final kind = (tracks[0] as media.NetTrack).kind; - expect((kind as net.VideoKind).width, 640); - expect((tracks[1] as media.MediaTrack).kind, media.Kind.video); - }); -} diff --git a/uniffi/dart/fixtures/namespaces/tests/mod.rs b/uniffi/dart/fixtures/namespaces/tests/mod.rs deleted file mode 100644 index e2f0892e9..000000000 --- a/uniffi/dart/fixtures/namespaces/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn namespaces() -> Result<()> { - uniffi_dart::testing::run_library_test("dart_namespaces") -} diff --git a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/Cargo.toml b/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/Cargo.toml deleted file mode 100644 index 893d1e01f..000000000 --- a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "proc-macro-no-implicit-prelude" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -name = "proc_macro_no_implicit_prelude" -crate-type = ["lib", "cdylib"] - -[features] -ffi-trace = ["uniffi/ffi-trace"] -default = ["myfeature"] -myfeature = [] - -[dependencies] -thiserror = "1.0" -uniffi = { workspace = true, features = ["scaffolding-ffi-buffer-fns"] } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } -camino = "1" - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" diff --git a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/build.rs b/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/build.rs deleted file mode 100644 index 797041d85..000000000 --- a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/build.rs +++ /dev/null @@ -1,5 +0,0 @@ -use camino::Utf8Path; - -fn main() { - uniffi_dart::generate_scaffolding(Utf8Path::new("src/api.udl")).unwrap(); -} diff --git a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/api.udl b/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/api.udl deleted file mode 100644 index d2118dc06..000000000 --- a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/api.udl +++ /dev/null @@ -1,26 +0,0 @@ -// Tests proc-macros work without Rust `std::` type preludes. -dictionary Zero { - string inner; -}; - -typedef record One; -typedef enum MaybeBool; -typedef interface Object; -typedef trait Trait; -typedef trait_with_foreign TraitWithForeign; - -// Then stuff defined here but referencing the imported types. -dictionary Externals { - One? one; - MaybeBool? bool; -}; - -// Namespace different from crate name. -namespace proc_macro { - One get_one(One? one); - MaybeBool get_bool(MaybeBool? b); - Object get_object(Object? o); - Trait get_trait(Trait? t); - TraitWithForeign get_trait_with_foreign(TraitWithForeign? t); - Externals get_externals(Externals? e); -}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/callback_interface.rs b/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/callback_interface.rs deleted file mode 100644 index 40919c432..000000000 --- a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/callback_interface.rs +++ /dev/null @@ -1,24 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use ::std::{marker::Sized, sync::Arc}; - -use crate::{BasicError, Object, RecordWithBytes}; - -#[::uniffi::export(with_foreign)] -pub trait TestCallbackInterface: ::std::marker::Send + ::std::marker::Sync { - fn do_nothing(&self); - fn add(&self, a: u32, b: u32) -> u32; - fn optional(&self, a: ::std::option::Option) -> u32; - fn with_bytes(&self, rwb: RecordWithBytes) -> ::std::vec::Vec; - fn try_parse_int(&self, value: ::std::string::String) - -> ::std::result::Result; - fn callback_handler(&self, h: Arc) -> u32; - fn get_other_callback_interface(&self) -> Arc; -} - -#[::uniffi::export(with_foreign)] -pub trait OtherCallbackInterface: ::std::marker::Send + ::std::marker::Sync { - fn multiply(&self, a: u32, b: u32) -> u32; -} diff --git a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/lib.rs b/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/lib.rs deleted file mode 100644 index 2b92f526d..000000000 --- a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/src/lib.rs +++ /dev/null @@ -1,404 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#![no_implicit_prelude] - -// Let's not have the macros care about derive being shadowed in the macro namespace for now.. -// Required for now because `static-assertions` (used internally) macros assume it to be in scope. -use ::std::marker::Sized; -use ::std::prelude::rust_2021::derive; - -mod callback_interface; - -use callback_interface::TestCallbackInterface; - -#[derive(::uniffi::Record)] -pub struct One { - inner: i32, -} - -#[::uniffi::export] -pub fn one_inner_by_ref(one: &One) -> i32 { - one.inner -} - -#[derive(::uniffi::Record)] -pub struct Two { - a: ::std::string::String, -} - -#[derive(::uniffi::Record)] -pub struct NestedRecord { - // This used to result in an error in bindings generation - user_type_in_builtin_generic: ::std::option::Option, -} - -#[derive(::uniffi::Record)] -pub struct Three { - obj: ::std::sync::Arc, -} - -#[derive(::uniffi::Record, Debug, PartialEq)] -pub struct RecordWithBytes { - some_bytes: ::std::vec::Vec, -} - -// An object that's not used anywhere (ie, in records, function signatures, etc) -// should not break things. -#[derive(::uniffi::Object)] -pub struct Unused; - -#[::uniffi::export] -impl Unused { - #[::uniffi::constructor] - fn new() -> ::std::sync::Arc { - ::std::sync::Arc::new(Self) - } -} - -#[::uniffi::export] -pub trait Trait: ::std::marker::Send + ::std::marker::Sync { - // Test the absence of `with_foreign` by inputting reference arguments, which is - // incompatible with callback interfaces - #[allow(clippy::ptr_arg)] - fn concat_strings(&self, a: &str, b: &str) -> ::std::string::String; -} - -struct TraitImpl {} - -impl Trait for TraitImpl { - fn concat_strings(&self, a: &str, b: &str) -> ::std::string::String { - ::std::format!("{a}{b}") - } -} - -#[::uniffi::export(with_foreign)] -pub trait TraitWithForeign: ::std::marker::Send + ::std::marker::Sync { - fn name(&self) -> ::std::string::String; -} - -struct RustTraitImpl {} - -impl TraitWithForeign for RustTraitImpl { - fn name(&self) -> ::std::string::String { - use ::std::string::ToString; - "RustTraitImpl".to_string() - } -} - -#[derive(::uniffi::Object)] -pub struct Object; - -#[cfg_attr(feature = "myfeature", ::uniffi::export)] -impl Object { - #[cfg_attr(feature = "myfeature", ::uniffi::constructor)] - fn new() -> ::std::sync::Arc { - ::std::sync::Arc::new(Self) - } - - #[::uniffi::constructor] - fn named_ctor(arg: u32) -> Self { - _ = arg; - // This constructor returns Self directly. UniFFI ensures that it's wrapped in an Arc - // before sending it across the FFI. - Self - } - - fn is_heavy(&self) -> MaybeBool { - MaybeBool::Uncertain - } - - fn is_other_heavy(&self, other: &Self) -> MaybeBool { - other.is_heavy() - } - - fn get_trait( - &self, - inc: ::std::option::Option<::std::sync::Arc>, - ) -> ::std::sync::Arc { - inc.unwrap_or_else(|| ::std::sync::Arc::new(TraitImpl {})) - } - - fn get_trait_with_foreign( - &self, - inc: ::std::option::Option<::std::sync::Arc>, - ) -> ::std::sync::Arc { - inc.unwrap_or_else(|| ::std::sync::Arc::new(RustTraitImpl {})) - } - - fn take_error(&self, e: BasicError) -> u32 { - ::std::assert!(::std::matches!(e, BasicError::InvalidInput)); - 42 - } -} - -#[::uniffi::export] -fn concat_strings_by_ref(t: &dyn Trait, a: &str, b: &str) -> ::std::string::String { - t.concat_strings(a, b) -} - -#[::uniffi::export] -fn make_one(inner: i32) -> One { - One { inner } -} - -#[::uniffi::export] -fn take_two(two: Two) -> ::std::string::String { - two.a -} - -#[::uniffi::export] -fn make_hashmap(k: i8, v: u64) -> ::std::collections::HashMap { - ::std::convert::From::from([(k, v)]) -} - -#[::uniffi::export] -fn return_hashmap(h: ::std::collections::HashMap) -> ::std::collections::HashMap { - h -} - -#[::uniffi::export] -fn take_record_with_bytes(rwb: RecordWithBytes) -> ::std::vec::Vec { - rwb.some_bytes -} - -#[::uniffi::export] -pub fn call_callback_interface(cb: ::std::sync::Arc) { - use ::std::option::Option::*; - use ::std::result::Result::*; - use ::std::string::ToString; - use ::std::{assert_eq, matches, vec}; - - cb.do_nothing(); - assert_eq!(cb.add(1, 1), 2); - assert_eq!(cb.optional(Some(1)), 1); - assert_eq!(cb.optional(None), 0); - assert_eq!(cb.with_bytes(RecordWithBytes { some_bytes: vec![9, 8, 7] }), vec![9, 8, 7]); - assert_eq!(Ok(10), cb.try_parse_int("10".to_string())); - assert_eq!(Err(BasicError::InvalidInput), cb.try_parse_int("ten".to_string())); - assert!(matches!( - cb.try_parse_int("force-unexpected-error".to_string()), - Err(BasicError::UnexpectedError { .. }), - )); - assert_eq!(42, cb.callback_handler(Object::new())); - - assert_eq!(6, cb.get_other_callback_interface().multiply(2, 3)); -} - -// Type that's defined in the UDL and not wrapped with #[::uniffi::export] -pub struct Zero { - inner: ::std::string::String, -} - -#[::uniffi::export] -fn make_zero() -> Zero { - use ::std::borrow::ToOwned; - Zero { inner: "ZERO".to_owned() } -} - -#[::uniffi::export] -fn make_record_with_bytes() -> RecordWithBytes { - RecordWithBytes { some_bytes: ::std::vec![0, 1, 2, 3, 4] } -} - -#[derive(::uniffi::Enum)] -pub enum MaybeBool { - True, - False, - Uncertain, -} - -#[derive(::uniffi::Enum)] -pub enum MixedEnum { - None, - String(::std::string::String), - Int(i64), - Both(::std::string::String, i64), - All { s: ::std::string::String, i: i64 }, -} - -#[::uniffi::export] -fn get_mixed_enum(v: ::std::option::Option) -> MixedEnum { - v.unwrap_or(MixedEnum::Int(1)) -} - -#[repr(u8)] -#[derive(::uniffi::Enum)] -pub enum ReprU8 { - One = 1, - Three = 0x3, -} - -#[::uniffi::export] -fn enum_identity(value: MaybeBool) -> MaybeBool { - value -} - -#[derive(::uniffi::Error, Debug, PartialEq, Eq)] -pub enum BasicError { - InvalidInput, - OsError, - UnexpectedError { reason: ::std::string::String }, -} - -impl ::std::fmt::Display for BasicError { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - f.write_str(match self { - Self::InvalidInput => "InvalidInput", - Self::OsError => "OsError", - Self::UnexpectedError { .. } => "UnexpectedError", - }) - } -} - -impl ::std::error::Error for BasicError {} - -impl ::std::convert::From<::uniffi::UnexpectedUniFFICallbackError> for BasicError { - fn from(e: ::uniffi::UnexpectedUniFFICallbackError) -> Self { - Self::UnexpectedError { reason: e.reason } - } -} - -#[::uniffi::export] -fn always_fails() -> ::std::result::Result<(), BasicError> { - ::std::result::Result::Err(BasicError::OsError) -} - -#[derive(Debug, ::uniffi::Error)] -#[uniffi(flat_error)] -#[non_exhaustive] -pub enum FlatError { - InvalidInput, - - // Inner types that aren't FFI-convertible, as well as unnamed fields, - // are allowed for flat errors - OsError(::std::io::Error), -} - -impl ::std::fmt::Display for FlatError { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match self { - Self::InvalidInput => f.write_str("Invalid input"), - Self::OsError(e) => ::std::write!(f, "OS error: {e}"), - } - } -} - -#[::uniffi::export] -impl Object { - fn do_stuff(&self, times: u32) -> ::std::result::Result<(), FlatError> { - match times { - 0 => ::std::result::Result::Err(FlatError::InvalidInput), - _ => { - // do stuff - ::std::result::Result::Ok(()) - } - } - } -} - -// defined in UDL. -fn get_one(one: ::std::option::Option) -> One { - one.unwrap_or(One { inner: 0 }) -} - -fn get_bool(b: ::std::option::Option) -> MaybeBool { - b.unwrap_or(MaybeBool::Uncertain) -} - -fn get_object(o: ::std::option::Option<::std::sync::Arc>) -> ::std::sync::Arc { - o.unwrap_or_else(Object::new) -} - -fn get_trait(o: ::std::option::Option<::std::sync::Arc>) -> ::std::sync::Arc { - o.unwrap_or_else(|| ::std::sync::Arc::new(TraitImpl {})) -} - -fn get_trait_with_foreign( - o: ::std::option::Option<::std::sync::Arc>, -) -> ::std::sync::Arc { - o.unwrap_or_else(|| ::std::sync::Arc::new(RustTraitImpl {})) -} - -#[derive(Default)] -struct Externals { - one: ::std::option::Option, - bool: ::std::option::Option, -} - -fn get_externals(e: ::std::option::Option) -> Externals { - e.unwrap_or_default() -} - -#[::uniffi::export] -pub fn join(parts: &[::std::string::String], sep: &str) -> ::std::string::String { - parts.join(sep) -} - -// Custom names -#[derive(::uniffi::Object)] -pub struct Renamed; - -// `renamed_new` becomes the default constructor because it's named `new` -#[::uniffi::export] -impl Renamed { - #[::uniffi::constructor(name = "new")] - fn renamed_new() -> ::std::sync::Arc { - ::std::sync::Arc::new(Self) - } - - #[::uniffi::method(name = "func")] - fn renamed_func(&self) -> bool { - true - } -} - -#[::uniffi::export(name = "rename_test")] -fn renamed_rename_test() -> bool { - true -} - -/// Test defaults on Records -#[derive(::uniffi::Record)] -pub struct RecordWithDefaults { - no_default_string: ::std::string::String, - #[uniffi(default = true)] - boolean: bool, - #[uniffi(default = 42)] - integer: i32, - #[uniffi(default = 4.2)] - float_var: f64, - #[uniffi(default=[])] - vec: ::std::vec::Vec, - #[uniffi(default=None)] - opt_vec: ::std::option::Option<::std::vec::Vec>, - #[uniffi(default = Some(42))] - opt_integer: ::std::option::Option, -} - -/// Test defaults on top-level functions -#[::uniffi::export(default(num = 21))] -fn double_with_default(num: i32) -> i32 { - num + num -} - -/// Test defaults on constructors / methods -#[derive(::uniffi::Object)] -pub struct ObjectWithDefaults { - num: i32, -} - -#[::uniffi::export] -impl ObjectWithDefaults { - #[::uniffi::constructor(default(num = 30))] - fn new(num: i32) -> Self { - Self { num } - } - - #[::uniffi::method(default(other = 12))] - fn add_to_num(&self, other: i32) -> i32 { - self.num + other - } -} - -::uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/test/proc_macro_no_implicit_prelude_test.dart b/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/test/proc_macro_no_implicit_prelude_test.dart deleted file mode 100644 index f6f4faf98..000000000 --- a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/test/proc_macro_no_implicit_prelude_test.dart +++ /dev/null @@ -1,235 +0,0 @@ -import 'dart:typed_data'; - -import 'package:test/test.dart'; -import '../proc_macro.dart'; - -// Mock callback interface implementations -class DartTestCallbackInterface implements TestCallbackInterface { - @override - void doNothing() { - // Does nothing - } - - @override - int add(int a, int b) { - return a + b; - } - - @override - int optional(int? a) { - return a ?? 0; - } - - @override - Uint8List withBytes(RecordWithBytes rwb) => Uint8List.fromList(rwb.someBytes); - - @override - int tryParseInt(String value) { - if (value == 'force-unexpected-error') { - throw StateError('forced unexpected error'); - } - final parsed = int.tryParse(value); - if (parsed == null) { - throw InvalidInputBasicException(); - } - return parsed; - } - - @override - int callbackHandler(Object h) { - return h.isHeavy() == MaybeBool.uncertain ? 42 : 0; - } - - @override - OtherCallbackInterface getOtherCallbackInterface() { - return DartOtherCallbackInterface(); - } -} - -class DartOtherCallbackInterface implements OtherCallbackInterface { - @override - int multiply(int a, int b) { - return a * b; - } -} - -void main() { - ensureInitialized(); - - group('Proc-Macro No Implicit Prelude', () { - test('basic records without prelude', () { - final one = makeOne(inner: 42); - expect(one.inner, equals(42)); - expect(oneInnerByRef(one: one), equals(42)); - - final two = Two(a: 'hello'); - expect(takeTwo(two: two), equals('hello')); - }); - - test('nested and complex records', () { - final nested = NestedRecord(userTypeInBuiltinGeneric: Two(a: 'nested')); - expect(nested.userTypeInBuiltinGeneric?.a, equals('nested')); - - final recordWithBytes = makeRecordWithBytes(); - expect(recordWithBytes.someBytes, equals([0, 1, 2, 3, 4])); - - final extractedBytes = takeRecordWithBytes(rwb: recordWithBytes); - expect(extractedBytes, equals([0, 1, 2, 3, 4])); - }); - - test('objects without prelude', () { - final obj = Object(); - expect(obj, isNotNull); - - final namedObj = Object.namedCtor(arg: 123); - expect(namedObj, isNotNull); - - expect(obj.isHeavy(), equals(MaybeBool.uncertain)); - expect(obj.isOtherHeavy(other: namedObj), equals(MaybeBool.uncertain)); - - obj.dispose(); - namedObj.dispose(); - }); - - test('enums without prelude', () { - expect(enumIdentity(value: MaybeBool.true_), equals(MaybeBool.true_)); - expect(enumIdentity(value: MaybeBool.false_), equals(MaybeBool.false_)); - expect( - enumIdentity(value: MaybeBool.uncertain), - equals(MaybeBool.uncertain), - ); - - final mixedEnum = getMixedEnum(v: StringMixedEnum('test')); - expect(mixedEnum, isA()); - - final defaultMixed = getMixedEnum(v: null); - expect(defaultMixed, isA()); - expect((defaultMixed as IntMixedEnum).v0, equals(1)); - }); - - test('errors without prelude', () { - expect(() => alwaysFails(), throwsA(isA())); - - final obj = Object(); - final result = obj.takeError(e: InvalidInputBasicException()); - expect(result, equals(42)); - obj.dispose(); - }); - - test('hashmaps without prelude', () { - final hashMap = makeHashmap(k: 1, v: 100); - expect(hashMap, isA>()); - - final returned = returnHashmap(h: hashMap); - expect(returned[1], equals(100)); - }); - - test('traits without prelude', () { - final obj = Object(); - final trait = obj.getTrait(inc: null); - expect(trait, isNotNull); - - final result = concatStringsByRef(t: trait, a: 'hello', b: 'world'); - expect(result, equals('helloworld')); - - final traitWithForeign = obj.getTraitWithForeign(inc: null); - expect(traitWithForeign, isNotNull); - expect(traitWithForeign.name(), equals('RustTraitImpl')); - - obj.dispose(); - trait.dispose(); - }); - - test('callback interfaces without prelude', () { - final callback = DartTestCallbackInterface(); - - expect(() => callCallbackInterface(cb: callback), returnsNormally); - }); - - test('UDL integration with proc-macro types', () { - final one = getOne(one: One(inner: 123)); - expect(one.inner, equals(123)); - - final defaultOne = getOne(one: null); - expect(defaultOne.inner, equals(0)); - - final bool_ = getBool(b: MaybeBool.true_); - expect(bool_, equals(MaybeBool.true_)); - - final defaultBool = getBool(b: null); - expect(defaultBool, equals(MaybeBool.uncertain)); - - final obj = getObject(o: null); - expect(obj, isNotNull); - - final externals = getExternals(e: null); - expect(externals.one, isNull); - expect(externals.bool, isNull); - - obj.dispose(); - }); - - test('custom names', () { - final renamed = Renamed(); - expect(renamed, isNotNull); - expect(renamed.func(), equals(true)); - - expect(renameTest(), equals(true)); - - renamed.dispose(); - }); - - test('explicit values for defaultable APIs', () { - expect(doubleWithDefault(), equals(42)); - expect(doubleWithDefault(num: 21), equals(42)); - expect(doubleWithDefault(num: 10), equals(20)); - - final objWithDefaults = ObjectWithDefaults(num: 30); - expect(objWithDefaults.addToNum(), equals(42)); - expect(objWithDefaults.addToNum(other: 12), equals(42)); - expect(objWithDefaults.addToNum(other: 5), equals(35)); - objWithDefaults.dispose(); - - final defaultObjWithDefaults = ObjectWithDefaults(); - expect(defaultObjWithDefaults.addToNum(other: 12), equals(42)); - defaultObjWithDefaults.dispose(); - }); - - test('string operations without prelude', () { - final result = join(parts: ['hello', 'world'], sep: ' '); - expect(result, equals('hello world')); - - final zero = makeZero(); - expect(zero.inner, equals('ZERO')); - }); - - test('flat errors', () { - final obj = Object(); - - expect(() => obj.doStuff(times: 0), throwsA(FlatException.invalidInput)); - expect(() => obj.doStuff(times: 1), returnsNormally); - obj.dispose(); - }); - - test('comprehensive proc-macro functionality', () { - final one = One(inner: 999); - expect(one.inner, equals(999)); - - final maybeBool = MaybeBool.true_; - expect(maybeBool, equals(MaybeBool.true_)); - - final obj = Object(); - expect(obj, isNotNull); - - final recordBytes = RecordWithBytes( - someBytes: Uint8List.fromList([1, 2, 3]), - ); - expect(recordBytes.someBytes, equals([1, 2, 3])); - - final zero = Zero(inner: 'test'); - expect(zero.inner, equals('test')); - - obj.dispose(); - }); - }); -} diff --git a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/tests/mod.rs b/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/tests/mod.rs deleted file mode 100644 index e92ec2121..000000000 --- a/uniffi/dart/fixtures/proc-macro-no-implicit-prelude/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn proc_macro_no_implicit_prelude() -> Result<()> { - uniffi_dart::testing::run_test("proc-macro-no-implicit-prelude", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/proc-macro/Cargo.toml b/uniffi/dart/fixtures/proc-macro/Cargo.toml deleted file mode 100644 index 2aed16bcb..000000000 --- a/uniffi/dart/fixtures/proc-macro/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "proc_macro_uniffi" -version = "0.1.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "proc_macro_uniffi" -crate-type = ["lib", "cdylib"] - -[features] -ffi-trace = ["uniffi/ffi-trace"] -default = ["myfeature"] -myfeature = [] - -[dependencies] -uniffi = { workspace = true, features = ["scaffolding-ffi-buffer-fns"] } -thiserror = "1.0" -lazy_static = "1.4" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" \ No newline at end of file diff --git a/uniffi/dart/fixtures/proc-macro/build.rs b/uniffi/dart/fixtures/proc-macro/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/proc-macro/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/proc-macro/src/api.udl b/uniffi/dart/fixtures/proc-macro/src/api.udl deleted file mode 100644 index 817ad7ed1..000000000 --- a/uniffi/dart/fixtures/proc-macro/src/api.udl +++ /dev/null @@ -1,27 +0,0 @@ -// Use this to test that types defined in the UDL can be used in the proc-macros -dictionary Zero { - string inner; -}; - -// And all of these for the opposite - proc-macro types used in UDL. -typedef record One; -typedef enum MaybeBool; -typedef interface Object; -typedef trait Trait; -typedef trait_with_foreign TraitWithForeign; - -// Then stuff defined here but referencing the imported types. -dictionary Externals { - One? one; - MaybeBool? bool; -}; - -// Namespace different from crate name. -namespace proc_macro { - One get_one(One? one); - MaybeBool get_bool(MaybeBool? b); - Object get_object(Object? o); - Trait get_trait(Trait? t); - TraitWithForeign get_trait_with_foreign(TraitWithForeign? t); - Externals get_externals(Externals? e); -}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/proc-macro/src/callback_interface.rs b/uniffi/dart/fixtures/proc-macro/src/callback_interface.rs deleted file mode 100644 index ef45e81dc..000000000 --- a/uniffi/dart/fixtures/proc-macro/src/callback_interface.rs +++ /dev/null @@ -1,19 +0,0 @@ -use std::sync::Arc; - -use crate::{BasicError, Object, RecordWithBytes}; - -#[uniffi::export(with_foreign)] -pub trait TestCallbackInterface: Send + Sync { - fn do_nothing(&self); - fn add(&self, a: i32, b: i32) -> i32; - fn optional(&self, a: Option) -> i32; - fn with_bytes(&self, rwb: RecordWithBytes) -> Vec; - fn try_parse_int(&self, value: String) -> Result; - fn callback_handler(&self, o: Arc) -> i32; - fn get_other_callback_interface(&self) -> Arc; -} - -#[uniffi::export(with_foreign)] -pub trait OtherCallbackInterface: Send + Sync { - fn multiply(&self, a: i32, b: i32) -> i32; -} diff --git a/uniffi/dart/fixtures/proc-macro/src/lib.rs b/uniffi/dart/fixtures/proc-macro/src/lib.rs deleted file mode 100644 index 09f072042..000000000 --- a/uniffi/dart/fixtures/proc-macro/src/lib.rs +++ /dev/null @@ -1,202 +0,0 @@ -use std::collections::HashMap; -use std::sync::Arc; - -mod callback_interface; -pub use callback_interface::{OtherCallbackInterface, TestCallbackInterface}; - -#[derive(uniffi::Record)] -pub struct One { - inner: i32, -} - -#[derive(uniffi::Record)] -pub struct Two { - a: String, -} - -#[derive(uniffi::Record)] -pub struct RecordWithBytes { - some_bytes: Vec, -} - -#[derive(uniffi::Object)] -pub struct Object; - -#[uniffi::export] -impl Object { - #[uniffi::constructor] - fn new() -> Arc { - Arc::new(Self) - } - - fn is_heavy(&self) -> MaybeBool { - MaybeBool::Uncertain - } - - fn get_trait(&self, inc: Option>) -> Arc { - inc.unwrap_or_else(|| Arc::new(TraitImpl {})) - } - - fn get_trait_with_foreign( - &self, - inc: Option>, - ) -> Arc { - inc.unwrap_or_else(|| Arc::new(RustTraitImpl {})) - } -} - -#[uniffi::export] -pub trait Trait: Send + Sync { - fn concat_strings(&self, a: &str, b: &str) -> String; -} - -struct TraitImpl {} - -impl Trait for TraitImpl { - fn concat_strings(&self, a: &str, b: &str) -> String { - format!("{a}{b}") - } -} - -#[uniffi::export(with_foreign)] -pub trait TraitWithForeign: Send + Sync { - fn name(&self) -> String; -} - -struct RustTraitImpl {} - -impl TraitWithForeign for RustTraitImpl { - fn name(&self) -> String { - "RustTraitImpl".to_string() - } -} - -#[uniffi::export] -pub fn make_one(inner: i32) -> One { - One { inner } -} - -#[uniffi::export] -pub fn take_two(two: Two) -> String { - two.a -} - -#[uniffi::export] -pub fn make_hashmap(k: i8, v: u64) -> HashMap { - HashMap::from([(k, v)]) -} - -#[derive(uniffi::Enum)] -pub enum MaybeBool { - True, - False, - Uncertain, -} - -#[derive(uniffi::Enum)] -pub enum MixedEnum { - None, - String(String), - Int(i64), - Both(String, i64), -} - -#[derive(thiserror::Error, uniffi::Error, Debug, PartialEq, Eq)] -pub enum BasicError { - #[error("InvalidInput")] - InvalidInput, - #[error("OsError")] - OsError, - #[error("UnexpectedError")] - UnexpectedError { reason: String }, -} - -#[uniffi::export] -pub fn always_fails() -> Result<(), BasicError> { - Err(BasicError::OsError) -} - -// Type that's defined in the UDL and not wrapped with #[uniffi::export] -pub struct Zero { - inner: String, -} - -#[uniffi::export] -fn make_zero() -> Zero { - Zero { inner: String::from("ZERO") } -} - -// UDL functions that reference proc-macro types -fn get_one(one: Option) -> One { - one.unwrap_or(One { inner: 0 }) -} - -fn get_bool(b: Option) -> MaybeBool { - b.unwrap_or(MaybeBool::Uncertain) -} - -fn get_object(o: Option>) -> Arc { - o.unwrap_or_else(Object::new) -} - -fn get_trait(o: Option>) -> Arc { - o.unwrap_or_else(|| Arc::new(TraitImpl {})) -} - -fn get_trait_with_foreign(o: Option>) -> Arc { - o.unwrap_or_else(|| Arc::new(RustTraitImpl {})) -} - -#[derive(Default)] -struct Externals { - one: Option, - bool: Option, -} - -fn get_externals(e: Option) -> Externals { - e.unwrap_or_default() -} - -#[uniffi::export] -pub fn callback_do_nothing(callback: Arc) { - callback.do_nothing() -} - -#[uniffi::export] -pub fn callback_add(callback: Arc, a: i32, b: i32) -> i32 { - callback.add(a, b) -} - -#[uniffi::export] -pub fn callback_optional(callback: Arc, value: Option) -> i32 { - callback.optional(value) -} - -#[uniffi::export] -pub fn callback_with_bytes(callback: Arc, bytes: Vec) -> Vec { - callback.with_bytes(RecordWithBytes { some_bytes: bytes }) -} - -#[uniffi::export] -pub fn callback_try_parse_int( - callback: Arc, - value: String, -) -> Result { - callback.try_parse_int(value) -} - -#[uniffi::export] -pub fn callback_handler(callback: Arc) -> i32 { - callback.callback_handler(Object::new()) -} - -#[uniffi::export] -pub fn callback_get_other_multiply( - callback: Arc, - a: i32, - b: i32, -) -> i32 { - callback.get_other_callback_interface().multiply(a, b) -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/proc-macro/test/proc_macro_test.dart b/uniffi/dart/fixtures/proc-macro/test/proc_macro_test.dart deleted file mode 100644 index f6a6f329d..000000000 --- a/uniffi/dart/fixtures/proc-macro/test/proc_macro_test.dart +++ /dev/null @@ -1,159 +0,0 @@ -import 'dart:typed_data'; - -import 'package:test/test.dart'; -import '../proc_macro.dart'; - -class DartOtherCallback implements OtherCallbackInterface { - @override - int multiply(int a, int b) => a * b; -} - -class DartTraitWithForeign implements TraitWithForeign { - DartTraitWithForeign(this.value); - - final String value; - - @override - String name() => value; -} - -class DartTestCallback implements TestCallbackInterface { - var didNothing = false; - - @override - void doNothing() { - didNothing = true; - } - - @override - int add(int a, int b) => a + b; - - @override - int optional(int? a) => a ?? -1; - - @override - Uint8List withBytes(RecordWithBytes rwb) { - return Uint8List.fromList(rwb.someBytes.reversed.toList()); - } - - @override - int tryParseInt(String value) { - if (value == 'bad') { - throw InvalidInputBasicException(); - } - return int.parse(value); - } - - @override - int callbackHandler(Object o) { - return o.isHeavy() == MaybeBool.uncertain ? 42 : -1; - } - - @override - OtherCallbackInterface getOtherCallbackInterface() => DartOtherCallback(); -} - -void main() { - ensureInitialized(); - - group('ProcMacro', () { - test('UDL and proc-macro interoperability', () { - final one = makeOne(inner: 42); - expect(one.inner, 42); - - final two = Two(a: 'hello'); - expect(takeTwo(two: two), 'hello'); - - expect(makeHashmap(k: 1, v: 100), {1: 100}); - - final obj = Object(); - expect(obj.isHeavy(), MaybeBool.uncertain); - - final defaultObject = getObject(o: null); - expect(defaultObject.isHeavy(), MaybeBool.uncertain); - - expect(() => alwaysFails(), throwsA(isA())); - - expect(getOne(one: null).inner, 0); - expect(getOne(one: One(inner: 7)).inner, 7); - expect(getBool(b: null), MaybeBool.uncertain); - expect(getBool(b: MaybeBool.true_), MaybeBool.true_); - - final zero = makeZero(); - expect(zero.inner, 'ZERO'); - - final externals = getExternals(e: null); - expect(externals.one, isNull); - expect(externals.bool, isNull); - - final filled = getExternals( - e: Externals(one: One(inner: 5), bool: MaybeBool.false_), - ); - expect(filled.one?.inner, 5); - expect(filled.bool, MaybeBool.false_); - - final rustForeignTrait = getTraitWithForeign(t: null); - expect(rustForeignTrait.name(), 'RustTraitImpl'); - - final dartForeignTrait = DartTraitWithForeign('from-dart'); - expect(getTraitWithForeign(t: dartForeignTrait).name(), 'from-dart'); - - obj.dispose(); - defaultObject.dispose(); - }); - - test('callback interfaces', () { - final callback = DartTestCallback(); - - callbackDoNothing(callback: callback); - expect(callback.didNothing, isTrue); - expect(callbackAdd(callback: callback, a: 2, b: 3), 5); - expect(callbackOptional(callback: callback, value: null), -1); - expect(callbackOptional(callback: callback, value: 9), 9); - expect( - callbackWithBytes( - callback: callback, - bytes: Uint8List.fromList([1, 2, 3]), - ), - [3, 2, 1], - ); - expect(callbackTryParseInt(callback: callback, value: '42'), 42); - expect(callbackHandler(callback: callback), 42); - expect(callbackGetOtherMultiply(callback: callback, a: 6, b: 7), 42); - }); - - test('callback interfaces preserve expected errors', () { - final callback = DartTestCallback(); - - expect( - () => callbackTryParseInt(callback: callback, value: 'bad'), - throwsA(isA()), - ); - }); - - test('trait objects', () { - final obj = Object(); - - final fromMethod = obj.getTrait(inc: null); - expect( - fromMethod.concatStrings(a: 'hello, ', b: 'trait'), - 'hello, trait', - ); - - final roundtripped = obj.getTrait(inc: fromMethod); - expect(roundtripped.concatStrings(a: 'round', b: 'trip'), 'roundtrip'); - - final fromFunction = getTrait(t: null); - expect(fromFunction.concatStrings(a: 'top', b: 'level'), 'toplevel'); - - final functionRoundtrip = getTrait(t: fromFunction); - expect(functionRoundtrip.concatStrings(a: 'again', b: '!'), 'again!'); - - obj.dispose(); - fromMethod.dispose(); - roundtripped.dispose(); - fromFunction.dispose(); - functionRoundtrip.dispose(); - }); - }); -} diff --git a/uniffi/dart/fixtures/proc-macro/tests/mod.rs b/uniffi/dart/fixtures/proc-macro/tests/mod.rs deleted file mode 100644 index 225950822..000000000 --- a/uniffi/dart/fixtures/proc-macro/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn proc_macro() -> Result<()> { - uniffi_dart::testing::run_test("proc_macro_uniffi", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/simple-fns/Cargo.toml b/uniffi/dart/fixtures/simple-fns/Cargo.toml deleted file mode 100644 index 0d9c6f1a7..000000000 --- a/uniffi/dart/fixtures/simple-fns/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "simple_fns" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -name = "simple_fns" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } -camino = "1" - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/simple-fns/build.rs b/uniffi/dart/fixtures/simple-fns/build.rs deleted file mode 100644 index 797041d85..000000000 --- a/uniffi/dart/fixtures/simple-fns/build.rs +++ /dev/null @@ -1,5 +0,0 @@ -use camino::Utf8Path; - -fn main() { - uniffi_dart::generate_scaffolding(Utf8Path::new("src/api.udl")).unwrap(); -} diff --git a/uniffi/dart/fixtures/simple-fns/clippy.toml b/uniffi/dart/fixtures/simple-fns/clippy.toml deleted file mode 100644 index 9cc29f294..000000000 --- a/uniffi/dart/fixtures/simple-fns/clippy.toml +++ /dev/null @@ -1,2 +0,0 @@ -# MyHashSet hashes by identity, so its Mutex never changes its hash. -ignore-interior-mutability = ["simple_fns::MyHashSet"] diff --git a/uniffi/dart/fixtures/simple-fns/src/api.udl b/uniffi/dart/fixtures/simple-fns/src/api.udl deleted file mode 100644 index 457b8fd5f..000000000 --- a/uniffi/dart/fixtures/simple-fns/src/api.udl +++ /dev/null @@ -1,18 +0,0 @@ -namespace simple_fns { - string get_string(); - i32 get_int(); - string string_identity(string s); - record hash_map_identity(record h); - record object_map_identity(record m); - u32 byte_to_u32(u8 byte); - MyHashSet new_set(); - void add_to_set(MyHashSet set, string value); - boolean set_contains(MyHashSet set, string value); - void dummy(i8? arg); -}; - -interface MyHashSet { - constructor(); - void add(string value); - boolean contains(string value); -}; diff --git a/uniffi/dart/fixtures/simple-fns/src/lib.rs b/uniffi/dart/fixtures/simple-fns/src/lib.rs deleted file mode 100644 index 7c7185b21..000000000 --- a/uniffi/dart/fixtures/simple-fns/src/lib.rs +++ /dev/null @@ -1,85 +0,0 @@ -use std::collections::{HashMap, HashSet}; -use std::hash::{Hash, Hasher}; -use std::sync::{Arc, Mutex}; - -// Free-standing functions -fn get_string() -> String { - "String created by Rust".to_owned() -} - -fn get_int() -> i32 { - 1289 -} - -fn string_identity(s: String) -> String { - s -} - -fn hash_map_identity(h: HashMap) -> HashMap { - h -} - -fn object_map_identity(m: HashMap, u32>) -> HashMap, u32> { - m -} - -fn byte_to_u32(byte: u8) -> u32 { - byte.into() -} - -fn new_set() -> Arc { - Arc::new(MyHashSet::new()) -} - -fn add_to_set(set: Arc, value: String) { - set.add(value); -} - -fn set_contains(set: Arc, value: String) -> bool { - set.contains(value) -} - -// This used to generate broken bindings because the type inside `Option` (and -// other generic builtin types) wasn't being added as a known type. -fn dummy(_arg: Option) {} - -// MyHashSet implementation -pub struct MyHashSet { - inner: Mutex>, -} - -impl Default for MyHashSet { - fn default() -> Self { - Self::new() - } -} - -impl MyHashSet { - pub fn new() -> Self { - Self { inner: Mutex::new(HashSet::new()) } - } - - pub fn add(&self, value: String) { - self.inner.lock().unwrap().insert(value); - } - - pub fn contains(&self, value: String) -> bool { - self.inner.lock().unwrap().contains(&value) - } -} - -impl PartialEq for MyHashSet { - fn eq(&self, other: &Self) -> bool { - std::ptr::eq(self, other) - } -} - -impl Eq for MyHashSet {} - -impl Hash for MyHashSet { - fn hash(&self, state: &mut H) { - (self as *const Self as usize).hash(state); - } -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/simple-fns/test/simple_fns_test.dart b/uniffi/dart/fixtures/simple-fns/test/simple_fns_test.dart deleted file mode 100644 index 980c9d248..000000000 --- a/uniffi/dart/fixtures/simple-fns/test/simple_fns_test.dart +++ /dev/null @@ -1,156 +0,0 @@ -import 'package:test/test.dart'; -import '../simple_fns.dart'; - -void main() { - group('Simple Functions Tests', () { - test('get_string returns correct string', () { - expect(getString(), 'String created by Rust'); - }); - - test('get_int returns correct integer', () { - expect(getInt(), 1289); - }); - - test('string_identity returns same string', () { - expect( - stringIdentity(s: 'String created by Dart'), - 'String created by Dart', - ); - }); - - test('byte_to_u32 converts correctly', () { - expect(byteToU32(byte: 255), 255); - expect(byteToU32(byte: 0), 0); - expect(byteToU32(byte: 128), 128); - }); - - test('hash_map_identity returns same map', () { - final testMap = {'a': 'b', 'hello': 'world'}; - expect(hashMapIdentity(h: testMap), testMap); - }); - - test('empty map identity', () { - final emptyMap = {}; - expect(hashMapIdentity(h: emptyMap), emptyMap); - }); - - group('MyHashSet Tests', () { - test('new_set creates empty set', () { - final set = newSet(); - expect(setContains(set_: set, value: 'foo'), false); - expect(setContains(set_: set, value: 'bar'), false); - }); - - test('add_to_set and set_contains work together', () { - final set = newSet(); - - // Add items to set - addToSet(set_: set, value: 'foo'); - addToSet(set_: set, value: 'bar'); - - // Check that items are in set - expect(setContains(set_: set, value: 'foo'), true); - expect(setContains(set_: set, value: 'bar'), true); - - // Check that non-existent item is not in set - expect(setContains(set_: set, value: 'baz'), false); - }); - - test('set handles duplicate additions', () { - final set = newSet(); - - // Add same item multiple times - addToSet(set_: set, value: 'duplicate'); - addToSet(set_: set, value: 'duplicate'); - addToSet(set_: set, value: 'duplicate'); - - // Should still only contain it once - expect(setContains(set_: set, value: 'duplicate'), true); - }); - - test('set with multiple items', () { - final set = newSet(); - - // Add multiple different items - final items = ['apple', 'banana', 'cherry', 'date']; - for (final item in items) { - addToSet(set_: set, value: item); - } - - // Check all items are present - for (final item in items) { - expect(setContains(set_: set, value: item), true); - } - - // Check non-existent items are not present - expect(setContains(set_: set, value: 'elderberry'), false); - expect(setContains(set_: set, value: 'fig'), false); - }); - }); - - group('MyHashSet object methods', () { - test('direct object creation and methods', () { - final set = MyHashSet(); - - // Test direct add method - set.add(value: 'direct'); - expect(set.contains(value: 'direct'), true); - expect(set.contains(value: 'not-there'), false); - - // Test multiple additions - set.add(value: 'first'); - set.add(value: 'second'); - expect(set.contains(value: 'first'), true); - expect(set.contains(value: 'second'), true); - }); - - test('object handles duplicates', () { - final set = MyHashSet(); - - set.add(value: 'same'); - set.add(value: 'same'); - set.add(value: 'same'); - - expect(set.contains(value: 'same'), true); - }); - }); - - test('dummy function with optional parameter', () { - // Test with null - dummy(arg: null); - - // Test with value - dummy(arg: 42); - dummy(arg: -128); - dummy(arg: 127); - - // These should not throw exceptions - expect(() => dummy(arg: null), returnsNormally); - expect(() => dummy(arg: 0), returnsNormally); - }); - - group('Edge cases', () { - test('empty string handling', () { - expect(stringIdentity(s: ''), ''); - }); - - test('byte boundary values', () { - expect(byteToU32(byte: 0), 0); - expect(byteToU32(byte: 255), 255); - }); - - test('special characters in strings', () { - expect(stringIdentity(s: 'Hello 世界! 🌍'), 'Hello 世界! 🌍'); - }); - - test('set with special characters', () { - final set = newSet(); - addToSet(set_: set, value: 'Hello 世界!'); - addToSet(set_: set, value: '🌍🌎🌏'); - - expect(setContains(set_: set, value: 'Hello 世界!'), true); - expect(setContains(set_: set, value: '🌍🌎🌏'), true); - }); - }); - }); -} diff --git a/uniffi/dart/fixtures/simple-fns/tests/mod.rs b/uniffi/dart/fixtures/simple-fns/tests/mod.rs deleted file mode 100644 index c32e768fb..000000000 --- a/uniffi/dart/fixtures/simple-fns/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn simple_fns() -> Result<()> { - uniffi_dart::testing::run_test("simple_fns", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/simple-iface/Cargo.toml b/uniffi/dart/fixtures/simple-iface/Cargo.toml deleted file mode 100644 index bb5c12915..000000000 --- a/uniffi/dart/fixtures/simple-iface/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "simple_iface" -version = "0.1.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "simple_iface" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/simple-iface/build.rs b/uniffi/dart/fixtures/simple-iface/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/simple-iface/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/simple-iface/src/api.udl b/uniffi/dart/fixtures/simple-iface/src/api.udl deleted file mode 100644 index bb33a115f..000000000 --- a/uniffi/dart/fixtures/simple-iface/src/api.udl +++ /dev/null @@ -1,17 +0,0 @@ -namespace simple_iface { - Object make_object(i32 inner); - ProtocolError get_protocol_error(string message); -}; - -interface Object { - i32 get_inner(); - Object? some_method(); -}; - -interface PayloadError { - string message(); -}; - -interface ProtocolError { - PayloadError? payload_error(); -}; diff --git a/uniffi/dart/fixtures/simple-iface/src/lib.rs b/uniffi/dart/fixtures/simple-iface/src/lib.rs deleted file mode 100644 index 531ae03a5..000000000 --- a/uniffi/dart/fixtures/simple-iface/src/lib.rs +++ /dev/null @@ -1,60 +0,0 @@ -use std::sync::Arc; - -#[derive(Debug)] -pub struct Object { - inner: i32, -} - -#[derive(Debug)] -pub struct PayloadError { - message: String, -} - -#[derive(Debug)] -pub struct ProtocolError { - payload_error: Arc, -} - -impl Object { - pub fn new(inner: i32) -> Self { - Self { inner } - } - - pub fn get_inner(&self) -> i32 { - self.inner - } - - pub fn some_method(self: Arc) -> Option> { - None - } -} - -impl PayloadError { - pub fn new(message: String) -> Self { - Self { message } - } - - pub fn message(&self) -> String { - self.message.clone() - } -} - -impl ProtocolError { - pub fn new(message: String) -> Self { - Self { payload_error: Arc::new(PayloadError::new(message)) } - } - - pub fn payload_error(self: Arc) -> Option> { - Some(self.payload_error.clone()) - } -} - -pub fn make_object(inner: i32) -> Arc { - Arc::new(Object::new(inner)) -} - -pub fn get_protocol_error(message: String) -> Arc { - Arc::new(ProtocolError::new(message)) -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/simple-iface/test/simple_iface_test.dart b/uniffi/dart/fixtures/simple-iface/test/simple_iface_test.dart deleted file mode 100644 index 7bc2678b8..000000000 --- a/uniffi/dart/fixtures/simple-iface/test/simple_iface_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -import 'package:test/test.dart'; -import '../simple_iface.dart'; - -void main() { - group('SimpleIface', () { - test('basic object creation and method calls', () { - final obj = makeObject(inner: 9000); - expect(obj.getInner(), equals(9000)); - - final result = obj.someMethod(); - expect(result, isNull); - }); - - test('object with different values', () { - final obj1 = makeObject(inner: 42); - expect(obj1.getInner(), equals(42)); - - final obj2 = makeObject(inner: -100); - expect(obj2.getInner(), equals(-100)); - }); - - test('error-named objects compile and work', () { - final protocol = getProtocolError(message: 'nested payload'); - final payload = protocol.payloadError(); - - expect(payload, isNotNull); - expect(payload!.message(), equals('nested payload')); - expect(payload, isA()); - expect(protocol, isA()); - }); - }); -} diff --git a/uniffi/dart/fixtures/simple-iface/tests/mod.rs b/uniffi/dart/fixtures/simple-iface/tests/mod.rs deleted file mode 100644 index eb5ba7774..000000000 --- a/uniffi/dart/fixtures/simple-iface/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn simple_iface() -> Result<()> { - uniffi_dart::testing::run_test("simple_iface", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/streams_ext/Cargo.toml b/uniffi/dart/fixtures/streams_ext/Cargo.toml deleted file mode 100644 index 4ea96319d..000000000 --- a/uniffi/dart/fixtures/streams_ext/Cargo.toml +++ /dev/null @@ -1,34 +0,0 @@ -[package] -name = "streams_ext" -version = "0.1.0" -edition = "2021" -publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - - -[lib] -name = "streams_ext" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -uniffi-dart = { path = "../../" } -uniffi_dart_macro = { path = "../../uniffi_dart_macro" } -lazy_static = "1.4.0" -futures = "0.3" -async-stream = "0.3" -smol = "1.3" -thiserror = "1.0.66" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/streams_ext/build.rs b/uniffi/dart/fixtures/streams_ext/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/streams_ext/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/streams_ext/src/api.udl b/uniffi/dart/fixtures/streams_ext/src/api.udl deleted file mode 100644 index 6f26011a0..000000000 --- a/uniffi/dart/fixtures/streams_ext/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace streams_ext { }; diff --git a/uniffi/dart/fixtures/streams_ext/src/lib.rs b/uniffi/dart/fixtures/streams_ext/src/lib.rs deleted file mode 100644 index b5b615717..000000000 --- a/uniffi/dart/fixtures/streams_ext/src/lib.rs +++ /dev/null @@ -1,343 +0,0 @@ -use std::pin::Pin; -use std::time::Duration; - -use async_stream::stream; -use futures::stream::{self, Stream, StreamExt}; -use smol::Timer; - -// // Define custom error enums -// #[derive(Debug, thiserror::Error)] -// pub enum StreamErrorInt { -// #[error("An integer error occurred: {0}")] -// IntegerError(String), -// } - -// #[derive(Debug, thiserror::Error)] -// pub enum StreamErrorString { -// #[error("A string error occurred: {0}")] -// StringError(String), -// } - -#[uniffi_dart::export_stream(i32)] -pub fn simple_stream() -> impl Stream { - stream::iter(0..5) -} - -#[uniffi_dart::export_stream(i32)] -pub fn count_stream() -> Pin + Send>> { - Box::pin(stream::iter(0..5)) -} - -#[uniffi_dart::export_stream(u64)] -pub fn fibonacci_stream() -> Pin + Send>> { - Box::pin(stream! { - let mut a = 0; - let mut b = 1; - loop { - yield a; - let next = a + b; - a = b; - b = next; - } - }) -} - -#[uniffi_dart::export_stream(u64)] -pub fn async_timer_stream() -> Pin + Send>> { - Box::pin(stream! { - let mut count = 0; - loop { - Timer::after(Duration::from_secs(1)).await; - count += 1; - yield count; - } - }) -} - -#[uniffi_dart::export_stream(String)] -pub fn combined_streams() -> impl Stream + Send { - let stream1 = count_stream().take(5).map(|n| format!("Count: {}", n)); - let stream3 = fibonacci_stream().take(5).map(|n| format!("Fibonacci: {}", n)); - - stream::select(stream1, stream3) -} - -// pub fn error_stream() -> impl Stream > +Send { -// { -// let(mut __yield_tx,__yield_rx) = unsafe { -// async_stream::__private::yielder::pair() -// }; -// async_stream::__private::AsyncStream::new(__yield_rx,async move { -// __yield_tx.send(Ok(1)).await; -// __yield_tx.send(Ok(2)).await; -// __yield_tx.send(Err(StreamErrorInt::IntegerError("An error occurred".to_string()))).await; -// __yield_tx.send(Ok(4)).await; -// }) -// } -// } -// #[derive(uniffi::Object)] -// pub struct ErrorStreamStreamExt { -// stream:tokio::sync::Mutex > +Send>> > , -// } -// impl ErrorStreamStreamExt { -// pub fn new() -> std::sync::Arc{ -// std::sync::Arc::new(Self { -// stream:tokio::sync::Mutex::new(Box::pin(error_stream())), -// }) -// } -// pub async fn next(&self) -> Option >{ -// let mut stream = self.stream.lock().await; -// stream.as_mut().next().await -// } - -// } - -// #[uniffi_dart::export_stream(Result)] -// pub fn error_stream() -> impl Stream> + Send { -// stream! { -// yield Ok(1); -// yield Ok(2); -// yield Err("An error occurred".to_string()); -// yield Ok(4); -// } -// } - -// #[uniffi_dart::export_stream(Result)] -// pub fn combined_error_streams() -> impl Stream> + Send { -// let stream1 = count_stream() -// .take(3) -// .map(|n| Ok(format!("Count: {}", n))); -// let stream3 = fibonacci_stream() -// .take(3) -// .map(|n| { -// if n == 2 { -// Err("Fibonacci error".to_string()) -// } else { -// Ok(format!("Fibonacci: {}", n)) -// } -// }); - -// stream::select(stream1, stream3) -// } - -#[cfg(test)] -mod tests { - use futures::stream::StreamExt; - use smol::block_on; - - use super::*; - - #[test] - fn test_simple_stream() { - block_on(async { - let result: Vec = simple_stream().collect().await; - assert_eq!(result, vec![0, 1, 2, 3, 4]); - }); - } - - #[test] - fn test_count_stream() { - block_on(async { - let result: Vec = count_stream().collect().await; - assert_eq!(result, vec![0, 1, 2, 3, 4]); - }); - } - - // #[tokio::test] - // async fn test_alphabet_stream() { - // let result: String = alphabet_stream().collect().await; - // assert_eq!(result, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - // } - - #[test] - fn test_fibonacci_stream() { - block_on(async { - let result: Vec = fibonacci_stream().take(10).collect().await; - assert_eq!(result, vec![0, 1, 1, 2, 3, 5, 8, 13, 21, 34]); - }); - } - - #[test] - fn test_async_timer_stream() { - block_on(async { - let mut stream = async_timer_stream(); - let mut values = Vec::new(); - for _ in 0..3 { - if let Some(value) = stream.next().await { - values.push(value); - } - } - assert_eq!(values, vec![1, 2, 3]); - }); - } - - #[test] - fn test_combined_streams() { - block_on(async { - let result: Vec = combined_streams().take(10).collect().await; - - // Check if we have the correct number of items - assert_eq!(result.len(), 10); - - // Check if we have items from all three streams - assert!(result.iter().any(|s| s.starts_with("Count:"))); - assert!(result.iter().any(|s| s.starts_with("Fibonacci:"))); - - // Check specific items - assert!(result.contains(&"Count: 0".to_string())); - assert!(result.contains(&"Fibonacci: 3".to_string())); - }); - } - - #[test] - fn test_poll_next() { - let instance = create_stream_count_stream(); - - block_on(async { - let mut results = Vec::new(); - for _ in 0..5 { - if let Some(value) = instance.next().await { - results.push(value); - } - } - - assert_eq!(results, vec![0, 1, 2, 3, 4]); - }); - } - - #[test] - fn test_multiple_streams() { - block_on(async { - let instance1 = create_stream_count_stream(); - let instance2 = create_stream_count_stream(); - - let result1 = instance1.next().await; - let result2 = instance2.next().await; - - // Both instances should return the first item (0) - assert_eq!(result1, Some(0)); - assert_eq!(result2, Some(0)); - - // The next call should return the second item (1) for both instances - let result3 = instance1.next().await; - let result4 = instance2.next().await; - - assert_eq!(result3, Some(1)); - assert_eq!(result4, Some(1)); - }); - } - - #[test] - fn test_stream_exhaustion() { - block_on(async { - let instance = create_stream_count_stream(); - - // Consume all items - for _ in 0..5 { - print!("{:?}", instance.next().await); - } - - // The next call should return None - assert_eq!(instance.next().await, None); - }); - } - - // #[tokio::test] - // async fn test_error_stream() { - // let mut stream = error_stream(); - // let mut results = Vec::new(); - - // while let Some(item) = stream.next().await { - // match item { - // Ok(value) => results.push(value), - // Err(e) => { - // results.push(-1); // Using -1 to indicate an error occurred - // println!("Stream error: {}", e); - // } - // } - // } - - // assert_eq!(results, vec![1, 2, -1, 4]); - // } - - // #[tokio::test] - // async fn test_combined_error_streams() { - // let mut stream = combined_error_streams(); - // let mut results = Vec::new(); - - // while let Some(item) = stream.next().await { - // match item { - // Ok(value) => results.push(value), - // Err(e) => { - // results.push("Error".to_string()); - // println!("Combined stream error: {}", e); - // } - // } - // } - - // assert_eq!( - // results, - // vec![ - // "Count: 0".to_string(), - // "Count: 1".to_string(), - // "Count: 2".to_string(), - // "Fibonacci: 0".to_string(), - // "Fibonacci: 1".to_string(), - // "Error".to_string(), - // ] - // ); - // } - - // #[tokio::test] - // async fn test_error_stream_with_timeout() { - // let mut stream = error_stream(); - // let result = timeout(Duration::from_secs(1), async { - // let mut collected = Vec::new(); - // while let Some(item) = stream.next().await { - // collected.push(item); - // } - // collected - // }) - // .await; - - // match result { - // Ok(items) => { - // assert_eq!( - // items, - // vec![ - // Ok(1), - // Ok(2), - // Err(StreamErrorInt::IntegerError("An error occurred".to_string())), - // Ok(4) - // ] - // ); - // } - // Err(_) => panic!("Timeout occurred while collecting error stream"), - // } - // } - - // #[tokio::test] - // async fn test_combined_error_streams_handling() { - // let mut stream = combined_error_streams(); - // let mut counts = 0; - // let mut fibs = 0; - // let mut errors = 0; - - // while let Some(item) = stream.next().await { - // let item: Result = item; // Explicit type annotation - - // match item { - // Ok(ref s) if s.starts_with("Count:") => counts += 1, - // Ok(ref s) if s.starts_with("Fibonacci:") => fibs += 1, - // Err(_) => errors += 1, - // _ => {} - // } - // } - - // assert_eq!(counts, 3); - // assert_eq!(fibs, 2); // One Fibonacci stream yields an error - // assert_eq!(errors, 1); - // } -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/streams_ext/test/strems_ext_test.dart b/uniffi/dart/fixtures/streams_ext/test/strems_ext_test.dart deleted file mode 100644 index e257d24b5..000000000 --- a/uniffi/dart/fixtures/streams_ext/test/strems_ext_test.dart +++ /dev/null @@ -1,82 +0,0 @@ -import 'package:test/test.dart'; -import '../streams_ext.dart'; - -void main() { - test('Simple Stream emits expected sequence', () { - expect( - simpleStream(), - emitsInOrder([0, 1, 2, 3, 4, emitsDone]), - ); - }); - - test('Count Stream emits expected sequence', () { - expect( - countStream(), - emitsInOrder([0, 1, 2, 3, 4, emitsDone]), - ); - }); - - // test('Alphabet Stream emits all uppercase letters', () { - // expect( - // alphabetStream(), - // emitsInOrder([ - // ...('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')), - // emitsDone, - // ]), - // ); - // }); - - test('Fibonacci Stream emits first 10 Fibonacci numbers', () { - expect( - fibonacciStream().take(10), - emitsInOrder([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, emitsDone]), - ); - }); - - test('Async Timer Stream emits incrementing numbers', () { - expect( - asyncTimerStream().take(5), - emitsInOrder([1, 2, 3, 4, 5, emitsDone]), - ); - }, timeout: Timeout(Duration(seconds: 6))); - - test('Combined Streams emits from all source streams, verify count', - () async { - var count = 0; - await for (final event in combinedStreams().take(15)) { - print(event); - count++; - } - print('Stream done'); - expect(count, 10); - }); - - test('Combined Streams emits from all source streams, specifically', () { - expect( - combinedStreams(), - emitsInAnyOrder([ - 'Count: 0', - 'Fibonacci: 0', - 'Count: 1', - 'Fibonacci: 1', - 'Count: 2', - 'Fibonacci: 1', - 'Count: 3', - 'Fibonacci: 2', - 'Count: 4', - 'Fibonacci: 3', - emitsDone, - ]), - ); - }); - - test('Combined Streams emits from all source streams', () { - expect( - combinedStreams(), - emitsInAnyOrder([ - predicate((String s) => s.startsWith('Count:')), - predicate((String s) => s.startsWith('Fibonacci:')), - ]), - ); - }); -} diff --git a/uniffi/dart/fixtures/streams_ext/tests/mod.rs b/uniffi/dart/fixtures/streams_ext/tests/mod.rs deleted file mode 100644 index 4659eedff..000000000 --- a/uniffi/dart/fixtures/streams_ext/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn streams_ext() -> Result<()> { - uniffi_dart::testing::run_test("streams_ext", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/struct-default-values/Cargo.toml b/uniffi/dart/fixtures/struct-default-values/Cargo.toml deleted file mode 100644 index 1ea5a3066..000000000 --- a/uniffi/dart/fixtures/struct-default-values/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "struct_default_values" -version = "0.1.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "struct_default_values" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/struct-default-values/build.rs b/uniffi/dart/fixtures/struct-default-values/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/struct-default-values/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/struct-default-values/src/api.udl b/uniffi/dart/fixtures/struct-default-values/src/api.udl deleted file mode 100644 index 5472b0da1..000000000 --- a/uniffi/dart/fixtures/struct-default-values/src/api.udl +++ /dev/null @@ -1,17 +0,0 @@ -namespace struct_default_values { -}; - -dictionary Bookmark { - string? guid = null; - i32 position; - i32? last_modified = null; - string url; - string? title = null; -}; - -dictionary Contact { - string name; - string? email; - i32 age; - string? nickname; -}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/struct-default-values/src/lib.rs b/uniffi/dart/fixtures/struct-default-values/src/lib.rs deleted file mode 100644 index 3b641f53b..000000000 --- a/uniffi/dart/fixtures/struct-default-values/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -pub struct Bookmark { - pub guid: Option, - pub position: i32, - pub last_modified: Option, - pub url: String, - pub title: Option, -} - -pub struct Contact { - pub name: String, - pub email: Option, - pub age: i32, - pub nickname: Option, -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/struct-default-values/test/struct_default_values_test.dart b/uniffi/dart/fixtures/struct-default-values/test/struct_default_values_test.dart deleted file mode 100644 index 4fcf0c78f..000000000 --- a/uniffi/dart/fixtures/struct-default-values/test/struct_default_values_test.dart +++ /dev/null @@ -1,84 +0,0 @@ -import 'package:test/test.dart'; -import '../struct_default_values.dart'; - -void main() { - group('StructDefaultValues', () { - test('bookmark only nondefault set', () { - const url = "https://mozilla.github.io/uniffi-rs"; - final bookmark = Bookmark(position: 2, url: url); - - expect(bookmark.guid, isNull); - expect(bookmark.position, equals(2)); - expect(bookmark.url, equals(url)); - expect(bookmark.lastModified, isNull); - expect(bookmark.title, isNull); - }); - - test('bookmark others set', () { - const url = "https://mozilla.github.io/uniffi-rs"; - final bookmark = Bookmark( - position: 3, - url: url, - guid: "c0ffee", - title: "Test Title", - ); - - expect(bookmark.guid, equals("c0ffee")); - expect(bookmark.position, equals(3)); - expect(bookmark.url, equals(url)); - expect(bookmark.lastModified, isNull); - expect(bookmark.title, equals("Test Title")); - }); - - test('bookmark all fields set', () { - const url = "https://mozilla.github.io/uniffi-rs"; - final bookmark = Bookmark( - position: 1, - url: url, - guid: "deadbeef", - lastModified: 1234567890, - title: "Full Bookmark", - ); - - expect(bookmark.guid, equals("deadbeef")); - expect(bookmark.position, equals(1)); - expect(bookmark.url, equals(url)); - expect(bookmark.lastModified, equals(1234567890)); - expect(bookmark.title, equals("Full Bookmark")); - }); - }); - - group('Contact (optional fields without defaults)', () { - test('only required fields', () { - final contact = Contact(name: "Alice", age: 30); - - expect(contact.name, equals("Alice")); - expect(contact.age, equals(30)); - expect(contact.email, isNull); - expect(contact.nickname, isNull); - }); - - test('one optional field set', () { - final contact = Contact(name: "Bob", age: 25, email: "bob@example.com"); - - expect(contact.name, equals("Bob")); - expect(contact.age, equals(25)); - expect(contact.email, equals("bob@example.com")); - expect(contact.nickname, isNull); - }); - - test('all fields set', () { - final contact = Contact( - name: "Carol", - age: 40, - email: "carol@example.com", - nickname: "CC", - ); - - expect(contact.name, equals("Carol")); - expect(contact.age, equals(40)); - expect(contact.email, equals("carol@example.com")); - expect(contact.nickname, equals("CC")); - }); - }); -} diff --git a/uniffi/dart/fixtures/struct-default-values/tests/mod.rs b/uniffi/dart/fixtures/struct-default-values/tests/mod.rs deleted file mode 100644 index 923b7909d..000000000 --- a/uniffi/dart/fixtures/struct-default-values/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn struct_default_values() -> Result<()> { - uniffi_dart::testing::run_test("struct_default_values", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/trait-interfaces/Cargo.toml b/uniffi/dart/fixtures/trait-interfaces/Cargo.toml deleted file mode 100644 index d737cf2de..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "trait_interfaces" -version = "0.1.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "trait_interfaces" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -once_cell = "1.12" -thiserror = "1.0" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/trait-interfaces/build.rs b/uniffi/dart/fixtures/trait-interfaces/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/trait-interfaces/src/api.udl b/uniffi/dart/fixtures/trait-interfaces/src/api.udl deleted file mode 100644 index e2150f14f..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/src/api.udl +++ /dev/null @@ -1 +0,0 @@ -namespace trait_interfaces {}; diff --git a/uniffi/dart/fixtures/trait-interfaces/src/lib.rs b/uniffi/dart/fixtures/trait-interfaces/src/lib.rs deleted file mode 100644 index 65cb3f0ea..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/src/lib.rs +++ /dev/null @@ -1,135 +0,0 @@ -use std::fmt; -use std::sync::Arc; - -#[uniffi::export] -pub trait Greeter: Send + Sync { - fn greet(&self, name: String) -> String; -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash, uniffi::Object)] -#[uniffi::export(Debug, Display, Eq, Hash)] -pub struct FriendlyGreeter { - phrase: String, -} - -#[uniffi::export] -impl FriendlyGreeter { - #[uniffi::constructor] - pub fn new(phrase: String) -> Arc { - Arc::new(Self { phrase }) - } - - pub fn to_trait(self: Arc) -> Arc { - self as Arc - } - - pub fn greet(&self, name: String) -> String { - ::greet(self, name) - } -} - -impl Greeter for FriendlyGreeter { - fn greet(&self, name: String) -> String { - format!("{} {name}", self.phrase) - } -} - -impl fmt::Display for FriendlyGreeter { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "FriendlyGreeter({})", self.phrase) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash, uniffi::Object)] -#[uniffi::export(Debug, Display, Eq, Hash)] -pub struct ProcFriendlyGreeter { - phrase: String, -} - -#[uniffi::export] -impl ProcFriendlyGreeter { - #[uniffi::constructor] - pub fn new(phrase: String) -> Arc { - Arc::new(Self { phrase }) - } - - pub fn to_trait(self: Arc) -> Arc { - self as Arc - } - - pub fn greet(&self, name: String) -> String { - ::greet(self, name) - } -} - -impl Greeter for ProcFriendlyGreeter { - fn greet(&self, name: String) -> String { - format!("{} {}", self.phrase.to_uppercase(), name.to_uppercase()) - } -} - -impl fmt::Display for ProcFriendlyGreeter { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "ProcFriendlyGreeter({})", self.phrase) - } -} - -#[derive(Default, uniffi::Object)] -pub struct Registry; - -#[uniffi::export] -impl Registry { - #[uniffi::constructor] - pub fn new() -> Arc { - Arc::new(Self) - } - - pub fn make_friendly(&self, phrase: String) -> Arc { - FriendlyGreeter::new(phrase).to_trait() - } - - pub fn make_proc(&self, phrase: String) -> Arc { - ProcFriendlyGreeter::new(phrase).to_trait() - } -} - -// Keep lifecycle counts separate from the other fixture objects/finalizers. -static DISPOSAL_DROPS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - -#[derive(uniffi::Object)] -pub struct DisposalProbe; - -#[uniffi::export] -impl DisposalProbe { - #[uniffi::constructor] - pub fn new() -> Arc { - Arc::new(Self) - } - - pub fn greet(&self, name: String) -> String { - format!("Hello {name}") - } - - pub fn as_greeter(self: Arc) -> Arc { - self - } -} - -impl Greeter for DisposalProbe { - fn greet(&self, name: String) -> String { - self.greet(name) - } -} - -impl Drop for DisposalProbe { - fn drop(&mut self) { - DISPOSAL_DROPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } -} - -#[uniffi::export] -pub fn disposal_drop_count() -> u32 { - DISPOSAL_DROPS.load(std::sync::atomic::Ordering::SeqCst) -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/trait-interfaces/test/disposal_allocation_cases.dart b/uniffi/dart/fixtures/trait-interfaces/test/disposal_allocation_cases.dart deleted file mode 100644 index 00ca39c6e..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/test/disposal_allocation_cases.dart +++ /dev/null @@ -1,37 +0,0 @@ -import 'package:test/test.dart'; - -import '../trait_interfaces.dart'; -import 'tracking_allocator.dart' as tracker; - -void main() { - tearDown(tracker.calloc.reset); - - test('object disposal stays retryable when status allocation fails', () { - final before = disposalDropCount(); - final probe = DisposalProbe(); - tracker.calloc.failAfter = 0; - expect(() => probe.dispose(), throwsStateError); - tracker.calloc.failAfter = null; - probe.dispose(); - expect(disposalDropCount(), before + 1); - probe.dispose(); - expect(disposalDropCount(), before + 1); - expect(tracker.calloc.live, isEmpty); - }); - - test('trait disposal stays retryable when status allocation fails', () { - final before = disposalDropCount(); - final probe = DisposalProbe(); - final greeter = probe.asGreeter(); - tracker.calloc.failAfter = 0; - expect(() => greeter.dispose(), throwsStateError); - tracker.calloc.failAfter = null; - greeter.dispose(); - greeter.dispose(); - // The probe still holds its own reference. - expect(disposalDropCount(), before); - probe.dispose(); - expect(disposalDropCount(), before + 1); - expect(tracker.calloc.live, isEmpty); - }); -} diff --git a/uniffi/dart/fixtures/trait-interfaces/test/disposal_allocation_test.dart b/uniffi/dart/fixtures/trait-interfaces/test/disposal_allocation_test.dart deleted file mode 100644 index 28e65101b..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/test/disposal_allocation_test.dart +++ /dev/null @@ -1,64 +0,0 @@ -import 'dart:io'; - -import 'package:test/test.dart'; - -void main() { - test('disposal survives injected status allocation failure', () async { - // Run a child suite in an isolated copy of this package with an - // instrumented allocator. The child's build hooks replace the native - // library, so it must not share this run's package directory. - final work = Directory.systemTemp.createTempSync('disposal_allocation'); - try { - await _copyPackage(Directory.current, work); - final pubGet = await Process.run(Platform.resolvedExecutable, [ - 'pub', - 'get', - '--offline', - ], workingDirectory: work.path); - print(pubGet.stdout); - print(pubGet.stderr); - expect(pubGet.exitCode, 0); - for (final name in ['trait_interfaces.dart', 'uniffi_runtime.dart']) { - final file = File('${work.path}/$name'); - final source = file.readAsStringSync(); - final import = RegExp(r'''import ["']package:ffi/ffi.dart["'];'''); - expect(import.allMatches(source), hasLength(1)); - file.writeAsStringSync( - source.replaceFirst( - import, - 'import "package:ffi/ffi.dart" hide calloc;\n' - 'import "test/tracking_allocator.dart";', - ), - ); - } - final result = await Process.run(Platform.resolvedExecutable, [ - 'test', - 'test/disposal_allocation_cases.dart', - '--reporter', - 'expanded', - ], workingDirectory: work.path); - print(result.stdout); - print(result.stderr); - expect(result.exitCode, 0); - } finally { - work.deleteSync(recursive: true); - } - }, timeout: Timeout(Duration(minutes: 3))); -} - -Future _copyPackage(Directory from, Directory to) async { - to.createSync(recursive: true); - for (final entity in from.listSync()) { - final name = entity.uri.pathSegments - .where((segment) => segment.isNotEmpty) - .last; - if (name == '.dart_tool') { - continue; - } - if (entity is Directory) { - await _copyPackage(entity, Directory('${to.path}/$name')); - } else { - File(entity.path).copySync('${to.path}/$name'); - } - } -} diff --git a/uniffi/dart/fixtures/trait-interfaces/test/tracking_allocator.dart b/uniffi/dart/fixtures/trait-interfaces/test/tracking_allocator.dart deleted file mode 100644 index e661da86b..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/test/tracking_allocator.dart +++ /dev/null @@ -1,34 +0,0 @@ -import 'dart:ffi'; - -import 'package:ffi/ffi.dart' as ffi; - -class TrackingAllocator implements Allocator { - final live = {}; - int? failAfter; - - @override - Pointer allocate(int byteCount, {int? alignment}) { - if (failAfter == 0) throw StateError('injected allocation failure'); - if (failAfter != null) failAfter = failAfter! - 1; - final pointer = ffi.calloc.allocate(byteCount, alignment: alignment); - live[pointer.address] = byteCount; - return pointer; - } - - @override - void free(Pointer pointer) { - if (live.remove(pointer.address) == null) { - throw StateError('free of untracked pointer'); - } - ffi.calloc.free(pointer); - } - - void reset() { - failAfter = null; - for (final address in live.keys.toList()) { - free(Pointer.fromAddress(address)); - } - } -} - -final calloc = TrackingAllocator(); diff --git a/uniffi/dart/fixtures/trait-interfaces/test/trait_interfaces_test.dart b/uniffi/dart/fixtures/trait-interfaces/test/trait_interfaces_test.dart deleted file mode 100644 index fdecd040e..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/test/trait_interfaces_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -import 'package:test/test.dart'; -import '../trait_interfaces.dart'; - -void main() { - group('FriendlyGreeter', () { - test('toTrait produces a Greeter handle', () { - final friendly = FriendlyGreeter(phrase: 'Hello'); - final Greeter greeter = friendly.toTrait(); - expect(greeter.greet(name: 'World'), equals('Hello World')); - greeter.dispose(); - }); - - test('equality and hashing honour Rust traits', () { - final a = FriendlyGreeter(phrase: 'Hi'); - final b = FriendlyGreeter(phrase: 'Hi'); - final c = FriendlyGreeter(phrase: 'Hey'); - - expect(a, equals(b)); - expect(a.hashCode, equals(b.hashCode)); - expect(a, isNot(equals(c))); - - final map = {a: 'value'}; - expect(map.containsKey(b), isTrue); - }); - }); - - group('Registry', () { - test('returns Greeter trait objects', () { - final registry = Registry(); - - final Greeter friendly = registry.makeFriendly(phrase: 'Hi'); - final Greeter proc = registry.makeProc(phrase: 'hola'); - - expect(friendly.greet(name: 'there'), equals('Hi there')); - expect(proc.greet(name: 'mundo'), equals('HOLA MUNDO')); - - friendly.dispose(); - proc.dispose(); - }); - }); -} diff --git a/uniffi/dart/fixtures/trait-interfaces/tests/mod.rs b/uniffi/dart/fixtures/trait-interfaces/tests/mod.rs deleted file mode 100644 index a3e67828e..000000000 --- a/uniffi/dart/fixtures/trait-interfaces/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn trait_interfaces() -> Result<()> { - uniffi_dart::testing::run_test("trait_interfaces", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/trait-methods/Cargo.toml b/uniffi/dart/fixtures/trait-methods/Cargo.toml deleted file mode 100644 index 9b5c48a05..000000000 --- a/uniffi/dart/fixtures/trait-methods/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "trait_methods" -version = "0.1.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "trait_methods" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } -once_cell = "1.12" -thiserror = "1.0" - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = ["bindgen-tests"] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/trait-methods/build.rs b/uniffi/dart/fixtures/trait-methods/build.rs deleted file mode 100644 index 17e394981..000000000 --- a/uniffi/dart/fixtures/trait-methods/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - uniffi_dart::generate_scaffolding("./src/api.udl".into()).unwrap(); -} diff --git a/uniffi/dart/fixtures/trait-methods/src/api.udl b/uniffi/dart/fixtures/trait-methods/src/api.udl deleted file mode 100644 index 60a81bbe6..000000000 --- a/uniffi/dart/fixtures/trait-methods/src/api.udl +++ /dev/null @@ -1,6 +0,0 @@ -namespace trait_methods {}; - -[Traits=(Display, Debug, Eq, Hash)] -interface TraitMethods { - constructor(string name); -}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/trait-methods/src/lib.rs b/uniffi/dart/fixtures/trait-methods/src/lib.rs deleted file mode 100644 index 9e42817d0..000000000 --- a/uniffi/dart/fixtures/trait-methods/src/lib.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::sync::Arc; - -#[derive(Debug, PartialEq, Eq, Hash)] -pub struct TraitMethods { - val: String, -} - -impl TraitMethods { - pub fn new(val: String) -> Self { - Self { val } - } -} - -impl std::fmt::Display for TraitMethods { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "TraitMethods({})", self.val) - } -} - -#[derive(Debug, PartialEq, Eq, Hash, uniffi::Object)] -#[uniffi::export(Debug, Display, Eq, Hash)] -pub struct ProcTraitMethods { - val: String, -} - -#[uniffi::export] -impl ProcTraitMethods { - #[uniffi::constructor] - fn new(val: String) -> Arc { - Arc::new(Self { val }) - } -} - -impl std::fmt::Display for ProcTraitMethods { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "ProcTraitMethods({})", self.val) - } -} - -#[derive(Debug, thiserror::Error, uniffi::Error)] -#[uniffi::export(Display)] -pub enum DisplayError { - #[error("closed")] - Closed, - #[error("transport: {0}")] - Transport(String), -} - -#[uniffi::export] -fn throw_display(message: Option) -> Result<(), DisplayError> { - match message { - Some(message) => Err(DisplayError::Transport(message)), - None => Err(DisplayError::Closed), - } -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/trait-methods/test/trait_methods_test.dart b/uniffi/dart/fixtures/trait-methods/test/trait_methods_test.dart deleted file mode 100644 index df81edb4e..000000000 --- a/uniffi/dart/fixtures/trait-methods/test/trait_methods_test.dart +++ /dev/null @@ -1,71 +0,0 @@ -import 'package:test/test.dart'; -import '../trait_methods.dart'; - -void main() { - group('TraitMethods', () { - test('display trait (toString)', () { - // This test will fail until trait method support is implemented - // Expected: TraitMethods toString() should return "TraitMethods(yo)" - - final m = TraitMethods(name: "yo"); - expect(m.toString(), equals("TraitMethods(yo)")); - }); - - test('debug trait (representation)', () { - // This test will fail until trait method support is implemented - // Expected: TraitMethods debug representation should return 'TraitMethods { val: "yo" }' - - final m = TraitMethods(name: "yo"); - expect(m.debugString(), equals('TraitMethods { val: "yo" }')); - }); - - test('eq trait (equality)', () { - // This test will fail until trait method support is implemented - // Expected: TraitMethods objects should be equal if they have the same value - - final m1 = TraitMethods(name: "yo"); - final m2 = TraitMethods(name: "yo"); - final m3 = TraitMethods(name: "yoyo"); - - expect(m1, equals(m2)); - expect(m1, isNot(equals(m3))); - }); - - test('hash trait (hashability)', () { - // This test will fail until trait method support is implemented - // Expected: TraitMethods objects should be hashable and usable as map keys - - final map = {}; - final m = TraitMethods(name: "m"); - map[m] = "m"; - expect(map.containsKey(m), isTrue); - }); - }); - - group('ProcTraitMethods', () { - test('proc-macro trait methods', () { - // This test will fail until proc-macro support is implemented - // Expected: ProcTraitMethods should behave like TraitMethods but using proc-macros - - final m = ProcTraitMethods(val: "yo"); - expect(m.toString(), equals("ProcTraitMethods(yo)")); - expect(m.debugString(), equals('ProcTraitMethods { val: "yo" }')); - }); - }); - - group('DisplayError', () { - test('toString renders the exported Display', () { - expect( - () => throwDisplay(message: null), - throwsA(isA() - .having((e) => e.toString(), 'toString', 'closed')), - ); - expect( - () => throwDisplay(message: 'reset'), - throwsA(isA() - .having((e) => e.toString(), 'toString', 'transport: reset')), - ); - expect(ClosedDisplayException().toString(), equals('closed')); - }); - }); -} diff --git a/uniffi/dart/fixtures/trait-methods/tests/mod.rs b/uniffi/dart/fixtures/trait-methods/tests/mod.rs deleted file mode 100644 index aaaebea44..000000000 --- a/uniffi/dart/fixtures/trait-methods/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn trait_methods() -> Result<()> { - uniffi_dart::testing::run_test("trait_methods", "src/api.udl", None) -} diff --git a/uniffi/dart/fixtures/type-limits/Cargo.toml b/uniffi/dart/fixtures/type-limits/Cargo.toml deleted file mode 100644 index 2332f0a0d..000000000 --- a/uniffi/dart/fixtures/type-limits/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "type_limits" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -name = "type_limits" -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi-dart = { path = "../../", features = ["build"] } -camino = "1" - -[dev-dependencies] -uniffi-dart = { path = "../../", features = ["bindgen-tests"] } -uniffi = { workspace = true, features = [ - "bindgen-tests", -] } -anyhow = "1" - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/dart/fixtures/type-limits/build.rs b/uniffi/dart/fixtures/type-limits/build.rs deleted file mode 100644 index 797041d85..000000000 --- a/uniffi/dart/fixtures/type-limits/build.rs +++ /dev/null @@ -1,5 +0,0 @@ -use camino::Utf8Path; - -fn main() { - uniffi_dart::generate_scaffolding(Utf8Path::new("src/api.udl")).unwrap(); -} diff --git a/uniffi/dart/fixtures/type-limits/src/api.udl b/uniffi/dart/fixtures/type-limits/src/api.udl deleted file mode 100644 index 1c5f0690a..000000000 --- a/uniffi/dart/fixtures/type-limits/src/api.udl +++ /dev/null @@ -1,17 +0,0 @@ -namespace type_limits { - i8 take_i8(i8 v); - i16 take_i16(i16 v); - i32 take_i32(i32 v); - i64 take_i64(i64 v); - - u8 take_u8(u8 v); - u16 take_u16(u16 v); - u32 take_u32(u32 v); - u64 take_u64(u64 v); - - f32 take_f32(f32 v); - f64 take_f64(f64 v); - - string take_string(string v); - bytes take_bytes(bytes v); -}; \ No newline at end of file diff --git a/uniffi/dart/fixtures/type-limits/src/lib.rs b/uniffi/dart/fixtures/type-limits/src/lib.rs deleted file mode 100644 index b000f2e68..000000000 --- a/uniffi/dart/fixtures/type-limits/src/lib.rs +++ /dev/null @@ -1,52 +0,0 @@ -use std::str; - -fn take_i8(v: i8) -> i8 { - v -} - -fn take_i16(v: i16) -> i16 { - v -} - -fn take_i32(v: i32) -> i32 { - v -} - -fn take_i64(v: i64) -> i64 { - v -} - -fn take_u8(v: u8) -> u8 { - v -} - -fn take_u16(v: u16) -> u16 { - v -} - -fn take_u32(v: u32) -> u32 { - v -} - -fn take_u64(v: u64) -> u64 { - v -} - -fn take_f32(v: f32) -> f32 { - v -} - -fn take_f64(v: f64) -> f64 { - v -} - -fn take_string(v: String) -> String { - assert!(str::from_utf8(v.as_bytes()).is_ok()); - v -} - -fn take_bytes(v: Vec) -> Vec { - v -} - -uniffi::include_scaffolding!("api"); diff --git a/uniffi/dart/fixtures/type-limits/test/type_limits_test.dart b/uniffi/dart/fixtures/type-limits/test/type_limits_test.dart deleted file mode 100644 index 2bfe97610..000000000 --- a/uniffi/dart/fixtures/type-limits/test/type_limits_test.dart +++ /dev/null @@ -1,268 +0,0 @@ -import 'dart:typed_data'; -import 'package:test/test.dart'; -import '../type_limits.dart'; - -void main() { - group('Type Limits Tests', () { - group('Signed Integer Lower Bounds', () { - test('i8 bounds', () { - // Test valid lower bound - expect(takeI8(v: -128), -128); // -2^7 - - // Test invalid lower bound - expect(() => takeI8(v: -129), throwsArgumentError); - }); - - test('i16 bounds', () { - // Test valid lower bound - expect(takeI16(v: -32768), -32768); // -2^15 - - // Test invalid lower bound - expect(() => takeI16(v: -32769), throwsArgumentError); - }); - - test('i32 bounds', () { - // Test valid lower bound - expect(takeI32(v: -2147483648), -2147483648); // -2^31 - - // Test invalid lower bound (will be caught by Dart before reaching Rust) - expect(() => takeI32(v: -2147483649), throwsArgumentError); - }); - - test('i64 bounds', () { - // Test valid lower bound - final minI64 = - -9223372036854775808; // -2^63 (this is within Dart's range) - expect(takeI64(v: minI64), minI64); - - // Test values that would overflow are caught by Dart - // We can't easily test overflow in Dart as it handles large integers differently - }); - }); - - group('Signed Integer Upper Bounds', () { - test('i8 bounds', () { - // Test valid upper bound - expect(takeI8(v: 127), 127); // 2^7 - 1 - - // Test invalid upper bound - expect(() => takeI8(v: 128), throwsArgumentError); - }); - - test('i16 bounds', () { - // Test valid upper bound - expect(takeI16(v: 32767), 32767); // 2^15 - 1 - - // Test invalid upper bound - expect(() => takeI16(v: 32768), throwsArgumentError); - }); - - test('i32 bounds', () { - // Test valid upper bound - expect(takeI32(v: 2147483647), 2147483647); // 2^31 - 1 - - // Test invalid upper bound - expect(() => takeI32(v: 2147483648), throwsArgumentError); - }); - - test('i64 bounds', () { - // Test valid upper bound - final maxI64 = - 9223372036854775807; // 2^63 - 1 (this is within Dart's range) - expect(takeI64(v: maxI64), maxI64); - - // Test values that would overflow are caught by Dart - // We can't easily test overflow in Dart as it handles large integers differently - }); - }); - - group('Unsigned Integer Lower Bounds', () { - test('u8 bounds', () { - // Test valid lower bound - expect(takeU8(v: 0), 0); - - // Test invalid lower bound - expect(() => takeU8(v: -1), throwsArgumentError); - }); - - test('u16 bounds', () { - // Test valid lower bound - expect(takeU16(v: 0), 0); - - // Test invalid lower bound - expect(() => takeU16(v: -1), throwsArgumentError); - }); - - test('u32 bounds', () { - // Test valid lower bound - expect(takeU32(v: 0), 0); - - // Test invalid lower bound - expect(() => takeU32(v: -1), throwsArgumentError); - }); - - test('u64 bounds', () { - // Test valid lower bound - expect(takeU64(v: 0), 0); - - // Test invalid lower bound - expect(() => takeU64(v: -1), throwsArgumentError); - }); - }); - - group('Unsigned Integer Upper Bounds', () { - test('u8 bounds', () { - // Test valid upper bound - expect(takeU8(v: 255), 255); // 2^8 - 1 - - // Test invalid upper bound - expect(() => takeU8(v: 256), throwsArgumentError); - }); - - test('u16 bounds', () { - // Test valid upper bound - expect(takeU16(v: 65535), 65535); // 2^16 - 1 - - // Test invalid upper bound - expect(() => takeU16(v: 65536), throwsArgumentError); - }); - - test('u32 bounds', () { - // Test valid upper bound - expect(takeU32(v: 4294967295), 4294967295); // 2^32 - 1 - - // Test invalid upper bound - expect(() => takeU32(v: 4294967296), throwsArgumentError); - }); - - test('u64 bounds', () { - // Test valid upper bound within 53-bit safe integer range - const maxSafeU64 = 9007199254740991; // 2^53 - 1 - expect(takeU64(v: maxSafeU64), maxSafeU64); - - // Test values that would overflow are caught by Dart - // We can't easily test overflow in Dart as it handles large integers differently - }); - }); - - group('Float Tests', () { - test('f32 normal values', () { - expect(takeF32(v: 0.0), 0.0); - expect(takeF32(v: 1.0), 1.0); - expect(takeF32(v: -1.0), -1.0); - expect(takeF32(v: 123.456), closeTo(123.456, 0.001)); - }); - - test('f64 normal values', () { - expect(takeF64(v: 0.0), 0.0); - expect(takeF64(v: 1.0), 1.0); - expect(takeF64(v: -1.0), -1.0); - expect(takeF64(v: 123.456789), closeTo(123.456789, 0.000001)); - }); - - test('f32 special values', () { - expect(takeF32(v: double.infinity), double.infinity); - expect(takeF32(v: double.negativeInfinity), double.negativeInfinity); - expect(takeF32(v: double.nan).isNaN, true); - }); - - test('f64 special values', () { - expect(takeF64(v: double.infinity), double.infinity); - expect(takeF64(v: double.negativeInfinity), double.negativeInfinity); - expect(takeF64(v: double.nan).isNaN, true); - }); - }); - - group('String Tests', () { - test('valid strings', () { - expect(takeString(v: ''), ''); - expect(takeString(v: 'hello'), 'hello'); - expect(takeString(v: '愛'), '愛'); - expect(takeString(v: '💖'), '💖'); - }); - - test('unicode strings', () { - expect(takeString(v: 'Hello, 世界!'), 'Hello, 世界!'); - expect(takeString(v: '🌍🌎🌏'), '🌍🌎🌏'); - }); - }); - - group('Bytes Tests', () { - test('valid bytes', () { - expect(takeBytes(v: Uint8List.fromList([])), Uint8List.fromList([])); - expect( - takeBytes(v: Uint8List.fromList([1, 2, 3])), - Uint8List.fromList([1, 2, 3]), - ); - expect( - takeBytes(v: Uint8List.fromList([0, 255])), - Uint8List.fromList([0, 255]), - ); - }); - - test('utf8 encoded bytes', () { - final utf8Bytes = Uint8List.fromList('愛'.codeUnits); - expect(takeBytes(v: utf8Bytes), utf8Bytes); - - final emojiBytes = Uint8List.fromList('💖'.codeUnits); - expect(takeBytes(v: emojiBytes), emojiBytes); - }); - - test('binary data', () { - final binaryData = Uint8List.fromList([ - 0x00, - 0x01, - 0x02, - 0xFF, - 0xFE, - 0xFD, - ]); - expect(takeBytes(v: binaryData), binaryData); - }); - }); - - group('Large Number Tests', () { - test('large valid numbers', () { - expect(takeI8(v: 100), 100); - expect(takeI16(v: 10000), 10000); - expect(takeI32(v: 1000000000), 1000000000); - expect(takeI64(v: 1000000000000000000), 1000000000000000000); - - expect(takeU8(v: 100), 100); - expect(takeU16(v: 10000), 10000); - expect(takeU32(v: 1000000000), 1000000000); - expect(takeU64(v: 1000000000000000000), 1000000000000000000); - }); - - test('large invalid numbers', () { - expect(() => takeI8(v: 1000), throwsArgumentError); - expect(() => takeI16(v: 100000), throwsArgumentError); - expect(() => takeI32(v: 10000000000), throwsArgumentError); - - expect(() => takeU8(v: 1000), throwsArgumentError); - expect(() => takeU16(v: 100000), throwsArgumentError); - expect(() => takeU32(v: 10000000000), throwsArgumentError); - }); - }); - - group('Zero and Boundary Values', () { - test('zero values', () { - expect(takeI8(v: 0), 0); - expect(takeI16(v: 0), 0); - expect(takeI32(v: 0), 0); - expect(takeI64(v: 0), 0); - expect(takeU8(v: 0), 0); - expect(takeU16(v: 0), 0); - expect(takeU32(v: 0), 0); - expect(takeU64(v: 0), 0); - expect(takeF32(v: 0.0), 0.0); - expect(takeF64(v: 0.0), 0.0); - }); - - test('negative zero for floats', () { - expect(takeF32(v: -0.0), -0.0); - expect(takeF64(v: -0.0), -0.0); - }); - }); - }); -} diff --git a/uniffi/dart/fixtures/type-limits/tests/mod.rs b/uniffi/dart/fixtures/type-limits/tests/mod.rs deleted file mode 100644 index 1246d6cfe..000000000 --- a/uniffi/dart/fixtures/type-limits/tests/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -use anyhow::Result; - -#[test] -fn type_limits() -> Result<()> { - uniffi_dart::testing::run_test("type_limits", "src/api.udl", None) -} diff --git a/uniffi/dart/rustfmt.toml b/uniffi/dart/rustfmt.toml deleted file mode 100644 index f0c9e157c..000000000 --- a/uniffi/dart/rustfmt.toml +++ /dev/null @@ -1,23 +0,0 @@ -## Based on https://github.com/payjoin/rust-payjoin/blob/master/rustfmt.toml -## -## Keep this to stable rustfmt options because this repository's lint matrix runs -## `cargo fmt --all -- --check` on MSRV, stable, and nightly Rust. - -hard_tabs = false -tab_spaces = 4 -newline_style = "Auto" - -max_width = 100 -use_small_heuristics = "Max" - -reorder_imports = true -reorder_modules = true -remove_nested_parens = true -fn_params_layout = "Tall" -match_block_trailing_comma = false -edition = "2021" -merge_derives = true -use_try_shorthand = false -use_field_init_shorthand = false -force_explicit_abi = true -disable_all_formatting = false diff --git a/uniffi/dart/src/bin.rs b/uniffi/dart/src/bin.rs deleted file mode 100644 index 30e67186d..000000000 --- a/uniffi/dart/src/bin.rs +++ /dev/null @@ -1,148 +0,0 @@ -use std::process::exit; - -use camino::Utf8PathBuf; - -use uniffi_dart::gen::generate_dart_bindings; - -const USAGE: &str = "\ -uniffi_bindgen_dart — generate Dart bindings from a compiled UniFFI library - -USAGE: - uniffi_bindgen_dart [OPTIONS] - -ARGS: - Path to the compiled cdylib/dylib (.so/.dylib/.dll) whose - embedded UniFFI metadata is read (library mode). This is how - `setup_scaffolding!()` (proc-macro, no UDL) crates are consumed. - -OPTIONS: - --library Treat as a compiled library. Accepted for parity - with `uniffi-bindgen`; library mode is the only mode this - tool supports, so the flag is optional. - --out-dir Directory the generated `.dart` binding is written into. - --config Optional `uniffi.toml` whose values are merged into each - crate's config (its values take precedence). - --crate Generate bindings for only this crate, when the library - bundles more than one UniFFI component. - --no-format Skip running `dart format` on the generated output. - --version Print the version and exit. - -h, --help Print this help. - -Runs `cargo metadata` in the current directory to resolve each crate's -`uniffi.toml`/UDL, so it must be run inside the Cargo workspace. -"; - -fn main() { - let mut source: Option = None; - let mut out_dir: Option = None; - let mut config: Option = None; - let mut crate_name: Option = None; - let mut try_format = true; - - let mut args = std::env::args().skip(1); - while let Some(raw) = args.next() { - // Accept both `--opt value` and `--opt=value`, matching the clap-based - // uniffi-bindgen / -cs / -go. Only split a leading `--flag=…`; a positional - // path that happens to contain `=` is left intact. - let (arg, inline): (String, Option) = match raw.split_once('=') { - Some((flag, value)) if flag.starts_with("--") => { - (flag.to_string(), Some(value.to_string())) - } - _ => (raw, None), - }; - // Take an option's value: the attached `=value` if present, otherwise the - // next argument — rejected if missing or itself an option (so - // `--out-dir --config x` errors instead of silently using `--config`). - let mut take = |name: &str| { - if let Some(value) = &inline { - return value.clone(); - } - match args.next() { - Some(v) if !v.starts_with("--") => v, - _ => { - eprintln!("error: `{name}` requires a value\n\n{USAGE}"); - exit(2); - } - } - }; - // A boolean flag rejects an attached `=value` rather than ignoring it. - let reject_inline = |name: &str| { - if inline.is_some() { - eprintln!("error: `{name}` takes no value\n\n{USAGE}"); - exit(2); - } - }; - // Reject a repeated path option rather than silently keeping the last value. - let set_once = |slot: &mut Option, name: &str, value: String| { - if slot.is_some() { - eprintln!("error: `{name}` given more than once\n\n{USAGE}"); - exit(2); - } - *slot = Some(Utf8PathBuf::from(value)); - }; - match arg.as_str() { - "--library" => reject_inline("--library"), // implied; accepted for compatibility - "--out-dir" => { - let v = take("--out-dir"); - set_once(&mut out_dir, "--out-dir", v); - } - "--config" => { - let v = take("--config"); - set_once(&mut config, "--config", v); - } - "--crate" => { - if crate_name.is_some() { - eprintln!("error: `--crate` given more than once\n\n{USAGE}"); - exit(2); - } - crate_name = Some(take("--crate")); - } - "--no-format" => { - reject_inline("--no-format"); - try_format = false; - } - "--version" => { - reject_inline("--version"); - println!("uniffi_bindgen_dart {}", env!("CARGO_PKG_VERSION")); - return; - } - "-h" | "--help" => { - print!("{USAGE}"); - return; - } - other if other.starts_with('-') => { - eprintln!("error: unknown option `{other}`\n\n{USAGE}"); - exit(2); - } - _ => { - if source.is_some() { - eprintln!("error: more than one source path given\n\n{USAGE}"); - exit(2); - } - source = Some(Utf8PathBuf::from(arg)); - } - } - } - - let (Some(source), Some(out_dir)) = (source, out_dir) else { - eprintln!("error: a source library path and --out-dir are required\n\n{USAGE}"); - exit(2); - }; - - if let Err(e) = generate_dart_bindings( - // In library mode the UDL is resolved per-crate from cargo metadata, so the - // `udl_file` argument is unused — pass the library path as a harmless stand-in. - source.as_path(), - config.as_deref(), - Some(out_dir.as_path()), - source.as_path(), - true, - crate_name, - try_format, - ) { - eprintln!("error: failed to generate Dart bindings: {e:?}"); - exit(1); - } - - eprintln!("Generated Dart bindings from {source} into {out_dir}"); -} diff --git a/uniffi/dart/src/build.rs b/uniffi/dart/src/build.rs deleted file mode 100644 index 7ab3c7b3f..000000000 --- a/uniffi/dart/src/build.rs +++ /dev/null @@ -1,19 +0,0 @@ -use std::env; - -use anyhow::{Context, Result}; -use camino::Utf8Path; - -pub fn generate_scaffolding(udl_file: &Utf8Path) -> Result<()> { - uniffi_build::generate_scaffolding(udl_file)?; - let out_dir = env::var("OUT_DIR").context("$OUT_DIR missing?!")?; - uniffi_bindgen::generate_external_bindings( - &crate::gen::DartBindingGenerator {}, - udl_file, - None::<&Utf8Path>, - Some(out_dir), - None::<&Utf8Path>, - None, - true, - )?; - Ok(()) -} diff --git a/uniffi/dart/src/gen/callback_interface.rs b/uniffi/dart/src/gen/callback_interface.rs deleted file mode 100644 index 0341b7499..000000000 --- a/uniffi/dart/src/gen/callback_interface.rs +++ /dev/null @@ -1,661 +0,0 @@ -use genco::prelude::*; -use heck::ToUpperCamelCase; -use uniffi_bindgen::interface::ffi::{FfiStruct, FfiType}; -use uniffi_bindgen::interface::{AsType, Method, Type}; -use uniffi_bindgen::ComponentInterface; - -use crate::gen::oracle::{AsCodeType, DartCodeOracle}; -use crate::gen::render::{AsRenderable, Renderable, TypeHelperRenderer}; -use crate::gen::CodeType; - -#[derive(Debug)] -pub struct CallbackInterfaceCodeType { - name: String, - self_type: Type, - namespace: Option, -} - -impl CallbackInterfaceCodeType { - pub fn new(name: String, self_type: Type, namespace: Option) -> Self { - Self { name, self_type, namespace } - } -} - -impl CodeType for CallbackInterfaceCodeType { - fn type_label(&self) -> String { - DartCodeOracle::qualify(self.namespace.as_deref(), DartCodeOracle::class_name(&self.name)) - } - - fn canonical_name(&self) -> String { - DartCodeOracle::qualify_canonical( - self.namespace.as_deref(), - format!("CallbackInterface{}", DartCodeOracle::class_name(&self.name)), - ) - } - - fn ffi_converter_name(&self) -> String { - DartCodeOracle::qualify( - self.namespace.as_deref(), - format!("FfiConverterCallbackInterface{}", DartCodeOracle::class_name(&self.name)), - ) - } - - fn initialization_fn(&self) -> Option { - Some(format!("_uniffiInitializeCallbackInterface{}", self.name)) - } -} - -impl Renderable for CallbackInterfaceCodeType { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - type_helper.include_once_check(&self.canonical_name(), &self.self_type); - // Another crate's library declares its own helpers. - if self.namespace.is_some() { - return quote!(); - } - let callback = type_helper.get_ci().get_callback_interface_definition(&self.name).unwrap(); - - // Generate all necessary components for the callback interface - let interface = generate_callback_interface( - callback.name(), - &callback.as_codetype(type_helper.get_ci()).ffi_converter_name(), - &callback.methods(), - type_helper, - None, - ); - let vtable_interface = - generate_callback_vtable_interface(callback.name(), &callback.methods()); - let functions = - generate_callback_functions(callback.name(), &callback.methods(), type_helper); - let namespace = type_helper - .get_ci() - .namespace_for_type(&callback.as_type()) - .unwrap_or_else(|_| type_helper.get_ci().namespace()) - .to_string(); - let ffi_module = DartCodeOracle::infer_ffi_module(type_helper.get_ci(), move || namespace); - let vtable_init = generate_callback_interface_vtable_init_function( - callback.name(), - &callback.methods(), - &ffi_module, - ); - - quote! { - $interface - $vtable_interface - $functions - $vtable_init - } - } -} - -pub fn generate_callback_interface( - callback_name: &str, - ffi_converter_name: &str, - methods: &[&Method], - type_helper: &dyn TypeHelperRenderer, - rust_impl_name: Option<&str>, -) -> dart::Tokens { - let cls_name = &DartCodeOracle::class_name(callback_name); - let ffi_conv_name = &DartCodeOracle::class_name(ffi_converter_name); - let init_fn_name = &format!("init{callback_name}VTable"); - let lift_rust_impl = - rust_impl_name.map(|name| quote!(return $name._internal(handle);)).unwrap_or_else(|| { - quote!( - throw UniffiInternalError( - UniffiInternalError.unexpectedStaleHandle, - "Rust-owned callback interface handle is not supported for $cls_name", - ); - ) - }); - let lower_rust_impl = rust_impl_name - .map(|name| { - quote!( - if (value is $name) { - return value.uniffiClonePointer(); - } - ) - }) - .unwrap_or_else(|| quote!()); - - let mut async_struct_defs: Vec = Vec::new(); - let mut async_completion_typedefs: Vec = Vec::new(); - - for method in methods { - if method.is_async() { - let struct_def = method.foreign_future_ffi_result_struct(); - let struct_name = struct_def.name().to_string(); - - if !type_helper.include_once_by_name(&struct_name) { - async_struct_defs.push(generate_foreign_future_struct_definition(&struct_def)); - } - - let completion_name = foreign_future_completion_name(method); - if !type_helper.include_once_by_name(&completion_name) { - async_completion_typedefs.push(generate_foreign_future_completion_typedef( - &completion_name, - &struct_name, - )); - } - } - } - - let async_support = if !async_struct_defs.is_empty() || !async_completion_typedefs.is_empty() { - quote! { - $(for typedef in &async_completion_typedefs => $typedef) - $(for struct_def in &async_struct_defs => $struct_def) - } - } else { - quote!() - }; - - let tokens = quote! { - // This is the abstract class to be implemented - abstract class $cls_name { - $(for m in methods { - $(generate_callback_methods_definitions(m, type_helper)) - }) - } - - // This is the type helper to convert from FFI to Dart - class $ffi_conv_name { - static final _handleMap = UniffiHandleMap<$cls_name>(); - static bool _vtableInitialized = false; - - static $cls_name lift(Pointer handle) { - final rawHandle = handle.address; - if ((rawHandle & 0x1) == 0) { - $lift_rust_impl - } - return _handleMap.remove(rawHandle); - } - - static Pointer lower($cls_name value) { - $lower_rust_impl - _ensureVTableInitialized(); - final handle = _handleMap.insert(value); - return Pointer.fromAddress(handle); - } - - static void _ensureVTableInitialized() { - if (!_vtableInitialized) { - $init_fn_name(); - _vtableInitialized = true; - } - } - - static LiftRetVal<$cls_name> read(Uint8List buf) { - final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); - final pointer = Pointer.fromAddress(handle); - return LiftRetVal(lift(pointer), 8); - } - - static int write($cls_name value, Uint8List buf) { - final handle = lower(value); - buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); - return 8; - } - - static int allocationSize($cls_name value) { - return 8; // Just a handle (int64). - } - } - - // Additional support definitions for async callbacks - $async_support - - // We must define callback signatures - $(generate_callback_methods_signatures(cls_name, methods, type_helper.get_ci())) - }; - - tokens -} - -fn generate_callback_methods_definitions( - method: &Method, - type_helper: &dyn TypeHelperRenderer, -) -> dart::Tokens { - let method_name = DartCodeOracle::fn_name(method.name()); - let dart_args = &method - .arguments() - .iter() - .map(|arg| { - let arg_type = - arg.as_renderable(type_helper.get_ci()).render_type(&arg.as_type(), type_helper); - let arg_name = DartCodeOracle::var_name(arg.name()); - - quote!($arg_type $arg_name) - }) - .collect::>(); - - let ret_type = if method.is_async() { - if let Some(ret) = method.return_type() { - let rendered = ret.as_renderable(type_helper.get_ci()).render_type(ret, type_helper); - quote!(Future<$rendered>) - } else { - quote!(Future) - } - } else if let Some(ret) = method.return_type() { - ret.as_renderable(type_helper.get_ci()).render_type(ret, type_helper) - } else { - quote!(void) - }; - - quote!( - $ret_type $method_name($(for a in dart_args => $a,)); - ) -} - -fn generate_callback_methods_signatures( - callback_name: &str, - methods: &[&Method], - ci: &ComponentInterface, -) -> dart::Tokens { - let mut tokens = dart::Tokens::new(); - for (method_index, method) in methods.iter().enumerate() { - //let method_name = DartCodeOracle::fn_name(method.name()); - - let ffi_method_type = format!("UniffiCallbackInterface{callback_name}Method{method_index}"); - let dart_method_type = - format!("UniffiCallbackInterface{callback_name}Method{method_index}Dart"); - - let arg_native_types: Vec = method - .arguments() - .iter() - .map(|arg| DartCodeOracle::native_type_label(Some(&arg.as_type()), ci)) - .collect(); - - let arg_dart_types: Vec = method - .arguments() - .iter() - .map(|arg| DartCodeOracle::native_dart_type_label(Some(&arg.as_type()), ci)) - .collect(); - - if method.is_async() { - let completion_base = foreign_future_completion_name(method); - let completion_native = format!("Uniffi{}", completion_base.to_upper_camel_case()); - let completion_pointer = format!("Pointer>", completion_native); - - tokens.append(quote! { - typedef $ffi_method_type = Void Function( - Uint64, $(for arg in &arg_native_types => $arg,) - $(&completion_pointer), Uint64, Pointer); - typedef $dart_method_type = void Function( - int, $(for arg in &arg_dart_types => $arg,) - $(&completion_pointer), int, Pointer); - }); - } else { - let method_return_type = if let Some(ret) = method.return_type() { - DartCodeOracle::native_type_label(Some(ret), ci) - } else { - quote!(Void) - }; - - tokens.append(quote! { - typedef $ffi_method_type = Void Function( - Uint64, $(for arg in &arg_native_types => $arg,) - Pointer<$(&method_return_type)>, Pointer); - typedef $dart_method_type = void Function( - int, $(for arg in &arg_dart_types => $arg,) - Pointer<$(&method_return_type)>, Pointer); - }); - } - } - - tokens.append(quote! { - typedef UniffiCallbackInterface$(callback_name)Free = Void Function(Uint64); - typedef UniffiCallbackInterface$(callback_name)FreeDart = void Function(int); - typedef UniffiCallbackInterface$(callback_name)Clone = Uint64 Function(Uint64); - typedef UniffiCallbackInterface$(callback_name)CloneDart = int Function(int); - }); - - tokens -} - -pub fn generate_callback_vtable_interface( - callback_name: &str, - methods: &[&Method], -) -> dart::Tokens { - let vtable_name = format!("UniffiVTableCallbackInterface{callback_name}"); - let methods_vec: Vec<_> = methods.iter().enumerate().collect(); - - quote! { - final class $vtable_name extends Struct { - external Pointer> uniffiFree; - external Pointer> uniffiClone; - $(for (index, m) in &methods_vec => - external Pointer> $(DartCodeOracle::fn_name(m.name())); - ) - } - } -} - -pub fn generate_callback_functions( - callback_name: &str, - methods: &[&Method], - type_helper: &dyn TypeHelperRenderer, -) -> dart::Tokens { - let cls_name = &DartCodeOracle::class_name(callback_name); - - let functions: Vec = methods.iter().enumerate().map(|(index, m)| { - let method_name = &DartCodeOracle::fn_name(m.name()).to_string(); - let ffi_method_type = &format!("UniffiCallbackInterface{callback_name}Method{index}"); - let _dart_method_type = &format!("UniffiCallbackInterface{callback_name}Method{index}Dart"); - - // Get parameter types using the oracle - let param_types: Vec = m - .arguments() - .iter() - .map(|arg| { - let arg_name = DartCodeOracle::var_name(arg.name()); - DartCodeOracle::callback_param_type(&arg.as_type(), &arg_name, type_helper.get_ci()) - }) - .collect(); - - // Get argument lifts using the oracle - let arg_lifts: Vec = m - .arguments() - .iter() - .enumerate() - .map(|(arg_idx, arg)| { - let arg_name = DartCodeOracle::var_name(arg.name()); - DartCodeOracle::callback_arg_lift_indexed(&arg.as_type(), &arg_name, arg_idx, type_helper.get_ci()) - }) - .collect(); - - // Prepare arg names for the method call using indexes - let arg_names: Vec = m - .arguments() - .iter() - .enumerate() - .map(|(arg_idx, arg)| DartCodeOracle::callback_arg_name(&arg.as_type(), arg_idx)) - .collect(); - - // Generate the function body - let callback_method_name = - &format!("{}{}", DartCodeOracle::fn_name(callback_name), DartCodeOracle::class_name(m.name())); - - if m.is_async() { - let completion_base = foreign_future_completion_name(m); - let completion_native = format!("Uniffi{}", completion_base.to_upper_camel_case()); - let completion_pointer = format!("Pointer>", completion_native); - let completion_dart = format!("{completion_native}Dart"); - let result_struct = m.foreign_future_ffi_result_struct(); - let struct_tokens = DartCodeOracle::ffi_struct_name(result_struct.name()); - let struct_tokens_alt = struct_tokens.clone(); - - if let Some(ret) = m.return_type() { - type_helper.include_once_check(&ret.as_codetype(type_helper.get_ci()).canonical_name(), ret); - } - - let success_return = if let Some(ret) = m.return_type() { - let converter = ret.as_codetype(type_helper.get_ci()).ffi_converter_name(); - quote!(resultStructPtr.ref.returnValue = $(&converter).lower(result);) - } else { - quote!() - }; - - let async_error_handling = callback_error_handling( - m.throws_type(), - type_helper, - quote!(resultStructPtr.ref.callStatus), - ); - - quote! { - void $callback_method_name( - int uniffiHandle, - $(for param in ¶m_types => $param,) - $(&completion_pointer) uniffiFutureCallback, - int uniffiCallbackData, - Pointer outReturn, - ) { - final obj = FfiConverterCallbackInterface$cls_name._handleMap.get(uniffiHandle); - $(arg_lifts) - final callback = uniffiFutureCallback.asFunction<$(&completion_dart)>(); - final state = UniffiForeignFutureState(); - final handle = uniffiForeignFutureHandleMap.insert(state); - outReturn.ref.handle = handle; - outReturn.ref.free = uniffiForeignFutureFreePointer; - - () async { - try { - final result = await obj.$method_name($(for arg in &arg_names => $arg,)); - final removedState = uniffiForeignFutureHandleMap.maybeRemove(handle); - final effectiveState = removedState ?? state; - if (effectiveState.cancelled) { - return; - } - effectiveState.cancelled = true; - final resultStructPtr = calloc<$struct_tokens>(); - try { - $success_return - resultStructPtr.ref.callStatus.code = CALL_SUCCESS; - callback(uniffiCallbackData, resultStructPtr.ref); - } finally { - calloc.free(resultStructPtr); - } - } catch (e) { - final removedState = uniffiForeignFutureHandleMap.maybeRemove(handle); - final effectiveState = removedState ?? state; - if (effectiveState.cancelled) { - return; - } - effectiveState.cancelled = true; - final resultStructPtr = calloc<$struct_tokens_alt>(); - try { - $async_error_handling - callback(uniffiCallbackData, resultStructPtr.ref); - } finally { - calloc.free(resultStructPtr); - } - } - }(); - } - - final Pointer> $(callback_method_name)Pointer = - Pointer.fromFunction<$ffi_method_type>($callback_method_name); - } - } else { - // Handle return value using the oracle - let call_dart_method = if let Some(ret) = m.return_type() { - DartCodeOracle::callback_return_handling(ret, method_name, arg_names, type_helper.get_ci()) - } else { - // Handle void return types - DartCodeOracle::callback_void_handling(method_name, arg_names) - }; - - // Get the appropriate out return type - let out_return_type = DartCodeOracle::callback_out_return_type(m.return_type()); - let sync_error_handling = - callback_error_handling(m.throws_type(), type_helper, quote!(status)); - - quote! { - void $callback_method_name(int uniffiHandle, $(for param in ¶m_types => $param,) $out_return_type outReturn, Pointer callStatus) { - final status = callStatus.ref; - try { - final obj = FfiConverterCallbackInterface$cls_name._handleMap.get(uniffiHandle); - $(arg_lifts) - $call_dart_method - } catch (e) { - $sync_error_handling - } - } - - final Pointer> $(callback_method_name)Pointer = - Pointer.fromFunction<$ffi_method_type>($callback_method_name); - } - } - }).collect(); - - // Free callback - let free_callback_fn = &format!("{}FreeCallback", DartCodeOracle::fn_name(callback_name)); - let free_callback_pointer = &format!("{}FreePointer", DartCodeOracle::fn_name(callback_name)); - let free_callback_type = &format!("UniffiCallbackInterface{callback_name}Free"); - - // Clone callback - let clone_callback_fn = &format!("{}CloneCallback", DartCodeOracle::fn_name(callback_name)); - let clone_callback_pointer = &format!("{}ClonePointer", DartCodeOracle::fn_name(callback_name)); - let clone_callback_type = &format!("UniffiCallbackInterface{callback_name}Clone"); - - quote! { - $(functions) - - void $free_callback_fn(int handle) { - try { - FfiConverterCallbackInterface$cls_name._handleMap.remove(handle); - } catch (e) { - // Optionally log error, but do not return anything. - } - } - - final Pointer> $free_callback_pointer = - Pointer.fromFunction<$free_callback_type>($free_callback_fn); - - int $clone_callback_fn(int handle) { - try { - final obj = FfiConverterCallbackInterface$cls_name._handleMap.get(handle); - final newHandle = FfiConverterCallbackInterface$cls_name._handleMap.insert(obj); - return newHandle; - } catch (e) { - // Return 0 on error, which should trigger an error on the Rust side - return 0; - } - } - - final Pointer> $clone_callback_pointer = - Pointer.fromFunction<$clone_callback_type>($clone_callback_fn, 0); - } -} - -fn callback_error_handling( - throws_type: Option<&Type>, - type_helper: &dyn TypeHelperRenderer, - status: dart::Tokens, -) -> dart::Tokens { - if let Some(error_type) = throws_type { - let error_type_label = - error_type.as_renderable(type_helper.get_ci()).render_type(error_type, type_helper); - let error_lower = error_type.as_codetype(type_helper.get_ci()).ffi_converter_name(); - quote! { - if (e is $error_type_label) { - $(&status).code = CALL_ERROR; - $(&status).errorBuf = $error_lower.lower(e); - } else { - $(&status).code = CALL_UNEXPECTED_ERROR; - $(&status).errorBuf = FfiConverterString.lower(e.toString()); - } - } - } else { - quote! { - $(&status).code = CALL_UNEXPECTED_ERROR; - $(&status).errorBuf = FfiConverterString.lower(e.toString()); - } - } -} - -fn generate_foreign_future_struct_definition(ffi_struct: &FfiStruct) -> dart::Tokens { - let struct_name = DartCodeOracle::ffi_struct_name(ffi_struct.name()); - let fields: Vec = ffi_struct - .fields() - .iter() - .map(|field| { - let field_name = DartCodeOracle::var_name(field.name()); - let ffi_field_type = field.type_(); - let field_type = match &ffi_field_type { - FfiType::RustCallStatus => quote!(RustCallStatus), - _ => DartCodeOracle::ffi_dart_type_label(Some(&ffi_field_type)), - }; - if let Some(annotation) = foreign_future_field_annotation(&ffi_field_type) { - quote! { - $annotation - external $field_type $field_name; - } - } else { - quote! { - external $field_type $field_name; - } - } - }) - .collect(); - - quote! { - final class $struct_name extends Struct { - $(for field in fields => $field) - } - } -} - -fn generate_foreign_future_completion_typedef( - callback_base: &str, - struct_name: &str, -) -> dart::Tokens { - let native_callback_name = format!("Uniffi{}", callback_base.to_upper_camel_case()); - let dart_callback_name = format!("{native_callback_name}Dart"); - let struct_tokens = DartCodeOracle::ffi_struct_name(struct_name); - let struct_tokens_alt = struct_tokens.clone(); - - let mut tokens = dart::Tokens::new(); - tokens.append(quote!(typedef $native_callback_name = Void Function(Uint64, $struct_tokens);)); - tokens.append(quote!(typedef $dart_callback_name = void Function(int, $struct_tokens_alt);)); - tokens -} - -fn foreign_future_completion_name(method: &Method) -> String { - let return_ffi_type = method.return_type().cloned().map(FfiType::from); - let suffix = FfiType::return_type_name(return_ffi_type.as_ref()).to_upper_camel_case(); - format!("ForeignFutureComplete{suffix}") -} - -fn foreign_future_field_annotation(field_type: &FfiType) -> Option { - match field_type { - FfiType::Int8 => Some(quote!(@Int8())), - FfiType::UInt8 => Some(quote!(@Uint8())), - FfiType::Int16 => Some(quote!(@Int16())), - FfiType::UInt16 => Some(quote!(@Uint16())), - FfiType::Int32 => Some(quote!(@Int32())), - FfiType::UInt32 => Some(quote!(@Uint32())), - FfiType::Int64 => Some(quote!(@Int64())), - FfiType::UInt64 => Some(quote!(@Uint64())), - FfiType::Float32 => Some(quote!(@Float())), - FfiType::Float64 => Some(quote!(@Double())), - _ => None, - } -} - -pub fn generate_callback_interface_vtable_init_function( - callback_name: &str, - methods: &[&Method], - ffi_module: &str, -) -> dart::Tokens { - let vtable_name = &format!("UniffiVTableCallbackInterface{callback_name}"); - let vtable_static_instance_name = - format!("{}{}", DartCodeOracle::fn_name(callback_name), "VTable"); - let init_fn_name = &format!("init{callback_name}VTable"); - let snake_callback = callback_name.to_lowercase(); - - quote! { - late final Pointer<$vtable_name> $(&vtable_static_instance_name); - - void $init_fn_name() { - // Make initialization idempotent - return early if already initialized - if (FfiConverterCallbackInterface$(DartCodeOracle::class_name(callback_name))._vtableInitialized) { - return; - } - - $(&vtable_static_instance_name) = calloc<$vtable_name>(); - $(&vtable_static_instance_name).ref.uniffiFree = $(format!("{}FreePointer", DartCodeOracle::fn_name(callback_name))); - $(&vtable_static_instance_name).ref.uniffiClone = $(format!("{}ClonePointer", DartCodeOracle::fn_name(callback_name))); - $(for m in methods { - $(&vtable_static_instance_name).ref.$(DartCodeOracle::fn_name(m.name())) = $(DartCodeOracle::fn_name(callback_name))$(DartCodeOracle::class_name(m.name()))Pointer; - }) - - rustCall((status) { - uniffi_$(ffi_module)_fn_init_callback_vtable_$(snake_callback)( - $(vtable_static_instance_name), - ); - checkCallStatus(NullRustCallStatusErrorHandler(), status); - }); - - // Update the flag to prevent re-initialization - FfiConverterCallbackInterface$(DartCodeOracle::class_name(callback_name))._vtableInitialized = true; - } - } -} diff --git a/uniffi/dart/src/gen/code_type.rs b/uniffi/dart/src/gen/code_type.rs deleted file mode 100644 index 11d3c72fd..000000000 --- a/uniffi/dart/src/gen/code_type.rs +++ /dev/null @@ -1,52 +0,0 @@ -use std::fmt::Debug; - -use uniffi_bindgen::interface::Literal; - -/// A trait tor the implementation. -pub trait CodeType: Debug { - /// The language specific label used to reference this type. This will be used in - /// method signatures and property declarations. - fn type_label(&self) -> String; - - /// A representation of this type label that can be used as part of another - /// identifier. e.g. `read_foo()`, or `FooInternals`. - /// - /// This is especially useful when creating specialized objects or methods to deal - /// with this type only. - fn canonical_name(&self) -> String { - self.type_label() - } - - fn literal(&self, _literal: &Literal) -> String { - unimplemented!("Unimplemented for {}", self.type_label()) - } - - /// Name of the FfiConverter - /// - /// This is the object that contains the lower, write, lift, and read methods for this type. - fn ffi_converter_name(&self) -> String { - format!("FfiConverter{}", self.canonical_name()) - } - - /// Function to run at startup - fn initialization_fn(&self) -> Option { - None - } - - // The following must create an instance of the converter object - fn lower(&self) -> String { - format!("{}.lower", self.ffi_converter_name()) - } - - fn write(&self) -> String { - format!("{}.write", self.ffi_converter_name()) - } - - fn lift(&self) -> String { - format!("{}.lift", self.ffi_converter_name()) - } - - fn read(&self) -> String { - format!("{}.read", self.ffi_converter_name()) - } -} diff --git a/uniffi/dart/src/gen/compounds.rs b/uniffi/dart/src/gen/compounds.rs deleted file mode 100644 index 2999e1d32..000000000 --- a/uniffi/dart/src/gen/compounds.rs +++ /dev/null @@ -1,345 +0,0 @@ -use genco::lang::dart; -use genco::prelude::*; -use paste::paste; -use uniffi_bindgen::interface::Type; -use uniffi_bindgen::ComponentInterface; - -use super::oracle::{AsCodeType, DartCodeOracle}; -use crate::gen::render::{AsRenderable, Renderable, TypeHelperRenderer}; -use crate::gen::CodeType; - -macro_rules! impl_code_type_for_compound { - ($T:ty, $type_label_pattern:literal, $canonical_name_pattern: literal) => { - paste! { - #[derive(Debug)] - pub struct $T { - self_type: Type, - inner: Type, - inner_code: Box, - } - - impl $T { - pub fn new(self_type: Type, inner: Type, ci: &ComponentInterface) -> Self { - let inner_code = inner.as_codetype(ci); - Self { self_type, inner, inner_code } - } - fn inner(&self) -> &Type { - &self.inner - } - } - - impl CodeType for $T { - fn type_label(&self) -> String { - format!($type_label_pattern, self.inner_code.type_label()) - } - - fn canonical_name(&self) -> String { - format!($canonical_name_pattern, self.inner_code.canonical_name()) - } - } - } - }; -} - -macro_rules! impl_renderable_for_compound { - ($T:ty, $type_label_pattern:literal, $canonical_name_pattern: literal) => { - paste! { - impl Renderable for $T { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - type_helper.include_once_check(&self.ffi_converter_name(), &self.self_type); - let inner_codetype = &self.inner_code; - - let original_canonical = inner_codetype.canonical_name(); - let canonical_with_exception = - DartCodeOracle::exception_safe_name(&original_canonical); - let inner_already_registered = - type_helper.include_once_check(&original_canonical, &self.inner()) - || (canonical_with_exception != original_canonical - && type_helper.include_once_check( - &canonical_with_exception, - &self.inner(), - )); - - let raw_type_label = inner_codetype.type_label(); - let inner_type_label = - DartCodeOracle::exception_safe_name(&raw_type_label); - - let cl_name_buf = - format!($canonical_name_pattern, canonical_with_exception.as_str()); - let cl_name = &cl_name_buf; - let type_label_buf = - format!($type_label_pattern, inner_type_label.as_str()); - let type_label = &type_label_buf; - - let raw_converter_name = inner_codetype.ffi_converter_name(); - let inner_cl_converter_name_buf = - DartCodeOracle::exception_safe_name(&raw_converter_name); - let inner_cl_converter_name = &inner_cl_converter_name_buf; - let inner_data_type_buf = canonical_with_exception - .as_str() - .replace("UInt", "Uint") - .replace("Double", "Float"); - let inner_data_type = &inner_data_type_buf; - let _inner_type_signature = - if inner_data_type.contains("Float") { "double" } else { "int" }; - - // Render inner helper for Sequences and primitives that haven't been rendered yet - let inner_helper = if !inner_already_registered { - match self.inner() { - Type::Sequence { .. } - | Type::Int8 | Type::Int16 | Type::Int32 | Type::Int64 - | Type::UInt8 | Type::UInt16 | Type::UInt32 | Type::UInt64 - | Type::Float32 | Type::Float64 => { - self.inner().as_renderable(type_helper.get_ci()).render_type_helper(type_helper) - } - _ => quote!() - } - } else { - quote!() - }; - - quote! { - class $cl_name { - - static $type_label lift( RustBuffer buf) { - return $cl_name.read(buf.asUint8List()).value; - } - - static LiftRetVal<$type_label> read( Uint8List buf) { - if (ByteData.view(buf.buffer, buf.offsetInBytes).getInt8(0) == 0){ - return LiftRetVal(null, 1); - } - final result = $inner_cl_converter_name.read(Uint8List.view(buf.buffer, buf.offsetInBytes + 1)); - return LiftRetVal<$type_label>(result.value, result.bytesRead + 1); - } - - - static int allocationSize([$type_label value]) { - if (value == null) { - return 1; - } - return $inner_cl_converter_name.allocationSize(value) + 1; - } - - static RustBuffer lower( $type_label value) { - if (value == null) { - return toRustBuffer(Uint8List.fromList([0])); - } - - final buf = Uint8List($cl_name.allocationSize(value)); - $cl_name.write(value, buf); - return toRustBuffer(buf); - } - - static int write( $type_label value, Uint8List buf) { - if (value == null) { - buf[0] = 0; - return 1; - } - // we have a value - buf[0] = 1; - - return $inner_cl_converter_name.write(value, Uint8List.view(buf.buffer, buf.offsetInBytes + 1)) + 1; - } - } - $inner_helper - } - } - } - } - }; - - (SequenceCodeType, $canonical_name_pattern: literal) => { - paste! { - impl Renderable for SequenceCodeType { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - - let converter_name = self.ffi_converter_name(); - if type_helper.include_once_check(&converter_name, &self.self_type) { - return quote!(); - } - let inner_codetype = &self.inner_code; - - let original_canonical = inner_codetype.canonical_name(); - let canonical_with_exception = - DartCodeOracle::exception_safe_name(&original_canonical); - type_helper.include_once_check(&original_canonical, &self.inner()); - if canonical_with_exception != original_canonical { - type_helper.include_once_check(&canonical_with_exception, &self.inner()); - } - - let raw_type_label = inner_codetype.type_label(); - let inner_type_label = - DartCodeOracle::exception_safe_name(&raw_type_label); - - let cl_name_buf = - format!($canonical_name_pattern, canonical_with_exception.as_str()); - let cl_name = &cl_name_buf; - let type_label_buf = format!("List<{}>", inner_type_label.as_str()); - let type_label = &type_label_buf; - - let raw_converter_name = inner_codetype.ffi_converter_name(); - let inner_cl_converter_name_buf = - DartCodeOracle::exception_safe_name(&raw_converter_name); - let inner_cl_converter_name = &inner_cl_converter_name_buf; - let inner_data_type = canonical_with_exception - .as_str() - .replace("UInt", "Uint") - .replace("Double", "Float"); - let _inner_type_signature = if inner_data_type.contains("Float") { "double" } else { "int" }; - - - quote! { - class $cl_name { - - static $type_label lift( RustBuffer buf) { - return $cl_name.read(buf.asUint8List()).value; - } - - static LiftRetVal<$type_label> read( Uint8List buf) { - $type_label res = []; - final length = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); - int offset = buf.offsetInBytes + 4; - for (var i = 0; i < length; i++) { - final ret = $inner_cl_converter_name.read(Uint8List.view(buf.buffer, offset)); - offset += ret.bytesRead; - res.add(ret.value); - } - return LiftRetVal(res, offset - buf.offsetInBytes); - } - - static int write( $type_label value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, value.length); - int offset = buf.offsetInBytes + 4; - for (var i = 0; i < value.length; i++) { - offset += $inner_cl_converter_name.write(value[i], Uint8List.view(buf.buffer, offset)); - } - return offset - buf.offsetInBytes; - } - static int allocationSize($type_label value) { - return value.map((l) => $inner_cl_converter_name.allocationSize(l)).fold(0, (a, b) => a + b) + 4; - } - - static RustBuffer lower( $type_label value) { - final buf = Uint8List(allocationSize(value)); - write(value, buf); - return toRustBuffer(buf); - } - } - } - } - } - } - } -} - -impl_code_type_for_compound!(OptionalCodeType, "{}?", "Optional{}"); -impl_code_type_for_compound!(SequenceCodeType, "List<{}>", "Sequence{}"); - -impl_renderable_for_compound!(OptionalCodeType, "{}?", "FfiConverterOptional{}"); -impl_renderable_for_compound!(SequenceCodeType, "FfiConverterSequence{}"); - -// Map -#[derive(Debug)] -pub struct MapCodeType { - self_type: Type, - key: Type, - value: Type, - key_code: Box, - value_code: Box, -} - -impl MapCodeType { - pub fn new(self_type: Type, key: Type, value: Type, ci: &ComponentInterface) -> Self { - let key_code = key.as_codetype(ci); - let value_code = value.as_codetype(ci); - Self { self_type, key, value, key_code, value_code } - } - - fn key(&self) -> &Type { - &self.key - } - - fn value(&self) -> &Type { - &self.value - } -} - -impl CodeType for MapCodeType { - fn type_label(&self) -> String { - format!("Map<{}, {}>", self.key_code.type_label(), self.value_code.type_label()) - } - - fn canonical_name(&self) -> String { - let key = self.key_code.canonical_name(); - let val = self.value_code.canonical_name(); - format!("Map{}To{}", key, val) - } -} - -impl Renderable for MapCodeType { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - type_helper.include_once_check(&self.ffi_converter_name(), &self.self_type); - - let key_codetype = &self.key_code; - let val_codetype = &self.value_code; - - type_helper.include_once_check(&key_codetype.canonical_name(), self.key()); - type_helper.include_once_check(&val_codetype.canonical_name(), self.value()); - - let cl_name = &self.ffi_converter_name(); - let key_type_label_owned = key_codetype.type_label(); - let val_type_label_owned = val_codetype.type_label(); - let key_type_label = &key_type_label_owned; - let val_type_label = &val_type_label_owned; - - let key_conv_owned = key_codetype.ffi_converter_name(); - let val_conv_owned = val_codetype.ffi_converter_name(); - let key_conv = &key_conv_owned; - let val_conv = &val_conv_owned; - - quote! { - class $cl_name { - static Map<$key_type_label, $val_type_label> lift(RustBuffer buf) { - return $cl_name.read(buf.asUint8List()).value; - } - - static LiftRetVal> read(Uint8List buf) { - final map = <$key_type_label, $val_type_label>{}; - final length = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); - int offset = buf.offsetInBytes + 4; - for (var i = 0; i < length; i++) { - final k = $key_conv.read(Uint8List.view(buf.buffer, offset)); - offset += k.bytesRead; - final v = $val_conv.read(Uint8List.view(buf.buffer, offset)); - offset += v.bytesRead; - map[k.value] = v.value; - } - return LiftRetVal(map, offset - buf.offsetInBytes); - } - - static int write(Map<$key_type_label, $val_type_label> value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, value.length); - int offset = buf.offsetInBytes + 4; - for (final entry in value.entries) { - offset += $key_conv.write(entry.key, Uint8List.view(buf.buffer, offset)); - offset += $val_conv.write(entry.value, Uint8List.view(buf.buffer, offset)); - } - return offset - buf.offsetInBytes; - } - - static int allocationSize(Map<$key_type_label, $val_type_label> value) { - return value.entries - .map((e) => $key_conv.allocationSize(e.key) + $val_conv.allocationSize(e.value)) - .fold(4, (a, b) => a + b); - } - - static RustBuffer lower(Map<$key_type_label, $val_type_label> value) { - final buf = Uint8List(allocationSize(value)); - write(value, buf); - return toRustBuffer(buf); - } - } - } - } -} diff --git a/uniffi/dart/src/gen/custom.rs b/uniffi/dart/src/gen/custom.rs deleted file mode 100644 index b148b243f..000000000 --- a/uniffi/dart/src/gen/custom.rs +++ /dev/null @@ -1,76 +0,0 @@ -use genco::prelude::*; -use uniffi_bindgen::interface::{AsType, Type}; - -use super::oracle::{AsCodeType, DartCodeOracle}; -use super::render::{Renderable, TypeHelperRenderer}; -use super::CodeType; - -#[derive(Debug)] -pub struct CustomCodeType { - name: String, - module_path: String, - builtin: Box, - namespace: Option, -} - -impl CustomCodeType { - pub fn new( - name: String, - module_path: String, - builtin: Box, - namespace: Option, - ) -> Self { - CustomCodeType { name, module_path, builtin, namespace } - } -} - -impl CodeType for CustomCodeType { - fn type_label(&self) -> String { - DartCodeOracle::qualify(self.namespace.as_deref(), DartCodeOracle::class_name(&self.name)) - } - - fn canonical_name(&self) -> String { - DartCodeOracle::qualify_canonical( - self.namespace.as_deref(), - DartCodeOracle::class_name(&self.name), - ) - } - - fn ffi_converter_name(&self) -> String { - DartCodeOracle::qualify( - self.namespace.as_deref(), - format!("FfiConverter{}", DartCodeOracle::class_name(&self.name)), - ) - } -} - -impl AsType for CustomCodeType { - fn as_type(&self) -> Type { - Type::Custom { - name: self.name.clone(), - module_path: self.module_path.clone(), - builtin: self.builtin.clone(), - } - } -} - -impl Renderable for CustomCodeType { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - type_helper.include_once_check(&self.name, &self.as_type()); - // Another crate's library declares its own typedefs. - if self.namespace.is_some() { - return quote!(); - } - - let ffi_converter_name = &self.ffi_converter_name(); - let type_name = &self.type_label(); - let ci = type_helper.get_ci(); - let builtin_ffi_converter_name = &(*self.builtin).as_codetype(ci).ffi_converter_name(); - let builtin_name = DartCodeOracle::dart_type_label(Some(&*self.builtin), ci); - - quote! { - typedef $(type_name) = $(builtin_name); - typedef $(ffi_converter_name) = $(builtin_ffi_converter_name); - } - } -} diff --git a/uniffi/dart/src/gen/defaults.rs b/uniffi/dart/src/gen/defaults.rs deleted file mode 100644 index 0340b842a..000000000 --- a/uniffi/dart/src/gen/defaults.rs +++ /dev/null @@ -1,45 +0,0 @@ -use genco::prelude::*; -use uniffi_bindgen::interface::{Argument, AsType, DefaultValue, Type}; - -use uniffi_bindgen::ComponentInterface; - -use super::oracle::{AsCodeType, DartCodeOracle}; -use super::primitives::render_interface_default_value; - -fn enum_name_from_type(ty: &Type, ci: &ComponentInterface) -> Option { - match ty { - Type::Enum { .. } => Some(ty.as_codetype(ci).type_label()), - Type::Optional { inner_type } => enum_name_from_type(inner_type, ci), - _ => None, - } -} - -pub(crate) fn render_default_value( - default_value: &DefaultValue, - ty: &Type, - ci: &ComponentInterface, -) -> Option { - render_interface_default_value(default_value, ty, |ty, variant| { - let enum_name = enum_name_from_type(ty, ci)?; - let variant_name = DartCodeOracle::enum_variant_name(variant); - Some(format!("{enum_name}.{variant_name}")) - }) -} - -pub(crate) fn render_argument_param( - arg: &Argument, - type_tokens: dart::Tokens, - ci: &ComponentInterface, -) -> dart::Tokens { - let name = DartCodeOracle::var_name(arg.name()); - - if let Some(default_value) = arg.default_value() { - if let Some(default_expr) = render_default_value(default_value, &arg.as_type(), ci) { - quote!($type_tokens $name = $(default_expr)) - } else { - quote!(required $type_tokens $name) - } - } else { - quote!(required $type_tokens $name) - } -} diff --git a/uniffi/dart/src/gen/enums.rs b/uniffi/dart/src/gen/enums.rs deleted file mode 100644 index 0ebcd176b..000000000 --- a/uniffi/dart/src/gen/enums.rs +++ /dev/null @@ -1,452 +0,0 @@ -use genco::prelude::*; -use heck::ToLowerCamelCase; -use uniffi_bindgen::interface::{AsType, Enum, Field, Literal, Type}; -use uniffi_bindgen::ComponentInterface; - -use super::oracle::{AsCodeType, DartCodeOracle}; -use super::render::{AsRenderable, Renderable, TypeHelperRenderer}; -use crate::gen::CodeType; - -#[derive(Debug)] -pub struct EnumCodeType { - id: String, - namespace: Option, -} - -impl EnumCodeType { - pub fn new(id: String, namespace: Option) -> Self { - Self { id, namespace } - } -} - -impl CodeType for EnumCodeType { - fn type_label(&self) -> String { - DartCodeOracle::qualify(self.namespace.as_deref(), DartCodeOracle::class_name(&self.id)) - } - - fn canonical_name(&self) -> String { - DartCodeOracle::qualify_canonical( - self.namespace.as_deref(), - DartCodeOracle::class_name(&self.id), - ) - } - - fn literal(&self, literal: &Literal) -> String { - if let Literal::Enum(v, _) = literal { - format!("{}{}", self.type_label(), DartCodeOracle::enum_variant_name(v)) - } else { - unreachable!(); - } - } - - fn ffi_converter_name(&self) -> String { - DartCodeOracle::qualify( - self.namespace.as_deref(), - format!("FfiConverter{}", DartCodeOracle::class_name(&self.id)), - ) - } -} - -impl Renderable for EnumCodeType { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let canonical = self.canonical_name(); - // Another crate's library declares its own helpers. - if self.namespace.is_some() || type_helper.check(&canonical) { - quote!() - } else if let Some(enum_) = type_helper.get_enum(&self.id) { - generate_enum(enum_, type_helper) - } else { - unreachable!() - } - } -} - -pub fn generate_enum(obj: &Enum, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let dart_cls_name = &DartCodeOracle::class_name(obj.name()); - let ffi_converter_name = &obj.as_codetype(type_helper.get_ci()).ffi_converter_name(); - if obj.is_flat() { - let is_error_enum = type_helper.get_ci().is_used_as_error(obj); - let implements_exception = - if is_error_enum { quote!( implements Exception) } else { quote!() }; - - // For flat error enums, generate an error handler - let error_handler_class = if is_error_enum { - let error_handler_name = format!("{dart_cls_name}ErrorHandler"); - let instance_name = dart_cls_name.to_lower_camel_case(); - quote! { - class $(&error_handler_name) extends UniffiRustCallStatusErrorHandler { - @override - Exception lift(RustBuffer errorBuf) { - return $ffi_converter_name.lift(errorBuf); - } - } - - final $(&error_handler_name) $(instance_name)ErrorHandler = $(&error_handler_name)(); - } - } else { - quote!() - }; - - quote! { - enum $dart_cls_name $implements_exception { - $(for variant in obj.variants() => - $(DartCodeOracle::enum_variant_name(variant.name())),) - ; - } - - class $ffi_converter_name { - static LiftRetVal<$dart_cls_name> read( Uint8List buf) { - final index = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); - switch(index) { - $(for (index, variant) in obj.variants().iter().enumerate() => - case $(index + 1): - return LiftRetVal( - $dart_cls_name.$(DartCodeOracle::enum_variant_name(variant.name())), - 4, - ); - ) - default: - throw UniffiInternalError(UniffiInternalError.unexpectedEnumCase, "Unable to determine enum variant"); - } - } - - static $dart_cls_name lift( RustBuffer buffer) { - return $ffi_converter_name.read(buffer.asUint8List()).value; - } - - static RustBuffer lower( $dart_cls_name input) { - return toRustBuffer(createUint8ListFromInt(input.index + 1)); - } - - static int allocationSize($dart_cls_name _value) { - return 4; - } - - static int write( $dart_cls_name value, Uint8List buf) { - buf.buffer - .asByteData(buf.offsetInBytes) - .setInt32(0, value.index + 1); - return 4; - } - } - - $error_handler_class - } - } else { - let mut variants = vec![]; - - // helper functions to get the sanitized field name and type strings - fn field_name(field: &Field, field_num: usize) -> String { - if field.name().is_empty() { - format!("v{field_num}") - } else { - DartCodeOracle::var_name(field.name()) - } - } - fn field_type(field: &Field, type_helper: &dyn TypeHelperRenderer) -> String { - field - .as_type() - .as_renderable(type_helper.get_ci()) - .render_type(&field.as_type(), type_helper) - .to_string() - .expect("Could not stringify type") - } - fn field_ffi_converter_name(field: &Field, ci: &ComponentInterface) -> String { - field.as_type().as_codetype(ci).ffi_converter_name() - } - // Looked up in the crate that defines the enum: a local enum may share its name. - fn is_flat_enum(field: &Field, type_helper: &dyn TypeHelperRenderer) -> bool { - let ty = field.as_type(); - let Type::Enum { name, module_path } = &ty else { - return false; - }; - let ci = type_helper.get_ci(); - let defining = if ci.is_external(&ty) { - ci.find_component_interface(module_path) - } else { - Some(ci) - }; - defining.and_then(|ci| ci.get_enum_definition(name)).is_some_and(|e| e.is_flat()) - } - - // A data-carrying variant's Dart class is named `{Variant}{Enum}`, which - // can collide with a real top-level type of the same name (e.g. enum - // `Condition` variant `Field` -> `FieldCondition`, clashing with a record - // `FieldCondition`). Collect the names of every type that emits a - // top-level Dart class so a colliding variant class can be disambiguated - // instead of emitted twice. (Custom types lower to a typedef/converter, - // not a class of that name, so they are deliberately excluded.) - let reserved_type_names: std::collections::HashSet = { - let ci = type_helper.get_ci(); - ci.record_definitions() - .iter() - .map(|d| DartCodeOracle::class_name(d.name())) - .chain(ci.enum_definitions().iter().map(|d| DartCodeOracle::class_name(d.name()))) - .chain(ci.object_definitions().iter().map(|d| DartCodeOracle::class_name(d.name()))) - .chain( - ci.callback_interface_definitions() - .iter() - .map(|d| DartCodeOracle::class_name(d.name())), - ) - .collect() - }; - - // Name a data-carrying variant's Dart class `{Variant}{Enum}`, suffixing - // on collision so it doesn't clash with a same-named top-level type (a - // duplicate declaration). Used both where the class is defined and where - // the FfiConverter's `read` dispatches to it, so the two stay in sync. - let variant_class_name = |variant_name: &str| -> String { - let base = format!("{}{}", DartCodeOracle::class_name(variant_name), dart_cls_name); - if !reserved_type_names.contains(&base) { - return base; - } - // Loop rather than suffix once: a type literally named `{base}Variant` - // would otherwise reintroduce the very duplicate this guards against. - let mut candidate = format!("{base}Variant"); - let mut n = 2; - while reserved_type_names.contains(&candidate) { - candidate = format!("{base}Variant{n}"); - n += 1; - } - candidate - }; - - // An exported Display becomes toString() on the base class. - let display_to_string: Option = - obj.uniffi_trait_methods().display_fmt.map(|fmt| { - let ret = fmt.return_type().expect("Display returns a string"); - type_helper.include_once_check(&ret.as_codetype(type_helper.get_ci()).canonical_name(), ret); - let lifter = ret.as_codetype(type_helper.get_ci()).lift(); - quote! { - @override - String toString() { - return rustCallWithLifter( - (status) => $(fmt.ffi_func().name())($ffi_converter_name.lower(this), status), - $lifter, - ); - } - } - }); - let variant_to_string = - display_to_string.is_none() && type_helper.get_ci().is_used_as_error(obj); - - for (index, variant_obj) in obj.variants().iter().enumerate() { - for f in variant_obj.fields() { - type_helper.include_once_check( - &f.as_codetype(type_helper.get_ci()).canonical_name(), - &f.as_type(), - ); - } - let variant_dart_cls_name = &variant_class_name(variant_obj.name()); - - // Prepare constructor parameters - let constructor_params = variant_obj - .fields() - .iter() - .enumerate() - .map(|(i, field)| { - let param_name = field_name(field, i); - let param_type = field_type(field, type_helper); - if variant_obj.fields().len() > 1 { - quote!(required $param_type this.$param_name) - } else { - quote!($param_type this.$param_name) - } - }) - .collect::>(); - - let constructor_param_list = if variant_obj.fields().len() > 1 { - quote!({ $( for p in constructor_params => $p, ) }) - } else { - quote!($( for p in constructor_params => $p, )) - }; - - // Pre-process field reading code - let field_read_code: Vec = variant_obj.fields().iter().enumerate().map(|(i, field)| { - if is_flat_enum(field, type_helper) { - // Handle flat enums specially - they serialize as int32 (4 bytes) - quote!( - final $(field_name(field, i))_int = buf.buffer.asByteData(new_offset).getInt32(0); - final $(field_name(field, i)) = $(field_ffi_converter_name(field, type_helper.get_ci())).lift(toRustBuffer(createUint8ListFromInt($(field_name(field, i))_int))); - new_offset += 4; - ) - } else { - quote!( - final $(field_name(field, i))_lifted = $(field_ffi_converter_name(field, type_helper.get_ci())).read(Uint8List.view(buf.buffer, new_offset)); - final $(field_name(field, i)) = $(field_name(field, i))_lifted.value; - new_offset += $(field_name(field, i))_lifted.bytesRead; - ) - } - }).collect(); - - // Pre-process allocation size calculation - let allocation_parts: Vec = variant_obj.fields().iter().enumerate().map(|(i, field)| { - if is_flat_enum(field, type_helper) { - quote!(4 + ) // Flat enums are 4 bytes (int32) - } else { - quote!($(field_ffi_converter_name(field, type_helper.get_ci())).allocationSize($(field_name(field, i))) + ) - } - }).collect(); - - // Pre-process field write code - let field_write_code: Vec = variant_obj.fields().iter().enumerate().map(|(i, field)| { - if is_flat_enum(field, type_helper) { - // Handle flat enums specially - lower to RustBuffer and extract int32 - quote!( - final $(field_name(field, i))_buffer = $(field_ffi_converter_name(field, type_helper.get_ci())).lower($(field_name(field, i))); - final $(field_name(field, i))_int = $(field_name(field, i))_buffer.asUint8List().buffer.asByteData().getInt32(0); - buf.buffer.asByteData(new_offset).setInt32(0, $(field_name(field, i))_int); - new_offset += 4; - ) - } else { - quote!( - new_offset += $(field_ffi_converter_name(field, type_helper.get_ci())).write($(field_name(field, i)), Uint8List.view(buf.buffer, new_offset)); - ) - } - }).collect(); - - // Generate simple toString() method for error enum variants - // without an exported Display - let to_string_method: dart::Tokens = if variant_to_string { - if variant_obj.has_fields() { - let field_interpolations = variant_obj - .fields() - .iter() - .enumerate() - .map(|(i, field)| format!("${}", field_name(field, i))) - .collect::>() - .join(", "); - let to_string_with_fields = - format!("\"{variant_dart_cls_name}({field_interpolations})\""); - quote!( - @override - String toString() { - return $(&to_string_with_fields); - } - ) - } else { - quote!( - @override - String toString() { - return $(format!("\"{}\"", variant_dart_cls_name)); - } - ) - } - } else { - quote!() - }; - - variants.push(quote!{ - class $variant_dart_cls_name extends $dart_cls_name { - $(for (i, field) in variant_obj.fields().iter().enumerate() => final $(field_type(field, type_helper)) $(field_name(field, i)); ) - - // Add the public const constructor - $variant_dart_cls_name($constructor_param_list); - - // Keep the private constructor used by `read` - $variant_dart_cls_name._($(for (i, field) in variant_obj.fields().iter().enumerate() => $(field_type(field, type_helper)) this.$(field_name(field, i)), )); - - static LiftRetVal<$variant_dart_cls_name> read( Uint8List buf) { - int new_offset = buf.offsetInBytes; - - $(for code in &field_read_code => $code) - return LiftRetVal($variant_dart_cls_name._( - $(for (i, field) in variant_obj.fields().iter().enumerate() => $(field_name(field, i)),) - ), new_offset); - } - - @override - RustBuffer lower() { - final buf = Uint8List(allocationSize()); - write(buf); - return toRustBuffer(buf); - } - - @override - int allocationSize() { - return $(for part in &allocation_parts => $part) 4; - } - - @override - int write( Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, $(index + 1)); // write index into first position; - int new_offset = buf.offsetInBytes + 4; - - $(for code in &field_write_code => $code) - - return new_offset; - } - - $to_string_method - } - }); - } - - let is_error_enum = type_helper.get_ci().is_used_as_error(obj); - let implements_exception = - if is_error_enum { quote!( implements Exception) } else { quote!() }; - - // For error enums, also generate an error handler - let error_handler_class = if is_error_enum { - let error_handler_name = format!("{dart_cls_name}ErrorHandler"); - let instance_name = dart_cls_name.to_lower_camel_case(); - quote! { - class $(&error_handler_name) extends UniffiRustCallStatusErrorHandler { - @override - Exception lift(RustBuffer errorBuf) { - return $ffi_converter_name.lift(errorBuf); - } - } - - final $(&error_handler_name) $(instance_name)ErrorHandler = $(&error_handler_name)(); - } - } else { - quote!() - }; - - quote! { - abstract class $dart_cls_name $implements_exception { - RustBuffer lower(); - int allocationSize(); - int write( Uint8List buf); - - $(display_to_string) - } - - class $ffi_converter_name { - static $dart_cls_name lift( RustBuffer buffer) { - return $ffi_converter_name.read(buffer.asUint8List()).value; - } - - static LiftRetVal<$dart_cls_name> read( Uint8List buf) { - final index = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); - final subview = Uint8List.view(buf.buffer, buf.offsetInBytes + 4); - switch(index) { - $(for (index, variant) in obj.variants().iter().enumerate() => - case $(index + 1): - final lifted = $(variant_class_name(variant.name())).read(subview); - return LiftRetVal<$dart_cls_name>(lifted.value, lifted.bytesRead - subview.offsetInBytes + 4); - ) - default: throw UniffiInternalError(UniffiInternalError.unexpectedEnumCase, "Unable to determine enum variant"); - } - } - - static RustBuffer lower( $dart_cls_name value) { - return value.lower(); - } - - static int allocationSize($dart_cls_name value) { - return value.allocationSize(); - } - - static int write( $dart_cls_name value, Uint8List buf) { - return value.write(buf) - buf.offsetInBytes; - } - } - - $(variants) - - $error_handler_class - } - } -} diff --git a/uniffi/dart/src/gen/functions.rs b/uniffi/dart/src/gen/functions.rs deleted file mode 100644 index 3b8fe3a3e..000000000 --- a/uniffi/dart/src/gen/functions.rs +++ /dev/null @@ -1,92 +0,0 @@ -use genco::prelude::*; -use uniffi_bindgen::interface::{AsType, Function}; - -use super::defaults::render_argument_param; -use super::oracle::AsCodeType; -use super::render::TypeHelperRenderer; -use crate::gen::oracle::DartCodeOracle; -use crate::gen::render::AsRenderable; - -pub fn generate_function(func: &Function, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let args = if func.arguments().is_empty() { - quote!() - } else { - quote!({$(for arg in &func.arguments() => - $(render_argument_param( - arg, - arg.as_renderable(type_helper.get_ci()).render_type(&arg.as_type(), type_helper), - type_helper.get_ci() - )), - )}) - }; - - let (ret, lifter) = if let Some(ret) = func.return_type() { - ( - ret.as_renderable(type_helper.get_ci()).render_type(ret, type_helper), - quote!($(ret.as_codetype(type_helper.get_ci()).lift())), - ) - } else { - (quote!(void), quote!((_) {})) - }; - - // Check if function can throw errors - let error_handler = if let Some(error_type) = func.throws_type() { - let handler_name = DartCodeOracle::error_handler_name(error_type, type_helper.get_ci()); - quote!($(handler_name)) - } else { - quote!(null) - }; - - // Use centralized callback-aware argument lowering - if func.is_async() { - // For async methods returning objects, we need to convert the int pointer to Pointer - let async_lifter = if let Some(ret_type) = func.return_type() { - match ret_type { - uniffi_bindgen::interface::Type::Object { .. } => { - quote!((ptr) => $lifter(Pointer.fromAddress(ptr))) - } - _ => lifter.clone(), - } - } else { - lifter.clone() - }; - - quote!( - UniffiRustFuture<$ret> $(DartCodeOracle::fn_name(func.name()))($args) { - return uniffiRustCallAsync( - () => $(func.ffi_func().name())( - $(for arg in &func.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) - ), - $(DartCodeOracle::async_poll(func, type_helper.get_ci())), - $(DartCodeOracle::async_complete(func, type_helper.get_ci())), - $(DartCodeOracle::async_cancel(func, type_helper.get_ci())), - $(DartCodeOracle::async_free(func, type_helper.get_ci())), - $async_lifter, - $error_handler, - ); - } - ) - } else if ret == quote!(void) { - quote!( - $ret $(DartCodeOracle::fn_name(func.name()))($args) { - return rustCall((status) { - $(func.ffi_func().name())( - $(for arg in &func.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) status - ); - }, $error_handler); - } - ) - } else { - quote!( - $ret $(DartCodeOracle::fn_name(func.name()))($args) { - return rustCallWithLifter( - (status) => $(func.ffi_func().name())( - $(for arg in &func.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) status - ), - $lifter, - $error_handler - ); - } - ) - } -} diff --git a/uniffi/dart/src/gen/mod.rs b/uniffi/dart/src/gen/mod.rs deleted file mode 100644 index 236d9da8d..000000000 --- a/uniffi/dart/src/gen/mod.rs +++ /dev/null @@ -1,410 +0,0 @@ -use std::collections::{HashMap, HashSet}; -use std::process::Command; - -use anyhow::{bail, Context, Result}; -use camino::Utf8Path; -use genco::fmt; -use genco::prelude::*; -use serde::{Deserialize, Serialize}; -use toml; -use uniffi_bindgen::{BindingGenerator, Component, ComponentInterface}; - -// use uniffi_bindgen::MergeWith; -use self::render::Renderer; -use self::types::TypeHelpersRenderer; -use crate::gen::oracle::DartCodeOracle; - -mod callback_interface; -mod code_type; -mod compounds; -mod custom; -mod defaults; -mod enums; -mod functions; -mod objects; -mod oracle; -mod primitives; -mod records; -mod render; -pub mod stream; -mod types; - -pub use code_type::CodeType; - -#[derive(Debug, Default, Clone, Serialize, Deserialize)] -pub struct Config { - package_name: Option, - cdylib_name: Option, - #[serde(default)] - external_packages: HashMap, - asset_id: Option, -} - -impl From<&ComponentInterface> for Config { - fn from(ci: &ComponentInterface) -> Self { - Config { - package_name: Some(ci.namespace().to_owned()), - cdylib_name: Some(ci.namespace().to_owned()), - external_packages: HashMap::new(), - asset_id: None, - } - } -} - -impl Config { - pub fn package_name(&self) -> String { - if let Some(package_name) = &self.package_name { - package_name.clone() - } else { - "uniffi".into() - } - } - - pub fn cdylib_name(&self) -> String { - if let Some(cdylib_name) = &self.cdylib_name { - cdylib_name.clone() - } else { - "uniffi".into() - } - } - - pub fn asset_id(&self) -> String { - if let Some(asset_id) = &self.asset_id { - asset_id.clone() - } else { - // Default: uniffi:{cdylib_name} - // Dart's Native Assets system automatically prefixes this with package:{dart_package_name}/ - // so the full ID becomes package:{dart_package_name}/uniffi:{cdylib_name} - format!("uniffi:{}", self.cdylib_name()) - } - } -} - -/// The `RustBuffer` alloc/free/reserve helpers, which `RustBuffer`'s own methods -/// call. They live alongside `RustBuffer` in the shared runtime rather than being -/// repeated in every component file. -fn is_rustbuffer_fn(ci: &ComponentInterface, name: &str) -> bool { - ci.iter_rust_buffer_ffi_function_definitions().any(|f| f.name() == name) -} - -/// Emit the `@Native` extern declarations for `ci`'s FFI functions. -/// -/// `include` partitions them: the shared runtime file takes the `rustbuffer_*` -/// helpers it calls from `RustBuffer`, and each component file takes the rest. -/// Declaring a symbol in both places would be a duplicate definition. -fn uniffi_function_definitions( - ci: &ComponentInterface, - asset_id: &str, - include: impl Fn(&str) -> bool, -) -> dart::Tokens { - let mut definitions = quote!(); - let mut defined_functions = HashSet::new(); // Track defined function names - - for fun in ci.iter_ffi_function_definitions() { - let fun_name = fun.name().to_owned(); - - if !include(&fun_name) { - continue; - } - - // Check for duplicate function names - if !defined_functions.insert(fun_name.clone()) { - // Function name already exists, skip to prevent duplicate definition - continue; - } - - // For @Native, we need both native types (for the annotation) and Dart types (for the external declaration) - let native_return_type = match fun.return_type() { - Some(return_type) => { - quote! { $(DartCodeOracle::ffi_native_type_label(Some(return_type))) } - } - None => quote! { Void }, - }; - - let dart_return_type = match fun.return_type() { - Some(return_type) => { - quote! { $(DartCodeOracle::ffi_dart_type_label(Some(return_type))) } - } - None => quote! { void }, - }; - - let (native_args, dart_args) = { - let mut native_arg_vec = vec![]; - let mut dart_arg_with_names_vec = vec![]; - - for arg in fun.arguments() { - let arg_name = arg.name(); - let native_type = DartCodeOracle::ffi_native_type_label(Some(&arg.type_())); - let dart_type = DartCodeOracle::ffi_dart_type_label(Some(&arg.type_())); - - native_arg_vec.push(native_type); - dart_arg_with_names_vec.push(quote!($dart_type $arg_name)); - } - - if fun.has_rust_call_status_arg() { - native_arg_vec.push(quote!(Pointer)); - dart_arg_with_names_vec.push(quote!(Pointer uniffiStatus)); - } - - let native_args = quote!($(for (i, arg) in native_arg_vec.iter().enumerate() => $(if i > 0 => , )$[' ']$arg)); - let dart_args = quote!($(for (i, arg) in dart_arg_with_names_vec.iter().enumerate() => $(if i > 0 => , )$[' ']$arg)); - (native_args, dart_args) - }; - - // Generate @Native annotation with assetId - // @Native uses the function name as symbol automatically - // assetId references the _uniffiAssetId constant - definitions.append(quote! { - @Native<$(&native_return_type) Function($(&native_args))>( - assetId: $asset_id - ) - external $(&dart_return_type) $fun_name($(&dart_args)); - $['\n'] - }); - } - - definitions -} - -pub struct DartWrapper<'a> { - config: &'a Config, - ci: &'a ComponentInterface, - type_renderer: TypeHelpersRenderer<'a>, -} - -impl<'a> DartWrapper<'a> { - pub fn new(ci: &'a ComponentInterface, config: &'a Config) -> Self { - let type_renderer = TypeHelpersRenderer::new(ci); - DartWrapper { ci, config, type_renderer } - } - - fn generate(&self) -> dart::Tokens { - let package_name = &self.config.package_name(); - - let (type_helper_code, functions_definitions) = &self.type_renderer.render(); - - let asset_id_suffix = &self.config.asset_id(); // e.g., "uniffi:hello_world" - - quote! { - // The runtime scaffolding moved to the shared module, so a component - // file may not use every import it declares. Which ones go unused - // depends on the interface, so the directive is simpler than tracking - // usage per import. - $("// ignore_for_file: unused_import")$['\n'] - library $package_name; - - $(type_helper_code) // Imports, Types and Type Helper - - // Generated by uniffi-dart – do NOT edit. - // This asset ID is used by @Native annotations to locate the native library - // via Native Assets. Dart automatically prefixes asset names with "package:{packageName}/", - // so we construct the full ID here to match what the build hook registers. - // The asset ID format is: package:{dart_package_name}/uniffi:{cdylib_name} - const _uniffiAssetId = $(quoted(format!("package:{}/{}", package_name, asset_id_suffix))); - - $(functions_definitions) - - // FFI function definitions using @Native - $(uniffi_function_definitions(self.ci, "_uniffiAssetId", |name| !is_rustbuffer_fn(self.ci, name))) - - // API version and checksum validation - void _checkApiVersion() { - final bindingsVersion = $(self.ci.uniffi_contract_version()); - final scaffoldingVersion = $(self.ci.ffi_uniffi_contract_version().name())(); - if (bindingsVersion != scaffoldingVersion) { - throw UniffiInternalError.panicked("UniFFI contract version mismatch: bindings version $bindingsVersion, scaffolding version $scaffoldingVersion"); - } - } - - void _checkApiChecksums() { - $(for (name, expected_checksum) in self.ci.iter_checksums() => - if ($(name)() != $expected_checksum) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - ) - } - - void ensureInitialized() { - _checkApiVersion(); - _checkApiChecksums(); - } - - // Backwards-compatible entry point used by existing tests - @Deprecated("Use ensureInitialized instead") - void initialize() { - ensureInitialized(); - } - } - } -} - -pub struct DartBindingGenerator; - -impl BindingGenerator for DartBindingGenerator { - type Config = Config; - - fn write_bindings( - &self, - settings: &uniffi_bindgen::GenerationSettings, - components: &[uniffi_bindgen::Component], - ) -> Result<()> { - let write_dart = |filename: camino::Utf8PathBuf, tokens: dart::Tokens| -> Result<()> { - let file = std::fs::File::create(filename)?; - let mut w = fmt::IoWriter::new(file); - - let mut fmt = fmt::Config::from_lang::(); - if settings.try_format_code { - fmt = fmt.with_indentation(fmt::Indentation::Space(2)); - } - let config = dart::Config::default(); - - tokens.format_file(&mut w.as_formatter(&fmt), &config)?; - Ok(()) - }; - - // A component whose namespace matches the runtime module would write its - // own file over the shared runtime. - if let Some(Component { ci, .. }) = - components.iter().find(|c| c.ci.namespace() == types::RUNTIME_MODULE) - { - bail!( - "namespace `{}` collides with the shared runtime module `{}.dart`; \ - rename the namespace", - ci.namespace(), - types::RUNTIME_MODULE - ); - } - - // The shared runtime goes out once for the whole generation, ahead of the - // per-component files that import it. One component supplies the - // `rustbuffer_*` symbols and asset id for all of them: only library mode - // generates more than one component, every component there links into one - // cdylib, and UniFFI gives each the same cdylib name. If a configuration - // ever breaks that assumption, the runtime would resolve its allocator - // against the wrong library, so check rather than trust it. - let full_asset_id = - |config: &Config| format!("package:{}/{}", config.package_name(), config.asset_id()); - if let Some(Component { config: first, .. }) = components.first() { - for Component { ci, config, .. } in components { - if full_asset_id(config) != full_asset_id(first) { - bail!( - "component `{}` has asset id `{}`, which differs from `{}`; \ - the shared runtime module can only carry one asset id", - ci.namespace(), - full_asset_id(config), - full_asset_id(first) - ); - } - } - } - - // Components arrive in no particular order; take the runtime from the same one every run. - if let Some(Component { ci, config, .. }) = - components.iter().min_by_key(|c| c.ci.crate_name()) - { - let asset_id = full_asset_id(config); - let runtime = quote! { - $("// ignore_for_file: unused_import")$['\n'] - $(format!("library {};", types::RUNTIME_MODULE)) - - $(types::runtime_scaffolding(ci)) - - const _uniffiAssetId = $(quoted(asset_id)); - - $(uniffi_function_definitions(ci, "_uniffiAssetId", |name| is_rustbuffer_fn(ci, name))) - }; - write_dart(settings.out_dir.join(format!("{}.dart", types::RUNTIME_MODULE)), runtime)?; - } - - for Component { ci, config, .. } in components { - write_dart( - settings.out_dir.join(format!("{}.dart", ci.namespace())), - DartWrapper::new(ci, config).generate(), - )?; - } - - // Run full Dart formatter on the output directory as a best-effort step. - // This is non-fatal: failures will only emit a warning. - let mut format_command = Command::new("dart"); - format_command.current_dir(&settings.out_dir).arg("format").arg("."); - match format_command.spawn().and_then(|mut c| c.wait()) { - Ok(status) if status.success() => {} - Ok(_) | Err(_) => { - eprintln!( - "WARNING: dart format failed or is unavailable; proceeding without full formatting" - ); - } - } - Ok(()) - } - - fn new_config(&self, root_toml: &toml::value::Value) -> Result { - Ok(match root_toml.get("bindings").and_then(|b| b.get("dart")) { - Some(v) => v.clone().try_into()?, - None => Default::default(), - }) - } - - fn update_component_configs( - &self, - settings: &uniffi_bindgen::GenerationSettings, - components: &mut Vec>, - ) -> Result<()> { - for c in &mut *components { - c.config.cdylib_name.get_or_insert_with(|| { - settings.cdylib.clone().unwrap_or_else(|| format!("uniffi_{}", c.ci.namespace())) - }); - } - Ok(()) - } -} - -pub fn generate_dart_bindings( - udl_file: &Utf8Path, - config_file_override: Option<&Utf8Path>, - out_dir_override: Option<&Utf8Path>, - library_file: &Utf8Path, - library_mode: bool, - crate_name: Option, - try_format: bool, -) -> anyhow::Result<()> { - if library_mode { - // Resolve each crate's `uniffi.toml` and UDL from cargo metadata, exactly - // as uniffi-bindgen itself does. This is what makes `package_name` / - // `cdylib_name` (and any per-crate config) resolve correctly — a custom - // supplier that reads only a single file would default those and desync - // the generated asset ids from the Native Assets build hook. - let config_supplier = - uniffi_bindgen::cargo_metadata::CrateConfigSupplier::from_cargo_metadata_command(false) - .context("Failed to build the crate config supplier from cargo metadata")?; - - let out_dir = - out_dir_override.context("an output directory is required in library mode")?; - - uniffi_bindgen::library_mode::generate_bindings( - library_file, - crate_name, - &DartBindingGenerator {}, - &config_supplier, - // Pass the `--config` override through so uniffi merges it into each - // crate's config (values take precedence), rather than replacing every - // crate's config with the same file. - config_file_override, - out_dir, - try_format, - )?; - Ok(()) - } else { - // Note: library_file is needed by uniffi_bindgen to extract metadata from proc macros, - // even though we don't use it for DynamicLibrary.open() anymore (Native Assets handle that) - uniffi_bindgen::generate_external_bindings( - &DartBindingGenerator {}, - udl_file, - config_file_override, - out_dir_override, - Some(library_file), - None, - try_format, - ) - } -} diff --git a/uniffi/dart/src/gen/objects.rs b/uniffi/dart/src/gen/objects.rs deleted file mode 100644 index 8704d0c3c..000000000 --- a/uniffi/dart/src/gen/objects.rs +++ /dev/null @@ -1,913 +0,0 @@ -use std::fmt::Debug; - -use genco::prelude::*; -use heck::ToLowerCamelCase; -use uniffi_bindgen::interface::{ - AsType, Literal, Method, Object, ObjectImpl, TraitKind, UniffiTrait, -}; - -use super::defaults::render_argument_param; -use super::stream::generate_stream; -use crate::gen::callback_interface::{ - generate_callback_functions, generate_callback_interface, - generate_callback_interface_vtable_init_function, generate_callback_vtable_interface, -}; -use crate::gen::oracle::{AsCodeType, DartCodeOracle}; -use crate::gen::render::{AsRenderable, Renderable, TypeHelperRenderer}; -use crate::gen::CodeType; - -#[derive(Debug)] -pub struct ObjectCodeType { - id: String, - imp: ObjectImpl, - namespace: Option, -} - -impl ObjectCodeType { - pub fn new(id: String, imp: ObjectImpl, namespace: Option) -> Self { - Self { id, imp, namespace } - } -} - -impl CodeType for ObjectCodeType { - fn type_label(&self) -> String { - DartCodeOracle::qualify(self.namespace.as_deref(), DartCodeOracle::class_name(&self.id)) - } - - fn canonical_name(&self) -> String { - DartCodeOracle::qualify_canonical( - self.namespace.as_deref(), - DartCodeOracle::class_name(&self.id), - ) - } - - fn literal(&self, _literal: &Literal) -> String { - unreachable!(); - } - - fn ffi_converter_name(&self) -> String { - let class_name = DartCodeOracle::class_name(&self.id); - let name = match self.imp { - // The converter lives in its own class rather than on the object itself, so - // that a Rust method named `read`/`write`/`lower` cannot collide with the - // converter's statics (Dart rejects a static and an instance member sharing - // a name). Matches how records, enums and callback interfaces are emitted. - ObjectImpl::Struct => format!("FfiConverter{class_name}"), - // Foreign-implementable traits (with_foreign / callback_interface) are - // lowered through a callback-interface FfiConverter. Mirrors - // uniffi's `ObjectImpl::has_callback_interface()` (Both | ForeignOnly). - ObjectImpl::Trait(TraitKind::Both | TraitKind::ForeignOnly) => { - format!("FfiConverterCallbackInterface{}", self.id) - } - // A pure Rust-only trait object uses its own sibling FfiConverter class. - ObjectImpl::Trait(TraitKind::RustOnly) => format!("FfiConverter{class_name}"), - }; - DartCodeOracle::qualify(self.namespace.as_deref(), name) - } -} - -impl Renderable for ObjectCodeType { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - // Another crate's library declares its own helpers. - if self.namespace.is_some() || type_helper.check(&self.id) { - quote!() - } else if let Some(obj) = type_helper.get_object(&self.id) { - generate_object(obj, type_helper) - } else { - unreachable!() - } - } -} -pub fn generate_object(obj: &Object, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - type_helper.include_once_check(obj.name(), &obj.as_type()); - - if obj.has_callback_interface() { - let interface = generate_callback_interface( - obj.name(), - &obj.as_codetype(type_helper.get_ci()).ffi_converter_name(), - &obj.methods(), - type_helper, - Some(&format!("_{}Impl", DartCodeOracle::class_name(obj.name()))), - ); - let vtable_interface = generate_callback_vtable_interface(obj.name(), &obj.methods()); - let functions = generate_callback_functions(obj.name(), &obj.methods(), type_helper); - let fallback_namespace = { - let namespace = type_helper - .get_ci() - .namespace_for_type(&obj.as_type()) - .expect("object should have namespace"); - namespace.to_string() - }; - let ffi_module = - DartCodeOracle::infer_ffi_module(type_helper.get_ci(), move || fallback_namespace); - let vtable_init = generate_callback_interface_vtable_init_function( - obj.name(), - &obj.methods(), - &ffi_module, - ); - let rust_impl = generate_callback_trait_rust_impl(obj, type_helper); - return quote!( - $interface - $rust_impl - $vtable_interface - $functions - $vtable_init - ); - } else if obj.is_trait_interface() { - return generate_trait_object(obj, type_helper); - } - - let cls_name = &DartCodeOracle::class_name(obj.name()); - let ffi_converter_name = &obj.as_codetype(type_helper.get_ci()).ffi_converter_name(); - let interface_name = DartCodeOracle::object_interface_name(type_helper.get_ci(), obj); - let interface_definition = generate_object_interface(obj, &interface_name, type_helper); - let finalizer_cls_name = &format!("{cls_name}Finalizer"); - let ffi_object_free_name = obj.ffi_object_free().name(); - let ffi_object_clone_name = obj.ffi_object_clone().name(); - - // Stream workaround, make it more elegant later - - let stream_glue = - if obj.name().contains("StreamExt") { generate_stream(obj, type_helper) } else { quote!() }; - - let mut constructor_definitions: Vec = Vec::new(); - let mut async_constructor_factories: Vec = Vec::new(); - - for constructor in obj.constructors() { - let ffi_func_name = constructor.ffi_func().name(); - let constructor_name = constructor.name(); - - let dart_constructor_decl = if constructor_name == "new" { - quote!($cls_name) - } else { - quote!($cls_name.$(DartCodeOracle::fn_name(constructor_name))) - }; - - // Check if function can throw errors - let error_handler = if let Some(error_type) = constructor.throws_type() { - let handler_name = DartCodeOracle::error_handler_name(error_type, type_helper.get_ci()); - quote!($(handler_name)) - } else { - quote!(null) - }; - - let dart_params = if constructor.arguments().is_empty() { - quote!() - } else { - quote!({$(for arg in constructor.arguments() => - $(render_argument_param( - arg, - quote!($(DartCodeOracle::dart_type_label(Some(&arg.as_type()), type_helper.get_ci()))), - type_helper.get_ci() - )), - )}) - }; - - let ffi_call_args = quote!($(for arg in constructor.arguments() => - $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) - ); - - // Ensure argument types are included - for arg in constructor.arguments() { - type_helper.include_once_check( - &arg.as_codetype(type_helper.get_ci()).canonical_name(), - &arg.as_type(), - ); - } - - if constructor.is_async() { - async_constructor_factories.push(quote! { - static UniffiRustFuture<$cls_name> $(DartCodeOracle::fn_name(constructor_name))($dart_params) { - return uniffiRustCallAsync( - () => $ffi_func_name( - $ffi_call_args - ), - $(DartCodeOracle::async_poll(constructor, type_helper.get_ci())), - $(DartCodeOracle::async_complete(constructor, type_helper.get_ci())), - $(DartCodeOracle::async_cancel(constructor, type_helper.get_ci())), - $(DartCodeOracle::async_free(constructor, type_helper.get_ci())), - (int handle) => $cls_name._(Pointer.fromAddress(handle)), - $error_handler, - ); - } - }); - } else { - constructor_definitions.push(quote! { - // Public constructor - $dart_constructor_decl($dart_params) : _ptr = rustCall((status) => - $ffi_func_name( - $ffi_call_args status - ), - $error_handler - ) { - _$finalizer_cls_name.attach(this, _ptr, detach: this); - } - }); - } - } - - // For interface objects that are used as error types, generate error handlers - let is_error_interface = type_helper.get_ci().is_used_as_error(obj); - - let error_handler_class = if is_error_interface { - // Generate error handlers for specific error interfaces - let error_handler_name = format!("{cls_name}ErrorHandler"); - let instance_name = cls_name.to_lower_camel_case(); - quote! { - class $(&error_handler_name) extends UniffiRustCallStatusErrorHandler { - @override - Exception lift(RustBuffer errorBuf) { - return $(ffi_converter_name).read(errorBuf.asUint8List()).value; - } - } - - final $(&error_handler_name) $(instance_name)ErrorHandler = $(&error_handler_name)(); - } - } else { - quote!() - }; - - let mut implements: Vec = Vec::new(); - if !obj.is_trait_interface() { - implements.push(interface_name.clone()); - } - if is_error_interface && !implements.iter().any(|entry| entry == "Exception") { - implements.push("Exception".to_string()); - } - - for trait_impl in obj.trait_impls() { - // Extract the trait name from the trait_ty Type - let trait_name = match &trait_impl.trait_ty { - uniffi_bindgen::interface::Type::Object { name, .. } => name, - uniffi_bindgen::interface::Type::CallbackInterface { name, .. } => name, - _ => continue, // Skip if it's not an Object or CallbackInterface - }; - let trait_iface = DartCodeOracle::trait_interface_name(type_helper.get_ci(), trait_name); - if !implements.contains(&trait_iface) { - implements.push(trait_iface); - } - } - - let implements_clause = if implements.is_empty() { - quote!() - } else { - quote!( implements $(for imp in implements.iter() join (, ) => $(imp))) - }; - - // Generate toString() method for error interfaces - let has_display_trait = - obj.uniffi_traits().iter().any(|t| matches!(t, UniffiTrait::Display { .. })); - - let to_string_method: dart::Tokens = - if is_error_interface && !obj.is_trait_interface() && !has_display_trait { - // Only generate toString for regular error interfaces, skip trait interfaces for now - let dart_class_name = format!("\"{cls_name}\""); - quote! { - @override - String toString() { - return $(&dart_class_name); - } - } - } else { - quote!() - }; - - let trait_methods = generate_trait_helpers(obj, type_helper); - - quote! { - $interface_definition - - final _$finalizer_cls_name = Finalizer>((ptr) { - rustCall((status) => $ffi_object_free_name(ptr, status)); - }); - - class $cls_name $implements_clause { - late final Pointer _ptr; - bool _isDisposed = false; - - // Private constructor for internal use / lift - $cls_name._(this._ptr) { - _$finalizer_cls_name.attach(this, _ptr, detach: this); - } - - // Public constructors generated from UDL - $( for ctor_def in constructor_definitions => $ctor_def ) - $( for factory_def in async_constructor_factories => $factory_def ) - - // Factory for lifting pointers - factory $cls_name.lift(Pointer ptr) { - return $cls_name._(ptr); - } - - Pointer uniffiClonePointer() { - if (_isDisposed) { - throw StateError("Object has already been disposed"); - } - return rustCall((status) => $ffi_object_clone_name(_ptr, status)); - } - - void dispose() { - if (_isDisposed) { - return; - } - // Reserve status storage before closing, so allocation failure - // leaves the handle owned and disposal retryable. - final status = calloc(); - _isDisposed = true; - _$finalizer_cls_name.detach(this); - try { - $ffi_object_free_name(_ptr, status); - checkCallStatus(NullRustCallStatusErrorHandler(), status); - } finally { - calloc.free(status); - } - } - - $to_string_method - $trait_methods - - $(for mt in &obj.methods() => $(generate_method(mt, type_helper))) - } - - class $ffi_converter_name { - static $cls_name lift(Pointer ptr) { - return $cls_name.lift(ptr); - } - - static Pointer lower($cls_name value) { - return value.uniffiClonePointer(); - } - - // A Rust pointer is 8 bytes - static int allocationSize($cls_name value) { - return 8; - } - - static LiftRetVal<$cls_name> read(Uint8List buf) { - final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); - final pointer = Pointer.fromAddress(handle); - return LiftRetVal($cls_name.lift(pointer), 8); - } - - static int write($cls_name value, Uint8List buf) { - final handle = lower(value); - buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); - return 8; - } - } - - $error_handler_class - - $(stream_glue) - } -} - -fn generate_callback_trait_rust_impl( - obj: &Object, - type_helper: &dyn TypeHelperRenderer, -) -> dart::Tokens { - let cls_name = &DartCodeOracle::class_name(obj.name()); - let impl_name = format!("_{cls_name}Impl"); - let finalizer_field = format!("_{cls_name}ImplFinalizer"); - let ffi_object_free_name = obj.ffi_object_free().name(); - let ffi_object_clone_name = obj.ffi_object_clone().name(); - let concrete_methods = obj - .methods() - .into_iter() - .map(|method| generate_callback_trait_rust_method(method, type_helper)); - - quote! { - final class $(&impl_name) implements $cls_name { - $(&impl_name)._internal(this._ptr) { - $(&finalizer_field).attach(this, _ptr, detach: this); - } - - static final Finalizer> $(&finalizer_field) = - Finalizer>((ptr) { - rustCall((status) => $ffi_object_free_name(ptr, status)); - }); - - Pointer _ptr; - bool _isDisposed = false; - - Pointer uniffiClonePointer() { - if (_isDisposed) { - throw StateError("Object has already been disposed"); - } - return rustCall((status) => $ffi_object_clone_name(_ptr, status)); - } - - void dispose() { - if (_isDisposed) { - return; - } - // Reserve status storage before closing, so allocation failure - // leaves the handle owned and disposal retryable. - final status = calloc(); - _isDisposed = true; - $(&finalizer_field).detach(this); - try { - $ffi_object_free_name(_ptr, status); - checkCallStatus(NullRustCallStatusErrorHandler(), status); - } finally { - calloc.free(status); - } - } - - $(for method in concrete_methods => $method) - } - } -} - -fn generate_callback_trait_rust_method( - method: &Method, - type_helper: &dyn TypeHelperRenderer, -) -> dart::Tokens { - let method_name = DartCodeOracle::fn_name(method.name()); - let dart_args = method - .arguments() - .iter() - .map(|arg| { - let arg_type = - arg.as_renderable(type_helper.get_ci()).render_type(&arg.as_type(), type_helper); - let arg_name = DartCodeOracle::var_name(arg.name()); - quote!($arg_type $arg_name) - }) - .collect::>(); - - let (ret, lifter) = if let Some(ret) = method.return_type() { - ( - ret.as_renderable(type_helper.get_ci()).render_type(ret, type_helper), - quote!($(ret.as_codetype(type_helper.get_ci()).lift())), - ) - } else { - (quote!(void), quote!((_) {})) - }; - - let error_handler = if let Some(error_type) = method.throws_type() { - let handler_name = DartCodeOracle::error_handler_name(error_type, type_helper.get_ci()); - quote!($(handler_name)) - } else { - quote!(null) - }; - - if method.is_async() { - let async_lifter = if let Some(ret_type) = method.return_type() { - match ret_type { - uniffi_bindgen::interface::Type::Object { .. } => { - quote!((ptr) => $lifter(Pointer.fromAddress(ptr))) - } - _ => lifter.clone(), - } - } else { - lifter.clone() - }; - - quote! { - @override - UniffiRustFuture<$ret> $method_name($(for a in &dart_args => $a,)) { - return uniffiRustCallAsync( - () => $(method.ffi_func().name())( - uniffiClonePointer(), - $(for arg in &method.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) - ), - $(DartCodeOracle::async_poll(method, type_helper.get_ci())), - $(DartCodeOracle::async_complete(method, type_helper.get_ci())), - $(DartCodeOracle::async_cancel(method, type_helper.get_ci())), - $(DartCodeOracle::async_free(method, type_helper.get_ci())), - $async_lifter, - $error_handler, - ); - } - } - } else if ret == quote!(void) { - quote! { - @override - $ret $method_name($(for a in &dart_args => $a,)) { - return rustCall((status) { - $(method.ffi_func().name())( - uniffiClonePointer(), - $(for arg in &method.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) - status - ); - }, $error_handler); - } - } - } else { - quote! { - @override - $ret $method_name($(for a in &dart_args => $a,)) { - return rustCallWithLifter( - (status) => $(method.ffi_func().name())( - uniffiClonePointer(), - $(for arg in &method.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) - status - ), - $lifter, - $error_handler - ); - } - } - } -} - -#[allow(unused_variables)] -pub fn generate_method(func: &Method, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - // if func.takes_self_by_arc() {} // TODO: Do something about this condition - let args = if func.arguments().is_empty() { - quote!() - } else { - quote!({$(for arg in &func.arguments() => - $(render_argument_param( - arg, - arg.as_renderable(type_helper.get_ci()).render_type(&arg.as_type(), type_helper), - type_helper.get_ci() - )), - )}) - }; - - let (ret, lifter) = if let Some(ret) = func.return_type() { - ( - ret.as_renderable(type_helper.get_ci()).render_type(ret, type_helper), - quote!($(ret.as_codetype(type_helper.get_ci()).lift())), - ) - } else { - (quote!(void), quote!((_) {})) - }; - - // Check if function can throw errors - let error_handler = if let Some(error_type) = func.throws_type() { - let handler_name = DartCodeOracle::error_handler_name(error_type, type_helper.get_ci()); - quote!($(handler_name)) - } else { - quote!(null) - }; - - if func.is_async() { - // For async methods returning objects, we need to convert the int pointer to Pointer - let async_lifter = if let Some(ret_type) = func.return_type() { - match ret_type { - uniffi_bindgen::interface::Type::Object { .. } => { - quote!((ptr) => $lifter(Pointer.fromAddress(ptr))) - } - _ => lifter.clone(), - } - } else { - lifter.clone() - }; - - quote!( - UniffiRustFuture<$ret> $(DartCodeOracle::fn_name(func.name()))($args) { - return uniffiRustCallAsync( - () => $(func.ffi_func().name())( - uniffiClonePointer(), - $(for arg in &func.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) - ), - $(DartCodeOracle::async_poll(func, type_helper.get_ci())), - $(DartCodeOracle::async_complete(func, type_helper.get_ci())), - $(DartCodeOracle::async_cancel(func, type_helper.get_ci())), - $(DartCodeOracle::async_free(func, type_helper.get_ci())), - $async_lifter, - $error_handler, - ); - } - - ) - } else if ret == quote!(void) { - quote!( - $ret $(DartCodeOracle::fn_name(func.name()))($args) { - return rustCall((status) { - $(func.ffi_func().name())( - uniffiClonePointer(), - $(for arg in &func.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) status - ); - }, $error_handler); - } - ) - } else { - quote!( - $ret $(DartCodeOracle::fn_name(func.name()))($args) { - return rustCallWithLifter( - (status) => $(func.ffi_func().name())( - uniffiClonePointer(), - $(for arg in &func.arguments() => $(DartCodeOracle::lower_arg_with_callback_handling(arg, type_helper.get_ci())),) status - ), - $lifter, - $error_handler - ); - } - ) - } -} - -fn generate_trait_helpers(obj: &Object, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let mut tokens = quote!(); - let mut generated_display = false; - let mut generated_debug = false; - let mut generated_eq = false; - let mut generated_hash = false; - - for trait_impl in obj.uniffi_traits() { - match trait_impl { - UniffiTrait::Display { fmt } => { - if generated_display { - continue; - } - let call = trait_method_call(fmt, type_helper, &[]); - tokens.append(quote! { - @override - String toString() { - return $call; - } - }); - generated_display = true; - } - UniffiTrait::Debug { fmt } => { - if generated_debug { - continue; - } - let call = trait_method_call(fmt, type_helper, &[]); - tokens.append(quote! { - String debugString() { - return $call; - } - }); - generated_debug = true; - } - UniffiTrait::Eq { eq, .. } => { - if generated_eq { - continue; - } - let call = trait_method_call(eq, type_helper, &[quote!(other)]); - tokens.append(quote! { - @override - bool operator ==(Object other) { - if (identical(this, other)) { - return true; - } - if (other is! $(DartCodeOracle::class_name(obj.name()))) { - return false; - } - return $call; - } - }); - generated_eq = true; - } - UniffiTrait::Hash { hash } => { - if generated_hash { - continue; - } - let call = trait_method_call(hash, type_helper, &[]); - tokens.append(quote! { - @override - int get hashCode { - return $call; - } - }); - generated_hash = true; - } - UniffiTrait::Ord { .. } => { - // Ord trait is not currently supported in Dart bindings - // Skip generation for now - } - } - } - - tokens -} - -fn trait_method_call( - method: &Method, - type_helper: &dyn TypeHelperRenderer, - arg_exprs: &[dart::Tokens], -) -> dart::Tokens { - assert_eq!(method.arguments().len(), arg_exprs.len()); - - let ffi_name = method.ffi_func().name(); - - let error_handler = if let Some(error_type) = method.throws_type() { - let handler_name = DartCodeOracle::error_handler_name(error_type, type_helper.get_ci()); - quote!($(handler_name)) - } else { - quote!(null) - }; - - let mut lowered_args = Vec::new(); - for (arg, expr) in method.arguments().into_iter().zip(arg_exprs.iter()) { - type_helper.include_once_check( - &arg.as_codetype(type_helper.get_ci()).canonical_name(), - &arg.as_type(), - ); - lowered_args.push(DartCodeOracle::type_lower_fn( - &arg.as_type(), - expr.clone(), - type_helper.get_ci(), - )); - } - - if let Some(ret) = method.return_type() { - type_helper - .include_once_check(&ret.as_codetype(type_helper.get_ci()).canonical_name(), ret); - let lifter = quote!($(ret.as_codetype(type_helper.get_ci()).lift())); - quote!( - rustCallWithLifter( - (status) => $ffi_name( - uniffiClonePointer(), - $(for arg in lowered_args => $arg,) - status - ), - $lifter, - $error_handler - ) - ) - } else { - quote!( - rustCall((status) { - $ffi_name( - uniffiClonePointer(), - $(for arg in lowered_args => $arg,) - status - ); - }, $error_handler) - ) - } -} - -fn generate_trait_object(obj: &Object, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - type_helper.include_once_check(obj.name(), &obj.as_type()); - - let cls_name = &DartCodeOracle::class_name(obj.name()); - let ffi_converter_name = &obj.as_codetype(type_helper.get_ci()).ffi_converter_name(); - let impl_name = format!("_{cls_name}Impl"); - let finalizer_field = format!("_{cls_name}ImplFinalizer"); - - let ffi_object_free_name = obj.ffi_object_free().name(); - let ffi_object_clone_name = obj.ffi_object_clone().name(); - - let abstract_methods = - obj.methods().into_iter().map(|method| generate_interface_method(method, type_helper)); - - let concrete_methods = - obj.methods().into_iter().map(|method| generate_method(method, type_helper)); - - quote! { - abstract class $cls_name { - factory $cls_name.lift(Pointer ptr) { - // UniFFI 0.30.0: Check if handle is from foreign side (lowest bit set) - final handle = ptr.address; - final isForeign = (handle & 0x1) != 0; - - if (isForeign) { - // Foreign (Dart-side) trait implementations not yet supported - throw UnsupportedError("Foreign trait implementations are not yet supported in uniffi-dart"); - } - - // Rust-generated handle (lowest bit is 0) - return $(&impl_name)._internal(ptr); - } - - void dispose(); - - $(for method in abstract_methods => $method) - } - - class $ffi_converter_name { - static $cls_name lift(Pointer ptr) { - return $cls_name.lift(ptr); - } - - static Pointer lower($cls_name value) { - if (value is $(&impl_name)) { - return value.uniffiClonePointer(); - } - throw UnsupportedError("Only Rust-implemented $cls_name values are supported."); - } - - static int allocationSize($cls_name value) { - if (value is $(&impl_name)) { - return $(&impl_name).allocationSize(value); - } - throw UnsupportedError("Only Rust-implemented $cls_name values are supported."); - } - - static LiftRetVal<$cls_name> read(Uint8List buf) { - final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); - final pointer = Pointer.fromAddress(handle); - return LiftRetVal($cls_name.lift(pointer), 8); - } - - static int write($cls_name value, Uint8List buf) { - final handle = lower(value); - buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); - return 8; - } - } - - final class $(&impl_name) implements $cls_name { - $(&impl_name)._internal(this._ptr) { - $(&finalizer_field).attach(this, _ptr, detach: this); - } - - static final Finalizer> $(&finalizer_field) = - Finalizer>((ptr) { - rustCall((status) => $ffi_object_free_name(ptr, status)); - }); - - Pointer _ptr; - bool _isDisposed = false; - - static int allocationSize($(&impl_name) _) => 8; - - Pointer uniffiClonePointer() { - if (_isDisposed) { - throw StateError("Object has already been disposed"); - } - return rustCall((status) => $ffi_object_clone_name(_ptr, status)); - } - - @override - void dispose() { - if (_isDisposed) { - return; - } - // Reserve status storage before closing, so allocation failure - // leaves the handle owned and disposal retryable. - final status = calloc(); - _isDisposed = true; - $(&finalizer_field).detach(this); - try { - $ffi_object_free_name(_ptr, status); - checkCallStatus(NullRustCallStatusErrorHandler(), status); - } finally { - calloc.free(status); - } - } - - $(for method in concrete_methods => $method) - } - } -} - -fn generate_object_interface( - obj: &Object, - interface_name: &str, - type_helper: &dyn TypeHelperRenderer, -) -> dart::Tokens { - let method_tokens: Vec = obj - .methods() - .into_iter() - .map(|method| generate_interface_method(method, type_helper)) - .collect(); - - if method_tokens.is_empty() { - quote! { - abstract class $(interface_name) {} - } - } else { - quote! { - abstract class $(interface_name) { - $(for method in method_tokens => $method) - } - } - } -} - -fn generate_interface_method( - method: &Method, - type_helper: &dyn TypeHelperRenderer, -) -> dart::Tokens { - let params = if method.arguments().is_empty() { - quote!() - } else { - quote!({$(for arg in method.arguments() => - $(render_argument_param( - arg, - arg.as_renderable(type_helper.get_ci()).render_type(&arg.as_type(), type_helper), - type_helper.get_ci() - )), - )}) - }; - let ret_type = method_return_type_tokens(method, type_helper); - let method_name = DartCodeOracle::fn_name(method.name()); - - quote!( - $ret_type $method_name($params); - ) -} - -fn method_return_type_tokens( - method: &Method, - type_helper: &dyn TypeHelperRenderer, -) -> dart::Tokens { - let base = if let Some(ret) = method.return_type() { - ret.as_renderable(type_helper.get_ci()).render_type(ret, type_helper) - } else { - quote!(void) - }; - - if method.is_async() { - quote!(UniffiRustFuture<$base>) - } else { - base - } -} diff --git a/uniffi/dart/src/gen/oracle.rs b/uniffi/dart/src/gen/oracle.rs deleted file mode 100644 index 1485fd8aa..000000000 --- a/uniffi/dart/src/gen/oracle.rs +++ /dev/null @@ -1,756 +0,0 @@ -use genco::lang::dart; -use genco::quote; -use heck::{ToLowerCamelCase, ToUpperCamelCase}; -use uniffi_bindgen::interface::{ - Argument, AsType, Callable, FfiType, Object, ObjectImpl, TraitKind, Type, -}; -use uniffi_bindgen::ComponentInterface; - -// use super::render::{AsRenderable, Renderable}; -use super::{callback_interface, compounds, custom, enums, objects, records}; -use crate::gen::{primitives, CodeType}; - -pub struct DartCodeOracle; - -impl DartCodeOracle { - /// The namespace of the crate that defines `ty`, if it is not `ci`'s crate. - pub fn external_namespace(ty: &Type, ci: &ComponentInterface) -> Option { - ci.is_external(ty).then(|| { - ci.namespace_for_type(ty).expect("external type should have a namespace").to_string() - }) - } - - /// The prefix the library of `namespace` is imported under. - /// - /// Another crate's library is always imported under a prefix, so a local type of the same - /// name cannot shadow its types. The bare namespace would itself be shadowed by a member of - /// the same name, such as a record field `net` holding `net` types; generated members are - /// lowerCamelCase, so they never contain the underscore. - pub fn import_prefix(namespace: &str) -> String { - format!("uniffi_{namespace}") - } - - /// Refers to `name` through the library of `namespace` that declares it, if it is not local. - pub fn qualify(namespace: Option<&str>, name: String) -> String { - match namespace { - Some(namespace) => format!("{}.{name}", Self::import_prefix(namespace)), - None => name, - } - } - - /// The canonical name of a type from the library of `namespace`, unique within this one. - pub fn qualify_canonical(namespace: Option<&str>, canonical: String) -> String { - match namespace { - Some(namespace) => format!("{}{canonical}", namespace.to_upper_camel_case()), - None => canonical, - } - } - - /// The handler that lifts `error_type` when a call throws it. - pub fn error_handler_name(error_type: &Type, ci: &ComponentInterface) -> String { - let error_name = Self::class_name(error_type.name().unwrap_or("UnknownError")); - Self::qualify( - Self::external_namespace(error_type, ci).as_deref(), - format!("{}ErrorHandler", error_name.to_lower_camel_case()), - ) - } - - /// Sanitize a Dart identifier, appending an underscore if it's a reserved keyword. - pub fn sanitize_identifier(id: &str) -> String { - if Self::is_reserved_identifier(id) { - format!("{id}_") - } else { - id.to_string() - } - } - - /// Check if the given identifier is a reserved keyword in Dart. - pub fn is_reserved_identifier(id: &str) -> bool { - RESERVED_IDENTIFIERS.contains(&id) - } - - /// Get the idiomatic Dart rendering of a class name (for enums, records, errors, etc). - pub fn class_name(nm: &str) -> String { - let name = Self::sanitize_identifier(&nm.to_upper_camel_case()); - // Handle the special case where the name is exactly "Error" to avoid conflicts with Dart's Exception - if name == "Error" { - "ErrorException".to_string() - } else { - // Only replace "Error" at the end of the name for other cases - match name.strip_suffix("Error") { - None => name, - Some(stripped) => format!("{stripped}Exception"), - } - } - } - - /// Replace any occurrence of `Error` with `Exception` to avoid Dart naming conflicts. - pub fn exception_safe_name(name: &str) -> String { - name.replace("Error", "Exception") - } - - /// Get the idiomatic Dart rendering of a function name. - pub fn fn_name(nm: &str) -> String { - Self::sanitize_identifier(&nm.to_lower_camel_case()) - } - - /// Get the idiomatic Dart rendering of a variable name. - pub fn var_name(nm: &str) -> String { - Self::sanitize_identifier(&nm.to_lower_camel_case()) - } - - /// Get the idiomatic Dart rendering of an individual enum variant. - pub fn enum_variant_name(nm: &str) -> String { - Self::sanitize_identifier(&nm.to_lower_camel_case()) - } - - /// Get the idiomatic Dart rendering of an FFI callback function name - pub fn ffi_callback_name(nm: &str) -> String { - format!("Pointer>", Self::callback_name(&nm.to_upper_camel_case())) - } - - /// Helper method to generate the callback name based on `Type`. - fn callback_name(name: &str) -> String { - format!("Uniffi{}", name.to_upper_camel_case()) - } - - ///// Get the idiomatic Dart rendering of an exception name - // pub fn error_name(nm: &str) -> String { - // let name = Self::class_name(nm); - // match name.strip_suffix("Error") { - // None => name, - // Some(stripped) => format!("{stripped}Exception"), - // } - // } - - pub fn infer_ffi_module(ci: &ComponentInterface, fallback: F) -> String - where - F: FnOnce() -> String, - { - ci.iter_ffi_function_definitions() - .next() - .and_then(|f| { - let name = f.name(); - name.strip_prefix("uniffi_") - .and_then(|rest| rest.split("_fn_").next()) - .map(|s| s.replace('-', "_")) - }) - .unwrap_or_else(|| { - let fallback_value = fallback(); - fallback_value.replace('-', "_") - }) - } - - // TODO: Replace instances of `generate_ffi_dart_type` with ffi_type_label - pub fn ffi_dart_type_label(ffi_type: Option<&FfiType>) -> dart::Tokens { - if let Some(ret_type) = ffi_type { - match ret_type { - FfiType::Int8 => quote!(int), - FfiType::UInt8 => quote!(int), - FfiType::Int16 => quote!(int), - FfiType::UInt16 => quote!(int), - FfiType::Int32 => quote!(int), - FfiType::UInt32 => quote!(int), - FfiType::Int64 => quote!(int), - FfiType::UInt64 => quote!(int), - FfiType::Float32 => quote!(double), - FfiType::Float64 => quote!(double), - FfiType::RustBuffer(_) => quote!(RustBuffer), - FfiType::ForeignBytes => quote!(ForeignBytes), - FfiType::Handle => quote!(Pointer), - FfiType::Callback(name) => quote!($(Self::ffi_callback_name(name))), - FfiType::Reference(inner) => quote!($(Self::ffi_type_label_by_reference(inner))), - _ => panic!("Unimplemented FfiType: {ret_type:?}"), // Fallback implementation - } - } else { - quote!(void) - } - } - - pub fn ffi_native_type_label(ffi_ret_type: Option<&FfiType>) -> dart::Tokens { - if let Some(ret_type) = ffi_ret_type { - match ret_type { - FfiType::Int8 => quote!(Int8), - FfiType::UInt8 => quote!(Uint8), - FfiType::Int16 => quote!(Int16), - FfiType::UInt16 => quote!(Uint16), - FfiType::Int32 => quote!(Int32), - FfiType::UInt32 => quote!(Uint32), - FfiType::Int64 => quote!(Int64), - FfiType::UInt64 => quote!(Uint64), - FfiType::Float32 => quote!(Float), - FfiType::Float64 => quote!(Double), - FfiType::RustBuffer(_) => quote!(RustBuffer), - FfiType::ForeignBytes => quote!(ForeignBytes), - FfiType::Handle => quote!(Pointer), - FfiType::Callback(name) => quote!($(Self::ffi_callback_name(name))), - FfiType::Reference(inner) => quote!($(Self::ffi_type_label_by_reference(inner))), - _ => panic!("Unimplemented FfiType: {ret_type:?}"), // Fallback implementation - } - } else { - quote!(void) - } - } - - fn ffi_type_label_by_reference(ffi_type: &FfiType) -> dart::Tokens { - match ffi_type { - FfiType::Int8 => quote!(Int8), - FfiType::UInt8 => quote!(Uint8), - FfiType::Int16 => quote!(Int16), - FfiType::UInt16 => quote!(Uint16), - FfiType::Int32 => quote!(Int32), - FfiType::UInt32 => quote!(Uint32), - FfiType::Int64 => quote!(Int64), - FfiType::UInt64 => quote!(Uint64), - FfiType::Float32 => quote!(Float), - FfiType::Float64 => quote!(Double), - FfiType::RustBuffer(_) => quote!(RustBuffer), - FfiType::Callback(name) => quote!(Pointer<$(Self::ffi_callback_name(name))>), - FfiType::Struct(name) => quote!(Pointer<$(Self::ffi_struct_name(name))>), - _ => quote!(Pointer), // Fallback implementation - } - } - - pub fn ffi_struct_name(name: &str) -> dart::Tokens { - quote!($(format!("Uniffi{}", name.to_upper_camel_case()))) - } - - // pub fn convert_from_rust_buffer(ty: &Type, inner: dart::Tokens) -> dart::Tokens { - // match ty { - // Type::Object { .. } => inner, - // Type::String | Type::Optional { .. } => quote!($(inner).asUint8List()), - // _ => inner, - // } - // } - - // pub fn convert_to_rust_buffer(ty: &Type, inner: dart::Tokens) -> dart::Tokens { - // match ty { - // Type::Object { .. } => inner, - // Type::String | Type::Optional { .. } | Type::Enum { .. } | Type::Sequence { .. } => { - // quote!(toRustBuffer($inner)) - // } - // _ => inner, - // } - // } - - pub fn type_lower_fn(ty: &Type, inner: dart::Tokens, ci: &ComponentInterface) -> dart::Tokens { - match ty { - Type::Int8 - | Type::Int16 - | Type::Int32 - | Type::Int64 - | Type::UInt8 - | Type::UInt16 - | Type::UInt32 - | Type::UInt64 => { - quote!($(ty.as_codetype(ci).ffi_converter_name()).lower($inner)) - } - Type::Float32 | Type::Float64 => inner, - Type::Boolean - | Type::Duration - | Type::String - | Type::Object { .. } - | Type::Enum { .. } - | Type::Optional { .. } - | Type::Record { .. } => { - quote!($(ty.as_codetype(ci).ffi_converter_name()).lower($inner)) - } - _ => quote!($(ty.as_codetype(ci).ffi_converter_name()).lower($inner)), // Fallback implementation - } - } - - /// With @Native, async functions are called directly by name - pub fn async_poll(callable: impl Callable, ci: &ComponentInterface) -> dart::Tokens { - let ffi_func = callable.ffi_rust_future_poll(ci); - quote!($ffi_func) - } - - /// With @Native, async functions are called directly by name - pub fn async_complete(callable: impl Callable, ci: &ComponentInterface) -> dart::Tokens { - let ffi_func = callable.ffi_rust_future_complete(ci); - quote!($ffi_func) - } - - /// With @Native, async functions are called directly by name - pub fn async_cancel(callable: impl Callable, ci: &ComponentInterface) -> dart::Tokens { - let ffi_func = callable.ffi_rust_future_cancel(ci); - quote!($ffi_func) - } - - /// With @Native, async functions are called directly by name - pub fn async_free(callable: impl Callable, ci: &ComponentInterface) -> dart::Tokens { - let ffi_func = callable.ffi_rust_future_free(ci); - quote!($ffi_func) - } - - /// Get the idiomatic Dart rendering of a class name based on `Type`. - pub fn dart_type_label(type_: Option<&Type>, ci: &ComponentInterface) -> dart::Tokens { - if let Some(ret_type) = type_ { - match ret_type { - Type::UInt8 - | Type::UInt16 - | Type::UInt32 - | Type::UInt64 - | Type::Int8 - | Type::Int16 - | Type::Int32 - | Type::Int64 => quote!(int), - Type::Float32 | Type::Float64 => quote!(double), - Type::Boolean => quote!(bool), - Type::Bytes => quote!(Uint8List), - Type::String => quote!(String), - Type::Timestamp => quote!(DateTime), - Type::Duration => quote!(Duration), - // Reference types - Type::Object { .. } - | Type::Enum { .. } - | Type::Record { .. } - | Type::Custom { .. } => { - quote!($(ret_type.as_codetype(ci).type_label())) - } - Type::Optional { inner_type } => { - let inner = DartCodeOracle::dart_type_label(Some(inner_type), ci); - quote!($inner?) - } - Type::Sequence { inner_type } => { - let inner = DartCodeOracle::dart_type_label(Some(inner_type), ci); - quote!(List<$inner>) - } - Type::Map { key_type, value_type, .. } => { - let key = DartCodeOracle::dart_type_label(Some(key_type), ci); - let value = DartCodeOracle::dart_type_label(Some(value_type), ci); - quote!(Map<$key, $value>) - } - _ => quote!(dynamic), - } - } else { - quote!(void) - } - } - - /// Get the native Dart FFI type rendering based on `Type`. - pub fn native_type_label( - native_ret_type: Option<&Type>, - ci: &ComponentInterface, - ) -> dart::Tokens { - if let Some(ret_type) = native_ret_type { - match ret_type { - Type::UInt8 => quote!(Uint8), - Type::UInt16 => quote!(Uint16), - Type::UInt32 => quote!(Uint32), - Type::UInt64 => quote!(Uint64), - Type::Int8 => quote!(Int8), - Type::Int16 => quote!(Int16), - Type::Int32 => quote!(Int32), - Type::Int64 => quote!(Int64), - Type::Float32 => quote!(Float), - Type::Float64 => quote!(Double), - Type::Boolean => quote!(Int8), - Type::Bytes => quote!(RustBuffer), - Type::String => quote!(RustBuffer), - Type::Timestamp => quote!(Int64), - Type::Duration => quote!(Int64), - Type::Optional { inner_type } => match **inner_type { - Type::String => quote!(RustBuffer), - _ => quote!(RustBuffer), - }, - Type::Sequence { .. } => quote!(RustBuffer), - Type::Map { .. } => quote!(RustBuffer), - Type::Object { .. } => quote!(Pointer), - Type::Enum { .. } => quote!(Int32), - Type::Record { .. } => quote!(RustBuffer), - Type::Custom { .. } => quote!($(ret_type.as_codetype(ci).type_label())), - _ => quote!(Pointer), - } - } else { - quote!(Void) - } - } - - /// Get the native Dart FFI type rendering based on `Type`. - pub fn native_dart_type_label( - native_ret_type: Option<&Type>, - ci: &ComponentInterface, - ) -> dart::Tokens { - if let Some(ret_type) = native_ret_type { - match ret_type { - Type::UInt8 - | Type::UInt16 - | Type::UInt32 - | Type::UInt64 - | Type::Int8 - | Type::Int16 - | Type::Int32 - | Type::Int64 => quote!(int), // Adjust based on actual FFI size - Type::Float32 => quote!(double), - Type::Float64 => quote!(double), - Type::Boolean => quote!(int), - Type::Bytes => quote!(RustBuffer), - Type::String => quote!(RustBuffer), - Type::Timestamp => quote!(int), - Type::Duration => quote!(int), - Type::Optional { inner_type } => match **inner_type { - Type::String => quote!(RustBuffer), - _ => quote!(RustBuffer), - }, - Type::Sequence { .. } => quote!(RustBuffer), - Type::Map { .. } => quote!(RustBuffer), - Type::Object { .. } => quote!(Pointer), - Type::Enum { .. } => quote!(int), - Type::Record { .. } => quote!(RustBuffer), - Type::Custom { .. } => quote!($(ret_type.as_codetype(ci).type_label())), - _ => quote!(dynamic), - } - } else { - quote!(void) - } - } - - // Method to get the appropriate callback parameter type - pub fn callback_param_type( - arg_type: &Type, - arg_name: &str, - ci: &ComponentInterface, - ) -> dart::Tokens { - let type_label = DartCodeOracle::native_dart_type_label(Some(arg_type), ci); - quote!($type_label $arg_name) - } - - // Method to generate code for handling callback return values - pub fn callback_return_handling( - ret_type: &Type, - method_name: &str, - args: Vec, - ci: &ComponentInterface, - ) -> dart::Tokens { - match ret_type { - Type::Boolean => { - // For boolean return values - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.value = result ? 1 : 0; - ) - } - Type::UInt8 - | Type::UInt16 - | Type::UInt32 - | Type::UInt64 - | Type::Int8 - | Type::Int16 - | Type::Int32 - | Type::Int64 => { - // For primitive integer return values - let lowered = ret_type.as_codetype(ci).ffi_converter_name(); - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.value = $lowered.lower(result); - ) - } - Type::Float32 | Type::Float64 => { - // For float return values - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.value = result; - ) - } - Type::Optional { .. } => { - // For optional return values, use the Optional FfiConverter which already - // handles the discriminant byte encoding correctly. - let ffi_converter = ret_type.as_codetype(ci).ffi_converter_name(); - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - if (result == null) { - outReturn.ref = toRustBuffer(Uint8List.fromList([0])); - } else { - final lowered = $ffi_converter.lower(result); - outReturn.ref = toRustBuffer(lowered.asUint8List()); - } - ) - } - Type::String => { - // For string return values - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.ref = FfiConverterString.lower(result); - status.code = CALL_SUCCESS; - ) - } - Type::Object { .. } => { - let lowered = ret_type.as_codetype(ci).ffi_converter_name(); - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.value = $lowered.lower(result); - ) - } - Type::Sequence { inner_type } => { - if let Type::Int32 = **inner_type { - // For int32 sequence return values - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.ref = FfiConverterSequenceInt32.lower(result); - ) - } else { - // For other sequence types - let lowered = ret_type.as_codetype(ci).ffi_converter_name(); - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.ref = $lowered.lower(result); - ) - } - } - _ => { - // For other return types - let lowered = ret_type.as_codetype(ci).ffi_converter_name(); - quote!( - final result = obj.$method_name($(for arg in &args => $arg,)); - outReturn.ref = $lowered.lower(result); - ) - } - } - } - - // Method to get the appropriate return type for callback functions - pub fn callback_out_return_type(ret_type: Option<&Type>) -> dart::Tokens { - if let Some(ret) = ret_type { - match ret { - Type::UInt8 => quote!(Pointer), - Type::UInt16 => quote!(Pointer), - Type::UInt32 => quote!(Pointer), - Type::UInt64 => quote!(Pointer), - Type::Int8 => quote!(Pointer), - Type::Int16 => quote!(Pointer), - Type::Int32 => quote!(Pointer), - Type::Int64 => quote!(Pointer), - Type::Float32 => quote!(Pointer), - Type::Float64 => quote!(Pointer), - Type::Boolean => quote!(Pointer), - Type::Object { .. } => quote!(Pointer>), - _ => quote!(Pointer), - } - } else { - quote!(Pointer) - } - } - - // Method to handle void return values in callbacks - pub fn callback_void_handling(method_name: &str, args: Vec) -> dart::Tokens { - quote!( - obj.$method_name($(for arg in &args => $arg,)); - status.code = CALL_SUCCESS; - ) - } - - // Method to get the appropriate lift expression for callback arguments with indexed variable names - pub fn callback_arg_lift_indexed( - arg_type: &Type, - arg_name: &str, - arg_idx: usize, - ci: &ComponentInterface, - ) -> dart::Tokens { - // Use index-based variable names to avoid conflicts - if let Type::Boolean = arg_type { - quote!(final bool_arg$(arg_idx) = $arg_name == 1;) - } else if let Type::Enum { .. } = arg_type { - let converter = arg_type.as_codetype(ci).ffi_converter_name(); - quote!(final arg$(arg_idx) = $converter.read(createUint8ListFromInt($arg_name)).value;) - } else if let Type::Bytes = arg_type { - quote!(final arg$(arg_idx) = FfiConverterUint8List.lift($arg_name);) - } else if let Type::String = arg_type { - quote!(final arg$(arg_idx) = FfiConverterString.lift($arg_name);) - } else if let Type::Optional { inner_type } = arg_type { - if let Type::String = **inner_type { - quote!(final arg$(arg_idx) = FfiConverterOptionalString.lift($arg_name);) - } else { - let converter = arg_type.as_codetype(ci).ffi_converter_name(); - quote!(final arg$(arg_idx) = $converter.lift($arg_name);) - } - } else if let Type::Sequence { inner_type } = arg_type { - if let Type::Int32 = **inner_type { - quote!(final arg$(arg_idx) = FfiConverterSequenceInt32.lift($arg_name);) - } else { - let converter = arg_type.as_codetype(ci).ffi_converter_name(); - quote!(final arg$(arg_idx) = $converter.lift($arg_name);) - } - } else { - let converter = arg_type.as_codetype(ci).ffi_converter_name(); - quote!(final arg$(arg_idx) = $converter.lift($arg_name);) - } - } - - // Method to get argument name for a callback method based on type and index - pub fn callback_arg_name(arg_type: &Type, arg_idx: usize) -> dart::Tokens { - if let Type::Boolean = arg_type { - quote!(bool_arg$(arg_idx)) - } else { - quote!(arg$(arg_idx)) - } - } - - /// Lower argument with special handling for callback traits - pub fn lower_arg_with_callback_handling( - arg: &Argument, - ci: &ComponentInterface, - ) -> dart::Tokens { - // Borrowed `&[u8]` / `[ByRef] bytes` arguments take the `ForeignBytes` - // FFI path, not the owned `RustBuffer` path. uniffi 0.32 selects - // `FfiType::ForeignBytes` for these (see `Argument::is_borrowed_bytes`), - // so the FFI signature already expects `ForeignBytes`; lower the - // `Uint8List` into one instead of a `RustBuffer`. "Borrowed" is the - // Rust view (it borrows for the call rather than owning a RustBuffer); - // the emitted `lowerForeignBytes` still copies into native memory since - // a GC-managed `Uint8List` has no stable address. Mirrors the ByRef-bytes - // converter in uniffi's Kotlin/Python backends. - if arg.is_borrowed_bytes() { - return quote!(lowerForeignBytes($(Self::var_name(arg.name())))); - } - let base_lower = - Self::type_lower_fn(&arg.as_type(), quote!($(Self::var_name(arg.name()))), ci); - match arg.as_type() { - Type::Object { - imp: ObjectImpl::Trait(TraitKind::Both | TraitKind::ForeignOnly), - .. - } => base_lower, - Type::CallbackInterface { .. } => quote!($base_lower.address), - _ => base_lower, - } - } - - pub fn object_interface_name(_ci: &ComponentInterface, obj: &Object) -> String { - let class_name = Self::class_name(obj.name()); - if obj.has_callback_interface() || obj.is_trait_interface() { - class_name - } else { - format!("{class_name}Interface") - } - } - - pub fn trait_interface_name(ci: &ComponentInterface, name: &str) -> String { - if let Some(obj) = ci.get_object_definition(name) { - let class_name = Self::class_name(obj.name()); - if obj.has_callback_interface() || obj.is_trait_interface() { - class_name - } else { - Self::object_interface_name(ci, obj) - } - } else if let Some(callback) = ci.get_callback_interface_definition(name) { - Self::class_name(callback.name()) - } else { - Self::class_name(name) - } - } -} - -// https://dart.dev/guides/language/language-tour#keywords -pub static RESERVED_IDENTIFIERS: [&str; 63] = [ - "abstract", - "as", - "assert", - "async", - "await", - "break", - "case", - "catch", - "class", - "const", - "continue", - "covariant", - "default", - "deferred", - "do", - "dynamic", - "else", - "enum", - "export", - "extends", - "extension", - "external", - "factory", - "false", - "final", - "finally", - "for", - "Function", - "get", - "hide", - "if", - "implements", - "import", - "in", - "interface", - "is", - "late", - "library", - "mixin", - "new", - "null", - "on", - "operator", - "part", - "required", - "rethrow", - "return", - "set", - "show", - "static", - "super", - "switch", - "sync", - "this", - "throw", - "true", - "try", - "typedef", - "var", - "void", - "while", - "with", - "yield", -]; - -pub trait AsCodeType { - /// The code type of this type as `ci`'s library sees it. - fn as_codetype(&self, ci: &ComponentInterface) -> Box; -} - -impl AsCodeType for T { - fn as_codetype(&self, ci: &ComponentInterface) -> Box { - let namespace = DartCodeOracle::external_namespace(&self.as_type(), ci); - match self.as_type() { - Type::UInt8 => Box::new(primitives::UInt8CodeType), - Type::Int8 => Box::new(primitives::Int8CodeType), - Type::UInt16 => Box::new(primitives::UInt16CodeType), - Type::Int16 => Box::new(primitives::Int16CodeType), - Type::UInt32 => Box::new(primitives::UInt32CodeType), - Type::Int32 => Box::new(primitives::Int32CodeType), - Type::UInt64 => Box::new(primitives::UInt64CodeType), - Type::Int64 => Box::new(primitives::Int64CodeType), - Type::Float32 => Box::new(primitives::Float32CodeType), - Type::Float64 => Box::new(primitives::Float64CodeType), - Type::Boolean => Box::new(primitives::BooleanCodeType), - Type::String => Box::new(primitives::StringCodeType), - Type::Duration => Box::new(primitives::DurationCodeType), - Type::Bytes => Box::new(primitives::BytesCodeType), - Type::Object { name, imp, .. } => { - Box::new(objects::ObjectCodeType::new(name, imp, namespace)) - } - Type::Optional { inner_type } => { - Box::new(compounds::OptionalCodeType::new(self.as_type(), *inner_type, ci)) - } - Type::Sequence { inner_type } => { - Box::new(compounds::SequenceCodeType::new(self.as_type(), *inner_type, ci)) - } - Type::Map { key_type, value_type, .. } => { - Box::new(compounds::MapCodeType::new(self.as_type(), *key_type, *value_type, ci)) - } - Type::Enum { name, .. } => Box::new(enums::EnumCodeType::new(name, namespace)), - Type::Record { name, .. } => Box::new(records::RecordCodeType::new(name, namespace)), - Type::CallbackInterface { name, .. } => Box::new( - callback_interface::CallbackInterfaceCodeType::new(name, self.as_type(), namespace), - ), - Type::Custom { name, module_path, builtin } => { - Box::new(custom::CustomCodeType::new(name, module_path, builtin, namespace)) - } - _ => todo!("As Type for Type::{:?}", self.as_type()), - } - } -} diff --git a/uniffi/dart/src/gen/primitives/boolean.rs b/uniffi/dart/src/gen/primitives/boolean.rs deleted file mode 100644 index bd44095c0..000000000 --- a/uniffi/dart/src/gen/primitives/boolean.rs +++ /dev/null @@ -1,41 +0,0 @@ -use genco::lang::dart; - -use super::paste; -use crate::gen::quote; -use crate::gen::render::{Renderable, TypeHelperRenderer}; - -impl_code_type_for_primitive!(BooleanCodeType, "bool", "Bool"); - -impl Renderable for BooleanCodeType { - fn render_type_helper(&self, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - quote! { - class FfiConverterBool { - - static bool lift( int value) { - return value == 1; - } - - static int lower( bool value) { - return value ? 1 :0; - } - - static LiftRetVal read( Uint8List buf) { - return LiftRetVal(FfiConverterBool.lift(buf.first), 1); - } - - static RustBuffer lowerIntoRustBuffer( bool value) { - return toRustBuffer(Uint8List.fromList([FfiConverterBool.lower(value)])); - } - - static int allocationSize([bool value = false]) { - return 1; - } - - static int write( bool value, Uint8List buf) { - buf.setAll(0, [value ? 1 : 0]); - return allocationSize(); - } - } - } - } -} diff --git a/uniffi/dart/src/gen/primitives/duration.rs b/uniffi/dart/src/gen/primitives/duration.rs deleted file mode 100644 index f6c7b815d..000000000 --- a/uniffi/dart/src/gen/primitives/duration.rs +++ /dev/null @@ -1,44 +0,0 @@ -use genco::lang::dart; - -use super::paste; -use crate::gen::quote; -use crate::gen::render::{Renderable, TypeHelperRenderer}; - -impl_code_type_for_primitive!(DurationCodeType, "Duration", "Duration"); - -impl Renderable for DurationCodeType { - fn render_type_helper(&self, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - quote! { - class FfiConverterDuration { - static Duration lift( RustBuffer buf) { - return FfiConverterDuration.read(buf.asUint8List()).value; - } - - static RustBuffer lower( Duration value) { - final buf = Uint8List(allocationSize(value)); - write(value, buf); - return toRustBuffer(buf); - } - - static LiftRetVal read( Uint8List buf) { - final bytes = buf.buffer.asByteData(buf.offsetInBytes, 12); - final seconds = bytes.getUint64(0); - final micros = (bytes.getUint32(8) ~/ 1000); - return LiftRetVal(Duration(seconds: seconds, microseconds: micros), 12); - } - - static int allocationSize([Duration value = const Duration()]) { - return 12; - } - - static int write( Duration value, Uint8List buf) { - final bytes = buf.buffer.asByteData(buf.offsetInBytes, 12); - bytes.setUint64(0, value.inSeconds); - final ms = (value.inMicroseconds - (value.inSeconds * 1000000)) * 1000; - bytes.setUint32(8, ms.toInt()); - return 12; - } - } - } - } -} diff --git a/uniffi/dart/src/gen/primitives/macros.rs b/uniffi/dart/src/gen/primitives/macros.rs deleted file mode 100644 index a7d977fb8..000000000 --- a/uniffi/dart/src/gen/primitives/macros.rs +++ /dev/null @@ -1,155 +0,0 @@ -macro_rules! impl_code_type_for_primitive { - ($T:ty, $class_name:literal, $canonical_name:literal) => { - paste! { - #[derive(Debug)] - pub struct $T; - - impl crate::gen::CodeType for $T { - fn type_label(&self,) -> String { - $class_name.into() - } - - fn literal(&self, literal: &uniffi_bindgen::interface::Literal) -> String { - $crate::gen::primitives::render_literal(&literal) - } - - fn canonical_name(&self,) -> String { - $canonical_name.into() - } - - fn ffi_converter_name(&self) -> String { - format!("FfiConverter{}", self.canonical_name()) - } - } - } - }; -} - -macro_rules! impl_renderable_for_primitive { - (BytesCodeType, $class_name:literal, $canonical_name:literal) => { - impl Renderable for BytesCodeType { - fn render_type_helper(&self, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let cl_name = &self.ffi_converter_name(); - let type_signature = &self.type_label(); - - quote! { - class $cl_name { - static $type_signature lift(RustBuffer value) { - return $cl_name.read(value.asUint8List()).value; - } - - static LiftRetVal<$type_signature> read(Uint8List buf) { - final length = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); - // Copy rather than view: the RustBuffer this reads from is - // freed as soon as lifting finishes, and a view would dangle. - final bytes = buf.sublist(4, 4 + length); - return LiftRetVal(bytes, length + 4); - } - - static RustBuffer lower($type_signature value) { - final buf = Uint8List(allocationSize(value)); - write(value, buf); - return toRustBuffer(buf); - } - - static int allocationSize([$type_signature? value]) { - if (value == null) { - return 4; - } - return 4 + value.length; - } - - static int write($type_signature value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, value.length); - buf.setRange(4, 4 + value.length, value); - return 4 + value.length; - } - } - } - } - } - }; - ($T:ty, $class_name:literal, $canonical_name:literal, $allocation_size:literal) => { - impl Renderable for $T { - fn render_type_helper(&self, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - use crate::gen::code_type::CodeType; - let endian = (if $canonical_name.contains("Float") { - ", Endian.little" - } else { - "" - }); - - let cl_name = &self.ffi_converter_name(); - let type_signature = &self.type_label(); - let conversion_name = &$canonical_name - .replace("UInt", "Uint") - .replace("Double", "Float"); - - quote! { - class $cl_name { - // According to generated funtion signatures, we won't need to convert number types - static $type_signature lift($type_signature value) => value; - - - static LiftRetVal<$type_signature> read(Uint8List buf) { - return LiftRetVal(buf.buffer.asByteData(buf.offsetInBytes).get$conversion_name(0), $allocation_size); - } - - static $type_signature lower($type_signature value) => value; - - - static int allocationSize([$type_signature value = 0]) { - return $allocation_size; - } - - static int write($type_signature value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).set$conversion_name(0, value$endian); - return $cl_name.allocationSize(); - } - - } - } - } - } - }; - ($T:ty, $class_name:literal, $canonical_name:literal, $allocation_size:literal, $min_value:literal, $max_value:literal, $type_name:literal) => { - impl Renderable for $T { - fn render_type_helper(&self, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let cl_name = &self.ffi_converter_name(); - let type_signature = &self.type_label(); - let conversion_name = &$canonical_name - .replace("UInt", "Uint") - .replace("Double", "Float"); - - let error_message = - format!("\"Value out of range for {}: \" + value.toString()", $type_name); - - quote! { - class $cl_name { - static $type_signature lift($type_signature value) => value; - - static LiftRetVal<$type_signature> read(Uint8List buf) { - return LiftRetVal(buf.buffer.asByteData(buf.offsetInBytes).get$conversion_name(0), $allocation_size); - } - - static $type_signature lower($type_signature value) { - if (value < $min_value || value > $max_value) { - throw ArgumentError($error_message); - } - return value; - } - - static int allocationSize([$type_signature value = 0]) { - return $allocation_size; - } - - static int write($type_signature value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).set$conversion_name(0, lower(value)); - return $allocation_size; - } - } - } - } - } - }; -} diff --git a/uniffi/dart/src/gen/primitives/mod.rs b/uniffi/dart/src/gen/primitives/mod.rs deleted file mode 100644 index db582b1b0..000000000 --- a/uniffi/dart/src/gen/primitives/mod.rs +++ /dev/null @@ -1,207 +0,0 @@ -#[macro_use] -mod macros; -mod boolean; -mod duration; -mod string; - -pub use boolean::BooleanCodeType; -pub use duration::DurationCodeType; -use genco::prelude::*; -use paste::paste; -pub use string::StringCodeType; -use uniffi_bindgen::interface::{ - DefaultValue as InterfaceDefaultValue, Literal as InterfaceLiteral, Radix as InterfaceRadix, - Type as InterfaceType, -}; - -use crate::gen::render::{Renderable, TypeHelperRenderer}; -use crate::gen::CodeType; - -pub(crate) fn escape_dart_string(value: &str) -> String { - value - .replace('\\', "\\\\") - .replace('\'', "\\'") - .replace('\n', "\\n") - .replace('\r', "\\r") - .replace('\t', "\\t") -} - -fn render_literal(literal: &InterfaceLiteral) -> String { - fn typed_number(ty: &InterfaceType, num_str: String) -> String { - match ty { - InterfaceType::Int8 - | InterfaceType::UInt8 - | InterfaceType::Int16 - | InterfaceType::UInt16 - | InterfaceType::Int32 - | InterfaceType::UInt32 - | InterfaceType::Int64 - | InterfaceType::UInt64 - | InterfaceType::Float32 - | InterfaceType::Float64 - | InterfaceType::Duration => num_str, - _ => panic!("Unexpected literal: {num_str} is not a number"), - } - } - - match literal { - InterfaceLiteral::Boolean(v) => format!("{v}"), - InterfaceLiteral::String(s) => format!("'{}'", escape_dart_string(s)), - InterfaceLiteral::Int(i, radix, ty) => typed_number( - ty, - match radix { - InterfaceRadix::Octal => format!("{i:#x}"), - InterfaceRadix::Decimal => format!("{i}"), - InterfaceRadix::Hexadecimal => format!("{i:#x}"), - }, - ), - InterfaceLiteral::UInt(i, radix, ty) => typed_number( - ty, - match radix { - InterfaceRadix::Octal => format!("{i:#x}"), - InterfaceRadix::Decimal => format!("{i}"), - InterfaceRadix::Hexadecimal => format!("{i:#x}"), - }, - ), - InterfaceLiteral::Float(string, ty) => typed_number(ty, string.clone()), - _ => unreachable!("Literal"), - } -} - -fn default_for_interface_type(ty: &InterfaceType) -> Option { - match ty { - InterfaceType::Boolean => Some("false".to_string()), - InterfaceType::String => Some("''".to_string()), - InterfaceType::Int8 - | InterfaceType::Int16 - | InterfaceType::Int32 - | InterfaceType::Int64 - | InterfaceType::UInt8 - | InterfaceType::UInt16 - | InterfaceType::UInt32 - | InterfaceType::UInt64 => Some("0".to_string()), - InterfaceType::Float32 | InterfaceType::Float64 => Some("0.0".to_string()), - InterfaceType::Duration => Some("Duration.zero".to_string()), - InterfaceType::Optional { .. } => Some("null".to_string()), - InterfaceType::Sequence { .. } => Some("const []".to_string()), - InterfaceType::Map { .. } => Some("const {}".to_string()), - _ => None, - } -} - -fn render_interface_literal( - literal: &InterfaceLiteral, - field_type: &InterfaceType, - enum_variant_renderer: F, -) -> Option -where - F: Fn(&InterfaceType, &str) -> Option + Copy, -{ - match literal { - InterfaceLiteral::Boolean(value) => Some(value.to_string()), - InterfaceLiteral::String(value) => Some(format!("'{}'", escape_dart_string(value))), - InterfaceLiteral::Int(value, radix, _) => Some(match radix { - InterfaceRadix::Decimal => format!("{value}"), - InterfaceRadix::Octal | InterfaceRadix::Hexadecimal => format!("{value:#x}"), - }), - InterfaceLiteral::UInt(value, radix, _) => Some(match radix { - InterfaceRadix::Decimal => format!("{value}"), - InterfaceRadix::Octal | InterfaceRadix::Hexadecimal => format!("{value:#x}"), - }), - InterfaceLiteral::Float(value, _) => Some(value.clone()), - InterfaceLiteral::Enum(variant, ty) => enum_variant_renderer(ty, variant) - .or_else(|| enum_variant_renderer(field_type, variant)), - InterfaceLiteral::EmptySequence => Some("const []".to_string()), - InterfaceLiteral::EmptyMap => Some("const {}".to_string()), - // `Set` types are not yet rendered by this generator (every Set path - // is a `todo!`), so there is no Set-typed position for `const {}` to land - // in — it would emit an empty Map. Degrade to no-default (→ required), - // mirroring `default_for_interface_type`, until real Set support exists. - InterfaceLiteral::EmptySet => None, - InterfaceLiteral::None => Some("null".to_string()), - InterfaceLiteral::Some { inner } => { - render_interface_default_value(inner, field_type, enum_variant_renderer) - } - } -} - -pub(crate) fn render_interface_default_value( - default: &InterfaceDefaultValue, - field_type: &InterfaceType, - enum_variant_renderer: F, -) -> Option -where - F: Fn(&InterfaceType, &str) -> Option + Copy, -{ - match default { - InterfaceDefaultValue::Default => default_for_interface_type(field_type), - InterfaceDefaultValue::Literal(literal) => { - render_interface_literal(literal, field_type, enum_variant_renderer) - } - } -} - -impl_code_type_for_primitive!(BytesCodeType, "Uint8List", "Uint8List"); -impl_code_type_for_primitive!(Int8CodeType, "int", "Int8"); -impl_code_type_for_primitive!(Int16CodeType, "int", "Int16"); -impl_code_type_for_primitive!(Int32CodeType, "int", "Int32"); -impl_code_type_for_primitive!(Int64CodeType, "int", "Int64"); -impl_code_type_for_primitive!(UInt8CodeType, "int", "UInt8"); -impl_code_type_for_primitive!(UInt16CodeType, "int", "UInt16"); -impl_code_type_for_primitive!(UInt32CodeType, "int", "UInt32"); -impl_code_type_for_primitive!(UInt64CodeType, "int", "UInt64"); -impl_code_type_for_primitive!(Float32CodeType, "double", "Double32"); -impl_code_type_for_primitive!(Float64CodeType, "double", "Double64"); - -impl_renderable_for_primitive!(BytesCodeType, "Uint8List", "Uint8List"); -impl_renderable_for_primitive!(Int8CodeType, "int", "Int8", 1, -128, 127, "i8"); -impl_renderable_for_primitive!(Int16CodeType, "int", "Int16", 2, -32768, 32767, "i16"); -impl_renderable_for_primitive!(Int32CodeType, "int", "Int32", 4, -2147483648, 2147483647, "i32"); -impl_renderable_for_primitive!( - Int64CodeType, - "int", - "Int64", - 8, - -9223372036854775808, - 9223372036854775807, - "i64" -); -impl_renderable_for_primitive!(UInt8CodeType, "int", "UInt8", 1, 0, 255, "u8"); -impl_renderable_for_primitive!(UInt16CodeType, "int", "UInt16", 2, 0, 65535, "u16"); -impl_renderable_for_primitive!(UInt32CodeType, "int", "UInt32", 4, 0, 4294967295, "u32"); -impl_renderable_for_primitive!(Float32CodeType, "double", "Double32", 4); -impl_renderable_for_primitive!(Float64CodeType, "double", "Double64", 8); - -// Keep u64 on the legacy int path for now; full upper-bound validation lands with BigInt support. -impl Renderable for UInt64CodeType { - fn render_type_helper(&self, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let cl_name = &self.ffi_converter_name(); - let type_signature = &self.type_label(); - - quote! { - class $cl_name { - static $type_signature lift($type_signature value) => value; - - static LiftRetVal<$type_signature> read(Uint8List buf) { - return LiftRetVal(buf.buffer.asByteData(buf.offsetInBytes).getUint64(0), 8); - } - - static $type_signature lower($type_signature value) { - if (value < 0) { - throw ArgumentError("Value out of range for u64: " + value.toString()); - } - return value; - } - - static int allocationSize([$type_signature value = 0]) { - return 8; - } - - static int write($type_signature value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setUint64(0, lower(value)); - return 8; - } - } - } - } -} diff --git a/uniffi/dart/src/gen/primitives/string.rs b/uniffi/dart/src/gen/primitives/string.rs deleted file mode 100644 index 652e9f910..000000000 --- a/uniffi/dart/src/gen/primitives/string.rs +++ /dev/null @@ -1,47 +0,0 @@ -use genco::lang::dart; - -use crate::gen::render::{Renderable, TypeHelperRenderer}; -use crate::gen::{quote, CodeType}; - -#[derive(Debug)] -pub struct StringCodeType; -impl CodeType for StringCodeType { - fn type_label(&self) -> String { - "String".to_owned() - } -} - -impl Renderable for StringCodeType { - fn render_type_helper(&self, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - quote! { - class FfiConverterString { - static String lift( RustBuffer buf) { - // reading the entire buffer, the len is where the string finishes - return utf8.decoder.convert(buf.asUint8List()); - } - - static RustBuffer lower( String value) { - return toRustBuffer(Utf8Encoder().convert(value)); - } - - static LiftRetVal read( Uint8List buf) { - final end = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0) + 4; - return LiftRetVal(utf8.decoder.convert(buf, 4, end), end); - } - - static int allocationSize([String value = ""]) { - // FIXME: doing this twice for every string is bad - return utf8.encoder.convert(value).length + 4; // Four additional bytes for the length data - } - - static int write( String value, Uint8List buf) { - // two memcopies feels bad :( - final list = utf8.encoder.convert(value); - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, list.length); - buf.setAll(4, list); - return list.length + 4; - } - } - } - } -} diff --git a/uniffi/dart/src/gen/records.rs b/uniffi/dart/src/gen/records.rs deleted file mode 100644 index e81e021ae..000000000 --- a/uniffi/dart/src/gen/records.rs +++ /dev/null @@ -1,136 +0,0 @@ -use genco::prelude::*; -use uniffi_bindgen::interface::{AsType, Literal as PipelineLiteral, Record, Type}; - -use super::defaults::render_default_value; -use super::oracle::{AsCodeType, DartCodeOracle}; -use super::render::{Renderable, TypeHelperRenderer}; -use super::types::generate_type; -use crate::gen::CodeType; - -#[derive(Debug)] -pub struct RecordCodeType { - id: String, - namespace: Option, -} - -impl RecordCodeType { - pub fn new(id: String, namespace: Option) -> Self { - Self { id, namespace } - } -} - -impl CodeType for RecordCodeType { - fn type_label(&self) -> String { - DartCodeOracle::qualify(self.namespace.as_deref(), DartCodeOracle::class_name(&self.id)) - } - - fn canonical_name(&self) -> String { - DartCodeOracle::qualify_canonical(self.namespace.as_deref(), self.id.to_string()) - } - - fn ffi_converter_name(&self) -> String { - DartCodeOracle::qualify(self.namespace.as_deref(), format!("FfiConverter{}", self.id)) - } - - fn literal(&self, _literal: &PipelineLiteral) -> String { - todo!("literal not implemented for RecordCodeType"); - } -} - -impl Renderable for RecordCodeType { - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - // Another crate's library declares its own helpers. - if self.namespace.is_some() || type_helper.check(&self.id) { - quote!() - } else if let Some(record_) = type_helper.get_record(&self.id) { - generate_record(record_, type_helper) - } else { - todo!("render_type_helper not implemented for unknown record type"); - } - } -} - -pub fn generate_record(obj: &Record, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let cls_name = &DartCodeOracle::class_name(obj.name()); - let ffi_conv_name = &obj.as_codetype(type_helper.get_ci()).ffi_converter_name(); - let constructor_params: Vec = obj - .fields() - .iter() - .map(|field| { - let name = DartCodeOracle::var_name(field.name()); - if let Some(default_value) = field.default_value() { - if let Some(default_expr) = - render_default_value(default_value, &field.as_type(), type_helper.get_ci()) - { - quote!(this.$name = $(default_expr)) - } else { - // Fallback to required when a default is present but cannot be rendered safely. - quote!(required this.$name) - } - } else if matches!(field.as_type(), Type::Optional { .. }) { - quote!(this.$name) - } else { - quote!(required this.$name) - } - }) - .collect(); - - let constructor = if obj.fields().is_empty() { - quote!($(cls_name)();) - } else { - quote!($(cls_name)({$(for param in constructor_params => $param, )});) - }; - - for f in obj.fields() { - type_helper.include_once_check( - &f.as_codetype(type_helper.get_ci()).canonical_name(), - &f.as_type(), - ); - } - quote! { - class $cls_name { - $(for f in obj.fields() => final $(generate_type(&f.as_type(), type_helper.get_ci())) $(DartCodeOracle::var_name(f.name()));) - - $constructor - } - - class $ffi_conv_name { - static $cls_name lift( RustBuffer buf) { - return $ffi_conv_name.read(buf.asUint8List()).value; - } - - static LiftRetVal<$cls_name> read( Uint8List buf) { - int new_offset = buf.offsetInBytes; - - $(for f in obj.fields() => - final $(DartCodeOracle::var_name(f.name()))_lifted = $(f.as_type().as_codetype(type_helper.get_ci()).ffi_converter_name()).read(Uint8List.view(buf.buffer, new_offset)); - final $(DartCodeOracle::var_name(f.name())) = $(DartCodeOracle::var_name(f.name()))_lifted.value; - new_offset += $(DartCodeOracle::var_name(f.name()))_lifted.bytesRead; - ) - return LiftRetVal($(cls_name)( - $(for f in obj.fields() => $(DartCodeOracle::var_name(f.name())): $(DartCodeOracle::var_name(f.name())),) - ), new_offset - buf.offsetInBytes); - } - - static RustBuffer lower( $cls_name value) { - final total_length = $(for f in obj.fields() => $(f.as_type().as_codetype(type_helper.get_ci()).ffi_converter_name()).allocationSize(value.$(DartCodeOracle::var_name(f.name()))) + ) 0; - final buf = Uint8List(total_length); - write(value, buf); - return toRustBuffer(buf); - } - - static int write( $cls_name value, Uint8List buf) { - int new_offset = buf.offsetInBytes; - - $(for f in obj.fields() => - new_offset += $(f.as_type().as_codetype(type_helper.get_ci()).ffi_converter_name()).write(value.$(DartCodeOracle::var_name(f.name())), Uint8List.view(buf.buffer, new_offset)); - ) - return new_offset - buf.offsetInBytes; - } - - static int allocationSize($cls_name value) { - return $(for f in obj.fields() => $(f.as_type().as_codetype(type_helper.get_ci()).ffi_converter_name()).allocationSize(value.$(DartCodeOracle::var_name(f.name()))) + ) 0; - } - } - } -} diff --git a/uniffi/dart/src/gen/render/mod.rs b/uniffi/dart/src/gen/render/mod.rs deleted file mode 100644 index f5242d4de..000000000 --- a/uniffi/dart/src/gen/render/mod.rs +++ /dev/null @@ -1,113 +0,0 @@ -use genco::lang::dart; -use genco::quote; -use uniffi_bindgen::interface::{AsType, Enum, Object, Record, Type}; -use uniffi_bindgen::ComponentInterface; - -use super::oracle::AsCodeType; -use super::{callback_interface, compounds, custom, enums, objects, primitives, records}; - -pub trait Renderer { - fn render(&self) -> T; -} - -pub trait TypeHelperRenderer { - fn get_ci(&self) -> &ComponentInterface; - fn include_once_check(&self, name: &str, ty: &Type) -> bool; - fn check(&self, name: &str) -> bool; - /// Marks a name as included and returns true if it was already present (should skip generation). - /// Use this for types that don't have a corresponding Type enum variant. - fn include_once_by_name(&self, name: &str) -> bool; - - fn get_object(&self, name: &str) -> Option<&Object>; - fn get_enum(&self, name: &str) -> Option<&Enum>; - fn get_record(&self, name: &str) -> Option<&Record>; -} - -pub trait Renderable { - fn render_type(&self, ty: &Type, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let type_name = match ty { - Type::UInt8 - | Type::Int8 - | Type::UInt16 - | Type::Int16 - | Type::UInt32 - | Type::Int32 - | Type::UInt64 - | Type::Int64 => quote!(int), - Type::Float32 | Type::Float64 => quote!(double), - Type::String => quote!(String), - Type::Boolean => quote!(bool), - Type::Bytes => quote!(Uint8List), - Type::Object { .. } - | Type::Enum { .. } - | Type::Record { .. } - | Type::Custom { .. } - | Type::CallbackInterface { .. } => { - quote!($(ty.as_codetype(type_helper.get_ci()).type_label())) - } - Type::Optional { inner_type } => quote!($(&self.render_type(inner_type, type_helper))?), - Type::Sequence { inner_type } => { - quote!(List<$(&self.render_type(inner_type, type_helper))>) - } - Type::Map { key_type, value_type } => { - quote!(Map<$(&self.render_type(key_type, type_helper)), $(&self.render_type(value_type, type_helper))>) - } - Type::Duration => quote!(Duration), - _ => todo!("Type::{:?}", ty), - }; - - type_helper.include_once_check(&ty.as_codetype(type_helper.get_ci()).canonical_name(), ty); - - type_name - } - - fn render_type_helper(&self, type_helper: &dyn TypeHelperRenderer) -> dart::Tokens; -} - -pub trait AsRenderable { - /// The renderer of this type as `ci`'s library sees it. - fn as_renderable(&self, ci: &ComponentInterface) -> Box; -} - -impl AsRenderable for T { - fn as_renderable(&self, ci: &ComponentInterface) -> Box { - let namespace = super::oracle::DartCodeOracle::external_namespace(&self.as_type(), ci); - match self.as_type() { - Type::UInt8 => Box::new(primitives::UInt8CodeType), - Type::Int8 => Box::new(primitives::Int8CodeType), - Type::UInt16 => Box::new(primitives::UInt16CodeType), - Type::Int16 => Box::new(primitives::Int16CodeType), - Type::UInt32 => Box::new(primitives::UInt32CodeType), - Type::Int32 => Box::new(primitives::Int32CodeType), - Type::UInt64 => Box::new(primitives::UInt64CodeType), - Type::Int64 => Box::new(primitives::Int64CodeType), - Type::Float32 => Box::new(primitives::Float32CodeType), - Type::Float64 => Box::new(primitives::Float64CodeType), - Type::Boolean => Box::new(primitives::BooleanCodeType), - Type::String => Box::new(primitives::StringCodeType), - Type::Duration => Box::new(primitives::DurationCodeType), - Type::Bytes => Box::new(primitives::BytesCodeType), - Type::Object { name, imp, .. } => { - Box::new(objects::ObjectCodeType::new(name, imp, namespace)) - } - Type::Optional { inner_type } => { - Box::new(compounds::OptionalCodeType::new(self.as_type(), *inner_type, ci)) - } - Type::Sequence { inner_type } => { - Box::new(compounds::SequenceCodeType::new(self.as_type(), *inner_type, ci)) - } - Type::Map { key_type, value_type } => { - Box::new(compounds::MapCodeType::new(self.as_type(), *key_type, *value_type, ci)) - } - Type::Enum { name, .. } => Box::new(enums::EnumCodeType::new(name, namespace)), - Type::Record { name, .. } => Box::new(records::RecordCodeType::new(name, namespace)), - Type::Custom { name, module_path, builtin } => { - Box::new(custom::CustomCodeType::new(name, module_path, builtin, namespace)) - } - Type::CallbackInterface { name, .. } => Box::new( - callback_interface::CallbackInterfaceCodeType::new(name, self.as_type(), namespace), - ), - _ => todo!("Renderable for Type::{:?}", self.as_type()), - } - } -} diff --git a/uniffi/dart/src/gen/stream/mod.rs b/uniffi/dart/src/gen/stream/mod.rs deleted file mode 100644 index b2a41d9b9..000000000 --- a/uniffi/dart/src/gen/stream/mod.rs +++ /dev/null @@ -1,31 +0,0 @@ -use genco::prelude::*; -use uniffi_bindgen::interface::Object; - -use crate::gen::oracle::DartCodeOracle; -use crate::gen::render::TypeHelperRenderer; - -pub fn generate_stream(obj: &Object, _type_helper: &dyn TypeHelperRenderer) -> dart::Tokens { - let obj_name = obj.name(); - let fn_name = DartCodeOracle::fn_name(&obj_name.replace("StreamExt", "")); - let obj_var_name = &DartCodeOracle::var_name(&fn_name); - let create_obj_fn_name = format!("createStream{}", obj_name.replace("StreamExt", "")); - - quote! { - $fn_name() async* { - final $obj_var_name = $create_obj_fn_name(); - try { - while (true) { - final value = await $obj_var_name.next(); - if (value == null) { - break; - } - yield value; - } - } catch (e) { - // Handle exceptions if necessary - rethrow; - } - // No need to call drop(), Finalizer will handle it - } - } -} diff --git a/uniffi/dart/src/gen/types.rs b/uniffi/dart/src/gen/types.rs deleted file mode 100644 index 0319b07b1..000000000 --- a/uniffi/dart/src/gen/types.rs +++ /dev/null @@ -1,753 +0,0 @@ -use std::cell::RefCell; -use std::collections::{BTreeMap, BTreeSet}; - -use genco::prelude::*; -use uniffi_bindgen::interface::{AsType, Callable, Type}; -use uniffi_bindgen::ComponentInterface; - -use super::oracle::AsCodeType; -use super::render::{AsRenderable, Renderable, Renderer, TypeHelperRenderer}; -use super::{enums, functions, objects, primitives, records}; -use crate::gen::oracle::DartCodeOracle; - -type FunctionDefinition = dart::Tokens; - -/// Basename (no extension) of the file holding the shared runtime scaffolding. -/// Every generated component file imports it; see [`runtime_scaffolding`]. -pub const RUNTIME_MODULE: &str = "uniffi_runtime"; - -pub struct TypeHelpersRenderer<'a> { - ci: &'a ComponentInterface, - include_once_names: RefCell>, - // Tracks ad-hoc "include once" names that don't map to a concrete `Type` - include_once_custom: RefCell>, -} - -impl<'a> TypeHelpersRenderer<'a> { - pub fn new(ci: &'a ComponentInterface) -> Self { - Self { - ci, - include_once_names: RefCell::new(BTreeMap::new()), - include_once_custom: RefCell::new(BTreeSet::new()), - } - } - - pub fn get_include_names(&self) -> BTreeMap { - self.include_once_names.clone().into_inner() - } - - fn register_type_helper(&self, ty: &Type) { - let canonical_name = ty.as_codetype(self.ci).canonical_name(); - self.include_once_check(&canonical_name, ty); - - let exception_safe_name = DartCodeOracle::exception_safe_name(&canonical_name); - if exception_safe_name != canonical_name { - self.include_once_check(&exception_safe_name, ty); - } - } - - fn register_type_helpers(&self, ty: &Type) { - for ty in ty.iter_types() { - self.register_type_helper(ty); - } - } - - fn register_callable_type_helpers(&self, callable: &dyn Callable) { - for ty in callable.iter_types() { - self.register_type_helper(ty); - } - } - - fn register_component_interface_type_helpers(&self) { - for record in self.ci.record_definitions() { - self.register_type_helpers(&record.as_type()); - for ty in record.iter_types() { - self.register_type_helpers(ty); - } - } - - for enm in self.ci.enum_definitions() { - self.register_type_helpers(&enm.as_type()); - for ty in enm.iter_types() { - self.register_type_helpers(ty); - } - } - - for obj in self.ci.object_definitions() { - self.register_type_helpers(&obj.as_type()); - for ty in obj.iter_types() { - self.register_type_helpers(ty); - } - } - - for func in self.ci.function_definitions() { - self.register_callable_type_helpers(func); - } - - for callback in self.ci.callback_interface_definitions() { - self.register_type_helpers(&callback.as_type()); - for ty in callback.iter_types() { - self.register_type_helpers(ty); - } - } - } -} - -impl TypeHelperRenderer for TypeHelpersRenderer<'_> { - // Checks if the type imports for each type have already been added - fn include_once_check(&self, name: &str, ty: &Type) -> bool { - let mut map = self.include_once_names.borrow_mut(); - let found = map.insert(name.to_string(), ty.clone()).is_some(); - drop(map); - found - } - - fn check(&self, name: &str) -> bool { - let map = self.include_once_names.borrow(); - let contains = map.contains_key(&name.to_string()); - drop(map); - contains - } - - fn include_once_by_name(&self, name: &str) -> bool { - let mut set = self.include_once_custom.borrow_mut(); - !set.insert(name.to_string()) - } - - fn get_object(&self, name: &str) -> Option<&uniffi_bindgen::interface::Object> { - self.ci.get_object_definition(name) - } - - fn get_enum(&self, name: &str) -> Option<&uniffi_bindgen::interface::Enum> { - self.ci.get_enum_definition(name) - } - - fn get_ci(&self) -> &ComponentInterface { - self.ci - } - - fn get_record(&self, name: &str) -> Option<&uniffi_bindgen::interface::Record> { - self.ci.get_record_definition(name) - } -} - -impl Renderer<(FunctionDefinition, dart::Tokens)> for TypeHelpersRenderer<'_> { - // TODO: Implimient a two pass system where the first pass will render the main code, and the second pass will render the helper code - // this is so the generator knows what helper code to include. - - fn render(&self) -> (dart::Tokens, dart::Tokens) { - // Render all the types and their helpers - let types_definitions = quote! { - $( for rec in self.ci.record_definitions() => $(records::generate_record(rec, self))) - - $( for enm in self.ci.enum_definitions() => $(enums::generate_enum(enm, self))) - $( for obj in self.ci.object_definitions() => $(objects::generate_object(obj, self))) - }; - - // Render all unique imports, sorted alphabetically. Each library is imported under a - // prefix, which every reference to its types goes through. - let modules_to_import = self - .ci - .iter_external_types() - .map(|ty| { - self.ci.namespace_for_type(ty).expect("external type should have module_path") - }) - .collect::>(); - let imports: dart::Tokens = quote!( - $( for imp in modules_to_import { - $(format!("import \"{imp}.dart\" as {}", DartCodeOracle::import_prefix(imp))); - }) - ); - - // let function_definitions = quote!($( for fun in self.ci.function_definitions() => $(functions::generate_function("this", fun, self)))); - - let function_definitions = quote!( - $(for fun in self.ci.function_definitions() => - $(functions::generate_function(fun, self)) - - ) - ); - - self.register_component_interface_type_helpers(); - - // `FfiConverterString` is emitted once, into the shared runtime -- the - // runtime itself calls it (to lift panic messages), and repeating it here - // would collide with the re-exported one. - let helpers_definitions = quote! { - $(for (_, ty) in self.get_include_names().iter().filter(|(_, ty)| !matches!(ty, Type::String)) => - $(ty.as_renderable(self.ci).render_type_helper(self)) ) - }; - - let types_helper_code = quote! { - import "dart:async"; - import "dart:convert"; - import "dart:ffi"; - import "dart:io" show Platform, File, Directory; - import "dart:isolate"; - import "dart:typed_data"; - import "package:ffi/ffi.dart"; - $(format!("import \"{RUNTIME_MODULE}.dart\";")) - // Re-exported so a consumer importing only this file still sees the - // shared runtime types that surface in the generated public API. - $(format!("export \"{RUNTIME_MODULE}.dart\";")) - $(imports) - - $(types_definitions) - - - $(helpers_definitions) - - }; - - (types_helper_code, function_definitions) - } -} - -pub fn generate_type(ty: &Type, ci: &ComponentInterface) -> dart::Tokens { - match ty { - Type::UInt8 - | Type::UInt32 - | Type::Int8 - | Type::Int16 - | Type::Int64 - | Type::UInt16 - | Type::Int32 - | Type::UInt64 => quote!(int), - Type::Float32 | Type::Float64 => quote!(double), - Type::String => quote!(String), - Type::Bytes => quote!(Uint8List), - Type::Object { .. } | Type::Enum { .. } | Type::Record { .. } | Type::Custom { .. } => { - quote!($(ty.as_codetype(ci).type_label())) - } - Type::Boolean => quote!(bool), - Type::Optional { inner_type } => quote!($(generate_type(inner_type, ci))?), - Type::Sequence { inner_type } => quote!(List<$(generate_type(inner_type, ci))>), - Type::Map { key_type, value_type } => { - quote!(Map<$(generate_type(key_type, ci)), $(generate_type(value_type, ci))>) - } - Type::Duration => quote!(Duration), - _ => todo!("Type::{:?}", ty), - } -} - -/// Runtime scaffolding shared by every generated file. -/// -/// Emitted once into its own file rather than copied into each component, so -/// that a type crossing a crate boundary -- an error handler declared in a -/// dependency, say -- is the *same* Dart type on both sides. Duplicating these -/// declarations per file makes them nominally distinct and the two halves stop -/// type-checking against each other. -/// -/// `ci` only supplies the `rustbuffer_*` symbol names for `RustBuffer`'s own -/// allocator methods. Every component in a generation links into the same -/// cdylib and each exports an equivalent implementation, so any component's -/// names serve for all of them. -pub fn runtime_scaffolding(ci: &ComponentInterface) -> dart::Tokens { - // `StringCodeType` ignores the renderer it is handed; this one just satisfies - // the signature. - let string_converter = - primitives::StringCodeType.render_type_helper(&TypeHelpersRenderer::new(ci)); - - quote! { - import "dart:async"; - import "dart:convert"; - import "dart:ffi"; - import "dart:io" show Platform, File, Directory; - import "dart:isolate"; - import "dart:typed_data"; - import "package:ffi/ffi.dart"; - - class UniffiInternalError implements Exception { - static const int bufferOverflow = 0; - static const int incompleteData = 1; - static const int unexpectedOptionalTag = 2; - static const int unexpectedEnumCase = 3; - static const int unexpectedNullPointer = 4; - static const int unexpectedRustCallStatusCode = 5; - static const int unexpectedRustCallError = 6; - static const int unexpectedStaleHandle = 7; - static const int rustPanic = 8; - - final int errorCode; - final String? panicMessage; - - const UniffiInternalError(this.errorCode, this.panicMessage); - - static UniffiInternalError panicked(String message) { - return UniffiInternalError(rustPanic, message); - } - - @override - String toString() { - switch (errorCode) { - case bufferOverflow: - return "UniFfi::BufferOverflow"; - case incompleteData: - return "UniFfi::IncompleteData"; - case unexpectedOptionalTag: - return "UniFfi::UnexpectedOptionalTag"; - case unexpectedEnumCase: - return "UniFfi::UnexpectedEnumCase"; - case unexpectedNullPointer: - return "UniFfi::UnexpectedNullPointer"; - case unexpectedRustCallStatusCode: - return "UniFfi::UnexpectedRustCallStatusCode"; - case unexpectedRustCallError: - return "UniFfi::UnexpectedRustCallError"; - case unexpectedStaleHandle: - return "UniFfi::UnexpectedStaleHandle"; - case rustPanic: - return $[str](UniFfi::rustPanic: $panicMessage); - default: - return $[str](UniFfi::UnknownError: $errorCode); - } - } - } - - const int CALL_SUCCESS = 0; - const int CALL_ERROR = 1; - const int CALL_UNEXPECTED_ERROR = 2; - const int CALL_CANCELLED = 3; - - final class RustCallStatus extends Struct { - @Int8() - external int code; - - external RustBuffer errorBuf; - - //Pointer asPointer() => Pointer.fromAddress(address); - } - - void checkCallStatus(UniffiRustCallStatusErrorHandler errorHandler, Pointer status) { - - if (status.ref.code == CALL_SUCCESS) { - return; - } else if (status.ref.code == CALL_ERROR) { - throw liftAndFree(status.ref.errorBuf, errorHandler.lift); - } else if (status.ref.code == CALL_CANCELLED) { - throw const UniffiCancelledException(); - } else if (status.ref.code == CALL_UNEXPECTED_ERROR) { - if (status.ref.errorBuf.len > 0) { - throw UniffiInternalError.panicked(liftAndFree(status.ref.errorBuf, FfiConverterString.lift)); - } else { - throw UniffiInternalError.panicked("Rust panic"); - } - } else { - throw UniffiInternalError.panicked("Unexpected RustCallStatus code: ${status.ref.code}"); - } - } - - T rustCall(T Function(Pointer) callback, [UniffiRustCallStatusErrorHandler? errorHandler]) { - final status = calloc(); - try { - final result = callback(status); - checkCallStatus(errorHandler ?? NullRustCallStatusErrorHandler(), status); - return result; - } finally { - calloc.free(status); - } - } - - // Rust hands ownership of a returned or error buffer to us. Every lifter - // copies out of it, so it is dead once lifting is done. The raw value is - // also instantiated with pointers and integers, which own nothing here. - T liftAndFree(F raw, T Function(F) lifter) { - try { - return lifter(raw); - } finally { - if (raw is RustBuffer) { - raw.free(); - } - } - } - - // New version that separates FFI call from lifting to avoid deserializing garbage on error - T rustCallWithLifter(F Function(Pointer) ffiCall, T Function(F) lifter, [UniffiRustCallStatusErrorHandler? errorHandler]) { - final status = calloc(); - try { - final rawResult = ffiCall(status); - checkCallStatus(errorHandler ?? NullRustCallStatusErrorHandler(), status); - return liftAndFree(rawResult, lifter); - } finally { - calloc.free(status); - } - } - - class NullRustCallStatusErrorHandler extends UniffiRustCallStatusErrorHandler { - @override - Exception lift(RustBuffer errorBuf) { - return UniffiInternalError.panicked("Unexpected CALL_ERROR"); - } - } - - abstract class UniffiRustCallStatusErrorHandler { - Exception lift(RustBuffer errorBuf); - } - - final class RustBuffer extends Struct { - @Uint64() - external int capacity; - - @Uint64() - external int len; - - external Pointer data; - - static RustBuffer alloc(int size) { - return rustCall((status) => $(ci.ffi_rustbuffer_alloc().name())(size, status)); - } - - static RustBuffer fromBytes(ForeignBytes bytes) { - return rustCall((status) => $(ci.ffi_rustbuffer_from_bytes().name())(bytes, status)); - } - - // static RustBuffer from(Pointer bytes, int len) { - // final foreignBytes = ForeignBytes(len: len, data: bytes); - // return rustCall((status) => _UniffiLib.instance.ffi_uniffi_futures_rustbuffer_from_bytes(foreignBytes)); - // } - - void free() { - rustCall((status) => $(ci.ffi_rustbuffer_free().name())(this, status)); - } - - RustBuffer reserve(int additionalCapacity) { - return rustCall((status) => $(ci.ffi_rustbuffer_reserve().name())(this, additionalCapacity, status)); - } - - Uint8List asUint8List() { - final dataList = data.asTypedList(len); - final byteData = ByteData.sublistView(dataList); - return Uint8List.view(byteData.buffer); - } - - @override - String toString() { - return "RustBuffer{capacity: $capacity, len: $len, data: $data}"; - } - } - - RustBuffer toRustBuffer(Uint8List data) { - final length = data.length; - - final frameData = calloc(length); - try { - frameData.asTypedList(length).setAll(0, data); - final bytes = calloc(); - try { - bytes.ref.len = length; - bytes.ref.data = frameData; - return RustBuffer.fromBytes(bytes.ref); - } finally { - calloc.free(bytes); - } - } finally { - calloc.free(frameData); - } - } - - // Lowers a `Uint8List` into a `ForeignBytes` for a borrowed `&[u8]` - // (`[ByRef] bytes`) argument. The Rust side only borrows the buffer - // for the duration of the call, so this is valid in argument - // position only (never lifted or read back). Dart's GC-managed - // `Uint8List` has no stable native address, so the bytes are copied - // into native memory, mirroring `toRustBuffer` above. - ForeignBytes lowerForeignBytes(Uint8List data) { - final length = data.length; - // `ForeignBytes.len` is an Int32; fail loudly rather than - // silently truncate a >2GiB buffer into a bogus length. - if (length > 0x7fffffff) { - throw ArgumentError( - "Uint8List too large for a borrowed &[u8] FFI argument: " + length.toString() + " bytes"); - } - final bytes = calloc(); - if (length == 0) { - // Empty slice: pass (null, 0). `calloc(0)` is - // platform-variable (some allocators return null and make - // `calloc` throw); Rust reads (null, 0) as `&[]`. Mirrors the - // ByRef-bytes converters in uniffi's Kotlin/Python backends. - bytes.ref.len = 0; - bytes.ref.data = Pointer.fromAddress(0); - return bytes.ref; - } - final Pointer frameData = calloc(length); - frameData.asTypedList(length).setAll(0, data); - bytes.ref.len = length; - bytes.ref.data = frameData; - return bytes.ref; - } - - final class ForeignBytes extends Struct { - @Int32() - external int len; - external Pointer data; - - //ForeignBytes({required this.len, required this.data}); - - // factory ForeignBytes.fromTypedData(Uint8List typedData) { - // final data = calloc(typedData.length); - // final dataList = data.asTypedList(typedData.length); - // dataList.setAll(0, typedData); - // return ForeignBytes(len: typedData.length, data: data); - // } - - void free() { - calloc.free(data); - } - } - - class LiftRetVal { - final T value; - final int bytesRead; - const LiftRetVal(this.value, this.bytesRead); - - LiftRetVal copyWithOffset(int offset) { - return LiftRetVal(value, bytesRead + offset); - } - } - - abstract class FfiConverter { - const FfiConverter(); - - D lift(F value); - F lower(D value); - D read(ByteData buffer, int offset); - void write(D value, ByteData buffer, int offset); - int size(D value); - } - - mixin FfiConverterPrimitive on FfiConverter { - @override - T lift(T value) => value; - - @override - T lower(T value) => value; - } - - Uint8List createUint8ListFromInt(int value) { - int length = value.bitLength ~/ 8 + 1; - - // Ensure the length is either 4 or 8 - if (length != 4 && length != 8) { - length = (value < 0x100000000) ? 4 : 8; - } - - Uint8List uint8List = Uint8List(length); - - for (int i = length - 1; i >= 0; i--) { - uint8List[i] = value & 0xFF; - value >>= 8; - } - - return uint8List; - } - - - const int UNIFFI_RUST_FUTURE_POLL_READY = 0; - const int UNIFFI_RUST_FUTURE_POLL_MAYBE_READY = 1; - - typedef UniffiRustFutureContinuationCallback = Void Function(Uint64, Int8); - - final _uniffiRustFutureContinuationHandles = UniffiHandleMap>(); - - $("/// A native call whose Future can cancel and release only its own operation.\n") - abstract interface class UniffiRustFuture implements Future { - $("/// Request cancellation and wait until native call cleanup finishes.\n") - Future cancel(); - } - - $("/// The native operation was cancelled before producing a result.\n") - final class UniffiCancelledException implements Exception { - const UniffiCancelledException(); - - @override - String toString() => "Native operation cancelled"; - } - - final class _UniffiRustFuture implements UniffiRustFuture { - final Future _future; - final void Function() _cancel; - - _UniffiRustFuture(this._future, this._cancel); - - @override - Future cancel() { - _cancel(); - return _future.then((_) {}, onError: (Object error, StackTrace stack) {}); - } - - @override - Stream asStream() => _future.asStream(); - - @override - Future catchError(Function onError, {bool Function(Object)? test}) => - _future.catchError(onError, test: test); - - @override - Future then(FutureOr Function(T) onValue, {Function? onError}) => - _future.then(onValue, onError: onError); - - @override - Future timeout(Duration timeLimit, {FutureOr Function()? onTimeout}) => - _future.timeout(timeLimit, onTimeout: onTimeout); - - @override - Future whenComplete(FutureOr Function() action) => - _future.whenComplete(action); - } - - UniffiRustFuture uniffiRustCallAsync( - Pointer Function() rustFutureFunc, - void Function(Pointer, Pointer>, Pointer) pollFunc, - F Function(Pointer, Pointer) completeFunc, - void Function(Pointer) cancelFunc, - void Function(Pointer) freeFunc, - T Function(F) liftFunc, [ - UniffiRustCallStatusErrorHandler? errorHandler, - ]) { - Pointer? rustFuture; - var freed = false; - var cancelRequested = false; - - Future run() async { - final nativeFuture = rustFutureFunc(); - rustFuture = nativeFuture; - final completer = Completer(); - final handle = _uniffiRustFutureContinuationHandles.insert(completer); - final callbackData = Pointer.fromAddress(handle); - late final NativeCallable callback; - - void repoll() { - pollFunc(nativeFuture, callback.nativeFunction, callbackData); - } - - void onResponse(int data, int pollResult) { - if (freed || completer.isCompleted) return; - if (pollResult == UNIFFI_RUST_FUTURE_POLL_READY) { - _uniffiRustFutureContinuationHandles.maybeRemove(data); - completer.complete(pollResult); - } else if (pollResult == UNIFFI_RUST_FUTURE_POLL_MAYBE_READY) { - repoll(); - } else { - _uniffiRustFutureContinuationHandles.maybeRemove(data); - completer.completeError( - UniffiInternalError.panicked("Unexpected native future poll result"), - ); - } - } - - callback = NativeCallable.listener(onResponse); - try { - repoll(); - await completer.future; - final status = calloc(); - try { - final result = completeFunc(nativeFuture, status); - checkCallStatus(errorHandler ?? NullRustCallStatusErrorHandler(), status); - return liftAndFree(result, liftFunc); - } finally { - calloc.free(status); - } - } finally { - freed = true; - _uniffiRustFutureContinuationHandles.maybeRemove(handle); - try { - freeFunc(nativeFuture); - } finally { - callback.close(); - } - } - } - - return _UniffiRustFuture(run(), () { - if (freed || cancelRequested) return; - cancelRequested = true; - final nativeFuture = rustFuture; - if (nativeFuture != null) cancelFunc(nativeFuture); - }); - } - - typedef UniffiForeignFutureFree = Void Function(Uint64); - typedef UniffiForeignFutureFreeDart = void Function(int); - - class UniffiForeignFutureState { - bool cancelled = false; - } - - final uniffiForeignFutureHandleMap = UniffiHandleMap(); - - void _uniffiForeignFutureFree(int handle) { - final state = uniffiForeignFutureHandleMap.maybeRemove(handle); - if (state != null) { - state.cancelled = true; - } - } - - final Pointer> - uniffiForeignFutureFreePointer = - Pointer.fromFunction(_uniffiForeignFutureFree); - - final class UniffiForeignFuture extends Struct { - @Uint64() - external int handle; - - external Pointer> free; - } - - // As of uniffi 0.30, foreign handles must always have the lowest bit set - // This is achieved here with an odd number sequence. - class UniffiHandleMap { - final Map _map = {}; - int _counter = 1; - - int insert(T obj) { - final handle = _counter; - _counter += 2; - _map[handle] = obj; - return handle; - } - - T get(int handle) { - final obj = _map[handle]; - if (obj == null) { - throw UniffiInternalError( - UniffiInternalError.unexpectedStaleHandle, "Handle not found"); - } - return obj; - } - - T remove(int handle) { - final obj = maybeRemove(handle); - if (obj == null) { - throw UniffiInternalError( - UniffiInternalError.unexpectedStaleHandle, "Handle not found"); - } - return obj; - } - - T? maybeRemove(int handle) { - return _map.remove(handle); - } - } - - - $(string_converter) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn include_names_iterate_in_name_order() { - let ci = ComponentInterface::new("determinism"); - let renderer = TypeHelpersRenderer::new(&ci); - - renderer.include_once_check("z", &Type::String); - renderer.include_once_check("a", &Type::UInt8); - renderer.include_once_check("m", &Type::Boolean); - - let names: Vec<_> = renderer.get_include_names().keys().cloned().collect(); - assert_eq!(names, ["a", "m", "z"]); - } -} diff --git a/uniffi/dart/src/lib.rs b/uniffi/dart/src/lib.rs deleted file mode 100644 index c566ebd2c..000000000 --- a/uniffi/dart/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -#[cfg(feature = "build")] -mod build; -#[cfg(feature = "bindgen-tests")] -pub mod testing; -#[cfg(feature = "build")] -pub use build::generate_scaffolding; - -pub mod gen; - -pub use uniffi_dart_macro::*; diff --git a/uniffi/dart/src/testing.rs b/uniffi/dart/src/testing.rs deleted file mode 100644 index 7bd758e8a..000000000 --- a/uniffi/dart/src/testing.rs +++ /dev/null @@ -1,395 +0,0 @@ -use std::fs::{copy, create_dir_all, File}; -use std::io::Write; -use std::process::Command; -use std::thread; -use std::time::Duration; - -use anyhow::{bail, Result}; -use camino::{Utf8Path, Utf8PathBuf}; -use camino_tempfile::tempdir; -use uniffi_testing::UniFFITestHelper; - -use crate::gen; - -// A source to compile for a test -#[derive(Debug)] -pub struct CompileSource { - pub udl_path: Utf8PathBuf, - pub config_path: Option, -} - -/// Test execution options -#[derive(Debug, Clone, Default)] -pub struct TestConfig { - /// Custom output directory for test files - pub custom_output_dir: Option, - /// Preserve test files after completion - pub no_delete: bool, - /// Delay in seconds after test failure (0 = no delay; None = default) - pub failure_delay_secs: Option, -} - -impl TestConfig { - /// Build from environment variables - /// - UNIFFI_DART_TEST_DIR: custom output dir - /// - UNIFFI_DART_NO_DELETE: preserve files - /// - UNIFFI_DART_FAILURE_DELAY: failure delay (seconds) - pub fn from_env() -> Self { - let mut config = Self::default(); - - if let Ok(test_dir) = std::env::var("UNIFFI_DART_TEST_DIR") { - config.custom_output_dir = Some(Utf8PathBuf::from(test_dir)); - } - if std::env::var("UNIFFI_DART_NO_DELETE").is_ok() { - config.no_delete = true; - } - if let Ok(delay_str) = std::env::var("UNIFFI_DART_FAILURE_DELAY") { - if let Ok(delay) = delay_str.parse::() { - config.failure_delay_secs = Some(delay); - } - } - - config - } - - pub fn with_no_delete(mut self, no_delete: bool) -> Self { - self.no_delete = no_delete; - self - } - - pub fn with_output_dir>(mut self, dir: P) -> Self { - self.custom_output_dir = Some(dir.into()); - self - } - - pub fn with_failure_delay(mut self, delay_secs: u64) -> Self { - self.failure_delay_secs = Some(delay_secs); - self - } -} - -/// Run a test with default options (env vars honored) -/// -/// Env overrides: -/// - UNIFFI_DART_TEST_DIR -/// - UNIFFI_DART_NO_DELETE -/// - UNIFFI_DART_FAILURE_DELAY -pub fn run_test(fixture: &str, udl_path: &str, config_path: Option<&str>) -> Result<()> { - run_test_with_config(fixture, udl_path, config_path, &TestConfig::from_env()) -} - -/// Run a test in library mode, over every crate whose scaffolding `fixture`'s cdylib holds -/// -/// Env overrides are the same as `run_test`'s. -pub fn run_library_test(fixture: &str) -> Result<()> { - run_test_impl(fixture, None, None, &TestConfig::from_env()) -} - -/// Run a test with explicit configuration -pub fn run_test_with_config( - fixture: &str, - udl_path: &str, - config_path: Option<&str>, - test_config: &TestConfig, -) -> Result<()> { - run_test_impl(fixture, Some(udl_path), config_path, test_config) -} - -/// Run a test with an explicit output directory (convenience wrapper) -pub fn run_test_with_output_dir( - fixture: &str, - udl_path: &str, - config_path: Option<&str>, - custom_output_dir: Option<&Utf8Path>, -) -> Result<()> { - let config = TestConfig { - custom_output_dir: custom_output_dir.map(|p| p.to_owned()), - ..Default::default() - }; - run_test_impl(fixture, Some(udl_path), config_path, &config) -} - -/// Test execution (core implementation), in library mode without a UDL file -fn run_test_impl( - fixture: &str, - udl_path: Option<&str>, - config_path: Option<&str>, - test_config: &TestConfig, -) -> Result<()> { - // Resolve project root (cargo may change CWD when running tests) - let project_root = find_project_root()?; - - let script_path = Utf8Path::new(".").canonicalize_utf8()?; - let test_helper = UniFFITestHelper::new(fixture)?; - - // Function-scope guard to keep temp dir alive until function end - let mut _temp_guard: Option<_> = None; - - // Resolve output dir: custom → temp (with optional preservation) - let out_dir = if let Some(custom_dir) = &test_config.custom_output_dir { - let resolved_dir = if custom_dir.is_absolute() { - custom_dir.clone() - } else { - project_root.join(custom_dir) - }; - create_dir_all(&resolved_dir)?; - test_helper.create_out_dir(&resolved_dir, &script_path)? - } else { - let temp_dir = tempdir()?; - let out_dir = test_helper.create_out_dir(temp_dir.path(), &script_path)?; - if test_config.no_delete { - // Keep temp directory alive when no_delete is set - std::mem::forget(temp_dir); - } else { - _temp_guard = Some(temp_dir); - } - out_dir - }; - - let udl_path = match udl_path { - Some(udl_path) => Some(Utf8Path::new(".").canonicalize_utf8()?.join(udl_path)), - None => None, - }; - let config_path = if let Some(path) = config_path { - Some(Utf8Path::new(".").canonicalize_utf8()?.join(path)) - } else { - None - }; - - println!("{out_dir}"); - - if test_config.no_delete { - println!("Test files will be preserved after completion (no-delete mode)"); - } - - // Get package name from config (default to "uniffi") - let package_name = if let Some(config_path) = config_path.as_deref() { - // Try to read package name from config - if let Ok(config_content) = std::fs::read_to_string(config_path) { - if let Ok(config_toml) = toml::from_str::(&config_content) { - config_toml - .get("bindings") - .and_then(|b| b.get("dart")) - .and_then(|d| d.get("package_name")) - .and_then(|p| p.as_str()) - .map(|s| s.to_string()) - .unwrap_or_else(|| "uniffi".to_string()) - } else { - "uniffi".to_string() - } - } else { - "uniffi".to_string() - } - } else { - "uniffi".to_string() - }; - - let mut pubspec = File::create(out_dir.join("pubspec.yaml"))?; - pubspec.write_all( - format!( - r#" -name: {} -description: testing module for uniffi -version: 1.0.0 - -environment: - sdk: '>=3.10.0' -dev_dependencies: - test: ^1.24.3 -dependencies: - ffi: ^2.0.1 - code_assets: any - hooks: any -"#, - package_name - ) - .as_bytes(), - )?; - pubspec.flush()?; - let test_outdir = out_dir.join("test"); - create_dir_all(&test_outdir)?; - - // Create hook directory for Native Assets - let hook_dir = out_dir.join("hook"); - create_dir_all(&hook_dir)?; - - // Copy cdylib and get its path - test_helper.copy_cdylib_to_out_dir(&out_dir)?; - let cdylib_path = test_helper.cdylib_path()?; - let cdylib_filename = cdylib_path.file_name().unwrap(); - - // Get the asset ID (should match what's in generated Dart code) - // Format: "uniffi:{cdylib_name}" (without package prefix - that's added by Dart automatically) - let cdylib_stem = cdylib_path.file_stem().unwrap().trim_start_matches("lib"); // Remove "lib" prefix on Unix - - // Create Native Assets build hook using modern hooks package - let mut build_hook = File::create(hook_dir.join("build.dart"))?; - build_hook.write_all( - format!( - r#"import 'package:code_assets/code_assets.dart'; -import 'package:hooks/hooks.dart'; - -// Generated by uniffi-dart – this is the full asset ID that Dart will use -// Dart automatically prefixes the 'name' with 'package:$packageName/', so we construct the full ID here -String _makeAssetId(String packageName) => 'package:$packageName/uniffi:{}'; - -void main(List args) async {{ - await build(args, (input, output) async {{ - // The native library is in the package root (copied by test infrastructure) - final libPath = input.packageRoot.resolve('{}'); - - // Register the asset - Dart will automatically prefix the name with package:$packageName/ - // So if name is "uniffi:hello_world", the full ID becomes "package:uniffi/uniffi:hello_world" - output.assets.code.add( - CodeAsset( - package: input.packageName, - name: 'uniffi:{}', // Dart prefixes this with "package:$packageName/" - linkMode: DynamicLoadingBundled(), - file: libPath, - ), - ); - - // Verify the asset ID matches what's in generated code - print('Registered asset: ${{_makeAssetId(input.packageName)}}'); - }}); -}} -"#, - cdylib_stem, cdylib_filename, cdylib_stem - ) - .as_bytes(), - )?; - build_hook.flush()?; - gen::generate_dart_bindings( - // Library mode reads no UDL file. - udl_path.as_deref().unwrap_or(Utf8Path::new("")), - config_path.as_deref(), - Some(&out_dir), - &test_helper.cdylib_path()?, - udl_path.is_none(), // library_mode - None, // crate_name filter (library mode only) - true, // try_format - )?; - - // Copy fixture test files to output directory - let test_glob_pattern = "test/*.dart"; - for file in glob::glob(test_glob_pattern)?.filter_map(Result::ok) { - let filename = file.file_name().expect("bad filename").to_str().expect("non-UTF8 filename"); - copy(&file, test_outdir.join(filename))?; - } - - // Best effort formatting - let mut format_command = Command::new("dart"); - format_command.current_dir(&out_dir).arg("format").arg("."); - match format_command.spawn().and_then(|mut c| c.wait()) { - Ok(status) if status.success() => {} - Ok(_) | Err(_) => { - println!("WARNING: dart format unavailable or failed; continuing with tests anyway"); - if std::env::var("CI").is_err() { - thread::sleep(Duration::from_secs(1)); - } - } - } - - // Run tests - let mut command = Command::new("dart"); - command.current_dir(&out_dir).arg("test"); - let status = command.spawn()?.wait()?; - if !status.success() { - println!("FAILED"); - - // Optional delay after failure (skipped on CI) - let delay_secs = test_config.failure_delay_secs.unwrap_or(2); - if delay_secs > 0 && std::env::var("CI").is_err() { - println!("Waiting {} seconds before cleanup...", delay_secs); - thread::sleep(Duration::from_secs(delay_secs)); - } - - bail!("running `dart` to run test script failed ({:?})", command); - } - Ok(()) -} - -/// Locate the workspace root: -/// - CARGO_WORKSPACE_ROOT if set -/// - ascend until a Cargo.toml with [workspace] -fn find_project_root() -> Result { - if let Ok(ws_root) = std::env::var("CARGO_WORKSPACE_ROOT") { - if let Some(p) = Utf8Path::from_path(std::path::Path::new(&ws_root)) { - return Ok(p.to_owned()); - } - } - - let mut current = std::env::current_dir() - .map_err(|e| anyhow::anyhow!("Failed to get current directory: {}", e))?; - - loop { - let cargo_toml = current.join("Cargo.toml"); - if cargo_toml.exists() { - if let Ok(content) = std::fs::read_to_string(&cargo_toml) { - if content.contains("[workspace]") { - return Utf8Path::from_path(¤t) - .ok_or_else(|| anyhow::anyhow!("Project root path is not valid UTF-8")) - .map(|p| p.to_owned()); - } - } - } - if let Some(parent) = current.parent() { - current = parent.to_owned(); - } else { - break; - } - } - - Utf8Path::from_path(&std::env::current_dir()?) - .ok_or_else(|| anyhow::anyhow!("Current directory path is not valid UTF-8")) - .map(|p| p.to_owned()) -} - -pub fn get_compile_sources() -> Result> { - todo!("Not implemented") -} - -/// Generate bindings for `fixture` in **library mode** — reading the crate's -/// committed `uniffi.toml` from cargo metadata, with no `--config` override — -/// and assert the emitted asset id uses `expected_package`. -/// -/// This guards the library-mode config path: if the bindgen failed to read the -/// crate's `uniffi.toml`, `package_name` would default and the generated -/// `_uniffiAssetId` would desync from what the Native Assets build hook -/// registers (the Dart compiles, then fails to find the library at run time). -/// It is the only in-repo test that exercises `generate_dart_bindings` with -/// `library_mode = true` — every fixture `run_test` uses non-library mode. -pub fn assert_library_mode_asset_id(fixture: &str, expected_package: &str) -> Result<()> { - let script_path = Utf8Path::new(".").canonicalize_utf8()?; - let test_helper = UniFFITestHelper::new(fixture)?; - - let temp_dir = tempdir()?; - let out_dir = test_helper.create_out_dir(temp_dir.path(), &script_path)?; - test_helper.copy_cdylib_to_out_dir(&out_dir)?; - let cdylib_path = test_helper.cdylib_path()?; - - // Library mode; no `--config`, so the config comes solely from the crate's - // `uniffi.toml`. `udl_file` is unused on the library-mode path — pass the - // cdylib as a harmless stand-in. `try_format = false` keeps the test from - // depending on a `dart` toolchain. - gen::generate_dart_bindings( - &cdylib_path, - None, - Some(&out_dir), - &cdylib_path, - true, - None, - false, - )?; - - let expected = format!("package:{expected_package}/"); - for entry in glob::glob(&format!("{out_dir}/*.dart"))?.filter_map(Result::ok) { - if std::fs::read_to_string(&entry)?.contains(&expected) { - return Ok(()); - } - } - bail!( - "no generated .dart under {out_dir} contains the asset-id prefix `{expected}` \ - — library mode did not read the crate's uniffi.toml" - ); -} diff --git a/uniffi/dart/uniffi_dart_macro/Cargo.toml b/uniffi/dart/uniffi_dart_macro/Cargo.toml deleted file mode 100644 index 165421a05..000000000 --- a/uniffi/dart/uniffi_dart_macro/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "uniffi_dart_macro" -version = "0.1.0" -publish = false -edition = "2021" - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1.0" -quote = "1.0" -syn = { version = "1.0", features = ["full"] } -stringcase = "0.3.0" -futures = "0.3" -uniffi = { workspace = true, features = [ - "build", "tokio" -] } diff --git a/uniffi/dart/uniffi_dart_macro/src/lib.rs b/uniffi/dart/uniffi_dart_macro/src/lib.rs deleted file mode 100644 index aa5a8b602..000000000 --- a/uniffi/dart/uniffi_dart_macro/src/lib.rs +++ /dev/null @@ -1,95 +0,0 @@ -use proc_macro::TokenStream; -use quote::{format_ident, quote}; -use stringcase::pascal_case; -use syn::parse::Parse; -use syn::{parse_macro_input, Ident, ItemFn, LitStr, Type}; - -struct StreamAttr { - item_type: Type, - runtime: Option, -} - -impl Parse for StreamAttr { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - let item_type: Type = input.parse()?; - let mut runtime = None; - - while input.peek(syn::Token![,]) { - input.parse::()?; - - if input.is_empty() { - break; - } - - let ident: Ident = input.parse()?; - - if ident != "runtime" { - return Err(syn::Error::new_spanned(ident, "expected `runtime`")); - } - - input.parse::()?; - if runtime.is_some() { - return Err(syn::Error::new(ident.span(), "duplicate `runtime` argument")); - } - - let value: LitStr = input.parse()?; - runtime = Some(value); - } - - Ok(StreamAttr { item_type, runtime }) - } -} - -#[proc_macro_attribute] -pub fn export_stream(attr: TokenStream, item: TokenStream) -> TokenStream { - let attr = parse_macro_input!(attr as StreamAttr); - let input = parse_macro_input!(item as ItemFn); - - let fn_name = &input.sig.ident; - let vis = &input.vis; - let struct_name = format_ident!("{}StreamExt", pascal_case(&fn_name.to_string())); - let create_fn_name = format_ident!("create_stream_{}", fn_name); - let StreamAttr { item_type, runtime } = attr; - let runtime_attr = if let Some(runtime) = runtime { - quote!(#[uniffi::export(async_runtime = #runtime)]) - } else { - quote!(#[uniffi::export(async_runtime = "tokio")]) - }; - - let expanded = quote! { - #input - - #[derive(uniffi::Object)] - #vis struct #struct_name { - stream: std::sync::Mutex + Send>>>, - } - - #runtime_attr - impl #struct_name { - #[uniffi::constructor] - pub fn new() -> std::sync::Arc { - std::sync::Arc::new(Self { - stream: std::sync::Mutex::new(Box::pin(#fn_name())), - }) - } - - pub async fn next(&self) -> Option<#item_type> { - futures::future::poll_fn(|cx| { - let mut stream = self - .stream - .lock() - .expect("stream mutex poisoned"); - stream.as_mut().poll_next(cx) - }).await - } - - } - - #[uniffi::export] - #vis fn #create_fn_name() -> std::sync::Arc<#struct_name> { - #struct_name::new() - } - }; - - TokenStream::from(expanded) -} diff --git a/uniffi/examples/README.md b/uniffi/examples/README.md deleted file mode 100644 index 5c7eefe66..000000000 --- a/uniffi/examples/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Example uniffi components - -This directory contains some small example components implemented using uniffi. It's currently being used -more as a living test environment than user-facing docs, but hopefully it gives you a bit of an idea of -what we're up to with this crate. - -Newcomers are recommended to explore them in the following order: - -* [`./arithmetic/`](./arithmetic/) is the most minimal example - just some plain functions that operate - on integers, and some minimal error handling. -* [`./arithmetic-procmacro/`](./arithmetic-procmacro/) is a copy of the above example implemented using - procmacros - it has no UDL file nor `build.rs` script. -* [`./geometry/`](./geometry/) shows how to use records and nullable types for working with more complex - data. -* [`./sprites/`](./sprites/) shows how to work with stateful objects that have methods, in classical - object-oriented style. -* [`./todolist`](./todolist/) is a simplistic todo-list that can only add items and show the last item, - meant to show how interacting with strings works. -* [`./rondpoint`](./rondpoint/) exercises complex data types by round-tripping them from the foreign-language - code, through rust and back again. -* [`./async-api-client`](./async-api-client/) shows how to handle async calls across the FFI. The - foreign code supplies the HTTP client, the Rust code uses that client to expose a GitHub API - client, then the foreign code consumes the client. All code on both sides of the FFI is async. - -Each example has the following structure: - -* `src/.udl`, the component interface definition which defines the main object and its methods. - This is processed by functions in `build.rs` to generate Rust scaffolding for the component. -* `src/lib.rs`, the core implementation of the component in Rust. This basically - pulls in the generated Rust scaffolding via `uniffi::include_scaffolding!()` and fills in function implementations. -* `Cargo.toml` configures the crate to build a `cdylib` with an appropriate name. -* Some small test scripts that double as API examples in each target foreign language: - * Kotlin `tests/bindings/test_.kts` - * Swift `tests/bindings/test_.swift` - * Python `tests/bindings/test_.py` - * Ruby `tests/bindings/test_.rb` - -If you want to try them out, you will need: - -* The [Kotlin command-line tools](https://kotlinlang.org/docs/tutorials/command-line.html), particularly `kotlinc`. -* The [Java Native Access](https://github.com/java-native-access/jna#download) JAR downloaded and its path - added to your `$CLASSPATH` environment variable. -* Python 3 -* The [Swift command-line tools](https://swift.org/download/), particularly `swift`, `swiftc` and - the `Foundation` package. -* The [Ruby FFI](https://github.com/ffi/ffi#installation) - * `gem install ffi test-unit rubocop` - -We publish a [docker image](https://hub.docker.com/r/janerik/uniffi-ci-test) that has all of this dependencies -pre-installed, if you want to get up and running quickly. - -With that in place, try the following: - -* Run `cargo build`. That compiles the component implementation into a native library named `uniffi_` - in `../target/debug/`. -* Run `cargo test`. This will run each of the foreign-language testcases against the compiled Rust code, - confirming whether everything is working as intended. -* Explore the build process in more detail: - * Change to the root directory of this repo, so the `uniffi-bindgen` package referenced below can be found. - * Run `cargo run --bin uniffi-bindgen -- scaffolding examples//src/.udl`. - This will generate the Rust scaffolding code which exposes a C FFI for the component. - You can view the generated code in `./src/.uniffi.rs`. - * Run `cargo run --bin uniffi-bindgen -- generate --language kotlin examples//src/.udl`. - This will generate the foreign-language bindings for Kotlin, which load the compiled Rust code - and use the C FFI generated above to interact with it. - You can view the generated code in `./src/uniffi//.kt`. - * Try using `--language swift`, `--language python`, or `--language ruby` to explore the foreign-language bindings - generated for other languages. diff --git a/uniffi/examples/arithmetic-procmacro/Cargo.toml b/uniffi/examples/arithmetic-procmacro/Cargo.toml deleted file mode 100644 index 90c1cde5e..000000000 --- a/uniffi/examples/arithmetic-procmacro/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "uniffi-example-arithmetic-procmacro" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "arithmeticpm" - -[dependencies] -uniffi = { workspace = true } -thiserror = "2" - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/arithmetic-procmacro/src/lib.rs b/uniffi/examples/arithmetic-procmacro/src/lib.rs deleted file mode 100644 index a123702bb..000000000 --- a/uniffi/examples/arithmetic-procmacro/src/lib.rs +++ /dev/null @@ -1,40 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// This example uses `uniffi::` macros to describe the interface. - -#[derive(Debug, thiserror::Error, uniffi::Error)] -pub enum ArithmeticError { - #[error("Integer overflow on an operation with {a} and {b}")] - IntegerOverflow { a: u64, b: u64 }, -} - -#[uniffi::export] -fn add(a: u64, b: u64) -> Result { - a.checked_add(b) - .ok_or(ArithmeticError::IntegerOverflow { a, b }) -} - -#[uniffi::export] -fn sub(a: u64, b: u64) -> Result { - a.checked_sub(b) - .ok_or(ArithmeticError::IntegerOverflow { a, b }) -} - -#[uniffi::export] -fn div(dividend: u64, divisor: u64) -> u64 { - if divisor == 0 { - panic!("Can't divide by zero"); - } - dividend / divisor -} - -#[uniffi::export] -fn equal(a: u64, b: u64) -> bool { - a == b -} - -type Result = std::result::Result; - -uniffi::setup_scaffolding!(); diff --git a/uniffi/examples/arithmetic-procmacro/tests/test.py b/uniffi/examples/arithmetic-procmacro/tests/test.py deleted file mode 100644 index 9099d475a..000000000 --- a/uniffi/examples/arithmetic-procmacro/tests/test.py +++ /dev/null @@ -1,14 +0,0 @@ -from arithmeticpm import * - -try: - add(18446744073709551615, 1) - assert(not("Should have thrown a IntegerOverflow exception!")) -except ArithmeticError.IntegerOverflow: - # It's okay! - pass - -assert add(2, 4) == 6 -assert sub(4, 2) == 2 -assert div(8, 4) == 2 -assert equal(2, 2) -assert not equal(4, 8) diff --git a/uniffi/examples/arithmetic-procmacro/tests/test_generated_bindings.rs b/uniffi/examples/arithmetic-procmacro/tests/test_generated_bindings.rs deleted file mode 100644 index f6b2902e2..000000000 --- a/uniffi/examples/arithmetic-procmacro/tests/test_generated_bindings.rs +++ /dev/null @@ -1,3 +0,0 @@ -// See the tests from the `arithmetic` crate for more comprehensive -// examples - there's just a Python smoke-test here. -uniffi::build_foreign_language_testcases!("tests/test.py"); diff --git a/uniffi/examples/arithmetic/Cargo.toml b/uniffi/examples/arithmetic/Cargo.toml deleted file mode 100644 index ed9089518..000000000 --- a/uniffi/examples/arithmetic/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "uniffi-example-arithmetic" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "arithmetical" - -[dependencies] -uniffi = { workspace = true, features=["scaffolding-ffi-buffer-fns"] } -thiserror = "2" - -[build-dependencies] -# Add the "scaffolding-ffi-buffer-fns" feature to make sure things can build correctly -uniffi = { workspace = true, features = ["build", "scaffolding-ffi-buffer-fns"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/arithmetic/build.rs b/uniffi/examples/arithmetic/build.rs deleted file mode 100644 index 303ac22d8..000000000 --- a/uniffi/examples/arithmetic/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/arithmetic.udl").unwrap(); -} diff --git a/uniffi/examples/arithmetic/src/arithmetic.udl b/uniffi/examples/arithmetic/src/arithmetic.udl deleted file mode 100644 index 117df4834..000000000 --- a/uniffi/examples/arithmetic/src/arithmetic.udl +++ /dev/null @@ -1,16 +0,0 @@ -[Error] -enum ArithmeticError { - "IntegerOverflow", -}; - -namespace arithmetic { - [Throws=ArithmeticError] - u64 add(u64 a, u64 b); - - [Throws=ArithmeticError] - u64 sub(u64 a, u64 b); - - u64 div(u64 dividend, u64 divisor); - - boolean equal(u64 a, u64 b); -}; diff --git a/uniffi/examples/arithmetic/src/lib.rs b/uniffi/examples/arithmetic/src/lib.rs deleted file mode 100644 index 92ab8c072..000000000 --- a/uniffi/examples/arithmetic/src/lib.rs +++ /dev/null @@ -1,34 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[derive(Debug, thiserror::Error)] -pub enum ArithmeticError { - #[error("Integer overflow on an operation with {a} and {b}")] - IntegerOverflow { a: u64, b: u64 }, -} - -fn add(a: u64, b: u64) -> Result { - a.checked_add(b) - .ok_or(ArithmeticError::IntegerOverflow { a, b }) -} - -fn sub(a: u64, b: u64) -> Result { - a.checked_sub(b) - .ok_or(ArithmeticError::IntegerOverflow { a, b }) -} - -fn div(dividend: u64, divisor: u64) -> u64 { - if divisor == 0 { - panic!("Can't divide by zero"); - } - dividend / divisor -} - -fn equal(a: u64, b: u64) -> bool { - a == b -} - -type Result = std::result::Result; - -uniffi::include_scaffolding!("arithmetic"); diff --git a/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.kts b/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.kts deleted file mode 100644 index ef11850ae..000000000 --- a/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.kts +++ /dev/null @@ -1,29 +0,0 @@ -import org.mozilla.uniffi.example.arithmetic.*; - -assert(add(2u, 4u) == 6uL) -assert(add(4u, 8u) == 12uL) - -try { - sub(0u, 2u) - throw RuntimeException("Should have thrown a IntegerOverflow exception!") -} catch (e: ArithmeticException) { - // It's okay! -} - -assert(sub(4u, 2u) == 2uL) -assert(sub(8u, 4u) == 4uL) - -assert(div(8u, 4u) == 2uL) - -try { - div(8u, 0u) - throw RuntimeException("Should have panicked when dividing by zero") -} catch (e: InternalException) { - // It's okay! -} - -assert(equal(2u, 2uL)) -assert(equal(4u, 4uL)) - -assert(!equal(2u, 4uL)) -assert(!equal(4u, 8uL)) diff --git a/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.py b/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.py deleted file mode 100644 index 0d4e666fb..000000000 --- a/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.py +++ /dev/null @@ -1,37 +0,0 @@ -from arithmetic import * - -try: - add(18446744073709551615, 1) - assert(not("Should have thrown a IntegerOverflow exception!")) -except ArithmeticError.IntegerOverflow: - # It's okay! - pass - -assert add(2, 4) == 6 -assert add(4, 8) == 12 - -try: - sub(0, 1) - assert(not("Should have thrown a IntegerOverflow exception!")) -except ArithmeticError.IntegerOverflow: - # It's okay! - pass - -assert sub(4, 2) == 2 -assert sub(8, 4) == 4 - -assert div(8, 4) == 2 - -try: - div(8, 0) -except InternalError: - # It's okay! - pass -else: - assert(not("Should have panicked when dividing by zero")) - -assert equal(2, 2) -assert equal(4, 4) - -assert not equal(2, 4) -assert not equal(4, 8) diff --git a/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.swift b/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.swift deleted file mode 100644 index a8e34680e..000000000 --- a/uniffi/examples/arithmetic/tests/bindings/test_arithmetic.swift +++ /dev/null @@ -1,32 +0,0 @@ -import arithmetic - -do { - let _ = try add(a: 18446744073709551615, b: 1) - fatalError("Should have thrown a IntegerOverflow exception!") -} catch ArithmeticError.IntegerOverflow { - // It's okay! -} - -assert(try! add(a: 2, b: 4) == 6, "add work") -assert(try! add(a: 4, b: 8) == 12, "add work") - -do { - let _ = try sub(a: 0, b: 1) - fatalError("Should have thrown a IntegerOverflow exception!") -} catch ArithmeticError.IntegerOverflow { - // It's okay! -} - -assert(try! sub(a: 4, b: 2) == 2, "sub work") -assert(try! sub(a: 8, b: 4) == 4, "sub work") - -assert(div(dividend: 8, divisor: 4) == 2, "div works") - -// We can't test panicking in Swift because we force unwrap the error in -// `div`, which we can't catch. - -assert(equal(a: 2, b: 2), "equal works") -assert(equal(a: 4, b: 4), "equal works") - -assert(!equal(a: 2, b: 4), "non-equal works") -assert(!equal(a: 4, b: 8), "non-equal works") diff --git a/uniffi/examples/arithmetic/tests/test_generated_bindings.rs b/uniffi/examples/arithmetic/tests/test_generated_bindings.rs deleted file mode 100644 index 121e1549e..000000000 --- a/uniffi/examples/arithmetic/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_arithmetic.py", - "tests/bindings/test_arithmetic.kts", - "tests/bindings/test_arithmetic.swift", -); diff --git a/uniffi/examples/arithmetic/uniffi.toml b/uniffi/examples/arithmetic/uniffi.toml deleted file mode 100644 index 883231dca..000000000 --- a/uniffi/examples/arithmetic/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.kotlin] -package_name = "org.mozilla.uniffi.example.arithmetic" diff --git a/uniffi/examples/async-api-client/Cargo.toml b/uniffi/examples/async-api-client/Cargo.toml deleted file mode 100644 index 53b0a4592..000000000 --- a/uniffi/examples/async-api-client/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "uniffi-example-async-api-client" -edition = "2021" -version = "0.26.1" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_async_api_client" - -[dependencies] -async-trait = "0.1" -uniffi = { workspace = true } -serde = { version = "1", features=["derive"] } -serde_json = "1" -thiserror = "2" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/async-api-client/README.md b/uniffi/examples/async-api-client/README.md deleted file mode 100644 index f97734414..000000000 --- a/uniffi/examples/async-api-client/README.md +++ /dev/null @@ -1,28 +0,0 @@ -This crate is a toy build an async API client, with some parts implemented in Rust and some parts -implemented in the foreign language. Each side makes async calls across the FFI. - -The motivation is to show how to build an async-based Rust library, using a foreign async executor to drive the futures. -Note that the Rust code does not start any threads of its own, nor does it use startup an async runtime like tokio. -Instead, it awaits async calls to the foreign code and the foreign executor manages the threads. - -There are two basic ways the Rust code in this crate awaits the foreign code: - -## API calls - -API calls are the simple case. -Rust awaits an HTTP call to the foreign side, then uses `serde` to parse the JSON into a structured response. -As long as the Rust code is "non-blocking" this system should work fine. -Note: there is not a strict definition for "non-blocking", but typically it means not performing IO and not executing a long-running CPU operation. - -## Blocking tasks - -The more difficult case is a blocking Rust call. -The example from this crate is reading the API credentials from disk. -The `tasks.rs` module and the foreign implementations of the `TaskRunner` interface are an experiment to show how this can be accomplished using async callback methods. - -The code works, but is a bit clunky. -For example requiring that the task closure is `'static` creates some extra work for the `load_credentials` function. -It also requires an extra `Mutex` and `Arc`. - -The UniFFI team is looking for ways to simplify this process by handling it natively in UniFFI, see https://github.com/mozilla/uniffi-rs/pull/1837. -If you are writing Rust code that needs to make async blocking calls, please tell us about your use case which will help us develop the feature. diff --git a/uniffi/examples/async-api-client/build.rs b/uniffi/examples/async-api-client/build.rs deleted file mode 100644 index 2b44dddc7..000000000 --- a/uniffi/examples/async-api-client/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/async-api-client.udl").unwrap(); -} diff --git a/uniffi/examples/async-api-client/src/api_client.rs b/uniffi/examples/async-api-client/src/api_client.rs deleted file mode 100644 index adf9c5d45..000000000 --- a/uniffi/examples/async-api-client/src/api_client.rs +++ /dev/null @@ -1,77 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use crate::{run_task, ApiError, Result, TaskRunner}; -use std::sync::Arc; - -#[async_trait::async_trait] -#[uniffi::trait_interface] -pub trait HttpClient: Send + Sync { - async fn fetch(&self, url: String, credentials: String) -> Result; -} - -impl From for ApiError { - fn from(e: serde_json::Error) -> Self { - Self::Json { - reason: e.to_string(), - } - } -} - -#[derive(Debug, serde::Deserialize)] -pub struct Issue { - pub url: String, - pub title: String, - pub state: IssueState, -} - -#[derive(Debug, serde::Deserialize)] -pub enum IssueState { - #[serde(rename = "open")] - Open, - #[serde(rename = "closed")] - Closed, -} - -pub struct ApiClient { - http_client: Arc, - task_runner: Arc, -} - -impl ApiClient { - // Pretend this is a blocking call that needs to load the credentials from disk/network - fn load_credentials_sync(&self) -> String { - String::from("username:password") - } - - async fn load_credentials(self: Arc) -> String { - let self_cloned = Arc::clone(&self); - run_task(&self.task_runner, move || { - self_cloned.load_credentials_sync() - }) - .await - } -} - -impl ApiClient { - pub fn new(http_client: Arc, task_runner: Arc) -> Self { - Self { - http_client, - task_runner, - } - } - - pub async fn get_issue( - self: Arc, - owner: String, - repository: String, - issue_number: u32, - ) -> Result { - let credentials = self.clone().load_credentials().await; - let url = - format!("https://api.github.com/repos/{owner}/{repository}/issues/{issue_number}"); - let body = self.http_client.fetch(url, credentials).await?; - Ok(serde_json::from_str(&body)?) - } -} diff --git a/uniffi/examples/async-api-client/src/async-api-client.udl b/uniffi/examples/async-api-client/src/async-api-client.udl deleted file mode 100644 index 282c433a9..000000000 --- a/uniffi/examples/async-api-client/src/async-api-client.udl +++ /dev/null @@ -1,49 +0,0 @@ -namespace async_api_client { - string test_response_data(); -}; - -[Error] -interface ApiError { - Http(string reason); - Api(string reason); - Json(string reason); -}; - -// Implemented by the foreign bindings -[Trait, WithForeign] -interface HttpClient { - [Throws=ApiError, Async] - string fetch(string url, string credentials); // fetch an URL and return the body -}; - -// Run Rust tasks in a thread pool. -// Implemented by the foreign bindings -[Trait, WithForeign] -interface TaskRunner { - [Async] - void run_task(RustTask task); -}; - -[Trait] -interface RustTask { - void execute(); -}; - -dictionary Issue { - string url; - string title; - IssueState state; -}; - -enum IssueState { - "Open", - "Closed", -}; - -// Implemented by the Rust code -interface ApiClient { - constructor(HttpClient http_client, TaskRunner task_runner); - - [Throws=ApiError, Async] - Issue get_issue(string owner, string repository, u32 issue_number); -}; diff --git a/uniffi/examples/async-api-client/src/lib.rs b/uniffi/examples/async-api-client/src/lib.rs deleted file mode 100644 index 8417136e3..000000000 --- a/uniffi/examples/async-api-client/src/lib.rs +++ /dev/null @@ -1,25 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -mod api_client; -mod tasks; -mod test_data; - -pub use api_client::{ApiClient, HttpClient, Issue, IssueState}; -pub use tasks::{run_task, RustTask, TaskRunner}; -pub use test_data::test_response_data; - -#[derive(Debug, thiserror::Error)] -pub enum ApiError { - #[error("HttpError: {reason}")] - Http { reason: String }, - #[error("ApiError: {reason}")] - Api { reason: String }, - #[error("JsonError: {reason}")] - Json { reason: String }, -} - -pub type Result = std::result::Result; - -uniffi::include_scaffolding!("async-api-client"); diff --git a/uniffi/examples/async-api-client/src/tasks.rs b/uniffi/examples/async-api-client/src/tasks.rs deleted file mode 100644 index 30f4ff3fd..000000000 --- a/uniffi/examples/async-api-client/src/tasks.rs +++ /dev/null @@ -1,92 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::{Arc, Mutex}; - -#[async_trait::async_trait] -#[uniffi::trait_interface] -pub trait TaskRunner: Send + Sync { - async fn run_task(&self, task: Arc); -} - -#[uniffi::trait_interface] -pub trait RustTask: Send + Sync { - fn execute(&self); -} - -pub async fn run_task(runner: &Arc, closure: F) -> T -where - F: FnOnce() -> T + Send + Sync + 'static, - T: Send + 'static, -{ - let closure = Arc::new(TaskClosure::new(closure)); - runner - .run_task(Arc::clone(&closure) as Arc) - .await; - closure.take_result() -} - -struct TaskClosure -where - F: FnOnce() -> T + Send + Sync, - T: Send, -{ - inner: Mutex>, -} - -enum TaskClosureInner -where - F: FnOnce() -> T + Send + Sync, - T: Send, -{ - Pending(F), - Running, - Complete(T), - Finished, -} - -impl TaskClosure -where - F: FnOnce() -> T + Send + Sync, - T: Send, -{ - fn new(closure: F) -> Self { - Self { - inner: Mutex::new(TaskClosureInner::Pending(closure)), - } - } - - fn take_result(&self) -> T { - let mut inner = self.inner.lock().unwrap(); - match *inner { - TaskClosureInner::Pending(_) => panic!("Task never ran"), - TaskClosureInner::Running => panic!("Task still running"), - TaskClosureInner::Finished => panic!("Task already finished"), - TaskClosureInner::Complete(_) => (), - }; - match std::mem::replace(&mut *inner, TaskClosureInner::Finished) { - TaskClosureInner::Complete(v) => v, - _ => unreachable!(), - } - } -} - -impl RustTask for TaskClosure -where - F: FnOnce() -> T + Send + Sync, - T: Send, -{ - fn execute(&self) { - let mut inner = self.inner.lock().unwrap(); - match std::mem::replace(&mut *inner, TaskClosureInner::Running) { - TaskClosureInner::Pending(f) => { - let result = f(); - *inner = TaskClosureInner::Complete(result) - } - TaskClosureInner::Running => panic!("Task already started"), - TaskClosureInner::Complete(_) => panic!("Task already executed"), - TaskClosureInner::Finished => panic!("Task already finished"), - } - } -} diff --git a/uniffi/examples/async-api-client/src/test_data.rs b/uniffi/examples/async-api-client/src/test_data.rs deleted file mode 100644 index 9c502f4d6..000000000 --- a/uniffi/examples/async-api-client/src/test_data.rs +++ /dev/null @@ -1,76 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/// Sample data downloaded from a real github api call -/// -/// The tests don't make real HTTP calls to avoid them failing because of network errors. -pub fn test_response_data() -> String { - String::from( - r#"{ - "url": "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017", - "repository_url": "https://api.github.com/repos/mozilla/uniffi-rs", - "labels_url": "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017/labels{/name}", - "comments_url": "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017/comments", - "events_url": "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017/events", - "html_url": "https://github.com/mozilla/uniffi-rs/issues/2017", - "id": 2174982360, - "node_id": "I_kwDOECpYAM6Bo5jY", - "number": 2017, - "title": "Foreign-implemented async traits", - "user": { - "login": "bendk", - "id": 1012809, - "node_id": "MDQ6VXNlcjEwMTI4MDk=", - "avatar_url": "https://avatars.githubusercontent.com/u/1012809?v=4", - "gravatar_id": "", - "url": "https://api.github.com/users/bendk", - "html_url": "https://github.com/bendk", - "followers_url": "https://api.github.com/users/bendk/followers", - "following_url": "https://api.github.com/users/bendk/following{/other_user}", - "gists_url": "https://api.github.com/users/bendk/gists{/gist_id}", - "starred_url": "https://api.github.com/users/bendk/starred{/owner}{/repo}", - "subscriptions_url": "https://api.github.com/users/bendk/subscriptions", - "organizations_url": "https://api.github.com/users/bendk/orgs", - "repos_url": "https://api.github.com/users/bendk/repos", - "events_url": "https://api.github.com/users/bendk/events{/privacy}", - "received_events_url": "https://api.github.com/users/bendk/received_events", - "type": "User", - "site_admin": false - }, - "labels": [ - - ], - "state": "open", - "locked": false, - "assignee": null, - "assignees": [ - - ], - "milestone": null, - "comments": 0, - "created_at": "2024-03-07T23:07:29Z", - "updated_at": "2024-03-07T23:07:29Z", - "closed_at": null, - "author_association": "CONTRIBUTOR", - "active_lock_reason": null, - "body": "We currently allow Rust code to implement async trait methods, but foreign implementations are not supported. We should extend support to allow for foreign code.\\r\\n\\r\\nI think this is a key feature for full async support. It allows Rust code to define an async method that depends on a foreign async method. This allows users to use async code without running a Rust async runtime, you can effectively piggyback on the foreign async runtime.", - "closed_by": null, - "reactions": { - "url": "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017/reactions", - "total_count": 0, - "+1": 0, - "-1": 0, - "laugh": 0, - "hooray": 0, - "confused": 0, - "heart": 0, - "rocket": 0, - "eyes": 0 - }, - "timeline_url": "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017/timeline", - "performed_via_github_app": null, - "state_reason": null -}"#, - ) -} diff --git a/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.kts b/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.kts deleted file mode 100644 index 110a5f01d..000000000 --- a/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.kts +++ /dev/null @@ -1,37 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import uniffi.async_api_client.* - -class KtHttpClient : HttpClient { - override suspend fun fetch(url: String, credentials: String): String { - if (credentials != "username:password") { - throw ApiException.Http("Unauthorized") - } - // In the real-world we would use an async HTTP library and make a real - // HTTP request, but to keep the dependencies simple and avoid test - // fragility we just fake it. - if (url == "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017") { - return testResponseData() - } else { - throw ApiException.Http("Wrong URL: ${url}") - } - } -} - -class KtTaskRunner : TaskRunner { - override suspend fun runTask(task: RustTask) { - withContext(Dispatchers.IO) { - task.execute() - } - } -} - -kotlinx.coroutines.runBlocking { - val client = ApiClient(KtHttpClient(), KtTaskRunner()) - val issue = client.getIssue("mozilla", "uniffi-rs", 2017u) - assert(issue.title == "Foreign-implemented async traits") -} diff --git a/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.py b/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.py deleted file mode 100644 index f45682fcf..000000000 --- a/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.py +++ /dev/null @@ -1,35 +0,0 @@ -import asyncio -import concurrent.futures -import unittest -from urllib.request import urlopen -from async_api_client import * - -# Http client that the Rust code depends on -class PyHttpClient(HttpClient): - async def fetch(self, url, credentials): - if credentials != "username:password": - raise ApiError.Http("Unauthorized") - # In the real-world we would use something like aiohttp and make a real HTTP request, but to keep - # the dependencies simple and avoid test fragility we just fake it. - await asyncio.sleep(0.01) - if url == "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017": - return test_response_data() - else: - raise ApiError.Http(f"Wrong URL: {url}") - -# Run a rust task in a thread pool -class PyTaskRunner(TaskRunner): - def __init__(self): - self.executer = concurrent.futures.ThreadPoolExecutor() - - async def run_task(self, task): - return self.executer.submit(lambda: task.execute()).result() - -class CallbacksTest(unittest.IsolatedAsyncioTestCase): - async def test_api_client(self): - client = ApiClient(PyHttpClient(), PyTaskRunner()) - issue = await client.get_issue("mozilla", "uniffi-rs", 2017) - self.assertEqual(issue.title, "Foreign-implemented async traits") - -unittest.main() - diff --git a/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.swift b/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.swift deleted file mode 100644 index 0d6564489..000000000 --- a/uniffi/examples/async-api-client/tests/bindings/test_async_api_client.swift +++ /dev/null @@ -1,43 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import Foundation // To get `DispatchGroup` - -#if canImport(async_api_client) - import async_api_client -#endif - -final class SwiftHttpClient : HttpClient { - func fetch(url: String, credentials: String) async throws -> String { - if (credentials != "username:password") { - throw ApiError.Http(reason: "Unauthorized") - } - - // In the real-world we would use an async HTTP library and make a real - // HTTP request, but to keep the dependencies simple and avoid test - // fragility we just fake it. - if (url == "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017") { - return testResponseData() - } else { - throw ApiError.Http(reason: "Wrong URL: \(url)") - } - } -} - -final class SwiftTaskRunner : TaskRunner { - func runTask(task: RustTask) async { - let swiftTask = Task { task.execute() } - let _ = await swiftTask.result - } -} - -var counter = DispatchGroup() -counter.enter() -Task { - let client = ApiClient(httpClient: SwiftHttpClient(), taskRunner: SwiftTaskRunner()) - let issue = try! await client.getIssue(owner: "mozilla", repository: "uniffi-rs", issueNumber: 2017) - assert(issue.title == "Foreign-implemented async traits") - counter.leave() -} -counter.wait() diff --git a/uniffi/examples/async-api-client/tests/test_generated_bindings.rs b/uniffi/examples/async-api-client/tests/test_generated_bindings.rs deleted file mode 100644 index 609bbe4c2..000000000 --- a/uniffi/examples/async-api-client/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_async_api_client.kts", - "tests/bindings/test_async_api_client.swift", - "tests/bindings/test_async_api_client.py", -); diff --git a/uniffi/examples/callbacks/Cargo.toml b/uniffi/examples/callbacks/Cargo.toml deleted file mode 100644 index 31d1a5947..000000000 --- a/uniffi/examples/callbacks/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "uniffi-example-callbacks" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_callbacks" - -[dependencies] -uniffi = { workspace = true } -thiserror = "2" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/callbacks/README.md b/uniffi/examples/callbacks/README.md deleted file mode 100644 index 44d76f9e7..000000000 --- a/uniffi/examples/callbacks/README.md +++ /dev/null @@ -1,5 +0,0 @@ -This is an example of UniFFI "callbacks". - -Callbacks are the ability to implement Rust traits in foreign languages. These are defined by -[normal UniFFI traits](../../docs/manual/src/foreign_traits.md) or via ["callback" definitions](../../docs/manual/src/types/callback_interfaces.md). - diff --git a/uniffi/examples/callbacks/build.rs b/uniffi/examples/callbacks/build.rs deleted file mode 100644 index 1bdad42a1..000000000 --- a/uniffi/examples/callbacks/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/callbacks.udl").unwrap(); -} diff --git a/uniffi/examples/callbacks/src/callbacks.udl b/uniffi/examples/callbacks/src/callbacks.udl deleted file mode 100644 index 1ce79fda6..000000000 --- a/uniffi/examples/callbacks/src/callbacks.udl +++ /dev/null @@ -1,28 +0,0 @@ -namespace callbacks { - // `get_sim_cards` is defined via a procmacro. -}; - -// This trait is implemented in Rust and in foreign bindings. -[Trait, WithForeign] -interface SimCard { - string name(); // The name of the carrier/provider. -}; - -[Error] -enum TelephoneError { - "Busy", - "InternalTelephoneError", -}; - -interface Telephone { - constructor(); - [Throws=TelephoneError] - string call(SimCard sim, CallAnswerer answerer); -}; - -// callback interfaces are discouraged now that foreign code can -// implement traits, but here's one! -callback interface CallAnswerer { - [Throws=TelephoneError] - string answer(); -}; diff --git a/uniffi/examples/callbacks/src/lib.rs b/uniffi/examples/callbacks/src/lib.rs deleted file mode 100644 index 677f3b474..000000000 --- a/uniffi/examples/callbacks/src/lib.rs +++ /dev/null @@ -1,93 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -#[derive(Debug, thiserror::Error)] -pub enum TelephoneError { - #[error("Busy")] - Busy, - #[error("InternalTelephoneError")] - InternalTelephoneError, -} - -// Need to implement this From<> impl in order to handle unexpected callback errors. See the -// Callback Interfaces section of the handbook for more info. -impl From for TelephoneError { - fn from(_: uniffi::UnexpectedUniFFICallbackError) -> Self { - Self::InternalTelephoneError - } -} - -// SIM cards. -#[uniffi::trait_interface] -pub trait SimCard: Send + Sync { - fn name(&self) -> String; -} - -struct RustySim; -impl SimCard for RustySim { - fn name(&self) -> String { - "rusty!".to_string() - } -} - -// namespace functions. -#[uniffi::export] -fn get_sim_cards() -> Vec> { - vec![Arc::new(RustySim {})] -} - -// The call-answer, callback interface. -pub trait CallAnswerer { - fn answer(&self) -> Result; -} - -#[derive(Debug, Default, Clone)] -pub struct Telephone; -impl Telephone { - pub fn new() -> Self { - Self {} - } - - pub fn call( - &self, - // Traits are Arc<>, callbacks Box<>. - sim: Arc, - answerer: Box, - ) -> Result { - if sim.name() != "rusty!" { - Ok(format!("{} est bon marché", sim.name())) - } else { - answerer.answer() - } - } -} - -// Some proc-macro definitions of the same thing. -#[derive(uniffi::Object, Debug, Default, Clone)] -pub struct FancyTelephone; - -#[uniffi::export] -impl FancyTelephone { - #[uniffi::constructor] - pub fn new() -> Arc { - Arc::new(Self) - } - - // Exact same signature as the UDL version. - pub fn call( - &self, - sim: Arc, - answerer: Box, - ) -> Result { - if sim.name() != "rusty!" { - Ok(format!("{} est bon marché", sim.name())) - } else { - answerer.answer() - } - } -} - -uniffi::include_scaffolding!("callbacks"); diff --git a/uniffi/examples/callbacks/tests/bindings/test_callbacks.kts b/uniffi/examples/callbacks/tests/bindings/test_callbacks.kts deleted file mode 100644 index 9239bc6d9..000000000 --- a/uniffi/examples/callbacks/tests/bindings/test_callbacks.kts +++ /dev/null @@ -1,51 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import uniffi.callbacks.* - -class SomeOtherError: Exception() - -// Simple example just to see it work. -// Pass in a string, get a string back. -// Pass in nothing, get unit back. -class CallAnswererImpl(val mode: String) : CallAnswerer { - override fun answer(): String { - if (mode == "normal") { - return "Bonjour" - } else if (mode == "busy") { - throw TelephoneException.Busy("I'm busy") - } else { - throw SomeOtherError(); - } - } -} - -val telephone = Telephone() -val sim = getSimCards()[0] - -assert(telephone.call(sim, CallAnswererImpl("normal")) == "Bonjour") - -// Our own sim. -class Sim() : SimCard { - override fun name(): String { - return "kotlin" - } -} -assert(telephone.call(Sim(), CallAnswererImpl("normal")) == "kotlin est bon marché") - -try { - telephone.call(sim, CallAnswererImpl("busy")) - throw RuntimeException("Should have thrown a Busy exception!") -} catch(e: TelephoneException.Busy) { - // It's okay -} - -try { - telephone.call(sim, CallAnswererImpl("something-else")) - throw RuntimeException("Should have thrown an internal exception!") -} catch(e: TelephoneException.InternalTelephoneException) { - // It's okay -} - -telephone.destroy() diff --git a/uniffi/examples/callbacks/tests/bindings/test_callbacks.py b/uniffi/examples/callbacks/tests/bindings/test_callbacks.py deleted file mode 100644 index ab0061574..000000000 --- a/uniffi/examples/callbacks/tests/bindings/test_callbacks.py +++ /dev/null @@ -1,53 +0,0 @@ -import unittest -from callbacks import * - -# This is defined in UDL as a "callback". It's not possible to have a Rust -# implementation of a callback, they only exist on the foreign side. -class CallAnswererImpl(CallAnswerer): - def __init__(self, mode): - self.mode = mode - - def answer(self): - if self.mode == "ready": - return "Bonjour" - elif self.mode == "busy": - raise TelephoneError.Busy() - else: - raise ValueError("Testing an unexpected error") - -# This is a normal Rust trait - very much like a callback but can be implemented -# in Rust or in foreign code and is generally more consistent with the uniffi -# Arc<>-based object model. -class DiscountSim(SimCard): - def name(self): - return "python" - -class CallbacksTest(unittest.TestCase): - TelephoneImpl = Telephone - def test_answer(self): - cb_object = CallAnswererImpl("ready") - telephone = self.TelephoneImpl() - self.assertEqual("Bonjour", telephone.call(get_sim_cards()[0], cb_object)) - - def test_busy(self): - cb_object = CallAnswererImpl("busy") - telephone = self.TelephoneImpl() - with self.assertRaises(TelephoneError.Busy): - telephone.call(get_sim_cards()[0], cb_object) - - def test_unexpected_error(self): - cb_object = CallAnswererImpl("something-else") - telephone = self.TelephoneImpl() - with self.assertRaises(TelephoneError.InternalTelephoneError): - telephone.call(get_sim_cards()[0], cb_object) - - def test_sims(self): - cb_object = CallAnswererImpl("ready") - telephone = self.TelephoneImpl() - sim = DiscountSim() - self.assertEqual("python est bon marché", telephone.call(sim, cb_object)) - -class FancyCallbacksTest(CallbacksTest): - TelephoneImpl = FancyTelephone - -unittest.main() diff --git a/uniffi/examples/callbacks/tests/bindings/test_callbacks.swift b/uniffi/examples/callbacks/tests/bindings/test_callbacks.swift deleted file mode 100644 index e2c860969..000000000 --- a/uniffi/examples/callbacks/tests/bindings/test_callbacks.swift +++ /dev/null @@ -1,60 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if canImport(callbacks) - import callbacks -#endif - -struct SomeOtherError: Error { } - -// Simple example just to see it work. -// Pass in a string, get a string back. -// Pass in nothing, get unit back. -final class OnCallAnsweredImpl : CallAnswerer { - let mode: String - - init(withMode: String) { - mode = withMode - } - - func answer() throws -> String { - switch mode { - case "ready": - return "Bonjour" - - case "busy": - throw TelephoneError.Busy(message: "I'm Busy") - - default: - throw SomeOtherError() - } - } -} - -let telephone = Telephone() -let sim = getSimCards()[0]; - -assert(try! telephone.call(sim: sim, answerer: OnCallAnsweredImpl(withMode: "ready")) == "Bonjour") - -// We can implement our own sim cards. -final class Sim : SimCard { - func name() -> String { - return "swift" - } -} - -assert(try! telephone.call(sim: Sim(), answerer: OnCallAnsweredImpl(withMode: "ready")) == "swift est bon marché") - -// Error cases. -do { - _ = try telephone.call(sim: sim, answerer: OnCallAnsweredImpl(withMode: "busy")) -} catch TelephoneError.Busy { - // Expected error -} - -do { - _ = try telephone.call(sim: sim, answerer: OnCallAnsweredImpl(withMode: "unexpected-value")) -} catch TelephoneError.InternalTelephoneError { - // Expected error -} diff --git a/uniffi/examples/callbacks/tests/test_generated_bindings.rs b/uniffi/examples/callbacks/tests/test_generated_bindings.rs deleted file mode 100644 index 6544a6607..000000000 --- a/uniffi/examples/callbacks/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_callbacks.kts", - "tests/bindings/test_callbacks.swift", - "tests/bindings/test_callbacks.py", -); diff --git a/uniffi/examples/callbacks/uniffi.toml b/uniffi/examples/callbacks/uniffi.toml deleted file mode 100644 index bec5a45e5..000000000 --- a/uniffi/examples/callbacks/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.kotlin] -package_name = "uniffi.callbacks" diff --git a/uniffi/examples/custom-types/Cargo.toml b/uniffi/examples/custom-types/Cargo.toml deleted file mode 100644 index b52ebffb3..000000000 --- a/uniffi/examples/custom-types/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "uniffi-example-custom-types" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "custom_types" - -[dependencies] -anyhow = "1" -bytes = "1.11" -uniffi = { workspace = true } -url = "2.2" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/custom-types/build.rs b/uniffi/examples/custom-types/build.rs deleted file mode 100644 index 216e258f4..000000000 --- a/uniffi/examples/custom-types/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/custom-types.udl").unwrap(); -} diff --git a/uniffi/examples/custom-types/src/custom-types.udl b/uniffi/examples/custom-types/src/custom-types.udl deleted file mode 100644 index a4bbc854c..000000000 --- a/uniffi/examples/custom-types/src/custom-types.udl +++ /dev/null @@ -1,26 +0,0 @@ -[Custom] -typedef string Url; - -[Custom] -typedef i64 Handle; - -[Custom] -typedef i64 TimeIntervalMs; - -[Custom] -typedef f64 TimeIntervalSecDbl; - -[Custom] -typedef f32 TimeIntervalSecFlt; - -dictionary CustomTypesDemo { - Url url; - Handle handle; - TimeIntervalMs time_interval_ms; - TimeIntervalSecDbl time_interval_sec_dbl; - TimeIntervalSecFlt time_interval_sec_flt; -}; - -namespace custom_types { - CustomTypesDemo get_custom_types_demo(CustomTypesDemo? demo); -}; diff --git a/uniffi/examples/custom-types/src/lib.rs b/uniffi/examples/custom-types/src/lib.rs deleted file mode 100644 index b92a775a7..000000000 --- a/uniffi/examples/custom-types/src/lib.rs +++ /dev/null @@ -1,98 +0,0 @@ -use url::Url; - -// A custom guid defined via a proc-macro (ie, not referenced in the UDL) -pub struct ExampleCustomType(String); - -// custom_newtype! is the easiest way to define custom types. -// (Note that docstrings for custom types can't appear here - see below) -uniffi::custom_newtype!(ExampleCustomType, String); - -// Custom Handle type which trivially wraps an i64. -pub struct Handle(pub i64); - -// This one could also use custom_newtype!, but let's use Into and TryFrom instead -uniffi::custom_type!(Handle, i64); - -// Defining `From for i64` also gives us `Into for Handle` -impl From for i64 { - fn from(val: Handle) -> Self { - val.0 - } -} - -impl From for Handle { - fn from(val: i64) -> Handle { - Handle(val) - } -} - -// Custom TimeIntervalMs type which trivially wraps an i64. -pub struct TimeIntervalMs(pub i64); - -// Another custom type, this time we will define an infallible conversion back to Rust. -uniffi::custom_type!(TimeIntervalMs, i64); - -impl From for i64 { - fn from(val: TimeIntervalMs) -> Self { - val.0 - } -} -// Defining `From for Handle` also gives us `Into for i64` -impl From for TimeIntervalMs { - fn from(val: i64) -> TimeIntervalMs { - TimeIntervalMs(val) - } -} - -// Custom TimeIntervalSecDbl type which trivially wraps an f64. -pub struct TimeIntervalSecDbl(pub f64); - -// custom_type! can take an additional parameter with closures to control the conversions -uniffi::custom_type!(TimeIntervalSecDbl, f64, { - lower: |time_interval| time_interval.0, - try_lift: |val| Ok(TimeIntervalSecDbl(val)), -}); - -// Custom TimeIntervalSecFlt type which trivially wraps an f32. -pub struct TimeIntervalSecFlt(pub f32); - -// Let's go back to custom_newtype for this one. -// This also shows how to set a docstring for a custom type - it's got to be part of the macro invocation. -uniffi::custom_newtype!( - /// This is a docstring for the type, which some languages might be able to render with the alias. - TimeIntervalSecFlt, f32 -); - -// `Url` gets converted to a `String` to pass across the FFI. -uniffi::custom_type!(Url, String, { - // Remote is required since `Url` is from a different crate - remote, - try_lift: |val| Ok(Url::parse(&val)?), - lower: |obj| obj.into(), -}); - -// And a little struct and function that ties them together. -pub struct CustomTypesDemo { - url: Url, - handle: Handle, - time_interval_ms: TimeIntervalMs, - time_interval_sec_dbl: TimeIntervalSecDbl, - time_interval_sec_flt: TimeIntervalSecFlt, -} - -pub fn get_custom_types_demo(v: Option) -> CustomTypesDemo { - v.unwrap_or_else(|| CustomTypesDemo { - url: Url::parse("http://example.com/").unwrap(), - handle: Handle(123), - time_interval_ms: TimeIntervalMs(456000), - time_interval_sec_dbl: TimeIntervalSecDbl(456.0), - time_interval_sec_flt: TimeIntervalSecFlt(777.0), - }) -} - -#[uniffi::export] -pub fn get_example_custom_type() -> ExampleCustomType { - ExampleCustomType("abadidea".to_string()) -} - -uniffi::include_scaffolding!("custom-types"); diff --git a/uniffi/examples/custom-types/tests/bindings/test_custom_types.kts b/uniffi/examples/custom-types/tests/bindings/test_custom_types.kts deleted file mode 100644 index d75bd99ee..000000000 --- a/uniffi/examples/custom-types/tests/bindings/test_custom_types.kts +++ /dev/null @@ -1,21 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import java.net.URL - -import customtypes.* - -// TODO: use an actual test runner. - -// Get the custom types and check their data -val demo = getCustomTypesDemo(null) -// URL is customized on the bindings side -assert(demo.url == URL("http://example.com/")) -// Handle isn't so it appears as a plain Long -assert(demo.handle == 123L) - -// Change some data and ensure that the round-trip works -demo.url = URL("http://new.example.com/") -demo.handle = 456; -assert(demo == getCustomTypesDemo(demo)) diff --git a/uniffi/examples/custom-types/tests/bindings/test_custom_types.py b/uniffi/examples/custom-types/tests/bindings/test_custom_types.py deleted file mode 100644 index cd9e080a6..000000000 --- a/uniffi/examples/custom-types/tests/bindings/test_custom_types.py +++ /dev/null @@ -1,13 +0,0 @@ -from custom_types import * - -# Get the custom types and check their data -val = get_custom_types_demo(None) -assert val.url.scheme == 'http' -assert val.url.netloc == 'example.com' -assert val.url.path == '/' -assert val.handle == 123 - -# Change some data and ensure that the round-trip works -val.url = val.url._replace(netloc='new.example.com') -val.handle = 456 -assert val == get_custom_types_demo(val) diff --git a/uniffi/examples/custom-types/tests/bindings/test_custom_types.swift b/uniffi/examples/custom-types/tests/bindings/test_custom_types.swift deleted file mode 100644 index 97dea019c..000000000 --- a/uniffi/examples/custom-types/tests/bindings/test_custom_types.swift +++ /dev/null @@ -1,26 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import custom_types -import Foundation - -// TODO: use an actual test runner. - -do { - // Test simple values. - var demo = getCustomTypesDemo(demo: nil) - assert(demo.url == URL(string: "http://example.com/")) - assert(demo.handle == 123) - assert(demo.timeIntervalMs == Date(timeIntervalSince1970: 456.0)) - assert(demo.timeIntervalSecDbl == Date(timeIntervalSince1970: 456.0)) - assert(demo.timeIntervalSecFlt == Date(timeIntervalSince1970: 777.0)) - - // Change some data and ensure that the round-trip works - demo.url = URL(string: "http://new.example.com/")! - demo.handle = 456 - demo.timeIntervalMs = Date(timeIntervalSince1970: 789.0) - demo.timeIntervalSecDbl = Date(timeIntervalSince1970: 789.0) - demo.timeIntervalSecFlt = Date(timeIntervalSince1970: 111.0) - assert(demo == getCustomTypesDemo(demo: demo)) -} diff --git a/uniffi/examples/custom-types/tests/test_generated_bindings.rs b/uniffi/examples/custom-types/tests/test_generated_bindings.rs deleted file mode 100644 index 15b502e7d..000000000 --- a/uniffi/examples/custom-types/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_custom_types.kts", - "tests/bindings/test_custom_types.py", - "tests/bindings/test_custom_types.swift", -); diff --git a/uniffi/examples/custom-types/uniffi.toml b/uniffi/examples/custom-types/uniffi.toml deleted file mode 100644 index f05404530..000000000 --- a/uniffi/examples/custom-types/uniffi.toml +++ /dev/null @@ -1,61 +0,0 @@ -[bindings.swift.custom_types.Url] -# Name of the type in the Swift code -type_name = "URL" -# Modules that need to be imported -imports = ["Foundation"] -# Function to lift a string from Rust into a Swift URL. -lift = "URL(string: {})!" -# and to lower it to a Rust string -lower = "String(describing: {})" - -[bindings.swift.custom_types.TimeIntervalMs] -# Name of the type in the Swift code -type_name = "Date" -# Modules that need to be imported -imports = ["Foundation"] -lift = "Date(timeIntervalSince1970: TimeInterval({}) / 1000.0)" -lower = "Int64({}.timeIntervalSince1970 * 1000.0)" - -[bindings.swift.custom_types.TimeIntervalSecDbl] -# Name of the type in the Swift code -type_name = "Date" -# Modules that need to be imported -imports = ["Foundation"] -# Functions to convert between f64 and TimeIntervalSecDbl -lift = "Date(timeIntervalSince1970: {})" -lower = "{}.timeIntervalSince1970" - -[bindings.swift.custom_types.TimeIntervalSecFlt] -# Name of the type in the Swift code -type_name = "Date" -# Modules that need to be imported -imports = ["Foundation"] -# Functions to convert between f32 and TimeIntervalSecFlt -# (here we use the deprecated names instead of `lift` and `lower`) -into_custom = "Date(timeIntervalSince1970: TimeInterval({}))" -from_custom = "Float({}.timeIntervalSince1970)" - -[bindings.kotlin] -package_name = "customtypes" - -[bindings.kotlin.custom_types.Url] -# Name of the type in the Kotlin code -type_name = "URL" -# Classes that need to be imported -imports = [ "java.net.URI", "java.net.URL" ] -# Function to lift a string from Rust into a Kotlin URL. -lift = "URI({}).toURL()" -# and to lower it to a Rust string -lower = "{}.toString()" - -[bindings.python.custom_types.Url] -# We're going to be the urllib.parse.ParseResult class, which is the closest -# thing Python has to a Url class. - -# `type_name` is optional, but it improves Python's optional type-checking -type_name = "urllib.parse.ParseResult" -imports = ["urllib.parse"] -# Function to lift a string from Rust into a Python URL. -lift = "urllib.parse.urlparse({})" -# and to lower it to a Rust string -lower = "urllib.parse.urlunparse({})" diff --git a/uniffi/examples/futures/Cargo.toml b/uniffi/examples/futures/Cargo.toml deleted file mode 100644 index a8dd720f5..000000000 --- a/uniffi/examples/futures/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "uniffi-example-futures" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] - -[dependencies] -async-std = "1.13" -thiserror = "2" -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/futures/src/lib.rs b/uniffi/examples/futures/src/lib.rs deleted file mode 100644 index bdea17ee0..000000000 --- a/uniffi/examples/futures/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use async_std::future::{pending, timeout}; -use std::time::Duration; - -/// Async function that says something after a certain time. -#[uniffi::export] -pub async fn say_after(ms: u64, who: String) -> String { - let never = pending::<()>(); - timeout(Duration::from_millis(ms), never).await.unwrap_err(); - format!("Hello, {who}!") -} - -uniffi::setup_scaffolding!(); diff --git a/uniffi/examples/futures/tests/bindings/test.py b/uniffi/examples/futures/tests/bindings/test.py deleted file mode 100644 index 18fd24cc5..000000000 --- a/uniffi/examples/futures/tests/bindings/test.py +++ /dev/null @@ -1,8 +0,0 @@ -import asyncio -from uniffi_example_futures import * - -async def main(): - assert(await say_after(20, 'Alice') == "Hello, Alice!") - -if __name__ == '__main__': - asyncio.run(main()) diff --git a/uniffi/examples/futures/tests/test_generated_bindings.rs b/uniffi/examples/futures/tests/test_generated_bindings.rs deleted file mode 100644 index 6829833c9..000000000 --- a/uniffi/examples/futures/tests/test_generated_bindings.rs +++ /dev/null @@ -1 +0,0 @@ -uniffi::build_foreign_language_testcases!("tests/bindings/test.py"); diff --git a/uniffi/examples/geometry/Cargo.toml b/uniffi/examples/geometry/Cargo.toml deleted file mode 100644 index ad2225dbb..000000000 --- a/uniffi/examples/geometry/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-example-geometry" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_geometry" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/geometry/build.rs b/uniffi/examples/geometry/build.rs deleted file mode 100644 index 2dd1c96bc..000000000 --- a/uniffi/examples/geometry/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/geometry.udl").unwrap(); -} diff --git a/uniffi/examples/geometry/src/geometry.udl b/uniffi/examples/geometry/src/geometry.udl deleted file mode 100644 index af60d429b..000000000 --- a/uniffi/examples/geometry/src/geometry.udl +++ /dev/null @@ -1,15 +0,0 @@ - -namespace geometry { - double gradient(Line ln); - Point? intersection(Line ln1, Line ln2); -}; - -dictionary Point { - double coord_x; - double coord_y; -}; - -dictionary Line { - Point start; - Point end; -}; diff --git a/uniffi/examples/geometry/src/lib.rs b/uniffi/examples/geometry/src/lib.rs deleted file mode 100644 index d710b150b..000000000 --- a/uniffi/examples/geometry/src/lib.rs +++ /dev/null @@ -1,47 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp -// Silence, clippy! -const EPSILON: f64 = 0.0001f64; - -#[derive(Debug, Clone)] -pub struct Point { - coord_x: f64, - coord_y: f64, -} - -#[derive(Debug, Clone)] -pub struct Line { - start: Point, - end: Point, -} - -pub fn gradient(ln: Line) -> f64 { - let rise = ln.end.coord_y - ln.start.coord_y; - let run = ln.end.coord_x - ln.start.coord_x; - rise / run -} - -pub fn intersection(ln1: Line, ln2: Line) -> Option { - // TODO: yuck, should be able to take &Line as argument here - // and have rust figure it out with a bunch of annotations... - let g1 = gradient(ln1.clone()); - let z1 = ln1.start.coord_y - g1 * ln1.start.coord_x; - let g2 = gradient(ln2.clone()); - let z2 = ln2.start.coord_y - g2 * ln2.start.coord_x; - // Parallel lines do not intersect. - if (g1 - g2).abs() < EPSILON { - return None; - } - // Otherwise, they intersect at this fancy calculation that - // I found on wikipedia. - let x = (z2 - z1) / (g1 - g2); - Some(Point { - coord_x: x, - coord_y: g1 * x + z1, - }) -} - -uniffi::include_scaffolding!("geometry"); diff --git a/uniffi/examples/geometry/tests/bindings/test_geometry.kts b/uniffi/examples/geometry/tests/bindings/test_geometry.kts deleted file mode 100644 index 77bb9932e..000000000 --- a/uniffi/examples/geometry/tests/bindings/test_geometry.kts +++ /dev/null @@ -1,10 +0,0 @@ -import uniffi.geometry.*; - -val ln1 = Line(Point(0.0,0.0), Point(1.0,2.0)) -val ln2 = Line(Point(1.0,1.0), Point(2.0,2.0)) - -assert( gradient(ln1) == 2.0 ) -assert( gradient(ln2) == 1.0 ) - -assert( intersection(ln1, ln2) == Point(0.0, 0.0) ) -assert( intersection(ln1, ln1) == null ) diff --git a/uniffi/examples/geometry/tests/bindings/test_geometry.py b/uniffi/examples/geometry/tests/bindings/test_geometry.py deleted file mode 100644 index fd6772be2..000000000 --- a/uniffi/examples/geometry/tests/bindings/test_geometry.py +++ /dev/null @@ -1,10 +0,0 @@ -from geometry import * - -ln1 = Line(start=Point(coord_x=0, coord_y=0), end=Point(coord_x=1, coord_y=2)) -ln2 = Line(start=Point(coord_x=1, coord_y=1), end=Point(coord_x=2, coord_y=2)) - -assert gradient(ln1) == 2 -assert gradient(ln2) == 1 - -assert intersection(ln1, ln2) == Point(coord_x=0, coord_y=0) -assert intersection(ln1, ln1) is None diff --git a/uniffi/examples/geometry/tests/bindings/test_geometry.swift b/uniffi/examples/geometry/tests/bindings/test_geometry.swift deleted file mode 100644 index 58bd65607..000000000 --- a/uniffi/examples/geometry/tests/bindings/test_geometry.swift +++ /dev/null @@ -1,10 +0,0 @@ -import geometry - -let ln1 = Line(start: Point(coordX: 0, coordY: 0), end: Point(coordX: 1, coordY: 2)) -let ln2 = Line(start: Point(coordX: 1, coordY: 1), end: Point(coordX: 2, coordY: 2)) - -assert(gradient(ln: ln1) == 2.0) -assert(gradient(ln: ln2) == 1.0) - -assert(intersection(ln1: ln1, ln2: ln2) == Point(coordX: 0, coordY: 0)) -assert(intersection(ln1: ln1, ln2: ln1) == nil) diff --git a/uniffi/examples/geometry/tests/test_generated_bindings.rs b/uniffi/examples/geometry/tests/test_generated_bindings.rs deleted file mode 100644 index 03fa34ce9..000000000 --- a/uniffi/examples/geometry/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_geometry.py", - "tests/bindings/test_geometry.kts", - "tests/bindings/test_geometry.swift", -); diff --git a/uniffi/examples/remote-types/Cargo.toml b/uniffi/examples/remote-types/Cargo.toml deleted file mode 100644 index 7657d5b05..000000000 --- a/uniffi/examples/remote-types/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "uniffi-example-remote-types" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "remote_types" - -[dependencies] -anyhow = "1" -log = "0.4" -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/remote-types/README.md b/uniffi/examples/remote-types/README.md deleted file mode 100644 index 84a499468..000000000 --- a/uniffi/examples/remote-types/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Remote types example - -This crate uses 2 types from remote crates: `log::Level` and `anyhow::Error`. -Remote types require special handling, since there's no way to add a `#[derive]` to a type that's -already been defined upstream. Instead, use `#[uniffi::remote()]` to wrap the item's -definition. UniFFI will generate the code to handle that type in the FFI, similar to if it had been -wrapped with `#[derive(uniffi::)]`. - -See https://mozilla.github.io/uniffi-rs/latest/types/remote_ext_types.html for more details. diff --git a/uniffi/examples/remote-types/src/lib.rs b/uniffi/examples/remote-types/src/lib.rs deleted file mode 100644 index 720fa7e86..000000000 --- a/uniffi/examples/remote-types/src/lib.rs +++ /dev/null @@ -1,53 +0,0 @@ -// It's often useful, but not required, to define type aliases for remote type. -// -// These control the names of the types in the generated code. -type AnyhowError = anyhow::Error; -type LogLevel = log::Level; - -// Use #[uniffi::remote] to enable support for passing the types across the FFI - -// For records/enums, wrap the item definition with `#[uniffi::remote]`. -// Copy each field/variant definitions exactly as they appear in the remote crate. -#[uniffi::remote(Enum)] -pub enum LogLevel { - Error = 1, - Warn = 2, - Info = 3, - Debug = 4, - Trace = 5, -} - -// For interfaces, wrap a unit struct with `#[uniffi::remote]`. -#[uniffi::remote(Object)] -pub struct AnyhowError; - -// TODO: -// - Add support for exporting methods on remote interfaces types -// - Add support for Rust traits like `Display` - -/// Logger that uses the remote types -#[derive(uniffi::Object)] -pub struct LogSink {} - -#[uniffi::export] -impl LogSink { - /// Construct a new LogSink that writes to a file - /// We currently need to wrap AnyhowError in an Arc, but #2093 should fix that. - #[uniffi::constructor] - pub fn new(path: &str) -> Result> { - // For this example, we don't actually do anything with the path except check that it's - // non-empty. - if path.is_empty() { - Err(std::sync::Arc::new(AnyhowError::msg("Empty path"))) - } else { - Ok(Self {}) - } - } - - /// Log a message to our file - pub fn log(&self, _level: log::Level, _msg: String) { - // Pretend this code actually writes something out - } -} - -uniffi::setup_scaffolding!(); diff --git a/uniffi/examples/remote-types/tests/bindings/test_remote_types.kts b/uniffi/examples/remote-types/tests/bindings/test_remote_types.kts deleted file mode 100644 index 00ba8f581..000000000 --- a/uniffi/examples/remote-types/tests/bindings/test_remote_types.kts +++ /dev/null @@ -1,12 +0,0 @@ -import remote_types.* - -val testLogger = LogSink("SomeFile") -testLogger.log(LogLevel.INFO, "Hello world") - -// Test the error handling -try { - LogSink("") - throw RuntimeException("Constructor should have thrown") -} catch (e: AnyhowException) { - // Expected -} diff --git a/uniffi/examples/remote-types/tests/bindings/test_remote_types.py b/uniffi/examples/remote-types/tests/bindings/test_remote_types.py deleted file mode 100644 index 531174903..000000000 --- a/uniffi/examples/remote-types/tests/bindings/test_remote_types.py +++ /dev/null @@ -1,11 +0,0 @@ -from remote_types import * - -testLogger = LogSink("SomeFile") -testLogger.log(LogLevel.INFO, "Hello world") - -# Test the error handling -try: - LogSink("") - raise RuntimeError("Constructor should have thrown") -except AnyhowError: - pass diff --git a/uniffi/examples/remote-types/tests/bindings/test_remote_types.swift b/uniffi/examples/remote-types/tests/bindings/test_remote_types.swift deleted file mode 100644 index 47b285f8f..000000000 --- a/uniffi/examples/remote-types/tests/bindings/test_remote_types.swift +++ /dev/null @@ -1,12 +0,0 @@ -import remote_types - -let testLogger = try! LogSink(path: "SomeFile") -testLogger.log(level: LogLevel.info, msg: "Hello world") - -// Test the error handling -do { - let _ = try LogSink(path: "") - fatalError("Constructor should have thrown") -} catch is AnyhowError { - // Expected -} diff --git a/uniffi/examples/remote-types/tests/test_generated_bindings.rs b/uniffi/examples/remote-types/tests/test_generated_bindings.rs deleted file mode 100644 index dbe7f8c2b..000000000 --- a/uniffi/examples/remote-types/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_remote_types.kts", - "tests/bindings/test_remote_types.py", - "tests/bindings/test_remote_types.swift", -); diff --git a/uniffi/examples/remote-types/uniffi.toml b/uniffi/examples/remote-types/uniffi.toml deleted file mode 100644 index 34af2e652..000000000 --- a/uniffi/examples/remote-types/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.kotlin] -package_name = "remote_types" diff --git a/uniffi/examples/rondpoint/Cargo.toml b/uniffi/examples/rondpoint/Cargo.toml deleted file mode 100644 index 1f925dc29..000000000 --- a/uniffi/examples/rondpoint/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-example-rondpoint" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_rondpoint" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/rondpoint/build.rs b/uniffi/examples/rondpoint/build.rs deleted file mode 100644 index f830879d0..000000000 --- a/uniffi/examples/rondpoint/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/rondpoint.udl").unwrap(); -} diff --git a/uniffi/examples/rondpoint/src/lib.rs b/uniffi/examples/rondpoint/src/lib.rs deleted file mode 100644 index 3f2233dda..000000000 --- a/uniffi/examples/rondpoint/src/lib.rs +++ /dev/null @@ -1,293 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::collections::HashMap; - -#[derive(Debug, Clone)] -pub struct Dictionnaire { - un: Enumeration, - deux: bool, - petit_nombre: u8, - gros_nombre: u64, -} - -#[derive(Debug, Clone)] -pub struct DictionnaireNombres { - petit_nombre: u8, - court_nombre: u16, - nombre_simple: u32, - gros_nombre: u64, -} - -#[derive(Debug, Clone)] -pub struct DictionnaireNombresSignes { - petit_nombre: i8, - court_nombre: i16, - nombre_simple: i32, - gros_nombre: i64, -} - -#[derive(Debug, Clone)] -pub enum Enumeration { - Un, - Deux, - Trois, -} - -#[derive(Debug, Clone)] -pub enum EnumerationAvecDonnees { - Zero, - Un { premier: u32 }, - Deux { premier: u32, second: String }, -} - -#[allow(non_camel_case_types)] -#[allow(non_snake_case)] -pub struct minusculeMAJUSCULEDict { - minusculeMAJUSCULEField: bool, -} - -#[allow(non_camel_case_types)] -pub enum minusculeMAJUSCULEEnum { - minusculeMAJUSCULEVariant, -} - -fn copie_enumeration(e: Enumeration) -> Enumeration { - e -} - -fn copie_enumerations(e: Vec) -> Vec { - e -} - -fn copie_carte( - e: HashMap, -) -> HashMap { - e -} - -fn copie_dictionnaire(d: Dictionnaire) -> Dictionnaire { - d -} - -fn switcheroo(b: bool) -> bool { - !b -} - -// Test that values can traverse both ways across the FFI. -// Even if roundtripping works, it's possible we have -// symmetrical errors that cancel each other out. -#[derive(Debug, Clone)] -struct Retourneur; -impl Retourneur { - fn new() -> Self { - Retourneur - } - fn identique_i8(&self, value: i8) -> i8 { - value - } - fn identique_u8(&self, value: u8) -> u8 { - value - } - fn identique_i16(&self, value: i16) -> i16 { - value - } - fn identique_u16(&self, value: u16) -> u16 { - value - } - fn identique_i32(&self, value: i32) -> i32 { - value - } - fn identique_u32(&self, value: u32) -> u32 { - value - } - fn identique_i64(&self, value: i64) -> i64 { - value - } - fn identique_u64(&self, value: u64) -> u64 { - value - } - fn identique_float(&self, value: f32) -> f32 { - value - } - fn identique_double(&self, value: f64) -> f64 { - value - } - fn identique_boolean(&self, value: bool) -> bool { - value - } - fn identique_string(&self, value: String) -> String { - value - } - fn identique_nombres_signes( - &self, - value: DictionnaireNombresSignes, - ) -> DictionnaireNombresSignes { - value - } - fn identique_nombres(&self, value: DictionnaireNombres) -> DictionnaireNombres { - value - } - fn identique_optionneur_dictionnaire( - &self, - value: OptionneurDictionnaire, - ) -> OptionneurDictionnaire { - value - } -} - -#[derive(Debug, Clone)] -struct Stringifier; - -#[allow(dead_code)] -impl Stringifier { - fn new() -> Self { - Stringifier - } - fn to_string_i8(&self, value: i8) -> String { - value.to_string() - } - fn to_string_u8(&self, value: u8) -> String { - value.to_string() - } - fn to_string_i16(&self, value: i16) -> String { - value.to_string() - } - fn to_string_u16(&self, value: u16) -> String { - value.to_string() - } - fn to_string_i32(&self, value: i32) -> String { - value.to_string() - } - fn to_string_u32(&self, value: u32) -> String { - value.to_string() - } - fn to_string_i64(&self, value: i64) -> String { - value.to_string() - } - fn to_string_u64(&self, value: u64) -> String { - value.to_string() - } - fn to_string_float(&self, value: f32) -> String { - value.to_string() - } - fn to_string_double(&self, value: f64) -> String { - value.to_string() - } - fn to_string_boolean(&self, value: bool) -> String { - value.to_string() - } - fn well_known_string(&self, value: String) -> String { - format!("uniffi 💚 {value}!") - } -} - -#[derive(Debug, Clone)] -struct Optionneur; -impl Optionneur { - fn new() -> Self { - Optionneur - } - fn sinon_string(&self, value: String) -> String { - value - } - fn sinon_null(&self, value: Option) -> Option { - value - } - fn sinon_boolean(&self, value: bool) -> bool { - value - } - fn sinon_sequence(&self, value: Vec) -> Vec { - value - } - - fn sinon_zero(&self, value: Option) -> Option { - value - } - - fn sinon_u8_dec(&self, value: u8) -> u8 { - value - } - fn sinon_i8_dec(&self, value: i8) -> i8 { - value - } - fn sinon_u16_dec(&self, value: u16) -> u16 { - value - } - fn sinon_i16_dec(&self, value: i16) -> i16 { - value - } - fn sinon_u32_dec(&self, value: u32) -> u32 { - value - } - fn sinon_i32_dec(&self, value: i32) -> i32 { - value - } - fn sinon_u64_dec(&self, value: u64) -> u64 { - value - } - fn sinon_i64_dec(&self, value: i64) -> i64 { - value - } - - fn sinon_u8_hex(&self, value: u8) -> u8 { - value - } - fn sinon_i8_hex(&self, value: i8) -> i8 { - value - } - fn sinon_u16_hex(&self, value: u16) -> u16 { - value - } - fn sinon_i16_hex(&self, value: i16) -> i16 { - value - } - fn sinon_u32_hex(&self, value: u32) -> u32 { - value - } - fn sinon_i32_hex(&self, value: i32) -> i32 { - value - } - fn sinon_u64_hex(&self, value: u64) -> u64 { - value - } - fn sinon_i64_hex(&self, value: i64) -> i64 { - value - } - - fn sinon_u32_oct(&self, value: u32) -> u32 { - value - } - - fn sinon_f32(&self, value: f32) -> f32 { - value - } - fn sinon_f64(&self, value: f64) -> f64 { - value - } - - fn sinon_enum(&self, value: Enumeration) -> Enumeration { - value - } -} - -pub struct OptionneurDictionnaire { - i8_var: i8, - u8_var: u8, - i16_var: i16, - u16_var: u16, - i32_var: i32, - u32_var: u32, - i64_var: i64, - u64_var: u64, - float_var: f32, - double_var: f64, - boolean_var: bool, - string_var: String, - list_var: Vec, - enumeration_var: Enumeration, - dictionnaire_var: Option, -} - -uniffi::include_scaffolding!("rondpoint"); diff --git a/uniffi/examples/rondpoint/src/rondpoint.udl b/uniffi/examples/rondpoint/src/rondpoint.udl deleted file mode 100644 index 7c8261d74..000000000 --- a/uniffi/examples/rondpoint/src/rondpoint.udl +++ /dev/null @@ -1,146 +0,0 @@ -namespace rondpoint { - Dictionnaire copie_dictionnaire(Dictionnaire d); - Enumeration copie_enumeration(Enumeration e); - sequence copie_enumerations(sequence e); - record copie_carte(record c); - boolean switcheroo(boolean b); -}; - -dictionary minusculeMAJUSCULEDict { - boolean minusculeMAJUSCULEField; -}; - -enum minusculeMAJUSCULEEnum { - "minusculeMAJUSCULEVariant", -}; - -enum Enumeration { - "Un", - "Deux", - "Trois", -}; - -[Enum] -interface EnumerationAvecDonnees { - Zero(); - Un(u32 premier); - Deux(u32 premier, string second); -}; - -dictionary Dictionnaire { - Enumeration un; - boolean deux; - u8 petit_nombre; - u64 gros_nombre; -}; - -dictionary DictionnaireNombres { - u8 petit_nombre; - u16 court_nombre; - u32 nombre_simple; - u64 gros_nombre; -}; - -dictionary DictionnaireNombresSignes { - i8 petit_nombre; - i16 court_nombre; - i32 nombre_simple; - i64 gros_nombre; -}; - -interface Retourneur { - constructor(); - i8 identique_i8(i8 value); - u8 identique_u8(u8 value); - i16 identique_i16(i16 value); - u16 identique_u16(u16 value); - i32 identique_i32(i32 value); - u32 identique_u32(u32 value); - i64 identique_i64(i64 value); - u64 identique_u64(u64 value); - float identique_float(float value); - double identique_double(double value); - boolean identique_boolean(boolean value); - string identique_string(string value); - - DictionnaireNombresSignes identique_nombres_signes(DictionnaireNombresSignes value); - DictionnaireNombres identique_nombres(DictionnaireNombres value); - OptionneurDictionnaire identique_optionneur_dictionnaire(OptionneurDictionnaire value); -}; - -interface Stringifier { - constructor(); - string well_known_string(string value); - - string to_string_i8(i8 value); - string to_string_u8(u8 value); - string to_string_i16(i16 value); - string to_string_u16(u16 value); - string to_string_i32(i32 value); - string to_string_u32(u32 value); - string to_string_i64(i64 value); - string to_string_u64(u64 value); - string to_string_float(float value); - string to_string_double(double value); - string to_string_boolean(boolean value); -}; - -interface Optionneur { - constructor(); - boolean sinon_boolean(optional boolean value = false); - string sinon_string(optional string value = "default"); - - sequence sinon_sequence(optional sequence value = []); - - // Either sides of nullable. - string? sinon_null(optional string? value = null); - i32? sinon_zero(optional i32? value = 0); - - // Decimal integers, all 42. - u8 sinon_u8_dec(optional u8 value = 42); - i8 sinon_i8_dec(optional i8 value = -42); - u16 sinon_u16_dec(optional u16 value = 42); - i16 sinon_i16_dec(optional i16 value = 42); - u32 sinon_u32_dec(optional u32 value = 42); - i32 sinon_i32_dec(optional i32 value = 42); - u64 sinon_u64_dec(optional u64 value = 42); - i64 sinon_i64_dec(optional i64 value = 42); - - // Hexadecimal, including negatgives. - u8 sinon_u8_hex(optional u8 value = 0xff); - i8 sinon_i8_hex(optional i8 value = -0x7f); - u16 sinon_u16_hex(optional u16 value = 0xffff); - i16 sinon_i16_hex(optional i16 value = 0x7f); - u32 sinon_u32_hex(optional u32 value = 0xffffffff); - i32 sinon_i32_hex(optional i32 value = 0x7fffffff); - u64 sinon_u64_hex(optional u64 value = 0xffffffffffffffff); - i64 sinon_i64_hex(optional i64 value = 0x7fffffffffffffff); - - // Octal, FWIW. - u32 sinon_u32_oct(optional u32 value = 0755); - - // Floats - f32 sinon_f32(optional f32 value = 42.0); - f64 sinon_f64(optional f64 value = 42.1); - - // Enums, which we have to treat as strings in the UDL frontend. - Enumeration sinon_enum(optional Enumeration value = "Trois"); -}; - -dictionary OptionneurDictionnaire { - i8 i8_var = -8; - u8 u8_var = 8; - i16 i16_var = -0x10; - u16 u16_var = 0x10; - i32 i32_var = -32; - u32 u32_var = 32; - i64 i64_var = -64; - u64 u64_var = 64; - float float_var = 4.0; - double double_var = 8.0; - boolean boolean_var = true; - string string_var = "default"; - sequence list_var = []; - Enumeration enumeration_var = "DEUX"; - minusculeMAJUSCULEEnum? dictionnaire_var = null; -}; diff --git a/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.kts b/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.kts deleted file mode 100644 index cc5ddf2a8..000000000 --- a/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.kts +++ /dev/null @@ -1,250 +0,0 @@ -import uniffi.rondpoint.* - -val dico = Dictionnaire(Enumeration.DEUX, true, 0u, 123456789u) -val copyDico = copieDictionnaire(dico) -assert(dico == copyDico) - -assert(copieEnumeration(Enumeration.DEUX) == Enumeration.DEUX) -assert(copieEnumerations(listOf(Enumeration.UN, Enumeration.DEUX)) == listOf(Enumeration.UN, Enumeration.DEUX)) -assert(copieCarte(mapOf( - "0" to EnumerationAvecDonnees.Zero, - "1" to EnumerationAvecDonnees.Un(1u), - "2" to EnumerationAvecDonnees.Deux(2u, "deux") -)) == mapOf( - "0" to EnumerationAvecDonnees.Zero, - "1" to EnumerationAvecDonnees.Un(1u), - "2" to EnumerationAvecDonnees.Deux(2u, "deux") -)) - -val var1: EnumerationAvecDonnees = EnumerationAvecDonnees.Zero -val var2: EnumerationAvecDonnees = EnumerationAvecDonnees.Un(1u) -val var3: EnumerationAvecDonnees = EnumerationAvecDonnees.Un(2u) -assert(var1 != var2) -assert(var2 != var3) -assert(var1 == EnumerationAvecDonnees.Zero) -assert(var1 != EnumerationAvecDonnees.Un(1u)) -assert(var2 == EnumerationAvecDonnees.Un(1u)) - -assert(switcheroo(false)) - -// Test the roundtrip across the FFI. -// This shows that the values we send come back in exactly the same state as we sent them. -// i.e. it shows that lowering from kotlin and lifting into rust is symmetrical with -// lowering from rust and lifting into kotlin. -val rt = Retourneur() - -fun List.affirmAllerRetour(fn: (T) -> T) { - this.forEach { v -> - assert(fn.invoke(v) == v) { "$fn($v)" } - } -} - -// Booleans -listOf(true, false).affirmAllerRetour(rt::identiqueBoolean) - -// Bytes. -listOf(Byte.MIN_VALUE, Byte.MAX_VALUE).affirmAllerRetour(rt::identiqueI8) -listOf(0x00, 0xFF).map { it.toUByte() }.affirmAllerRetour(rt::identiqueU8) - -// Shorts -listOf(Short.MIN_VALUE, Short.MAX_VALUE).affirmAllerRetour(rt::identiqueI16) -listOf(0x0000, 0xFFFF).map { it.toUShort() }.affirmAllerRetour(rt::identiqueU16) - -// Ints -listOf(0, 1, -1, Int.MIN_VALUE, Int.MAX_VALUE).affirmAllerRetour(rt::identiqueI32) -listOf(0x00000000, 0xFFFFFFFF).map { it.toUInt() }.affirmAllerRetour(rt::identiqueU32) - -// Longs -listOf(0L, 1L, -1L, Long.MIN_VALUE, Long.MAX_VALUE).affirmAllerRetour(rt::identiqueI64) -listOf(0u, 1u, ULong.MIN_VALUE, ULong.MAX_VALUE).affirmAllerRetour(rt::identiqueU64) - -// Floats -listOf(0.0F, 0.5F, 0.25F, Float.MIN_VALUE, Float.MAX_VALUE).affirmAllerRetour(rt::identiqueFloat) - -// Doubles -listOf(0.0, 1.0, Double.MIN_VALUE, Double.MAX_VALUE).affirmAllerRetour(rt::identiqueDouble) - -// Strings -listOf("", "abc", "null\u0000byte", "été", "ښي لاس ته لوستلو لوستل", "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama") - .affirmAllerRetour(rt::identiqueString) - -listOf(-1, 0, 1).map { DictionnaireNombresSignes(it.toByte(), it.toShort(), it.toInt(), it.toLong()) } - .affirmAllerRetour(rt::identiqueNombresSignes) - -listOf(0, 1).map { DictionnaireNombres(it.toUByte(), it.toUShort(), it.toUInt(), it.toULong()) } - .affirmAllerRetour(rt::identiqueNombres) - - -rt.destroy() - -// Test one way across the FFI. -// -// We send one representation of a value to lib.rs, and it transforms it into another, a string. -// lib.rs sends the string back, and then we compare here in kotlin. -// -// This shows that the values are transformed into strings the same way in both kotlin and rust. -// i.e. if we assume that the string return works (we test this assumption elsewhere) -// we show that lowering from kotlin and lifting into rust has values that both kotlin and rust -// both stringify in the same way. i.e. the same values. -// -// If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust t here, -// and this convinces us that lowering/lifting from here to rust is correct, then -// together, we've shown the correctness of the return leg. -val st = Stringifier() - -typealias StringyEquals = (observed: String, expected: T) -> Boolean -fun List.affirmEnchaine( - fn: (T) -> String, - equals: StringyEquals = { obs, exp -> obs == exp.toString() } -) { - this.forEach { exp -> - val obs = fn.invoke(exp) - assert(equals(obs, exp)) { "$fn($exp): observed=$obs, expected=$exp" } - } -} - -// Test the efficacy of the string transport from rust. If this fails, but everything else -// works, then things are very weird. -val wellKnown = st.wellKnownString("kotlin") -assert("uniffi 💚 kotlin!" == wellKnown) { "wellKnownString 'uniffi 💚 kotlin!' == '$wellKnown'" } - -// Booleans -listOf(true, false).affirmEnchaine(st::toStringBoolean) - -// Bytes. -listOf(Byte.MIN_VALUE, Byte.MAX_VALUE).affirmEnchaine(st::toStringI8) -listOf(UByte.MIN_VALUE, UByte.MAX_VALUE).affirmEnchaine(st::toStringU8) - -// Shorts -listOf(Short.MIN_VALUE, Short.MAX_VALUE).affirmEnchaine(st::toStringI16) -listOf(UShort.MIN_VALUE, UShort.MAX_VALUE).affirmEnchaine(st::toStringU16) - -// Ints -listOf(0, 1, -1, Int.MIN_VALUE, Int.MAX_VALUE).affirmEnchaine(st::toStringI32) -listOf(0u, 1u, UInt.MIN_VALUE, UInt.MAX_VALUE).affirmEnchaine(st::toStringU32) - -// Longs -listOf(0L, 1L, -1L, Long.MIN_VALUE, Long.MAX_VALUE).affirmEnchaine(st::toStringI64) -listOf(0u, 1u, ULong.MIN_VALUE, ULong.MAX_VALUE).affirmEnchaine(st::toStringU64) - -// Floats -// MIN_VALUE is 1.4E-45. Accuracy and formatting get weird at small sizes. -listOf(0.0F, 1.0F, -1.0F, Float.MIN_VALUE, Float.MAX_VALUE).affirmEnchaine(st::toStringFloat) { s, n -> s.toFloat() == n } - -// Doubles -// MIN_VALUE is 4.9E-324. Accuracy and formatting get weird at small sizes. -listOf(0.0, 1.0, -1.0, Double.MIN_VALUE, Double.MAX_VALUE).affirmEnchaine(st::toStringDouble) { s, n -> s.toDouble() == n } - -st.destroy() - -// Prove to ourselves that default arguments are being used. -// Step 1: call the methods without arguments, and check against the UDL. -val op = Optionneur() - -assert(op.sinonString() == "default") - -assert(op.sinonBoolean() == false) - -assert(op.sinonSequence() == listOf()) - -// optionals -assert(op.sinonNull() == null) -assert(op.sinonZero() == 0) - -// decimal integers -assert(op.sinonI8Dec() == (-42).toByte()) -assert(op.sinonU8Dec() == 42.toUByte()) -assert(op.sinonI16Dec() == 42.toShort()) -assert(op.sinonU16Dec() == 42.toUShort()) -assert(op.sinonI32Dec() == 42) -assert(op.sinonU32Dec() == 42.toUInt()) -assert(op.sinonI64Dec() == 42L) -assert(op.sinonU64Dec() == 42uL) - -// hexadecimal integers -assert(op.sinonI8Hex() == (-0x7f).toByte()) -assert(op.sinonU8Hex() == 0xff.toUByte()) -assert(op.sinonI16Hex() == 0x7f.toShort()) -assert(op.sinonU16Hex() == 0xffff.toUShort()) -assert(op.sinonI32Hex() == 0x7fffffff) -assert(op.sinonU32Hex() == 0xffffffff.toUInt()) -assert(op.sinonI64Hex() == 0x7fffffffffffffffL) -assert(op.sinonU64Hex() == 0xffffffffffffffffuL) - -// octal integers -assert(op.sinonU32Oct() == 493u) // 0o755 - -// floats -assert(op.sinonF32() == 42.0f) -assert(op.sinonF64() == 42.1) - -// enums -assert(op.sinonEnum() == Enumeration.TROIS) - -// Step 2. Convince ourselves that if we pass something else, then that changes the output. -// We have shown something coming out of the sinon methods, but without eyeballing the Rust -// we can't be sure that the arguments will change the return value. -listOf("foo", "bar").affirmAllerRetour(op::sinonString) -listOf(true, false).affirmAllerRetour(op::sinonBoolean) -listOf(listOf("a", "b"), listOf()).affirmAllerRetour(op::sinonSequence) - -// optionals -listOf("0", "1").affirmAllerRetour(op::sinonNull) -listOf(0, 1).affirmAllerRetour(op::sinonZero) - -// integers -listOf(0, 1).map { it.toUByte() }.affirmAllerRetour(op::sinonU8Dec) -listOf(0, 1).map { it.toByte() }.affirmAllerRetour(op::sinonI8Dec) -listOf(0, 1).map { it.toUShort() }.affirmAllerRetour(op::sinonU16Dec) -listOf(0, 1).map { it.toShort() }.affirmAllerRetour(op::sinonI16Dec) -listOf(0, 1).map { it.toUInt() }.affirmAllerRetour(op::sinonU32Dec) -listOf(0, 1).map { it.toInt() }.affirmAllerRetour(op::sinonI32Dec) -listOf(0, 1).map { it.toULong() }.affirmAllerRetour(op::sinonU64Dec) -listOf(0, 1).map { it.toLong() }.affirmAllerRetour(op::sinonI64Dec) - -listOf(0, 1).map { it.toUByte() }.affirmAllerRetour(op::sinonU8Hex) -listOf(0, 1).map { it.toByte() }.affirmAllerRetour(op::sinonI8Hex) -listOf(0, 1).map { it.toUShort() }.affirmAllerRetour(op::sinonU16Hex) -listOf(0, 1).map { it.toShort() }.affirmAllerRetour(op::sinonI16Hex) -listOf(0, 1).map { it.toUInt() }.affirmAllerRetour(op::sinonU32Hex) -listOf(0, 1).map { it.toInt() }.affirmAllerRetour(op::sinonI32Hex) -listOf(0, 1).map { it.toULong() }.affirmAllerRetour(op::sinonU64Hex) -listOf(0, 1).map { it.toLong() }.affirmAllerRetour(op::sinonI64Hex) - -listOf(0, 1).map { it.toUInt() }.affirmAllerRetour(op::sinonU32Oct) - -// floats -listOf(0.0f, 1.0f).affirmAllerRetour(op::sinonF32) -listOf(0.0, 1.0).affirmAllerRetour(op::sinonF64) - -// enums -Enumeration.values().toList().affirmAllerRetour(op::sinonEnum) - -op.destroy() - -// Testing defaulting properties in record types. -val defaultes = OptionneurDictionnaire() -val explicites = OptionneurDictionnaire( - i8Var = -8, - u8Var = 8u, - i16Var = -16, - u16Var = 0x10u, - i32Var = -32, - u32Var = 32u, - i64Var = -64L, - u64Var = 64uL, - floatVar = 4.0f, - doubleVar = 8.0, - booleanVar = true, - stringVar = "default", - listVar = listOf(), - enumerationVar = Enumeration.DEUX, - dictionnaireVar = null -) -assert(defaultes == explicites) - -// …and makes sure they travel across and back the FFI. -val rt2 = Retourneur() -listOf(defaultes).affirmAllerRetour(rt2::identiqueOptionneurDictionnaire) - -rt2.destroy() diff --git a/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.py b/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.py deleted file mode 100644 index 0b47c0fa5..000000000 --- a/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.py +++ /dev/null @@ -1,146 +0,0 @@ -import sys -import ctypes -from rondpoint import * - -dico = Dictionnaire(un=Enumeration.DEUX, deux=True, petit_nombre=0, gros_nombre=123456789) -copyDico = copie_dictionnaire(dico) -assert dico == copyDico - -assert copie_enumeration(Enumeration.DEUX) == Enumeration.DEUX -assert copie_enumerations([Enumeration.UN, Enumeration.DEUX]) == [Enumeration.UN, Enumeration.DEUX] -assert copie_carte({ - "0": EnumerationAvecDonnees.ZERO(), - "1": EnumerationAvecDonnees.UN(1), - "2": EnumerationAvecDonnees.DEUX(2, "deux"), -}) == { - "0": EnumerationAvecDonnees.ZERO(), - "1": EnumerationAvecDonnees.UN(1), - "2": EnumerationAvecDonnees.DEUX(2, "deux"), -} - -assert switcheroo(False) is True - -assert EnumerationAvecDonnees.ZERO() != EnumerationAvecDonnees.UN(1) -assert EnumerationAvecDonnees.UN(1) == EnumerationAvecDonnees.UN(1) -assert EnumerationAvecDonnees.UN(1) != EnumerationAvecDonnees.UN(2) - -# Test the roundtrip across the FFI. -# This shows that the values we send come back in exactly the same state as we sent them. -# i.e. it shows that lowering from python and lifting into rust is symmetrical with -# lowering from rust and lifting into python. -rt = Retourneur() - -def affirmAllerRetour(vals, identique): - for v in vals: - id_v = identique(v) - assert id_v == v, f"Round-trip failure: {v} => {id_v}" - -MIN_I8 = -1 * 2**7 -MAX_I8 = 2**7 - 1 -MIN_I16 = -1 * 2**15 -MAX_I16 = 2**15 - 1 -MIN_I32 = -1 * 2**31 -MAX_I32 = 2**31 - 1 -MIN_I64 = -1 * 2**31 -MAX_I64 = 2**31 - 1 - -# Python floats are always doubles, so won't round-trip through f32 correctly. -# This truncates them appropriately. -F32_ONE_THIRD = ctypes.c_float(1.0 / 3).value - -# Booleans -affirmAllerRetour([True, False], rt.identique_boolean) - -# Bytes. -affirmAllerRetour([MIN_I8, -1, 0, 1, MAX_I8], rt.identique_i8) -affirmAllerRetour([0x00, 0x12, 0xFF], rt.identique_u8) - -# Shorts -affirmAllerRetour([MIN_I16, -1, 0, 1, MAX_I16], rt.identique_i16) -affirmAllerRetour([0x0000, 0x1234, 0xFFFF], rt.identique_u16) - -# Ints -affirmAllerRetour([MIN_I32, -1, 0, 1, MAX_I32], rt.identique_i32) -affirmAllerRetour([0x00000000, 0x12345678, 0xFFFFFFFF], rt.identique_u32) - -# Longs -affirmAllerRetour([MIN_I64, -1, 0, 1, MAX_I64], rt.identique_i64) -affirmAllerRetour([0x0000000000000000, 0x1234567890ABCDEF, 0xFFFFFFFFFFFFFFFF], rt.identique_u64) - -# Floats -affirmAllerRetour([0.0, 0.5, 0.25, 1.0, F32_ONE_THIRD], rt.identique_float) - -# Doubles -affirmAllerRetour( - [0.0, 0.5, 0.25, 1.0, 1.0 / 3, sys.float_info.max, sys.float_info.min], - rt.identique_double -) - -# Strings -affirmAllerRetour( - ["", "abc", "été", "ښي لاس ته لوستلو لوستل", "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama"], - rt.identique_string -) - -# Test one way across the FFI. -# -# We send one representation of a value to lib.rs, and it transforms it into another, a string. -# lib.rs sends the string back, and then we compare here in python. -# -# This shows that the values are transformed into strings the same way in both python and rust. -# i.e. if we assume that the string return works (we test this assumption elsewhere) -# we show that lowering from python and lifting into rust has values that both python and rust -# both stringify in the same way. i.e. the same values. -# -# If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust to here, -# and this convinces us that lowering/lifting from here to rust is correct, then -# together, we've shown the correctness of the return leg. -st = Stringifier() - -def affirmEnchaine(vals, toString, rustyStringify=lambda v: str(v).lower()): - for v in vals: - str_v = toString(v) - assert rustyStringify(v) == str_v, f"String compare error {v} => {str_v}" - -# Test the efficacy of the string transport from rust. If this fails, but everything else -# works, then things are very weird. -wellKnown = st.well_known_string("python") -assert "uniffi 💚 python!" == wellKnown - -# Booleans -affirmEnchaine([True, False], st.to_string_boolean) - -# Bytes. -affirmEnchaine([MIN_I8, -1, 0, 1, MAX_I8], st.to_string_i8) -affirmEnchaine([0x00, 0x12, 0xFF], st.to_string_u8) - -# Shorts -affirmEnchaine([MIN_I16, -1, 0, 1, MAX_I16], st.to_string_i16) -affirmEnchaine([0x0000, 0x1234, 0xFFFF], st.to_string_u16) - -# Ints -affirmEnchaine([MIN_I32, -1, 0, 1, MAX_I32], st.to_string_i32) -affirmEnchaine([0x00000000, 0x12345678, 0xFFFFFFFF], st.to_string_u32) - -# Longs -affirmEnchaine([MIN_I64, -1, 0, 1, MAX_I64], st.to_string_i64) -affirmEnchaine([0x0000000000000000, 0x1234567890ABCDEF, 0xFFFFFFFFFFFFFFFF], st.to_string_u64) - -# Floats -def rustyFloatToStr(v): - """Stringify a float in the same way that rust seems to.""" - # Rust doesn't include the decimal part of whole enumber floats when stringifying. - if int(v) == v: - return str(int(v)) - return str(v) - -affirmEnchaine([0.0, 0.5, 0.25, 1.0], st.to_string_float, rustyFloatToStr) -assert st.to_string_float(F32_ONE_THIRD) == "0.33333334" # annoyingly different string repr - -# Doubles -# TODO: float_info.max/float_info.min don't stringify-roundtrip properly yet, TBD. -affirmEnchaine( - [0.0, 0.5, 0.25, 1.0, 1.0 / 3], - st.to_string_double, - rustyFloatToStr, -) diff --git a/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.swift b/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.swift deleted file mode 100644 index d9f47058e..000000000 --- a/uniffi/examples/rondpoint/tests/bindings/test_rondpoint.swift +++ /dev/null @@ -1,232 +0,0 @@ -import rondpoint - -let dico = Dictionnaire(un: .deux, deux: false, petitNombre: 0, grosNombre: 123456789) -let copyDico = copieDictionnaire(d: dico) -assert(dico == copyDico) - -assert(copieEnumeration(e: .deux) == .deux) -assert(copieEnumerations(e: [.un, .deux]) == [.un, .deux]) -assert(copieCarte(c: - ["0": .zero, - "1": .un(premier: 1), - "2": .deux(premier: 2, second: "deux") -]) == [ - "0": .zero, - "1": .un(premier: 1), - "2": .deux(premier: 2, second: "deux") -]) - -assert(EnumerationAvecDonnees.zero != EnumerationAvecDonnees.un(premier: 1)) -assert(EnumerationAvecDonnees.un(premier: 1) == EnumerationAvecDonnees.un(premier: 1)) -assert(EnumerationAvecDonnees.un(premier: 1) != EnumerationAvecDonnees.un(premier: 2)) - - -assert(switcheroo(b: false)) - -// Test the roundtrip across the FFI. -// This shows that the values we send come back in exactly the same state as we sent them. -// i.e. it shows that lowering from swift and lifting into rust is symmetrical with -// lowering from rust and lifting into swift. -let rt = Retourneur() - -// Booleans -[true, false].affirmAllerRetour(rt.identiqueBoolean) - -// Bytes. -[.min, .max].affirmAllerRetour(rt.identiqueI8) -[0x00, 0xFF].map { $0 as UInt8 }.affirmAllerRetour(rt.identiqueU8) - -// Shorts -[.min, .max].affirmAllerRetour(rt.identiqueI16) -[0x0000, 0xFFFF].map { $0 as UInt16 }.affirmAllerRetour(rt.identiqueU16) - -// Ints -[0, 1, -1, .min, .max].affirmAllerRetour(rt.identiqueI32) -[0x00000000, 0xFFFFFFFF].map { $0 as UInt32 }.affirmAllerRetour(rt.identiqueU32) - -// Longs -[.zero, 1, -1, .min, .max].affirmAllerRetour(rt.identiqueI64) -[.zero, 1, .min, .max].affirmAllerRetour(rt.identiqueU64) - -// Floats -[.zero, 1, 0.25, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmAllerRetour(rt.identiqueFloat) - -// Doubles -[0.0, 1.0, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmAllerRetour(rt.identiqueDouble) - -// Strings -["", "abc", "null\0byte", "été", "ښي لاس ته لوستلو لوستل", "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama"] - .affirmAllerRetour(rt.identiqueString) - -// Test one way across the FFI. -// -// We send one representation of a value to lib.rs, and it transforms it into another, a string. -// lib.rs sends the string back, and then we compare here in swift. -// -// This shows that the values are transformed into strings the same way in both swift and rust. -// i.e. if we assume that the string return works (we test this assumption elsewhere) -// we show that lowering from swift and lifting into rust has values that both swift and rust -// both stringify in the same way. i.e. the same values. -// -// If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust t here, -// and this convinces us that lowering/lifting from here to rust is correct, then -// together, we've shown the correctness of the return leg. -let st = Stringifier() - -// Test the effigacy of the string transport from rust. If this fails, but everything else -// works, then things are very weird. -let wellKnown = st.wellKnownString(value: "swift") -assert("uniffi 💚 swift!" == wellKnown, "wellKnownString 'uniffi 💚 swift!' == '\(wellKnown)'") - -// Booleans -[true, false].affirmEnchaine(st.toStringBoolean) - -// Bytes. -[.min, .max].affirmEnchaine(st.toStringI8) -[.min, .max].affirmEnchaine(st.toStringU8) - -// Shorts -[.min, .max].affirmEnchaine(st.toStringI16) -[.min, .max].affirmEnchaine(st.toStringU16) - -// Ints -[0, 1, -1, .min, .max].affirmEnchaine(st.toStringI32) -[0, 1, .min, .max].affirmEnchaine(st.toStringU32) - -// Longs -[.zero, 1, -1, .min, .max].affirmEnchaine(st.toStringI64) -[.zero, 1, .min, .max].affirmEnchaine(st.toStringU64) - -// Floats -[.zero, 1, -1, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmEnchaine(st.toStringFloat) { Float.init($0) == $1 } - -// Doubles -[.zero, 1, -1, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmEnchaine(st.toStringDouble) { Double.init($0) == $1 } - -// Some extension functions for testing the results of roundtripping and stringifying -extension Array where Element: Equatable { - static func defaultEquals(_ observed: String, expected: Element) -> Bool { - let exp = "\(expected)" - return observed == exp - } - - func affirmEnchaine(_ fn: (Element) -> String, equals: (String, Element) -> Bool = defaultEquals) { - self.forEach { v in - let obs = fn(v) - assert(equals(obs, v), "toString_\(type(of:v))(\(v)): observed=\(obs), expected=\(v)") - } - } - - func affirmAllerRetour(_ fn: (Element) -> Element) { - self.forEach { v in - assert(fn(v) == v, "identique_\(type(of:v))(\(v))") - } - } -} - -// Prove to ourselves that default arguments are being used. -// Step 1: call the methods without arguments, and check against the UDL. -let op = Optionneur() - -assert(op.sinonString() == "default") - -assert(op.sinonBoolean() == false) - -assert(op.sinonSequence() == []) - -// optionals -assert(op.sinonNull() == nil) -assert(op.sinonZero() == 0) - -// decimal integers -assert(op.sinonU8Dec() == UInt8(42)) -assert(op.sinonI8Dec() == Int8(-42)) -assert(op.sinonU16Dec() == UInt16(42)) -assert(op.sinonI16Dec() == Int16(42)) -assert(op.sinonU32Dec() == UInt32(42)) -assert(op.sinonI32Dec() == Int32(42)) -assert(op.sinonU64Dec() == UInt64(42)) -assert(op.sinonI64Dec() == Int64(42)) - -// hexadecimal integers -assert(op.sinonU8Hex() == UInt8(0xff)) -assert(op.sinonI8Hex() == Int8(-0x7f)) -assert(op.sinonU16Hex() == UInt16(0xffff)) -assert(op.sinonI16Hex() == Int16(0x7f)) -assert(op.sinonU32Hex() == UInt32(0xffffffff)) -assert(op.sinonI32Hex() == Int32(0x7fffffff)) -assert(op.sinonU64Hex() == UInt64(0xffffffffffffffff)) -assert(op.sinonI64Hex() == Int64(0x7fffffffffffffff)) - -// octal integers -assert(op.sinonU32Oct() == UInt32(0o755)) - -// floats -assert(op.sinonF32() == 42.0) -assert(op.sinonF64() == Double(42.1)) - -// enums -assert(op.sinonEnum() == .trois) - -// Step 2. Convince ourselves that if we pass something else, then that changes the output. -// We have shown something coming out of the sinon methods, but without eyeballing the Rust -// we can't be sure that the arguments will change the return value. -["foo", "bar"].affirmAllerRetour(op.sinonString) -[true, false].affirmAllerRetour(op.sinonBoolean) -[["a", "b"], []].affirmAllerRetour(op.sinonSequence) - -// optionals -["0", "1"].affirmAllerRetour(op.sinonNull) -[0, 1].affirmAllerRetour(op.sinonZero) - -// integers -[0, 1].affirmAllerRetour(op.sinonU8Dec) -[0, 1].affirmAllerRetour(op.sinonI8Dec) -[0, 1].affirmAllerRetour(op.sinonU16Dec) -[0, 1].affirmAllerRetour(op.sinonI16Dec) -[0, 1].affirmAllerRetour(op.sinonU32Dec) -[0, 1].affirmAllerRetour(op.sinonI32Dec) -[0, 1].affirmAllerRetour(op.sinonU64Dec) -[0, 1].affirmAllerRetour(op.sinonI64Dec) - -[0, 1].affirmAllerRetour(op.sinonU8Hex) -[0, 1].affirmAllerRetour(op.sinonI8Hex) -[0, 1].affirmAllerRetour(op.sinonU16Hex) -[0, 1].affirmAllerRetour(op.sinonI16Hex) -[0, 1].affirmAllerRetour(op.sinonU32Hex) -[0, 1].affirmAllerRetour(op.sinonI32Hex) -[0, 1].affirmAllerRetour(op.sinonU64Hex) -[0, 1].affirmAllerRetour(op.sinonI64Hex) - -[0, 1].affirmAllerRetour(op.sinonU32Oct) - -// floats -[0.0, 1.0].affirmAllerRetour(op.sinonF32) -[0.0, 1.0].affirmAllerRetour(op.sinonF64) - -// enums -[.un, .deux, .trois].affirmAllerRetour(op.sinonEnum) - -// Testing defaulting properties in record types. -let defaultes = OptionneurDictionnaire() -let explicites = OptionneurDictionnaire( - i8Var: Int8(-8), - u8Var: UInt8(8), - i16Var: Int16(-16), - u16Var: UInt16(0x10), - i32Var: -32, - u32Var: UInt32(32), - i64Var: Int64(-64), - u64Var: UInt64(64), - floatVar: Float(4.0), - doubleVar: Double(8.0), - booleanVar: true, - stringVar: "default", - listVar: [], - enumerationVar: .deux, - dictionnaireVar: nil -) - -// …and makes sure they travel across and back the FFI. -assert(defaultes == explicites) -[defaultes].affirmAllerRetour(rt.identiqueOptionneurDictionnaire) diff --git a/uniffi/examples/rondpoint/tests/test_generated_bindings.rs b/uniffi/examples/rondpoint/tests/test_generated_bindings.rs deleted file mode 100644 index b7530d52f..000000000 --- a/uniffi/examples/rondpoint/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_rondpoint.kts", - "tests/bindings/test_rondpoint.swift", - "tests/bindings/test_rondpoint.py", -); diff --git a/uniffi/examples/sprites/Cargo.toml b/uniffi/examples/sprites/Cargo.toml deleted file mode 100644 index e38c9a768..000000000 --- a/uniffi/examples/sprites/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-example-sprites" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_sprites" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/sprites/build.rs b/uniffi/examples/sprites/build.rs deleted file mode 100644 index 26ac3085b..000000000 --- a/uniffi/examples/sprites/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/sprites.udl").unwrap(); -} diff --git a/uniffi/examples/sprites/src/lib.rs b/uniffi/examples/sprites/src/lib.rs deleted file mode 100644 index d3cc11e40..000000000 --- a/uniffi/examples/sprites/src/lib.rs +++ /dev/null @@ -1,65 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::RwLock; - -// A point in two-dimensional space. -#[derive(Debug, Clone)] -pub struct Point { - x: f64, - y: f64, -} - -// A magnitude and direction in two-dimensional space. -// For simplicity we represent this as a point relative to the origin. -#[derive(Debug, Clone)] -pub struct Vector { - dx: f64, - dy: f64, -} - -// Move from the given Point, according to the given Vector. -pub fn translate(p: &Point, v: Vector) -> Point { - Point { - x: p.x + v.dx, - y: p.y + v.dy, - } -} - -// An entity in our imaginary world, which occupies a position in space -// and which can move about over time. -#[derive(Debug)] -pub struct Sprite { - // We must use interior mutability for managing mutable state, hence the `RwLock`. - current_position: RwLock, -} - -impl Sprite { - fn new(initial_position: Option) -> Sprite { - Sprite { - current_position: RwLock::new(initial_position.unwrap_or(Point { x: 0.0, y: 0.0 })), - } - } - - fn new_relative_to(reference: Point, direction: Vector) -> Sprite { - Sprite { - current_position: RwLock::new(translate(&reference, direction)), - } - } - - fn get_position(&self) -> Point { - self.current_position.read().unwrap().clone() - } - - fn move_to(&self, position: Point) { - *self.current_position.write().unwrap() = position; - } - - fn move_by(&self, direction: Vector) { - let mut current_position = self.current_position.write().unwrap(); - *current_position = translate(¤t_position, direction) - } -} - -uniffi::include_scaffolding!("sprites"); diff --git a/uniffi/examples/sprites/src/sprites.udl b/uniffi/examples/sprites/src/sprites.udl deleted file mode 100644 index 6781c6cee..000000000 --- a/uniffi/examples/sprites/src/sprites.udl +++ /dev/null @@ -1,22 +0,0 @@ - -namespace sprites { - Point translate([ByRef] Point position, Vector direction); -}; - -dictionary Point { - double x; - double y; -}; - -dictionary Vector { - double dx; - double dy; -}; - -interface Sprite { - constructor(Point? initial_position); - [Name=new_relative_to] constructor(Point reference, Vector direction); - Point get_position(); - void move_to(Point position); - void move_by(Vector direction); -}; diff --git a/uniffi/examples/sprites/tests/bindings/test_sprites.kts b/uniffi/examples/sprites/tests/bindings/test_sprites.kts deleted file mode 100644 index 42451f28d..000000000 --- a/uniffi/examples/sprites/tests/bindings/test_sprites.kts +++ /dev/null @@ -1,25 +0,0 @@ -import uniffi.sprites.*; - -val sempty = Sprite(null) -assert( sempty.getPosition() == Point(0.0, 0.0) ) - -val s = Sprite(Point(0.0, 1.0)) -assert( s.getPosition() == Point(0.0, 1.0) ) - -s.moveTo(Point(1.0, 2.0)) -assert( s.getPosition() == Point(1.0, 2.0) ) - -s.moveBy(Vector(-4.0, 2.0)) -assert( s.getPosition() == Point(-3.0, 4.0) ) - -s.destroy() -try { - s.moveBy(Vector(0.0, 0.0)) - assert(false) { "Should not be able to call anything after `destroy`" } -} catch(e: IllegalStateException) { - assert(true) -} - -val srel = Sprite.newRelativeTo(Point(0.0, 1.0), Vector(1.0, 1.5)) -assert( srel.getPosition() == Point(1.0, 2.5) ) - diff --git a/uniffi/examples/sprites/tests/bindings/test_sprites.py b/uniffi/examples/sprites/tests/bindings/test_sprites.py deleted file mode 100644 index d04742e07..000000000 --- a/uniffi/examples/sprites/tests/bindings/test_sprites.py +++ /dev/null @@ -1,17 +0,0 @@ -from sprites import * - -sempty = Sprite(None) -assert sempty.get_position() == Point(x=0, y=0) - -s = Sprite(Point(x=0, y=1)) -assert s.get_position() == Point(x=0, y=1) - -s.move_to(Point(x=1, y=2)) -assert s.get_position() == Point(x=1, y=2) - -s.move_by(Vector(dx=-4, dy=2)) -assert s.get_position() == Point(x=-3, y=4) - -srel = Sprite.new_relative_to(Point(x=0, y=1), Vector(dx=1, dy=1.5)) -assert srel.get_position() == Point(x=1, y=2.5) - diff --git a/uniffi/examples/sprites/tests/bindings/test_sprites.swift b/uniffi/examples/sprites/tests/bindings/test_sprites.swift deleted file mode 100644 index d5428ac67..000000000 --- a/uniffi/examples/sprites/tests/bindings/test_sprites.swift +++ /dev/null @@ -1,16 +0,0 @@ -import sprites - -let sempty = Sprite(initialPosition: nil) -assert( sempty.getPosition() == Point(x: 0, y: 0)) - -let s = Sprite(initialPosition: Point(x: 0, y: 1)) -assert( s.getPosition() == Point(x: 0, y: 1)) - -s.moveTo(position: Point(x: 1.0, y: 2.0)) -assert( s.getPosition() == Point(x: 1, y: 2)) - -s.moveBy(direction: Vector(dx: -4, dy: 2)) -assert( s.getPosition() == Point(x: -3, y: 4)) - -let srel = Sprite.newRelativeTo(reference: Point(x: 0.0, y: 1.0), direction: Vector(dx: 1, dy: 1.5)) -assert( srel.getPosition() == Point(x: 1.0, y: 2.5) ) diff --git a/uniffi/examples/sprites/tests/test_generated_bindings.rs b/uniffi/examples/sprites/tests/test_generated_bindings.rs deleted file mode 100644 index 429adf10e..000000000 --- a/uniffi/examples/sprites/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_sprites.py", - "tests/bindings/test_sprites.kts", - "tests/bindings/test_sprites.swift", -); diff --git a/uniffi/examples/todolist/Cargo.toml b/uniffi/examples/todolist/Cargo.toml deleted file mode 100644 index c06864f20..000000000 --- a/uniffi/examples/todolist/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "uniffi-example-todolist" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_todolist" - -[dependencies] -uniffi = { workspace = true } -once_cell = "1.12" -thiserror = "2" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/todolist/build.rs b/uniffi/examples/todolist/build.rs deleted file mode 100644 index 2dd2f68b7..000000000 --- a/uniffi/examples/todolist/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/todolist.udl").unwrap(); -} diff --git a/uniffi/examples/todolist/src/lib.rs b/uniffi/examples/todolist/src/lib.rs deleted file mode 100644 index 11cdc63ae..000000000 --- a/uniffi/examples/todolist/src/lib.rs +++ /dev/null @@ -1,150 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::{Arc, RwLock}; - -use once_cell::sync::Lazy; - -#[derive(Debug, Clone)] -pub struct TodoEntry { - text: String, -} - -// There is a single "default" TodoList that can be shared -// by all consumers of this component. Depending on requirements, -// a real app might like to use a `Weak<>` rather than an `Arc<>` -// here to reduce the risk of circular references. -static DEFAULT_LIST: Lazy>>> = Lazy::new(|| RwLock::new(None)); - -#[derive(Debug, thiserror::Error)] -pub enum TodoError { - #[error("The todo does not exist!")] - TodoDoesNotExist, - #[error("The todolist is empty!")] - EmptyTodoList, - #[error("That todo already exists!")] - DuplicateTodo, - #[error("Empty String error!: {0}")] - EmptyString(String), - #[error("I am a delegated Error: {0}")] - DeligatedError(#[from] std::io::Error), -} - -/// Get a reference to the global default TodoList, if set. -/// -fn get_default_list() -> Option> { - DEFAULT_LIST.read().unwrap().clone() -} - -/// Set the global default TodoList. -/// -/// This will silently drop any previously set value. -/// -fn set_default_list(list: Arc) { - *DEFAULT_LIST.write().unwrap() = Some(list); -} - -/// Create a new TodoEntry from the given string. -/// -fn create_entry_with>(item: S) -> Result { - let text = item.into(); - if text.is_empty() { - return Err(TodoError::EmptyString( - "Cannot add empty string as entry".to_string(), - )); - } - Ok(TodoEntry { text }) -} - -type Result = std::result::Result; - -// A simple Todolist. -// UniFFI requires that we use interior mutability for managing mutable state, so we wrap our `Vec` in a RwLock. -// (A Mutex would also work, but a RwLock is more appropriate for this use-case, so we use it). -#[derive(Debug)] -pub struct TodoList { - items: RwLock>, -} - -impl TodoList { - fn new() -> Self { - Self { - items: RwLock::new(Vec::new()), - } - } - - fn add_item>(&self, item: S) -> Result<()> { - let item = item.into(); - if item.is_empty() { - return Err(TodoError::EmptyString( - "Cannot add empty string as item".to_string(), - )); - } - let mut items = self.items.write().unwrap(); - if items.contains(&item) { - return Err(TodoError::DuplicateTodo); - } - items.push(item); - Ok(()) - } - - fn get_last(&self) -> Result { - let items = self.items.read().unwrap(); - items.last().cloned().ok_or(TodoError::EmptyTodoList) - } - - fn get_first(&self) -> Result { - let items = self.items.read().unwrap(); - items.first().cloned().ok_or(TodoError::EmptyTodoList) - } - - fn add_entries(&self, entries: Vec) { - let mut items = self.items.write().unwrap(); - items.extend(entries.into_iter().map(|e| e.text)) - } - - fn add_entry(&self, entry: TodoEntry) -> Result<()> { - self.add_item(entry.text) - } - - fn add_items>(&self, items: Vec) { - let mut my_items = self.items.write().unwrap(); - my_items.extend(items.into_iter().map(Into::into)) - } - - fn get_items(&self) -> Vec { - let items = self.items.read().unwrap(); - items.clone() - } - - fn get_entries(&self) -> Vec { - let items = self.items.read().unwrap(); - items - .iter() - .map(|text| TodoEntry { text: text.clone() }) - .collect() - } - - fn get_last_entry(&self) -> Result { - let text = self.get_last()?; - Ok(TodoEntry { text }) - } - - fn clear_item>(&self, item: S) -> Result<()> { - let item = item.into(); - let mut items = self.items.write().unwrap(); - let idx = items - .iter() - .position(|s| s == &item) - .ok_or(TodoError::TodoDoesNotExist)?; - items.remove(idx); - Ok(()) - } - - fn make_default(self: Arc) { - set_default_list(self); - } -} - -uniffi::include_scaffolding!("todolist"); diff --git a/uniffi/examples/todolist/src/todolist.udl b/uniffi/examples/todolist/src/todolist.udl deleted file mode 100644 index 5c923314c..000000000 --- a/uniffi/examples/todolist/src/todolist.udl +++ /dev/null @@ -1,38 +0,0 @@ -namespace todolist { - TodoList? get_default_list(); - undefined set_default_list(TodoList list); - - [Throws=TodoError] - TodoEntry create_entry_with(string todo); -}; - -dictionary TodoEntry { - string text; -}; - -[Error] -enum TodoError { - "TodoDoesNotExist", "EmptyTodoList", "DuplicateTodo", "EmptyString", "DeligatedError" -}; - -interface TodoList { - constructor(); - [Throws=TodoError] - void add_item(string todo); - [Throws=TodoError] - void add_entry(TodoEntry entry); - sequence get_entries(); - sequence get_items(); - void add_entries(sequence entries); - void add_items(sequence items); - [Throws=TodoError] - TodoEntry get_last_entry(); - [Throws=TodoError] - string get_last(); - [Throws=TodoError] - string get_first(); - [Throws=TodoError] - void clear_item(string todo); - [Self=ByArc] - undefined make_default(); -}; diff --git a/uniffi/examples/todolist/tests/bindings/test_todolist.kts b/uniffi/examples/todolist/tests/bindings/test_todolist.kts deleted file mode 100644 index bb2b29222..000000000 --- a/uniffi/examples/todolist/tests/bindings/test_todolist.kts +++ /dev/null @@ -1,83 +0,0 @@ -import uniffi.todolist.* - -val todo = TodoList() - -// This throws an exception: -try { - todo.getLast() - throw RuntimeException("Should have thrown a TodoError!") -} catch (e: TodoException.EmptyTodoList) { - // It's okay, we don't have any items yet! -} - -try { - createEntryWith("") - throw RuntimeException("Should have thrown a TodoError!") -} catch (e: TodoException) { - // It's okay, the string was empty! - assert(e is TodoException.EmptyString) - assert(e !is TodoException.EmptyTodoList) -} - -todo.addItem("Write strings support") - -assert(todo.getLast() == "Write strings support") - -todo.addItem("Write tests for strings support") - -assert(todo.getLast() == "Write tests for strings support") - -val entry = createEntryWith("Write bindings for strings as record members") - -todo.addEntry(entry) -assert(todo.getLast() == "Write bindings for strings as record members") -assert(todo.getLastEntry().text == "Write bindings for strings as record members") - -todo.addItem("Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") -assert(todo.getLast() == "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") - -val entry2 = TodoEntry("Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") -todo.addEntry(entry2) -assert(todo.getLastEntry().text == "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") - -assert(todo.getEntries().size == 5) - -todo.addEntries(listOf(TodoEntry("foo"), TodoEntry("bar"))) -assert(todo.getEntries().size == 7) -assert(todo.getLastEntry().text == "bar") - -todo.addItems(listOf("bobo", "fofo")) -assert(todo.getItems().size == 9) -assert(todo.getItems()[7] == "bobo") - -assert(getDefaultList() == null) - -// Note that each individual object instance needs to be explicitly destroyed, -// either by using the `.use` helper or explicitly calling its `.destroy` method. -// Failure to do so will leak the underlying Rust object. -TodoList().use { todo2 -> - setDefaultList(todo) - getDefaultList()!!.use { default -> - assert(todo.getEntries() == default.getEntries()) - assert(todo2.getEntries() != default.getEntries()) - } - - todo2.makeDefault() - getDefaultList()!!.use { default -> - assert(todo.getEntries() != default.getEntries()) - assert(todo2.getEntries() == default.getEntries()) - } - - todo.addItem("Test liveness after being demoted from default") - assert(todo.getLast() == "Test liveness after being demoted from default") - - todo2.addItem("Test shared state through local vs default reference") - getDefaultList()!!.use { default -> - assert(default.getLast() == "Test shared state through local vs default reference") - } -} - -// Ensure the kotlin version of deinit doesn't crash, and is idempotent. -todo.destroy() -todo.destroy() - diff --git a/uniffi/examples/todolist/tests/bindings/test_todolist.py b/uniffi/examples/todolist/tests/bindings/test_todolist.py deleted file mode 100644 index 7b676c83d..000000000 --- a/uniffi/examples/todolist/tests/bindings/test_todolist.py +++ /dev/null @@ -1,44 +0,0 @@ -from todolist import * - -todo = TodoList() - -entry = TodoEntry(text="Write bindings for strings in records") - -todo.add_item("Write python bindings") - -assert(todo.get_last() == "Write python bindings") - -todo.add_item("Write tests for bindings") - -assert(todo.get_last() == "Write tests for bindings") - -todo.add_entry(entry) - -assert(todo.get_last() == "Write bindings for strings in records") -assert(todo.get_last_entry().text == "Write bindings for strings in records") - -todo.add_item("Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") -assert(todo.get_last() == "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") - -entry2 = TodoEntry(text="Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") -todo.add_entry(entry2) -assert(todo.get_last_entry().text == "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") - -todo2 = TodoList() -assert(todo != todo2) -assert(todo is not todo2) - -assert(get_default_list() is None) - -set_default_list(todo) -assert(todo.get_items() == get_default_list().get_items()) - -todo2.make_default() -assert(todo2.get_items() == get_default_list().get_items()) - -todo.add_item("Test liveness after being demoted from default") -assert(todo.get_last() == "Test liveness after being demoted from default") - -todo2.add_item("Test shared state through local vs default reference") -assert(get_default_list().get_last() == "Test shared state through local vs default reference") - diff --git a/uniffi/examples/todolist/tests/bindings/test_todolist.swift b/uniffi/examples/todolist/tests/bindings/test_todolist.swift deleted file mode 100644 index 6ce72cadb..000000000 --- a/uniffi/examples/todolist/tests/bindings/test_todolist.swift +++ /dev/null @@ -1,69 +0,0 @@ -import todolist - - -let todo = TodoList() -do { - let _ = try todo.getLast() - fatalError("Should have thrown an EmptyTodoList error!") -} catch TodoError.EmptyTodoList{ - //It's okay! There are not todos! -} -try! todo.addItem(todo: "Write swift bindings") -assert( try! todo.getLast() == "Write swift bindings") - -try! todo.addItem(todo: "Write tests for bindings") -assert(try! todo.getLast() == "Write tests for bindings") - -let entry = TodoEntry(text: "Write bindings for strings as record members") -try! todo.addEntry(entry: entry) -assert(try! todo.getLast() == "Write bindings for strings as record members") - -try! todo.addItem(todo: "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") -assert(try! todo.getLast() == "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") - -do { - let _ = try createEntryWith(todo: "") - fatalError("Should have thrown an EmptyString error!") -} catch TodoError.EmptyString { - // It's okay! It was an empty string -} - -let entry2 = TodoEntry(text: "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") -try! todo.addEntry(entry: entry2) -assert(try! todo.getLastEntry() == entry2) - -assert(todo.getEntries().count == 5) - -todo.addEntries(entries: [TodoEntry(text: "foo"), TodoEntry(text: "bar")]) -assert(todo.getEntries().count == 7) -assert(todo.getItems().count == 7) -assert(try! todo.getLast() == "bar") - -todo.addItems(items: ["bobo", "fofo"]) -assert(todo.getItems().count == 9) -assert(todo.getItems()[7] == "bobo") - -// Ensure deinit doesn't crash. -for _ in 0..<10 { - let list = TodoList() - try! list.addItem(todo: "todo") -} - -let todo2 = TodoList() - -assert(getDefaultList() == nil) - -setDefaultList(list: todo) -assert(todo.getItems() == getDefaultList()!.getItems()) -assert(todo2.getItems() != getDefaultList()!.getItems()) - -todo2.makeDefault() -assert(todo.getItems() != getDefaultList()!.getItems()) -assert(todo2.getItems() == getDefaultList()!.getItems()) - -try! todo.addItem(todo: "Test liveness after being demoted from default") -assert(try! todo.getLast() == "Test liveness after being demoted from default") - -try! todo2.addItem(todo: "Test shared state through local vs default reference") -assert(try! getDefaultList()!.getLast() == "Test shared state through local vs default reference") - diff --git a/uniffi/examples/todolist/tests/test_generated_bindings.rs b/uniffi/examples/todolist/tests/test_generated_bindings.rs deleted file mode 100644 index 942e8c890..000000000 --- a/uniffi/examples/todolist/tests/test_generated_bindings.rs +++ /dev/null @@ -1,5 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_todolist.kts", - "tests/bindings/test_todolist.swift", - "tests/bindings/test_todolist.py" -); diff --git a/uniffi/examples/traits/Cargo.toml b/uniffi/examples/traits/Cargo.toml deleted file mode 100644 index 95f06471e..000000000 --- a/uniffi/examples/traits/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "uniffi-example-traits" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_traits" - -[dependencies] -uniffi = { workspace = true } -thiserror = "2" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } - - -[features] -ffi-trace = ["uniffi/ffi-trace"] diff --git a/uniffi/examples/traits/build.rs b/uniffi/examples/traits/build.rs deleted file mode 100644 index d053b72ca..000000000 --- a/uniffi/examples/traits/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/traits.udl").unwrap(); -} diff --git a/uniffi/examples/traits/src/lib.rs b/uniffi/examples/traits/src/lib.rs deleted file mode 100644 index 51d81d83d..000000000 --- a/uniffi/examples/traits/src/lib.rs +++ /dev/null @@ -1,37 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -// namespace functions. -fn get_buttons() -> Vec> { - vec![Arc::new(StopButton {}), Arc::new(GoButton {})] -} - -fn press(button: Arc) -> Arc { - button -} - -#[uniffi::trait_interface] -pub trait Button: Send + Sync { - fn name(&self) -> String; -} - -struct GoButton {} - -impl Button for GoButton { - fn name(&self) -> String { - "go".to_string() - } -} - -struct StopButton {} - -impl Button for StopButton { - fn name(&self) -> String { - "stop".to_string() - } -} - -uniffi::include_scaffolding!("traits"); diff --git a/uniffi/examples/traits/src/traits.udl b/uniffi/examples/traits/src/traits.udl deleted file mode 100644 index 6b75916d3..000000000 --- a/uniffi/examples/traits/src/traits.udl +++ /dev/null @@ -1,12 +0,0 @@ -namespace traits { - // Get all the buttons we can press. - sequence