-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Make getter
s, setter
s, and constructor
s compiler errors for enums
#4278
base: main
Are you sure you want to change the base?
Make getter
s, setter
s, and constructor
s compiler errors for enums
#4278
Conversation
So that's unfortunate. So either we give up on good error messages, or we conditionally enable the attribute only for Rust versions that support it like zerocopy does (see their |
We established over chat that we want to use |
Alright, I added a new (Btw, Another change is that I raised the rust version we use to run UI tests in CI from 1.76 to 1.78. This is necessary for the CI to actually test the custom trait impl error messages. However, this also caused a few other UI tests to slightly change their output, so I had to update their output as well. Hence this PR touches a few unrelated test files. |
This PR implements a compile-time check to verify that enums have no methods with
#[wasm_bindgen(getter)]
,#[wasm_bindgen(setter)]
, and#[wasm_bindgen(constructor)]
. This was previously accepted and resulted in incorrect JS code gen.The check is implemented like I outlined in this comment. There are 3 new internal marker traits (
SupportsConstructor
,SupportsInstanceProperty
,SupportsStaticProperty
) that are implemented bystruct
s with#[wasm_bindgen]
and notenum
s. Exported function then generate aconst _: ()
that checks whether theSelf
type (if any) implements those traits. I useddiagnostic::on_unimplemented
to make the trait errors easily understandable for users.Example error for using
#[wasm_bindgen(constructor)]
on an enum calledRustEnum
:As we can see, the error message is clear and even offers a suggestion to fix the error.
This PR is virtually a minimal implementation of a technique we could use a lot more. E.g. it can be used to verify that the
Self
type actually has a#[wasm_bindgen]
macro (the test file I added includes an example where exactly this case does not cause an error). However, I kept it minimal so we can concentrate on the "how" this PR does things.As for the how: I initially wanted to add just a single trait (something like
IsStruct
) and then let constructors/getters/setters/etc. assert that they are on a struct. This did work, but resulted in error messages that were a lot worse. By using traits that describe the capabilities of the type and not what the type is, error messages can be a lot more specific. Plus, adding/removing/changing capabilities seems easier at scale.