-
Notifications
You must be signed in to change notification settings - Fork 234
/
function.rs
247 lines (228 loc) · 8 KB
/
function.rs
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
/* 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 std::hash::{Hash, Hasher};
use anyhow::{bail, Result};
use super::attributes::{ArgumentAttributes, FunctionAttributes};
use super::ffi::{FFIArgument, FFIFunction};
use super::literal::{convert_default_value, Literal};
use super::types::Type;
use super::{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)]
pub struct Function {
pub(super) name: String,
pub(super) arguments: Vec<Argument>,
pub(super) return_type: Option<Type>,
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 return_type(&self) -> Option<&Type> {
self.return_type.as_ref()
}
pub fn ffi_func(&self) -> &FFIFunction {
&self.ffi_func
}
pub fn throws(&self) -> Option<&str> {
self.attributes.get_throws_err()
}
pub fn derive_ffi_func(&mut self, ci_prefix: &str) -> Result<()> {
self.ffi_func.name.push_str(ci_prefix);
self.ffi_func.name.push_str("_");
self.ffi_func.name.push_str(&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 Hash for Function {
fn hash<H: Hasher>(&self, state: &mut H) {
// 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 depenendency in the calculation.
self.name.hash(state);
self.arguments.hash(state);
self.return_type.hash(state);
self.attributes.hash(state);
}
}
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)?;
if let Some(Type::Object(_)) = return_type {
bail!("Objects cannot currently be returned from functions");
}
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: match &self.attributes {
Some(attr) => FunctionAttributes::try_from(attr)?,
None => Default::default(),
},
})
}
}
/// 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, Hash)]
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_.clone()
}
pub fn by_ref(&self) -> bool {
self.by_ref
}
pub fn default_value(&self) -> Option<Literal> {
self.default.clone()
}
}
impl Into<FFIArgument> for &Argument {
fn into(self: Self) -> FFIArgument {
FFIArgument {
name: self.name.clone(),
type_: (&self.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_)?;
if let Type::Object(_) = type_ {
bail!("Objects cannot currently be passed as arguments");
}
let default = match self.default {
None => None,
Some(v) => Some(convert_default_value(&v.value, &type_)?),
};
let by_ref = match &self.attributes {
Some(attrs) => ArgumentAttributes::try_from(attrs)?.by_ref(),
None => false,
};
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().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(), Some("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(),
"RecordTestDict"
);
Ok(())
}
}