TIL: Serde's borrowing can be treacherous
5 points
9 hours ago
| 1 comment
| yossarian.net
| HN
qouteall
8 hours ago
[-]
One limitation of Rust macro is that it can only access code token, not actual type information.

When macro sees a type `X` macro can never be sure whether it's `&str` as Rust allows type alias. If `X` is not `&str` it may also be a struct that contains `&str`, still macro cannot know.

Wasm-bindgen workarounds this issue by generating "fake functions" then read and remove them in CLI:

https://wasm-bindgen.github.io/wasm-bindgen/contributing/des...

Zig comptime allows getting full type information. This is one advantage of Zig.

reply
SkiFire13
4 hours ago
[-]
While this is true, it is kind of orthogonal to the issue here, since the macro correctly guessed that `&str` referred to a borrowed string and generated code for it.

The issue was that the deserializer could produce non-borrowable strings at runtime, which cannot be used to create an instance of this type and hence caused a runtime panic.

Catching this should be possible (even without precise type informations) but I'm not sure it can be done without breaking changes to the Deserializer trait. It would also suffer from false positives since sometimes you might know that the inputs you will deserialize only include strings that can be deserialized in this way.

reply