use std::borrow::Borrow;
use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Debug;
use anyhow::{bail, Context, Result};
use askama::Template;
use camino::Utf8Path;
use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToUpperCamelCase};
use serde::{Deserialize, Serialize};
use crate::backend::TemplateExpression;
use crate::bindings::kotlin;
use crate::interface::*;
use crate::{BindingGenerator, BindingsConfig};
mod callback_interface;
mod compounds;
mod custom;
mod enum_;
mod external;
mod miscellany;
mod object;
mod primitives;
mod record;
mod variant;
pub struct KotlinBindingGenerator;
impl BindingGenerator for KotlinBindingGenerator {
type Config = Config;
fn write_bindings(
&self,
ci: &ComponentInterface,
config: &Config,
out_dir: &Utf8Path,
try_format_code: bool,
) -> Result<()> {
kotlin::write_bindings(config, ci, out_dir, try_format_code)
}
fn check_library_path(&self, library_path: &Utf8Path, cdylib_name: Option<&str>) -> Result<()> {
if cdylib_name.is_none() {
bail!("Generate bindings for Kotlin requires a cdylib, but {library_path} was given");
}
Ok(())
}
}
trait CodeType: Debug {
fn type_label(&self, ci: &ComponentInterface) -> String;
fn canonical_name(&self) -> String;
fn literal(&self, _literal: &Literal, ci: &ComponentInterface) -> String {
unimplemented!("Unimplemented for {}", self.type_label(ci))
}
fn ffi_converter_name(&self) -> String {
format!("FfiConverter{}", self.canonical_name())
}
fn imports(&self) -> Option<Vec<String>> {
None
}
fn initialization_fn(&self) -> Option<String> {
None
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Config {
package_name: Option<String>,
cdylib_name: Option<String>,
generate_immutable_records: Option<bool>,
#[serde(default)]
custom_types: HashMap<String, CustomTypeConfig>,
#[serde(default)]
external_packages: HashMap<String, String>,
#[serde(default)]
android: bool,
#[serde(default)]
android_cleaner: Option<bool>,
}
impl Config {
pub(crate) fn android_cleaner(&self) -> bool {
self.android_cleaner.unwrap_or(self.android)
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CustomTypeConfig {
imports: Option<Vec<String>>,
type_name: Option<String>,
into_custom: TemplateExpression,
from_custom: TemplateExpression,
}
impl Config {
pub fn package_name(&self) -> String {
if let Some(package_name) = &self.package_name {
package_name.clone()
} else {
"uniffi".into()
}
}
pub fn cdylib_name(&self) -> String {
if let Some(cdylib_name) = &self.cdylib_name {
cdylib_name.clone()
} else {
"uniffi".into()
}
}
pub fn generate_immutable_records(&self) -> bool {
self.generate_immutable_records.unwrap_or(false)
}
}
impl BindingsConfig for Config {
fn update_from_ci(&mut self, ci: &ComponentInterface) {
self.package_name
.get_or_insert_with(|| format!("uniffi.{}", ci.namespace()));
self.cdylib_name
.get_or_insert_with(|| format!("uniffi_{}", ci.namespace()));
}
fn update_from_cdylib_name(&mut self, cdylib_name: &str) {
self.cdylib_name
.get_or_insert_with(|| cdylib_name.to_string());
}
fn update_from_dependency_configs(&mut self, config_map: HashMap<&str, &Self>) {
for (crate_name, config) in config_map {
if !self.external_packages.contains_key(crate_name) {
self.external_packages
.insert(crate_name.to_string(), config.package_name());
}
}
}
}
pub fn generate_bindings(config: &Config, ci: &ComponentInterface) -> Result<String> {
KotlinWrapper::new(config.clone(), ci)
.render()
.context("failed to render kotlin bindings")
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ImportRequirement {
Import { name: String },
ImportAs { name: String, as_name: String },
}
impl ImportRequirement {
fn render(&self) -> String {
match &self {
ImportRequirement::Import { name } => format!("import {name}"),
ImportRequirement::ImportAs { name, as_name } => {
format!("import {name} as {as_name}")
}
}
}
}
#[derive(Template)]
#[template(syntax = "kt", escape = "none", path = "Types.kt")]
pub struct TypeRenderer<'a> {
config: &'a Config,
ci: &'a ComponentInterface,
include_once_names: RefCell<HashSet<String>>,
imports: RefCell<BTreeSet<ImportRequirement>>,
}
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()),
}
}
fn external_type_package_name(&self, module_path: &str, namespace: &str) -> String {
let crate_name = module_path.split("::").next().unwrap();
match self.config.external_packages.get(crate_name) {
Some(name) => name.clone(),
None => format!("uniffi.{namespace}"),
}
}
fn include_once_check(&self, name: &str) -> bool {
self.include_once_names
.borrow_mut()
.insert(name.to_string())
}
fn add_import(&self, name: &str) -> &str {
self.imports.borrow_mut().insert(ImportRequirement::Import {
name: name.to_owned(),
});
""
}
fn add_import_as(&self, name: &str, as_name: &str) -> &str {
self.imports
.borrow_mut()
.insert(ImportRequirement::ImportAs {
name: name.to_owned(),
as_name: as_name.to_owned(),
});
""
}
}
#[derive(Template)]
#[template(syntax = "kt", escape = "none", path = "wrapper.kt")]
pub struct KotlinWrapper<'a> {
config: Config,
ci: &'a ComponentInterface,
type_helper_code: String,
type_imports: BTreeSet<ImportRequirement>,
}
impl<'a> KotlinWrapper<'a> {
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 initialization_fns(&self) -> Vec<String> {
self.ci
.iter_types()
.map(|t| KotlinCodeOracle.find(t))
.filter_map(|ct| ct.initialization_fn())
.collect()
}
pub fn imports(&self) -> Vec<ImportRequirement> {
self.type_imports.iter().cloned().collect()
}
}
#[derive(Clone)]
pub struct KotlinCodeOracle;
impl KotlinCodeOracle {
fn find(&self, type_: &Type) -> Box<dyn CodeType> {
type_.clone().as_type().as_codetype()
}
fn class_name(&self, ci: &ComponentInterface, nm: &str) -> String {
let name = nm.to_string().to_upper_camel_case();
ci.is_name_used_as_error(nm)
.then(|| self.convert_error_suffix(&name))
.unwrap_or(name)
}
fn convert_error_suffix(&self, nm: &str) -> String {
match nm.strip_suffix("Error") {
None => nm.to_string(),
Some(stripped) => format!("{stripped}Exception"),
}
}
fn fn_name(&self, nm: &str) -> String {
format!("`{}`", nm.to_string().to_lower_camel_case())
}
fn var_name(&self, nm: &str) -> String {
format!("`{}`", self.var_name_raw(nm))
}
pub fn var_name_raw(&self, nm: &str) -> String {
nm.to_string().to_lower_camel_case()
}
fn enum_variant_name(&self, nm: &str) -> String {
nm.to_string().to_shouty_snake_case()
}
fn ffi_callback_name(&self, nm: &str) -> String {
format!("Uniffi{}", nm.to_upper_camel_case())
}
fn ffi_struct_name(&self, nm: &str) -> String {
format!("Uniffi{}", nm.to_upper_camel_case())
}
fn ffi_type_label_by_value(&self, ffi_type: &FfiType) -> String {
match ffi_type {
FfiType::RustBuffer(_) => format!("{}.ByValue", self.ffi_type_label(ffi_type)),
FfiType::Struct(name) => format!("{}.UniffiByValue", self.ffi_struct_name(name)),
_ => self.ffi_type_label(ffi_type),
}
}
fn ffi_type_label_for_ffi_struct(&self, ffi_type: &FfiType) -> String {
match ffi_type {
FfiType::Callback(name) => format!("{}?", self.ffi_callback_name(name)),
_ => self.ffi_type_label_by_value(ffi_type),
}
}
fn ffi_default_value(&self, ffi_type: &FfiType) -> String {
match ffi_type {
FfiType::UInt8 | FfiType::Int8 => "0.toByte()".to_owned(),
FfiType::UInt16 | FfiType::Int16 => "0.toShort()".to_owned(),
FfiType::UInt32 | FfiType::Int32 => "0".to_owned(),
FfiType::UInt64 | FfiType::Int64 => "0.toLong()".to_owned(),
FfiType::Float32 => "0.0f".to_owned(),
FfiType::Float64 => "0.0".to_owned(),
FfiType::RustArcPtr(_) => "Pointer.NULL".to_owned(),
FfiType::RustBuffer(_) => "RustBuffer.ByValue()".to_owned(),
FfiType::Callback(_) => "null".to_owned(),
FfiType::RustCallStatus => "UniffiRustCallStatus.ByValue()".to_owned(),
_ => unimplemented!("ffi_default_value: {ffi_type:?}"),
}
}
fn ffi_type_label_by_reference(&self, ffi_type: &FfiType) -> String {
match ffi_type {
FfiType::Int8
| FfiType::UInt8
| FfiType::Int16
| FfiType::UInt16
| FfiType::Int32
| FfiType::UInt32
| FfiType::Int64
| FfiType::UInt64
| FfiType::Float32
| FfiType::Float64 => format!("{}ByReference", self.ffi_type_label(ffi_type)),
FfiType::RustArcPtr(_) => "PointerByReference".to_owned(),
FfiType::RustBuffer(_) | FfiType::Struct(_) => self.ffi_type_label(ffi_type),
_ => panic!("{ffi_type:?} by reference is not implemented"),
}
}
fn ffi_type_label(&self, ffi_type: &FfiType) -> String {
match ffi_type {
FfiType::Int8 | FfiType::UInt8 => "Byte".to_string(),
FfiType::Int16 | FfiType::UInt16 => "Short".to_string(),
FfiType::Int32 | FfiType::UInt32 => "Int".to_string(),
FfiType::Int64 | FfiType::UInt64 => "Long".to_string(),
FfiType::Float32 => "Float".to_string(),
FfiType::Float64 => "Double".to_string(),
FfiType::Handle => "Long".to_string(),
FfiType::RustArcPtr(_) => "Pointer".to_string(),
FfiType::RustBuffer(maybe_suffix) => {
format!("RustBuffer{}", maybe_suffix.as_deref().unwrap_or_default())
}
FfiType::RustCallStatus => "UniffiRustCallStatus.ByValue".to_string(),
FfiType::ForeignBytes => "ForeignBytes.ByValue".to_string(),
FfiType::Callback(name) => self.ffi_callback_name(name),
FfiType::Struct(name) => self.ffi_struct_name(name),
FfiType::Reference(inner) => self.ffi_type_label_by_reference(inner),
FfiType::VoidPointer => "Pointer".to_string(),
}
}
fn object_names(&self, ci: &ComponentInterface, obj: &Object) -> (String, String) {
let class_name = self.class_name(ci, obj.name());
if obj.has_callback_interface() {
let impl_name = format!("{class_name}Impl");
(class_name, impl_name)
} else {
(format!("{class_name}Interface"), class_name)
}
}
}
trait AsCodeType {
fn as_codetype(&self) -> Box<dyn CodeType>;
}
impl<T: AsType> AsCodeType for T {
fn as_codetype(&self) -> Box<dyn CodeType> {
match self.as_type() {
Type::UInt8 => Box::new(primitives::UInt8CodeType),
Type::Int8 => Box::new(primitives::Int8CodeType),
Type::UInt16 => Box::new(primitives::UInt16CodeType),
Type::Int16 => Box::new(primitives::Int16CodeType),
Type::UInt32 => Box::new(primitives::UInt32CodeType),
Type::Int32 => Box::new(primitives::Int32CodeType),
Type::UInt64 => Box::new(primitives::UInt64CodeType),
Type::Int64 => Box::new(primitives::Int64CodeType),
Type::Float32 => Box::new(primitives::Float32CodeType),
Type::Float64 => Box::new(primitives::Float64CodeType),
Type::Boolean => Box::new(primitives::BooleanCodeType),
Type::String => Box::new(primitives::StringCodeType),
Type::Bytes => Box::new(primitives::BytesCodeType),
Type::Timestamp => Box::new(miscellany::TimestampCodeType),
Type::Duration => Box::new(miscellany::DurationCodeType),
Type::Enum { name, .. } => Box::new(enum_::EnumCodeType::new(name)),
Type::Object { name, imp, .. } => Box::new(object::ObjectCodeType::new(name, imp)),
Type::Record { name, .. } => Box::new(record::RecordCodeType::new(name)),
Type::CallbackInterface { name, .. } => {
Box::new(callback_interface::CallbackInterfaceCodeType::new(name))
}
Type::Optional { inner_type } => {
Box::new(compounds::OptionalCodeType::new(*inner_type))
}
Type::Sequence { inner_type } => {
Box::new(compounds::SequenceCodeType::new(*inner_type))
}
Type::Map {
key_type,
value_type,
} => Box::new(compounds::MapCodeType::new(*key_type, *value_type)),
Type::External { name, .. } => Box::new(external::ExternalCodeType::new(name)),
Type::Custom { name, .. } => Box::new(custom::CustomCodeType::new(name)),
}
}
}
mod filters {
use super::*;
pub use crate::backend::filters::*;
use uniffi_meta::LiteralMetadata;
pub(super) fn type_name(
as_ct: &impl AsCodeType,
ci: &ComponentInterface,
) -> Result<String, askama::Error> {
Ok(as_ct.as_codetype().type_label(ci))
}
pub(super) fn canonical_name(as_ct: &impl AsCodeType) -> Result<String, askama::Error> {
Ok(as_ct.as_codetype().canonical_name())
}
pub(super) fn ffi_converter_name(as_ct: &impl AsCodeType) -> Result<String, askama::Error> {
Ok(as_ct.as_codetype().ffi_converter_name())
}
pub(super) fn lower_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> {
Ok(format!(
"{}.lower",
as_ct.as_codetype().ffi_converter_name()
))
}
pub(super) fn allocation_size_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> {
Ok(format!(
"{}.allocationSize",
as_ct.as_codetype().ffi_converter_name()
))
}
pub(super) fn write_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> {
Ok(format!(
"{}.write",
as_ct.as_codetype().ffi_converter_name()
))
}
pub(super) fn lift_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> {
Ok(format!("{}.lift", as_ct.as_codetype().ffi_converter_name()))
}
pub(super) fn read_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> {
Ok(format!("{}.read", as_ct.as_codetype().ffi_converter_name()))
}
pub fn render_literal(
literal: &Literal,
as_ct: &impl AsType,
ci: &ComponentInterface,
) -> Result<String, askama::Error> {
Ok(as_ct.as_codetype().literal(literal, ci))
}
fn int_literal(t: &Option<Type>, base10: String) -> Result<String, askama::Error> {
if let Some(t) = t {
match t {
Type::Int8 | Type::Int16 | Type::Int32 | Type::Int64 => Ok(base10),
Type::UInt8 | Type::UInt16 | Type::UInt32 | Type::UInt64 => Ok(base10 + "u"),
_ => Err(askama::Error::Custom(Box::new(UniFFIError::new(
"Only ints are supported.".to_string(),
)))),
}
} else {
Err(askama::Error::Custom(Box::new(UniFFIError::new(
"Enum hasn't defined a repr".to_string(),
))))
}
}
pub fn variant_discr_literal(e: &Enum, index: &usize) -> Result<String, askama::Error> {
let literal = e.variant_discr(*index).expect("invalid index");
match literal {
LiteralMetadata::UInt(v, _, _) => int_literal(e.variant_discr_type(), v.to_string()),
LiteralMetadata::Int(v, _, _) => int_literal(e.variant_discr_type(), v.to_string()),
_ => Err(askama::Error::Custom(Box::new(UniFFIError::new(
"Only ints are supported.".to_string(),
)))),
}
}
pub fn ffi_type_name_by_value(type_: &FfiType) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.ffi_type_label_by_value(type_))
}
pub fn ffi_type_name_for_ffi_struct(type_: &FfiType) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.ffi_type_label_for_ffi_struct(type_))
}
pub fn ffi_default_value(type_: FfiType) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.ffi_default_value(&type_))
}
pub fn class_name(nm: &str, ci: &ComponentInterface) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.class_name(ci, nm))
}
pub fn fn_name(nm: &str) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.fn_name(nm))
}
pub fn var_name(nm: &str) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.var_name(nm))
}
pub fn var_name_raw(nm: &str) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.var_name_raw(nm))
}
pub fn variant_name(v: &Variant) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.enum_variant_name(v.name()))
}
pub fn error_variant_name(v: &Variant) -> Result<String, askama::Error> {
let name = v.name().to_string().to_upper_camel_case();
Ok(KotlinCodeOracle.convert_error_suffix(&name))
}
pub fn ffi_callback_name(nm: &str) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.ffi_callback_name(nm))
}
pub fn ffi_struct_name(nm: &str) -> Result<String, askama::Error> {
Ok(KotlinCodeOracle.ffi_struct_name(nm))
}
pub fn object_names(
obj: &Object,
ci: &ComponentInterface,
) -> Result<(String, String), askama::Error> {
Ok(KotlinCodeOracle.object_names(ci, obj))
}
pub fn async_poll(
callable: impl Callable,
ci: &ComponentInterface,
) -> Result<String, askama::Error> {
let ffi_func = callable.ffi_rust_future_poll(ci);
Ok(format!(
"{{ future, callback, continuation -> UniffiLib.INSTANCE.{ffi_func}(future, callback, continuation) }}"
))
}
pub fn async_complete(
callable: impl Callable,
ci: &ComponentInterface,
) -> Result<String, askama::Error> {
let ffi_func = callable.ffi_rust_future_complete(ci);
let call = format!("UniffiLib.INSTANCE.{ffi_func}(future, continuation)");
let call = match callable.return_type() {
Some(Type::External {
kind: ExternalKind::DataClass,
name,
..
}) => {
let suffix = KotlinCodeOracle.class_name(ci, &name);
format!("{call}.let {{ RustBuffer{suffix}.create(it.capacity.toULong(), it.len.toULong(), it.data) }}")
}
_ => call,
};
Ok(format!("{{ future, continuation -> {call} }}"))
}
pub fn async_free(
callable: impl Callable,
ci: &ComponentInterface,
) -> Result<String, askama::Error> {
let ffi_func = callable.ffi_rust_future_free(ci);
Ok(format!(
"{{ future -> UniffiLib.INSTANCE.{ffi_func}(future) }}"
))
}
pub fn unquote(nm: &str) -> Result<String, askama::Error> {
Ok(nm.trim_matches('`').to_string())
}
pub fn docstring(docstring: &str, spaces: &i32) -> Result<String, askama::Error> {
let middle = textwrap::indent(&textwrap::dedent(docstring), " * ");
let wrapped = format!("/**\n{middle}\n */");
let spaces = usize::try_from(*spaces).unwrap_or_default();
Ok(textwrap::indent(&wrapped, &" ".repeat(spaces)))
}
}