How to set up hooks at the beginning and end of a function?

Hello, I'm working on a tooling project that requires hooks at the start and end of functions, which should be applied automatically to all functions without editing each function's code individually. How can this be done?

do you mean the functions in your crate or somehow every function ever

Every function in the main crate. I'm creating a library, the hooks should be applied to all functions in the project that uses the library

well then you should look at proc macros. i may be wrong, but i fear you may have to put an attribute on each function you want to have hooks.

i guess if they are in a module, you can put the attribute on the module instead

With Cargo, this is impossible by design. Dependencies can't influence how their dependents are compiled.

It's not possible. There's no such language feature. Rust is too low-level and too strict about isolation of crates to let you do such things.

You'd have to modify the Rust compiler to insert such instrumentation automatically.

You might be able to insert hooks at the LLVM level, e.g. if you generate Rust crates as bitcode and then modify and compile the rest yourself, but that's also a tricky process, and it would miss functions that were inlined early by rustc's MIR pass.

If you don't need to modify runtime behavior, then you could use debuginfo to trace which functions are running, similarly to how profilers do it.

The most reasonable implementation at the language level would be a proc macro that edits the functions at source code level to add instrumentation you want. The tracing crate has such macro. It does require explicit attribute for every function.

i immagine that you don't actually need it for all funtions but rather just in a few specific places for arbitrary functions in which case you should use either a macro or an onject that wraps the function an provides the hooks