forked from mozilla/uniffi-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenum_.rs
414 lines (384 loc) · 13.7 KB
/
enum_.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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/* 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/. */
//! # Enum definitions for a `ComponentInterface`.
//!
//! This module converts enum definition 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 {};
//! enum Example {
//! "one",
//! "two"
//! };
//! # "##)?;
//! # Ok::<(), anyhow::Error>(())
//! ```
//!
//! Will result in a [`Enum`] member being added to the resulting [`ComponentInterface`]:
//!
//! ```
//! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
//! # namespace example {};
//! # enum Example {
//! # "one",
//! # "two"
//! # };
//! # "##)?;
//! let e = ci.get_enum_definition("Example").unwrap();
//! assert_eq!(e.name(), "Example");
//! assert_eq!(e.variants().len(), 2);
//! assert_eq!(e.variants()[0].name(), "one");
//! assert_eq!(e.variants()[1].name(), "two");
//! # Ok::<(), anyhow::Error>(())
//! ```
//!
//! Like in Rust, UniFFI enums can contain associated data, but this needs to be
//! declared with a different syntax in order to work within the restrictions of
//! WebIDL. A declaration like this:
//!
//! ```
//! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
//! # namespace example {};
//! [Enum]
//! interface Example {
//! Zero();
//! One(u32 first);
//! Two(u32 first, string second);
//! };
//! # "##)?;
//! # Ok::<(), anyhow::Error>(())
//! ```
//!
//! Will result in an [`Enum`] member whose variants have associated fields:
//!
//! ```
//! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
//! # namespace example {};
//! # [Enum]
//! # interface ExampleWithData {
//! # Zero();
//! # One(u32 first);
//! # Two(u32 first, string second);
//! # };
//! # "##)?;
//! let e = ci.get_enum_definition("ExampleWithData").unwrap();
//! assert_eq!(e.name(), "ExampleWithData");
//! assert_eq!(e.variants().len(), 3);
//! assert_eq!(e.variants()[0].name(), "Zero");
//! assert_eq!(e.variants()[0].fields().len(), 0);
//! assert_eq!(e.variants()[1].name(), "One");
//! assert_eq!(e.variants()[1].fields().len(), 1);
//! assert_eq!(e.variants()[1].fields()[0].name(), "first");
//! # Ok::<(), anyhow::Error>(())
//! ```
use anyhow::{bail, Result};
use super::record::Field;
use super::types::{Type, TypeIterator};
use super::{APIConverter, ComponentInterface};
/// Represents an enum with named variants, each of which may have named
/// and typed fields.
///
/// Enums are passed across the FFI by serializing to a bytebuffer, with a
/// i32 indicating the variant followed by the serialization of each field.
#[derive(Debug, Clone, Hash)]
pub struct Enum {
pub(super) name: String,
pub(super) variants: Vec<Variant>,
// "Flat" enums do not have, and will never have, variants with associated data.
pub(super) flat: bool,
}
impl Enum {
pub fn name(&self) -> &str {
&self.name
}
pub fn type_(&self) -> Type {
// *sigh* at the clone here, the relationship between a ComponentInterace
// and its contained types could use a bit of a cleanup.
Type::Enum(self.name.clone())
}
pub fn variants(&self) -> Vec<&Variant> {
self.variants.iter().collect()
}
pub fn is_flat(&self) -> bool {
self.flat
}
pub fn iter_types(&self) -> TypeIterator<'_> {
Box::new(self.variants.iter().flat_map(Variant::iter_types))
}
}
// Note that we have two `APIConverter` impls here - one for the `enum` case
// and one for the `[Enum] interface` case.
impl APIConverter<Enum> for weedle::EnumDefinition<'_> {
fn convert(&self, _ci: &mut ComponentInterface) -> Result<Enum> {
Ok(Enum {
name: self.identifier.0.to_string(),
variants: self
.values
.body
.list
.iter()
.map::<Result<_>, _>(|v| {
Ok(Variant {
name: v.0.to_string(),
..Default::default()
})
})
.collect::<Result<Vec<_>>>()?,
// Enums declared using the `enum` syntax can never have variants with fields.
flat: true,
})
}
}
impl APIConverter<Enum> for weedle::InterfaceDefinition<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Enum> {
if self.inheritance.is_some() {
bail!("interface inheritence is not supported for enum interfaces");
}
// We don't need to check `self.attributes` here; if calling code has dispatched
// to this impl then we already know there was an `[Enum]` attribute.
Ok(Enum {
name: self.identifier.0.to_string(),
variants: self
.members
.body
.iter()
.map::<Result<Variant>, _>(|member| match member {
weedle::interface::InterfaceMember::Operation(t) => Ok(t.convert(ci)?),
_ => bail!(
"interface member type {:?} not supported in enum interface",
member
),
})
.collect::<Result<Vec<_>>>()?,
// Enums declared using the `[Enum] interface` syntax might have variants with fields.
flat: false,
})
}
}
/// Represents an individual variant in an Enum.
///
/// Each variant has a name and zero or more fields.
#[derive(Debug, Clone, Default, Hash)]
pub struct Variant {
pub(super) name: String,
pub(super) fields: Vec<Field>,
}
impl Variant {
pub fn name(&self) -> &str {
&self.name
}
pub fn fields(&self) -> Vec<&Field> {
self.fields.iter().collect()
}
pub fn has_fields(&self) -> bool {
!self.fields.is_empty()
}
pub fn iter_types(&self) -> TypeIterator<'_> {
Box::new(self.fields.iter().flat_map(Field::iter_types))
}
}
impl APIConverter<Variant> for weedle::interface::OperationInterfaceMember<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Variant> {
if self.special.is_some() {
bail!("special operations not supported");
}
if let Some(weedle::interface::StringifierOrStatic::Stringifier(_)) = self.modifier {
bail!("stringifiers are not supported");
}
// OK, so this is a little weird.
// The syntax we use for enum interface members is `Name(type arg, ...);`, which parses
// as an anonymous operation where `Name` is the return type. We re-interpret it to
// use `Name` as the name of the variant.
if self.identifier.is_some() {
bail!("enum interface members must not have a method name");
}
let name: String = {
use weedle::types::{
NonAnyType::Identifier, ReturnType, SingleType::NonAny, Type::Single,
};
match &self.return_type {
ReturnType::Type(Single(NonAny(Identifier(id)))) => id.type_.0.to_owned(),
_ => bail!("enum interface members must have plain identifers as names"),
}
};
Ok(Variant {
name,
fields: self
.args
.body
.list
.iter()
.map(|arg| arg.convert(ci))
.collect::<Result<Vec<_>>>()?,
})
}
}
impl APIConverter<Field> for weedle::argument::Argument<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Field> {
match self {
weedle::argument::Argument::Single(t) => t.convert(ci),
weedle::argument::Argument::Variadic(_) => bail!("variadic arguments not supported"),
}
}
}
impl APIConverter<Field> for weedle::argument::SingleArgument<'_> {
fn convert(&self, ci: &mut ComponentInterface) -> Result<Field> {
let type_ = ci.resolve_type_expression(&self.type_)?;
if let Type::Object(_) = type_ {
bail!("Objects cannot currently be used in enum variant data");
}
if self.default.is_some() {
bail!("enum interface variant fields must not have default values");
}
if self.attributes.is_some() {
bail!("enum interface variant fields must not have attributes");
}
// TODO: maybe we should use our own `Field` type here with just name and type,
// rather than appropriating record::Field..?
Ok(Field {
name: self.identifier.0.to_string(),
type_,
required: false,
default: None,
})
}
}
#[cfg(test)]
mod test {
use super::super::ffi::FFIType;
use super::*;
#[test]
fn test_duplicate_variants() {
const UDL: &str = r#"
namespace test{};
// Weird, but currently allowed!
// We should probably disallow this...
enum Testing { "one", "two", "one" };
"#;
let ci = ComponentInterface::from_webidl(UDL).unwrap();
assert_eq!(ci.enum_definitions().len(), 1);
assert_eq!(
ci.get_enum_definition("Testing").unwrap().variants().len(),
3
);
}
#[test]
fn test_associated_data() {
const UDL: &str = r##"
namespace test {
void takes_an_enum(TestEnum e);
void takes_an_enum_with_data(TestEnumWithData ed);
TestEnum returns_an_enum();
TestEnumWithData returns_an_enum_with_data();
};
enum TestEnum { "one", "two" };
[Enum]
interface TestEnumWithData {
Zero();
One(u32 first);
Two(u32 first, string second);
};
[Enum]
interface TestEnumWithoutData {
One();
Two();
};
"##;
let ci = ComponentInterface::from_webidl(UDL).unwrap();
assert_eq!(ci.enum_definitions().len(), 3);
assert_eq!(ci.function_definitions().len(), 4);
// The "flat" enum with no associated data.
let e = ci.get_enum_definition("TestEnum").unwrap();
assert!(e.is_flat());
assert_eq!(e.variants().len(), 2);
assert_eq!(
e.variants().iter().map(|v| v.name()).collect::<Vec<_>>(),
vec!["one", "two"]
);
assert_eq!(e.variants()[0].fields().len(), 0);
assert_eq!(e.variants()[1].fields().len(), 0);
// The enum with associated data.
let ed = ci.get_enum_definition("TestEnumWithData").unwrap();
assert!(!ed.is_flat());
assert_eq!(ed.variants().len(), 3);
assert_eq!(
ed.variants().iter().map(|v| v.name()).collect::<Vec<_>>(),
vec!["Zero", "One", "Two"]
);
assert_eq!(ed.variants()[0].fields().len(), 0);
assert_eq!(
ed.variants()[1]
.fields()
.iter()
.map(|f| f.name())
.collect::<Vec<_>>(),
vec!["first"]
);
assert_eq!(
ed.variants()[1]
.fields()
.iter()
.map(|f| f.type_())
.collect::<Vec<_>>(),
vec![Type::UInt32]
);
assert_eq!(
ed.variants()[2]
.fields()
.iter()
.map(|f| f.name())
.collect::<Vec<_>>(),
vec!["first", "second"]
);
assert_eq!(
ed.variants()[2]
.fields()
.iter()
.map(|f| f.type_())
.collect::<Vec<_>>(),
vec![Type::UInt32, Type::String]
);
// The enum declared via interface, but with no associated data.
let ewd = ci.get_enum_definition("TestEnumWithoutData").unwrap();
assert!(!ewd.is_flat());
assert_eq!(ewd.variants().len(), 2);
assert_eq!(
ewd.variants().iter().map(|v| v.name()).collect::<Vec<_>>(),
vec!["One", "Two"]
);
assert_eq!(ewd.variants()[0].fields().len(), 0);
assert_eq!(ewd.variants()[1].fields().len(), 0);
// Flat enums pass over the FFI as bytebuffers.
// (It might be nice to optimize these to pass as plain integers, but that's
// difficult atop the current factoring of `ComponentInterface` and friends).
let farg = ci.get_function_definition("takes_an_enum").unwrap();
assert_eq!(farg.arguments()[0].type_(), Type::Enum("TestEnum".into()));
assert_eq!(farg.ffi_func().arguments()[0].type_(), FFIType::RustBuffer);
let fret = ci.get_function_definition("returns_an_enum").unwrap();
assert!(matches!(fret.return_type(), Some(Type::Enum(nm)) if nm == "TestEnum"));
assert!(matches!(
fret.ffi_func().return_type(),
Some(FFIType::RustBuffer)
));
// Enums with associated data pass over the FFI as bytebuffers.
let farg = ci
.get_function_definition("takes_an_enum_with_data")
.unwrap();
assert_eq!(
farg.arguments()[0].type_(),
Type::Enum("TestEnumWithData".into())
);
assert_eq!(farg.ffi_func().arguments()[0].type_(), FFIType::RustBuffer);
let fret = ci
.get_function_definition("returns_an_enum_with_data")
.unwrap();
assert!(matches!(fret.return_type(), Some(Type::Enum(nm)) if nm == "TestEnumWithData"));
assert!(matches!(
fret.ffi_func().return_type(),
Some(FFIType::RustBuffer)
));
}
}