Debian Codegraph @

third_party/rust/uniffi_bindgen/src/pipeline/initial/from_uniffi_meta.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 //! Organize the metadata, transforming it from a simple list to a more tree-like structure.
6
7 use anyhow::{anyhow, bail, Context, Result};
8 use camino::Utf8Path;
9 use std::{collections::BTreeMap, fs};
10
11 use super::nodes::*;
12 use uniffi_pipeline::Node;
13
14 /// Converts `uniffi_meta` items into the initial IR.
15 ///
16 /// Usage:
17 /// * Call [Self::add_metadata_item] with all `uniffi_meta` items in the interface (also [Self::add_module_docstring])
18 /// * Call [Self::try_into_initial_ir] to construct a `initial::Root` node.
19 #[derive(Default)]
20 pub struct UniffiMetaConverter {
21 // Map module_path to `Module::name`
22 //
23 // This is needed because UDL and proc-macro code can generate different module paths. To
24 // normalize things, we find the `NamespaceMetadata::name` that matches the module path.
25 //
26 // Use BTreeMap for each of these so that things stay consistent, regardless of how the
27 // metadata is ordered.
28 module_path_map: BTreeMap<String, String>,
29 // Top level modules
30 modules: BTreeMap<String, Module>,
31 // Top-level type definitions and functions, keyed by module name
32 module_docstrings: BTreeMap<String, String>,
33 module_toml: BTreeMap<String, String>,
34 functions: BTreeMap<String, BTreeMap<String, Function>>,
35 records: BTreeMap<String, BTreeMap<String, Record>>,
36 callback_interfaces: BTreeMap<String, BTreeMap<String, CallbackInterface>>,
37 enums: BTreeMap<String, BTreeMap<String, Enum>>,
38 custom_types: BTreeMap<String, BTreeMap<String, CustomType>>,
39 interfaces: BTreeMap<String, BTreeMap<String, Interface>>,
40 // Child items, keyed by module name + parent name
41 constructors: BTreeMap<(String, String), BTreeMap<String, Constructor>>,
42 methods: BTreeMap<(String, String), BTreeMap<String, Method>>,
43 trait_methods: BTreeMap<(String, String), BTreeMap<String, TraitMethod>>,
44 uniffi_traits: BTreeMap<(String, String), BTreeMap<String, UniffiTrait>>,
45 trait_impls: BTreeMap<(String, String), BTreeMap<String, ObjectTraitImpl>>,
46 }
47
48 impl UniffiMetaConverter {
49 /// Add a [uniffi_meta::Metadata] item to be converted
50 pub fn add_metadata_item(&mut self, meta: uniffi_meta::Metadata) -> Result<()> {
51 match meta {
52 uniffi_meta::Metadata::Namespace(namespace) => {
53 // Map both the crate name and module name to the module name. This simplifies the
54 // code in `get_module`
55 self.module_path_map
56 .insert(namespace.crate_name.clone(), namespace.name.clone());
57 self.module_path_map
58 .insert(namespace.name.clone(), namespace.name.clone());
59 // Insert a new module
60 self.modules
61 .entry(namespace.name.clone())
62 .or_insert(Module {
63 // TODO: Is this the correct crate name in all cases? I'm pretty sure
64 // it is for proc-macro based generation, since the proc-macro
65 // namespace is added to the metadata list before the UDL one.
66 // However, I'm not so sure what happens if we're generating from a UDL
67 // file.
68 crate_name: namespace.crate_name,
69 docstring: None,
70 config_toml: None,
71 name: namespace.name,
72 functions: vec![],
73 type_definitions: vec![],
74 });
75 }
76 uniffi_meta::Metadata::Func(func) => {
77 self.functions
78 .entry(func.module_path.clone())
79 .or_default()
80 .insert(func.name.clone(), Function::try_from_node(func)?);
81 }
82 uniffi_meta::Metadata::Record(rec) => {
83 self.records
84 .entry(rec.module_path.clone())
85 .or_default()
86 .insert(rec.name.clone(), Record::try_from_node(rec)?);
87 }
88 uniffi_meta::Metadata::Enum(en) => {
89 self.enums
90 .entry(en.module_path.clone())
91 .or_default()
92 .insert(en.name.clone(), Enum::try_from_node(en)?);
93 }
94 uniffi_meta::Metadata::Object(int) => {
95 self.interfaces
96 .entry(int.module_path.clone())
97 .or_default()
98 .insert(int.name.clone(), Interface::try_from_node(int)?);
99 }
100 uniffi_meta::Metadata::CallbackInterface(cbi) => {
101 self.callback_interfaces
102 .entry(cbi.module_path.clone())
103 .or_default()
104 .insert(cbi.name.clone(), CallbackInterface::try_from_node(cbi)?);
105 }
106 uniffi_meta::Metadata::CustomType(custom) => {
107 self.custom_types
108 .entry(custom.module_path.clone())
109 .or_default()
110 .insert(custom.name.clone(), CustomType::try_from_node(custom)?);
111 }
112 uniffi_meta::Metadata::Constructor(cons) => {
113 self.constructors
114 .entry((cons.module_path.clone(), cons.self_name.clone()))
115 .or_default()
116 .insert(cons.name.clone(), Constructor::try_from_node(cons)?);
117 }
118 uniffi_meta::Metadata::Method(meth) => {
119 self.methods
120 .entry((meth.module_path.clone(), meth.self_name.clone()))
121 .or_default()
122 .insert(meth.name.clone(), Method::try_from_node(meth)?);
123 }
124 uniffi_meta::Metadata::TraitMethod(meth) => {
125 self.trait_methods
126 .entry((meth.module_path.clone(), meth.trait_name.clone()))
127 .or_default()
128 .insert(meth.name.clone(), TraitMethod::try_from_node(meth)?);
129 }
130 uniffi_meta::Metadata::UniffiTrait(ut) => {
131 let meth = match &ut {
132 uniffi_meta::UniffiTraitMetadata::Debug { fmt } => fmt,
133 uniffi_meta::UniffiTraitMetadata::Display { fmt } => fmt,
134 uniffi_meta::UniffiTraitMetadata::Eq { eq, .. } => eq,
135 uniffi_meta::UniffiTraitMetadata::Hash { hash } => hash,
136 };
137
138 self.uniffi_traits
139 .entry((meth.module_path.clone(), meth.self_name.clone()))
140 .or_default()
141 .insert(ut.name().clone(), UniffiTrait::try_from_node(ut)?);
142 }
143 uniffi_meta::Metadata::ObjectTraitImpl(imp) => {
144 let (module_path, name) = match &imp.ty {
145 uniffi_meta::Type::Object {
146 module_path, name, ..
147 }
148 | uniffi_meta::Type::Record {
149 module_path, name, ..
150 }
151 | uniffi_meta::Type::Enum {
152 module_path, name, ..
153 }
154 | uniffi_meta::Type::Custom {
155 module_path, name, ..
156 }
157 | uniffi_meta::Type::CallbackInterface {
158 module_path, name, ..
159 } => (module_path, name),
160 _ => bail!("Invalid ObjectTraitImpl type: {:?}", imp.ty),
161 };
162 self.trait_impls
163 .entry((module_path.to_string(), name.to_string()))
164 .or_default()
165 .insert(
166 imp.trait_name.clone(),
167 ObjectTraitImpl {
168 tr_module_name: match &imp.tr_module_path {
169 None => None,
170 Some(module_path) => Some(
171 get_module_name(&self.module_path_map, module_path)?
172 .to_string(),
173 ),
174 },
175 ..ObjectTraitImpl::try_from_node(imp)?
176 },
177 );
178 }
179 uniffi_meta::Metadata::UdlFile(_) => (),
180 }
181 Ok(())
182 }
183
184 pub fn add_module_config_toml(&mut self, module_name: String, path: &Utf8Path) -> Result<()> {
185 if !path.exists() {
186 return Ok(());
187 }
188 let contents =
189 fs::read_to_string(path).with_context(|| format!("read file: {:?}", path))?;
190 self.module_toml.insert(module_name, contents);
191 Ok(())
192 }
193
194 /// Add a docstring for a module,
195 ///
196 /// This is currently UDL-specific. Eventually, we should probably make this another metadata
197 /// items
198 pub fn add_module_docstring(&mut self, module_name: String, docstring: String) {
199 self.module_docstrings.insert(module_name, docstring);
200 }
201
202 pub fn try_into_initial_ir(mut self) -> Result<Root> {
203 let mut root = Root {
204 modules: self.modules.into_iter().collect(),
205 cdylib: None,
206 };
207
208 // Move child items into their parents
209 for (module_path, docstring) in self.module_docstrings {
210 get_module(&self.module_path_map, &mut root, &module_path)?.docstring = Some(docstring);
211 }
212 for (module_path, toml) in self.module_toml {
213 get_module(&self.module_path_map, &mut root, &module_path)?.config_toml = Some(toml);
214 }
215 for (module_path, funcs) in self.functions {
216 get_module(&self.module_path_map, &mut root, &module_path)?
217 .functions
218 .extend(funcs.into_values());
219 }
220 for (module_path, list) in self.records {
221 get_module(&self.module_path_map, &mut root, &module_path)?
222 .type_definitions
223 .extend(list.into_values().map(TypeDefinition::Record));
224 }
225 for (module_path, list) in self.enums {
226 get_module(&self.module_path_map, &mut root, &module_path)?
227 .type_definitions
228 .extend(list.into_values().map(TypeDefinition::Enum));
229 }
230 for (module_path, list) in self.custom_types {
231 get_module(&self.module_path_map, &mut root, &module_path)?
232 .type_definitions
233 .extend(list.into_values().map(TypeDefinition::Custom));
234 }
235 // Collect child items for interfaces and callback interfaces
236 for (module_path, list) in self.interfaces {
237 get_module(&self.module_path_map, &mut root, &module_path)?
238 .type_definitions
239 .extend(
240 list.into_values()
241 .map(|mut int| {
242 let key = (module_path.clone(), int.name.clone());
243 if let Some(methods) = self.methods.remove(&key) {
244 if self.trait_methods.contains_key(&key) {
245 // Trait methods have an explicit index, so mixing them with
246 // regular methods won't work.
247 bail!("{} contains both methods and trait methods", int.name)
248 }
249 int.methods.extend(methods.into_values());
250 } else if let Some(trait_methods) = self.trait_methods.remove(&key) {
251 int.methods.extend(Self::convert_trait_methods(
252 trait_methods.into_values().collect(),
253 ));
254 }
255 if let Some(constructors) = self.constructors.remove(&key) {
256 int.constructors.extend(constructors.into_values())
257 }
258 if let Some(uniffi_traits) = self.uniffi_traits.remove(&key) {
259 int.uniffi_traits.extend(uniffi_traits.into_values())
260 }
261 if let Some(trait_impls) = self.trait_impls.remove(&key) {
262 int.trait_impls.extend(trait_impls.into_values())
263 }
264 Ok(TypeDefinition::Interface(int))
265 })
266 .collect::<Result<Vec<_>>>()?,
267 )
268 }
269 for (module_path, list) in self.callback_interfaces {
270 get_module(&self.module_path_map, &mut root, &module_path)?
271 .type_definitions
272 .extend(list.into_values().map(|mut cbi| {
273 let key = (module_path.clone(), cbi.name.clone());
274 if let Some(trait_methods) = self.trait_methods.remove(&key) {
275 cbi.methods.extend(Self::convert_trait_methods(
276 trait_methods.into_values().collect(),
277 ));
278 }
279 TypeDefinition::CallbackInterface(cbi)
280 }))
281 }
282 if !self.constructors.is_empty() {
283 bail!("Leftover constructors: {:?}", self.constructors)
284 }
285 if !self.methods.is_empty() {
286 bail!("Leftover methods: {:?}", self.methods)
287 }
288 if !self.trait_methods.is_empty() {
289 bail!("Leftover trait_methods: {:?}", self.trait_methods)
290 }
291 if !self.uniffi_traits.is_empty() {
292 bail!("Leftover uniffi_traits: {:?}", self.uniffi_traits)
293 }
294 if !self.trait_impls.is_empty() {
295 bail!("Leftover trait_impls: {:?}", self.trait_impls)
296 }
297 // normalize type module names
298 root.try_visit_mut(|ty: &mut Type| match ty {
299 Type::Interface { module_name, .. }
300 | Type::Record { module_name, .. }
301 | Type::Enum { module_name, .. }
302 | Type::CallbackInterface { module_name, .. }
303 | Type::Custom { module_name, .. } => {
304 *module_name = get_module_name(&self.module_path_map, module_name)?.to_string();
305 Ok(())
306 }
307 _ => Ok(()),
308 })?;
309 Ok(root)
310 }
311
312 fn convert_trait_methods(mut trait_methods: Vec<TraitMethod>) -> impl Iterator<Item = Method> {
313 trait_methods.sort_by_key(|tm| tm.index);
314 trait_methods.into_iter().map(Self::convert_trait_method)
315 }
316
317 fn convert_trait_method(trait_method: TraitMethod) -> Method {
318 Method {
319 name: trait_method.name,
320 is_async: trait_method.is_async,
321 inputs: trait_method.inputs,
322 return_type: trait_method.return_type,
323 throws: trait_method.throws,
324 checksum: trait_method.checksum,
325 docstring: trait_method.docstring,
326 }
327 }
328 }
329
330 fn get_module_name<'a>(
331 module_path_map: &'a BTreeMap<String, String>,
332 module_path: &str,
333 ) -> Result<&'a str> {
334 module_path_map
335 .get(module_path)
336 .map(String::as_str)
337 .ok_or_else(|| anyhow!("module lookup failed: {module_path:?}"))
338 }
339
340 fn get_module<'a>(
341 module_path_map: &BTreeMap<String, String>,
342 root: &'a mut Root,
343 module_path: &str,
344 ) -> Result<&'a mut Module> {
345 let module_name = get_module_name(module_path_map, module_path)?;
346 root.modules
347 .get_mut(module_name)
348 .ok_or_else(|| anyhow!("root module lookup failed: {module_path:?}"))
349 }