packr 0.5.3

A WebAssembly package runtime with extended WIT support for recursive types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! Interface Implementation Builder
//!
//! Provides a unified way to declare and implement host interfaces.
//! The interface declaration and implementation are combined, ensuring
//! they can never drift apart.
//!
//! # Example
//!
//! ```ignore
//! let interface = InterfaceImpl::new("theater:simple/runtime")
//!     .func("log", |ctx: &mut Ctx<State>, msg: String| {
//!         println!("{}", msg);
//!     })
//!     .func("get-state", |ctx: &mut Ctx<State>| -> String {
//!         ctx.data().state.clone()
//!     });
//!
//! // Get the interface hash (computed from function signatures)
//! let hash = interface.hash();
//!
//! // Register with a linker
//! builder.register_interface(&interface)?;
//! ```

use crate::metadata::TypeHash;
use crate::parser::{MetadataValue, PactExport, PactInterface};
use crate::types::Type;
use sha2::Digest;

// ============================================================================
// PackType Trait - Maps Rust types to Pack types
// ============================================================================

/// Trait for types that can be represented in Pack's type system.
///
/// This enables automatic signature extraction from Rust closures.
pub trait PackType {
    /// The Pack type representation of this Rust type.
    fn pack_type() -> Type;
}

// Primitive implementations
impl PackType for () {
    fn pack_type() -> Type {
        Type::Unit
    }
}

impl PackType for bool {
    fn pack_type() -> Type {
        Type::Bool
    }
}

impl PackType for u8 {
    fn pack_type() -> Type {
        Type::U8
    }
}

impl PackType for u16 {
    fn pack_type() -> Type {
        Type::U16
    }
}

impl PackType for u32 {
    fn pack_type() -> Type {
        Type::U32
    }
}

impl PackType for u64 {
    fn pack_type() -> Type {
        Type::U64
    }
}

impl PackType for i8 {
    fn pack_type() -> Type {
        Type::S8
    }
}

impl PackType for i16 {
    fn pack_type() -> Type {
        Type::S16
    }
}

impl PackType for i32 {
    fn pack_type() -> Type {
        Type::S32
    }
}

impl PackType for i64 {
    fn pack_type() -> Type {
        Type::S64
    }
}

impl PackType for f32 {
    fn pack_type() -> Type {
        Type::F32
    }
}

impl PackType for f64 {
    fn pack_type() -> Type {
        Type::F64
    }
}

impl PackType for char {
    fn pack_type() -> Type {
        Type::Char
    }
}

impl PackType for String {
    fn pack_type() -> Type {
        Type::String
    }
}

impl PackType for crate::abi::Value {
    fn pack_type() -> Type {
        Type::Value
    }
}

impl<T: PackType> PackType for Vec<T> {
    fn pack_type() -> Type {
        Type::List(Box::new(T::pack_type()))
    }
}

impl<T: PackType> PackType for Option<T> {
    fn pack_type() -> Type {
        Type::Option(Box::new(T::pack_type()))
    }
}

impl<T: PackType, E: PackType> PackType for Result<T, E> {
    fn pack_type() -> Type {
        Type::Result {
            ok: Box::new(T::pack_type()),
            err: Box::new(E::pack_type()),
        }
    }
}

// Tuple implementations
impl<A: PackType> PackType for (A,) {
    fn pack_type() -> Type {
        Type::Tuple(vec![A::pack_type()])
    }
}

impl<A: PackType, B: PackType> PackType for (A, B) {
    fn pack_type() -> Type {
        Type::Tuple(vec![A::pack_type(), B::pack_type()])
    }
}

impl<A: PackType, B: PackType, C: PackType> PackType for (A, B, C) {
    fn pack_type() -> Type {
        Type::Tuple(vec![A::pack_type(), B::pack_type(), C::pack_type()])
    }
}

impl<A: PackType, B: PackType, C: PackType, D: PackType> PackType for (A, B, C, D) {
    fn pack_type() -> Type {
        Type::Tuple(vec![
            A::pack_type(),
            B::pack_type(),
            C::pack_type(),
            D::pack_type(),
        ])
    }
}

// ============================================================================
// Function Signature
// ============================================================================

/// A function signature extracted from Rust types.
#[derive(Debug, Clone)]
pub struct FuncSignature {
    pub name: String,
    pub params: Vec<Type>,
    pub results: Vec<Type>,
}

impl FuncSignature {
    /// Compute the hash of this function signature.
    pub fn hash(&self) -> TypeHash {
        // Convert Type to TypeHash for each param/result
        let param_hashes: Vec<_> = self.params.iter().map(type_to_hash).collect();
        let result_hashes: Vec<_> = self.results.iter().map(type_to_hash).collect();

        crate::metadata::hash_function(&param_hashes, &result_hashes)
    }
}

