Debian Codegraph @

third_party/rust/uniffi_meta/src/group.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 std::collections::{BTreeSet, HashMap};
6
7 use crate::*;
8 use anyhow::{bail, Result};
9
10 type MetadataGroupMap = HashMap<String, MetadataGroup>;
11
12 // Create empty metadata groups based on the metadata items.
13 pub fn create_metadata_groups(items: &[Metadata]) -> MetadataGroupMap {
14 // Map crate names to MetadataGroup instances
15 items
16 .iter()
17 .filter_map(|i| match i {
18 Metadata::Namespace(namespace) => {
19 let group = MetadataGroup {
20 namespace: namespace.clone(),
21 namespace_docstring: None,
22 items: BTreeSet::new(),
23 };
24 Some((namespace.crate_name.clone(), group))
25 }
26 Metadata::UdlFile(udl) => {
27 let namespace = NamespaceMetadata {
28 crate_name: udl.module_path.clone(),
29 name: udl.namespace.clone(),
30 };
31 let group = MetadataGroup {
32 namespace,
33 namespace_docstring: None,
34 items: BTreeSet::new(),
35 };
36 Some((udl.module_path.clone(), group))
37 }
38 _ => None,
39 })
40 .collect::<HashMap<_, _>>()
41 }
42
43 /// Consume the items into the previously created metadata groups.
44 pub fn group_metadata(group_map: &mut MetadataGroupMap, items: Vec<Metadata>) -> Result<()> {
45 for item in items {
46 if matches!(&item, Metadata::Namespace(_)) {
47 continue;
48 }
49
50 let crate_name = calc_crate_name(item.module_path()).to_owned();
51 let group = match group_map.get_mut(&crate_name) {
52 Some(ns) => ns,
53 None => bail!("Unknown namespace for {item:?} ({crate_name})"),
54 };
55 if group.items.contains(&item) {
56 bail!("Duplicate metadata item: {item:?}");
57 }
58 group.add_item(item);
59 }
60 Ok(())
61 }
62
63 #[derive(Debug)]
64 pub struct MetadataGroup {
65 pub namespace: NamespaceMetadata,
66 pub namespace_docstring: Option<String>,
67 pub items: BTreeSet<Metadata>,
68 }
69
70 impl MetadataGroup {
71 pub fn add_item(&mut self, item: Metadata) {
72 self.items.insert(item);
73 }
74 }
75
76 fn calc_crate_name(module_path: &str) -> &str {
77 module_path.split("::").next().unwrap()
78 }