| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use std::borrow::Borrow; |
| 6 |
use std::cell::RefCell; |
| 7 |
use std::collections::{BTreeSet, HashMap, HashSet}; |
| 8 |
use std::fmt::Debug; |
| 9 |
|
| 10 |
use askama::Template; |
| 11 |
use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToUpperCamelCase}; |
| 12 |
use serde::{Deserialize, Serialize}; |
| 13 |
|
| 14 |
use crate::{anyhow, bail, interface::ffi::ExternalFfiMetadata, interface::*, Context, Result}; |
| 15 |
|
| 16 |
mod callback_interface; |
| 17 |
mod compounds; |
| 18 |
mod custom; |
| 19 |
mod enum_; |
| 20 |
mod miscellany; |
| 21 |
mod object; |
| 22 |
mod primitives; |
| 23 |
mod record; |
| 24 |
mod variant; |
| 25 |
|
| 26 |
trait CodeType: Debug { |
| 27 |
/// The language specific label used to reference this type. This will be used in |
| 28 |
/// method signatures and property declarations. |
| 29 |
fn type_label(&self, ci: &ComponentInterface) -> String; |
| 30 |
|
| 31 |
/// A representation of this type label that can be used as part of another |
| 32 |
/// identifier. e.g. `read_foo()`, or `FooInternals`. |
| 33 |
/// |
| 34 |
/// This is especially useful when creating specialized objects or methods to deal |
| 35 |
/// with this type only. |
| 36 |
fn canonical_name(&self) -> String; |
| 37 |
|
| 38 |
fn literal(&self, _literal: &Literal, ci: &ComponentInterface) -> Result<String> { |
| 39 |
unimplemented!("Unimplemented for {}", self.type_label(ci)) |
| 40 |
} |
| 41 |
|
| 42 |
/// Name of the FfiConverter |
| 43 |
/// |
| 44 |
/// This is the object that contains the lower, write, lift, and read methods for this type. |
| 45 |
/// Depending on the binding this will either be a singleton or a class with static methods. |
| 46 |
/// |
| 47 |
/// This is the newer way of handling these methods and replaces the lower, write, lift, and |
| 48 |
/// read CodeType methods. Currently only used by Kotlin, but the plan is to move other |
| 49 |
/// backends to using this. |
| 50 |
fn ffi_converter_name(&self) -> String { |
| 51 |
format!("FfiConverter{}", self.canonical_name()) |
| 52 |
} |
| 53 |
|
| 54 |
/// Function to run at startup |
| 55 |
fn initialization_fn(&self) -> Option<String> { |
| 56 |
None |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
// config options to customize the generated Kotlin. |
| 61 |
#[derive(Debug, Default, Clone, Serialize, Deserialize)] |
| 62 |
pub struct Config { |
| 63 |
pub(super) package_name: Option<String>, |
| 64 |
pub(super) cdylib_name: Option<String>, |
| 65 |
generate_immutable_records: Option<bool>, |
| 66 |
#[serde(default)] |
| 67 |
omit_checksums: bool, |
| 68 |
#[serde(default)] |
| 69 |
custom_types: HashMap<String, CustomTypeConfig>, |
| 70 |
#[serde(default)] |
| 71 |
pub(super) external_packages: HashMap<String, String>, |
| 72 |
#[serde(default)] |
| 73 |
android: bool, |
| 74 |
#[serde(default)] |
| 75 |
android_cleaner: Option<bool>, |
| 76 |
#[serde(default)] |
| 77 |
kotlin_target_version: Option<String>, |
| 78 |
#[serde(default)] |
| 79 |
disable_java_cleaner: bool, |
| 80 |
} |
| 81 |
|
| 82 |
impl Config { |
| 83 |
pub(crate) fn android_cleaner(&self) -> bool { |
| 84 |
self.android_cleaner.unwrap_or(self.android) |
| 85 |
} |
| 86 |
|
| 87 |
pub(crate) fn use_enum_entries(&self) -> bool { |
| 88 |
self.get_kotlin_version() >= KotlinVersion::new(1, 9, 0) |
| 89 |
} |
| 90 |
|
| 91 |
/// Returns a `Version` with the contents of `kotlin_target_version`. |
| 92 |
/// If `kotlin_target_version` is not defined, version `0.0.0` will be used as a fallback. |
| 93 |
/// If it's not valid, this function will panic. |
| 94 |
fn get_kotlin_version(&self) -> KotlinVersion { |
| 95 |
self.kotlin_target_version |
| 96 |
.clone() |
| 97 |
.map(|v| { |
| 98 |
KotlinVersion::parse(&v).unwrap_or_else(|_| { |
| 99 |
panic!("Provided Kotlin target version is not valid: {}", v) |
| 100 |
}) |
| 101 |
}) |
| 102 |
.unwrap_or(KotlinVersion::new(0, 0, 0)) |
| 103 |
} |
| 104 |
|
| 105 |
// Get the package name for an external type |
| 106 |
fn external_package_name(&self, module_path: &str, namespace: Option<&str>) -> String { |
| 107 |
// config overrides are keyed by the crate name, default fallback is the namespace. |
| 108 |
let crate_name = module_path.split("::").next().unwrap(); |
| 109 |
match self.external_packages.get(crate_name) { |
| 110 |
Some(name) => name.clone(), |
| 111 |
// If the module path is not in `external_packages`, we need to fall back to a default |
| 112 |
// with the namespace, which we hopefully have. This is quite fragile, but it's |
| 113 |
// unreachable in library mode - all deps get an entry in `external_packages` with the |
| 114 |
// correct namespace. |
| 115 |
None => format!("uniffi.{}", namespace.unwrap_or(module_path)), |
| 116 |
} |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] |
| 121 |
struct KotlinVersion((u16, u16, u16)); |
| 122 |
|
| 123 |
impl KotlinVersion { |
| 124 |
fn new(major: u16, minor: u16, patch: u16) -> Self { |
| 125 |
Self((major, minor, patch)) |
| 126 |
} |
| 127 |
|
| 128 |
fn parse(version: &str) -> Result<Self> { |
| 129 |
let components = version |
| 130 |
.split('.') |
| 131 |
.map(|n| { |
| 132 |
n.parse::<u16>() |
| 133 |
.map_err(|_| anyhow!("Invalid version string ({n} is not an integer)")) |
| 134 |
}) |
| 135 |
.collect::<Result<Vec<u16>>>()?; |
| 136 |
|
| 137 |
match components.as_slice() { |
| 138 |
[major, minor, patch] => Ok(Self((*major, *minor, *patch))), |
| 139 |
[major, minor] => Ok(Self((*major, *minor, 0))), |
| 140 |
[major] => Ok(Self((*major, 0, 0))), |
| 141 |
_ => bail!("Invalid version string (expected 1-3 components): {version}"), |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
#[derive(Debug, Default, Clone, Serialize, Deserialize)] |
| 147 |
#[serde(default)] |
| 148 |
pub struct CustomTypeConfig { |
| 149 |
imports: Option<Vec<String>>, |
| 150 |
type_name: Option<String>, |
| 151 |
into_custom: String, // b/w compat alias for lift |
| 152 |
lift: String, |
| 153 |
from_custom: String, // b/w compat alias for lower |
| 154 |
lower: String, |
| 155 |
} |
| 156 |
|
| 157 |
// functions replace literal "{}" in strings with a specified value. |
| 158 |
impl CustomTypeConfig { |
| 159 |
fn lift(&self, name: &str) -> String { |
| 160 |
let converter = if self.lift.is_empty() { |
| 161 |
&self.into_custom |
| 162 |
} else { |
| 163 |
&self.lift |
| 164 |
}; |
| 165 |
converter.replace("{}", name) |
| 166 |
} |
| 167 |
fn lower(&self, name: &str) -> String { |
| 168 |
let converter = if self.lower.is_empty() { |
| 169 |
&self.from_custom |
| 170 |
} else { |
| 171 |
&self.lower |
| 172 |
}; |
| 173 |
converter.replace("{}", name) |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
impl Config { |
| 178 |
// We insist someone has already configured us - any defaults we supply would be wrong. |
| 179 |
pub fn package_name(&self) -> String { |
| 180 |
self.package_name |
| 181 |
.as_ref() |
| 182 |
.expect("package name should have been set in update_component_configs") |
| 183 |
.clone() |
| 184 |
} |
| 185 |
|
| 186 |
pub fn cdylib_name(&self) -> String { |
| 187 |
self.cdylib_name |
| 188 |
.as_ref() |
| 189 |
.expect("cdylib name should have been set in update_component_configs") |
| 190 |
.clone() |
| 191 |
} |
| 192 |
|
| 193 |
/// Whether to generate immutable records (`val` instead of `var`) |
| 194 |
pub fn generate_immutable_records(&self) -> bool { |
| 195 |
self.generate_immutable_records.unwrap_or(false) |
| 196 |
} |
| 197 |
|
| 198 |
pub fn disable_java_cleaner(&self) -> bool { |
| 199 |
self.disable_java_cleaner |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
// Generate kotlin bindings for the given ComponentInterface, as a string. |
| 204 |
pub fn generate_bindings(config: &Config, ci: &ComponentInterface) -> Result<String> { |
| 205 |
KotlinWrapper::new(config.clone(), ci) |
| 206 |
.context("failed to create a binding generator")? |
| 207 |
.render() |
| 208 |
.context("failed to render kotlin bindings") |
| 209 |
} |
| 210 |
|
| 211 |
/// A struct to record a Kotlin import statement. |
| 212 |
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] |
| 213 |
pub enum ImportRequirement { |
| 214 |
/// The name we are importing. |
| 215 |
Import { name: String }, |
| 216 |
/// Import the name with the specified local name. |
| 217 |
ImportAs { name: String, as_name: String }, |
| 218 |
} |
| 219 |
|
| 220 |
impl ImportRequirement { |
| 221 |
/// Render the Kotlin import statement. |
| 222 |
fn render(&self) -> String { |
| 223 |
match &self { |
| 224 |
ImportRequirement::Import { name } => format!("import {name}"), |
| 225 |
ImportRequirement::ImportAs { name, as_name } => { |
| 226 |
format!("import {name} as {as_name}") |
| 227 |
} |
| 228 |
} |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
/// Renders Kotlin helper code for all types |
| 233 |
/// |
| 234 |
/// This template is a bit different than others in that it stores internal state from the render |
| 235 |
/// process. Make sure to only call `render()` once. |
| 236 |
#[derive(Template)] |
| 237 |
#[template(syntax = "kt", escape = "none", path = "Types.kt")] |
| 238 |
pub struct TypeRenderer<'a> { |
| 239 |
config: &'a Config, |
| 240 |
ci: &'a ComponentInterface, |
| 241 |
// Track imports added with the `add_import()` macro |
| 242 |
imports: RefCell<BTreeSet<ImportRequirement>>, |
| 243 |
} |
| 244 |
|
| 245 |
impl<'a> TypeRenderer<'a> { |
| 246 |
fn new(config: &'a Config, ci: &'a ComponentInterface) -> Self { |
| 247 |
Self { |
| 248 |
config, |
| 249 |
ci, |
| 250 |
imports: RefCell::new(BTreeSet::new()), |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
// Get the package name for an external type |
| 255 |
fn external_type_package_name(&self, module_path: &str, namespace: &str) -> String { |
| 256 |
self.config |
| 257 |
.external_package_name(module_path, Some(namespace)) |
| 258 |
} |
| 259 |
|
| 260 |
// The following methods are used by the `Types.kt` macros. |
| 261 |
|
| 262 |
// Helper to add an import statement |
| 263 |
// |
| 264 |
// Call this inside your template to cause an import statement to be added at the top of the |
| 265 |
// file. Imports will be sorted and de-deuped. |
| 266 |
// |
| 267 |
// Returns an empty string so that it can be used inside an askama `{{ }}` block. |
| 268 |
fn add_import(&self, name: &str) -> &str { |
| 269 |
self.imports.borrow_mut().insert(ImportRequirement::Import { |
| 270 |
name: name.to_owned(), |
| 271 |
}); |
| 272 |
"" |
| 273 |
} |
| 274 |
|
| 275 |
// Like add_import, but arranges for `import name as as_name` |
| 276 |
fn add_import_as(&self, name: &str, as_name: &str) -> &str { |
| 277 |
self.imports |
| 278 |
.borrow_mut() |
| 279 |
.insert(ImportRequirement::ImportAs { |
| 280 |
name: name.to_owned(), |
| 281 |
as_name: as_name.to_owned(), |
| 282 |
}); |
| 283 |
"" |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
#[derive(Template)] |
| 288 |
#[template(syntax = "kt", escape = "none", path = "wrapper.kt")] |
| 289 |
pub struct KotlinWrapper<'a> { |
| 290 |
config: Config, |
| 291 |
ci: &'a ComponentInterface, |
| 292 |
type_helper_code: String, |
| 293 |
type_imports: BTreeSet<ImportRequirement>, |
| 294 |
} |
| 295 |
|
| 296 |
impl<'a> KotlinWrapper<'a> { |
| 297 |
pub fn new(config: Config, ci: &'a ComponentInterface) -> Result<Self> { |
| 298 |
let type_renderer = TypeRenderer::new(&config, ci); |
| 299 |
let type_helper_code = type_renderer.render()?; |
| 300 |
let type_imports = type_renderer.imports.into_inner(); |
| 301 |
Ok(Self { |
| 302 |
config, |
| 303 |
ci, |
| 304 |
type_helper_code, |
| 305 |
type_imports, |
| 306 |
}) |
| 307 |
} |
| 308 |
|
| 309 |
pub fn initialization_fns(&self, ci: &ComponentInterface) -> Vec<String> { |
| 310 |
let init_fns = self |
| 311 |
.ci |
| 312 |
.iter_local_types() |
| 313 |
.map(|t| KotlinCodeOracle.find(t)) |
| 314 |
.filter_map(|ct| ct.initialization_fn()) |
| 315 |
.map(|fn_name| format!("{fn_name}(lib)")); |
| 316 |
|
| 317 |
// Also call global initialization function for any external type we use. |
| 318 |
// For example, we need to make sure that all callback interface vtables are registered |
| 319 |
// (#2343). |
| 320 |
let extern_module_init_fns = self |
| 321 |
.ci |
| 322 |
.iter_external_types() |
| 323 |
.filter_map(|ty| ty.module_path()) |
| 324 |
.map(|module_path| { |
| 325 |
let namespace = ci.namespace_for_module_path(module_path).unwrap(); |
| 326 |
let package_name = self |
| 327 |
.config |
| 328 |
.external_package_name(module_path, Some(namespace)); |
| 329 |
format!("{package_name}.uniffiEnsureInitialized()") |
| 330 |
}) |
| 331 |
.collect::<HashSet<_>>(); |
| 332 |
|
| 333 |
init_fns.chain(extern_module_init_fns).collect() |
| 334 |
} |
| 335 |
|
| 336 |
pub fn imports(&self) -> Vec<ImportRequirement> { |
| 337 |
self.type_imports.iter().cloned().collect() |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
/// Get the name of the interface and class name for a trait. |
| 342 |
/// |
| 343 |
/// For a regular `struct Foo` or `trait Foo`, there's `FooInterface` with `Foo` as |
| 344 |
/// the name of the (Rust implemented) object. But if it's a foreign trait: |
| 345 |
/// * The name `Foo` is the name of the interface used by a the Kotlin implementation of the trait. |
| 346 |
/// * The Rust implemented object is `FooImpl`. |
| 347 |
/// |
| 348 |
/// This all impacts what types `FfiConverter.lower()` inputs. If it's a "foreign trait" |
| 349 |
/// `lower` must lower anything that implements the interface (ie, a kotlin implementation). |
| 350 |
/// If not, then lower only lowers the concrete class (ie, our simple instance with the pointer). |
| 351 |
fn object_interface_name(ci: &ComponentInterface, obj: &Object) -> String { |
| 352 |
let class_name = KotlinCodeOracle.class_name(ci, obj.name()); |
| 353 |
if obj.has_callback_interface() { |
| 354 |
class_name |
| 355 |
} else { |
| 356 |
format!("{class_name}Interface") |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
// *sigh* - same thing for a trait, which might be either Object or CallbackInterface. |
| 361 |
// (we should either fold it into object or kill it!) |
| 362 |
fn trait_interface_name(ci: &ComponentInterface, name: &str) -> Result<String> { |
| 363 |
let (obj_name, has_callback_interface) = match ci.get_object_definition(name) { |
| 364 |
Some(obj) => (obj.name(), obj.has_callback_interface()), |
| 365 |
None => ( |
| 366 |
ci.get_callback_interface_definition(name) |
| 367 |
.ok_or_else(|| anyhow!("no interface {}", name))? |
| 368 |
.name(), |
| 369 |
true, |
| 370 |
), |
| 371 |
}; |
| 372 |
let class_name = KotlinCodeOracle.class_name(ci, obj_name); |
| 373 |
if has_callback_interface { |
| 374 |
Ok(class_name) |
| 375 |
} else { |
| 376 |
Ok(format!("{class_name}Interface")) |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
// The name of the object exposing a Rust implementation. |
| 381 |
fn object_impl_name(ci: &ComponentInterface, obj: &Object) -> String { |
| 382 |
let class_name = KotlinCodeOracle.class_name(ci, obj.name()); |
| 383 |
if obj.has_callback_interface() { |
| 384 |
format!("{class_name}Impl") |
| 385 |
} else { |
| 386 |
class_name |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
#[derive(Clone)] |
| 391 |
pub struct KotlinCodeOracle; |
| 392 |
|
| 393 |
impl KotlinCodeOracle { |
| 394 |
fn find(&self, type_: &Type) -> Box<dyn CodeType> { |
| 395 |
type_.clone().as_type().as_codetype() |
| 396 |
} |
| 397 |
|
| 398 |
/// Get the idiomatic Kotlin rendering of a class name (for enums, records, errors, etc). |
| 399 |
fn class_name(&self, ci: &ComponentInterface, nm: &str) -> String { |
| 400 |
let name = nm.to_string().to_upper_camel_case(); |
| 401 |
// fixup errors. |
| 402 |
ci.is_name_used_as_error(nm) |
| 403 |
.then(|| self.convert_error_suffix(&name)) |
| 404 |
.unwrap_or(name) |
| 405 |
} |
| 406 |
|
| 407 |
fn convert_error_suffix(&self, nm: &str) -> String { |
| 408 |
match nm.strip_suffix("Error") { |
| 409 |
None => nm.to_string(), |
| 410 |
Some(stripped) => format!("{stripped}Exception"), |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
/// Get the idiomatic Kotlin rendering of a function name. |
| 415 |
fn fn_name(&self, nm: &str) -> String { |
| 416 |
format!("`{}`", nm.to_string().to_lower_camel_case()) |
| 417 |
} |
| 418 |
|
| 419 |
/// Get the idiomatic Kotlin rendering of a variable name. |
| 420 |
fn var_name(&self, nm: &str) -> String { |
| 421 |
format!("`{}`", self.var_name_raw(nm)) |
| 422 |
} |
| 423 |
|
| 424 |
/// `var_name` without the backticks. Useful for using in `@Structure.FieldOrder`. |
| 425 |
pub fn var_name_raw(&self, nm: &str) -> String { |
| 426 |
nm.to_string().to_lower_camel_case() |
| 427 |
} |
| 428 |
|
| 429 |
/// Get the idiomatic Kotlin rendering of an individual enum variant. |
| 430 |
fn enum_variant_name(&self, nm: &str) -> String { |
| 431 |
nm.to_string().to_shouty_snake_case() |
| 432 |
} |
| 433 |
|
| 434 |
/// Get the idiomatic Kotlin rendering of an FFI callback function name |
| 435 |
fn ffi_callback_name(&self, nm: &str) -> String { |
| 436 |
format!("Uniffi{}", nm.to_upper_camel_case()) |
| 437 |
} |
| 438 |
|
| 439 |
/// Get the idiomatic Kotlin rendering of an FFI struct name |
| 440 |
fn ffi_struct_name(&self, nm: &str) -> String { |
| 441 |
format!("Uniffi{}", nm.to_upper_camel_case()) |
| 442 |
} |
| 443 |
|
| 444 |
fn ffi_type_label_by_value(&self, ffi_type: &FfiType, ci: &ComponentInterface) -> String { |
| 445 |
match ffi_type { |
| 446 |
FfiType::RustBuffer(_) => format!("{}.ByValue", self.ffi_type_label(ffi_type, ci)), |
| 447 |
FfiType::Struct(name) => format!("{}.UniffiByValue", self.ffi_struct_name(name)), |
| 448 |
_ => self.ffi_type_label(ffi_type, ci), |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
/// FFI type name to use inside structs |
| 453 |
/// |
| 454 |
/// The main requirement here is that all types must have default values or else the struct |
| 455 |
/// won't work in some JNA contexts. |
| 456 |
fn ffi_type_label_for_ffi_struct(&self, ffi_type: &FfiType, ci: &ComponentInterface) -> String { |
| 457 |
match ffi_type { |
| 458 |
// Make callbacks function pointers nullable. This matches the semantics of a C |
| 459 |
// function pointer better and allows for `null` as a default value. |
| 460 |
FfiType::Callback(name) => format!("{}?", self.ffi_callback_name(name)), |
| 461 |
_ => self.ffi_type_label_by_value(ffi_type, ci), |
| 462 |
} |
| 463 |
} |
| 464 |
|
| 465 |
/// Default values for FFI |
| 466 |
/// |
| 467 |
/// This is used to: |
| 468 |
/// - Set a default return value for error results |
| 469 |
/// - Set a default for structs, which JNA sometimes requires |
| 470 |
fn ffi_default_value(&self, ffi_type: &FfiType) -> String { |
| 471 |
match ffi_type { |
| 472 |
FfiType::UInt8 | FfiType::Int8 => "0.toByte()".to_owned(), |
| 473 |
FfiType::UInt16 | FfiType::Int16 => "0.toShort()".to_owned(), |
| 474 |
FfiType::UInt32 | FfiType::Int32 => "0".to_owned(), |
| 475 |
FfiType::UInt64 | FfiType::Int64 => "0.toLong()".to_owned(), |
| 476 |
FfiType::Float32 => "0.0f".to_owned(), |
| 477 |
FfiType::Float64 => "0.0".to_owned(), |
| 478 |
FfiType::RustArcPtr(_) => "Pointer.NULL".to_owned(), |
| 479 |
FfiType::RustBuffer(_) => "RustBuffer.ByValue()".to_owned(), |
| 480 |
FfiType::Callback(_) => "null".to_owned(), |
| 481 |
FfiType::RustCallStatus => "UniffiRustCallStatus.ByValue()".to_owned(), |
| 482 |
_ => unimplemented!("ffi_default_value: {ffi_type:?}"), |
| 483 |
} |
| 484 |
} |
| 485 |
|
| 486 |
fn ffi_type_label_by_reference(&self, ffi_type: &FfiType, ci: &ComponentInterface) -> String { |
| 487 |
match ffi_type { |
| 488 |
FfiType::Int8 |
| 489 |
| FfiType::UInt8 |
| 490 |
| FfiType::Int16 |
| 491 |
| FfiType::UInt16 |
| 492 |
| FfiType::Int32 |
| 493 |
| FfiType::UInt32 |
| 494 |
| FfiType::Int64 |
| 495 |
| FfiType::UInt64 |
| 496 |
| FfiType::Float32 |
| 497 |
| FfiType::Float64 => format!("{}ByReference", self.ffi_type_label(ffi_type, ci)), |
| 498 |
FfiType::RustArcPtr(_) => "PointerByReference".to_owned(), |
| 499 |
// JNA structs default to ByReference |
| 500 |
FfiType::RustBuffer(_) | FfiType::Struct(_) => self.ffi_type_label(ffi_type, ci), |
| 501 |
_ => panic!("{ffi_type:?} by reference is not implemented"), |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
fn ffi_type_label(&self, ffi_type: &FfiType, ci: &ComponentInterface) -> String { |
| 506 |
match ffi_type { |
| 507 |
// Note that unsigned integers in Kotlin are currently experimental, but java.nio.ByteBuffer does not |
| 508 |
// support them yet. Thus, we use the signed variants to represent both signed and unsigned |
| 509 |
// types from the component API. |
| 510 |
FfiType::Int8 | FfiType::UInt8 => "Byte".to_string(), |
| 511 |
FfiType::Int16 | FfiType::UInt16 => "Short".to_string(), |
| 512 |
FfiType::Int32 | FfiType::UInt32 => "Int".to_string(), |
| 513 |
FfiType::Int64 | FfiType::UInt64 => "Long".to_string(), |
| 514 |
FfiType::Float32 => "Float".to_string(), |
| 515 |
FfiType::Float64 => "Double".to_string(), |
| 516 |
FfiType::Handle => "Long".to_string(), |
| 517 |
FfiType::RustArcPtr(_) => "Pointer".to_string(), |
| 518 |
FfiType::RustBuffer(maybe_external) => match maybe_external { |
| 519 |
Some(external_meta) if external_meta.module_path != ci.crate_name() => { |
| 520 |
format!("RustBuffer{}", external_meta.name) |
| 521 |
} |
| 522 |
_ => "RustBuffer".to_string(), |
| 523 |
}, |
| 524 |
FfiType::RustCallStatus => "UniffiRustCallStatus.ByValue".to_string(), |
| 525 |
FfiType::ForeignBytes => "ForeignBytes.ByValue".to_string(), |
| 526 |
FfiType::Callback(name) => self.ffi_callback_name(name), |
| 527 |
FfiType::Struct(name) => self.ffi_struct_name(name), |
| 528 |
FfiType::Reference(inner) | FfiType::MutReference(inner) => { |
| 529 |
self.ffi_type_label_by_reference(inner, ci) |
| 530 |
} |
| 531 |
FfiType::VoidPointer => "Pointer".to_string(), |
| 532 |
} |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
trait AsCodeType { |
| 537 |
fn as_codetype(&self) -> Box<dyn CodeType>; |
| 538 |
} |
| 539 |
|
| 540 |
impl<T: AsType> AsCodeType for T { |
| 541 |
fn as_codetype(&self) -> Box<dyn CodeType> { |
| 542 |
// Map `Type` instances to a `Box<dyn CodeType>` for that type. |
| 543 |
// |
| 544 |
// There is a companion match in `templates/Types.kt` which performs a similar function for the |
| 545 |
// template code. |
| 546 |
// |
| 547 |
// - When adding additional types here, make sure to also add a match arm to the `Types.kt` template. |
| 548 |
// - To keep things manageable, let's try to limit ourselves to these 2 mega-matches |
| 549 |
match self.as_type() { |
| 550 |
Type::UInt8 => Box::new(primitives::UInt8CodeType), |
| 551 |
Type::Int8 => Box::new(primitives::Int8CodeType), |
| 552 |
Type::UInt16 => Box::new(primitives::UInt16CodeType), |
| 553 |
Type::Int16 => Box::new(primitives::Int16CodeType), |
| 554 |
Type::UInt32 => Box::new(primitives::UInt32CodeType), |
| 555 |
Type::Int32 => Box::new(primitives::Int32CodeType), |
| 556 |
Type::UInt64 => Box::new(primitives::UInt64CodeType), |
| 557 |
Type::Int64 => Box::new(primitives::Int64CodeType), |
| 558 |
Type::Float32 => Box::new(primitives::Float32CodeType), |
| 559 |
Type::Float64 => Box::new(primitives::Float64CodeType), |
| 560 |
Type::Boolean => Box::new(primitives::BooleanCodeType), |
| 561 |
Type::String => Box::new(primitives::StringCodeType), |
| 562 |
Type::Bytes => Box::new(primitives::BytesCodeType), |
| 563 |
|
| 564 |
Type::Timestamp => Box::new(miscellany::TimestampCodeType), |
| 565 |
Type::Duration => Box::new(miscellany::DurationCodeType), |
| 566 |
|
| 567 |
Type::Enum { name, .. } => Box::new(enum_::EnumCodeType::new(name)), |
| 568 |
Type::Object { name, imp, .. } => Box::new(object::ObjectCodeType::new(name, imp)), |
| 569 |
Type::Record { name, .. } => Box::new(record::RecordCodeType::new(name)), |
| 570 |
Type::CallbackInterface { name, .. } => { |
| 571 |
Box::new(callback_interface::CallbackInterfaceCodeType::new(name)) |
| 572 |
} |
| 573 |
Type::Optional { inner_type } => { |
| 574 |
Box::new(compounds::OptionalCodeType::new(*inner_type)) |
| 575 |
} |
| 576 |
Type::Sequence { inner_type } => { |
| 577 |
Box::new(compounds::SequenceCodeType::new(*inner_type)) |
| 578 |
} |
| 579 |
Type::Map { |
| 580 |
key_type, |
| 581 |
value_type, |
| 582 |
} => Box::new(compounds::MapCodeType::new(*key_type, *value_type)), |
| 583 |
Type::Custom { name, .. } => Box::new(custom::CustomCodeType::new(name)), |
| 584 |
} |
| 585 |
} |
| 586 |
} |
| 587 |
|
| 588 |
// A work around for #2392 - we can't handle functions with external errors. |
| 589 |
fn can_render_callable(callable: &dyn Callable, ci: &ComponentInterface) -> bool { |
| 590 |
// can't handle external errors. |
| 591 |
callable |
| 592 |
.throws_type() |
| 593 |
.map(|t| !ci.is_external(t)) |
| 594 |
.unwrap_or(true) |
| 595 |
} |
| 596 |
|
| 597 |
mod filters { |
| 598 |
use super::*; |
| 599 |
pub use crate::backend::filters::*; |
| 600 |
use uniffi_meta::LiteralMetadata; |
| 601 |
|
| 602 |
pub(super) fn type_name( |
| 603 |
as_ct: &impl AsCodeType, |
| 604 |
ci: &ComponentInterface, |
| 605 |
) -> Result<String, askama::Error> { |
| 606 |
Ok(as_ct.as_codetype().type_label(ci)) |
| 607 |
} |
| 608 |
|
| 609 |
pub(super) fn canonical_name(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 610 |
Ok(as_ct.as_codetype().canonical_name()) |
| 611 |
} |
| 612 |
|
| 613 |
pub(super) fn ffi_converter_name(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 614 |
Ok(as_ct.as_codetype().ffi_converter_name()) |
| 615 |
} |
| 616 |
|
| 617 |
pub(super) fn lower_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 618 |
Ok(format!( |
| 619 |
"{}.lower", |
| 620 |
as_ct.as_codetype().ffi_converter_name() |
| 621 |
)) |
| 622 |
} |
| 623 |
|
| 624 |
pub(super) fn allocation_size_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 625 |
Ok(format!( |
| 626 |
"{}.allocationSize", |
| 627 |
as_ct.as_codetype().ffi_converter_name() |
| 628 |
)) |
| 629 |
} |
| 630 |
|
| 631 |
pub(super) fn write_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 632 |
Ok(format!( |
| 633 |
"{}.write", |
| 634 |
as_ct.as_codetype().ffi_converter_name() |
| 635 |
)) |
| 636 |
} |
| 637 |
|
| 638 |
pub(super) fn lift_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 639 |
Ok(format!("{}.lift", as_ct.as_codetype().ffi_converter_name())) |
| 640 |
} |
| 641 |
|
| 642 |
pub(super) fn read_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 643 |
Ok(format!("{}.read", as_ct.as_codetype().ffi_converter_name())) |
| 644 |
} |
| 645 |
|
| 646 |
pub fn render_literal( |
| 647 |
literal: &Literal, |
| 648 |
as_ct: &impl AsType, |
| 649 |
ci: &ComponentInterface, |
| 650 |
) -> Result<String, askama::Error> { |
| 651 |
as_ct |
| 652 |
.as_codetype() |
| 653 |
.literal(literal, ci) |
| 654 |
.map_err(|e| to_askama_error(&e)) |
| 655 |
} |
| 656 |
|
| 657 |
// Get the idiomatic Kotlin rendering of an integer. |
| 658 |
fn int_literal(t: &Option<Type>, base10: String) -> Result<String, askama::Error> { |
| 659 |
if let Some(t) = t { |
| 660 |
match t { |
| 661 |
Type::Int8 | Type::Int16 | Type::Int32 | Type::Int64 => Ok(base10), |
| 662 |
Type::UInt8 | Type::UInt16 | Type::UInt32 | Type::UInt64 => Ok(base10 + "u"), |
| 663 |
_ => Err(to_askama_error("Only ints are supported.")), |
| 664 |
} |
| 665 |
} else { |
| 666 |
Err(to_askama_error("Enum hasn't defined a repr")) |
| 667 |
} |
| 668 |
} |
| 669 |
|
| 670 |
// Get the idiomatic Kotlin rendering of an individual enum variant's discriminant |
| 671 |
pub fn variant_discr_literal(e: &Enum, index: &usize) -> Result<String, askama::Error> { |
| 672 |
let literal = e.variant_discr(*index).expect("invalid index"); |
| 673 |
match literal { |
| 674 |
// Kotlin doesn't convert between signed and unsigned by default |
| 675 |
// so we'll need to make sure we define the type as appropriately |
| 676 |
LiteralMetadata::UInt(v, _, _) => int_literal(e.variant_discr_type(), v.to_string()), |
| 677 |
LiteralMetadata::Int(v, _, _) => int_literal(e.variant_discr_type(), v.to_string()), |
| 678 |
_ => Err(to_askama_error("Only ints are supported.")), |
| 679 |
} |
| 680 |
} |
| 681 |
|
| 682 |
pub fn ffi_type_name_by_value( |
| 683 |
type_: &FfiType, |
| 684 |
ci: &ComponentInterface, |
| 685 |
) -> Result<String, askama::Error> { |
| 686 |
Ok(KotlinCodeOracle.ffi_type_label_by_value(type_, ci)) |
| 687 |
} |
| 688 |
|
| 689 |
pub fn ffi_type_name_for_ffi_struct( |
| 690 |
type_: &FfiType, |
| 691 |
ci: &ComponentInterface, |
| 692 |
) -> Result<String, askama::Error> { |
| 693 |
Ok(KotlinCodeOracle.ffi_type_label_for_ffi_struct(type_, ci)) |
| 694 |
} |
| 695 |
|
| 696 |
pub fn ffi_default_value(type_: FfiType) -> Result<String, askama::Error> { |
| 697 |
Ok(KotlinCodeOracle.ffi_default_value(&type_)) |
| 698 |
} |
| 699 |
|
| 700 |
/// Get the idiomatic Kotlin rendering of a function name. |
| 701 |
pub fn class_name<S: AsRef<str>>( |
| 702 |
nm: S, |
| 703 |
ci: &ComponentInterface, |
| 704 |
) -> Result<String, askama::Error> { |
| 705 |
Ok(KotlinCodeOracle.class_name(ci, nm.as_ref())) |
| 706 |
} |
| 707 |
|
| 708 |
/// Get the idiomatic Kotlin rendering of a function name. |
| 709 |
pub fn fn_name<S: AsRef<str>>(nm: S) -> Result<String, askama::Error> { |
| 710 |
Ok(KotlinCodeOracle.fn_name(nm.as_ref())) |
| 711 |
} |
| 712 |
|
| 713 |
/// Get the idiomatic Kotlin rendering of a variable name. |
| 714 |
pub fn var_name<S: AsRef<str>>(nm: S) -> Result<String, askama::Error> { |
| 715 |
Ok(KotlinCodeOracle.var_name(nm.as_ref())) |
| 716 |
} |
| 717 |
|
| 718 |
/// Get the idiomatic Kotlin rendering of a variable name. |
| 719 |
pub fn var_name_raw<S: AsRef<str>>(nm: S) -> Result<String, askama::Error> { |
| 720 |
Ok(KotlinCodeOracle.var_name_raw(nm.as_ref())) |
| 721 |
} |
| 722 |
|
| 723 |
/// Get a String representing the name used for an individual enum variant. |
| 724 |
pub fn variant_name(v: &Variant) -> Result<String, askama::Error> { |
| 725 |
Ok(KotlinCodeOracle.enum_variant_name(v.name())) |
| 726 |
} |
| 727 |
|
| 728 |
pub fn error_variant_name(v: &Variant) -> Result<String, askama::Error> { |
| 729 |
let name = v.name().to_string().to_upper_camel_case(); |
| 730 |
Ok(KotlinCodeOracle.convert_error_suffix(&name)) |
| 731 |
} |
| 732 |
|
| 733 |
/// Get the idiomatic Kotlin rendering of an FFI callback function name |
| 734 |
pub fn ffi_callback_name<S: AsRef<str>>(nm: S) -> Result<String, askama::Error> { |
| 735 |
Ok(KotlinCodeOracle.ffi_callback_name(nm.as_ref())) |
| 736 |
} |
| 737 |
|
| 738 |
/// Get the idiomatic Kotlin rendering of an FFI struct name |
| 739 |
pub fn ffi_struct_name<S: AsRef<str>>(nm: S) -> Result<String, askama::Error> { |
| 740 |
Ok(KotlinCodeOracle.ffi_struct_name(nm.as_ref())) |
| 741 |
} |
| 742 |
|
| 743 |
pub fn async_poll( |
| 744 |
callable: impl Callable, |
| 745 |
ci: &ComponentInterface, |
| 746 |
) -> Result<String, askama::Error> { |
| 747 |
let ffi_func = callable.ffi_rust_future_poll(ci); |
| 748 |
Ok(format!( |
| 749 |
"{{ future, callback, continuation -> UniffiLib.INSTANCE.{ffi_func}(future, callback, continuation) }}" |
| 750 |
)) |
| 751 |
} |
| 752 |
|
| 753 |
pub fn async_complete( |
| 754 |
callable: impl Callable, |
| 755 |
ci: &ComponentInterface, |
| 756 |
) -> Result<String, askama::Error> { |
| 757 |
let ffi_func = callable.ffi_rust_future_complete(ci); |
| 758 |
let call = format!("UniffiLib.INSTANCE.{ffi_func}(future, continuation)"); |
| 759 |
// May need to convert the RustBuffer from our package to the RustBuffer of the external package |
| 760 |
let call = match callable.return_type() { |
| 761 |
Some(return_type) if ci.is_external(return_type) => { |
| 762 |
let ffi_type = FfiType::from(return_type); |
| 763 |
match ffi_type { |
| 764 |
FfiType::RustBuffer(Some(ExternalFfiMetadata { name, .. })) => { |
| 765 |
let suffix = KotlinCodeOracle.class_name(ci, &name); |
| 766 |
format!("{call}.let {{ RustBuffer{suffix}.create(it.capacity.toULong(), it.len.toULong(), it.data) }}") |
| 767 |
} |
| 768 |
_ => call, |
| 769 |
} |
| 770 |
} |
| 771 |
_ => call, |
| 772 |
}; |
| 773 |
Ok(format!("{{ future, continuation -> {call} }}")) |
| 774 |
} |
| 775 |
|
| 776 |
pub fn async_free( |
| 777 |
callable: impl Callable, |
| 778 |
ci: &ComponentInterface, |
| 779 |
) -> Result<String, askama::Error> { |
| 780 |
let ffi_func = callable.ffi_rust_future_free(ci); |
| 781 |
Ok(format!( |
| 782 |
"{{ future -> UniffiLib.INSTANCE.{ffi_func}(future) }}" |
| 783 |
)) |
| 784 |
} |
| 785 |
|
| 786 |
/// Remove the "`" chars we put around function/variable names |
| 787 |
/// |
| 788 |
/// These are used to avoid name clashes with kotlin identifiers, but sometimes you want to |
| 789 |
/// render the name unquoted. One example is the message property for errors where we want to |
| 790 |
/// display the name for the user. |
| 791 |
pub fn unquote<S: AsRef<str>>(nm: S) -> Result<String, askama::Error> { |
| 792 |
Ok(nm.as_ref().trim_matches('`').to_string()) |
| 793 |
} |
| 794 |
|
| 795 |
/// Get the idiomatic Kotlin rendering of docstring |
| 796 |
pub fn docstring<S: AsRef<str>>(docstring: S, spaces: &i32) -> Result<String, askama::Error> { |
| 797 |
let middle = textwrap::indent(&textwrap::dedent(docstring.as_ref()), " * "); |
| 798 |
let wrapped = format!("/**\n{middle}\n */"); |
| 799 |
|
| 800 |
let spaces = usize::try_from(*spaces).unwrap_or_default(); |
| 801 |
Ok(textwrap::indent(&wrapped, &" ".repeat(spaces))) |
| 802 |
} |
| 803 |
} |
| 804 |
|
| 805 |
#[cfg(test)] |
| 806 |
mod test { |
| 807 |
use super::*; |
| 808 |
|
| 809 |
#[test] |
| 810 |
fn test_kotlin_version() { |
| 811 |
assert_eq!( |
| 812 |
KotlinVersion::parse("1.2.3").unwrap(), |
| 813 |
KotlinVersion::new(1, 2, 3) |
| 814 |
); |
| 815 |
assert_eq!( |
| 816 |
KotlinVersion::parse("2.3").unwrap(), |
| 817 |
KotlinVersion::new(2, 3, 0), |
| 818 |
); |
| 819 |
assert_eq!( |
| 820 |
KotlinVersion::parse("2").unwrap(), |
| 821 |
KotlinVersion::new(2, 0, 0), |
| 822 |
); |
| 823 |
assert!(KotlinVersion::parse("2.").is_err()); |
| 824 |
assert!(KotlinVersion::parse("").is_err()); |
| 825 |
assert!(KotlinVersion::parse("A.B.C").is_err()); |
| 826 |
assert!(KotlinVersion::new(1, 2, 3) > KotlinVersion::new(0, 1, 2)); |
| 827 |
assert!(KotlinVersion::new(1, 2, 3) > KotlinVersion::new(0, 100, 0)); |
| 828 |
assert!(KotlinVersion::new(10, 0, 0) > KotlinVersion::new(1, 10, 0)); |
| 829 |
} |
| 830 |
} |