/// Convert a Pack Type to a TypeHash.
fn type_to_hash(ty: &Type) -> TypeHash {
    use crate::metadata::*;

    match ty {
        Type::Bool => HASH_BOOL,
        Type::U8 => HASH_U8,
        Type::U16 => HASH_U16,
        Type::U32 => HASH_U32,
        Type::U64 => HASH_U64,
        Type::S8 => HASH_S8,
        Type::S16 => HASH_S16,
        Type::S32 => HASH_S32,
        Type::S64 => HASH_S64,
        Type::F32 => HASH_F32,
        Type::F64 => HASH_F64,
        Type::Char => HASH_CHAR,
        Type::String => HASH_STRING,
        Type::Unit => hash_tuple(&[]), // Unit is empty tuple
        Type::List(inner) => hash_list(&type_to_hash(inner)),
        Type::Option(inner) => hash_option(&type_to_hash(inner)),
        Type::Result { ok, err } => hash_result(&type_to_hash(ok), &type_to_hash(err)),
        Type::Tuple(items) => {
            let hashes: Vec<_> = items.iter().map(type_to_hash).collect();
            hash_tuple(&hashes)
        }
        // Type::Ref references a named type - for host functions using PackType,
        // we won't encounter these since PackType maps Rust types to inline types.
        // If we do encounter a Ref, use the path name to compute a placeholder hash.
        Type::Ref(path) => {
            // Named type reference - hash based on the path string
            let path_str = path.to_string();
            let mut hasher = sha2::Sha256::new();
            hasher.update(b"ref:");
            hasher.update(path_str.as_bytes());
            TypeHash::from_bytes(hasher.finalize().into())
        }
        // Dynamic value type - use HASH_SELF_REF for consistency with pack-guest-macros
        Type::Value => HASH_SELF_REF,
    }
}

// ============================================================================
// Interface Implementation
// ============================================================================

/// A declared and implemented interface.
///
/// This combines the interface signature with its implementation,
/// ensuring they can never drift apart.
#[derive(Debug)]
pub struct InterfaceImpl {
    /// The interface name (e.g., "theater:simple/runtime")
    pub name: String,
    /// Function signatures (extracted from Rust types)
    pub functions: Vec<FuncSignature>,
}

impl InterfaceImpl {
    /// Create a new interface implementation.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            functions: Vec::new(),
        }
    }

    /// Declare and implement a function.
    ///
    /// The signature is automatically extracted from the closure's types.
    pub fn func<F, Args, Ret>(mut self, name: &str, _f: F) -> Self
    where
        F: HostFunc<Args, Ret>,
        Args: PackParams,
        Ret: PackType + 'static,
    {
        let params = Args::pack_types();
        let results = if std::any::TypeId::of::<Ret>() == std::any::TypeId::of::<()>() {
            vec![]
        } else {
            vec![Ret::pack_type()]
        };

        self.functions.push(FuncSignature {
            name: name.to_string(),
            params,
            results,
        });

        self
    }

    /// Compute the interface hash from all function signatures.
    pub fn hash(&self) -> TypeHash {
        use crate::metadata::Binding;

        // Create bindings for each function (sorted by name for determinism)
        let mut bindings: Vec<_> = self
            .functions
            .iter()
            .map(|f| Binding {
                name: &f.name,
                hash: f.hash(),
            })
            .collect();
        bindings.sort_by(|a, b| a.name.cmp(b.name));

        crate::metadata::hash_interface(
            &self.name,
            &[], // No type bindings for now
            &bindings,
        )
    }

    /// Compute the interface hash for a subset of functions.
    ///
    /// This enables partial interface matching - an actor that imports only
    /// some functions from an interface can still verify compatibility with
    /// a handler that exports the full interface.
    ///
    /// Returns None if any requested function is not found in this interface.
    pub fn hash_subset(&self, function_names: &[&str]) -> Option<TypeHash> {
        use crate::metadata::Binding;

        // Find the requested functions and compute their hashes
        let mut bindings = Vec::with_capacity(function_names.len());
        for name in function_names {
            let func = self.functions.iter().find(|f| f.name == *name)?;
            bindings.push(Binding {
                name: &func.name,
                hash: func.hash(),
            });
        }

        // Sort by name for deterministic hashing
        bindings.sort_by(|a, b| a.name.cmp(b.name));

        Some(crate::metadata::hash_interface(
            &self.name,
            &[], // No type bindings for now
            &bindings,
        ))
    }

    /// Get the hash for a specific function by name.
    ///
    /// Useful for per-function verification.
    pub fn function_hash(&self, name: &str) -> Option<TypeHash> {
        self.functions
            .iter()
            .find(|f| f.name == name)
            .map(|f| f.hash())
    }

    /// Get the interface name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the function signatures.
    pub fn signatures(&self) -> &[FuncSignature] {
        &self.functions
    }

    /// Create an InterfaceImpl from a parsed PactInterface.
    ///
    /// This constructs the full interface name from the `@package` metadata and
    /// the interface name, then extracts all exported function signatures.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pact = parse_pact(include_str!("../../../pact/runtime.pact"))
    ///     .expect("embedded runtime.pact should be valid");
    /// let interface = InterfaceImpl::from_pact(&pact);
    /// ```
    pub fn from_pact(pact: &PactInterface) -> Self {
        // Get package from metadata (e.g., "theater:simple")
        let package = pact
            .metadata
            .iter()
            .find(|m| m.name == "package")
            .and_then(|m| match &m.value {
                MetadataValue::String(s) => Some(s.as_str()),
                _ => None,
            })
            .unwrap_or("");

        // Construct full interface name: "package/interface-name"
        let full_name = if package.is_empty() {
            pact.name.clone()
        } else {
            format!("{}/{}", package, pact.name)
        };

        let mut interface = InterfaceImpl::new(full_name);

        // Extract function signatures from exports
        for export in &pact.exports {
            if let PactExport::Function(func) = export {
                let params: Vec<Type> = func.params.iter().map(|p| p.ty.clone()).collect();
                let results: Vec<Type> = func.results.clone();

                interface.functions.push(FuncSignature {
                    name: func.name.clone(),
                    params,
                    results,
                });
            }
        }

        interface
    }
}

