fix: better suggestion when encoding is not implemented (#843)

Here is a code snippet that demonstrates the issue:
```rust
use extism_pdk::{encoding, plugin_fn, FnResult, FromBytes, Json, ToBytes};
use serde::{Serialize, Deserialize};

#[derive(Deserialize,FromBytes)]
pub struct Input {
    value:String
}

#[derive(Serialize, ToBytes)]
pub struct Output {
    value: f64,
}

#[plugin_fn]
pub fn convert(in_value: Input) -> FnResult<Output> {
    Ok(Output { value: in_value.value.parse().expect("Conversion failed") })
}
```

Because the structs don't derive `encoding` the rust-analyzer gives this
suggestion:
```
encoding needs to be specified

  = try: `#[encoding(ToJson)]`
```

I don't think this suggestion is correct because i could not find
`ToJson` anywhere. Adding `#[encoding(Json)]` solves the issue (as
described in the docs).
The final code would look as follows:
```rust
use extism_pdk::{encoding, plugin_fn, FnResult, FromBytes, Json, ToBytes};
use serde::{Serialize, Deserialize};

#[derive(Deserialize,FromBytes)]
#[encoding(Json)]
pub struct Input {
    value:String
}

#[derive(Serialize, ToBytes)]
#[encoding(Json)]
pub struct Output {
    value: f64,
}

#[plugin_fn]
pub fn convert(in_value: Input) -> FnResult<Output> {
    Ok(Output { value: in_value.value.parse().expect("Conversion failed") })
}
```

And compiles perfectly.

I think the suggestion given by the rust-analyzer is incorrect so i am
proposing a fix for this.

Since I'm new to the project, any feedback is appreciated.
Thanks!
_Alessandro Ruggiero_
This commit is contained in:
AlessandroRuggiero
2025-03-31 17:15:23 +02:00
committed by GitHub
parent f8e16dc875
commit 1ea498b5d9

View File

@@ -34,11 +34,11 @@ fn extract_encoding(attrs: &[Attribute]) -> Result<Path> {
.iter()
.filter(|attr| attr.path().is_ident("encoding"))
.collect();
ensure!(!encodings.is_empty(), "encoding needs to be specified"; try = "`#[encoding(ToJson)]`");
ensure!(!encodings.is_empty(), "encoding needs to be specified"; try = "`#[encoding(Json)]`");
ensure!(encodings.len() < 2, encodings[1], "only one encoding can be specified"; try = "remove `{}`", encodings[1].to_token_stream());
Ok(encodings[0].parse_args().map_err(
|e| error_message!(e.span(), "{e}"; note= "expects a path"; try = "`#[encoding(ToJson)]`"),
|e| error_message!(e.span(), "{e}"; note= "expects a path"; try = "`#[encoding(Json)]`"),
)?)
}