Qoros
Qoros

Reputation: 513

How to load Rust compiler plugins without modifying the source code?

Rust provides various ways to write plugins. To extend checks on Rust code, it allows developer to write Lint Plugins. A typical way to use the plugin is to add a line to the source code indicating the use of this plugin:

#![plugin(myplugin)]

You also need to edit the Cargo.toml file to include your plugin project in the dependencies section:

myplugin = {path = "/path/to/myproject"}

However, if you want to analyze big projects, these modifications seem to be troubling, I wonder if cargo build or rustc provides any way to load my plugins without modifying the source code.

Upvotes: 2

Views: 557

Answers (1)

Francis Gagné
Francis Gagné

Reputation: 65752

rustc has a command-line parameter for loading additional plugins: -Z extra-plugins=<plugins>. However, this option also requires that the path to the compiled plugin library be passed to the compiler. This is done automatically if the plugin library is declared as a dependency in Cargo.toml. If it's not in Cargo.toml, then you can compile it independently and reference it manually with --extern my_plugin=/path/to/plugin.rlib, in addition to the -Z extra-plugins=<plugins> option.

There's another option. Clippy, a large collection of general lints for Rust, provides a program that can be invoked as cargo clippy. That program basically acts as a fake rustc, implementing a compiler frontend (using internal crates used by rustc) that loads Clippy directly into the compiler's plugin registry (for the main project only, not for the project's dependencies). You can see the code on GitHub (licensed under MPLv2). The advantage of this approach is that you don't have to give a path to the plugin, because the plugin is built in the frontend. This makes it very convenient to use for the plugin's users. The disadvantage is that such a program relies on unstable compiler internals. This means that your program can stop compiling at any time due to a breaking change in rustc's unstable API.

Upvotes: 3

Related Questions