Stream: t-compiler/rust-analyzer

Topic: macro expansion


Mihir Luthra (Jun 07 2021 at 02:52, on Zulip):

I was working on some project where I want to parse rust source files and expand specific macros (without expanding the ones nested in it). I have seen rust-analyzer does that.
I was interested in understanding how does rust-analyzer do that. Can someone point me to the code in RA repo where this is done?

matklad (Jun 07 2021 at 11:25, on Zulip):

That's a rather complicated process. A good entry point to learn about it would be this function: https://github.com/rust-analyzer/rust-analyzer/blob/5f7fc5ae68ff5debead06e377153e100b6e9951d/crates/ide/src/expand_macro.rs#L17-L41.

Mihir Luthra (Jun 07 2021 at 11:34, on Zulip):

Thanks, will check it out :)

Mihir Luthra (Jun 07 2021 at 11:39, on Zulip):

Also, I was checking out hir_expand crate. Is it usable externally without RA specific data?

Florian Diebold (Jun 07 2021 at 11:59, on Zulip):

hir_expand is not intended to be used alone. hir is the crate you would use, and it should be usable for this, but the APIs are still experimental and can change all the time

Florian Diebold (Jun 07 2021 at 12:00, on Zulip):

also note that to expand one macro, you basically need to expand all, because name resolution is intertwined with macro expansion and you can't know in advance which macros you need to expand to be able to resolve the one macro you're actually interested in

Mihir Luthra (Jun 07 2021 at 12:27, on Zulip):

@Florian Diebold , I am
not sure I understand completely. When I bring my cursor over a macro, it does expand that specific macro without expanding nested ones. So how can I not know in advance which macro to expand?

Florian Diebold (Jun 07 2021 at 12:27, on Zulip):

it has already expanded all macros in the crate at that point

Florian Diebold (Jun 07 2021 at 12:28, on Zulip):

I don't mean that you can't request the expansion for a specific macro call, just that getting that expansion isn't as easy as "parse the file, expand that specific macro"

Mihir Luthra (Jun 07 2021 at 12:30, on Zulip):

Okay, that makes sense. I suppose this would still work for me. I will check the hir crate. Thanks!

Last update: Jul 28 2021 at 03:15UTC