// ============================================================================
// Host Function Traits
// ============================================================================

/// Trait for extracting parameter types from a tuple.
pub trait PackParams {
    fn pack_types() -> Vec<Type>;
}

impl PackParams for () {
    fn pack_types() -> Vec<Type> {
        vec![]
    }
}

impl<A: PackType> PackParams for (A,) {
    fn pack_types() -> Vec<Type> {
        vec![A::pack_type()]
    }
}

impl<A: PackType, B: PackType> PackParams for (A, B) {
    fn pack_types() -> Vec<Type> {
        vec![A::pack_type(), B::pack_type()]
    }
}

impl<A: PackType, B: PackType, C: PackType> PackParams for (A, B, C) {
    fn pack_types() -> Vec<Type> {
        vec![A::pack_type(), B::pack_type(), C::pack_type()]
    }
}

impl<A: PackType, B: PackType, C: PackType, D: PackType> PackParams for (A, B, C, D) {
    fn pack_types() -> Vec<Type> {
        vec![
            A::pack_type(),
            B::pack_type(),
            C::pack_type(),
            D::pack_type(),
        ]
    }
}

/// Marker trait for host functions.
///
/// This trait is implemented for closures that can be used as host functions.
/// It allows us to extract the parameter and return types at compile time.
pub trait HostFunc<Args, Ret> {}

// Implement for various closure signatures
// Note: In practice, these would need to match the actual host function signatures
// that include Ctx<T> as the first parameter.

impl<F, Ret> HostFunc<(), Ret> for F
where
    F: Fn() -> Ret,
    Ret: PackType,
{
}

impl<F, A, Ret> HostFunc<(A,), Ret> for F
where
    F: Fn(A) -> Ret,
    A: PackType,
    Ret: PackType,
{
}

impl<F, A, B, Ret> HostFunc<(A, B), Ret> for F
where
    F: Fn(A, B) -> Ret,
    A: PackType,
    B: PackType,
    Ret: PackType,
{
}

impl<F, A, B, C, Ret> HostFunc<(A, B, C), Ret> for F
where
    F: Fn(A, B, C) -> Ret,
    A: PackType,
    B: PackType,
    C: PackType,
    Ret: PackType,
{
}

