Is it possible to parse the Rust source file into HIR?


#1

Hi rustaceans :slight_smile:

Lately, I’ve been really interested in compilers and I’d love to learn more about them. I have come to learn through projects like MIRI that there are multiple IR in Rust!

Could any one please suggest me how to obtain this HIR from a crate or a source file?


#2

You can write a lint plugin that uses the check_crate method to get access to the crate’s HIR.

Lint plugin documentation is here: https://doc.rust-lang.org/book/compiler-plugins.html#lint-plugins You’ll need a LateLintPass and not an EarlyLintPass (the latter is the AST, not the HIR)


#3

These commands will get you started:

  • rustc a.rs -Z unstable-options --unpretty mir
  • rustc a.rs -Z unstable-options --unpretty hir

You can pass a few other arguments to --unpretty too, check them out!

The following RFC is a must read if you want to learn more about IRs: https://github.com/rust-lang/rfcs/blob/master/text/1211-mir.md I’d also suggest looking for *.md files in the rust source tree, some real gems are out there!


#4

Also its important to note that the HIR is not at all stable & if so if you upgrade your version of Rust any code you write based on it might be broken.


#5

Thanks a tone @stjepang!! This little info has been absolutely wonderful :thumbsup:


#6

Actually, I’m just trying to use HIR as the target code or a transcompiler - you reckon that MIR would be a better target?


#7

There’s no guarantee of stability around either representation AFAIK. You’d have to pin to a particular version of Rust.