summaryrefslogtreecommitdiff
path: root/src/ffi/callbackinterface.rs
blob: e7a4faab64b0e277a8f587ad13912933e778ab70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/* 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/. */

//! Callback interfaces are traits specified in UDL which can be implemented by foreign languages.
//!
//! # Using callback interfaces
//!
//! 1. Define a Rust trait.
//!
//! This toy example defines a way of Rust accessing a key-value store exposed
//! by the host operating system (e.g. the key chain).
//!
//! ```
//! trait Keychain: Send {
//!   fn get(&self, key: String) -> Option<String>;
//!   fn put(&self, key: String, value: String);
//! }
//! ```
//!
//! 2. Define a callback interface in the UDL
//!
//! ```idl
//! callback interface Keychain {
//!     string? get(string key);
//!     void put(string key, string data);
//! };
//! ```
//!
//! 3. And allow it to be passed into Rust.
//!
//! Here, we define a constructor to pass the keychain to rust, and then another method
//! which may use it.
//!
//! In UDL:
//! ```idl
//! object Authenticator {
//!     constructor(Keychain keychain);
//!     void login();
//! }
//! ```
//!
//! In Rust:
//!
//! ```
//!# trait Keychain: Send {
//!#  fn get(&self, key: String) -> Option<String>;
//!#  fn put(&self, key: String, value: String);
//!# }
//! struct Authenticator {
//!   keychain: Box<dyn Keychain>,
//! }
//!
//! impl Authenticator {
//!   pub fn new(keychain: Box<dyn Keychain>) -> Self {
//!     Self { keychain }
//!   }
//!   pub fn login(&self) {
//!     let username = self.keychain.get("username".into());
//!     let password = self.keychain.get("password".into());
//!   }
//! }
//! ```
//! 4. Create an foreign language implementation of the callback interface.
//!
//! In this example, here's a Kotlin implementation.
//!
//! ```kotlin
//! class AndroidKeychain: Keychain {
//!     override fun get(key: String): String? {
//!         // … elide the implementation.
//!         return value
//!     }
//!     override fun put(key: String) {
//!         // … elide the implementation.
//!     }
//! }
//! ```
//! 5. Pass the implementation to Rust.
//!
//! Again, in Kotlin
//!
//! ```kotlin
//! val authenticator = Authenticator(AndroidKeychain())
//! authenticator.login()
//! ```
//!
//! # How it works.
//!
//! ## High level
//!
//! Uniffi generates a protocol or interface in client code in the foreign language must implement.
//!
//! For each callback interface, UniFFI defines a VTable.
//! This is a `repr(C)` struct where each field is a `repr(C)` callback function pointer.
//! There is one field for each method, plus an extra field for the `uniffi_free` method.
//! The foreign code registers one VTable per callback interface with Rust.
//!
//! VTable methods have a similar signature to Rust scaffolding functions.
//! The one difference is that values are returned via an out pointer to work around a Python bug (https://bugs.python.org/issue5710).
//!
//! The foreign object that implements the interface is represented by an opaque handle.
//! UniFFI generates a struct that implements the trait by calling VTable methods, passing the handle as the first parameter.
//! When the struct is dropped, the `uniffi_free` method is called.

use std::fmt;

/// Used when internal/unexpected error happened when calling a foreign callback, for example when
/// a unknown exception is raised
///
/// User callback error types must implement a From impl from this type to their own error type.
#[derive(Debug)]
pub struct UnexpectedUniFFICallbackError {
    pub reason: String,
}

impl UnexpectedUniFFICallbackError {
    pub fn new(reason: impl fmt::Display) -> Self {
        Self {
            reason: reason.to_string(),
        }
    }
}

impl fmt::Display for UnexpectedUniFFICallbackError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "UnexpectedUniFFICallbackError(reason: {:?})",
            self.reason
        )
    }
}

impl std::error::Error for UnexpectedUniFFICallbackError {}

// Autoref-based specialization for converting UnexpectedUniFFICallbackError into error types.
//
// For more details, see:
// https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md

// Define two ZST types:
//   - One implements `try_convert_unexpected_callback_error` by always returning an error value.
//   - The specialized version implements it using `From<UnexpectedUniFFICallbackError>`

#[doc(hidden)]
#[derive(Debug)]
pub struct UnexpectedUniFFICallbackErrorConverterGeneric;

impl UnexpectedUniFFICallbackErrorConverterGeneric {
    pub fn try_convert_unexpected_callback_error<E>(
        &self,
        e: UnexpectedUniFFICallbackError,
    ) -> anyhow::Result<E> {
        Err(e.into())
    }
}

#[doc(hidden)]
#[derive(Debug)]
pub struct UnexpectedUniFFICallbackErrorConverterSpecialized;

impl UnexpectedUniFFICallbackErrorConverterSpecialized {
    pub fn try_convert_unexpected_callback_error<E>(
        &self,
        e: UnexpectedUniFFICallbackError,
    ) -> anyhow::Result<E>
    where
        E: From<UnexpectedUniFFICallbackError>,
    {
        Ok(E::from(e))
    }
}

// Macro to convert an UnexpectedUniFFICallbackError value for a particular type.  This is used in
// the `ConvertError` implementation.
#[doc(hidden)]
#[macro_export]
macro_rules! convert_unexpected_error {
    ($error:ident, $ty:ty) => {{
        // Trait for generic conversion, implemented for all &T.
        pub trait GetConverterGeneric {
            fn get_converter(&self) -> $crate::UnexpectedUniFFICallbackErrorConverterGeneric;
        }

        impl<T> GetConverterGeneric for &T {
            fn get_converter(&self) -> $crate::UnexpectedUniFFICallbackErrorConverterGeneric {
                $crate::UnexpectedUniFFICallbackErrorConverterGeneric
            }
        }
        // Trait for specialized conversion, implemented for all T that implements
        // `Into<ErrorType>`.  I.e. it's implemented for UnexpectedUniFFICallbackError when
        // ErrorType implements From<UnexpectedUniFFICallbackError>.
        pub trait GetConverterSpecialized {
            fn get_converter(&self) -> $crate::UnexpectedUniFFICallbackErrorConverterSpecialized;
        }

        impl<T: Into<$ty>> GetConverterSpecialized for T {
            fn get_converter(&self) -> $crate::UnexpectedUniFFICallbackErrorConverterSpecialized {
                $crate::UnexpectedUniFFICallbackErrorConverterSpecialized
            }
        }
        // Here's the hack.  Because of the auto-ref rules, this will use `GetConverterSpecialized`
        // if it's implemented and `GetConverterGeneric` if not.
        (&$error)
            .get_converter()
            .try_convert_unexpected_callback_error($error)
    }};
}