wit-bindgen icon indicating copy to clipboard operation
wit-bindgen copied to clipboard

[Rust] See through type aliases for borrowing optimizations

Open rylev opened this issue 2 years ago • 2 comments

As noted in https://github.com/bytecodealliance/wit-bindgen/issues/769 and https://github.com/bytecodealliance/wit-bindgen/pull/675, type aliases cause certain optimizations around borrowing to not longer be applied.

For example take the following semantically equivalent functions in wit:

borrow: func(param: list<u8>);

type param = list<u8>;
no-borrow: func(param: param);

Those functions will be generated as the following:

fn borrow(param: &[u8]);

type Param = Vec<u8>;
fn no_borrow(param: Param);

Unfortunately, we want to preserve the structure of the wit files in the generated code meaning that generating the no_borrow function with a &[u8] param instead of the Param alias would violate that tenant. It is unclear which should take precedent, the borrowing optimization or the desire to maintain wit structure.

rylev avatar Dec 04 '23 09:12 rylev

Shouldn't we just generate something like this?

fn borrow(param: &[u8]);

type Param<'call> = &'call [u8];
fn no_borrow<'call>(param: Param<'call>);

Rust Playground

esoterra avatar Dec 04 '23 16:12 esoterra

How do we handle the following then:

type param = list<u8>;
no-borrow: func(param: param);

record my-record {
  field: param
}

This would require two types: a borrowed type used as a function parameter and a type used in owned contexts such as struct fields. This is doable, but it violates the goal of having the generated code mirror the wit declaration.

rylev avatar Dec 05 '23 09:12 rylev