proc-macro2 icon indicating copy to clipboard operation
proc-macro2 copied to clipboard

impl PartialEq/Eq for TokenStream and TokenTree

Open cehteh opened this issue 1 year ago • 1 comments

While this is not really required for implementing proc-macros it helps a lot in tests where one can assert_eq!() expected results. Comparing TokenStream/TokenTrees directly with each other.

This addition is pretty trivial, so I just gone ahead implementing/PR this here. Although comparing TokenTrees doesn't come for free since Literals have to converted to_string() just to be dropped afterward. IMO this is good enough for the intended use in tests.

Whats your opinion about adding this?

cehteh avatar Sep 02 '24 13:09 cehteh

Unarguably the fail looks pretty ugly, so far i am using to_string() already.

I had the impression that '.to_string()' might be not very well defined in respect to spacing in all cases. If this is not true, then this PR/Idea is indeed void.

EDIT: Actually this is BS as long one TokenStream::to_string() the 'expected' side too. My worries where about providing string literals or constructing/concatenating the expected side somehow else.

cehteh avatar Sep 04 '24 11:09 cehteh

Just wanna point out for anyone stumbling on this issue looking for nicer diffs that you can use the prettyplease crate (also by the amazing @dtolnay ) to achieve that.

fn token_stream_to_string(token_stream: proc_macro2::TokenStream) -> String {
    prettyplease::unparse(&syn::parse2(token_stream).unwrap())
}
let a = quote::quote! {
    // this won't show up in the output
    /// This is a doc comment
    fn foo() {}
};
let b = quote::quote! {
    /// This is a different doc comment
    fn foo() {}
};
pretty_assertions::assert_eq!(token_stream_to_string(a), token_stream_to_string(b));

MendyBerger avatar Jun 24 '25 19:06 MendyBerger