How to get lifetime information

I want to write a program that needs to get the lifetime of any variable to do some analysis. The lifetime info needs to be reversed to the position in the source code. Is there any API in rustc or other tools (maybe RLS) that can do it? Thanks.

1 Like

Can you specify what you're trying to accomplish? A lifetime does not always have a meaningful correspondence to some span of code, and is more closely related to the control flow graph.

Sorry for replying late! I am thinking about making a lifetime visualizer as an IDE plugin. It will visualize the lifetime of the user-selected variable by background-highlighting in the source code. Since lifetime is an important concept in Rust and sometimes confusing, it may help. How about this idea and how can I access the lifetime information?

1 Like

I've found that librustc_mir::borrow_check and librustc_ast_borrowck are rather tight lipped (read: have few useful public members) apart from the full end-to-end graphviz output. If you dig a bit deeper, you'll find that borrowck relies heavily on ExprUseVisitor and its Delegate. It may or may not give you the information you want, but it seems like the closest thing you'll get for a single-pass workflow.

Great tips, I will look into that. Thx!