Debian Codegraph @

third_party/rust/uniffi_meta/src/lib.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::BTreeMap, hash::Hasher};
6 pub use uniffi_internal_macros::{Checksum, Node};
7
8 mod ffi_names;
9 pub use ffi_names::*;
10
11 mod group;
12 pub use group::{create_metadata_groups, group_metadata, MetadataGroup};
13
14 mod reader;
15 pub use reader::{read_metadata, read_metadata_type};
16
17 mod types;
18 pub use types::{AsType, ObjectImpl, Type, TypeIterator};
19
20 mod metadata;
21
22 // This needs to match the minor version of the `uniffi` crate. See
23 // `docs/uniffi-versioning.md` for details.
24 //
25 // Once we get to 1.0, then we'll need to update the scheme to something like 100 + major_version
26 pub const UNIFFI_CONTRACT_VERSION: u32 = 29;
27
28 /// Similar to std::hash::Hash.
29 ///
30 /// Implementations of this trait are expected to update the hasher state in
31 /// the same way across platforms. #[derive(Checksum)] will do the right thing.
32 pub trait Checksum {
33 fn checksum<H: Hasher>(&self, state: &mut H);
34 }
35
36 impl Checksum for bool {
37 fn checksum<H: Hasher>(&self, state: &mut H) {
38 state.write_u8(*self as u8);
39 }
40 }
41
42 impl Checksum for u64 {
43 fn checksum<H: Hasher>(&self, state: &mut H) {
44 state.write(&self.to_le_bytes());
45 }
46 }
47
48 impl Checksum for i64 {
49 fn checksum<H: Hasher>(&self, state: &mut H) {
50 state.write(&self.to_le_bytes());
51 }
52 }
53
54 impl<T: Checksum> Checksum for Box<T> {
55 fn checksum<H: Hasher>(&self, state: &mut H) {
56 (**self).checksum(state)
57 }
58 }
59
60 impl<T: Checksum> Checksum for [T] {
61 fn checksum<H: Hasher>(&self, state: &mut H) {
62 state.write(&(self.len() as u64).to_le_bytes());
63 for item in self {
64 Checksum::checksum(item, state);
65 }
66 }
67 }
68
69 impl<T: Checksum> Checksum for Vec<T> {
70 fn checksum<H: Hasher>(&self, state: &mut H) {
71 Checksum::checksum(&**self, state);
72 }
73 }
74
75 impl<K: Checksum, V: Checksum> Checksum for BTreeMap<K, V> {
76 fn checksum<H: Hasher>(&self, state: &mut H) {
77 state.write(&(self.len() as u64).to_le_bytes());
78 for (key, value) in self {
79 Checksum::checksum(key, state);
80 Checksum::checksum(value, state);
81 }
82 }
83 }
84
85 impl<T: Checksum> Checksum for Option<T> {
86 fn checksum<H: Hasher>(&self, state: &mut H) {
87 match self {
88 None => state.write(&0u64.to_le_bytes()),
89 Some(value) => {
90 state.write(&1u64.to_le_bytes());
91 Checksum::checksum(value, state)
92 }
93 }
94 }
95 }
96
97 impl Checksum for str {
98 fn checksum<H: Hasher>(&self, state: &mut H) {
99 state.write(self.as_bytes());
100 state.write_u8(0xff);
101 }
102 }
103
104 impl Checksum for String {
105 fn checksum<H: Hasher>(&self, state: &mut H) {
106 (**self).checksum(state)
107 }
108 }
109
110 impl Checksum for &str {
111 fn checksum<H: Hasher>(&self, state: &mut H) {
112 (**self).checksum(state)
113 }
114 }
115
116 // The namespace of a Component interface.
117 //
118 // This is used to match up the macro metadata with the UDL items.
119 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
120 pub struct NamespaceMetadata {
121 pub crate_name: String,
122 pub name: String,
123 }
124
125 // UDL file included with `include_scaffolding!()`
126 //
127 // This is to find the UDL files in library mode generation
128 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
129 pub struct UdlFile {
130 // The module path specified when the UDL file was parsed.
131 pub module_path: String,
132 pub namespace: String,
133 // the base filename of the udl file - no path, no extension.
134 pub file_stub: String,
135 }
136
137 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
138 pub struct FnMetadata {
139 pub module_path: String,
140 pub name: String,
141 pub is_async: bool,
142 pub inputs: Vec<FnParamMetadata>,
143 pub return_type: Option<Type>,
144 pub throws: Option<Type>,
145 pub checksum: Option<u16>,
146 pub docstring: Option<String>,
147 }
148
149 impl FnMetadata {
150 pub fn ffi_symbol_name(&self) -> String {
151 fn_symbol_name(&self.module_path, &self.name)
152 }
153
154 pub fn checksum_symbol_name(&self) -> String {
155 fn_checksum_symbol_name(&self.module_path, &self.name)
156 }
157 }
158
159 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
160 pub struct ConstructorMetadata {
161 pub module_path: String,
162 pub self_name: String,
163 pub name: String,
164 pub is_async: bool,
165 pub inputs: Vec<FnParamMetadata>,
166 pub throws: Option<Type>,
167 pub checksum: Option<u16>,
168 pub docstring: Option<String>,
169 }
170
171 impl ConstructorMetadata {
172 pub fn ffi_symbol_name(&self) -> String {
173 constructor_symbol_name(&self.module_path, &self.self_name, &self.name)
174 }
175
176 pub fn checksum_symbol_name(&self) -> String {
177 constructor_checksum_symbol_name(&self.module_path, &self.self_name, &self.name)
178 }
179
180 pub fn is_primary(&self) -> bool {
181 self.name == "new"
182 }
183 }
184
185 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
186 pub struct MethodMetadata {
187 pub module_path: String,
188 pub self_name: String,
189 pub name: String,
190 pub is_async: bool,
191 pub inputs: Vec<FnParamMetadata>,
192 pub return_type: Option<Type>,
193 pub throws: Option<Type>,
194 pub takes_self_by_arc: bool, // unused except by rust udl bindgen.
195 pub checksum: Option<u16>,
196 pub docstring: Option<String>,
197 }
198
199 impl MethodMetadata {
200 pub fn ffi_symbol_name(&self) -> String {
201 method_symbol_name(&self.module_path, &self.self_name, &self.name)
202 }
203
204 pub fn checksum_symbol_name(&self) -> String {
205 method_checksum_symbol_name(&self.module_path, &self.self_name, &self.name)
206 }
207 }
208
209 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
210 pub struct TraitMethodMetadata {
211 pub module_path: String,
212 pub trait_name: String,
213 // Note: the position of `index` is important since it causes callback interface methods to be
214 // ordered correctly in MetadataGroup.items
215 pub index: u32,
216 pub name: String,
217 pub is_async: bool,
218 pub inputs: Vec<FnParamMetadata>,
219 pub return_type: Option<Type>,
220 pub throws: Option<Type>,
221 pub takes_self_by_arc: bool, // unused except by rust udl bindgen.
222 pub checksum: Option<u16>,
223 pub docstring: Option<String>,
224 }
225
226 impl TraitMethodMetadata {
227 pub fn ffi_symbol_name(&self) -> String {
228 method_symbol_name(&self.module_path, &self.trait_name, &self.name)
229 }
230
231 pub fn checksum_symbol_name(&self) -> String {
232 method_checksum_symbol_name(&self.module_path, &self.trait_name, &self.name)
233 }
234 }
235
236 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
237 pub struct FnParamMetadata {
238 pub name: String,
239 pub ty: Type,
240 pub by_ref: bool,
241 pub optional: bool,
242 pub default: Option<LiteralMetadata>,
243 }
244
245 impl FnParamMetadata {
246 pub fn simple(name: &str, ty: Type) -> Self {
247 Self {
248 name: name.to_string(),
249 ty,
250 by_ref: false,
251 optional: false,
252 default: None,
253 }
254 }
255 }
256
257 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Checksum, Node)]
258 pub enum LiteralMetadata {
259 Boolean(bool),
260 String(String),
261 // Integers are represented as the widest representation we can.
262 // Number formatting vary with language and radix, so we avoid a lot of parsing and
263 // formatting duplication by using only signed and unsigned variants.
264 UInt(u64, Radix, Type),
265 Int(i64, Radix, Type),
266 // Pass the string representation through as typed in the UDL.
267 // This avoids a lot of uncertainty around precision and accuracy,
268 // though bindings for languages less sophisticated number parsing than WebIDL
269 // will have to do extra work.
270 Float(String, Type),
271 Enum(String, Type),
272 EmptySequence,
273 EmptyMap,
274 None,
275 Some { inner: Box<LiteralMetadata> },
276 }
277
278 impl LiteralMetadata {
279 pub fn new_uint(v: u64) -> Self {
280 LiteralMetadata::UInt(v, Radix::Decimal, Type::UInt64)
281 }
282 pub fn new_int(v: i64) -> Self {
283 LiteralMetadata::Int(v, Radix::Decimal, Type::Int64)
284 }
285 }
286
287 // Represent the radix of integer literal values.
288 // We preserve the radix into the generated bindings for readability reasons.
289 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Checksum, Node)]
290 pub enum Radix {
291 Decimal = 10,
292 Octal = 8,
293 Hexadecimal = 16,
294 }
295
296 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
297 pub struct RecordMetadata {
298 pub module_path: String,
299 pub name: String,
300 pub remote: bool, // only used when generating scaffolding from UDL
301 pub fields: Vec<FieldMetadata>,
302 pub docstring: Option<String>,
303 }
304
305 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
306 pub struct FieldMetadata {
307 pub name: String,
308 pub ty: Type,
309 pub default: Option<LiteralMetadata>,
310 pub docstring: Option<String>,
311 }
312
313 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Checksum, Node)]
314 pub enum EnumShape {
315 Enum,
316 Error { flat: bool },
317 }
318
319 impl EnumShape {
320 pub fn as_u8(&self) -> u8 {
321 match self {
322 EnumShape::Enum => 0,
323 EnumShape::Error { flat: false } => 1,
324 EnumShape::Error { flat: true } => 2,
325 }
326 }
327
328 pub fn from(v: u8) -> anyhow::Result<Self> {
329 Ok(match v {
330 0 => EnumShape::Enum,
331 1 => EnumShape::Error { flat: false },
332 2 => EnumShape::Error { flat: true },
333 _ => anyhow::bail!("invalid enum shape discriminant {v}"),
334 })
335 }
336 }
337
338 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
339 pub struct EnumMetadata {
340 pub module_path: String,
341 pub name: String,
342 pub shape: EnumShape,
343 pub remote: bool, // only used when generating scaffolding from UDL
344 pub variants: Vec<VariantMetadata>,
345 pub discr_type: Option<Type>,
346 pub non_exhaustive: bool,
347 pub docstring: Option<String>,
348 }
349
350 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
351 pub struct VariantMetadata {
352 pub name: String,
353 pub discr: Option<LiteralMetadata>,
354 pub fields: Vec<FieldMetadata>,
355 pub docstring: Option<String>,
356 }
357
358 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
359 pub struct ObjectMetadata {
360 pub module_path: String,
361 pub name: String,
362 pub remote: bool, // only used when generating scaffolding from UDL
363 pub imp: types::ObjectImpl,
364 pub docstring: Option<String>,
365 }
366
367 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
368 pub struct CallbackInterfaceMetadata {
369 pub module_path: String,
370 pub name: String,
371 pub docstring: Option<String>,
372 }
373
374 impl ObjectMetadata {
375 /// FFI symbol name for the `clone` function for this object.
376 ///
377 /// This function is used to increment the reference count before lowering an object to pass
378 /// back to Rust.
379 pub fn clone_ffi_symbol_name(&self) -> String {
380 clone_fn_symbol_name(&self.module_path, &self.name)
381 }
382
383 /// FFI symbol name for the `free` function for this object.
384 ///
385 /// This function is used to free the memory used by this object.
386 pub fn free_ffi_symbol_name(&self) -> String {
387 free_fn_symbol_name(&self.module_path, &self.name)
388 }
389 }
390
391 /// The list of "builtin" traits we support generating helper methods for.
392 /// Some interesting overlap with ObjectTraitImplMetadata, but quite different
393 /// implementations for now.
394 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
395 pub enum UniffiTraitMetadata {
396 Debug {
397 fmt: MethodMetadata,
398 },
399 Display {
400 fmt: MethodMetadata,
401 },
402 Eq {
403 eq: MethodMetadata,
404 ne: MethodMetadata,
405 },
406 Hash {
407 hash: MethodMetadata,
408 },
409 }
410
411 impl UniffiTraitMetadata {
412 fn module_path(&self) -> &String {
413 &match self {
414 UniffiTraitMetadata::Debug { fmt } => fmt,
415 UniffiTraitMetadata::Display { fmt } => fmt,
416 UniffiTraitMetadata::Eq { eq, .. } => eq,
417 UniffiTraitMetadata::Hash { hash } => hash,
418 }
419 .module_path
420 }
421
422 pub fn self_name(&self) -> &String {
423 &match self {
424 UniffiTraitMetadata::Debug { fmt } => fmt,
425 UniffiTraitMetadata::Display { fmt } => fmt,
426 UniffiTraitMetadata::Eq { eq, .. } => eq,
427 UniffiTraitMetadata::Hash { hash } => hash,
428 }
429 .self_name
430 }
431
432 pub fn name(&self) -> &String {
433 &match self {
434 UniffiTraitMetadata::Debug { fmt } => fmt,
435 UniffiTraitMetadata::Display { fmt } => fmt,
436 UniffiTraitMetadata::Eq { eq, .. } => eq,
437 UniffiTraitMetadata::Hash { hash } => hash,
438 }
439 .name
440 }
441 }
442
443 #[repr(u8)]
444 #[derive(Debug, Eq, PartialEq, Hash, Node)]
445 pub enum UniffiTraitDiscriminants {
446 Debug,
447 Display,
448 Eq,
449 Hash,
450 }
451
452 impl UniffiTraitDiscriminants {
453 pub fn from(v: u8) -> anyhow::Result<Self> {
454 Ok(match v {
455 0 => UniffiTraitDiscriminants::Debug,
456 1 => UniffiTraitDiscriminants::Display,
457 2 => UniffiTraitDiscriminants::Eq,
458 3 => UniffiTraitDiscriminants::Hash,
459 _ => anyhow::bail!("invalid trait discriminant {v}"),
460 })
461 }
462 }
463
464 /// This notes that a type implements a Trait.
465 /// eg, an `impl Tr for Ob` block. Not many types will support this.
466 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
467 pub struct ObjectTraitImplMetadata {
468 pub ty: Type,
469 pub trait_name: String,
470 pub tr_module_path: Option<String>,
471 }
472
473 impl Checksum for ObjectTraitImplMetadata {
474 fn checksum<H: Hasher>(&self, state: &mut H) {
475 Checksum::checksum(&self.ty, state);
476 Checksum::checksum(&self.trait_name, state);
477 Checksum::checksum(&self.tr_module_path, state);
478 }
479 }
480
481 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
482 pub struct CustomTypeMetadata {
483 pub module_path: String,
484 pub name: String,
485 pub builtin: Type,
486 pub docstring: Option<String>,
487 }
488
489 /// Returns the last 16 bits of the value's hash as computed with [`SipHasher13`].
490 ///
491 /// This is used as a safeguard against different UniFFI versions being used for scaffolding and
492 /// bindings generation.
493 pub fn checksum<T: Checksum>(val: &T) -> u16 {
494 let mut hasher = siphasher::sip::SipHasher13::new();
495 val.checksum(&mut hasher);
496 (hasher.finish() & 0x000000000000FFFF) as u16
497 }
498
499 /// Enum covering all the possible metadata types
500 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Node)]
501 pub enum Metadata {
502 Namespace(NamespaceMetadata),
503 UdlFile(UdlFile),
504 Func(FnMetadata),
505 Object(ObjectMetadata),
506 CallbackInterface(CallbackInterfaceMetadata),
507 Record(RecordMetadata),
508 Enum(EnumMetadata),
509 Constructor(ConstructorMetadata),
510 Method(MethodMetadata),
511 TraitMethod(TraitMethodMetadata),
512 CustomType(CustomTypeMetadata),
513 UniffiTrait(UniffiTraitMetadata),
514 ObjectTraitImpl(ObjectTraitImplMetadata),
515 }
516
517 impl Metadata {
518 pub fn read(data: &[u8]) -> anyhow::Result<Self> {
519 read_metadata(data)
520 }
521
522 pub fn module_path(&self) -> &str {
523 match self {
524 Metadata::Namespace(meta) => &meta.crate_name,
525 Metadata::UdlFile(meta) => &meta.module_path,
526 Metadata::Func(meta) => &meta.module_path,
527 Metadata::Constructor(meta) => &meta.module_path,
528 Metadata::Method(meta) => &meta.module_path,
529 Metadata::Record(meta) => &meta.module_path,
530 Metadata::Enum(meta) => &meta.module_path,
531 Metadata::Object(meta) => &meta.module_path,
532 Metadata::CallbackInterface(meta) => &meta.module_path,
533 Metadata::TraitMethod(meta) => &meta.module_path,
534 Metadata::CustomType(meta) => &meta.module_path,
535 Metadata::UniffiTrait(meta) => meta.module_path(),
536 Metadata::ObjectTraitImpl(t) => t.ty.module_path().expect("type has no module"),
537 }
538 }
539 }
540
541 impl From<NamespaceMetadata> for Metadata {
542 fn from(value: NamespaceMetadata) -> Metadata {
543 Self::Namespace(value)
544 }
545 }
546
547 impl From<UdlFile> for Metadata {
548 fn from(value: UdlFile) -> Metadata {
549 Self::UdlFile(value)
550 }
551 }
552
553 impl From<FnMetadata> for Metadata {
554 fn from(value: FnMetadata) -> Metadata {
555 Self::Func(value)
556 }
557 }
558
559 impl From<ConstructorMetadata> for Metadata {
560 fn from(c: ConstructorMetadata) -> Self {
561 Self::Constructor(c)
562 }
563 }
564
565 impl From<MethodMetadata> for Metadata {
566 fn from(m: MethodMetadata) -> Self {
567 Self::Method(m)
568 }
569 }
570
571 impl From<RecordMetadata> for Metadata {
572 fn from(r: RecordMetadata) -> Self {
573 Self::Record(r)
574 }
575 }
576
577 impl From<EnumMetadata> for Metadata {
578 fn from(e: EnumMetadata) -> Self {
579 Self::Enum(e)
580 }
581 }
582
583 impl From<ObjectMetadata> for Metadata {
584 fn from(v: ObjectMetadata) -> Self {
585 Self::Object(v)
586 }
587 }
588
589 impl From<CallbackInterfaceMetadata> for Metadata {
590 fn from(v: CallbackInterfaceMetadata) -> Self {
591 Self::CallbackInterface(v)
592 }
593 }
594
595 impl From<TraitMethodMetadata> for Metadata {
596 fn from(v: TraitMethodMetadata) -> Self {
597 Self::TraitMethod(v)
598 }
599 }
600
601 impl From<CustomTypeMetadata> for Metadata {
602 fn from(v: CustomTypeMetadata) -> Self {
603 Self::CustomType(v)
604 }
605 }
606
607 impl From<UniffiTraitMetadata> for Metadata {
608 fn from(v: UniffiTraitMetadata) -> Self {
609 Self::UniffiTrait(v)
610 }
611 }
612
613 impl From<ObjectTraitImplMetadata> for Metadata {
614 fn from(t: ObjectTraitImplMetadata) -> Self {
615 Self::ObjectTraitImpl(t)
616 }
617 }