FWIW, here is what the code to handle all the cases correctly looks like:
![]()
I personally agree that it could be legitimate to bundle some of these helpers into the "standard" proc-macro library, if only because it could perform some of these operations in a more performant fashion (unnecessary additional stringifications),
- In that regard, I think that a
with_str<R>(&self, _: impl FnOnce(&str) -> R) -> Rkind of API would be a simple, and performant optimization over the currentDisplay-based API ofLiterals (usingDisplayto inspect a value seems like a hack).
and also because most macro authors may not be aware of these caveats.
That being said, I don't think this logic belongs to a TryFrom trait; it should involve some ParseLiteral trait, which could be akin to FromStr (which incidentally relates to the with_str API). For instance, with integer literals, we shouldn't be assuming the underlying type nor the underlying base. So I'd expect things like
let n = lit.get_value::<parse_base_10::u16>()?;
let s = lit.get_value::<String>()?;
rather than:
let n = u16::try_from(lit)?;
let s = String::try_from(lit)?;