Extract return type from function in procedural macro

Hi there,
I'm quite new to procedural macros and trying to use the return type of a function decorated with my custom attribute. I got so far retrieving the output like so:

let func = parse_macro_input!(item as ItemFn);
let output = func.decl.output;

However, the output gives ReturnType enum that is either Default or Type(_, _).
So the output looks like:

Output: Type(
    RArrow,
    Path(
        TypePath {
            qself: None,
            path: Path {
                leading_colon: None,
                segments: [
                    PathSegment {
                        ident: Ident {
                            ident: "u32",
                            span: #0 bytes(184..187),
                        },
                        arguments: None,
                    },
                ],
            },
        },
    ),
)

Is there an easy way to extract the u32 type info to be used in subsequent calls to quote!( ) ?
Currently all my attempts failed so far... so any hint would be much appreciated.

Huh, I'm surprised that syn::ReturnType doesn't have a convenient to_type method.

I would try something like: (not tested, might need tweaking to compile)

let ty: syn::Type = match func.decl.output {
    syn::ReturnType::Type(_, ty) => *ty,
    syn::ReturnType::Default => parse_quote!{ () },
};

syn::Type is, of course, a type that you can freely use in quote!(), as it implements ToTokens.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.