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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
|
/* 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/. */
//! # Function definitions for a `ComponentInterface`.
//!
//! This module converts function definitions from UDL into structures that
//! can be added to a `ComponentInterface`. A declaration in the UDL like this:
//!
//! ```
//! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
//! namespace example {
//! string hello();
//! };
//! # "##)?;
//! # Ok::<(), anyhow::Error>(())
//! ```
//!
//! Will result in a [`Function`] member being added to the resulting [`ComponentInterface`]:
//!
//! ```
//! # use uniffi_bindgen::interface::Type;
//! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
//! # namespace example {
//! # string hello();
//! # };
//! # "##)?;
//! let func = ci.get_function_definition("hello").unwrap();
//! assert_eq!(func.name(), "hello");
//! assert!(matches!(func.return_type(), Some(Type::String)));
//! assert_eq!(func.arguments().len(), 0);
//! # Ok::<(), anyhow::Error>(())
//! ```
use std::convert::TryFrom;
use anyhow::{bail, Result};
use uniffi_meta::Checksum;
use super::attributes::{ArgumentAttributes, Attribute, FunctionAttributes};
use super::ffi::{FfiArgument, FfiFunction};
use super::literal::{convert_default_value, Literal};
use super::types::{Type, TypeIterator};
use super::{convert_type, APIConverter, ComponentInterface};
/// Represents a standalone function.
///
/// Each `Function` corresponds to a standalone function in the rust module,
/// and has a corresponding standalone function in the foreign language bindings.
///
/// In the FFI, this will be a standalone function with appropriately lowered types.
#[derive(Debug, Clone, Checksum)]
pub struct Function {
pub(super) name: String,
pub(super) arguments: Vec<Argument>,
pub(super) return_type: Option<Type>,
// We don't include the FFIFunc in the hash calculation, because:
// - it is entirely determined by the other fields,
// so excluding it is safe.
// - its `name` property includes a checksum derived from the very
// hash value we're trying to calculate here, so excluding it
// avoids a weird circular dependency in the calculation.
#[checksum_ignore]
pub(super) ffi_func: FfiFunction,
pub(super) attributes: FunctionAttributes,
}
impl Function {
pub fn name(&self) -> &str {
&self.name
}
pub fn arguments(&self) -> Vec<&Argument> {
self.arguments.iter().collect()
}
pub fn full_arguments(&self) -> Vec<Argument> {
self.arguments.to_vec()
}
pub fn return_type(&self) -> Option<&Type> {
self.return_type.as_ref()
}
pub fn ffi_func(&self) -> &FfiFunction {
&self.ffi_func
}
pub fn throws(&self) -> bool {
self.attributes.get_throws_err().is_some()
}
pub fn throws_name(&self) -> Option<&str> {
self.attributes.get_throws_err()
}
pub fn throws_type(&self) -> Option<Type> {
self.attributes
.get_throws_err()
.map(|name| Type::Error(name.to_owned()))
}
pub fn derive_ffi_func(&mut self, ci_prefix: &str) -> Result<()> {
// The name is already set if the function is defined through a proc-macro invocation
// rather than in UDL. Don't overwrite it in that case.
if self.ffi_func.name.is_empty() {
self.ffi_func.name = format!("{ci_prefix}_{}", self.name);
}
self.ffi_func.arguments = self.arguments.iter().map(|arg| arg.into()).collect();
self.ffi_func.return_type = self.return_type.as_ref().map(|rt| rt.into());
Ok(())
}
}
impl From<uniffi_meta::FnParamMetadata> for Argument {
fn from(meta: uniffi_meta::FnParamMetadata) -> Self {
Argument {
name: meta.name,
type_: convert_type(&meta.ty),
by_ref: false,
optional: false,
default: None,
}
}
}
impl From<uniffi_meta::FnMetadata> for Function {
fn from(meta: uniffi_meta::FnMetadata) -> Self {
let ffi_name = meta.ffi_symbol_name();
let return_type = meta.return_type.map(|out| convert_type(&out));
let arguments = meta.inputs.into_iter().map(Into::into).collect();
let ffi_func = FfiFunction {
name: ffi_name,
..FfiFunction::default()
};
Self {
name: meta.name,
arguments,
return_type,
ffi_func,
attributes: meta.throws.map(Attribute::Throws).into_iter().collect(),
}
}
}
impl APIConverter<Function> for weedle::namespace::NamespaceMember<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Function> {
match self {
weedle::namespace::NamespaceMember::Operation(f) => f.convert(ci),
_ => bail!("no support for namespace member type {:?} yet", self),
}
}
}
impl APIConverter<Function> for weedle::namespace::OperationNamespaceMember<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Function> {
let return_type = ci.resolve_return_type_expression(&self.return_type)?;
Ok(Function {
name: match self.identifier {
None => bail!("anonymous functions are not supported {:?}", self),
Some(id) => id.0.to_string(),
},
return_type,
arguments: self.args.body.list.convert(ci)?,
ffi_func: Default::default(),
attributes: FunctionAttributes::try_from(self.attributes.as_ref())?,
})
}
}
/// Represents an argument to a function/constructor/method call.
///
/// Each argument has a name and a type, along with some optional metadata.
#[derive(Debug, Clone, Checksum)]
pub struct Argument {
pub(super) name: String,
pub(super) type_: Type,
pub(super) by_ref: bool,
pub(super) optional: bool,
pub(super) default: Option<Literal>,
}
impl Argument {
pub fn name(&self) -> &str {
&self.name
}
pub fn type_(&self) -> &Type {
&self.type_
}
pub fn by_ref(&self) -> bool {
self.by_ref
}
pub fn default_value(&self) -> Option<&Literal> {
self.default.as_ref()
}
pub fn iter_types(&self) -> TypeIterator<'_> {
self.type_.iter_types()
}
}
impl From<&Argument> for FfiArgument {
fn from(a: &Argument) -> FfiArgument {
FfiArgument {
name: a.name.clone(),
type_: (&a.type_).into(),
}
}
}
impl APIConverter<Argument> for weedle::argument::Argument<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Argument> {
match self {
weedle::argument::Argument::Single(t) => t.convert(ci),
weedle::argument::Argument::Variadic(_) => bail!("variadic arguments not supported"),
}
}
}
impl APIConverter<Argument> for weedle::argument::SingleArgument<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Argument> {
let type_ = ci.resolve_type_expression(&self.type_)?;
let default = match self.default {
None => None,
Some(v) => Some(convert_default_value(&v.value, &type_)?),
};
let by_ref = ArgumentAttributes::try_from(self.attributes.as_ref())?.by_ref();
Ok(Argument {
name: self.identifier.0.to_string(),
type_,
by_ref,
optional: self.optional.is_some(),
default,
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_minimal_and_rich_function() -> Result<()> {
let ci = ComponentInterface::from_webidl(
r##"
namespace test {
void minimal();
[Throws=TestError]
sequence<string?> rich(u32 arg1, TestDict arg2);
};
[Error]
enum TestError { "err" };
dictionary TestDict {
u32 field;
};
"##,
)?;
let func1 = ci.get_function_definition("minimal").unwrap();
assert_eq!(func1.name(), "minimal");
assert!(func1.return_type().is_none());
assert!(func1.throws_type().is_none());
assert_eq!(func1.arguments().len(), 0);
let func2 = ci.get_function_definition("rich").unwrap();
assert_eq!(func2.name(), "rich");
assert_eq!(
func2.return_type().unwrap().canonical_name(),
"SequenceOptionalstring"
);
assert!(matches!(func2.throws_type(), Some(Type::Error(s)) if s == "TestError"));
assert_eq!(func2.arguments().len(), 2);
assert_eq!(func2.arguments()[0].name(), "arg1");
assert_eq!(func2.arguments()[0].type_().canonical_name(), "u32");
assert_eq!(func2.arguments()[1].name(), "arg2");
assert_eq!(
func2.arguments()[1].type_().canonical_name(),
"TypeTestDict"
);
Ok(())
}
}
|