impl<F, A, B, C, D, Ret> HostFunc<(A, B, C, D), Ret> for F
where
    F: Fn(A, B, C, D) -> Ret,
    A: PackType,
    B: PackType,
    C: PackType,
    D: PackType,
    Ret: PackType,
{
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pack_type_primitives() {
        assert!(matches!(String::pack_type(), Type::String));
        assert!(matches!(i32::pack_type(), Type::S32));
        assert!(matches!(bool::pack_type(), Type::Bool));
    }

    #[test]
    fn test_pack_type_compound() {
        let list_type = Vec::<u8>::pack_type();
        assert!(matches!(list_type, Type::List(_)));

        let option_type = Option::<String>::pack_type();
        assert!(matches!(option_type, Type::Option(_)));

        let result_type = Result::<String, String>::pack_type();
        assert!(matches!(result_type, Type::Result { .. }));
    }

    #[test]
    fn test_interface_impl_basic() {
        let interface = InterfaceImpl::new("test:example/api")
            .func("greet", |name: String| -> String {
                format!("Hello, {}!", name)
            })
            .func("add", |a: i32, b: i32| -> i32 { a + b });

        assert_eq!(interface.name(), "test:example/api");
        assert_eq!(interface.functions.len(), 2);

        // Check signatures
        let greet = &interface.functions[0];
        assert_eq!(greet.name, "greet");
        assert_eq!(greet.params.len(), 1);
        assert!(matches!(greet.params[0], Type::String));
        assert_eq!(greet.results.len(), 1);
        assert!(matches!(greet.results[0], Type::String));

        let add = &interface.functions[1];
        assert_eq!(add.name, "add");
        assert_eq!(add.params.len(), 2);
    }

    #[test]
    fn test_interface_hash_deterministic() {
        let interface1 = InterfaceImpl::new("test:api")
            .func("foo", |x: i32| -> i32 { x })
            .func("bar", |s: String| -> String { s });

        let interface2 = InterfaceImpl::new("test:api")
            .func("bar", |s: String| -> String { s }) // Different order
            .func("foo", |x: i32| -> i32 { x });

        // Same interface, different declaration order -> same hash
        assert_eq!(interface1.hash(), interface2.hash());
    }

    #[test]
    fn test_interface_hash_differs_on_signature() {
        let interface1 = InterfaceImpl::new("test:api").func("foo", |x: i32| -> i32 { x });

        let interface2 = InterfaceImpl::new("test:api").func("foo", |x: i64| -> i64 { x }); // Different type!

        assert_ne!(interface1.hash(), interface2.hash());
    }

    #[test]
    fn test_from_pact_basic() {
        use crate::parser::parse_pact;

        let src = r#"
            interface runtime {
                @package: string = "theater:simple"

                exports {
                    log: func(msg: string)
                    get-chain: func() -> list<u8>
                    shutdown: func(data: option<list<u8>>) -> result<_, string>
                }
            }
        "#;

        let pact = parse_pact(src).expect("should parse");
        let interface = InterfaceImpl::from_pact(&pact);

        assert_eq!(interface.name(), "theater:simple/runtime");
        assert_eq!(interface.functions.len(), 3);

        // Check function names
        let names: Vec<&str> = interface
            .functions
            .iter()
            .map(|f| f.name.as_str())
            .collect();
        assert!(names.contains(&"log"));
        assert!(names.contains(&"get-chain"));
        assert!(names.contains(&"shutdown"));

        // Check log function signature
        let log_fn = interface
            .functions
            .iter()
            .find(|f| f.name == "log")
            .unwrap();
        assert_eq!(log_fn.params.len(), 1);
        assert!(matches!(log_fn.params[0], Type::String));
        assert!(log_fn.results.is_empty());

        // Check get-chain function signature
        let get_chain_fn = interface
            .functions
            .iter()
            .find(|f| f.name == "get-chain")
            .unwrap();
        assert!(get_chain_fn.params.is_empty());
        assert_eq!(get_chain_fn.results.len(), 1);
        assert!(matches!(get_chain_fn.results[0], Type::List(_)));
    }

    #[test]
    fn test_from_pact_hash_determinism() {
        use crate::parser::parse_pact;

        let src = r#"
            interface test {
                @package: string = "my:package"

                exports {
                    add: func(a: s32, b: s32) -> s32
                    subtract: func(a: s32, b: s32) -> s32
                }
            }
        "#;

        let pact1 = parse_pact(src).expect("should parse");
        let pact2 = parse_pact(src).expect("should parse");

        let interface1 = InterfaceImpl::from_pact(&pact1);
        let interface2 = InterfaceImpl::from_pact(&pact2);

        assert_eq!(interface1.hash(), interface2.hash());
    }

    #[test]
    fn test_from_pact_matches_hand_coded() {
        use crate::parser::parse_pact;

        // Hand-coded interface
        let hand_coded = InterfaceImpl::new("test:example/calculator")
            .func("add", |_a: i32, _b: i32| -> i32 { 0 })
            .func("subtract", |_a: i32, _b: i32| -> i32 { 0 });

        // Pact-based interface
        let src = r#"
            interface calculator {
                @package: string = "test:example"

                exports {
                    add: func(a: s32, b: s32) -> s32
                    subtract: func(a: s32, b: s32) -> s32
                }
            }
        "#;

        let pact = parse_pact(src).expect("should parse");
        let from_pact = InterfaceImpl::from_pact(&pact);

        // Names should match
        assert_eq!(hand_coded.name(), from_pact.name());

        // Hashes should match
        assert_eq!(
            hand_coded.hash(),
            from_pact.hash(),
            "Hand-coded interface hash should match pact-based interface hash"
        );
    }
}