darling icon indicating copy to clipboard operation
darling copied to clipboard

Construct darling::Error from TokenStream

Open DCNick3 opened this issue 2 years ago • 5 comments

For interoperability reasons, it would be nice to be able to convert TokenStream (containing compile_error! invocations) into a darling error.

This would be particularly useful to convert an error from manyhow crate into a darling error.

Another way to achieve this is to make all darling traits use manyhow's error trait/error type, but I am not sure manyhow is ready to embraced likes this yet =)

DCNick3 avatar Jul 25 '23 08:07 DCNick3

A proc_macro2::TokenStream already impls Display, which means it can be wrapped using darling::Error::custom.

Alternatively, wouldn't it be possible for manyhow to add impl From<manyhow::Error> for darling::Error and impl ToTokensError for darling::Error without running afoul of coherence rules?

Another way to achieve this is to make all darling traits use manyhow's error trait/error type

Given that darling would like to decrease its impact on build time, it won't be adopting any external dependencies for its existing functionality, but I think it should be possible for manyhow to provide those impls (and feature-gate them if needed so that it only impacts build time for crates using both darling and manyhow).

TedDriggs avatar Jul 25 '23 12:07 TedDriggs

Isn't the contents of darling::Error::custom designed for human-readable text that later gets wrapped into compile_error! invocation?

manyhow already does have an of ToTokensError for darling::Error, so that direction is not a problem. manyhow assumes a more general type for a error: "something that can be converted to tokens", and I don't see a way to round-trip those tokens through a darling::Error

DCNick3 avatar Jul 25 '23 13:07 DCNick3

What would the error message would be in that situation?

TedDriggs avatar Jul 25 '23 14:07 TedDriggs

The error message is whatever the compiler spits out when parsing the compiler_error! invocations.

Now that I think of it, it might also make sense to make the Display impl nicer than just the tokens.. So, maybe take two arguments: tokens and text for Display?

DCNick3 avatar Jul 25 '23 14:07 DCNick3

I'm not sure how that's different from the current approach, which allows calling custom and then setting the span using with_span.

TedDriggs avatar Aug 01 '23 21:08 TedDriggs