• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


11 Jan, 2025

Updated at 18 Jan, 2025

Custom inlay hints in a proc macro

When you want to throw an error in a proc_macro you can use syn::Error#into_compiler_error() to throw a compiler error at a specific span, and rust-analyzer on vscode will draw a red squiggly line

Is there a similar TokenStream you can emit that creates a custom inlay hint?

For example (assume the proc_macro is in a separate crate from main() so it actually compiles):

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, punctuated::Punctuated, token::Comma, LitInt};

fn sum(lhs: u32, rhs: u32) -> u32 {
    lhs + rhs
}

#[proc_macro]
pub fn sum_macro(input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(input with Punctuated<LitInt, Comma>::parse_terminated);
    let mut iter = args.iter().map(|v| v.base10_parse::<u32>().unwrap());

    let lhs = iter.next().unwrap_or(0);
    let rhs = iter.next().unwrap_or(0);

    quote! { #lhs + #rhs }.into()
}

fn main() {
    sum(1, 2);
    sum_macro!(1, 2);
}

Looks like this in vscode with rust analyzer:

Is there a way of manually inserting inlay hints for the two arguments like those automatically done for the sum() function?

1 post - 1 participant

Read full topic