Getting value out of `proc_macro::Literal`

FWIW, here is what the code to handle all the cases correctly looks like:

:dizzy_face:

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) -> R kind of API would be a simple, and performant optimization over the current Display-based API of Literals (using Display to 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)?;