Debian Codegraph @

third_party/rust/uniffi_udl/src/converters/mod.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::{attributes::DictionaryAttributes, literal::convert_default_value, InterfaceCollector};
6 use anyhow::{bail, Result};
7
8 use uniffi_meta::{
9 CallbackInterfaceMetadata, FieldMetadata, RecordMetadata, TraitMethodMetadata, VariantMetadata,
10 };
11
12 mod callables;
13 mod enum_;
14 mod interface;
15
16 /// Trait to help convert WedIDL syntax nodes into `InterfaceCollector` objects.
17 ///
18 /// This trait does structural matching on the various weedle AST nodes and converts
19 /// them into appropriate structs that we can use to build up the contents of a
20 /// `InterfaceCollector`. It is basically the `TryFrom` trait except that the conversion
21 /// always happens in the context of a given `InterfaceCollector`, which is used for
22 /// resolving e.g. type definitions.
23 ///
24 /// The difference between this trait and `APIBuilder` is that `APIConverter` treats the
25 /// `InterfaceCollector` as a read-only data source for resolving types, while `APIBuilder`
26 /// actually mutates the `InterfaceCollector` to add new definitions.
27 pub(crate) trait APIConverter<T> {
28 fn convert(&self, ci: &mut InterfaceCollector) -> Result<T>;
29 }
30
31 // Convert UDL docstring into metadata docstring
32 pub(crate) fn convert_docstring(docstring: &str) -> String {
33 textwrap::dedent(docstring)
34 }
35
36 /// Convert a list of weedle items into a list of `InterfaceCollector` items,
37 /// by doing a direct item-by-item mapping.
38 impl<U, T: APIConverter<U>> APIConverter<Vec<U>> for Vec<T> {
39 fn convert(&self, ci: &mut InterfaceCollector) -> Result<Vec<U>> {
40 self.iter().map(|v| v.convert(ci)).collect::<Result<_>>()
41 }
42 }
43
44 impl APIConverter<VariantMetadata> for weedle::interface::OperationInterfaceMember<'_> {
45 fn convert(&self, ci: &mut InterfaceCollector) -> Result<VariantMetadata> {
46 if self.special.is_some() {
47 bail!("special operations not supported");
48 }
49 if let Some(weedle::interface::StringifierOrStatic::Stringifier(_)) = self.modifier {
50 bail!("stringifiers are not supported");
51 }
52 // OK, so this is a little weird.
53 // The syntax we use for enum interface members is `Name(type arg, ...);`, which parses
54 // as an anonymous operation where `Name` is the return type. We re-interpret it to
55 // use `Name` as the name of the variant.
56 if self.identifier.is_some() {
57 bail!("enum interface members must not have a method name");
58 }
59 let name: String = {
60 use weedle::types::{
61 NonAnyType::{self, Identifier},
62 ReturnType,
63 SingleType::NonAny,
64 Type::Single,
65 };
66 match &self.return_type {
67 ReturnType::Type(Single(NonAny(Identifier(id)))) => id.type_.0.to_owned(),
68 // Using recognized/parsed types as enum variant names can lead to the bail error because they match
69 // before `Identifier`. `Error` is one that's likely to be common, so we're circumventing what is
70 // likely a parsing issue here. As an example of the issue `Promise` (`Promise(PromiseType<'a>)`) as
71 // a variant matches the `Identifier` arm, but `DataView` (`DataView(MayBeNull<term!(DataView)>)`)
72 // fails.
73 ReturnType::Type(Single(NonAny(NonAnyType::Error(_)))) => "Error".to_string(),
74 _ => bail!("enum interface members must have plain identifiers as names"),
75 }
76 };
77 Ok(VariantMetadata {
78 name,
79 discr: None,
80 fields: self
81 .args
82 .body
83 .list
84 .iter()
85 .map(|arg| arg.convert(ci))
86 .collect::<Result<Vec<_>>>()?,
87 docstring: self.docstring.as_ref().map(|v| convert_docstring(&v.0)),
88 })
89 }
90 }
91
92 impl APIConverter<RecordMetadata> for weedle::DictionaryDefinition<'_> {
93 fn convert(&self, ci: &mut InterfaceCollector) -> Result<RecordMetadata> {
94 let attributes = DictionaryAttributes::try_from(self.attributes.as_ref())?;
95 if self.inheritance.is_some() {
96 bail!("dictionary inheritance is not supported");
97 }
98 Ok(RecordMetadata {
99 module_path: ci.module_path(),
100 name: self.identifier.0.to_string(),
101 remote: attributes.contains_remote(),
102 fields: self.members.body.convert(ci)?,
103 docstring: self.docstring.as_ref().map(|v| convert_docstring(&v.0)),
104 })
105 }
106 }
107
108 impl APIConverter<FieldMetadata> for weedle::dictionary::DictionaryMember<'_> {
109 fn convert(&self, ci: &mut InterfaceCollector) -> Result<FieldMetadata> {
110 if self.attributes.is_some() {
111 bail!("dictionary member attributes are not supported yet");
112 }
113 let type_ = ci.resolve_type_expression(&self.type_)?;
114 let default = match self.default {
115 None => None,
116 Some(v) => Some(convert_default_value(&v.value, &type_)?),
117 };
118 Ok(FieldMetadata {
119 name: self.identifier.0.to_string(),
120 ty: type_,
121 default,
122 docstring: self.docstring.as_ref().map(|v| convert_docstring(&v.0)),
123 })
124 }
125 }
126
127 impl APIConverter<CallbackInterfaceMetadata> for weedle::CallbackInterfaceDefinition<'_> {
128 fn convert(&self, ci: &mut InterfaceCollector) -> Result<CallbackInterfaceMetadata> {
129 if self.attributes.is_some() {
130 bail!("callback interface attributes are not supported yet");
131 }
132 if self.inheritance.is_some() {
133 bail!("callback interface inheritance is not supported");
134 }
135 let object_name = self.identifier.0;
136 for (index, member) in self.members.body.iter().enumerate() {
137 match member {
138 weedle::interface::InterfaceMember::Operation(t) => {
139 let mut method: TraitMethodMetadata = t.convert(ci)?;
140 // A CallbackInterface is described in Rust as a trait, but uniffi
141 // generates a struct implementing the trait and passes the concrete version
142 // of that.
143 // This really just reflects the fact that CallbackInterface and Object
144 // should be merged; we'd still need a way to ask for a struct delegating to
145 // foreign implementations be done.
146 // But currently they are passed as a concrete type with no associated types.
147 method.trait_name = object_name.to_string();
148 method.index = index as u32;
149 ci.items.insert(method.into());
150 }
151 _ => bail!(
152 "no support for callback interface member type {:?} yet",
153 member
154 ),
155 }
156 }
157 Ok(CallbackInterfaceMetadata {
158 module_path: ci.module_path(),
159 name: object_name.to_string(),
160 docstring: self.docstring.as_ref().map(|v| convert_docstring(&v.0)),
161 })
162 }
163 }
164
165 #[cfg(test)]
166 mod test {
167 use super::*;
168 use uniffi_meta::{LiteralMetadata, Metadata, Radix, Type};
169
170 #[test]
171 fn test_multiple_record_types() {
172 const UDL: &str = r#"
173 namespace test{};
174 dictionary Empty {};
175 dictionary Simple {
176 u32 field;
177 };
178 dictionary Complex {
179 string? key;
180 u32 value = 0;
181 required boolean spin;
182 };
183 "#;
184 let mut ci = InterfaceCollector::from_webidl(UDL, "crate-name").unwrap();
185 assert_eq!(ci.items.len(), 3);
186 match &ci.items.pop_first().unwrap() {
187 Metadata::Record(record) => {
188 assert_eq!(record.name, "Complex");
189 assert_eq!(record.fields.len(), 3);
190 assert_eq!(record.fields[0].name, "key");
191 assert_eq!(
192 record.fields[0].ty,
193 Type::Optional {
194 inner_type: Box::new(Type::String)
195 }
196 );
197 assert!(record.fields[0].default.is_none());
198 assert_eq!(record.fields[1].name, "value");
199 assert_eq!(record.fields[1].ty, Type::UInt32);
200 assert!(matches!(
201 record.fields[1].default,
202 Some(LiteralMetadata::UInt(0, Radix::Decimal, Type::UInt32))
203 ));
204 assert_eq!(record.fields[2].name, "spin");
205 assert_eq!(record.fields[2].ty, Type::Boolean);
206 assert!(record.fields[2].default.is_none());
207 }
208 _ => unreachable!(),
209 }
210
211 match &ci.items.pop_first().unwrap() {
212 Metadata::Record(record) => {
213 assert_eq!(record.name, "Empty");
214 assert_eq!(record.fields.len(), 0);
215 }
216 _ => unreachable!(),
217 }
218
219 match &ci.items.pop_first().unwrap() {
220 Metadata::Record(record) => {
221 assert_eq!(record.name, "Simple");
222 assert_eq!(record.fields.len(), 1);
223 assert_eq!(record.fields[0].name, "field");
224 assert_eq!(record.fields[0].ty, Type::UInt32);
225 assert!(record.fields[0].default.is_none());
226 }
227 _ => unreachable!(),
228 }
229 }
230 }