зеркало из https://github.com/mozilla/gecko-dev.git
Bug 1772132 - Update Glean and remove cargo metadata replacement. r=janerik,supply-chain-reviewers
Differential Revision: https://phabricator.services.mozilla.com/D151499
This commit is contained in:
Родитель
a96bb5524e
Коммит
a285a07c6e
|
@ -58,14 +58,14 @@ checksum = "85965b6739a430150bdd138e2374a98af0c3ee0d030b3bb7fc3bddff58d0102e"
|
|||
|
||||
[[package]]
|
||||
name = "android_logger"
|
||||
version = "0.10.1"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9ed09b18365ed295d722d0b5ed59c01b79a826ff2d2a8f73d5ecca8e6fb2f66"
|
||||
checksum = "b74b7ddf197de32e415d197aa21c1c0cb36e01e4794fd801302280ac7847ee02"
|
||||
dependencies = [
|
||||
"android_log-sys",
|
||||
"env_logger 0.8.999",
|
||||
"lazy_static",
|
||||
"env_logger 0.9.0",
|
||||
"log",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -644,13 +644,6 @@ dependencies = [
|
|||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cargo_metadata"
|
||||
version = "0.13.999"
|
||||
dependencies = [
|
||||
"cargo_metadata 0.14.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cargo_metadata"
|
||||
version = "0.14.2"
|
||||
|
@ -2277,9 +2270,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "glean"
|
||||
version = "50.1.0"
|
||||
version = "50.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0857be0c251ae1fc3b5672237c99f5115a6546cd8b171cb240173098ab5e9629"
|
||||
checksum = "813fa9059f1a7d9da4fcf6cff6c77e6226fc26f58797d1659d16a8279c4655f2"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"crossbeam-channel",
|
||||
|
@ -2297,15 +2290,15 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "glean-core"
|
||||
version = "50.1.0"
|
||||
version = "50.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1bdfa0e2e6476190b4762c4cdc87c1a7a0347f601864b091cf9ad674a909c68"
|
||||
checksum = "e5edb2b6cf2938242adda6ece26ac29b2238c693c423331c8a68ce980c348b28"
|
||||
dependencies = [
|
||||
"android_logger",
|
||||
"bincode",
|
||||
"chrono",
|
||||
"crossbeam-channel",
|
||||
"env_logger 0.8.999",
|
||||
"env_logger 0.9.0",
|
||||
"ffi-support",
|
||||
"flate2",
|
||||
"log",
|
||||
|
@ -3744,13 +3737,6 @@ dependencies = [
|
|||
"void",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "5.999.999"
|
||||
dependencies = [
|
||||
"nom 6.1.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "6.1.2"
|
||||
|
@ -5690,13 +5676,14 @@ checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04"
|
|||
|
||||
[[package]]
|
||||
name = "uniffi"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0fe14882ae6ea89f31ac922ad8e6f76b3f346f07965791a60ade60cc3bcdd60"
|
||||
checksum = "bc1de33ad46ce00bc9a31cea44e80ef69175d3a23007335216fe3996880a310d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes 1.1.0",
|
||||
"cargo_metadata 0.13.999",
|
||||
"camino",
|
||||
"cargo_metadata",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"paste",
|
||||
|
@ -5705,15 +5692,18 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "uniffi_bindgen"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49a9810482e988792ed22fc6747d872bd32600f7e3bfc11fe93019d155d7e89c"
|
||||
checksum = "b18e05c55840ddd690ba211f72bb1f2f6ca8c50bfeb7d7211ea5ee60b0f9be07"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
"cargo_metadata 0.13.999",
|
||||
"camino",
|
||||
"cargo_metadata",
|
||||
"clap",
|
||||
"fs-err",
|
||||
"heck",
|
||||
"lazy_static",
|
||||
"paste",
|
||||
"serde",
|
||||
"toml 0.5.9",
|
||||
|
@ -5722,20 +5712,22 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "uniffi_build"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bcb7401cfd8da93541c23a0683c1dab3c782d2a118254536106b0aa4d9b30607"
|
||||
checksum = "8fff0860625e4e621f0317e5f6ac9e79966262bd86a6cfb2049e8425df23afbd"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"camino",
|
||||
"uniffi_bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uniffi_macros"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7b60ccb030ef51b0c85eb9ca55f28ff68b82c1a29d2bc0c7053777010af0d3"
|
||||
checksum = "7956a6c1fb12bff15e537028ea2174f000f90dd4f87912233b276ea782d420f2"
|
||||
dependencies = [
|
||||
"camino",
|
||||
"glob",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
@ -6093,12 +6085,12 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "weedle2"
|
||||
version = "2.0.1"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a69b360c3d0df7dc1a18124677ee8476576c806418f30a360a6cf6cf4e072a6"
|
||||
checksum = "5d730d941cf471131c40a64cf2e8a595822009f51e64c05c5afdbc85af155857"
|
||||
dependencies = [
|
||||
"fs-err",
|
||||
"nom 5.999.999",
|
||||
"nom 6.1.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
@ -115,13 +115,6 @@ env_logger = { path = "build/rust/env_logger" }
|
|||
# Patch toml 0.4 to 0.5
|
||||
toml = { path = "build/rust/toml" }
|
||||
|
||||
# Patch cargo_metadata 0.13 to 0.14.2
|
||||
# FIXME(bug 1772132): To be removed with the next Glean update
|
||||
cargo_metadata = { path = "build/rust/cargo_metadata" }
|
||||
|
||||
# Patch nom 5 to nom 6
|
||||
nom = { path = "build/rust/nom" }
|
||||
|
||||
# Patch parking_lot 0.12 down to 0.11, which is compatible for most crates that use it, to avoid
|
||||
# dependencies on windows-sys.
|
||||
parking_lot = { path = "build/rust/parking_lot" }
|
||||
|
|
|
@ -36,7 +36,7 @@ allprojects {
|
|||
topsrcdir = gradle.mozconfig.topsrcdir
|
||||
topobjdir = gradle.mozconfig.topobjdir
|
||||
|
||||
gleanVersion = "50.1.0"
|
||||
gleanVersion = "50.1.2"
|
||||
if (gleanVersion != getRustVersionFor("glean")) {
|
||||
throw new StopExecutionException("Mismatched Glean version, expected: ${gleanVersion}," +
|
||||
" found ${getRustVersionFor("glean")}")
|
||||
|
|
|
@ -1,15 +0,0 @@
|
|||
[package]
|
||||
name = "cargo_metadata"
|
||||
version = "0.13.999"
|
||||
edition = "2018"
|
||||
license = "MPL-2.0"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
|
||||
[dependencies]
|
||||
cargo_metadata = "0.14.2"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
builder = ["cargo_metadata/derive_builder"]
|
|
@ -1,5 +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 use cargo_metadata::*;
|
|
@ -1,20 +0,0 @@
|
|||
[package]
|
||||
name = "nom"
|
||||
version = "5.999.999"
|
||||
edition = "2018"
|
||||
license = "MPL-2.0"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
|
||||
[dependencies.nom]
|
||||
version = "6.0"
|
||||
default-features = false
|
||||
|
||||
[features]
|
||||
alloc = ["nom/alloc"]
|
||||
default = ["nom/default"]
|
||||
lexical = ["nom/lexical-core"]
|
||||
regexp = ["nom/regex"]
|
||||
regexp_macros = ["nom/regexp_macros"]
|
||||
std = ["nom/std"]
|
|
@ -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/. */
|
||||
|
||||
pub use nom::*;
|
||||
|
||||
pub use nom::separated_list0 as separated_list;
|
||||
pub use nom::separated_list1 as separated_nonempty_list;
|
||||
|
||||
pub type IResult<I, O, E=(I, error::ErrorKind)> = nom::IResult<I, O, E>;
|
|
@ -31,14 +31,14 @@ checksum = "85965b6739a430150bdd138e2374a98af0c3ee0d030b3bb7fc3bddff58d0102e"
|
|||
|
||||
[[package]]
|
||||
name = "android_logger"
|
||||
version = "0.10.1"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9ed09b18365ed295d722d0b5ed59c01b79a826ff2d2a8f73d5ecca8e6fb2f66"
|
||||
checksum = "b74b7ddf197de32e415d197aa21c1c0cb36e01e4794fd801302280ac7847ee02"
|
||||
dependencies = [
|
||||
"android_log-sys",
|
||||
"env_logger",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -236,14 +236,13 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "cargo_metadata"
|
||||
version = "0.13.1"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "081e3f0755c1f380c2d010481b6fa2e02973586d5f2b24eebb7a2a1d98b143d8"
|
||||
checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa"
|
||||
dependencies = [
|
||||
"camino",
|
||||
"cargo-platform",
|
||||
"semver",
|
||||
"semver-parser",
|
||||
"semver 1.0.12",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
@ -673,9 +672,9 @@ checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3"
|
|||
|
||||
[[package]]
|
||||
name = "env_logger"
|
||||
version = "0.8.4"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3"
|
||||
checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"humantime",
|
||||
|
@ -877,9 +876,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "glean"
|
||||
version = "50.1.0"
|
||||
version = "50.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0857be0c251ae1fc3b5672237c99f5115a6546cd8b171cb240173098ab5e9629"
|
||||
checksum = "813fa9059f1a7d9da4fcf6cff6c77e6226fc26f58797d1659d16a8279c4655f2"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"crossbeam-channel",
|
||||
|
@ -897,9 +896,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "glean-core"
|
||||
version = "50.1.0"
|
||||
version = "50.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1bdfa0e2e6476190b4762c4cdc87c1a7a0347f601864b091cf9ad674a909c68"
|
||||
checksum = "e5edb2b6cf2938242adda6ece26ac29b2238c693c423331c8a68ce980c348b28"
|
||||
dependencies = [
|
||||
"android_logger",
|
||||
"bincode",
|
||||
|
@ -1427,16 +1426,6 @@ dependencies = [
|
|||
"memoffset",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "5.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ffb4262d26ed83a1c0a33a38fe2bb15797329c85770da05e6b828ddb782627af"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "6.2.1"
|
||||
|
@ -1939,6 +1928,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6"
|
||||
dependencies = [
|
||||
"semver-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2333e6df6d6598f2b1974829f853c2b4c5f4a6e503c10af918081aa6f8564e1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
|
@ -2239,12 +2236,13 @@ checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c"
|
|||
|
||||
[[package]]
|
||||
name = "uniffi"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0fe14882ae6ea89f31ac922ad8e6f76b3f346f07965791a60ade60cc3bcdd60"
|
||||
checksum = "bc1de33ad46ce00bc9a31cea44e80ef69175d3a23007335216fe3996880a310d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"camino",
|
||||
"cargo_metadata",
|
||||
"lazy_static",
|
||||
"log",
|
||||
|
@ -2254,15 +2252,18 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "uniffi_bindgen"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49a9810482e988792ed22fc6747d872bd32600f7e3bfc11fe93019d155d7e89c"
|
||||
checksum = "b18e05c55840ddd690ba211f72bb1f2f6ca8c50bfeb7d7211ea5ee60b0f9be07"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
"camino",
|
||||
"cargo_metadata",
|
||||
"clap",
|
||||
"fs-err",
|
||||
"heck",
|
||||
"lazy_static",
|
||||
"paste 1.0.7",
|
||||
"serde",
|
||||
"toml",
|
||||
|
@ -2271,20 +2272,22 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "uniffi_build"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bcb7401cfd8da93541c23a0683c1dab3c782d2a118254536106b0aa4d9b30607"
|
||||
checksum = "8fff0860625e4e621f0317e5f6ac9e79966262bd86a6cfb2049e8425df23afbd"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"camino",
|
||||
"uniffi_bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uniffi_macros"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7b60ccb030ef51b0c85eb9ca55f28ff68b82c1a29d2bc0c7053777010af0d3"
|
||||
checksum = "7956a6c1fb12bff15e537028ea2174f000f90dd4f87912233b276ea782d420f2"
|
||||
dependencies = [
|
||||
"camino",
|
||||
"glob",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
@ -2578,12 +2581,12 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "weedle2"
|
||||
version = "2.0.1"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a69b360c3d0df7dc1a18124677ee8476576c806418f30a360a6cf6cf4e072a6"
|
||||
checksum = "5d730d941cf471131c40a64cf2e8a595822009f51e64c05c5afdbc85af155857"
|
||||
dependencies = [
|
||||
"fs-err",
|
||||
"nom 5.1.2",
|
||||
"nom 6.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -2701,7 +2704,7 @@ dependencies = [
|
|||
"ndk-glue",
|
||||
"osmesa-src",
|
||||
"osmesa-sys",
|
||||
"semver",
|
||||
"semver 0.11.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"swgl",
|
||||
|
|
|
@ -55,7 +55,7 @@ debug = ["webrender/capture", "webrender/profiler"]
|
|||
|
||||
[dependencies]
|
||||
app_units = "0.7"
|
||||
env_logger = "0.8"
|
||||
env_logger = "0.9"
|
||||
euclid = "0.22"
|
||||
gleam = "0.13"
|
||||
glutin = "0.28"
|
||||
|
|
|
@ -51,7 +51,7 @@ svg_fmt = "0.4"
|
|||
tracy-rs = "0.1.2"
|
||||
derive_more = { version = "0.99", default-features = false, features = ["add_assign"] }
|
||||
etagere = "0.2.6"
|
||||
glean = "50.1.0"
|
||||
glean = "50.1.2"
|
||||
fog = { version = "0.1.0", optional = true }
|
||||
swgl = { path = "../swgl", optional = true }
|
||||
topological-sort = "0.1"
|
||||
|
|
|
@ -13,7 +13,7 @@ path = "src/main.rs"
|
|||
|
||||
[dependencies]
|
||||
base64 = "0.13"
|
||||
env_logger = { version = "0.8.4", optional = true }
|
||||
env_logger = { version = "0.9", optional = true }
|
||||
gleam = "0.13"
|
||||
glutin = "0.28"
|
||||
clap = { version = "3.1", features = ["yaml"] }
|
||||
|
|
|
@ -129,7 +129,7 @@ pth:xpcom/geckoprocesstypes_generator
|
|||
pth:xpcom/idl-parser
|
||||
# glean-sdk may not be installable if a wheel isn't available
|
||||
# and it has to be built from source.
|
||||
pypi-optional:glean-sdk==50.1.0:telemetry will not be collected
|
||||
pypi-optional:glean-sdk==50.1.2:telemetry will not be collected
|
||||
# Mach gracefully handles the case where `psutil` is unavailable.
|
||||
# We aren't (yet) able to pin packages in automation, so we have to
|
||||
# support down to the oldest locally-installed version (5.4.2).
|
||||
|
|
|
@ -1,6 +1,12 @@
|
|||
|
||||
# cargo-vet audits file
|
||||
|
||||
[[audits.android_logger]]
|
||||
who = "Jan-Erik Rediger <jrediger@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "0.11.0"
|
||||
notes = "Small crate, wrapping Android log functionality, reviewed by janerik"
|
||||
|
||||
[[audits.android_system_properties]]
|
||||
who = "Nicolas Silva <nical@fastmail.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
|
@ -57,12 +63,24 @@ criteria = "safe-to-deploy"
|
|||
version = "50.1.0"
|
||||
notes = "Maintained by the Glean team at Mozilla"
|
||||
|
||||
[[audits.glean]]
|
||||
who = "Travis Long <tlong@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "50.1.2"
|
||||
notes = "Maintained by the Glean team at Mozilla"
|
||||
|
||||
[[audits.glean-core]]
|
||||
who = "Jan-Erik Rediger <jrediger@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "50.1.0"
|
||||
notes = "Maintained by the Glean team at Mozilla"
|
||||
|
||||
[[audits.glean-core]]
|
||||
who = "Travis Long <tlong@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "50.1.2"
|
||||
notes = "Maintained by the Glean team at Mozilla"
|
||||
|
||||
[[audits.linked-hash-map]]
|
||||
who = "Aria Beingessner <a.beingessner@gmail.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
|
@ -129,12 +147,42 @@ criteria = "safe-to-deploy"
|
|||
delta = "0.1.19 -> 0.1.20"
|
||||
notes = "I am the author of most of these changes upstream, and prepared the release myself, at which point I looked at the other changes since 0.1.19."
|
||||
|
||||
[[audits.uniffi]]
|
||||
who = "Travis Long <tlong@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "0.19.3"
|
||||
notes = "Maintained by the Glean and Application Services teams"
|
||||
|
||||
[[audits.uniffi_bindgen]]
|
||||
who = "Travis Long <tlong@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "0.19.3"
|
||||
notes = "Maintained by the Glean and Application Services teams."
|
||||
|
||||
[[audits.uniffi_build]]
|
||||
who = "Travis Long <tlong@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "0.19.3"
|
||||
notes = "Maintained by the Glean and Application Services teams."
|
||||
|
||||
[[audits.uniffi_macros]]
|
||||
who = "Travis Long <tlong@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "0.19.3"
|
||||
notes = "Maintained by the Glean and Application Services teams."
|
||||
|
||||
[[audits.void]]
|
||||
who = "Bobby Holley <bobbyholley@gmail.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "1.0.2"
|
||||
notes = "Very small crate, just hosts the Void type for easier cross-crate interfacing."
|
||||
|
||||
[[audits.weedle2]]
|
||||
who = "Travis Long <tlong@mozilla.com>"
|
||||
criteria = "safe-to-deploy"
|
||||
version = "3.0.0"
|
||||
notes = "Maintained by the Glean and Application Services teams."
|
||||
|
||||
[[audits.webdriver]]
|
||||
who = "Henrik Skupin <mail@hskupin.info>"
|
||||
criteria = "safe-to-deploy"
|
||||
|
|
|
@ -177,10 +177,6 @@ criteria = "safe-to-deploy"
|
|||
version = "0.2.0"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.android_logger]]
|
||||
version = "0.10.1"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.anyhow]]
|
||||
version = "1.0.57"
|
||||
criteria = "safe-to-deploy"
|
||||
|
@ -1721,22 +1717,6 @@ criteria = "safe-to-deploy"
|
|||
version = "0.2.3"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.uniffi]]
|
||||
version = "0.18.0"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.uniffi_bindgen]]
|
||||
version = "0.18.0"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.uniffi_build]]
|
||||
version = "0.18.0"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.uniffi_macros]]
|
||||
version = "0.18.0"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.unix_path]]
|
||||
version = "1.0.1"
|
||||
criteria = "safe-to-run"
|
||||
|
@ -1793,10 +1773,6 @@ criteria = "safe-to-deploy"
|
|||
version = "0.3.9"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.weedle2]]
|
||||
version = "2.0.1"
|
||||
criteria = "safe-to-deploy"
|
||||
|
||||
[[exemptions.wgpu-core]]
|
||||
version = "0.12.0"
|
||||
criteria = "safe-to-deploy"
|
||||
|
|
|
@ -1 +1 @@
|
|||
{"files":{"Cargo.toml":"632df8824223ca0e23352f6b0d103ac994fab57dc51f33c2e6d41c91256e1c4d","LICENSE-APACHE":"99938c5864dd33decb62ab20fd883a9b00181d768ae887a4f19b2d0015c41dc9","LICENSE-MIT":"35043211d1b7be8f7e3f9cad27d981f2189ba9a39d9527b275b3c9740298dfe2","README.md":"7a4f75e61fc014f4dbb907fa947e1983f45993dc2a85104cdb619c0808433f65","src/lib.rs":"bdbd60c12117123c2554b1984949dfbc403d890318a0de637829592f4359de6d","tests/config_log_level.rs":"8aae2c7decbcf12a2a454486c9d4dd4a82a20e01d327c4abf4e9cfded973159d","tests/default_init.rs":"ef18c9ea38687a178623c11acfa3d34d16b9030eaad337ab9ed6a609a2c42ca2","tests/multiple_init.rs":"a6ed4986a758b7b2322c6ad0a18ec99fd06521a6c8767a6622eab2cbf9be601e"},"package":"d9ed09b18365ed295d722d0b5ed59c01b79a826ff2d2a8f73d5ecca8e6fb2f66"}
|
||||
{"files":{"Cargo.toml":"896268b277c2cd333293139e868abac82c39983de9aa56aead4464c38239b66a","LICENSE-APACHE":"99938c5864dd33decb62ab20fd883a9b00181d768ae887a4f19b2d0015c41dc9","LICENSE-MIT":"35043211d1b7be8f7e3f9cad27d981f2189ba9a39d9527b275b3c9740298dfe2","README.md":"bf2e6227790edeb5959c2be250b71d1a197a3a344dc5fc1638fbb39c73bdfd21","src/lib.rs":"e3a0a6bb68d7bad681a978274b612e77cecc41112b448209a09c96b5b33d029e","tests/config_log_level.rs":"8aae2c7decbcf12a2a454486c9d4dd4a82a20e01d327c4abf4e9cfded973159d","tests/default_init.rs":"ef18c9ea38687a178623c11acfa3d34d16b9030eaad337ab9ed6a609a2c42ca2","tests/multiple_init.rs":"a6ed4986a758b7b2322c6ad0a18ec99fd06521a6c8767a6622eab2cbf9be601e"},"package":"b74b7ddf197de32e415d197aa21c1c0cb36e01e4794fd801302280ac7847ee02"}
|
|
@ -3,38 +3,46 @@
|
|||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you believe there's an error in this file please file an
|
||||
# issue against the rust-lang/cargo repository. If you're
|
||||
# editing this file be aware that the upstream Cargo.toml
|
||||
# will likely look very different (and much more reasonable)
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
name = "android_logger"
|
||||
version = "0.10.1"
|
||||
version = "0.11.0"
|
||||
authors = ["The android_logger Developers"]
|
||||
description = "A logging implementation for `log` which hooks to android log output.\n"
|
||||
description = """
|
||||
A logging implementation for `log` which hooks to android log output.
|
||||
"""
|
||||
readme = "README.md"
|
||||
keywords = ["android", "bindings", "log", "logger"]
|
||||
keywords = [
|
||||
"android",
|
||||
"bindings",
|
||||
"log",
|
||||
"logger",
|
||||
]
|
||||
categories = ["api-bindings"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/Nercury/android_logger-rs"
|
||||
|
||||
[dependencies.android_log-sys]
|
||||
version = "0.2"
|
||||
|
||||
[dependencies.env_logger]
|
||||
version = "0.8"
|
||||
version = "0.9"
|
||||
default-features = false
|
||||
|
||||
[dependencies.lazy_static]
|
||||
version = "1.4"
|
||||
|
||||
[dependencies.log]
|
||||
version = "0.4"
|
||||
|
||||
[dependencies.once_cell]
|
||||
version = "1.9"
|
||||
|
||||
[features]
|
||||
default = ["regex"]
|
||||
regex = ["env_logger/regex"]
|
||||
|
||||
[badges.travis-ci]
|
||||
repository = "Nercury/android_logger-rs"
|
||||
|
|
|
@ -13,7 +13,7 @@ this library:
|
|||
|
||||
```toml
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
android_logger = "0.10"
|
||||
android_logger = "0.11"
|
||||
```
|
||||
|
||||
Example of initialization on activity creation, with log configuration:
|
||||
|
|
|
@ -65,15 +65,13 @@
|
|||
|
||||
#[cfg(target_os = "android")]
|
||||
extern crate android_log_sys as log_ffi;
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
extern crate once_cell;
|
||||
use once_cell::sync::OnceCell;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
extern crate env_logger;
|
||||
|
||||
use std::sync::RwLock;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
use log_ffi::LogPriority;
|
||||
use log::{Level, Log, Metadata, Record};
|
||||
|
@ -105,21 +103,20 @@ fn android_log(_priority: Level, _tag: &CStr, _msg: &CStr) {}
|
|||
|
||||
/// Underlying android logger backend
|
||||
pub struct AndroidLogger {
|
||||
config: RwLock<Config>,
|
||||
config: OnceCell<Config>,
|
||||
}
|
||||
|
||||
impl AndroidLogger {
|
||||
/// Create new logger instance from config
|
||||
pub fn new(config: Config) -> AndroidLogger {
|
||||
AndroidLogger {
|
||||
config: RwLock::new(config),
|
||||
config: OnceCell::from(config),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref ANDROID_LOGGER: AndroidLogger = AndroidLogger::default();
|
||||
}
|
||||
|
||||
static ANDROID_LOGGER: OnceCell<AndroidLogger> = OnceCell::new();
|
||||
|
||||
const LOGGING_TAG_MAX_LEN: usize = 23;
|
||||
const LOGGING_MSG_MAX_LEN: usize = 4000;
|
||||
|
@ -128,7 +125,7 @@ impl Default for AndroidLogger {
|
|||
/// Create a new logger with default config
|
||||
fn default() -> AndroidLogger {
|
||||
AndroidLogger {
|
||||
config: RwLock::new(Config::default()),
|
||||
config: OnceCell::from(Config::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -140,8 +137,7 @@ impl Log for AndroidLogger {
|
|||
|
||||
fn log(&self, record: &Record) {
|
||||
let config = self.config
|
||||
.read()
|
||||
.expect("failed to acquire android_log filter lock for read");
|
||||
.get_or_init(Config::default);
|
||||
|
||||
if !config.filter_matches(record) {
|
||||
return;
|
||||
|
@ -155,7 +151,7 @@ impl Log for AndroidLogger {
|
|||
|
||||
// If no tag was specified, use module name
|
||||
let custom_tag = &config.tag;
|
||||
let tag = custom_tag.as_ref().map(|s| s.as_bytes()).unwrap_or(module_path.as_bytes());
|
||||
let tag = custom_tag.as_ref().map(|s| s.as_bytes()).unwrap_or_else(|| module_path.as_bytes());
|
||||
|
||||
// truncate the tag here to fit into LOGGING_TAG_MAX_LEN
|
||||
self.fill_tag_bytes(&mut tag_bytes, tag);
|
||||
|
@ -206,6 +202,7 @@ impl AndroidLogger {
|
|||
}
|
||||
|
||||
/// Filter for android logger.
|
||||
#[derive(Default)]
|
||||
pub struct Config {
|
||||
log_level: Option<Level>,
|
||||
filter: Option<env_logger::filter::Filter>,
|
||||
|
@ -213,17 +210,6 @@ pub struct Config {
|
|||
custom_format: Option<FormatFn>,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
log_level: None,
|
||||
filter: None,
|
||||
tag: None,
|
||||
custom_format: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Change the minimum log level.
|
||||
///
|
||||
|
@ -236,7 +222,7 @@ impl Config {
|
|||
|
||||
fn filter_matches(&self, record: &Record) -> bool {
|
||||
if let Some(ref filter) = self.filter {
|
||||
filter.matches(&record)
|
||||
filter.matches(record)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
|
@ -365,7 +351,7 @@ impl<'a> PlatformLogWriter<'a> {
|
|||
|
||||
/// Copy `len` bytes from `index` position to starting position.
|
||||
fn copy_bytes_to_start(&mut self, index: usize, len: usize) {
|
||||
let src = unsafe { self.buffer.as_ptr().offset(index as isize) };
|
||||
let src = unsafe { self.buffer.as_ptr().add(index) };
|
||||
let dst = self.buffer.as_mut_ptr();
|
||||
unsafe { ptr::copy(src, dst, len) };
|
||||
}
|
||||
|
@ -423,7 +409,7 @@ impl<'a> fmt::Write for PlatformLogWriter<'a> {
|
|||
/// This action does not require initialization. However, without initialization it
|
||||
/// will use the default filter, which allows all logs.
|
||||
pub fn log(record: &Record) {
|
||||
ANDROID_LOGGER.log(record)
|
||||
ANDROID_LOGGER.get_or_init(AndroidLogger::default).log(record)
|
||||
}
|
||||
|
||||
/// Initializes the global logger with an android logger.
|
||||
|
@ -434,16 +420,13 @@ pub fn log(record: &Record) {
|
|||
/// It is ok to call this at the activity creation, and it will be
|
||||
/// repeatedly called on every lifecycle restart (i.e. screen rotation).
|
||||
pub fn init_once(config: Config) {
|
||||
if let Err(err) = log::set_logger(&*ANDROID_LOGGER) {
|
||||
let log_level = config.log_level;
|
||||
let logger = ANDROID_LOGGER.get_or_init(|| AndroidLogger::new(config));
|
||||
|
||||
if let Err(err) = log::set_logger(logger) {
|
||||
debug!("android_logger: log::set_logger failed: {}", err);
|
||||
} else {
|
||||
if let Some(level) = config.log_level {
|
||||
log::set_max_level(level.to_level_filter());
|
||||
}
|
||||
*ANDROID_LOGGER
|
||||
.config
|
||||
.write()
|
||||
.expect("failed to acquire android_log filter lock for write") = config;
|
||||
} else if let Some(level) = log_level {
|
||||
log::set_max_level(level.to_level_filter());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -531,7 +514,7 @@ mod tests {
|
|||
fn platform_log_writer_init_values() {
|
||||
let tag = CStr::from_bytes_with_nul(b"tag\0").unwrap();
|
||||
|
||||
let writer = PlatformLogWriter::new(Level::Warn, &tag);
|
||||
let writer = PlatformLogWriter::new(Level::Warn, tag);
|
||||
|
||||
assert_eq!(writer.tag, tag);
|
||||
// Android uses LogPriority instead, which doesn't implement equality checks
|
||||
|
@ -630,6 +613,6 @@ mod tests {
|
|||
}
|
||||
|
||||
fn get_tag_writer() -> PlatformLogWriter<'static> {
|
||||
PlatformLogWriter::new(Level::Warn, &CStr::from_bytes_with_nul(b"tag\0").unwrap())
|
||||
PlatformLogWriter::new(Level::Warn, CStr::from_bytes_with_nul(b"tag\0").unwrap())
|
||||
}
|
||||
}
|
||||
|
|
Различия файлов скрыты, потому что одна или несколько строк слишком длинны
|
@ -12,7 +12,7 @@
|
|||
[package]
|
||||
edition = "2018"
|
||||
name = "glean-core"
|
||||
version = "50.1.0"
|
||||
version = "50.1.2"
|
||||
authors = [
|
||||
"Jan-Erik Rediger <jrediger@mozilla.com>",
|
||||
"The Glean Team <glean-team@mozilla.com>",
|
||||
|
@ -76,10 +76,10 @@ version = "1.0.4"
|
|||
version = "0.1.40"
|
||||
|
||||
[dependencies.uniffi]
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
|
||||
[dependencies.uniffi_macros]
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
|
||||
[dependencies.uuid]
|
||||
version = "0.8.1"
|
||||
|
@ -95,7 +95,7 @@ version = "0.1.0"
|
|||
version = "0.1.12"
|
||||
|
||||
[dev-dependencies.env_logger]
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
features = [
|
||||
"termcolor",
|
||||
"atty",
|
||||
|
@ -110,14 +110,14 @@ version = "0.4"
|
|||
version = "3.1.0"
|
||||
|
||||
[build-dependencies.uniffi_build]
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
features = ["builtin-bindgen"]
|
||||
|
||||
[features]
|
||||
rkv-safe-mode = []
|
||||
|
||||
[target."cfg(not(target_os = \"android\"))".dependencies.env_logger]
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
features = [
|
||||
"termcolor",
|
||||
"atty",
|
||||
|
@ -126,7 +126,7 @@ features = [
|
|||
default-features = false
|
||||
|
||||
[target."cfg(target_os = \"android\")".dependencies.android_logger]
|
||||
version = "0.10.0"
|
||||
version = "0.11.0"
|
||||
default-features = false
|
||||
|
||||
[target."cfg(target_os = \"ios\")".dependencies.oslog]
|
||||
|
|
|
@ -63,7 +63,7 @@ enum Command {
|
|||
}
|
||||
|
||||
/// The error returned from operations on the dispatcher
|
||||
#[derive(Error, Debug, PartialEq)]
|
||||
#[derive(Error, Debug, PartialEq, Eq)]
|
||||
pub enum DispatchError {
|
||||
/// The worker panicked while running a task
|
||||
#[error("The worker panicked while running a task")]
|
||||
|
|
|
@ -27,7 +27,7 @@ use crate::Lifetime;
|
|||
/// in the platform-specific code (e.g. `ErrorType.kt`) and with the
|
||||
/// metrics in the registry files.
|
||||
// When adding a new error type ensure it's also added to `ErrorType::iter()` below.
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ErrorType {
|
||||
/// For when the value to be recorded does not match the metric-specific restrictions
|
||||
InvalidValue,
|
||||
|
|
|
@ -56,7 +56,7 @@ fn exponential_range(min: u64, max: u64, bucket_count: usize) -> Vec<u64> {
|
|||
///
|
||||
/// Buckets are pre-computed at instantiation with an exponential distribution from `min` to `max`
|
||||
/// and `bucket_count` buckets.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct PrecomputedExponential {
|
||||
// Don't serialize the (potentially large) array of ranges, instead compute them on first
|
||||
// access.
|
||||
|
|
|
@ -36,7 +36,7 @@ fn linear_range(min: u64, max: u64, count: usize) -> Vec<u64> {
|
|||
///
|
||||
/// Buckets are pre-computed at instantiation with a linear distribution from `min` to `max`
|
||||
/// and `bucket_count` buckets.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct PrecomputedLinear {
|
||||
// Don't serialize the (potentially large) array of ranges, instead compute them on first
|
||||
// access.
|
||||
|
|
|
@ -58,7 +58,7 @@ impl TryFrom<i32> for HistogramType {
|
|||
/// assert_eq!(10, hist.count());
|
||||
/// assert_eq!(55, hist.sum());
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Histogram<B> {
|
||||
/// Mapping bucket's minimum to sample count.
|
||||
values: HashMap<u64, u64>,
|
||||
|
|
|
@ -2,6 +2,7 @@
|
|||
// 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/.
|
||||
|
||||
#![allow(clippy::significant_drop_in_scrutinee)]
|
||||
#![deny(rustdoc::broken_intra_doc_links)]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
|
|||
use serde_json::{json, Map as JsonMap, Value as JsonValue};
|
||||
|
||||
/// Deserialized experiment data.
|
||||
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
|
||||
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
|
||||
pub struct RecordedExperiment {
|
||||
/// The experiment's branch as set through [`set_experiment_active`](crate::glean_set_experiment_active).
|
||||
pub branch: String,
|
||||
|
|
|
@ -11,7 +11,7 @@ use crate::error::{Error, ErrorKind};
|
|||
|
||||
/// Different resolutions supported by the time related
|
||||
/// metric types (e.g. DatetimeMetric).
|
||||
#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[repr(i32)] // use i32 to be compatible with our JNA definition
|
||||
pub enum TimeUnit {
|
||||
|
|
|
@ -127,7 +127,7 @@ impl RateLimiter {
|
|||
/// the requester may receive one out of three possible tasks.
|
||||
///
|
||||
/// If new variants are added, this should be reflected in `glean-core/ffi/src/upload.rs` as well.
|
||||
#[derive(PartialEq, Debug)]
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
pub enum PingUploadTask {
|
||||
/// An upload task
|
||||
Upload {
|
||||
|
|
|
@ -180,7 +180,7 @@ impl Builder {
|
|||
}
|
||||
|
||||
/// Represents a request to upload a ping.
|
||||
#[derive(PartialEq, Debug, Clone)]
|
||||
#[derive(PartialEq, Eq, Debug, Clone)]
|
||||
pub struct PingRequest {
|
||||
/// The Job ID to identify this request,
|
||||
/// this is the same as the ping UUID.
|
||||
|
|
|
@ -1 +1 @@
|
|||
{"files":{"Cargo.toml":"0b561e6268bc36b36c8c29d82fde25a451bd8fb7d618efa2145255033616a73b","LICENSE":"1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5","README.md":"5bc5b1c46695f628e1023662752272e938a963b535d5686bd1ecc433f9e018c4","src/common_test.rs":"68f6d408cb7b683fa32c8b38a4df1e6c45bfd77c0c90ca35976ea7548bbc4b2f","src/configuration.rs":"37ad5b3e7d4e31dd04a7d6690179168b5f2768d87dd36056dee5d08bdbe20fb2","src/core_metrics.rs":"76ac5350cb6f82d9a193d519b085a08f138dceba77da3514bd0c636bcdefefca","src/lib.rs":"e342d497d60abceca3c84d35523a54d187b0282220a112da53e4ab1cf76da205","src/net/http_uploader.rs":"43812a70d19a38e8d7a093c8076c2b6345372c3c861b0f3511428762700a65e0","src/net/mod.rs":"86cbcb0b46f9d13923a20db9e482b65da49d7daa4e335a3f3092f1d760f572b0","src/private/event.rs":"f6cd799c7764c53510180a1cef6a5a9b435fae27b87270519d5b4e59201e8ecc","src/private/mod.rs":"0364ecf5f0439443a5b209583f4ff2c474b79f7c253c981ab0b7cdc528368698","src/private/ping.rs":"cbdc57f41fc9d46e56b4dfff91ac683753d1f8b3ecd0aa9bc3419e3595b8b81b","src/system.rs":"ff23a5b94f52dab484342dfed702412bc29ab1bbfd5af326033d8e07e7b9075f","src/test.rs":"30d62d967c56a7ca76c097e27bfb6d6d3779ccd5d374cf5a07a04216e4e0880b","tests/common/mod.rs":"37cd4c48e140c793b852ae09fb3e812da28a4412977295015bcbffd632fcf294","tests/init_fails.rs":"9b78226a4e3220de5b64a205a97b8d5778d1700391b5b71c7819b6cdd120747e","tests/never_init.rs":"1f33b8ce7ca3514b57b48cc16d98408974c85cf8aa7d13257ffc2ad878ebb295","tests/no_time_to_init.rs":"494dcddce49f279c6508f484ee59cf8bb83e7324de07bdbc1142f2a066b7f6a1","tests/overflowing_preinit.rs":"396206d5078b7e6c148bbf2aecb0f963cfaa4d7eff3fc7bf6590125076ee6113","tests/persist_ping_lifetime.rs":"2297d4b208e14188e6dcca2d4806b805cfc7dd824d21bd143a7803b95e0709f4","tests/persist_ping_lifetime_nopanic.rs":"06f1f3ca3b8a6c8b7fc4d6fc48d0e1d2ccffd32139f080db0a95003e9edd507d","tests/schema.rs":"a96089f828928b6be1fad7815e3269f5693af1b773e570312b357a29af28122a","tests/simple.rs":"a1d72af899293390bb955ca379baafb89c29bb746630409f8c51f453d222dbad"},"package":"0857be0c251ae1fc3b5672237c99f5115a6546cd8b171cb240173098ab5e9629"}
|
||||
{"files":{"Cargo.toml":"22631469f647eb393b83eccffadea1ff3124ba4e79e402b754aab30926d384c0","LICENSE":"1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5","README.md":"5bc5b1c46695f628e1023662752272e938a963b535d5686bd1ecc433f9e018c4","src/common_test.rs":"68f6d408cb7b683fa32c8b38a4df1e6c45bfd77c0c90ca35976ea7548bbc4b2f","src/configuration.rs":"37ad5b3e7d4e31dd04a7d6690179168b5f2768d87dd36056dee5d08bdbe20fb2","src/core_metrics.rs":"76ac5350cb6f82d9a193d519b085a08f138dceba77da3514bd0c636bcdefefca","src/lib.rs":"e342d497d60abceca3c84d35523a54d187b0282220a112da53e4ab1cf76da205","src/net/http_uploader.rs":"43812a70d19a38e8d7a093c8076c2b6345372c3c861b0f3511428762700a65e0","src/net/mod.rs":"86cbcb0b46f9d13923a20db9e482b65da49d7daa4e335a3f3092f1d760f572b0","src/private/event.rs":"f6cd799c7764c53510180a1cef6a5a9b435fae27b87270519d5b4e59201e8ecc","src/private/mod.rs":"0364ecf5f0439443a5b209583f4ff2c474b79f7c253c981ab0b7cdc528368698","src/private/ping.rs":"cbdc57f41fc9d46e56b4dfff91ac683753d1f8b3ecd0aa9bc3419e3595b8b81b","src/system.rs":"ff23a5b94f52dab484342dfed702412bc29ab1bbfd5af326033d8e07e7b9075f","src/test.rs":"30d62d967c56a7ca76c097e27bfb6d6d3779ccd5d374cf5a07a04216e4e0880b","tests/common/mod.rs":"37cd4c48e140c793b852ae09fb3e812da28a4412977295015bcbffd632fcf294","tests/init_fails.rs":"9b78226a4e3220de5b64a205a97b8d5778d1700391b5b71c7819b6cdd120747e","tests/never_init.rs":"1f33b8ce7ca3514b57b48cc16d98408974c85cf8aa7d13257ffc2ad878ebb295","tests/no_time_to_init.rs":"494dcddce49f279c6508f484ee59cf8bb83e7324de07bdbc1142f2a066b7f6a1","tests/overflowing_preinit.rs":"396206d5078b7e6c148bbf2aecb0f963cfaa4d7eff3fc7bf6590125076ee6113","tests/persist_ping_lifetime.rs":"2297d4b208e14188e6dcca2d4806b805cfc7dd824d21bd143a7803b95e0709f4","tests/persist_ping_lifetime_nopanic.rs":"06f1f3ca3b8a6c8b7fc4d6fc48d0e1d2ccffd32139f080db0a95003e9edd507d","tests/schema.rs":"a96089f828928b6be1fad7815e3269f5693af1b773e570312b357a29af28122a","tests/simple.rs":"a1d72af899293390bb955ca379baafb89c29bb746630409f8c51f453d222dbad"},"package":"813fa9059f1a7d9da4fcf6cff6c77e6226fc26f58797d1659d16a8279c4655f2"}
|
|
@ -12,7 +12,7 @@
|
|||
[package]
|
||||
edition = "2018"
|
||||
name = "glean"
|
||||
version = "50.1.0"
|
||||
version = "50.1.2"
|
||||
authors = [
|
||||
"Jan-Erik Rediger <jrediger@mozilla.com>",
|
||||
"The Glean Team <glean-team@mozilla.com>",
|
||||
|
@ -41,7 +41,7 @@ features = ["serde"]
|
|||
version = "0.5"
|
||||
|
||||
[dependencies.glean-core]
|
||||
version = "50.1.0"
|
||||
version = "50.1.2"
|
||||
|
||||
[dependencies.inherent]
|
||||
version = "1"
|
||||
|
@ -73,7 +73,7 @@ features = ["v4"]
|
|||
version = "0.1.2"
|
||||
|
||||
[dev-dependencies.env_logger]
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
features = [
|
||||
"termcolor",
|
||||
"atty",
|
||||
|
|
|
@ -1 +1 @@
|
|||
{"files":{"Cargo.toml":"629736f65f72d44b4e972c6e21bc998f7cc0ab5880863d80ce462df9fe3c86e4","release.toml":"a6602545cd6eb46e44d89ce946d7954957ac00f1c955de54c736fa2cb560b1df","src/ffi/ffidefault.rs":"c7ab752fffed17c3fabb60e818ad1d093482f95dd0bdeae6871287695c583e48","src/ffi/foreignbytes.rs":"6dfd91c7c9371620d45a2e950ff7c16470a7f917e034a5f1c04672bcc45682d3","src/ffi/foreigncallbacks.rs":"e19a038128d25e7d945034935f0d296ea8603ad2f5a8da4bfe6d95c78a5f76b3","src/ffi/mod.rs":"3fb3b74607066e0052fc91168e9473dbf82dbae562f85c33774a7f5f6b350616","src/ffi/rustbuffer.rs":"93ca5e8608ef1cae0da76106aa2244e50e998c99b2530cb613ff735483cd914c","src/ffi/rustcalls.rs":"79192b82878fee2c09a74ec7cef1f8efdf5b7a84692a9f3a42b512bcf3400bed","src/lib.rs":"ef06d0f87da668edf8fda2381bf484a612d35d7507a0e3bf807390077b664b7d","src/panichook.rs":"de3c63909691efc014ff528c767aa346109dccedf8b529c339e6715784780ae5","src/testing.rs":"e474fc7486cd8101449284d15b71c5b3f70ac17fe8214ab0c495e94d761b6c19","tests/ui/version_mismatch.rs":"16ea359e5853517ee0d0704c015ae8c825533109fbefd715130d0f4a51f15898","tests/ui/version_mismatch.stderr":"aadbd8f3847f5663022d8dd75d6afa3b25dfc8abccd30b386a681f98587d4ceb"},"package":"d0fe14882ae6ea89f31ac922ad8e6f76b3f346f07965791a60ade60cc3bcdd60"}
|
||||
{"files":{"Cargo.toml":"2d5f07251fa9e9b2422003e9ac5d8d1d8ba4656b656ee3c493e8531266dc82ed","release.toml":"a6602545cd6eb46e44d89ce946d7954957ac00f1c955de54c736fa2cb560b1df","src/ffi/ffidefault.rs":"c7ab752fffed17c3fabb60e818ad1d093482f95dd0bdeae6871287695c583e48","src/ffi/foreignbytes.rs":"37061e2da7135576abccb86fe27b4fefc054586a040f2ca81fe9858d5649e887","src/ffi/foreigncallbacks.rs":"e19a038128d25e7d945034935f0d296ea8603ad2f5a8da4bfe6d95c78a5f76b3","src/ffi/mod.rs":"3fb3b74607066e0052fc91168e9473dbf82dbae562f85c33774a7f5f6b350616","src/ffi/rustbuffer.rs":"b773637d9e4651b80cd16f7a02ed75846d02ce0a9e32b718ce644cdba3a83cdd","src/ffi/rustcalls.rs":"79192b82878fee2c09a74ec7cef1f8efdf5b7a84692a9f3a42b512bcf3400bed","src/lib.rs":"a2dba349d0c0c2f31b314f145bf576a4d0c8855fe265f987542ddbbe638ca87f","src/panichook.rs":"de3c63909691efc014ff528c767aa346109dccedf8b529c339e6715784780ae5","src/testing.rs":"6dc9b93d8bd500a0abd552a1830b968718ac6c2f713af4c325ed46c3f0a7a6c4","tests/ui/version_mismatch.rs":"16ea359e5853517ee0d0704c015ae8c825533109fbefd715130d0f4a51f15898","tests/ui/version_mismatch.stderr":"aadbd8f3847f5663022d8dd75d6afa3b25dfc8abccd30b386a681f98587d4ceb"},"package":"bc1de33ad46ce00bc9a31cea44e80ef69175d3a23007335216fe3996880a310d"}
|
|
@ -10,9 +10,9 @@
|
|||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
name = "uniffi"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
authors = ["Firefox Sync Team <sync-team@mozilla.com>"]
|
||||
description = "a multi-language bindings generator for rust (runtime support code)"
|
||||
homepage = "https://mozilla.github.io/uniffi-rs"
|
||||
|
@ -23,6 +23,7 @@ keywords = [
|
|||
]
|
||||
license = "MPL-2.0"
|
||||
repository = "https://github.com/mozilla/uniffi-rs"
|
||||
resolver = "2"
|
||||
|
||||
[dependencies.anyhow]
|
||||
version = "1"
|
||||
|
@ -30,8 +31,11 @@ version = "1"
|
|||
[dependencies.bytes]
|
||||
version = "1.0"
|
||||
|
||||
[dependencies.camino]
|
||||
version = "1.0.8"
|
||||
|
||||
[dependencies.cargo_metadata]
|
||||
version = "0.13"
|
||||
version = "0.14"
|
||||
|
||||
[dependencies.lazy_static]
|
||||
version = "1.4"
|
||||
|
@ -46,7 +50,7 @@ version = "1.0"
|
|||
version = "1.1.0"
|
||||
|
||||
[dependencies.uniffi_bindgen]
|
||||
version = "=0.18.0"
|
||||
version = "=0.19.3"
|
||||
optional = true
|
||||
|
||||
[dev-dependencies.trybuild]
|
||||
|
|
|
@ -2,8 +2,6 @@
|
|||
* 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::convert::TryInto;
|
||||
|
||||
/// Support for reading a slice of foreign-language-allocated bytes over the FFI.
|
||||
///
|
||||
/// Foreign language code can pass a slice of bytes by providing a data pointer
|
||||
|
|
|
@ -3,7 +3,6 @@
|
|||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
use crate::ffi::{call_with_output, ForeignBytes, RustCallStatus};
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
|
||||
/// Support for passing an allocated-by-Rust buffer of bytes over the FFI.
|
||||
///
|
||||
|
|
|
@ -514,7 +514,7 @@ impl<T: FfiConverter> RustBufferFfiConverter for Vec<T> {
|
|||
// TODO: would be nice not to panic here :-/
|
||||
let len = i32::try_from(obj.len()).unwrap();
|
||||
buf.put_i32(len); // We limit arrays to i32::MAX items
|
||||
for item in obj.into_iter() {
|
||||
for item in obj {
|
||||
<T as FfiConverter>::write(item, buf);
|
||||
}
|
||||
}
|
||||
|
@ -548,7 +548,7 @@ where
|
|||
// TODO: would be nice not to panic here :-/
|
||||
let len = i32::try_from(obj.len()).unwrap();
|
||||
buf.put_i32(len); // We limit HashMaps to i32::MAX entries
|
||||
for (key, value) in obj.into_iter() {
|
||||
for (key, value) in obj {
|
||||
<K as FfiConverter>::write(key, buf);
|
||||
<V as FfiConverter>::write(value, buf);
|
||||
}
|
||||
|
|
|
@ -9,12 +9,12 @@
|
|||
//! and should instead use the `build_foreign_language_testcases!` macro provided by
|
||||
//! the `uniffi_macros` crate.
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use camino::{Utf8Path, Utf8PathBuf};
|
||||
use cargo_metadata::Message;
|
||||
use lazy_static::lazy_static;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::Path,
|
||||
process::{Command, Stdio},
|
||||
sync::Mutex,
|
||||
};
|
||||
|
@ -23,7 +23,7 @@ use std::{
|
|||
// They map uniffi component crate directories to data about build steps that have already
|
||||
// been executed by this process.
|
||||
lazy_static! {
|
||||
static ref COMPILED_COMPONENTS: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
|
||||
static ref COMPILED_COMPONENTS: Mutex<HashMap<Utf8PathBuf, Utf8PathBuf>> = Mutex::new(HashMap::new());
|
||||
// Since uniffi-bindgen does the actual generating/compiling of bindings and script files,
|
||||
// we ensure that only one call happens at once (making tests pretty much serialized sorry :/).
|
||||
static ref UNIFFI_BINDGEN: Mutex<i32> = Mutex::new(0);
|
||||
|
@ -41,11 +41,10 @@ pub fn run_foreign_language_testcase(
|
|||
test_file: &str,
|
||||
) -> Result<()> {
|
||||
let cdylib_file = ensure_compiled_cdylib(pkg_dir)?;
|
||||
let out_dir = Path::new(cdylib_file.as_str())
|
||||
let out_dir = cdylib_file
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("Generated cdylib has no parent directory"))?
|
||||
.to_str()
|
||||
.unwrap();
|
||||
.context("Generated cdylib has no parent directory")?
|
||||
.as_str();
|
||||
let _lock = UNIFFI_BINDGEN.lock();
|
||||
run_uniffi_bindgen_test(out_dir, udl_files, test_file)?;
|
||||
Ok(())
|
||||
|
@ -59,11 +58,13 @@ pub fn run_foreign_language_testcase(
|
|||
///
|
||||
/// Internally, this function does a bit of caching and concurrency management to avoid rebuilding
|
||||
/// the component for multiple testcases.
|
||||
pub fn ensure_compiled_cdylib(pkg_dir: &str) -> Result<String> {
|
||||
pub fn ensure_compiled_cdylib(pkg_dir: &str) -> Result<Utf8PathBuf> {
|
||||
let pkg_dir = Utf8Path::new(pkg_dir);
|
||||
|
||||
// Have we already compiled this component?
|
||||
let mut compiled_components = COMPILED_COMPONENTS.lock().unwrap();
|
||||
if let Some(cdylib_file) = compiled_components.get(pkg_dir) {
|
||||
return Ok(cdylib_file.to_string());
|
||||
return Ok(cdylib_file.to_owned());
|
||||
}
|
||||
// Nope, looks like we'll have to compile it afresh.
|
||||
let mut cmd = Command::new("cargo");
|
||||
|
@ -123,10 +124,10 @@ pub fn ensure_compiled_cdylib(pkg_dir: &str) -> Result<String> {
|
|||
if cdylib_files.len() != 1 {
|
||||
bail!("Failed to build exactly one cdylib file, it must not be a uniffi component");
|
||||
}
|
||||
let cdylib_file = cdylib_files[0].to_string();
|
||||
let cdylib_file = cdylib_files[0];
|
||||
// Cache the result for subsequent tests.
|
||||
compiled_components.insert(pkg_dir.to_string(), cdylib_file.clone());
|
||||
Ok(cdylib_file)
|
||||
compiled_components.insert(pkg_dir.to_owned(), cdylib_file.to_owned());
|
||||
Ok(cdylib_file.to_owned())
|
||||
}
|
||||
|
||||
/// Execute the `uniffi-bindgen test` command.
|
||||
|
@ -151,5 +152,5 @@ fn run_uniffi_bindgen_test(out_dir: &str, udl_files: &[&str], test_file: &str) -
|
|||
|
||||
#[cfg(feature = "builtin-bindgen")]
|
||||
fn run_uniffi_bindgen_test(out_dir: &str, udl_files: &[&str], test_file: &str) -> Result<()> {
|
||||
uniffi_bindgen::run_tests(out_dir, udl_files, vec![test_file], None)
|
||||
uniffi_bindgen::run_tests(out_dir, udl_files, &[test_file], None)
|
||||
}
|
||||
|
|
Различия файлов скрыты, потому что одна или несколько строк слишком длинны
|
@ -4,9 +4,9 @@ version = 3
|
|||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.57"
|
||||
version = "1.0.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc"
|
||||
checksum = "bb07d2053ccdbe10e2af2995a2f116c1330396493dc1269f6a91d0ae82e19704"
|
||||
|
||||
[[package]]
|
||||
name = "askama"
|
||||
|
@ -77,10 +77,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "camino"
|
||||
version = "1.0.7"
|
||||
name = "bitvec"
|
||||
version = "0.19.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f3132262930b0522068049f5870a856ab8affc80c70d08b6ecb785771a6fc23"
|
||||
checksum = "55f93d0ef3363c364d5976646a38f04cf67cfe1d4c8d160cdea02cab2c116b33"
|
||||
dependencies = [
|
||||
"funty",
|
||||
"radium",
|
||||
"tap",
|
||||
"wyz",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "camino"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "869119e97797867fd90f5e22af7d0bd274bd4635ebb9eb68c04f3f513ae6c412"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
@ -96,23 +108,22 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "cargo_metadata"
|
||||
version = "0.13.1"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "081e3f0755c1f380c2d010481b6fa2e02973586d5f2b24eebb7a2a1d98b143d8"
|
||||
checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa"
|
||||
dependencies = [
|
||||
"camino",
|
||||
"cargo-platform",
|
||||
"semver",
|
||||
"semver-parser",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "3.1.15"
|
||||
version = "3.1.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85a35a599b11c089a7f49105658d089b8f2cf0882993c17daf6de15285c2c35d"
|
||||
checksum = "d2dbdf4bdacb33466e854ce889eee8dfd5729abf7ccd7664d0a2d60cd384440b"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"bitflags",
|
||||
|
@ -127,9 +138,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "3.1.7"
|
||||
version = "3.1.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1"
|
||||
checksum = "25320346e922cffe59c0bbc5410c8d8784509efb321488971081313cb1e1a33c"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro-error",
|
||||
|
@ -140,18 +151,30 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "0.2.0"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213"
|
||||
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
|
||||
dependencies = [
|
||||
"os_str_bytes",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.11.2"
|
||||
name = "fs-err"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
|
||||
checksum = "5bd79fa345a495d3ae89fb7165fec01c0e72f41821d642dda363a1e97975652e"
|
||||
|
||||
[[package]]
|
||||
name = "funty"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fed34cd105917e91daa4da6b3728c47b068749d6a62c59811f06ed2ac71d9da7"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db0d4cf898abf0081f964436dc980e96670a0f36863e4b83aaacdb65c9d7ccc3"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
|
@ -170,9 +193,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.8.1"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee"
|
||||
checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"hashbrown",
|
||||
|
@ -180,9 +203,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
|
||||
checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d"
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
|
@ -192,15 +215,15 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
|
|||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.125"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"
|
||||
checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.5.0"
|
||||
version = "2.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
||||
checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525"
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
|
@ -226,10 +249,12 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
|||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "5.1.2"
|
||||
version = "6.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ffb4262d26ed83a1c0a33a38fe2bb15797329c85770da05e6b828ddb782627af"
|
||||
checksum = "9c5c51b9083a3c620fa67a2a635d1ce7d95b897e957d6b28ff9a5da960a103a6"
|
||||
dependencies = [
|
||||
"bitvec",
|
||||
"funty",
|
||||
"memchr",
|
||||
"version_check",
|
||||
]
|
||||
|
@ -246,9 +271,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "os_str_bytes"
|
||||
version = "6.0.0"
|
||||
version = "6.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"
|
||||
checksum = "21326818e99cfe6ce1e524c2a805c189a99b5ae555a35d19f9a284b427d86afa"
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
|
@ -256,15 +281,6 @@ version = "1.0.7"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c520e05135d6e763148b6426a837e239041653ba7becd2e538c076c738025fc"
|
||||
|
||||
[[package]]
|
||||
name = "pest"
|
||||
version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53"
|
||||
dependencies = [
|
||||
"ucd-trie",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error"
|
||||
version = "1.0.4"
|
||||
|
@ -291,61 +307,57 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.37"
|
||||
version = "1.0.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1"
|
||||
checksum = "dd96a1e8ed2596c337f8eae5f24924ec83f5ad5ab21ea8e455d3566c69fbcaf7"
|
||||
dependencies = [
|
||||
"unicode-xid",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.18"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1"
|
||||
checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.9"
|
||||
name = "radium"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
|
||||
checksum = "941ba9d78d8e2f7ce474c015eea4d9c6d25b6a3327f9832ee29a4de27f91bbb8"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "0.11.0"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6"
|
||||
checksum = "a2333e6df6d6598f2b1974829f853c2b4c5f4a6e503c10af918081aa6f8564e1"
|
||||
dependencies = [
|
||||
"semver-parser",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver-parser"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7"
|
||||
dependencies = [
|
||||
"pest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.137"
|
||||
version = "1.0.138"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1"
|
||||
checksum = "1578c6245786b9d168c5447eeacfb96856573ca56c9d68fdcf394be134882a47"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.137"
|
||||
version = "1.0.138"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be"
|
||||
checksum = "023e9b1467aef8a10fb88f25611870ada9800ef7e22afce356bb0d2387b6f27c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
@ -354,9 +366,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.81"
|
||||
version = "1.0.82"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c"
|
||||
checksum = "82c2c1fdcd807d1098552c5b9a36e425e42e9fbd7c6a37a8425f390f781f7fa7"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"ryu",
|
||||
|
@ -371,15 +383,21 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
|
|||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.92"
|
||||
version = "1.0.98"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52"
|
||||
checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-xid",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tap"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "termcolor"
|
||||
version = "1.1.3"
|
||||
|
@ -404,12 +422,6 @@ dependencies = [
|
|||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ucd-trie"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c"
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.6.0"
|
||||
|
@ -420,20 +432,23 @@ dependencies = [
|
|||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.3"
|
||||
name = "unicode-ident"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04"
|
||||
checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c"
|
||||
|
||||
[[package]]
|
||||
name = "uniffi_bindgen"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
"camino",
|
||||
"cargo_metadata",
|
||||
"clap",
|
||||
"fs-err",
|
||||
"heck",
|
||||
"lazy_static",
|
||||
"paste",
|
||||
"serde",
|
||||
"toml",
|
||||
|
@ -448,11 +463,12 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
|
|||
|
||||
[[package]]
|
||||
name = "weedle2"
|
||||
version = "2.0.0"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8655cb807b9f5c665d199c735dae90e10230eae6ae5cf009d3506963214fe451"
|
||||
checksum = "5d730d941cf471131c40a64cf2e8a595822009f51e64c05c5afdbc85af155857"
|
||||
dependencies = [
|
||||
"nom 5.1.2",
|
||||
"fs-err",
|
||||
"nom 6.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -485,3 +501,9 @@ 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 = "wyz"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85e60b0d1b5f99db2556934e21937020776a5d31520bf169e851ac44e6420214"
|
||||
|
|
|
@ -10,9 +10,9 @@
|
|||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
name = "uniffi_bindgen"
|
||||
version = "0.18.0"
|
||||
version = "0.19.3"
|
||||
authors = ["Firefox Sync Team <sync-team@mozilla.com>"]
|
||||
description = "a multi-language bindings generator for rust (codegen and cli tooling)"
|
||||
homepage = "https://mozilla.github.io/uniffi-rs"
|
||||
|
@ -23,6 +23,7 @@ keywords = [
|
|||
]
|
||||
license = "MPL-2.0"
|
||||
repository = "https://github.com/mozilla/uniffi-rs"
|
||||
resolver = "2"
|
||||
|
||||
[[bin]]
|
||||
name = "uniffi-bindgen"
|
||||
|
@ -36,20 +37,29 @@ version = "0.11"
|
|||
features = ["config"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.camino]
|
||||
version = "1.0.8"
|
||||
|
||||
[dependencies.cargo_metadata]
|
||||
version = "0.13"
|
||||
version = "0.14"
|
||||
|
||||
[dependencies.clap]
|
||||
version = "3"
|
||||
version = "~3.1"
|
||||
features = [
|
||||
"cargo",
|
||||
"std",
|
||||
"derive",
|
||||
]
|
||||
|
||||
[dependencies.fs-err]
|
||||
version = "2.7.0"
|
||||
|
||||
[dependencies.heck]
|
||||
version = "0.4"
|
||||
|
||||
[dependencies.lazy_static]
|
||||
version = "1.4"
|
||||
|
||||
[dependencies.paste]
|
||||
version = "1.0"
|
||||
|
||||
|
@ -60,4 +70,4 @@ version = "1"
|
|||
version = "0.5"
|
||||
|
||||
[dependencies.weedle2]
|
||||
version = "2.0.0"
|
||||
version = "3.0.0"
|
||||
|
|
|
@ -6,7 +6,7 @@ use std::borrow::Borrow;
|
|||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use askama::Template;
|
||||
use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToUpperCamelCase};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
@ -89,7 +89,7 @@ impl MergeWith for Config {
|
|||
pub fn generate_bindings(config: &Config, ci: &ComponentInterface) -> Result<String> {
|
||||
KotlinWrapper::new(config.clone(), ci)
|
||||
.render()
|
||||
.map_err(|_| anyhow::anyhow!("failed to render kotlin bindings"))
|
||||
.context("failed to render kotlin bindings")
|
||||
}
|
||||
|
||||
/// Renders Kotlin helper code for all types
|
||||
|
@ -174,7 +174,6 @@ impl<'a> KotlinWrapper<'a> {
|
|||
pub fn initialization_fns(&self) -> Vec<String> {
|
||||
self.ci
|
||||
.iter_types()
|
||||
.into_iter()
|
||||
.filter_map(|t| t.initialization_fn(&KotlinCodeOracle))
|
||||
.collect()
|
||||
}
|
||||
|
@ -241,12 +240,12 @@ impl CodeOracle for KotlinCodeOracle {
|
|||
|
||||
/// Get the idiomatic Kotlin rendering of a function name.
|
||||
fn fn_name(&self, nm: &str) -> String {
|
||||
nm.to_string().to_lower_camel_case()
|
||||
format!("`{}`", nm.to_string().to_lower_camel_case())
|
||||
}
|
||||
|
||||
/// Get the idiomatic Kotlin rendering of a variable name.
|
||||
fn var_name(&self, nm: &str) -> String {
|
||||
nm.to_string().to_lower_camel_case()
|
||||
format!("`{}`", nm.to_string().to_lower_camel_case())
|
||||
}
|
||||
|
||||
/// Get the idiomatic Kotlin rendering of an individual enum variant.
|
||||
|
@ -260,14 +259,11 @@ impl CodeOracle for KotlinCodeOracle {
|
|||
/// "Error" for any type of error but in the Java world, "Error" means a non-recoverable error
|
||||
/// and is distinguished from an "Exception".
|
||||
fn error_name(&self, nm: &str) -> String {
|
||||
let name = nm.to_string();
|
||||
// errors are a class in kotlin.
|
||||
let name = self.class_name(nm);
|
||||
match name.strip_suffix("Error") {
|
||||
None => name,
|
||||
Some(stripped) => {
|
||||
let mut kt_exc_name = stripped.to_owned();
|
||||
kt_exc_name.push_str("Exception");
|
||||
kt_exc_name
|
||||
}
|
||||
Some(stripped) => format!("{}Exception", stripped),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -282,7 +278,7 @@ impl CodeOracle for KotlinCodeOracle {
|
|||
FFIType::Int64 | FFIType::UInt64 => "Long".to_string(),
|
||||
FFIType::Float32 => "Float".to_string(),
|
||||
FFIType::Float64 => "Double".to_string(),
|
||||
FFIType::RustArcPtr => "Pointer".to_string(),
|
||||
FFIType::RustArcPtr(_) => "Pointer".to_string(),
|
||||
FFIType::RustBuffer => "RustBuffer.ByValue".to_string(),
|
||||
FFIType::ForeignBytes => "ForeignBytes.ByValue".to_string(),
|
||||
FFIType::ForeignCallback => "ForeignCallback".to_string(),
|
||||
|
@ -364,11 +360,8 @@ pub mod filters {
|
|||
Ok(oracle().enum_variant_name(nm))
|
||||
}
|
||||
|
||||
/// Get the idiomatic Kotlin rendering of an exception name
|
||||
///
|
||||
/// This replaces "Error" at the end of the name with "Exception". Rust code typically uses
|
||||
/// "Error" for any type of error but in the Java world, "Error" means a non-recoverable error
|
||||
/// and is distinguished from an "Exception".
|
||||
/// Get the idiomatic Kotlin rendering of an exception name, replacing
|
||||
/// `Error` with `Exception`.
|
||||
pub fn exception_name(nm: &str) -> Result<String, askama::Error> {
|
||||
Ok(oracle().error_name(nm))
|
||||
}
|
||||
|
|
|
@ -3,14 +3,9 @@
|
|||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::{
|
||||
env,
|
||||
ffi::OsString,
|
||||
fs::File,
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
use camino::{Utf8Path, Utf8PathBuf};
|
||||
use fs_err::{self as fs, File};
|
||||
use std::{env, ffi::OsString, io::Write, process::Command};
|
||||
|
||||
pub mod gen_kotlin;
|
||||
pub use gen_kotlin::{generate_bindings, Config};
|
||||
|
@ -20,23 +15,19 @@ use super::super::interface::ComponentInterface;
|
|||
pub fn write_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: &Path,
|
||||
out_dir: &Utf8Path,
|
||||
try_format_code: bool,
|
||||
) -> Result<()> {
|
||||
let mut kt_file = full_bindings_path(config, out_dir)?;
|
||||
std::fs::create_dir_all(&kt_file)?;
|
||||
let mut kt_file = full_bindings_path(config, out_dir);
|
||||
fs::create_dir_all(&kt_file)?;
|
||||
kt_file.push(format!("{}.kt", ci.namespace()));
|
||||
let mut f = File::create(&kt_file).context("Failed to create .kt file for bindings")?;
|
||||
let mut f = File::create(&kt_file)?;
|
||||
write!(f, "{}", generate_bindings(config, ci)?)?;
|
||||
if try_format_code {
|
||||
if let Err(e) = Command::new("ktlint")
|
||||
.arg("-F")
|
||||
.arg(kt_file.to_str().unwrap())
|
||||
.output()
|
||||
{
|
||||
if let Err(e) = Command::new("ktlint").arg("-F").arg(&kt_file).output() {
|
||||
println!(
|
||||
"Warning: Unable to auto-format {} using ktlint: {:?}",
|
||||
kt_file.file_name().unwrap().to_str().unwrap(),
|
||||
kt_file.file_name().unwrap(),
|
||||
e
|
||||
)
|
||||
}
|
||||
|
@ -44,18 +35,21 @@ pub fn write_bindings(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn full_bindings_path(config: &Config, out_dir: &Path) -> Result<PathBuf> {
|
||||
let package_path: PathBuf = config.package_name().split('.').collect();
|
||||
Ok(PathBuf::from(out_dir).join(package_path))
|
||||
fn full_bindings_path(config: &Config, out_dir: &Utf8Path) -> Utf8PathBuf {
|
||||
let package_path: Utf8PathBuf = config.package_name().split('.').collect();
|
||||
Utf8PathBuf::from(out_dir).join(package_path)
|
||||
}
|
||||
|
||||
/// Generate kotlin bindings for the given namespace, then use the kotlin
|
||||
/// command-line tools to compile them into a .jar file.
|
||||
pub fn compile_bindings(config: &Config, ci: &ComponentInterface, out_dir: &Path) -> Result<()> {
|
||||
let mut kt_file = full_bindings_path(config, out_dir)?;
|
||||
pub fn compile_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: &Utf8Path,
|
||||
) -> Result<()> {
|
||||
let mut kt_file = full_bindings_path(config, out_dir);
|
||||
kt_file.push(format!("{}.kt", ci.namespace()));
|
||||
let mut jar_file = PathBuf::from(out_dir);
|
||||
jar_file.push(format!("{}.jar", ci.namespace()));
|
||||
let jar_file = out_dir.join(format!("{}.jar", ci.namespace()));
|
||||
let status = Command::new("kotlinc")
|
||||
// Our generated bindings should not produce any warnings; fail tests if they do.
|
||||
.arg("-Werror")
|
||||
|
@ -76,7 +70,7 @@ pub fn compile_bindings(config: &Config, ci: &ComponentInterface, out_dir: &Path
|
|||
|
||||
/// Execute the specifed kotlin script, with classpath based on the generated
|
||||
// artifacts in the given output directory.
|
||||
pub fn run_script(out_dir: &Path, script_file: &Path) -> Result<()> {
|
||||
pub fn run_script(out_dir: &Utf8Path, script_file: &Utf8Path) -> Result<()> {
|
||||
let mut cmd = Command::new("kotlinc");
|
||||
// Make sure it can load the .jar and its dependencies.
|
||||
cmd.arg("-classpath").arg(classpath_for_testing(out_dir)?);
|
||||
|
@ -97,8 +91,8 @@ pub fn run_script(out_dir: &Path, script_file: &Path) -> Result<()> {
|
|||
}
|
||||
|
||||
// Calculate the classpath string to use for testing
|
||||
pub fn classpath_for_testing(out_dir: &Path) -> Result<OsString> {
|
||||
let mut classpath = env::var_os("CLASSPATH").unwrap_or_else(|| OsString::from(""));
|
||||
pub fn classpath_for_testing(out_dir: &Utf8Path) -> Result<OsString> {
|
||||
let mut classpath = env::var_os("CLASSPATH").unwrap_or_default();
|
||||
// This lets java find the compiled library for the rust component.
|
||||
classpath.push(":");
|
||||
classpath.push(out_dir);
|
||||
|
@ -107,7 +101,7 @@ pub fn classpath_for_testing(out_dir: &Path) -> Result<OsString> {
|
|||
// Including all .jar files is needed for tests like ext-types that use multiple UDL files.
|
||||
// TODO: Instead of including all .jar files, we should only include jar files that we
|
||||
// previously built for this test.
|
||||
for entry in PathBuf::from(out_dir)
|
||||
for entry in out_dir
|
||||
.read_dir()
|
||||
.context("Failed to list target directory when running Kotlin script")?
|
||||
{
|
||||
|
|
|
@ -10,7 +10,7 @@ fun {{ func.name()|fn_name }}({%- call kt::arg_list_decl(func) -%}): {{ return_t
|
|||
return {{ return_type|lift_fn }}({% call kt::to_ffi_call(func) %})
|
||||
}
|
||||
|
||||
{% when None -%}
|
||||
{% when None %}
|
||||
|
||||
fun {{ func.name()|fn_name }}({% call kt::arg_list_decl(func) %}) =
|
||||
{% call kt::to_ffi_call(func) %}
|
||||
|
|
|
@ -7,7 +7,7 @@
|
|||
{%- let contains_object_references = ci.item_contains_object_references(type_) %}
|
||||
|
||||
{#
|
||||
# Map `Type` instances to a `Box<dyn CodeType>` for that type.
|
||||
# Map `Type` instances to an include statement for that type.
|
||||
#
|
||||
# There is a companion match in `KotlinCodeOracle::create_code_type()` which performs a similar function for the
|
||||
# Rust code.
|
||||
|
|
|
@ -62,7 +62,7 @@
|
|||
-#}
|
||||
{%- macro arg_list_ffi_decl(func) %}
|
||||
{%- for arg in func.arguments() %}
|
||||
{{- arg.name() }}: {{ arg.type_().borrow()|ffi_type_name -}},
|
||||
{{- arg.name()|var_name }}: {{ arg.type_().borrow()|ffi_type_name -}},
|
||||
{%- endfor %}
|
||||
_uniffi_out_err: RustCallStatus
|
||||
{%- endmacro -%}
|
||||
|
@ -76,7 +76,7 @@
|
|||
{%- endmacro -%}
|
||||
|
||||
{%- macro ffi_function_definition(func) %}
|
||||
fun {{ func.name() }}(
|
||||
fun {{ func.name()|fn_name }}(
|
||||
{%- call arg_list_ffi_decl(func) %}
|
||||
){%- match func.return_type() -%}{%- when Some with (type_) %}: {{ type_|ffi_type_name }}{% when None %}: Unit{% endmatch %}
|
||||
{% endmacro %}
|
||||
|
|
|
@ -40,7 +40,7 @@ import {{ imported_class }}
|
|||
// Public interface members begin here.
|
||||
{{ type_helper_code }}
|
||||
|
||||
{%- for func in ci.iter_function_definitions() %}
|
||||
{%- for func in ci.function_definitions() %}
|
||||
{%- include "TopLevelFunctionTemplate.kt" %}
|
||||
{%- endfor %}
|
||||
|
||||
|
|
|
@ -8,9 +8,8 @@
|
|||
//! along with some helpers for executing foreign language scripts or tests.
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use camino::Utf8Path;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use std::path::Path;
|
||||
|
||||
use crate::interface::ComponentInterface;
|
||||
use crate::MergeWith;
|
||||
|
@ -99,17 +98,13 @@ impl MergeWith for Config {
|
|||
}
|
||||
|
||||
/// Generate foreign language bindings from a compiled `uniffi` library.
|
||||
pub fn write_bindings<P>(
|
||||
pub fn write_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: P,
|
||||
out_dir: &Utf8Path,
|
||||
language: TargetLanguage,
|
||||
try_format_code: bool,
|
||||
) -> Result<()>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
let out_dir = out_dir.as_ref();
|
||||
) -> Result<()> {
|
||||
match language {
|
||||
TargetLanguage::Kotlin => {
|
||||
kotlin::write_bindings(&config.kotlin, ci, out_dir, try_format_code)?
|
||||
|
@ -129,16 +124,12 @@ where
|
|||
///
|
||||
/// Note: This function is only used for compiling the unit tests. See #1169 for plans to refactor
|
||||
/// it.
|
||||
pub fn compile_bindings<P>(
|
||||
pub fn compile_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: P,
|
||||
out_dir: &Utf8Path,
|
||||
language: TargetLanguage,
|
||||
) -> Result<()>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
let out_dir = out_dir.as_ref();
|
||||
) -> Result<()> {
|
||||
match language {
|
||||
TargetLanguage::Kotlin => kotlin::compile_bindings(&config.kotlin, ci, out_dir)?,
|
||||
TargetLanguage::Swift => swift::compile_bindings(&config.swift, ci, out_dir)?,
|
||||
|
@ -152,13 +143,11 @@ where
|
|||
///
|
||||
/// Note: This function is only used for compiling the unit tests. See #1169 for plans to refactor
|
||||
/// it.
|
||||
pub fn run_script<P1, P2>(out_dir: P1, script_file: P2, language: TargetLanguage) -> Result<()>
|
||||
where
|
||||
P1: AsRef<Path>,
|
||||
P2: AsRef<Path>,
|
||||
{
|
||||
let out_dir = out_dir.as_ref();
|
||||
let script_file = script_file.as_ref();
|
||||
pub fn run_script(
|
||||
out_dir: &Utf8Path,
|
||||
script_file: &Utf8Path,
|
||||
language: TargetLanguage,
|
||||
) -> Result<()> {
|
||||
match language {
|
||||
TargetLanguage::Kotlin => kotlin::run_script(out_dir, script_file)?,
|
||||
TargetLanguage::Swift => swift::run_script(out_dir, script_file)?,
|
||||
|
|
|
@ -2,12 +2,8 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{CallbackInterface, ComponentInterface};
|
||||
use askama::Template;
|
||||
use std::borrow::Borrow;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
|
||||
use super::filters;
|
||||
pub struct CallbackInterfaceCodeType {
|
||||
id: String,
|
||||
}
|
||||
|
@ -35,49 +31,3 @@ impl CodeType for CallbackInterfaceCodeType {
|
|||
nm.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "CallbackInterfaceTemplate.py")]
|
||||
pub struct PythonCallbackInterface {
|
||||
inner: CallbackInterface,
|
||||
}
|
||||
|
||||
impl PythonCallbackInterface {
|
||||
pub fn new(inner: CallbackInterface, _ci: &ComponentInterface) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &CallbackInterface {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonCallbackInterface {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "CallbackInterfaceRuntime.py")]
|
||||
pub struct PythonCallbackInterfaceRuntime {
|
||||
is_needed: bool,
|
||||
}
|
||||
|
||||
impl PythonCallbackInterfaceRuntime {
|
||||
pub fn new(ci: &ComponentInterface) -> Self {
|
||||
Self {
|
||||
is_needed: !ci.iter_callback_interface_definitions().is_empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonCallbackInterfaceRuntime {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
if !self.is_needed {
|
||||
None
|
||||
} else {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,155 +2,120 @@
|
|||
* 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 super::filters;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal, TypeIdentifier};
|
||||
use askama::Template;
|
||||
use paste::paste;
|
||||
|
||||
fn render_literal(oracle: &dyn CodeOracle, literal: &Literal, inner: &TypeIdentifier) -> String {
|
||||
match literal {
|
||||
Literal::Null => "None".into(),
|
||||
Literal::EmptySequence => "[]".into(),
|
||||
Literal::EmptyMap => "{}".into(),
|
||||
pub struct OptionalCodeType {
|
||||
inner: TypeIdentifier,
|
||||
}
|
||||
|
||||
// For optionals
|
||||
_ => oracle.find(inner).literal(oracle, literal),
|
||||
impl OptionalCodeType {
|
||||
pub fn new(inner: TypeIdentifier) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_code_type_for_compound {
|
||||
($T:ty, $canonical_name_pattern: literal, $template_file:literal, $coerce_code:expr) => {
|
||||
paste! {
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = $template_file)]
|
||||
pub struct $T {
|
||||
inner: TypeIdentifier,
|
||||
outer: TypeIdentifier,
|
||||
}
|
||||
impl CodeType for OptionalCodeType {
|
||||
fn type_label(&self, oracle: &dyn CodeOracle) -> String {
|
||||
oracle.find(&self.inner).type_label(oracle)
|
||||
}
|
||||
|
||||
impl $T {
|
||||
pub fn new(inner: TypeIdentifier, outer: TypeIdentifier) -> Self {
|
||||
Self { inner, outer }
|
||||
}
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!(
|
||||
"Optional{}",
|
||||
oracle.find(&self.inner).canonical_name(oracle),
|
||||
)
|
||||
}
|
||||
|
||||
fn inner(&self) -> &TypeIdentifier {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
fn outer(&self) -> &TypeIdentifier {
|
||||
&self.outer
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeType for $T {
|
||||
fn type_label(&self, oracle: &dyn CodeOracle) -> String {
|
||||
oracle.find(self.inner()).type_label(oracle)
|
||||
}
|
||||
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!($canonical_name_pattern, oracle.find(self.inner()).canonical_name(oracle))
|
||||
}
|
||||
|
||||
fn literal(&self, oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
render_literal(oracle, &literal, self.inner())
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn coerce(&self, oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
$coerce_code(self, oracle, nm)
|
||||
}
|
||||
}
|
||||
fn literal(&self, oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
match literal {
|
||||
Literal::Null => "None".into(),
|
||||
_ => oracle.find(&self.inner).literal(oracle, literal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_code_type_for_compound!(
|
||||
OptionalCodeType,
|
||||
"Optional{}",
|
||||
"OptionalTemplate.py",
|
||||
optional_coerce
|
||||
);
|
||||
fn optional_coerce(this: &OptionalCodeType, oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
format!(
|
||||
"(None if {} is None else {})",
|
||||
nm,
|
||||
oracle.find(this.inner()).coerce(oracle, nm)
|
||||
)
|
||||
fn coerce(&self, oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
format!(
|
||||
"(None if {} is None else {})",
|
||||
nm,
|
||||
oracle.find(&self.inner).coerce(oracle, nm)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl_code_type_for_compound!(
|
||||
SequenceCodeType,
|
||||
"Sequence{}",
|
||||
"SequenceTemplate.py",
|
||||
sequence_coerce
|
||||
);
|
||||
fn sequence_coerce(this: &SequenceCodeType, oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
format!(
|
||||
"list({} for x in {})",
|
||||
oracle.find(this.inner()).coerce(oracle, "x"),
|
||||
nm
|
||||
)
|
||||
pub struct SequenceCodeType {
|
||||
inner: TypeIdentifier,
|
||||
}
|
||||
|
||||
impl SequenceCodeType {
|
||||
pub fn new(inner: TypeIdentifier) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeType for SequenceCodeType {
|
||||
fn type_label(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
"list".to_string()
|
||||
}
|
||||
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!(
|
||||
"Sequence{}",
|
||||
oracle.find(&self.inner).canonical_name(oracle),
|
||||
)
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
match literal {
|
||||
Literal::EmptySequence => "[]".into(),
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn coerce(&self, oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
format!(
|
||||
"list({} for x in {})",
|
||||
oracle.find(&self.inner).coerce(oracle, "x"),
|
||||
nm
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "MapTemplate.py")]
|
||||
pub struct MapCodeType {
|
||||
key: TypeIdentifier,
|
||||
value: TypeIdentifier,
|
||||
outer: TypeIdentifier,
|
||||
}
|
||||
|
||||
impl MapCodeType {
|
||||
pub fn new(key: TypeIdentifier, value: TypeIdentifier, outer: TypeIdentifier) -> Self {
|
||||
Self { key, value, outer }
|
||||
}
|
||||
|
||||
fn key(&self) -> &TypeIdentifier {
|
||||
&self.key
|
||||
}
|
||||
|
||||
fn value(&self) -> &TypeIdentifier {
|
||||
&self.value
|
||||
}
|
||||
|
||||
fn outer(&self) -> &TypeIdentifier {
|
||||
&self.outer
|
||||
pub fn new(key: TypeIdentifier, value: TypeIdentifier) -> Self {
|
||||
Self { key, value }
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeType for MapCodeType {
|
||||
fn type_label(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!(
|
||||
"Map<{}, {}>",
|
||||
self.key().type_label(oracle),
|
||||
self.value().type_label(oracle),
|
||||
)
|
||||
fn type_label(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
"dict".to_string()
|
||||
}
|
||||
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!(
|
||||
"Map{}{}",
|
||||
self.key().type_label(oracle),
|
||||
self.value().type_label(oracle),
|
||||
oracle.find(&self.key).canonical_name(oracle),
|
||||
oracle.find(&self.value).canonical_name(oracle),
|
||||
)
|
||||
}
|
||||
|
||||
fn literal(&self, oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
render_literal(oracle, literal, self.value())
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
match literal {
|
||||
Literal::EmptyMap => "{}".into(),
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn coerce(&self, oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
format!(
|
||||
"dict(({}, {}) for (k, v) in {}.items())",
|
||||
self.key().coerce(oracle, "k"),
|
||||
self.value().coerce(oracle, "v"),
|
||||
self.key.coerce(oracle, "k"),
|
||||
self.value.coerce(oracle, "v"),
|
||||
nm
|
||||
)
|
||||
}
|
||||
|
|
|
@ -2,9 +2,7 @@
|
|||
* 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 super::{filters, CustomTypeConfig};
|
||||
use crate::backend::{CodeDeclaration, CodeOracle, CodeType, TypeIdentifier};
|
||||
use askama::Template;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
|
||||
pub struct CustomCodeType {
|
||||
name: String,
|
||||
|
@ -28,42 +26,4 @@ impl CodeType for CustomCodeType {
|
|||
fn coerce(&self, _oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
nm.to_string()
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"# Helper code for {} is found in CustomType.py",
|
||||
self.name,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "CustomType.py")]
|
||||
pub struct PythonCustomType {
|
||||
name: String,
|
||||
builtin: TypeIdentifier,
|
||||
config: Option<CustomTypeConfig>,
|
||||
}
|
||||
|
||||
impl PythonCustomType {
|
||||
pub fn new(name: String, builtin: TypeIdentifier, config: Option<CustomTypeConfig>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
builtin,
|
||||
config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonCustomType {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn imports(&self, _oracle: &dyn CodeOracle) -> Option<Vec<String>> {
|
||||
match &self.config {
|
||||
None => None,
|
||||
Some(custom_type_config) => custom_type_config.imports.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,11 +2,8 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Enum};
|
||||
use askama::Template;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
|
||||
use super::filters;
|
||||
pub struct EnumCodeType {
|
||||
id: String,
|
||||
}
|
||||
|
@ -38,36 +35,7 @@ impl CodeType for EnumCodeType {
|
|||
}
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"# Helper code for {} enum is found in EnumTemplate.py",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
|
||||
fn coerce(&self, _oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
nm.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "EnumTemplate.py")]
|
||||
pub struct PythonEnum {
|
||||
inner: Enum,
|
||||
}
|
||||
|
||||
impl PythonEnum {
|
||||
pub fn new(inner: Enum, _ci: &ComponentInterface) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &Enum {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonEnum {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,12 +2,8 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Error, Type};
|
||||
use askama::Template;
|
||||
use std::borrow::Borrow;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
|
||||
use super::filters;
|
||||
pub struct ErrorCodeType {
|
||||
id: String,
|
||||
}
|
||||
|
@ -31,36 +27,7 @@ impl CodeType for ErrorCodeType {
|
|||
unreachable!();
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"# Helper code for {} error is found in ErrorTemplate.py",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
|
||||
fn coerce(&self, _oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
nm.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "ErrorTemplate.py")]
|
||||
pub struct PythonError {
|
||||
inner: Error,
|
||||
}
|
||||
|
||||
impl PythonError {
|
||||
pub fn new(inner: Error, _ci: &ComponentInterface) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &Error {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonError {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,20 +2,15 @@
|
|||
* 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 super::filters;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
use askama::Template;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "ExternalTemplate.py")]
|
||||
pub struct ExternalCodeType {
|
||||
name: String,
|
||||
crate_name: String,
|
||||
}
|
||||
|
||||
impl ExternalCodeType {
|
||||
pub fn new(name: String, crate_name: String) -> Self {
|
||||
Self { name, crate_name }
|
||||
pub fn new(name: String) -> Self {
|
||||
Self { name }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -28,10 +23,6 @@ impl CodeType for ExternalCodeType {
|
|||
format!("Type{}", self.name)
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn coerce(&self, _oracle: &dyn CodeOracle, _nm: &str) -> String {
|
||||
panic!("should not be necessary to coerce External types");
|
||||
}
|
||||
|
|
|
@ -1,31 +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::backend::{CodeDeclaration, CodeOracle};
|
||||
use crate::interface::{ComponentInterface, Function};
|
||||
use askama::Template;
|
||||
use std::borrow::Borrow;
|
||||
|
||||
use super::filters;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "TopLevelFunctionTemplate.py")]
|
||||
pub struct PythonFunction {
|
||||
inner: Function,
|
||||
}
|
||||
|
||||
impl PythonFunction {
|
||||
pub fn new(inner: Function, _ci: &ComponentInterface) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
pub fn inner(&self) -> &Function {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonFunction {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
|
@ -2,17 +2,12 @@
|
|||
* 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(unused_imports)]
|
||||
use super::filters;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
use askama::Template;
|
||||
use paste::paste;
|
||||
|
||||
macro_rules! impl_code_type_for_miscellany {
|
||||
($T:ty, $canonical_name:literal, $template_file:literal) => {
|
||||
($T:ty, $canonical_name:literal) => {
|
||||
paste! {
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = $template_file)]
|
||||
pub struct $T;
|
||||
|
||||
impl CodeType for $T {
|
||||
|
@ -28,10 +23,6 @@ macro_rules! impl_code_type_for_miscellany {
|
|||
unreachable!()
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn coerce(&self, _oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
nm.to_string()
|
||||
}
|
||||
|
@ -40,6 +31,6 @@ macro_rules! impl_code_type_for_miscellany {
|
|||
};
|
||||
}
|
||||
|
||||
impl_code_type_for_miscellany!(TimestampCodeType, "Timestamp", "TimestampHelper.py");
|
||||
impl_code_type_for_miscellany!(TimestampCodeType, "Timestamp");
|
||||
|
||||
impl_code_type_for_miscellany!(DurationCodeType, "Duration", "DurationHelper.py");
|
||||
impl_code_type_for_miscellany!(DurationCodeType, "Duration");
|
||||
|
|
|
@ -2,14 +2,15 @@
|
|||
* 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 anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use askama::Template;
|
||||
use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
use crate::backend::{CodeDeclaration, CodeOracle, CodeType, TemplateExpression, TypeIdentifier};
|
||||
use crate::backend::{CodeOracle, CodeType, TemplateExpression, TypeIdentifier};
|
||||
use crate::interface::*;
|
||||
use crate::MergeWith;
|
||||
|
||||
|
@ -19,12 +20,56 @@ mod custom;
|
|||
mod enum_;
|
||||
mod error;
|
||||
mod external;
|
||||
mod function;
|
||||
mod miscellany;
|
||||
mod object;
|
||||
mod primitives;
|
||||
mod record;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
// Taken from Python's `keyword.py` module.
|
||||
static ref KEYWORDS: HashSet<String> = {
|
||||
let kwlist = vec![
|
||||
"False",
|
||||
"None",
|
||||
"True",
|
||||
"__peg_parser__",
|
||||
"and",
|
||||
"as",
|
||||
"assert",
|
||||
"async",
|
||||
"await",
|
||||
"break",
|
||||
"class",
|
||||
"continue",
|
||||
"def",
|
||||
"del",
|
||||
"elif",
|
||||
"else",
|
||||
"except",
|
||||
"finally",
|
||||
"for",
|
||||
"from",
|
||||
"global",
|
||||
"if",
|
||||
"import",
|
||||
"in",
|
||||
"is",
|
||||
"lambda",
|
||||
"nonlocal",
|
||||
"not",
|
||||
"or",
|
||||
"pass",
|
||||
"raise",
|
||||
"return",
|
||||
"try",
|
||||
"while",
|
||||
"with",
|
||||
"yield",
|
||||
];
|
||||
HashSet::from_iter(kwlist.into_iter().map(|s| s.to_string()))
|
||||
};
|
||||
}
|
||||
|
||||
// Config options to customize the generated python.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
|
@ -72,9 +117,58 @@ impl MergeWith for Config {
|
|||
|
||||
// Generate python bindings for the given ComponentInterface, as a string.
|
||||
pub fn generate_python_bindings(config: &Config, ci: &ComponentInterface) -> Result<String> {
|
||||
PythonWrapper::new(PythonCodeOracle, config.clone(), ci)
|
||||
PythonWrapper::new(config.clone(), ci)
|
||||
.render()
|
||||
.map_err(|_| anyhow::anyhow!("failed to render python bindings"))
|
||||
.context("failed to render python bindings")
|
||||
}
|
||||
|
||||
/// Renders Python helper code for all types
|
||||
///
|
||||
/// This template is a bit different than others in that it stores internal state from the render
|
||||
/// process. Make sure to only call `render()` once.
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "Types.py")]
|
||||
pub struct TypeRenderer<'a> {
|
||||
python_config: &'a Config,
|
||||
ci: &'a ComponentInterface,
|
||||
// Track included modules for the `include_once()` macro
|
||||
include_once_names: RefCell<HashSet<String>>,
|
||||
// Track imports added with the `add_import()` macro
|
||||
imports: RefCell<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
impl<'a> TypeRenderer<'a> {
|
||||
fn new(python_config: &'a Config, ci: &'a ComponentInterface) -> Self {
|
||||
Self {
|
||||
python_config,
|
||||
ci,
|
||||
include_once_names: RefCell::new(HashSet::new()),
|
||||
imports: RefCell::new(BTreeSet::new()),
|
||||
}
|
||||
}
|
||||
|
||||
// The following methods are used by the `Types.py` macros.
|
||||
|
||||
// Helper for the including a template, but only once.
|
||||
//
|
||||
// The first time this is called with a name it will return true, indicating that we should
|
||||
// include the template. Subsequent calls will return false.
|
||||
fn include_once_check(&self, name: &str) -> bool {
|
||||
self.include_once_names
|
||||
.borrow_mut()
|
||||
.insert(name.to_string())
|
||||
}
|
||||
|
||||
// Helper to add an import statement
|
||||
//
|
||||
// Call this inside your template to cause an import statement to be added at the top of the
|
||||
// file. Imports will be sorted and de-deuped.
|
||||
//
|
||||
// Returns an empty string so that it can be used inside an askama `{{ }}` block.
|
||||
fn add_import(&self, name: &str) -> &str {
|
||||
self.imports.borrow_mut().insert(name.to_owned());
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
|
@ -82,96 +176,32 @@ pub fn generate_python_bindings(config: &Config, ci: &ComponentInterface) -> Res
|
|||
pub struct PythonWrapper<'a> {
|
||||
ci: &'a ComponentInterface,
|
||||
config: Config,
|
||||
oracle: PythonCodeOracle,
|
||||
type_helper_code: String,
|
||||
type_imports: BTreeSet<String>,
|
||||
}
|
||||
impl<'a> PythonWrapper<'a> {
|
||||
pub fn new(oracle: PythonCodeOracle, config: Config, ci: &'a ComponentInterface) -> Self {
|
||||
Self { oracle, config, ci }
|
||||
}
|
||||
|
||||
pub fn members(&self) -> Vec<Box<dyn CodeDeclaration + 'a>> {
|
||||
let ci = self.ci;
|
||||
vec![
|
||||
Box::new(callback_interface::PythonCallbackInterfaceRuntime::new(ci))
|
||||
as Box<dyn CodeDeclaration>,
|
||||
]
|
||||
.into_iter()
|
||||
.chain(
|
||||
ci.iter_enum_definitions().into_iter().map(|inner| {
|
||||
Box::new(enum_::PythonEnum::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}),
|
||||
)
|
||||
.chain(ci.iter_function_definitions().into_iter().map(|inner| {
|
||||
Box::new(function::PythonFunction::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}))
|
||||
.chain(ci.iter_object_definitions().into_iter().map(|inner| {
|
||||
Box::new(object::PythonObject::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}))
|
||||
.chain(ci.iter_record_definitions().into_iter().map(|inner| {
|
||||
Box::new(record::PythonRecord::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}))
|
||||
.chain(
|
||||
ci.iter_error_definitions().into_iter().map(|inner| {
|
||||
Box::new(error::PythonError::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}),
|
||||
)
|
||||
.chain(
|
||||
ci.iter_callback_interface_definitions()
|
||||
.into_iter()
|
||||
.map(|inner| {
|
||||
Box::new(callback_interface::PythonCallbackInterface::new(inner, ci))
|
||||
as Box<dyn CodeDeclaration>
|
||||
}),
|
||||
)
|
||||
.chain(ci.iter_custom_types().into_iter().map(|(name, type_)| {
|
||||
let config = self.config.custom_types.get(&name).cloned();
|
||||
Box::new(custom::PythonCustomType::new(name, type_, config)) as Box<dyn CodeDeclaration>
|
||||
}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn initialization_code(&self) -> Vec<String> {
|
||||
let oracle = &self.oracle;
|
||||
self.members()
|
||||
.into_iter()
|
||||
.filter_map(|member| member.initialization_code(oracle))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn declaration_code(&self) -> Vec<String> {
|
||||
let oracle = &self.oracle;
|
||||
self.members()
|
||||
.into_iter()
|
||||
.filter_map(|member| member.definition_code(oracle))
|
||||
.chain(
|
||||
self.ci
|
||||
.iter_types()
|
||||
.into_iter()
|
||||
.filter_map(|type_| oracle.find(&type_).helper_code(oracle)),
|
||||
)
|
||||
.collect()
|
||||
pub fn new(config: Config, ci: &'a ComponentInterface) -> Self {
|
||||
let type_renderer = TypeRenderer::new(&config, ci);
|
||||
let type_helper_code = type_renderer.render().unwrap();
|
||||
let type_imports = type_renderer.imports.into_inner();
|
||||
Self {
|
||||
config,
|
||||
ci,
|
||||
type_helper_code,
|
||||
type_imports,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn imports(&self) -> Vec<String> {
|
||||
let oracle = &self.oracle;
|
||||
let mut imports: Vec<String> = self
|
||||
.members()
|
||||
.into_iter()
|
||||
.filter_map(|member| member.imports(oracle))
|
||||
.flatten()
|
||||
.chain(
|
||||
self.ci
|
||||
.iter_types()
|
||||
.into_iter()
|
||||
.filter_map(|type_| oracle.find(&type_).imports(oracle))
|
||||
.flatten(),
|
||||
)
|
||||
.collect::<HashSet<String>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
self.type_imports.iter().cloned().collect()
|
||||
}
|
||||
}
|
||||
|
||||
imports.sort();
|
||||
imports
|
||||
fn fixup_keyword(name: String) -> String {
|
||||
if KEYWORDS.contains(&name) {
|
||||
format!("_{}", name)
|
||||
} else {
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -179,11 +209,14 @@ impl<'a> PythonWrapper<'a> {
|
|||
pub struct PythonCodeOracle;
|
||||
|
||||
impl PythonCodeOracle {
|
||||
// Map `Type` instances to a `Box<dyn CodeType>` for that type.
|
||||
//
|
||||
// There is a companion match in `templates/Types.py` which performs a similar function for the
|
||||
// template code.
|
||||
//
|
||||
// - When adding additional types here, make sure to also add a match arm to the `Types.py` template.
|
||||
// - To keep things managable, let's try to limit ourselves to these 2 mega-matches
|
||||
fn create_code_type(&self, type_: TypeIdentifier) -> Box<dyn CodeType> {
|
||||
// I really want access to the ComponentInterface here so I can look up the interface::{Enum, Record, Error, Object, etc}
|
||||
// However, there's some violence and gore I need to do to (temporarily) make the oracle usable from filters.
|
||||
|
||||
// Some refactor of the templates is needed to make progress here: I think most of the filter functions need to take an &dyn CodeOracle
|
||||
match type_ {
|
||||
Type::UInt8 => Box::new(primitives::UInt8CodeType),
|
||||
Type::Int8 => Box::new(primitives::Int8CodeType),
|
||||
|
@ -209,25 +242,10 @@ impl PythonCodeOracle {
|
|||
Box::new(callback_interface::CallbackInterfaceCodeType::new(id))
|
||||
}
|
||||
|
||||
Type::Optional(ref inner) => {
|
||||
let outer = type_.clone();
|
||||
let inner = *inner.to_owned();
|
||||
Box::new(compounds::OptionalCodeType::new(inner, outer))
|
||||
}
|
||||
Type::Sequence(ref inner) => {
|
||||
let outer = type_.clone();
|
||||
let inner = *inner.to_owned();
|
||||
Box::new(compounds::SequenceCodeType::new(inner, outer))
|
||||
}
|
||||
Type::Map(ref key, ref value) => {
|
||||
let outer = type_.clone();
|
||||
let key = *key.to_owned();
|
||||
let value = *value.to_owned();
|
||||
Box::new(compounds::MapCodeType::new(key, value, outer))
|
||||
}
|
||||
Type::External { name, crate_name } => {
|
||||
Box::new(external::ExternalCodeType::new(name, crate_name))
|
||||
}
|
||||
Type::Optional(inner) => Box::new(compounds::OptionalCodeType::new(*inner)),
|
||||
Type::Sequence(inner) => Box::new(compounds::SequenceCodeType::new(*inner)),
|
||||
Type::Map(key, value) => Box::new(compounds::MapCodeType::new(*key, *value)),
|
||||
Type::External { name, .. } => Box::new(external::ExternalCodeType::new(name)),
|
||||
Type::Custom { name, .. } => Box::new(custom::CustomCodeType::new(name)),
|
||||
}
|
||||
}
|
||||
|
@ -240,38 +258,31 @@ impl CodeOracle for PythonCodeOracle {
|
|||
|
||||
/// Get the idiomatic Python rendering of a class name (for enums, records, errors, etc).
|
||||
fn class_name(&self, nm: &str) -> String {
|
||||
nm.to_string().to_upper_camel_case()
|
||||
fixup_keyword(nm.to_string().to_upper_camel_case())
|
||||
}
|
||||
|
||||
/// Get the idiomatic Python rendering of a function name.
|
||||
fn fn_name(&self, nm: &str) -> String {
|
||||
nm.to_string().to_snake_case()
|
||||
fixup_keyword(nm.to_string().to_snake_case())
|
||||
}
|
||||
|
||||
/// Get the idiomatic Python rendering of a variable name.
|
||||
fn var_name(&self, nm: &str) -> String {
|
||||
nm.to_string().to_snake_case()
|
||||
fixup_keyword(nm.to_string().to_snake_case())
|
||||
}
|
||||
|
||||
/// Get the idiomatic Python rendering of an individual enum variant.
|
||||
fn enum_variant_name(&self, nm: &str) -> String {
|
||||
nm.to_string().to_shouty_snake_case()
|
||||
fixup_keyword(nm.to_string().to_shouty_snake_case())
|
||||
}
|
||||
|
||||
/// Get the idiomatic Python rendering of an exception name
|
||||
///
|
||||
/// This replaces "Error" at the end of the name with "Exception". Rust code typically uses
|
||||
/// "Error" for any type of error but in the Java world, "Error" means a non-recoverable error
|
||||
/// and is distinguished from an "Exception".
|
||||
/// This replaces "Error" at the end of the name with "Exception".
|
||||
fn error_name(&self, nm: &str) -> String {
|
||||
let name = nm.to_string();
|
||||
let name = fixup_keyword(self.class_name(nm));
|
||||
match name.strip_suffix("Error") {
|
||||
None => name,
|
||||
Some(stripped) => {
|
||||
let mut py_exc_name = stripped.to_owned();
|
||||
py_exc_name.push_str("Exception");
|
||||
py_exc_name
|
||||
}
|
||||
Some(stripped) => format!("{}Exception", stripped),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -287,7 +298,7 @@ impl CodeOracle for PythonCodeOracle {
|
|||
FFIType::UInt64 => "ctypes.c_uint64".to_string(),
|
||||
FFIType::Float32 => "ctypes.c_float".to_string(),
|
||||
FFIType::Float64 => "ctypes.c_double".to_string(),
|
||||
FFIType::RustArcPtr => "ctypes.c_void_p".to_string(),
|
||||
FFIType::RustArcPtr(_) => "ctypes.c_void_p".to_string(),
|
||||
FFIType::RustBuffer => "RustBuffer".to_string(),
|
||||
FFIType::ForeignBytes => "ForeignBytes".to_string(),
|
||||
FFIType::ForeignCallback => "FOREIGN_CALLBACK_T".to_string(),
|
||||
|
@ -367,10 +378,6 @@ pub mod filters {
|
|||
}
|
||||
|
||||
/// Get the idiomatic Python rendering of an exception name
|
||||
///
|
||||
/// This replaces "Error" at the end of the name with "Exception". Rust code typically uses
|
||||
/// "Error" for any type of error but in the Java world, "Error" means a non-recoverable error
|
||||
/// and is distinguished from an "Exception".
|
||||
pub fn exception_name(nm: &str) -> Result<String, askama::Error> {
|
||||
Ok(oracle().error_name(nm))
|
||||
}
|
||||
|
|
|
@ -2,13 +2,8 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Object};
|
||||
use askama::Template;
|
||||
use std::borrow::Borrow;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
|
||||
// Filters is used by ObjectTemplate.py, which looks for the filters module here.
|
||||
use super::filters;
|
||||
pub struct ObjectCodeType {
|
||||
id: String,
|
||||
}
|
||||
|
@ -32,35 +27,7 @@ impl CodeType for ObjectCodeType {
|
|||
unreachable!();
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"# Helper code for {} class is found in ObjectTemplate.py",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
|
||||
fn coerce(&self, _oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
nm.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "ObjectTemplate.py")]
|
||||
pub struct PythonObject {
|
||||
inner: Object,
|
||||
}
|
||||
|
||||
impl PythonObject {
|
||||
pub fn new(inner: Object, _ci: &ComponentInterface) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
pub fn inner(&self) -> &Object {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonObject {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,11 +2,8 @@
|
|||
* 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(unused_imports)]
|
||||
use super::filters;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
use crate::interface::Radix;
|
||||
use askama::Template;
|
||||
use paste::paste;
|
||||
|
||||
fn render_literal(_oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
|
@ -37,10 +34,8 @@ fn render_literal(_oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
|||
}
|
||||
|
||||
macro_rules! impl_code_type_for_primitive {
|
||||
($T:ty, $class_name:literal, $template_file:literal, $coerce_code:expr) => {
|
||||
($T:ty, $class_name:literal, $coerce_code:expr) => {
|
||||
paste! {
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = $template_file)]
|
||||
pub struct $T;
|
||||
|
||||
impl CodeType for $T {
|
||||
|
@ -52,10 +47,6 @@ macro_rules! impl_code_type_for_primitive {
|
|||
render_literal(oracle, &literal)
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn coerce(&self, _oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
format!($coerce_code, nm)
|
||||
}
|
||||
|
@ -64,15 +55,15 @@ macro_rules! impl_code_type_for_primitive {
|
|||
};
|
||||
}
|
||||
|
||||
impl_code_type_for_primitive!(BooleanCodeType, "Bool", "BooleanHelper.py", "bool({})");
|
||||
impl_code_type_for_primitive!(StringCodeType, "String", "StringHelper.py", "{}");
|
||||
impl_code_type_for_primitive!(Int8CodeType, "Int8", "Int8Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(Int16CodeType, "Int16", "Int16Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(Int32CodeType, "Int32", "Int32Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(Int64CodeType, "Int64", "Int64Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(UInt8CodeType, "UInt8", "UInt8Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(UInt16CodeType, "UInt16", "UInt16Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(UInt32CodeType, "UInt32", "UInt32Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(UInt64CodeType, "UInt64", "UInt64Helper.py", "int({})");
|
||||
impl_code_type_for_primitive!(Float32CodeType, "Float", "Float32Helper.py", "float({})");
|
||||
impl_code_type_for_primitive!(Float64CodeType, "Double", "Float64Helper.py", "float({})");
|
||||
impl_code_type_for_primitive!(BooleanCodeType, "Bool", "bool({})");
|
||||
impl_code_type_for_primitive!(StringCodeType, "String", "{}");
|
||||
impl_code_type_for_primitive!(Int8CodeType, "Int8", "int({})");
|
||||
impl_code_type_for_primitive!(Int16CodeType, "Int16", "int({})");
|
||||
impl_code_type_for_primitive!(Int32CodeType, "Int32", "int({})");
|
||||
impl_code_type_for_primitive!(Int64CodeType, "Int64", "int({})");
|
||||
impl_code_type_for_primitive!(UInt8CodeType, "UInt8", "int({})");
|
||||
impl_code_type_for_primitive!(UInt16CodeType, "UInt16", "int({})");
|
||||
impl_code_type_for_primitive!(UInt32CodeType, "UInt32", "int({})");
|
||||
impl_code_type_for_primitive!(UInt64CodeType, "UInt64", "int({})");
|
||||
impl_code_type_for_primitive!(Float32CodeType, "Float", "float({})");
|
||||
impl_code_type_for_primitive!(Float64CodeType, "Double", "float({})");
|
||||
|
|
|
@ -2,11 +2,7 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Record};
|
||||
use askama::Template;
|
||||
|
||||
use super::filters;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
|
||||
pub struct RecordCodeType {
|
||||
id: String,
|
||||
|
@ -31,36 +27,7 @@ impl CodeType for RecordCodeType {
|
|||
unreachable!();
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"# Helper code for {} record is found in RecordTemplate.py",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
|
||||
fn coerce(&self, _oracle: &dyn CodeOracle, nm: &str) -> String {
|
||||
nm.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "py", escape = "none", path = "RecordTemplate.py")]
|
||||
pub struct PythonRecord {
|
||||
inner: Record,
|
||||
}
|
||||
|
||||
impl PythonRecord {
|
||||
pub fn new(inner: Record, _ci: &ComponentInterface) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &Record {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for PythonRecord {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,18 +2,13 @@
|
|||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
use std::{
|
||||
env,
|
||||
ffi::OsString,
|
||||
fs::File,
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
use std::{env, io::Write, process::Command};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use fs_err::File;
|
||||
|
||||
pub mod gen_python;
|
||||
use camino::Utf8Path;
|
||||
pub use gen_python::{generate_python_bindings, Config};
|
||||
|
||||
use super::super::interface::ComponentInterface;
|
||||
|
@ -22,19 +17,18 @@ use super::super::interface::ComponentInterface;
|
|||
pub fn write_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: &Path,
|
||||
out_dir: &Utf8Path,
|
||||
try_format_code: bool,
|
||||
) -> Result<()> {
|
||||
let mut py_file = PathBuf::from(out_dir);
|
||||
py_file.push(format!("{}.py", ci.namespace()));
|
||||
let mut f = File::create(&py_file).context("Failed to create .py file for bindings")?;
|
||||
let py_file = out_dir.join(format!("{}.py", ci.namespace()));
|
||||
let mut f = File::create(&py_file)?;
|
||||
write!(f, "{}", generate_python_bindings(config, ci)?)?;
|
||||
|
||||
if try_format_code {
|
||||
if let Err(e) = Command::new("yapf").arg(py_file.to_str().unwrap()).output() {
|
||||
if let Err(e) = Command::new("yapf").arg(&py_file).output() {
|
||||
println!(
|
||||
"Warning: Unable to auto-format {} using yapf: {:?}",
|
||||
py_file.file_name().unwrap().to_str().unwrap(),
|
||||
py_file.file_name().unwrap(),
|
||||
e
|
||||
)
|
||||
}
|
||||
|
@ -45,12 +39,13 @@ pub fn write_bindings(
|
|||
|
||||
/// Execute the specifed python script, with environment based on the generated
|
||||
/// artifacts in the given output directory.
|
||||
pub fn run_script(out_dir: &Path, script_file: &Path) -> Result<()> {
|
||||
pub fn run_script(out_dir: &Utf8Path, script_file: &Utf8Path) -> Result<()> {
|
||||
let mut cmd = Command::new("python3");
|
||||
// This helps python find the generated .py wrapper for rust component.
|
||||
let pythonpath = env::var_os("PYTHONPATH").unwrap_or_else(|| OsString::from(""));
|
||||
let pythonpath =
|
||||
env::join_paths(env::split_paths(&pythonpath).chain(vec![out_dir.to_path_buf()]))?;
|
||||
let pythonpath = env::var_os("PYTHONPATH").unwrap_or_default();
|
||||
let pythonpath = env::join_paths(
|
||||
env::split_paths(&pythonpath).chain(vec![out_dir.as_std_path().to_owned()]),
|
||||
)?;
|
||||
cmd.env("PYTHONPATH", pythonpath);
|
||||
// We should now be able to execute the tests successfully.
|
||||
cmd.arg(script_file);
|
||||
|
|
|
@ -1,12 +1,11 @@
|
|||
{% import "macros.py" as py %}
|
||||
{%- let cbi = self.inner() %}
|
||||
{%- let canonical_name = cbi|canonical_name %}
|
||||
{%- let ffi_converter = cbi|ffi_converter_name %}
|
||||
{%- let foreign_callback = format!("foreignCallback{}", canonical_name) %}
|
||||
{%- let cbi = ci.get_callback_interface_definition(id).unwrap() %}
|
||||
{%- let foreign_callback = format!("foreignCallback{}", canonical_type_name) %}
|
||||
|
||||
# Declaration and FfiConverters for {{ cbi|type_name }} Callback Interface
|
||||
{% if self.include_once_check("CallbackInterfaceRuntime.py") %}{% include "CallbackInterfaceRuntime.py" %}{% endif %}
|
||||
|
||||
class {{ cbi|type_name }}:
|
||||
# Declaration and FfiConverters for {{ type_name }} Callback Interface
|
||||
|
||||
class {{ type_name }}:
|
||||
{% for meth in cbi.methods() -%}
|
||||
def {{ meth.name()|fn_name }}({% call py::arg_list_decl(meth) %}):
|
||||
raise NotImplementedError
|
||||
|
@ -45,12 +44,12 @@ def py_{{ foreign_callback }}(handle, method, args, buf_ptr):
|
|||
# https://github.com/mozilla/uniffi-rs/issues/351
|
||||
{% endfor %}
|
||||
|
||||
cb = {{ ffi_converter }}.lift(handle)
|
||||
cb = {{ ffi_converter_name }}.lift(handle)
|
||||
if not cb:
|
||||
raise InternalError("No callback in handlemap; this is a Uniffi bug")
|
||||
|
||||
if method == IDX_CALLBACK_FREE:
|
||||
{{ ffi_converter }}.drop(handle)
|
||||
{{ ffi_converter_name }}.drop(handle)
|
||||
# No return value.
|
||||
# See docs of ForeignCallback in `uniffi/src/ffi/foreigncallbacks.rs`
|
||||
return 0
|
||||
|
@ -80,4 +79,4 @@ def py_{{ foreign_callback }}(handle, method, args, buf_ptr):
|
|||
|
||||
# The FfiConverter which transforms the Callbacks in to Handles to pass to Rust.
|
||||
rust_call(lambda err: _UniFFILib.{{ cbi.ffi_init_callback().name() }}({{ foreign_callback }}, err))
|
||||
{{ ffi_converter }} = FfiConverterCallbackInterface({{ foreign_callback }})
|
||||
{{ ffi_converter_name }} = FfiConverterCallbackInterface({{ foreign_callback }})
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
{%- match config %}
|
||||
{%- when None %}
|
||||
{%- match python_config.custom_types.get(name.as_str()) %}
|
||||
{% when None %}
|
||||
{#- No custom type config, just forward all methods to our builtin type #}
|
||||
class FfiConverterType{{ name }}:
|
||||
@staticmethod
|
||||
|
@ -18,7 +18,16 @@ class FfiConverterType{{ name }}:
|
|||
def lower(value):
|
||||
return {{ builtin|ffi_converter_name }}.lower(value)
|
||||
|
||||
{%- when Some with (config) %}
|
||||
{%- when Some(config) %}
|
||||
|
||||
{%- match config.imports %}
|
||||
{%- when Some(imports) %}
|
||||
{%- for import_name in imports %}
|
||||
{{ self.add_import(import_name) }}
|
||||
{%- endfor %}
|
||||
{%- else %}
|
||||
{%- endmatch %}
|
||||
|
||||
{#- Custom type config supplied, use it to convert the builtin type #}
|
||||
class FfiConverterType{{ name }}:
|
||||
@staticmethod
|
||||
|
|
|
@ -4,18 +4,18 @@
|
|||
# when none of the variants have associated data, or a generic nested-class
|
||||
# construct when they do.
|
||||
#}
|
||||
{%- let e = self.inner() %}
|
||||
{%- let e = ci.get_enum_definition(name).unwrap() %}
|
||||
{% if e.is_flat() %}
|
||||
|
||||
class {{ e|type_name }}(enum.Enum):
|
||||
class {{ type_name }}(enum.Enum):
|
||||
{% for variant in e.variants() -%}
|
||||
{{ variant.name()|enum_variant_py }} = {{ loop.index }}
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
|
||||
class {{ e|type_name }}:
|
||||
class {{ type_name }}:
|
||||
def __init__(self):
|
||||
raise RuntimeError("{{ e|type_name }} cannot be instantiated directly")
|
||||
raise RuntimeError("{{ type_name }} cannot be instantiated directly")
|
||||
|
||||
# Each enum variant is a nested class of the enum itself.
|
||||
{% for variant in e.variants() -%}
|
||||
|
@ -30,7 +30,7 @@ class {{ e|type_name }}:
|
|||
{% endif %}
|
||||
|
||||
def __str__(self):
|
||||
return "{{ e|type_name }}.{{ variant.name()|enum_variant_py }}({% for field in variant.fields() %}{{ field.name() }}={}{% if loop.last %}{% else %}, {% endif %}{% endfor %})".format({% for field in variant.fields() %}self.{{ field.name() }}{% if loop.last %}{% else %}, {% endif %}{% endfor %})
|
||||
return "{{ type_name }}.{{ variant.name()|enum_variant_py }}({% for field in variant.fields() %}{{ field.name()|var_name }}={}{% if loop.last %}{% else %}, {% endif %}{% endfor %})".format({% for field in variant.fields() %}self.{{ field.name()|var_name }}{% if loop.last %}{% else %}, {% endif %}{% endfor %})
|
||||
|
||||
def __eq__(self, other):
|
||||
if not other.is_{{ variant.name()|var_name }}():
|
||||
|
@ -46,19 +46,19 @@ class {{ e|type_name }}:
|
|||
# whether an instance is that variant.
|
||||
{% for variant in e.variants() -%}
|
||||
def is_{{ variant.name()|var_name }}(self):
|
||||
return isinstance(self, {{ e|type_name }}.{{ variant.name()|enum_variant_py }})
|
||||
return isinstance(self, {{ type_name }}.{{ variant.name()|enum_variant_py }})
|
||||
{% endfor %}
|
||||
|
||||
# Now, a little trick - we make each nested variant class be a subclass of the main
|
||||
# enum class, so that method calls and instance checks etc will work intuitively.
|
||||
# We might be able to do this a little more neatly with a metaclass, but this'll do.
|
||||
{% for variant in e.variants() -%}
|
||||
{{ e|type_name }}.{{ variant.name()|enum_variant_py }} = type("{{ e|type_name }}.{{ variant.name()|enum_variant_py }}", ({{ e|type_name }}.{{variant.name()|enum_variant_py}}, {{ e|type_name }},), {})
|
||||
{{ type_name }}.{{ variant.name()|enum_variant_py }} = type("{{ type_name }}.{{ variant.name()|enum_variant_py }}", ({{ type_name }}.{{variant.name()|enum_variant_py}}, {{ type_name }},), {})
|
||||
{% endfor %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
class {{ e|ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
class {{ ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
@staticmethod
|
||||
def read(buf):
|
||||
variant = buf.readI32()
|
||||
|
@ -66,9 +66,9 @@ class {{ e|ffi_converter_name }}(FfiConverterRustBuffer):
|
|||
{%- for variant in e.variants() %}
|
||||
if variant == {{ loop.index }}:
|
||||
{%- if e.is_flat() %}
|
||||
return {{ e|type_name }}.{{variant.name()|enum_variant_py}}
|
||||
return {{ type_name }}.{{variant.name()|enum_variant_py}}
|
||||
{%- else %}
|
||||
return {{ e|type_name }}.{{variant.name()|enum_variant_py}}(
|
||||
return {{ type_name }}.{{variant.name()|enum_variant_py}}(
|
||||
{%- for field in variant.fields() %}
|
||||
{{ field|read_fn }}(buf),
|
||||
{%- endfor %}
|
||||
|
@ -80,7 +80,7 @@ class {{ e|ffi_converter_name }}(FfiConverterRustBuffer):
|
|||
def write(value, buf):
|
||||
{%- for variant in e.variants() %}
|
||||
{%- if e.is_flat() %}
|
||||
if value == {{ e|type_name }}.{{ variant.name()|enum_variant_py }}:
|
||||
if value == {{ type_name }}.{{ variant.name()|enum_variant_py }}:
|
||||
buf.writeI32({{ loop.index }})
|
||||
{%- else %}
|
||||
if value.is_{{ variant.name()|var_name }}():
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
{%- let e = self.inner() %}
|
||||
class {{ e|type_name }}(Exception):
|
||||
{%- let e = ci.get_error_definition(name).unwrap() %}
|
||||
class {{ type_name }}(Exception):
|
||||
{%- if e.is_flat() %}
|
||||
|
||||
# Each variant is a nested class of the error itself.
|
||||
|
@ -27,24 +27,24 @@ class {{ e|type_name }}(Exception):
|
|||
{%- if variant.has_fields() %}
|
||||
field_parts = [
|
||||
{%- for field in variant.fields() %}
|
||||
'{{ field.name() }}={!r}'.format(self.{{ field.name() }}),
|
||||
'{{ field.name()|var_name }}={!r}'.format(self.{{ field.name()|var_name }}),
|
||||
{%- endfor %}
|
||||
]
|
||||
return "{{ e|type_name }}.{{ variant.name()|class_name }}({})".format(', '.join(field_parts))
|
||||
return "{{ type_name }}.{{ variant.name()|class_name }}({})".format(', '.join(field_parts))
|
||||
{%- else %}
|
||||
return "{{ e|type_name }}.{{ variant.name()|class_name }}"
|
||||
return "{{ type_name }}.{{ variant.name()|class_name }}"
|
||||
{%- endif %}
|
||||
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
class {{ e|ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
class {{ ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
@staticmethod
|
||||
def read(buf):
|
||||
variant = buf.readI32()
|
||||
{%- for variant in e.variants() %}
|
||||
if variant == {{ loop.index }}:
|
||||
return {{ e|type_name }}.{{ variant.name()|class_name }}(
|
||||
return {{ type_name }}.{{ variant.name()|class_name }}(
|
||||
{%- if e.is_flat() %}
|
||||
{{ Type::String.borrow()|read_fn }}(buf),
|
||||
{%- else %}
|
||||
|
@ -59,7 +59,7 @@ class {{ e|ffi_converter_name }}(FfiConverterRustBuffer):
|
|||
@staticmethod
|
||||
def write(value, buf):
|
||||
{%- for variant in e.variants() %}
|
||||
if isinstance(value, {{ e|type_name }}.{{ variant.name()|class_name }}):
|
||||
if isinstance(value, {{ type_name }}.{{ variant.name()|class_name }}):
|
||||
buf.writeI32({{ loop.index }})
|
||||
{%- for field in variant.fields() %}
|
||||
{{ field|write_fn }}(value.{{ field.name()|var_name }}, buf)
|
||||
|
|
|
@ -1 +1 @@
|
|||
from {{ self.crate_name|fn_name }} import FfiConverterType{{ name }}
|
||||
from {{ crate_name|fn_name }} import FfiConverterType{{ name }}
|
||||
|
|
|
@ -1,10 +1,7 @@
|
|||
{%- let outer_type = self.outer() %}
|
||||
{%- let key_type = self.key() %}
|
||||
{%- let value_type = self.value() %}
|
||||
{%- let key_ffi_converter = key_type|ffi_converter_name %}
|
||||
{%- let value_ffi_converter = value_type|ffi_converter_name %}
|
||||
|
||||
class {{ outer_type|ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
class {{ ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
@classmethod
|
||||
def write(cls, items, buf):
|
||||
buf.writeI32(len(items))
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
{% import "macros.py" as py %}
|
||||
{%- let obj = self.inner() %}
|
||||
{%- let obj = ci.get_object_definition(name).unwrap() %}
|
||||
|
||||
class {{ obj|type_name }}(object):
|
||||
class {{ type_name }}(object):
|
||||
{%- match obj.primary_constructor() %}
|
||||
{%- when Some with (cons) %}
|
||||
def __init__(self, {% call py::arg_list_decl(cons) -%}):
|
||||
{%- call py::coerce_args_extra_indent(cons) %}
|
||||
{%- call py::setup_args_extra_indent(cons) %}
|
||||
self._pointer = {% call py::to_ffi_call(cons) %}
|
||||
{%- when None %}
|
||||
{%- endmatch %}
|
||||
|
@ -28,7 +27,7 @@ class {{ obj|type_name }}(object):
|
|||
{% for cons in obj.alternate_constructors() -%}
|
||||
@classmethod
|
||||
def {{ cons.name()|fn_name }}(cls, {% call py::arg_list_decl(cons) %}):
|
||||
{%- call py::coerce_args_extra_indent(cons) %}
|
||||
{%- call py::setup_args_extra_indent(cons) %}
|
||||
# Call the (fallible) function before creating any half-baked object instances.
|
||||
pointer = {% call py::to_ffi_call(cons) %}
|
||||
return cls._make_instance_(pointer)
|
||||
|
@ -39,20 +38,20 @@ class {{ obj|type_name }}(object):
|
|||
|
||||
{%- when Some with (return_type) -%}
|
||||
def {{ meth.name()|fn_name }}(self, {% call py::arg_list_decl(meth) %}):
|
||||
{%- call py::coerce_args_extra_indent(meth) %}
|
||||
{%- call py::setup_args_extra_indent(meth) %}
|
||||
return {{ return_type|lift_fn }}(
|
||||
{% call py::to_ffi_call_with_prefix("self._pointer", meth) %}
|
||||
)
|
||||
|
||||
{%- when None -%}
|
||||
def {{ meth.name()|fn_name }}(self, {% call py::arg_list_decl(meth) %}):
|
||||
{%- call py::coerce_args_extra_indent(meth) %}
|
||||
{%- call py::setup_args_extra_indent(meth) %}
|
||||
{% call py::to_ffi_call_with_prefix("self._pointer", meth) %}
|
||||
{% endmatch %}
|
||||
{% endfor %}
|
||||
|
||||
|
||||
class {{ obj|ffi_converter_name }}:
|
||||
class {{ ffi_converter_name }}:
|
||||
@classmethod
|
||||
def read(cls, buf):
|
||||
ptr = buf.readU64()
|
||||
|
@ -62,13 +61,13 @@ class {{ obj|ffi_converter_name }}:
|
|||
|
||||
@classmethod
|
||||
def write(cls, value, buf):
|
||||
if not isinstance(value, {{ obj|type_name }}):
|
||||
raise TypeError("Expected {{ obj|type_name }} instance, {} found".format(value.__class__.__name__))
|
||||
if not isinstance(value, {{ type_name }}):
|
||||
raise TypeError("Expected {{ type_name }} instance, {} found".format(value.__class__.__name__))
|
||||
buf.writeU64(cls.lower(value))
|
||||
|
||||
@staticmethod
|
||||
def lift(value):
|
||||
return {{ obj|type_name }}._make_instance_(value)
|
||||
return {{ type_name }}._make_instance_(value)
|
||||
|
||||
@staticmethod
|
||||
def lower(value):
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
{%- let inner_type = self.inner() %}
|
||||
{%- let outer_type = self.outer() %}
|
||||
{%- let inner_ffi_converter = inner_type|ffi_converter_name %}
|
||||
|
||||
class {{ outer_type|ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
class {{ ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
@classmethod
|
||||
def write(cls, value, buf):
|
||||
if value is None:
|
||||
|
|
|
@ -1,13 +1,26 @@
|
|||
{% import "macros.py" as py %}
|
||||
{%- let rec = self.inner() %}
|
||||
class {{ rec|type_name }}:
|
||||
def __init__(self, {% call py::field_list_decl(rec) %}):
|
||||
{%- let rec = ci.get_record_definition(name).unwrap() %}
|
||||
class {{ type_name }}:
|
||||
|
||||
def __init__(self, {% for field in rec.fields() %}
|
||||
{{- field.name()|var_name }}
|
||||
{%- if field.default_value().is_some() %} = DEFAULT{% endif %}
|
||||
{%- if !loop.last %}, {% endif %}
|
||||
{%- endfor %}):
|
||||
{%- for field in rec.fields() %}
|
||||
self.{{ field.name()|var_name }} = {{ field.name()|var_name }}
|
||||
{%- let field_name = field.name()|var_name %}
|
||||
{%- match field.default_value() %}
|
||||
{%- when None %}
|
||||
self.{{ field_name }} = {{ field_name }}
|
||||
{%- when Some with(literal) %}
|
||||
if {{ field_name }} is DEFAULT:
|
||||
self.{{ field_name }} = {{ literal|literal_py(field) }}
|
||||
else:
|
||||
self.{{ field_name }} = {{ field_name }}
|
||||
{%- endmatch %}
|
||||
{%- endfor %}
|
||||
|
||||
def __str__(self):
|
||||
return "{{ rec|type_name }}({% for field in rec.fields() %}{{ field.name() }}={}{% if loop.last %}{% else %}, {% endif %}{% endfor %})".format({% for field in rec.fields() %}self.{{ field.name() }}{% if loop.last %}{% else %}, {% endif %}{% endfor %})
|
||||
return "{{ type_name }}({% for field in rec.fields() %}{{ field.name()|var_name }}={}{% if loop.last %}{% else %}, {% endif %}{% endfor %})".format({% for field in rec.fields() %}self.{{ field.name()|var_name }}{% if loop.last %}{% else %}, {% endif %}{% endfor %})
|
||||
|
||||
def __eq__(self, other):
|
||||
{%- for field in rec.fields() %}
|
||||
|
@ -16,10 +29,10 @@ class {{ rec|type_name }}:
|
|||
{%- endfor %}
|
||||
return True
|
||||
|
||||
class {{ rec|ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
class {{ ffi_converter_name }}(FfiConverterRustBuffer):
|
||||
@staticmethod
|
||||
def read(buf):
|
||||
return {{ rec|type_name }}(
|
||||
return {{ type_name }}(
|
||||
{%- for field in rec.fields() %}
|
||||
{{ field.name()|var_name }}={{ field|read_fn }}(buf),
|
||||
{%- endfor %}
|
||||
|
@ -28,5 +41,5 @@ class {{ rec|ffi_converter_name }}(FfiConverterRustBuffer):
|
|||
@staticmethod
|
||||
def write(value, buf):
|
||||
{%- for field in rec.fields() %}
|
||||
{{ field|write_fn }}(value.{{ field.name() }}, buf)
|
||||
{{ field|write_fn }}(value.{{ field.name()|var_name }}, buf)
|
||||
{%- endfor %}
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
{%- let inner_type = self.inner() %}
|
||||
{%- let outer_type = self.outer() %}
|
||||
{%- let inner_ffi_converter = inner_type|ffi_converter_name %}
|
||||
|
||||
class {{ outer_type|ffi_converter_name}}(FfiConverterRustBuffer):
|
||||
class {{ ffi_converter_name}}(FfiConverterRustBuffer):
|
||||
@classmethod
|
||||
def write(cls, value, buf):
|
||||
items = len(value)
|
||||
|
|
|
@ -1,15 +1,13 @@
|
|||
{% import "macros.py" as py %}
|
||||
{%- let func = self.inner() %}
|
||||
{%- match func.return_type() -%}
|
||||
{%- when Some with (return_type) %}
|
||||
|
||||
def {{ func.name()|fn_name }}({%- call py::arg_list_decl(func) -%}):
|
||||
{%- call py::coerce_args(func) %}
|
||||
{%- call py::setup_args(func) %}
|
||||
return {{ return_type|lift_fn }}({% call py::to_ffi_call(func) %})
|
||||
|
||||
{% when None -%}
|
||||
{% when None %}
|
||||
|
||||
def {{ func.name()|fn_name }}({%- call py::arg_list_decl(func) -%}):
|
||||
{%- call py::coerce_args(func) %}
|
||||
{%- call py::setup_args(func) %}
|
||||
{% call py::to_ffi_call(func) %}
|
||||
{% endmatch %}
|
||||
|
|
|
@ -0,0 +1,93 @@
|
|||
{%- import "macros.py" as py %}
|
||||
|
||||
{%- for type_ in ci.iter_types() %}
|
||||
{%- let type_name = type_|type_name %}
|
||||
{%- let ffi_converter_name = type_|ffi_converter_name %}
|
||||
{%- let canonical_type_name = type_|canonical_name %}
|
||||
|
||||
{#
|
||||
# Map `Type` instances to an include statement for that type.
|
||||
#
|
||||
# There is a companion match in `PythonCodeOracle::create_code_type()` which performs a similar function for the
|
||||
# Rust code.
|
||||
#
|
||||
# - When adding additional types here, make sure to also add a match arm to that function.
|
||||
# - To keep things managable, let's try to limit ourselves to these 2 mega-matches
|
||||
#}
|
||||
{%- match type_ %}
|
||||
|
||||
{%- when Type::Boolean %}
|
||||
{%- include "BooleanHelper.py" %}
|
||||
|
||||
{%- when Type::Int8 %}
|
||||
{%- include "Int8Helper.py" %}
|
||||
|
||||
{%- when Type::Int16 %}
|
||||
{%- include "Int16Helper.py" %}
|
||||
|
||||
{%- when Type::Int32 %}
|
||||
{%- include "Int32Helper.py" %}
|
||||
|
||||
{%- when Type::Int64 %}
|
||||
{%- include "Int64Helper.py" %}
|
||||
|
||||
{%- when Type::UInt8 %}
|
||||
{%- include "UInt8Helper.py" %}
|
||||
|
||||
{%- when Type::UInt16 %}
|
||||
{%- include "UInt16Helper.py" %}
|
||||
|
||||
{%- when Type::UInt32 %}
|
||||
{%- include "UInt32Helper.py" %}
|
||||
|
||||
{%- when Type::UInt64 %}
|
||||
{%- include "UInt64Helper.py" %}
|
||||
|
||||
{%- when Type::Float32 %}
|
||||
{%- include "Float32Helper.py" %}
|
||||
|
||||
{%- when Type::Float64 %}
|
||||
{%- include "Float64Helper.py" %}
|
||||
|
||||
{%- when Type::String %}
|
||||
{%- include "StringHelper.py" %}
|
||||
|
||||
{%- when Type::Enum(name) %}
|
||||
{%- include "EnumTemplate.py" %}
|
||||
|
||||
{%- when Type::Error(name) %}
|
||||
{%- include "ErrorTemplate.py" %}
|
||||
|
||||
{%- when Type::Record(name) %}
|
||||
{%- include "RecordTemplate.py" %}
|
||||
|
||||
{%- when Type::Object(name) %}
|
||||
{%- include "ObjectTemplate.py" %}
|
||||
|
||||
{%- when Type::Timestamp %}
|
||||
{%- include "TimestampHelper.py" %}
|
||||
|
||||
{%- when Type::Duration %}
|
||||
{%- include "DurationHelper.py" %}
|
||||
|
||||
{%- when Type::Optional(inner_type) %}
|
||||
{%- include "OptionalTemplate.py" %}
|
||||
|
||||
{%- when Type::Sequence(inner_type) %}
|
||||
{%- include "SequenceTemplate.py" %}
|
||||
|
||||
{%- when Type::Map(key_type, value_type) %}
|
||||
{%- include "MapTemplate.py" %}
|
||||
|
||||
{%- when Type::CallbackInterface(id) %}
|
||||
{%- include "CallbackInterfaceTemplate.py" %}
|
||||
|
||||
{%- when Type::Custom { name, builtin } %}
|
||||
{%- include "CustomType.py" %}
|
||||
|
||||
{%- when Type::External { name, crate_name } %}
|
||||
{%- include "ExternalTemplate.py" %}
|
||||
|
||||
{%- else %}
|
||||
{%- endmatch %}
|
||||
{%- endfor %}
|
|
@ -32,7 +32,7 @@ rust_call(
|
|||
|
||||
{%- macro _arg_list_ffi_call(func) %}
|
||||
{%- for arg in func.arguments() %}
|
||||
{{ arg|lower_fn }}({{ arg.name() }})
|
||||
{{ arg|lower_fn }}({{ arg.name()|var_name }})
|
||||
{%- if !loop.last %},{% endif %}
|
||||
{%- endfor %}
|
||||
{%- endmacro -%}
|
||||
|
@ -46,28 +46,13 @@ rust_call(
|
|||
{%- for arg in func.arguments() -%}
|
||||
{{ arg.name()|var_name }}
|
||||
{%- match arg.default_value() %}
|
||||
{%- when Some with(literal) %} = {{ literal|literal_py(arg.type_().borrow()) }}
|
||||
{%- when Some with(literal) %} = DEFAULT
|
||||
{%- else %}
|
||||
{%- endmatch %}
|
||||
{%- if !loop.last %},{% endif -%}
|
||||
{%- endfor %}
|
||||
{%- endmacro %}
|
||||
|
||||
{#-
|
||||
// Field lists as used in Python declarations of Records.
|
||||
// Note the var_name.
|
||||
-#}
|
||||
{%- macro field_list_decl(item) %}
|
||||
{%- for field in item.fields() -%}
|
||||
{{ field.name()|var_name }}
|
||||
{%- match field.default_value() %}
|
||||
{%- when Some with(literal) %} = {{ literal|literal_py(field) }}
|
||||
{%- else %}
|
||||
{%- endmatch -%}
|
||||
{% if !loop.last %}, {% endif %}
|
||||
{%- endfor %}
|
||||
{%- endmacro %}
|
||||
|
||||
{#-
|
||||
// Arglist as used in the _UniFFILib function declations.
|
||||
// Note unfiltered name but ffi_type_name filters.
|
||||
|
@ -79,14 +64,38 @@ rust_call(
|
|||
ctypes.POINTER(RustCallStatus),
|
||||
{% endmacro -%}
|
||||
|
||||
{%- macro coerce_args(func) %}
|
||||
{#
|
||||
# Setup function arguments by initializing default values and passing other
|
||||
# values through coerce.
|
||||
#}
|
||||
{%- macro setup_args(func) %}
|
||||
{%- for arg in func.arguments() %}
|
||||
{{ arg.name() }} = {{ arg.name()|coerce_py(arg.type_().borrow()) -}}
|
||||
{%- match arg.default_value() %}
|
||||
{%- when None %}
|
||||
{{ arg.name()|var_name }} = {{ arg.name()|var_name|coerce_py(arg.type_().borrow()) -}}
|
||||
{%- when Some with(literal) %}
|
||||
if {{ arg.name()|var_name }} is DEFAULT:
|
||||
{{ arg.name()|var_name }} = {{ literal|literal_py(arg.type_().borrow()) }}
|
||||
else:
|
||||
{{ arg.name()|var_name }} = {{ arg.name()|var_name|coerce_py(arg.type_().borrow()) -}}
|
||||
{%- endmatch %}
|
||||
{% endfor -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- macro coerce_args_extra_indent(func) %}
|
||||
{#
|
||||
# Exactly the same thing as `setup_args()` but with an extra 4 spaces of
|
||||
# indent so that it works with object methods.
|
||||
#}
|
||||
{%- macro setup_args_extra_indent(func) %}
|
||||
{%- for arg in func.arguments() %}
|
||||
{{ arg.name() }} = {{ arg.name()|coerce_py(arg.type_().borrow()) }}
|
||||
{%- endfor %}
|
||||
{%- match arg.default_value() %}
|
||||
{%- when None %}
|
||||
{{ arg.name()|var_name }} = {{ arg.name()|var_name|coerce_py(arg.type_().borrow()) -}}
|
||||
{%- when Some with(literal) %}
|
||||
if {{ arg.name()|var_name }} is DEFAULT:
|
||||
{{ arg.name()|var_name }} = {{ literal|literal_py(arg.type_().borrow()) }}
|
||||
else:
|
||||
{{ arg.name()|var_name }} = {{ arg.name()|var_name|coerce_py(arg.type_().borrow()) -}}
|
||||
{%- endmatch %}
|
||||
{% endfor -%}
|
||||
{%- endmacro -%}
|
||||
|
|
|
@ -28,6 +28,9 @@ import datetime
|
|||
import {{ module_name }}
|
||||
{%- endfor %}
|
||||
|
||||
# Used for default argument values
|
||||
DEFAULT = object()
|
||||
|
||||
{% include "RustBufferTemplate.py" %}
|
||||
{% include "Helpers.py" %}
|
||||
{% include "RustBufferHelper.py" %}
|
||||
|
@ -37,28 +40,30 @@ import {{ module_name }}
|
|||
{% include "NamespaceLibraryTemplate.py" %}
|
||||
|
||||
# Public interface members begin here.
|
||||
{% for code in self.declaration_code() %}
|
||||
{{ code }}
|
||||
{{ type_helper_code }}
|
||||
|
||||
{%- for func in ci.function_definitions() %}
|
||||
{%- include "TopLevelFunctionTemplate.py" %}
|
||||
{%- endfor %}
|
||||
|
||||
__all__ = [
|
||||
"InternalError",
|
||||
{%- for e in ci.iter_enum_definitions() %}
|
||||
{%- for e in ci.enum_definitions() %}
|
||||
"{{ e|type_name }}",
|
||||
{%- endfor %}
|
||||
{%- for record in ci.iter_record_definitions() %}
|
||||
{%- for record in ci.record_definitions() %}
|
||||
"{{ record|type_name }}",
|
||||
{%- endfor %}
|
||||
{%- for func in ci.iter_function_definitions() %}
|
||||
{%- for func in ci.function_definitions() %}
|
||||
"{{ func.name()|fn_name }}",
|
||||
{%- endfor %}
|
||||
{%- for obj in ci.iter_object_definitions() %}
|
||||
{%- for obj in ci.object_definitions() %}
|
||||
"{{ obj|type_name }}",
|
||||
{%- endfor %}
|
||||
{%- for e in ci.iter_error_definitions() %}
|
||||
{%- for e in ci.error_definitions() %}
|
||||
"{{ e|type_name }}",
|
||||
{%- endfor %}
|
||||
{%- for c in ci.iter_callback_interface_definitions() %}
|
||||
{%- for c in ci.callback_interface_definitions() %}
|
||||
"{{ c.name()|class_name }}",
|
||||
{%- endfor %}
|
||||
]
|
||||
|
|
|
@ -92,7 +92,7 @@ mod filters {
|
|||
FFIType::UInt64 => ":uint64".to_string(),
|
||||
FFIType::Float32 => ":float".to_string(),
|
||||
FFIType::Float64 => ":double".to_string(),
|
||||
FFIType::RustArcPtr => ":pointer".to_string(),
|
||||
FFIType::RustArcPtr(_) => ":pointer".to_string(),
|
||||
FFIType::RustBuffer => "RustBuffer.by_value".to_string(),
|
||||
FFIType::ForeignBytes => "ForeignBytes".to_string(),
|
||||
FFIType::ForeignCallback => unimplemented!("Callback interfaces are not implemented"),
|
||||
|
|
|
@ -2,18 +2,13 @@
|
|||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
use std::{
|
||||
env,
|
||||
ffi::OsString,
|
||||
fs::File,
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
use std::{env, io::Write, process::Command};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use fs_err::File;
|
||||
|
||||
pub mod gen_ruby;
|
||||
use camino::Utf8Path;
|
||||
pub use gen_ruby::{Config, RubyWrapper};
|
||||
|
||||
use super::super::interface::ComponentInterface;
|
||||
|
@ -23,23 +18,18 @@ use super::super::interface::ComponentInterface;
|
|||
pub fn write_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: &Path,
|
||||
out_dir: &Utf8Path,
|
||||
try_format_code: bool,
|
||||
) -> Result<()> {
|
||||
let mut rb_file = PathBuf::from(out_dir);
|
||||
rb_file.push(format!("{}.rb", ci.namespace()));
|
||||
let mut f = File::create(&rb_file).context("Failed to create .rb file for bindings")?;
|
||||
let rb_file = out_dir.join(format!("{}.rb", ci.namespace()));
|
||||
let mut f = File::create(&rb_file)?;
|
||||
write!(f, "{}", generate_ruby_bindings(config, ci)?)?;
|
||||
|
||||
if try_format_code {
|
||||
if let Err(e) = Command::new("rubocop")
|
||||
.arg("-A")
|
||||
.arg(rb_file.to_str().unwrap())
|
||||
.output()
|
||||
{
|
||||
if let Err(e) = Command::new("rubocop").arg("-A").arg(&rb_file).output() {
|
||||
println!(
|
||||
"Warning: Unable to auto-format {} using rubocop: {:?}",
|
||||
rb_file.file_name().unwrap().to_str().unwrap(),
|
||||
rb_file.file_name().unwrap(),
|
||||
e
|
||||
)
|
||||
}
|
||||
|
@ -54,16 +44,17 @@ pub fn generate_ruby_bindings(config: &Config, ci: &ComponentInterface) -> Resul
|
|||
use askama::Template;
|
||||
RubyWrapper::new(config.clone(), ci)
|
||||
.render()
|
||||
.map_err(|_| anyhow::anyhow!("failed to render ruby bindings"))
|
||||
.context("failed to render ruby bindings")
|
||||
}
|
||||
|
||||
/// Execute the specifed ruby script, with environment based on the generated
|
||||
/// artifacts in the given output directory.
|
||||
pub fn run_script(out_dir: &Path, script_file: &Path) -> Result<()> {
|
||||
pub fn run_script(out_dir: &Utf8Path, script_file: &Utf8Path) -> Result<()> {
|
||||
let mut cmd = Command::new("ruby");
|
||||
// This helps ruby find the generated .rb wrapper for rust component.
|
||||
let rubypath = env::var_os("RUBYLIB").unwrap_or_else(|| OsString::from(""));
|
||||
let rubypath = env::join_paths(env::split_paths(&rubypath).chain(vec![out_dir.to_path_buf()]))?;
|
||||
let rubypath = env::var_os("RUBYLIB").unwrap_or_default();
|
||||
let rubypath =
|
||||
env::join_paths(env::split_paths(&rubypath).chain(vec![out_dir.as_std_path().to_owned()]))?;
|
||||
|
||||
cmd.env("RUBYLIB", rubypath);
|
||||
// We should now be able to execute the tests successfully.
|
||||
|
|
|
@ -19,7 +19,7 @@ end
|
|||
CALL_SUCCESS = 0
|
||||
CALL_ERROR = 1
|
||||
CALL_PANIC = 2
|
||||
{%- for e in ci.iter_error_definitions() %}
|
||||
{%- for e in ci.error_definitions() %}
|
||||
{% if e.is_flat() %}
|
||||
class {{ e.name()|class_name_rb }}
|
||||
{%- for variant in e.variants() %}
|
||||
|
@ -47,7 +47,7 @@ end
|
|||
|
||||
# Map error modules to the RustBuffer method name that reads them
|
||||
ERROR_MODULE_TO_READER_METHOD = {
|
||||
{%- for e in ci.iter_error_definitions() %}
|
||||
{%- for e in ci.error_definitions() %}
|
||||
{%- let typ=ci.get_type(e.name()).unwrap() %}
|
||||
{%- let canonical_type_name = typ.canonical_name().borrow()|class_name_rb %}
|
||||
{{ e.name()|class_name_rb }} => :read{{ canonical_type_name }},
|
||||
|
|
|
@ -7,7 +7,7 @@ def self.{{ func.name()|fn_name_rb }}({%- call rb::arg_list_decl(func) -%})
|
|||
return {{ "result"|lift_rb(return_type) }}
|
||||
end
|
||||
|
||||
{% when None -%}
|
||||
{% when None %}
|
||||
|
||||
def self.{{ func.name()|fn_name_rb }}({%- call rb::arg_list_decl(func) -%})
|
||||
{%- call rb::coerce_args(func) %}
|
||||
|
|
|
@ -27,19 +27,19 @@ module {{ ci.namespace()|class_name_rb }}
|
|||
|
||||
# Public interface members begin here.
|
||||
|
||||
{% for e in ci.iter_enum_definitions() %}
|
||||
{% for e in ci.enum_definitions() %}
|
||||
{% include "EnumTemplate.rb" %}
|
||||
{%- endfor -%}
|
||||
|
||||
{%- for rec in ci.iter_record_definitions() %}
|
||||
{%- for rec in ci.record_definitions() %}
|
||||
{% include "RecordTemplate.rb" %}
|
||||
{% endfor %}
|
||||
|
||||
{% for func in ci.iter_function_definitions() %}
|
||||
{% for func in ci.function_definitions() %}
|
||||
{% include "TopLevelFunctionTemplate.rb" %}
|
||||
{% endfor %}
|
||||
|
||||
{% for obj in ci.iter_object_definitions() %}
|
||||
{% for obj in ci.object_definitions() %}
|
||||
{% include "ObjectTemplate.rb" %}
|
||||
{% endfor %}
|
||||
end
|
||||
|
|
|
@ -2,12 +2,7 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{CallbackInterface, ComponentInterface};
|
||||
use askama::Template;
|
||||
|
||||
use super::filters;
|
||||
use super::Config;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
|
||||
pub struct CallbackInterfaceCodeType {
|
||||
id: String,
|
||||
|
@ -27,74 +22,4 @@ impl CodeType for CallbackInterfaceCodeType {
|
|||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!("CallbackInterface{}", self.type_label(oracle))
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, _literal: &Literal) -> String {
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(
|
||||
syntax = "swift",
|
||||
escape = "none",
|
||||
path = "CallbackInterfaceTemplate.swift"
|
||||
)]
|
||||
pub struct SwiftCallbackInterface {
|
||||
inner: CallbackInterface,
|
||||
config: Config,
|
||||
}
|
||||
|
||||
impl SwiftCallbackInterface {
|
||||
pub fn new(inner: CallbackInterface, _ci: &ComponentInterface, config: Config) -> Self {
|
||||
Self { inner, config }
|
||||
}
|
||||
pub fn inner(&self) -> &CallbackInterface {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftCallbackInterface {
|
||||
fn initialization_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn imports(&self, _oracle: &dyn CodeOracle) -> Option<Vec<String>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(
|
||||
syntax = "swift",
|
||||
escape = "none",
|
||||
path = "CallbackInterfaceRuntime.swift"
|
||||
)]
|
||||
pub struct SwiftCallbackInterfaceRuntime {
|
||||
is_needed: bool,
|
||||
}
|
||||
|
||||
impl SwiftCallbackInterfaceRuntime {
|
||||
pub fn new(ci: &ComponentInterface) -> Self {
|
||||
Self {
|
||||
is_needed: !ci.iter_callback_interface_definitions().is_empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftCallbackInterfaceRuntime {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
if !self.is_needed {
|
||||
None
|
||||
} else {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,103 +3,72 @@
|
|||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
use crate::backend::{CodeOracle, CodeType, Literal, TypeIdentifier};
|
||||
use askama::Template;
|
||||
use paste::paste;
|
||||
|
||||
// Used in template files.
|
||||
use super::filters;
|
||||
pub struct OptionalCodeType {
|
||||
inner: TypeIdentifier,
|
||||
}
|
||||
|
||||
fn render_literal(oracle: &dyn CodeOracle, literal: &Literal, inner: &TypeIdentifier) -> String {
|
||||
match literal {
|
||||
Literal::Null => "nil".into(),
|
||||
Literal::EmptySequence => "[]".into(),
|
||||
Literal::EmptyMap => "[:]".into(),
|
||||
|
||||
// For optionals
|
||||
_ => oracle.find(inner).literal(oracle, literal),
|
||||
impl OptionalCodeType {
|
||||
pub fn new(inner: TypeIdentifier) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_code_type_for_compound {
|
||||
($T:ty, $type_label_pattern:literal, $canonical_name_pattern:literal, $template_file:literal) => {
|
||||
paste! {
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = $template_file)]
|
||||
pub struct $T {
|
||||
inner: TypeIdentifier,
|
||||
outer: TypeIdentifier,
|
||||
}
|
||||
impl CodeType for OptionalCodeType {
|
||||
fn type_label(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!("{}?", oracle.find(&self.inner).type_label(oracle))
|
||||
}
|
||||
|
||||
impl $T {
|
||||
pub fn new(inner: TypeIdentifier, outer: TypeIdentifier) -> Self {
|
||||
Self { inner, outer }
|
||||
}
|
||||
fn inner(&self) -> &TypeIdentifier {
|
||||
&self.inner
|
||||
}
|
||||
fn outer(&self) -> &TypeIdentifier {
|
||||
&self.outer
|
||||
}
|
||||
}
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!("Option{}", oracle.find(&self.inner).canonical_name(oracle))
|
||||
}
|
||||
|
||||
impl CodeType for $T {
|
||||
fn type_label(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!($type_label_pattern, oracle.find(self.inner()).type_label(oracle))
|
||||
}
|
||||
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!($canonical_name_pattern, oracle.find(self.inner()).canonical_name(oracle))
|
||||
}
|
||||
|
||||
fn literal(&self, oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
render_literal(oracle, literal, self.inner())
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
fn literal(&self, oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
match literal {
|
||||
Literal::Null => "nil".into(),
|
||||
_ => oracle.find(&self.inner).literal(oracle, literal),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_code_type_for_compound!(
|
||||
OptionalCodeType,
|
||||
"{}?",
|
||||
"Option{}",
|
||||
"OptionalTemplate.swift"
|
||||
);
|
||||
pub struct SequenceCodeType {
|
||||
inner: TypeIdentifier,
|
||||
}
|
||||
|
||||
impl_code_type_for_compound!(
|
||||
SequenceCodeType,
|
||||
"[{}]",
|
||||
"Sequence{}",
|
||||
"SequenceTemplate.swift"
|
||||
);
|
||||
impl SequenceCodeType {
|
||||
pub fn new(inner: TypeIdentifier) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeType for SequenceCodeType {
|
||||
fn type_label(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!("[{}]", oracle.find(&self.inner).type_label(oracle))
|
||||
}
|
||||
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!(
|
||||
"Sequence{}",
|
||||
oracle.find(&self.inner).canonical_name(oracle)
|
||||
)
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
match literal {
|
||||
Literal::EmptySequence => "[]".into(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = "MapTemplate.swift")]
|
||||
pub struct MapCodeType {
|
||||
key: TypeIdentifier,
|
||||
value: TypeIdentifier,
|
||||
outer: TypeIdentifier,
|
||||
}
|
||||
|
||||
impl MapCodeType {
|
||||
pub fn new(key: TypeIdentifier, value: TypeIdentifier, outer: TypeIdentifier) -> Self {
|
||||
Self { key, value, outer }
|
||||
}
|
||||
|
||||
fn key(&self) -> &TypeIdentifier {
|
||||
&self.key
|
||||
}
|
||||
|
||||
fn value(&self) -> &TypeIdentifier {
|
||||
&self.value
|
||||
}
|
||||
|
||||
fn outer(&self) -> &TypeIdentifier {
|
||||
&self.outer
|
||||
pub fn new(key: TypeIdentifier, value: TypeIdentifier) -> Self {
|
||||
Self { key, value }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -107,24 +76,23 @@ impl CodeType for MapCodeType {
|
|||
fn type_label(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!(
|
||||
"[{}: {}]",
|
||||
oracle.find(self.key()).type_label(oracle),
|
||||
oracle.find(self.value()).type_label(oracle)
|
||||
oracle.find(&self.key).type_label(oracle),
|
||||
oracle.find(&self.value).type_label(oracle)
|
||||
)
|
||||
}
|
||||
|
||||
fn canonical_name(&self, oracle: &dyn CodeOracle) -> String {
|
||||
format!(
|
||||
"Dictionary{}{}",
|
||||
oracle.find(self.key()).type_label(oracle),
|
||||
oracle.find(self.value()).type_label(oracle)
|
||||
oracle.find(&self.key).type_label(oracle),
|
||||
oracle.find(&self.value).type_label(oracle)
|
||||
)
|
||||
}
|
||||
|
||||
fn literal(&self, oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
render_literal(oracle, literal, self.value())
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
match literal {
|
||||
Literal::EmptyMap => "[:]".into(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,11 +2,7 @@
|
|||
* 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 super::{filters, CustomTypeConfig};
|
||||
use crate::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{FFIType, Type};
|
||||
use askama::Template;
|
||||
use std::borrow::Borrow;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
|
||||
pub struct CustomCodeType {
|
||||
name: String,
|
||||
|
@ -26,51 +22,4 @@ impl CodeType for CustomCodeType {
|
|||
fn canonical_name(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
format!("Type{}", self.name)
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, _literal: &Literal) -> String {
|
||||
// No such thing as a literal custom type
|
||||
unreachable!("Can't have a literal of a custom type");
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"// Helper code for {} is found in CustomType.py",
|
||||
self.name,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = "CustomType.swift")]
|
||||
pub struct SwiftCustomType {
|
||||
name: String,
|
||||
builtin: Type,
|
||||
config: Option<CustomTypeConfig>,
|
||||
}
|
||||
|
||||
impl SwiftCustomType {
|
||||
pub fn new(name: String, builtin: Type, config: Option<CustomTypeConfig>) -> Self {
|
||||
SwiftCustomType {
|
||||
name,
|
||||
builtin,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
fn builtin_ffi_type(&self) -> FFIType {
|
||||
FFIType::from(&self.builtin)
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftCustomType {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn imports(&self, _oracle: &dyn CodeOracle) -> Option<Vec<String>> {
|
||||
match &self.config {
|
||||
None => None,
|
||||
Some(custom_type_config) => custom_type_config.imports.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,11 +2,8 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Enum};
|
||||
use askama::Template;
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
|
||||
use super::filters;
|
||||
pub struct EnumCodeType {
|
||||
id: String,
|
||||
}
|
||||
|
@ -33,39 +30,4 @@ impl CodeType for EnumCodeType {
|
|||
unreachable!();
|
||||
}
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"// Helper code for {} enum is found in EnumTemplate.swift",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = "EnumTemplate.swift")]
|
||||
pub struct SwiftEnum {
|
||||
inner: Enum,
|
||||
contains_object_references: bool,
|
||||
}
|
||||
|
||||
impl SwiftEnum {
|
||||
pub fn new(inner: Enum, ci: &ComponentInterface) -> Self {
|
||||
Self {
|
||||
contains_object_references: ci.item_contains_object_references(&inner),
|
||||
inner,
|
||||
}
|
||||
}
|
||||
pub fn inner(&self) -> &Enum {
|
||||
&self.inner
|
||||
}
|
||||
pub fn contains_object_references(&self) -> bool {
|
||||
self.contains_object_references
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftEnum {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,12 +2,8 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Error, Type};
|
||||
use askama::Template;
|
||||
use std::borrow::Borrow;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
|
||||
use super::filters;
|
||||
pub struct ErrorCodeType {
|
||||
id: String,
|
||||
}
|
||||
|
@ -26,43 +22,4 @@ impl CodeType for ErrorCodeType {
|
|||
fn canonical_name(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
format!("Type{}", self.id)
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, _literal: &Literal) -> String {
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"// Helper code for {} error is found in ErrorTemplate.swift",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = "ErrorTemplate.swift")]
|
||||
pub struct SwiftError {
|
||||
inner: Error,
|
||||
contains_object_references: bool,
|
||||
}
|
||||
|
||||
impl SwiftError {
|
||||
pub fn new(inner: Error, ci: &ComponentInterface) -> Self {
|
||||
Self {
|
||||
contains_object_references: ci.item_contains_object_references(&inner),
|
||||
inner,
|
||||
}
|
||||
}
|
||||
pub fn inner(&self) -> &Error {
|
||||
&self.inner
|
||||
}
|
||||
pub fn contains_object_references(&self) -> bool {
|
||||
self.contains_object_references
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftError {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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 crate::backend::{CodeDeclaration, CodeOracle};
|
||||
use crate::interface::{ComponentInterface, Function};
|
||||
use askama::Template;
|
||||
|
||||
use super::filters;
|
||||
use super::Config;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(
|
||||
syntax = "swift",
|
||||
escape = "none",
|
||||
path = "TopLevelFunctionTemplate.swift"
|
||||
)]
|
||||
pub struct SwiftFunction {
|
||||
inner: Function,
|
||||
config: Config,
|
||||
}
|
||||
|
||||
impl SwiftFunction {
|
||||
pub fn new(inner: Function, _ci: &ComponentInterface, config: Config) -> Self {
|
||||
Self { inner, config }
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &Function {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftFunction {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
|
@ -2,64 +2,28 @@
|
|||
* 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::backend::{CodeOracle, CodeType, Literal};
|
||||
use askama::Template;
|
||||
use paste::paste;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::filters;
|
||||
pub struct TimestampCodeType;
|
||||
|
||||
macro_rules! impl_code_type_for_miscellany {
|
||||
($T:ty, $class_name:literal, $canonical_name:literal, $imports:expr, $template_file:literal) => {
|
||||
paste! {
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = $template_file)]
|
||||
pub struct $T;
|
||||
impl CodeType for TimestampCodeType {
|
||||
fn type_label(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
"Date".into()
|
||||
}
|
||||
|
||||
impl CodeType for $T {
|
||||
fn type_label(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
$class_name.into()
|
||||
}
|
||||
|
||||
fn canonical_name(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
$canonical_name.into()
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, _literal: &Literal) -> String {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn imports(&self, _oracle: &dyn CodeOracle) -> Option<Vec<String>> {
|
||||
let imports: Vec<&str> = $imports;
|
||||
if (!imports.is_empty()) {
|
||||
Some(
|
||||
imports.into_iter().map(|s| s.into()).collect()
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
fn canonical_name(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
"Timestamp".into()
|
||||
}
|
||||
}
|
||||
|
||||
impl_code_type_for_miscellany!(
|
||||
TimestampCodeType,
|
||||
"Date",
|
||||
"Timestamp",
|
||||
vec![],
|
||||
"TimestampHelper.swift"
|
||||
);
|
||||
pub struct DurationCodeType;
|
||||
|
||||
impl_code_type_for_miscellany!(
|
||||
DurationCodeType,
|
||||
"TimeInterval",
|
||||
"Duration",
|
||||
vec![],
|
||||
"DurationHelper.swift"
|
||||
);
|
||||
impl CodeType for DurationCodeType {
|
||||
fn type_label(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
"TimeInterval".into()
|
||||
}
|
||||
|
||||
fn canonical_name(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
"Duration".into()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,15 +3,16 @@
|
|||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use anyhow::{Context, Result};
|
||||
use askama::Template;
|
||||
use heck::{ToLowerCamelCase, ToUpperCamelCase};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Bindings;
|
||||
use crate::backend::{CodeDeclaration, CodeOracle, CodeType, TemplateExpression, TypeIdentifier};
|
||||
use crate::backend::{CodeOracle, CodeType, TemplateExpression, TypeIdentifier};
|
||||
use crate::interface::*;
|
||||
use crate::MergeWith;
|
||||
|
||||
|
@ -20,7 +21,6 @@ mod compounds;
|
|||
mod custom;
|
||||
mod enum_;
|
||||
mod error;
|
||||
mod function;
|
||||
mod miscellany;
|
||||
mod object;
|
||||
mod primitives;
|
||||
|
@ -140,15 +140,15 @@ impl MergeWith for Config {
|
|||
pub fn generate_bindings(config: &Config, ci: &ComponentInterface) -> Result<Bindings> {
|
||||
let header = BridgingHeader::new(config, ci)
|
||||
.render()
|
||||
.map_err(|_| anyhow!("failed to render Swift bridging header"))?;
|
||||
let library = SwiftWrapper::new(SwiftCodeOracle, config.clone(), ci)
|
||||
.context("failed to render Swift bridging header")?;
|
||||
let library = SwiftWrapper::new(config.clone(), ci)
|
||||
.render()
|
||||
.map_err(|_| anyhow!("failed to render Swift library"))?;
|
||||
.context("failed to render Swift library")?;
|
||||
let modulemap = if config.generate_module_map() {
|
||||
Some(
|
||||
ModuleMap::new(config, ci)
|
||||
.render()
|
||||
.map_err(|_| anyhow!("failed to render Swift modulemap"))?,
|
||||
.context("failed to render Swift modulemap")?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
|
@ -160,6 +160,55 @@ pub fn generate_bindings(config: &Config, ci: &ComponentInterface) -> Result<Bin
|
|||
})
|
||||
}
|
||||
|
||||
/// Renders Swift helper code for all types
|
||||
///
|
||||
/// This template is a bit different than others in that it stores internal state from the render
|
||||
/// process. Make sure to only call `render()` once.
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "kt", escape = "none", path = "Types.swift")]
|
||||
pub struct TypeRenderer<'a> {
|
||||
config: &'a Config,
|
||||
ci: &'a ComponentInterface,
|
||||
// Track included modules for the `include_once()` macro
|
||||
include_once_names: RefCell<HashSet<String>>,
|
||||
// Track imports added with the `add_import()` macro
|
||||
imports: RefCell<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
impl<'a> TypeRenderer<'a> {
|
||||
fn new(config: &'a Config, ci: &'a ComponentInterface) -> Self {
|
||||
Self {
|
||||
config,
|
||||
ci,
|
||||
include_once_names: RefCell::new(HashSet::new()),
|
||||
imports: RefCell::new(BTreeSet::new()),
|
||||
}
|
||||
}
|
||||
|
||||
// The following methods are used by the `Types.kt` macros.
|
||||
|
||||
// Helper for the including a template, but only once.
|
||||
//
|
||||
// The first time this is called with a name it will return true, indicating that we should
|
||||
// include the template. Subsequent calls will return false.
|
||||
fn include_once_check(&self, name: &str) -> bool {
|
||||
self.include_once_names
|
||||
.borrow_mut()
|
||||
.insert(name.to_string())
|
||||
}
|
||||
|
||||
// Helper to add an import statement
|
||||
//
|
||||
// Call this inside your template to cause an import statement to be added at the top of the
|
||||
// file. Imports will be sorted and de-deuped.
|
||||
//
|
||||
// Returns an empty string so that it can be used inside an askama `{{ }}` block.
|
||||
fn add_import(&self, name: &str) -> &str {
|
||||
self.imports.borrow_mut().insert(name.to_owned());
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Template for generating the `.h` file that defines the low-level C FFI.
|
||||
///
|
||||
/// This file defines only the low-level structs and functions that are exposed
|
||||
|
@ -205,103 +254,32 @@ impl<'config, 'ci> ModuleMap<'config, 'ci> {
|
|||
pub struct SwiftWrapper<'a> {
|
||||
config: Config,
|
||||
ci: &'a ComponentInterface,
|
||||
oracle: SwiftCodeOracle,
|
||||
type_helper_code: String,
|
||||
type_imports: BTreeSet<String>,
|
||||
}
|
||||
impl<'a> SwiftWrapper<'a> {
|
||||
pub fn new(oracle: SwiftCodeOracle, config: Config, ci: &'a ComponentInterface) -> Self {
|
||||
Self { oracle, config, ci }
|
||||
}
|
||||
|
||||
pub fn members(&self) -> Vec<Box<dyn CodeDeclaration + 'a>> {
|
||||
let ci = self.ci;
|
||||
vec![
|
||||
Box::new(callback_interface::SwiftCallbackInterfaceRuntime::new(ci))
|
||||
as Box<dyn CodeDeclaration>,
|
||||
]
|
||||
.into_iter()
|
||||
.chain(
|
||||
ci.iter_enum_definitions().into_iter().map(|inner| {
|
||||
Box::new(enum_::SwiftEnum::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}),
|
||||
)
|
||||
.chain(ci.iter_function_definitions().into_iter().map(|inner| {
|
||||
Box::new(function::SwiftFunction::new(inner, ci, self.config.clone()))
|
||||
as Box<dyn CodeDeclaration>
|
||||
}))
|
||||
.chain(ci.iter_object_definitions().into_iter().map(|inner| {
|
||||
Box::new(object::SwiftObject::new(inner, ci, self.config.clone()))
|
||||
as Box<dyn CodeDeclaration>
|
||||
}))
|
||||
.chain(
|
||||
ci.iter_record_definitions().into_iter().map(|inner| {
|
||||
Box::new(record::SwiftRecord::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}),
|
||||
)
|
||||
.chain(
|
||||
ci.iter_error_definitions().into_iter().map(|inner| {
|
||||
Box::new(error::SwiftError::new(inner, ci)) as Box<dyn CodeDeclaration>
|
||||
}),
|
||||
)
|
||||
.chain(
|
||||
ci.iter_callback_interface_definitions()
|
||||
.into_iter()
|
||||
.map(|inner| {
|
||||
Box::new(callback_interface::SwiftCallbackInterface::new(
|
||||
inner,
|
||||
ci,
|
||||
self.config.clone(),
|
||||
)) as Box<dyn CodeDeclaration>
|
||||
}),
|
||||
)
|
||||
.chain(ci.iter_custom_types().into_iter().map(|(name, type_)| {
|
||||
let config = self.config.custom_types.get(&name).cloned();
|
||||
Box::new(custom::SwiftCustomType::new(name, type_, config)) as Box<dyn CodeDeclaration>
|
||||
}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn initialization_code(&self) -> Vec<String> {
|
||||
let oracle = &self.oracle;
|
||||
self.members()
|
||||
.into_iter()
|
||||
.filter_map(|member| member.initialization_code(oracle))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn declaration_code(&self) -> Vec<String> {
|
||||
let oracle = &self.oracle;
|
||||
self.members()
|
||||
.into_iter()
|
||||
.filter_map(|member| member.definition_code(oracle))
|
||||
.chain(
|
||||
self.ci
|
||||
.iter_types()
|
||||
.into_iter()
|
||||
.filter_map(|type_| oracle.find(&type_).helper_code(oracle)),
|
||||
)
|
||||
.collect()
|
||||
pub fn new(config: Config, ci: &'a ComponentInterface) -> Self {
|
||||
let type_renderer = TypeRenderer::new(&config, ci);
|
||||
let type_helper_code = type_renderer.render().unwrap();
|
||||
let type_imports = type_renderer.imports.into_inner();
|
||||
Self {
|
||||
config,
|
||||
ci,
|
||||
type_helper_code,
|
||||
type_imports,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn imports(&self) -> Vec<String> {
|
||||
let oracle = &self.oracle;
|
||||
let mut imports: Vec<String> = self
|
||||
.members()
|
||||
.into_iter()
|
||||
.filter_map(|member| member.imports(oracle))
|
||||
.flatten()
|
||||
.chain(
|
||||
self.ci
|
||||
.iter_types()
|
||||
.into_iter()
|
||||
.filter_map(|type_| oracle.find(&type_).imports(oracle))
|
||||
.flatten(),
|
||||
)
|
||||
.collect::<HashSet<String>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
self.type_imports.iter().cloned().collect()
|
||||
}
|
||||
|
||||
imports.sort();
|
||||
imports
|
||||
pub fn initialization_fns(&self) -> Vec<String> {
|
||||
self.ci
|
||||
.iter_types()
|
||||
.into_iter()
|
||||
.filter_map(|t| t.initialization_fn(&SwiftCodeOracle))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -309,11 +287,14 @@ impl<'a> SwiftWrapper<'a> {
|
|||
pub struct SwiftCodeOracle;
|
||||
|
||||
impl SwiftCodeOracle {
|
||||
// Map `Type` instances to a `Box<dyn CodeType>` for that type.
|
||||
//
|
||||
// There is a companion match in `templates/Types.swift` which performs a similar function for the
|
||||
// template code.
|
||||
//
|
||||
// - When adding additional types here, make sure to also add a match arm to the `Types.swift` template.
|
||||
// - To keep things managable, let's try to limit ourselves to these 2 mega-matches
|
||||
fn create_code_type(&self, type_: TypeIdentifier) -> Box<dyn CodeType> {
|
||||
// I really want access to the ComponentInterface here so I can look up the interface::{Enum, Record, Error, Object, etc}
|
||||
// However, there's some violence and gore I need to do to (temporarily) make the oracle usable from filters.
|
||||
|
||||
// Some refactor of the templates is needed to make progress here: I think most of the filter functions need to take an &dyn CodeOracle
|
||||
match type_ {
|
||||
Type::UInt8 => Box::new(primitives::UInt8CodeType),
|
||||
Type::Int8 => Box::new(primitives::Int8CodeType),
|
||||
|
@ -339,22 +320,9 @@ impl SwiftCodeOracle {
|
|||
Box::new(callback_interface::CallbackInterfaceCodeType::new(id))
|
||||
}
|
||||
|
||||
Type::Optional(ref inner) => {
|
||||
let outer = type_.clone();
|
||||
let inner = *inner.to_owned();
|
||||
Box::new(compounds::OptionalCodeType::new(inner, outer))
|
||||
}
|
||||
Type::Sequence(ref inner) => {
|
||||
let outer = type_.clone();
|
||||
let inner = *inner.to_owned();
|
||||
Box::new(compounds::SequenceCodeType::new(inner, outer))
|
||||
}
|
||||
Type::Map(ref key, ref value) => {
|
||||
let outer = type_.clone();
|
||||
let key = *key.to_owned();
|
||||
let value = *value.to_owned();
|
||||
Box::new(compounds::MapCodeType::new(key, value, outer))
|
||||
}
|
||||
Type::Optional(inner) => Box::new(compounds::OptionalCodeType::new(*inner)),
|
||||
Type::Sequence(inner) => Box::new(compounds::SequenceCodeType::new(*inner)),
|
||||
Type::Map(key, value) => Box::new(compounds::MapCodeType::new(*key, *value)),
|
||||
Type::External { .. } => panic!("no support for external types yet"),
|
||||
Type::Custom { name, .. } => Box::new(custom::CustomCodeType::new(name)),
|
||||
}
|
||||
|
@ -403,7 +371,7 @@ impl CodeOracle for SwiftCodeOracle {
|
|||
FFIType::UInt64 => "uint64_t".into(),
|
||||
FFIType::Float32 => "float".into(),
|
||||
FFIType::Float64 => "double".into(),
|
||||
FFIType::RustArcPtr => "void*_Nonnull".into(),
|
||||
FFIType::RustArcPtr(_) => "void*_Nonnull".into(),
|
||||
FFIType::RustBuffer => "RustBuffer".into(),
|
||||
FFIType::ForeignBytes => "ForeignBytes".into(),
|
||||
FFIType::ForeignCallback => "ForeignCallback _Nonnull".to_string(),
|
||||
|
@ -475,7 +443,7 @@ pub mod filters {
|
|||
FFIType::UInt64 => "UInt64".into(),
|
||||
FFIType::Float32 => "float".into(),
|
||||
FFIType::Float64 => "double".into(),
|
||||
FFIType::RustArcPtr => "void*_Nonnull".into(),
|
||||
FFIType::RustArcPtr(_) => "void*_Nonnull".into(),
|
||||
FFIType::RustBuffer => "RustBuffer".into(),
|
||||
FFIType::ForeignBytes => "ForeignBytes".into(),
|
||||
FFIType::ForeignCallback => "ForeignCallback _Nonnull".to_string(),
|
||||
|
|
|
@ -2,12 +2,7 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Object};
|
||||
use askama::Template;
|
||||
|
||||
use super::filters;
|
||||
use super::Config;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
|
||||
pub struct ObjectCodeType {
|
||||
id: String,
|
||||
|
@ -27,42 +22,4 @@ impl CodeType for ObjectCodeType {
|
|||
fn canonical_name(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
format!("Type{}", self.id)
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, _literal: &Literal) -> String {
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"// Helper code for {} class is found in ObjectTemplate.swift",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = "ObjectTemplate.swift")]
|
||||
pub struct SwiftObject {
|
||||
config: Config,
|
||||
inner: Object,
|
||||
}
|
||||
|
||||
impl SwiftObject {
|
||||
pub fn new(inner: Object, _ci: &ComponentInterface, config: Config) -> Self {
|
||||
Self { inner, config }
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &Object {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftObject {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
|
||||
fn imports(&self, _oracle: &dyn CodeOracle) -> Option<Vec<String>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,12 +4,8 @@
|
|||
|
||||
use crate::backend::{CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{types::Type, Radix};
|
||||
use askama::Template;
|
||||
use paste::paste;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::filters;
|
||||
|
||||
fn render_literal(oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
fn typed_number(oracle: &dyn CodeOracle, type_: &Type, num_str: String) -> String {
|
||||
match type_ {
|
||||
|
@ -60,10 +56,8 @@ fn render_literal(oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
|||
}
|
||||
|
||||
macro_rules! impl_code_type_for_primitive {
|
||||
($T:ty, $class_name:literal, $template_file:literal) => {
|
||||
($T:ty, $class_name:literal) => {
|
||||
paste! {
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = $template_file)]
|
||||
pub struct $T;
|
||||
|
||||
impl CodeType for $T {
|
||||
|
@ -74,24 +68,20 @@ macro_rules! impl_code_type_for_primitive {
|
|||
fn literal(&self, oracle: &dyn CodeOracle, literal: &Literal) -> String {
|
||||
render_literal(oracle, &literal)
|
||||
}
|
||||
|
||||
fn helper_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_code_type_for_primitive!(BooleanCodeType, "Bool", "BooleanHelper.swift");
|
||||
impl_code_type_for_primitive!(StringCodeType, "String", "StringHelper.swift");
|
||||
impl_code_type_for_primitive!(Int8CodeType, "Int8", "Int8Helper.swift");
|
||||
impl_code_type_for_primitive!(Int16CodeType, "Int16", "Int16Helper.swift");
|
||||
impl_code_type_for_primitive!(Int32CodeType, "Int32", "Int32Helper.swift");
|
||||
impl_code_type_for_primitive!(Int64CodeType, "Int64", "Int64Helper.swift");
|
||||
impl_code_type_for_primitive!(UInt8CodeType, "UInt8", "UInt8Helper.swift");
|
||||
impl_code_type_for_primitive!(UInt16CodeType, "UInt16", "UInt16Helper.swift");
|
||||
impl_code_type_for_primitive!(UInt32CodeType, "UInt32", "UInt32Helper.swift");
|
||||
impl_code_type_for_primitive!(UInt64CodeType, "UInt64", "UInt64Helper.swift");
|
||||
impl_code_type_for_primitive!(Float32CodeType, "Float", "Float32Helper.swift");
|
||||
impl_code_type_for_primitive!(Float64CodeType, "Double", "Float64Helper.swift");
|
||||
impl_code_type_for_primitive!(BooleanCodeType, "Bool");
|
||||
impl_code_type_for_primitive!(StringCodeType, "String");
|
||||
impl_code_type_for_primitive!(Int8CodeType, "Int8");
|
||||
impl_code_type_for_primitive!(Int16CodeType, "Int16");
|
||||
impl_code_type_for_primitive!(Int32CodeType, "Int32");
|
||||
impl_code_type_for_primitive!(Int64CodeType, "Int64");
|
||||
impl_code_type_for_primitive!(UInt8CodeType, "UInt8");
|
||||
impl_code_type_for_primitive!(UInt16CodeType, "UInt16");
|
||||
impl_code_type_for_primitive!(UInt32CodeType, "UInt32");
|
||||
impl_code_type_for_primitive!(UInt64CodeType, "UInt64");
|
||||
impl_code_type_for_primitive!(Float32CodeType, "Float");
|
||||
impl_code_type_for_primitive!(Float64CodeType, "Double");
|
||||
|
|
|
@ -2,11 +2,8 @@
|
|||
* 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::backend::{CodeDeclaration, CodeOracle, CodeType, Literal};
|
||||
use crate::interface::{ComponentInterface, Record};
|
||||
use askama::Template;
|
||||
use crate::backend::{CodeOracle, CodeType};
|
||||
|
||||
use super::filters;
|
||||
pub struct RecordCodeType {
|
||||
id: String,
|
||||
}
|
||||
|
@ -25,43 +22,4 @@ impl CodeType for RecordCodeType {
|
|||
fn canonical_name(&self, _oracle: &dyn CodeOracle) -> String {
|
||||
format!("Type{}", self.id)
|
||||
}
|
||||
|
||||
fn literal(&self, _oracle: &dyn CodeOracle, _literal: &Literal) -> String {
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
fn helper_code(&self, oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(format!(
|
||||
"// Helper code for {} record is found in RecordTemplate.swift",
|
||||
self.type_label(oracle)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(syntax = "swift", escape = "none", path = "RecordTemplate.swift")]
|
||||
pub struct SwiftRecord {
|
||||
inner: Record,
|
||||
contains_object_references: bool,
|
||||
}
|
||||
|
||||
impl SwiftRecord {
|
||||
pub fn new(inner: Record, ci: &ComponentInterface) -> Self {
|
||||
Self {
|
||||
contains_object_references: ci.item_contains_object_references(&inner),
|
||||
inner,
|
||||
}
|
||||
}
|
||||
pub fn inner(&self) -> &Record {
|
||||
&self.inner
|
||||
}
|
||||
pub fn contains_object_references(&self) -> bool {
|
||||
self.contains_object_references
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeDeclaration for SwiftRecord {
|
||||
fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
|
||||
Some(self.render().unwrap())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,14 +29,11 @@
|
|||
//! * How to read from and write into a byte buffer.
|
||||
//!
|
||||
|
||||
use std::{ffi::OsString, io::Write, process::Command};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
fs::File,
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
use camino::Utf8Path;
|
||||
use fs_err::File;
|
||||
|
||||
pub mod gen_swift;
|
||||
pub use gen_swift::{generate_bindings, Config};
|
||||
|
@ -62,43 +59,35 @@ pub struct Bindings {
|
|||
pub fn write_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: &Path,
|
||||
out_dir: &Utf8Path,
|
||||
try_format_code: bool,
|
||||
) -> Result<()> {
|
||||
let out_path = PathBuf::from(out_dir);
|
||||
|
||||
let Bindings {
|
||||
header,
|
||||
library,
|
||||
modulemap,
|
||||
} = generate_bindings(config, ci)?;
|
||||
|
||||
let mut source_file = out_path.clone();
|
||||
source_file.push(format!("{}.swift", config.module_name()));
|
||||
let mut l = File::create(&source_file).context("Failed to create .swift file for bindings")?;
|
||||
let source_file = out_dir.join(format!("{}.swift", config.module_name()));
|
||||
let mut l = File::create(&source_file)?;
|
||||
write!(l, "{}", library)?;
|
||||
|
||||
let mut header_file = out_path.clone();
|
||||
header_file.push(config.header_filename());
|
||||
let mut h = File::create(&header_file).context("Failed to create .h file for bindings")?;
|
||||
let mut h = File::create(out_dir.join(config.header_filename()))?;
|
||||
write!(h, "{}", header)?;
|
||||
|
||||
if let Some(modulemap) = modulemap {
|
||||
let mut modulemap_file = out_path;
|
||||
modulemap_file.push(config.modulemap_filename());
|
||||
let mut m = File::create(&modulemap_file)
|
||||
.context("Failed to create .modulemap file for bindings")?;
|
||||
let mut m = File::create(out_dir.join(config.modulemap_filename()))?;
|
||||
write!(m, "{}", modulemap)?;
|
||||
}
|
||||
|
||||
if try_format_code {
|
||||
if let Err(e) = Command::new("swiftformat")
|
||||
.arg(source_file.to_str().unwrap())
|
||||
.arg(source_file.as_str())
|
||||
.output()
|
||||
{
|
||||
println!(
|
||||
"Warning: Unable to auto-format {} using swiftformat: {:?}",
|
||||
source_file.file_name().unwrap().to_str().unwrap(),
|
||||
source_file.file_name().unwrap(),
|
||||
e
|
||||
)
|
||||
}
|
||||
|
@ -115,23 +104,21 @@ pub fn write_bindings(
|
|||
/// test scripts need to be able to import the generated bindings, we have to compile them
|
||||
/// ahead of time before running the tests.
|
||||
///
|
||||
pub fn compile_bindings(config: &Config, ci: &ComponentInterface, out_dir: &Path) -> Result<()> {
|
||||
let out_path = PathBuf::from(out_dir);
|
||||
|
||||
pub fn compile_bindings(
|
||||
config: &Config,
|
||||
ci: &ComponentInterface,
|
||||
out_dir: &Utf8Path,
|
||||
) -> Result<()> {
|
||||
if !config.generate_module_map() {
|
||||
bail!("Cannot compile Swift bindings when `generate_module_map` is `false`")
|
||||
}
|
||||
let mut module_map_file = out_path.clone();
|
||||
module_map_file.push(config.modulemap_filename());
|
||||
|
||||
let module_map_file = out_dir.join(config.modulemap_filename());
|
||||
let mut module_map_file_option = OsString::from("-fmodule-map-file=");
|
||||
module_map_file_option.push(module_map_file.as_os_str());
|
||||
|
||||
let mut source_file = out_path.clone();
|
||||
source_file.push(format!("{}.swift", config.module_name()));
|
||||
|
||||
let mut dylib_file = out_path.clone();
|
||||
dylib_file.push(format!("lib{}.dylib", config.module_name()));
|
||||
let source_file = out_dir.join(format!("{}.swift", config.module_name()));
|
||||
let dylib_file = out_dir.join(format!("lib{}.dylib", config.module_name()));
|
||||
|
||||
// `-emit-library -o <path>` generates a `.dylib`, so that we can use the
|
||||
// Swift module from the REPL. Otherwise, we'll get "Couldn't lookup
|
||||
|
@ -143,13 +130,13 @@ pub fn compile_bindings(config: &Config, ci: &ComponentInterface, out_dir: &Path
|
|||
.arg(ci.namespace())
|
||||
.arg("-emit-library")
|
||||
.arg("-o")
|
||||
.arg(&dylib_file)
|
||||
.arg(dylib_file)
|
||||
.arg("-emit-module")
|
||||
.arg("-emit-module-path")
|
||||
.arg(&out_path)
|
||||
.arg(out_dir)
|
||||
.arg("-parse-as-library")
|
||||
.arg("-L")
|
||||
.arg(&out_path)
|
||||
.arg(out_dir)
|
||||
.arg(format!("-l{}", config.cdylib_name()))
|
||||
.arg("-Xcc")
|
||||
.arg(module_map_file_option)
|
||||
|
@ -170,7 +157,7 @@ pub fn compile_bindings(config: &Config, ci: &ComponentInterface, out_dir: &Path
|
|||
/// Swift modules in the given output directory. The modules must have been pre-compiled
|
||||
/// using the [`compile_bindings`] function.
|
||||
///
|
||||
pub fn run_script(out_dir: &Path, script_file: &Path) -> Result<()> {
|
||||
pub fn run_script(out_dir: &Utf8Path, script_file: &Utf8Path) -> Result<()> {
|
||||
let mut cmd = Command::new("swift");
|
||||
|
||||
// Find any module maps and/or dylibs in the target directory, and tell swift to use them.
|
||||
|
@ -179,7 +166,7 @@ pub fn run_script(out_dir: &Path, script_file: &Path) -> Result<()> {
|
|||
// this test function doesn't allow us to pass that name in to the call.
|
||||
|
||||
cmd.arg("-I").arg(out_dir);
|
||||
for entry in PathBuf::from(out_dir)
|
||||
for entry in out_dir
|
||||
.read_dir()
|
||||
.context("Failed to list target directory when running script")?
|
||||
{
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
{% import "macros.swift" as swift %}
|
||||
{%- let cbi = self.inner() %}
|
||||
{%- let type_name = cbi|type_name %}
|
||||
{%- let canonical_type_name = cbi|canonical_name %}
|
||||
{%- let ffi_converter = cbi|ffi_converter_name %}
|
||||
{%- let cbi = ci.get_callback_interface_definition(name).unwrap() %}
|
||||
{%- let foreign_callback = format!("foreignCallback{}", canonical_type_name) %}
|
||||
{%- if self.include_once_check("CallbackInterfaceRuntime.swift") %}{%- include "CallbackInterfaceRuntime.swift" %}{%- endif %}
|
||||
|
||||
// Declaration and FfiConverters for {{ type_name }} Callback Interface
|
||||
|
||||
|
@ -59,10 +56,10 @@ fileprivate let {{ foreign_callback }} : ForeignCallback =
|
|||
}
|
||||
{% endfor %}
|
||||
|
||||
let cb = try! {{ ffi_converter }}.lift(handle)
|
||||
let cb = try! {{ ffi_converter_name }}.lift(handle)
|
||||
switch method {
|
||||
case IDX_CALLBACK_FREE:
|
||||
{{ ffi_converter }}.drop(handle: handle)
|
||||
{{ ffi_converter_name }}.drop(handle: handle)
|
||||
// No return value.
|
||||
// See docs of ForeignCallback in `uniffi/src/ffi/foreigncallbacks.rs`
|
||||
return 0
|
||||
|
@ -86,7 +83,7 @@ fileprivate let {{ foreign_callback }} : ForeignCallback =
|
|||
}
|
||||
|
||||
// FFIConverter protocol for callback interfaces
|
||||
fileprivate struct {{ ffi_converter }} {
|
||||
fileprivate struct {{ ffi_converter_name }} {
|
||||
// Initialize our callback method with the scaffolding code
|
||||
private static var callbackInitialized = false
|
||||
private static func initCallback() {
|
||||
|
@ -108,7 +105,7 @@ fileprivate struct {{ ffi_converter }} {
|
|||
private static var handleMap = ConcurrentHandleMap<{{ type_name }}>()
|
||||
}
|
||||
|
||||
extension {{ ffi_converter }} : FfiConverter {
|
||||
extension {{ ffi_converter_name }} : FfiConverter {
|
||||
typealias SwiftType = {{ type_name }}
|
||||
// We can use Handle as the FFIType because it's a typealias to UInt64
|
||||
typealias FfiType = Handle
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
{%- match config %}
|
||||
{%- let ffi_type_name=builtin.ffi_type().borrow()|ffi_type_name %}
|
||||
{%- match config.custom_types.get(name.as_str()) %}
|
||||
{%- when None %}
|
||||
{#- No config, just forward all methods to our builtin type #}
|
||||
/**
|
||||
|
@ -21,6 +22,14 @@ public typealias {{ name }} = {{ concrete_type_name }}
|
|||
{%- else %}
|
||||
{%- endmatch %}
|
||||
|
||||
{%- match config.imports %}
|
||||
{%- when Some(imports) %}
|
||||
{%- for import_name in imports %}
|
||||
{{ self.add_import(import_name) }}
|
||||
{%- endfor %}
|
||||
{%- else %}
|
||||
{%- endmatch %}
|
||||
|
||||
fileprivate struct FfiConverterType{{ name }} {
|
||||
{#- Custom type config supplied, use it to convert the builtin type #}
|
||||
|
||||
|
@ -34,12 +43,12 @@ fileprivate struct FfiConverterType{{ name }} {
|
|||
return {{ builtin|write_fn }}(builtinValue, into: buf)
|
||||
}
|
||||
|
||||
static func lift(_ value: {{ self.builtin_ffi_type().borrow()|type_ffi_lowered }}) throws -> {{ name }} {
|
||||
static func lift(_ value: {{ ffi_type_name }}) throws -> {{ name }} {
|
||||
let builtinValue = try {{ builtin|lift_fn }}(value)
|
||||
return {{ config.into_custom.render("builtinValue") }}
|
||||
}
|
||||
|
||||
static func lower(_ value: {{ name }}) -> {{ self.builtin_ffi_type().borrow()|type_ffi_lowered }} {
|
||||
static func lower(_ value: {{ name }}) -> {{ ffi_type_name }} {
|
||||
let builtinValue = {{ config.from_custom.render("value") }}
|
||||
return {{ builtin|lower_fn }}(builtinValue)
|
||||
}
|
||||
|
|
|
@ -1,18 +1,16 @@
|
|||
|
||||
// Note that we don't yet support `indirect` for enums.
|
||||
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
|
||||
{% import "macros.swift" as swift %}
|
||||
{%- let e = self.inner() %}
|
||||
public enum {{ e|type_name }} {
|
||||
{%- let e = ci.get_enum_definition(name).unwrap() %}
|
||||
public enum {{ type_name }} {
|
||||
{% for variant in e.variants() %}
|
||||
case {{ variant.name()|enum_variant_swift }}{% if variant.fields().len() > 0 %}({% call swift::field_list_decl(variant) %}){% endif -%}
|
||||
{% endfor %}
|
||||
}
|
||||
|
||||
fileprivate struct {{ e|ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
typealias SwiftType = {{ e|type_name }}
|
||||
fileprivate struct {{ ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
typealias SwiftType = {{ type_name }}
|
||||
|
||||
static func read(from buf: Reader) throws -> {{ e|type_name }} {
|
||||
static func read(from buf: Reader) throws -> {{ type_name }} {
|
||||
let variant: Int32 = try buf.readInt()
|
||||
switch variant {
|
||||
{% for variant in e.variants() %}
|
||||
|
@ -27,7 +25,7 @@ fileprivate struct {{ e|ffi_converter_name }}: FfiConverterRustBuffer {
|
|||
}
|
||||
}
|
||||
|
||||
static func write(_ value: {{ e|type_name }}, into buf: Writer) {
|
||||
static func write(_ value: {{ type_name }}, into buf: Writer) {
|
||||
switch value {
|
||||
{% for variant in e.variants() %}
|
||||
{% if variant.has_fields() %}
|
||||
|
@ -45,6 +43,6 @@ fileprivate struct {{ e|ffi_converter_name }}: FfiConverterRustBuffer {
|
|||
}
|
||||
}
|
||||
|
||||
{% if ! self.contains_object_references() %}
|
||||
extension {{ e|type_name }}: Equatable, Hashable {}
|
||||
{% if !contains_object_references %}
|
||||
extension {{ type_name }}: Equatable, Hashable {}
|
||||
{% endif %}
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
{% import "macros.swift" as swift %}
|
||||
{%- let e = self.inner() %}
|
||||
public enum {{ e|type_name }} {
|
||||
{%- let e = ci.get_error_definition(name).unwrap() %}
|
||||
public enum {{ type_name }} {
|
||||
|
||||
{% if e.is_flat() %}
|
||||
{% for variant in e.variants() %}
|
||||
|
@ -16,10 +15,10 @@ public enum {{ e|type_name }} {
|
|||
{%- endif %}
|
||||
}
|
||||
|
||||
fileprivate struct {{ e|ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
typealias SwiftType = {{ e|type_name }}
|
||||
fileprivate struct {{ ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
typealias SwiftType = {{ type_name }}
|
||||
|
||||
static func read(from buf: Reader) throws -> {{ e|type_name }} {
|
||||
static func read(from buf: Reader) throws -> {{ type_name }} {
|
||||
let variant: Int32 = try buf.readInt()
|
||||
switch variant {
|
||||
|
||||
|
@ -47,7 +46,7 @@ fileprivate struct {{ e|ffi_converter_name }}: FfiConverterRustBuffer {
|
|||
}
|
||||
}
|
||||
|
||||
static func write(_ value: {{ e|type_name }}, into buf: Writer) {
|
||||
static func write(_ value: {{ type_name }}, into buf: Writer) {
|
||||
switch value {
|
||||
|
||||
{% if e.is_flat() %}
|
||||
|
@ -78,7 +77,7 @@ fileprivate struct {{ e|ffi_converter_name }}: FfiConverterRustBuffer {
|
|||
}
|
||||
}
|
||||
|
||||
{% if !self.contains_object_references() %}
|
||||
extension {{ e|type_name }}: Equatable, Hashable {}
|
||||
{% if !contains_object_references %}
|
||||
extension {{ type_name }}: Equatable, Hashable {}
|
||||
{% endif %}
|
||||
extension {{ e|type_name }}: Error { }
|
||||
extension {{ type_name }}: Error { }
|
||||
|
|
|
@ -1,11 +1,5 @@
|
|||
{%- import "macros.swift" as swift -%}
|
||||
{%- let outer_type = self.outer() %}
|
||||
{%- let dict_type = outer_type|type_name %}
|
||||
{%- let key_type = self.key() %}
|
||||
{%- let value_type = self.value() %}
|
||||
|
||||
fileprivate struct {{ outer_type|ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
fileprivate static func write(_ value: {{ dict_type }}, into buf: Writer) {
|
||||
fileprivate struct {{ ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
fileprivate static func write(_ value: {{ type_name }}, into buf: Writer) {
|
||||
let len = Int32(value.count)
|
||||
buf.writeInt(len)
|
||||
for (key, value) in value {
|
||||
|
@ -14,9 +8,9 @@ fileprivate struct {{ outer_type|ffi_converter_name }}: FfiConverterRustBuffer {
|
|||
}
|
||||
}
|
||||
|
||||
fileprivate static func read(from buf: Reader) throws -> {{ dict_type }} {
|
||||
fileprivate static func read(from buf: Reader) throws -> {{ type_name }} {
|
||||
let len: Int32 = try buf.readInt()
|
||||
var dict = {{ dict_type }}()
|
||||
var dict = {{ type_name }}()
|
||||
dict.reserveCapacity(Int(len))
|
||||
for _ in 0..<len {
|
||||
let key = try {{ key_type|read_fn }}(from: buf)
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
{% import "macros.swift" as swift %}
|
||||
{%- let obj = self.inner() %}
|
||||
{%- let obj = ci.get_object_definition(name).unwrap() %}
|
||||
public protocol {{ obj.name() }}Protocol {
|
||||
{% for meth in obj.methods() -%}
|
||||
func {{ meth.name()|fn_name }}({% call swift::arg_list_protocol(meth) %}) {% call swift::throws(meth) -%}
|
||||
|
@ -10,7 +9,7 @@ public protocol {{ obj.name() }}Protocol {
|
|||
{% endfor %}
|
||||
}
|
||||
|
||||
public class {{ obj|type_name }}: {{ obj.name() }}Protocol {
|
||||
public class {{ type_name }}: {{ obj.name() }}Protocol {
|
||||
fileprivate let pointer: UnsafeMutableRawPointer
|
||||
|
||||
// TODO: We'd like this to be `private` but for Swifty reasons,
|
||||
|
@ -33,8 +32,8 @@ public class {{ obj|type_name }}: {{ obj.name() }}Protocol {
|
|||
}
|
||||
|
||||
{% for cons in obj.alternate_constructors() %}
|
||||
public static func {{ cons.name()|fn_name }}({% call swift::arg_list_decl(cons) %}) {% call swift::throws(cons) %} -> {{ obj|type_name }} {
|
||||
return {{ obj|type_name }}(unsafeFromRawPointer: {% call swift::to_ffi_call(cons) %})
|
||||
public static func {{ cons.name()|fn_name }}({% call swift::arg_list_decl(cons) %}) {% call swift::throws(cons) %} -> {{ type_name }} {
|
||||
return {{ type_name }}(unsafeFromRawPointer: {% call swift::to_ffi_call(cons) %})
|
||||
}
|
||||
{% endfor %}
|
||||
|
||||
|
@ -58,11 +57,11 @@ public class {{ obj|type_name }}: {{ obj.name() }}Protocol {
|
|||
}
|
||||
|
||||
|
||||
fileprivate struct {{ obj|ffi_converter_name }}: FfiConverter {
|
||||
fileprivate struct {{ ffi_converter_name }}: FfiConverter {
|
||||
typealias FfiType = UnsafeMutableRawPointer
|
||||
typealias SwiftType = {{ obj|type_name }}
|
||||
typealias SwiftType = {{ type_name }}
|
||||
|
||||
static func read(from buf: Reader) throws -> {{ obj|type_name }} {
|
||||
static func read(from buf: Reader) throws -> {{ type_name }} {
|
||||
let v: UInt64 = try buf.readInt()
|
||||
// The Rust code won't compile if a pointer won't fit in a UInt64.
|
||||
// We have to go via `UInt` because that's the thing that's the size of a pointer.
|
||||
|
@ -73,17 +72,17 @@ fileprivate struct {{ obj|ffi_converter_name }}: FfiConverter {
|
|||
return try lift(ptr!)
|
||||
}
|
||||
|
||||
static func write(_ value: {{ obj|type_name }}, into buf: Writer) {
|
||||
static func write(_ value: {{ type_name }}, into buf: Writer) {
|
||||
// This fiddling is because `Int` is the thing that's the same size as a pointer.
|
||||
// The Rust code won't compile if a pointer won't fit in a `UInt64`.
|
||||
buf.writeInt(UInt64(bitPattern: Int64(Int(bitPattern: lower(value)))))
|
||||
}
|
||||
|
||||
static func lift(_ pointer: UnsafeMutableRawPointer) throws -> {{ obj|type_name }} {
|
||||
return {{ obj|type_name}}(unsafeFromRawPointer: pointer)
|
||||
static func lift(_ pointer: UnsafeMutableRawPointer) throws -> {{ type_name }} {
|
||||
return {{ type_name}}(unsafeFromRawPointer: pointer)
|
||||
}
|
||||
|
||||
static func lower(_ value: {{ obj|type_name }}) -> UnsafeMutableRawPointer {
|
||||
static func lower(_ value: {{ type_name }}) -> UnsafeMutableRawPointer {
|
||||
return value.pointer
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
{%- let inner_type = self.inner() %}
|
||||
{%- let outer_type = self.outer() %}
|
||||
fileprivate struct {{ outer_type|ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
typealias SwiftType = {{ outer_type|type_name }}
|
||||
fileprivate struct {{ ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
typealias SwiftType = {{ type_name }}
|
||||
|
||||
static func write(_ value: SwiftType, into buf: Writer) {
|
||||
guard let value = value else {
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
{% import "macros.swift" as swift %}
|
||||
{%- let rec = self.inner() %}
|
||||
public struct {{ rec|type_name }} {
|
||||
{%- let rec = ci.get_record_definition(name).unwrap() %}
|
||||
public struct {{ type_name }} {
|
||||
{%- for field in rec.fields() %}
|
||||
public var {{ field.name()|var_name }}: {{ field|type_name }}
|
||||
{%- endfor %}
|
||||
|
@ -14,9 +13,9 @@ public struct {{ rec|type_name }} {
|
|||
}
|
||||
}
|
||||
|
||||
{% if ! self.contains_object_references() %}
|
||||
extension {{ rec|type_name }}: Equatable, Hashable {
|
||||
public static func ==(lhs: {{ rec|type_name }}, rhs: {{ rec|type_name }}) -> Bool {
|
||||
{% if !contains_object_references %}
|
||||
extension {{ type_name }}: Equatable, Hashable {
|
||||
public static func ==(lhs: {{ type_name }}, rhs: {{ type_name }}) -> Bool {
|
||||
{%- for field in rec.fields() %}
|
||||
if lhs.{{ field.name()|var_name }} != rhs.{{ field.name()|var_name }} {
|
||||
return false
|
||||
|
@ -33,9 +32,9 @@ extension {{ rec|type_name }}: Equatable, Hashable {
|
|||
}
|
||||
{% endif %}
|
||||
|
||||
fileprivate struct {{ rec|ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
fileprivate static func read(from buf: Reader) throws -> {{ rec|type_name }} {
|
||||
return try {{ rec|type_name }}(
|
||||
fileprivate struct {{ ffi_converter_name }}: FfiConverterRustBuffer {
|
||||
fileprivate static func read(from buf: Reader) throws -> {{ type_name }} {
|
||||
return try {{ type_name }}(
|
||||
{%- for field in rec.fields() %}
|
||||
{{ field.name()|var_name }}: {{ field|read_fn }}(from: buf)
|
||||
{%- if !loop.last %}, {% endif %}
|
||||
|
@ -43,7 +42,7 @@ fileprivate struct {{ rec|ffi_converter_name }}: FfiConverterRustBuffer {
|
|||
)
|
||||
}
|
||||
|
||||
fileprivate static func write(_ value: {{ rec|type_name }}, into buf: Writer) {
|
||||
fileprivate static func write(_ value: {{ type_name }}, into buf: Writer) {
|
||||
{%- for field in rec.fields() %}
|
||||
{{ field|write_fn }}(value.{{ field.name()|var_name }}, into: buf)
|
||||
{%- endfor %}
|
||||
|
|
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Загрузка…
Ссылка в новой задаче