How to modify all functions without syntax extension in compiler plugin?


#1

I am trying the way to modify all functions without syntax extension in rustc plugin.

For detail, what I want to do is inserting some instructions to entries of all functions using compiler plugin.
But in now, the only way I know is using syntax extension:

#[insert_instruction_to_entry]
fn func() { ... }

But, this is very annoying way and requires the modification of source code, so I want to do same thing without using syntax extension.
Who can let me know the way, please?


#2

This is possible with the newly stable attribute-like procedural macros. See https://doc.rust-lang.org/book/ch19-06-macros.html - the example there has us writing a custom derive macro but the process for writing attribute-like ones is very similar.

The main difference is using #[proc_macro_attribute] rather than #[proc_macro_derive].

I would recommend reading that chapter of the book then looking over this full attribute-macro example: https://github.com/dtolnay/syn/tree/master/examples/trace-var


#3

@daboross Thanks for your reply.
But what I want is the way to do this without adding ‘something’ to all functions or modules.

fn func() { ... }

I want to add some instructions to entry of that function without adding any thing to the beginning of the function.


#4

Ah, I see. I don’t know of any way to do this besides proc macros.

One option you have would be to use a proc macro on the crate itself, and within the macro parse the entire crate and then each function within it. You could have the syntax be something like

// once, at the top of lib.rs:
#![my_macro]

then the macro would be able to modify everything within the crate at once?


There are also compiler plugins, but I don’t know much about making those. They’re fully unstable.

I mentioned proc macros originally because I misread your post and thought you were trying to avoid compiler plugins.