Tips & Tricks

IntelliJ Rust features. Entry one: Macros

In this series of short blog posts, we are going to take a closer look at the key Rust-related features available in JetBrains IDEs through our corresponding plugin.

However, before we do that, let me briefly remind you about the current state of the Rust plugin:

  • It is available in all our IntelliJ-based IDEs.
  • It relies on the Cargo build system, and CLion is no exception here.
  • The debugging feature for Rust code is currently only available in CLion.

While macros are essential for Rustaceans, they can be finicky from time to time. Fortunately, there are tools around to help ease your burden.

Let’s create a macro foo! that takes an identifier, a type, and an expression and generates a simple function with a given name and type that will just return the given expression in its entirety.

As soon as we invoke it with fitting arguments anywhere in the code, the proper type inference shows that the macro result is now fully acknowledged by the IDE! Smart Code Completion already knows what the resulting code of the macro can be, and applicable items are suggested accordingly. It is really quite handy.

Here’s an example of how it works with the popular error_chain crate which is based on macros and can be used to straighten out your error handling:

You can also take a look under the hood yourself with a convenient popup. Just right-click an invocation and choose one of two options:

Show expanded macro to see the result of one in particular that you want to look at and ignore subsequent internal invocations, or Show recursively expanded macro to look through all of them:

It’s even aware of the methods declared by a macro:

Rust functionality is easy to include and can be found inside the Plugins tab in the settings of your JetBrains IDE of choice: Settings | Plugins.

Though, the debugger for Rust code is currently exclusive to CLion.

To learn more about the plugin, check out the link.

Thanks for reading this, and see you soon!

Respectfully,

The Rust team

image description