rustrust-proc-macros

How do I make the quote! macro print hex literals?


I'm using quote to auto-generate code for use in an embedded system. Some of the auto-generated code has numbers which would be way easier to read as hex.

Here's an example.

use quote::quote;

fn main() {
    let value = 0x1005;
    let tokens = quote! {
        let x = #value;
    }.to_string();
    println!("{}", tokens);
}

This prints

let x = 4101u16 ;

but I'd like it to be

let x = 0x1005u16 ;

Solution

  • If you will parse it from a string, it will remain how you typed it:

    use std::str::FromStr;
    use quote::quote;
    
    fn main() {
        let value = 0x1005;
        let value = proc_macro2::Literal::from_str(&format!("0x{value:x}i32")).unwrap();
        let tokens = quote! {
            let x = #value;
        }.to_string();
        println!("{tokens}");
    }