Published on

TIL: How to Display the AST in Rust

Authors
  • Mehdi Akiki avatar
    Name
    Mehdi Akiki
    Twitter

Today I learned how to view the Abstract Syntax Tree (AST) in Rust using the rustc compiler with the nightly toolchain.

Steps to Display the AST

Install the nightly toolchain if you don't have it:

rustup install nightly

Compile your Rust file using the -Z unpretty=ast-tree flag to display the AST in a human-readable format:

rustc +nightly -Z unpretty=ast-tree your_file.rs

This will print the AST of your file directly in the terminal.

To view the expanded AST (after macros are expanded), use the following command:

rustc +nightly -Z unpretty=ast-tree,expanded your_file.rs

Summary

The rustc compiler provides a powerful way to inspect the internals of your code by generating the AST. This can be particularly useful when debugging or understanding how macros are expanded. The -Z unpretty flag offers several options to view different levels of the compiler's internal representations.

I build and scale reliable production systems. Open to full-time and freelance work with U.S.-based teams that value ownership and execution.

Got something in mind?

Book a Discovery Call