Macros: retrieving ident type

I am trying to create a macro or syntax extension that will allow me to write something like that:

fn somefunc() { let a = 0u64; let b = 4i32;

probe!(a, b); }

where a, b refers to existing variable names, and in this macro I want to be able to retrieve a and b types.

Here is what I’ve found:

syntax::ext::base provide following options:

a) syntax extension using MultiModifier (or AttrProcMacro?)

This work on ast and gives me access to type parameters, but only as a function decorator. I do not have a function here, so it doesn’t work for me.

b) ProcMacro. Operates on TokenStream, so no access to types yet, right? Doesnt work for me either.

Am I missing something, or is there any other way to do it?

As far as I understand, and I'm no expert - types are just compile time structures. They don't exist during runtime. Although some procedural macros can use tricks* to get around it. For example println! macros.

EDIT: By tricks I mean println! parses arguments and applies apropriate macros to given arguments. So if you try to use println!("{0:b} ", 2.3f32)" you get an error, std::fmt::Binary not implemented for f32.

I don’t wan’t to “query them”, I want to know what they are. So for a it u64, for b it i32. This is the information I want to retrieve.

Ah - right. Println may be what I can look at.

Nope, println!, format! etc. are compiler builtins hardcoded into libsyntax. So dead end here.

Macros can’t look at types, because macro expansion happens on a purely syntactical level, before names are resolved and types are inferred. What you are asking for is impossible by design.

println! etc. are not special by the way, they just generate code that works regardless of the specific types of the arguments (using the std::fmt::* traits).

2 Likes

As rkruppe said, types exist only on a purely syntax level. You can't acquire them at runtime or compile time.

Never give up :smiley: Indeed if you look at macro_rules! format_args it does say compiler built-in.

What that means is that it is actually shadowed by a procedural macro from libsyntax_ext. There is also a parser for arguments in fmt_macros library.

Right, those are tricks I mentioned, but forgot what they were.

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