DouglasDwyer / wasm_component_layer

WebAssembly component model implementation for any backend.
68 stars 10 forks source link

Using resources as types #7

Closed olliptln closed 9 months ago

olliptln commented 9 months ago

Trying to use a resource as a type doesn't appear to work. I'm not sure if this is a bug, missing feature, or if I'm just trying to misuse the package.

Adapted from the resource example, I bring the resource type to use and add the resource as a result type to the function:

package test:guest

interface foo {
    use bar.{myresource}
    // Creates and uses a resource
    use-resource: func() -> myresource
}

interface bar {
    resource myresource { 
        constructor(a: s32)
        print-a: func()
    }
}

world guest {
    export foo
    import bar
}

Trying to instantiate the linker, where the appropriate resources and functions are already defined, gives the following error: Cannot instantiate resource as type

which comes from:

Stack backtrace:
   0: anyhow::kind::Adhoc::new
             at /home/User/.cargo/registry/src/index.crates.io-6f17d22bba15001f/anyhow-1.0.76/src/kind.rs:71:36
   1: wasm_component_layer::types::ValueType::from_component_typedef
             at /home/User/Downloads/wasm_component_layer-master/src/types.rs:226:50
   2: wasm_component_layer::types::ValueType::from_component
             at /home/User/Downloads/wasm_component_layer-master/src/types.rs:208:40
   3: wasm_component_layer::types::ValueType::from_component_typedef
             at /home/User/Downloads/wasm_component_layer-master/src/types.rs:276:49
   4: wasm_component_layer::Instance::generate_types
             at /home/User/Downloads/wasm_component_layer-master/src/lib.rs:1287:28
   5: wasm_component_layer::Instance::new
             at /home/User/Downloads/wasm_component_layer-master/src/lib.rs:1194:21
   6: wasm_component_layer::Linker::instantiate
             at /home/User/Downloads/wasm_component_layer-master/src/lib.rs:1094:9

The problem is specifically the "use bar.{myresource}" line.

Doing this should be supported in wit, according to https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md, for example the last example on that page.

From types.rs it seems Own and Borrow resources are supported, but not resources as such. Maybe the wit parser should interpret this as a Own resource, as that's the default?

DouglasDwyer commented 9 months ago

This is a bug, which seems to stem from the fact that wit_parser treats imported types differently than types in the same interface. It is fixed in 30c202620c0b35cdfcaef829ea4e7b70ba4516dc and version 0.1.15. You're the first one to be seriously using resources, so I guess you're running into all the issues haha. Feel free to let me know if you encounter any more problems!