| 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 |
//! # Collects metadata from UDL. |
| 6 |
|
| 7 |
use crate::attributes; |
| 8 |
use crate::converters::{convert_docstring, APIConverter}; |
| 9 |
use crate::finder; |
| 10 |
use crate::resolver::TypeResolver; |
| 11 |
use anyhow::{bail, Result}; |
| 12 |
use std::collections::{hash_map, BTreeSet, HashMap}; |
| 13 |
use uniffi_meta::Type; |
| 14 |
|
| 15 |
/// The implementation of this crate - we collect weedle definitions from UDL and convert |
| 16 |
/// them into `uniffi_meta` metadata. |
| 17 |
/// We don't really check the sanity of the output in terms of type correctness/duplications/etc |
| 18 |
/// etc, that's the job of the consumer. |
| 19 |
#[derive(Debug, Default)] |
| 20 |
pub(crate) struct InterfaceCollector { |
| 21 |
/// All of the types used in the interface. |
| 22 |
pub types: TypeCollector, |
| 23 |
/// The output we collect and supply to our consumer. |
| 24 |
pub items: BTreeSet<uniffi_meta::Metadata>, |
| 25 |
} |
| 26 |
|
| 27 |
impl InterfaceCollector { |
| 28 |
/// Parse an `InterfaceCollector` from a string containing a WebIDL definition. |
| 29 |
pub fn from_webidl(idl: &str, crate_name: &str) -> Result<Self> { |
| 30 |
let mut ci = Self::default(); |
| 31 |
// There's some lifetime thing with the errors returned from weedle::Definitions::parse |
| 32 |
// that my own lifetime is too short to worry about figuring out; unwrap and move on. |
| 33 |
|
| 34 |
// Note we use `weedle::Definitions::parse` instead of `weedle::parse` so |
| 35 |
// on parse errors we can see how far weedle got, which helps locate the problem. |
| 36 |
use weedle::Parse; // this trait must be in scope for parse to work. |
| 37 |
let (remaining, defns) = weedle::Definitions::parse(idl.trim()).unwrap(); |
| 38 |
if !remaining.is_empty() { |
| 39 |
println!("Error parsing the IDL. Text remaining to be parsed is:"); |
| 40 |
println!("{remaining}"); |
| 41 |
bail!("parse error"); |
| 42 |
} |
| 43 |
// We process the WebIDL definitions in 3 passes. |
| 44 |
// First, find the namespace. |
| 45 |
// XXX - TODO: it's no longer necessary to do this pass. |
| 46 |
ci.types.namespace = ci.find_namespace(&defns)?; |
| 47 |
ci.types.crate_name = crate_name.to_string(); |
| 48 |
// Next, go through and look for all the named types. |
| 49 |
ci.types.add_type_definitions_from(defns.as_slice())?; |
| 50 |
|
| 51 |
// With those names resolved, we can build a complete representation of the API. |
| 52 |
APIBuilder::process(&defns, &mut ci)?; |
| 53 |
// Any misc items we need to add to the set. |
| 54 |
for t in ci.types.type_definitions.values() { |
| 55 |
if let Type::Custom { |
| 56 |
module_path, |
| 57 |
name, |
| 58 |
builtin, |
| 59 |
} = t |
| 60 |
{ |
| 61 |
ci.items.insert( |
| 62 |
uniffi_meta::CustomTypeMetadata { |
| 63 |
module_path: module_path.clone(), |
| 64 |
name: name.clone(), |
| 65 |
builtin: *builtin.clone(), |
| 66 |
docstring: None, |
| 67 |
} |
| 68 |
.into(), |
| 69 |
); |
| 70 |
} |
| 71 |
} |
| 72 |
Ok(ci) |
| 73 |
} |
| 74 |
|
| 75 |
fn find_namespace(&mut self, defns: &Vec<weedle::Definition<'_>>) -> Result<String> { |
| 76 |
for defn in defns { |
| 77 |
if let weedle::Definition::Namespace(n) = defn { |
| 78 |
return Ok(n.identifier.0.to_string()); |
| 79 |
} |
| 80 |
} |
| 81 |
bail!("Failed to find the namespace"); |
| 82 |
} |
| 83 |
|
| 84 |
/// The module path which should be used by all items in this namespace. |
| 85 |
pub fn module_path(&self) -> String { |
| 86 |
self.types.module_path() |
| 87 |
} |
| 88 |
|
| 89 |
/// Get a specific type |
| 90 |
pub fn get_type(&self, name: &str) -> Option<Type> { |
| 91 |
self.types.get_type_definition(name) |
| 92 |
} |
| 93 |
|
| 94 |
/// Resolve a weedle type expression into a `Type`. |
| 95 |
/// |
| 96 |
/// This method uses the current state of our `TypeCollector` to turn a weedle type expression |
| 97 |
/// into a concrete `Type` (or error if the type expression is not well defined). It abstracts |
| 98 |
/// away the complexity of walking weedle's type struct hierarchy by dispatching to the `TypeResolver` |
| 99 |
/// trait. |
| 100 |
pub fn resolve_type_expression<T: TypeResolver>(&mut self, expr: T) -> Result<Type> { |
| 101 |
self.types.resolve_type_expression(expr) |
| 102 |
} |
| 103 |
|
| 104 |
/// Resolve a weedle `ReturnType` expression into an optional `Type`. |
| 105 |
/// |
| 106 |
/// This method is similar to `resolve_type_expression`, but tailored specifically for return types. |
| 107 |
/// It can return `None` to represent a non-existent return value. |
| 108 |
pub fn resolve_return_type_expression( |
| 109 |
&mut self, |
| 110 |
expr: &weedle::types::ReturnType<'_>, |
| 111 |
) -> Result<Option<Type>> { |
| 112 |
Ok(match expr { |
| 113 |
weedle::types::ReturnType::Undefined(_) => None, |
| 114 |
weedle::types::ReturnType::Type(t) => { |
| 115 |
// Older versions of WebIDL used `void` for functions that don't return a value, |
| 116 |
// while newer versions have replaced it with `undefined`. Special-case this for |
| 117 |
// backwards compatibility for our consumers. |
| 118 |
use weedle::types::{NonAnyType::Identifier, SingleType::NonAny, Type::Single}; |
| 119 |
match t { |
| 120 |
Single(NonAny(Identifier(id))) if id.type_.0 == "void" => None, |
| 121 |
_ => Some(self.resolve_type_expression(t)?), |
| 122 |
} |
| 123 |
} |
| 124 |
}) |
| 125 |
} |
| 126 |
|
| 127 |
/// Called by `APIBuilder` impls to add a newly-parsed definition to the `InterfaceCollector`. |
| 128 |
fn add_definition(&mut self, defn: uniffi_meta::Metadata) -> Result<()> { |
| 129 |
self.items.insert(defn); |
| 130 |
Ok(()) |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
/// Turn our internal object into an outgoing public `MetadataGroup`. |
| 135 |
impl From<InterfaceCollector> for uniffi_meta::MetadataGroup { |
| 136 |
fn from(value: InterfaceCollector) -> Self { |
| 137 |
Self { |
| 138 |
namespace: uniffi_meta::NamespaceMetadata { |
| 139 |
crate_name: value.types.module_path(), |
| 140 |
name: value.types.namespace, |
| 141 |
}, |
| 142 |
namespace_docstring: value.types.namespace_docstring.clone(), |
| 143 |
items: value.items, |
| 144 |
} |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
/// Trait to help build an `InterfaceCollector` from WedIDL syntax nodes. |
| 149 |
/// |
| 150 |
/// This trait does structural matching on the various weedle AST nodes and |
| 151 |
/// uses them to build up the records, enums, objects etc in the provided |
| 152 |
/// `InterfaceCollector`. |
| 153 |
trait APIBuilder { |
| 154 |
fn process(&self, ci: &mut InterfaceCollector) -> Result<()>; |
| 155 |
} |
| 156 |
|
| 157 |
/// Add to an `InterfaceCollector` from a list of weedle definitions, |
| 158 |
/// by processing each in turn. |
| 159 |
impl<T: APIBuilder> APIBuilder for Vec<T> { |
| 160 |
fn process(&self, ci: &mut InterfaceCollector) -> Result<()> { |
| 161 |
for item in self { |
| 162 |
item.process(ci)?; |
| 163 |
} |
| 164 |
Ok(()) |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
/// Add to an `InterfaceCollector` from a weedle definition. |
| 169 |
/// This is conceptually the root of the parser, and dispatches to implementations |
| 170 |
/// for the various specific WebIDL types that we support. |
| 171 |
impl APIBuilder for weedle::Definition<'_> { |
| 172 |
fn process(&self, ci: &mut InterfaceCollector) -> Result<()> { |
| 173 |
match self { |
| 174 |
weedle::Definition::Namespace(d) => d.process(ci)?, |
| 175 |
weedle::Definition::Enum(d) => { |
| 176 |
let e: uniffi_meta::EnumMetadata = d.convert(ci)?; |
| 177 |
ci.add_definition(e.into())?; |
| 178 |
} |
| 179 |
weedle::Definition::Dictionary(d) => { |
| 180 |
let rec = d.convert(ci)?; |
| 181 |
ci.add_definition(rec.into())?; |
| 182 |
} |
| 183 |
weedle::Definition::Interface(d) => { |
| 184 |
let attrs = attributes::InterfaceAttributes::try_from(d.attributes.as_ref())?; |
| 185 |
if attrs.contains_enum_attr() || attrs.contains_error_attr() { |
| 186 |
let e: uniffi_meta::EnumMetadata = d.convert(ci)?; |
| 187 |
ci.add_definition(e.into())?; |
| 188 |
} else { |
| 189 |
let obj: uniffi_meta::ObjectMetadata = d.convert(ci)?; |
| 190 |
ci.add_definition(obj.into())?; |
| 191 |
} |
| 192 |
} |
| 193 |
weedle::Definition::CallbackInterface(d) => { |
| 194 |
let obj = d.convert(ci)?; |
| 195 |
ci.add_definition(obj.into())?; |
| 196 |
} |
| 197 |
// everything needed for typedefs is done in finder.rs. |
| 198 |
weedle::Definition::Typedef(_) => {} |
| 199 |
_ => bail!("don't know how to deal with {:?}", self), |
| 200 |
} |
| 201 |
Ok(()) |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
impl APIBuilder for weedle::NamespaceDefinition<'_> { |
| 206 |
fn process(&self, ci: &mut InterfaceCollector) -> Result<()> { |
| 207 |
if self.attributes.is_some() { |
| 208 |
bail!("namespace attributes are not supported yet"); |
| 209 |
} |
| 210 |
if self.identifier.0 != ci.types.namespace { |
| 211 |
bail!("duplicate namespace definition"); |
| 212 |
} |
| 213 |
ci.types.namespace_docstring = self.docstring.as_ref().map(|v| convert_docstring(&v.0)); |
| 214 |
for func in self.members.body.convert(ci)? { |
| 215 |
ci.add_definition(func.into())?; |
| 216 |
} |
| 217 |
Ok(()) |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
#[derive(Debug, Default)] |
| 222 |
pub(crate) struct TypeCollector { |
| 223 |
/// The unique prefix that we'll use for namespacing when exposing this component's API. |
| 224 |
pub namespace: String, |
| 225 |
pub namespace_docstring: Option<String>, |
| 226 |
|
| 227 |
pub crate_name: String, |
| 228 |
|
| 229 |
// Named type definitions (including aliases). |
| 230 |
pub type_definitions: HashMap<String, Type>, |
| 231 |
} |
| 232 |
|
| 233 |
impl TypeCollector { |
| 234 |
/// The module path which should be used by all items in this namespace. |
| 235 |
pub fn module_path(&self) -> String { |
| 236 |
self.crate_name.clone() |
| 237 |
} |
| 238 |
|
| 239 |
/// Add the definitions of all named [Type]s from a given WebIDL definition. |
| 240 |
/// |
| 241 |
/// This will fail if you try to add a name for which an existing type definition exists. |
| 242 |
pub fn add_type_definitions_from<T: finder::TypeFinder>(&mut self, defn: T) -> Result<()> { |
| 243 |
defn.add_type_definitions_to(self) |
| 244 |
} |
| 245 |
|
| 246 |
/// Add the definition of a named [Type]. |
| 247 |
/// |
| 248 |
/// This will fail if you try to add a name for which an existing type definition exists. |
| 249 |
pub fn add_type_definition(&mut self, name: &str, type_: Type) -> Result<()> { |
| 250 |
match self.type_definitions.entry(name.to_string()) { |
| 251 |
hash_map::Entry::Occupied(o) => { |
| 252 |
let existing_def = o.get(); |
| 253 |
if type_ == *existing_def |
| 254 |
&& matches!(type_, Type::Record { .. } | Type::Enum { .. }) |
| 255 |
{ |
| 256 |
// UDL and proc-macro metadata are allowed to define the same record, enum and |
| 257 |
// error types, if the definitions match (fields and variants are checked in |
| 258 |
// add_{record,enum,error}_definition) |
| 259 |
Ok(()) |
| 260 |
} else { |
| 261 |
bail!( |
| 262 |
"Conflicting type definition for `{name}`! \ |
| 263 |
existing definition: {existing_def:?}, \ |
| 264 |
new definition: {type_:?}" |
| 265 |
); |
| 266 |
} |
| 267 |
} |
| 268 |
hash_map::Entry::Vacant(e) => { |
| 269 |
e.insert(type_); |
| 270 |
Ok(()) |
| 271 |
} |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
/// Get the [Type] corresponding to a given name, if any. |
| 276 |
pub fn get_type_definition(&self, name: &str) -> Option<Type> { |
| 277 |
self.type_definitions.get(name).cloned() |
| 278 |
} |
| 279 |
|
| 280 |
/// Get the [Type] corresponding to a given WebIDL type node. |
| 281 |
/// |
| 282 |
/// If the node is a structural type (e.g. a sequence) then this will also add |
| 283 |
/// it to the set of all types seen in the component interface. |
| 284 |
pub fn resolve_type_expression<T: TypeResolver>(&mut self, expr: T) -> Result<Type> { |
| 285 |
expr.resolve_type_expression(self) |
| 286 |
} |
| 287 |
} |