Modifying function of a dependency during compilation


I've been wondering whether It's possible to modify part of a function from my crate's dependencies, like for example injecting additional code at the beginning of it. I know I can just fork and modify It if I want, but my main goal is creating a library/tool that would help with that without the need for maintaining forks.

Initially I wanted to modify AST or HIR of the entire project, but there seems to be no easy way of getting It without going into rustc internals. Attribute macros (like #![...]) can only get my crate's AST, and from what I searched HIR is supposed to be immutable, so I shouldn't modify It. After more research I found that It might be possible to write custom rustc plugin that will gather all the necessary info from HIR and then modify MIR in the way that I want.

However, I'm asking this question to maybe find a better way of doing this, so If you know any better way this could be done please let me know. I considered asking this question on, but maybe it's possible without going through rustc plugins or forks.

This is not supported by the standard tools because it is fragile.

  • Suppose that you want to modify some crate (foo), and it has two dependents: your crate (bar), and another crate you depend on (baz). Then your changes might break baz's usage of foo. This is the fundamental reason why it cannot be permitted for a dependent to modify a dependency.
  • Also, an arbitrary change might not work as intended with a newer version of foo, because a crate's function bodies are its own business which it is free to change as it sees fit across versions.

Now, as the party starting the build (not as the dependent package), you do get to replace packages using [patch]. In principle, that could support a mechanism to modify code and not just to replace it. But if there is to be a general tool, especially one that works from within the compiler, it's going to have to be something that plays well with versioning and abstraction boundaries.


Thanks so much, I didn't know about cargo patch feature, this does almost exactly what I was looking for. :smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.