3 The tracking issue for this feature is: [#29597]
5 [#29597]: https://github.com/rust-lang/rust/issues/29597
8 This feature is part of "compiler plugins." It will often be used with the
9 [`plugin_registrar`] and `rustc_private` features.
11 [`plugin_registrar`]: language-features/plugin-registrar.html
13 ------------------------
15 `rustc` can load compiler plugins, which are user-provided libraries that
16 extend the compiler's behavior with new syntax extensions, lint checks, etc.
18 A plugin is a dynamic library crate with a designated *registrar* function that
19 registers extensions with `rustc`. Other crates can load these extensions using
20 the crate attribute `#![plugin(...)]`. See the
21 `rustc_plugin` documentation for more about the
22 mechanics of defining and loading a plugin.
24 If present, arguments passed as `#![plugin(foo(... args ...))]` are not
25 interpreted by rustc itself. They are provided to the plugin through the
26 `Registry`'s `args` method.
28 In the vast majority of cases, a plugin should *only* be used through
29 `#![plugin]` and not through an `extern crate` item. Linking a plugin would
30 pull in all of libsyntax and librustc as dependencies of your crate. This is
31 generally unwanted unless you are building another plugin. The
32 `plugin_as_library` lint checks these guidelines.
34 The usual practice is to put compiler plugins in their own crate, separate from
35 any `macro_rules!` macros or ordinary Rust code meant to be used by consumers
40 Plugins can extend Rust's syntax in various ways. One kind of syntax extension
41 is the procedural macro. These are invoked the same way as [ordinary
42 macros](../book/macros.html), but the expansion is performed by arbitrary Rust
43 code that manipulates syntax trees at
47 [`roman_numerals.rs`](https://github.com/rust-lang/rust/blob/master/src/test/run-pass-fulldeps/auxiliary/roman_numerals.rs)
48 that implements Roman numeral integer literals.
51 #![crate_type="dylib"]
52 #![feature(plugin_registrar, rustc_private)]
55 extern crate syntax_pos;
57 extern crate rustc_plugin;
59 use syntax::parse::token;
60 use syntax::tokenstream::TokenTree;
61 use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};
62 use syntax::ext::build::AstBuilder; // A trait for expr_usize.
64 use rustc_plugin::Registry;
66 fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
67 -> Box<MacResult + 'static> {
69 static NUMERALS: &'static [(&'static str, usize)] = &[
70 ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),
71 ("C", 100), ("XC", 90), ("L", 50), ("XL", 40),
72 ("X", 10), ("IX", 9), ("V", 5), ("IV", 4),
78 &format!("argument should be a single identifier, but got {} arguments", args.len()));
79 return DummyResult::any(sp);
82 let text = match args[0] {
83 TokenTree::Token(_, token::Ident(s)) => s.to_string(),
85 cx.span_err(sp, "argument should be a single identifier");
86 return DummyResult::any(sp);
90 let mut text = &*text;
92 while !text.is_empty() {
93 match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
96 text = &text[rn.len()..];
99 cx.span_err(sp, "invalid Roman numeral");
100 return DummyResult::any(sp);
105 MacEager::expr(cx.expr_usize(sp, total))
109 pub fn plugin_registrar(reg: &mut Registry) {
110 reg.register_macro("rn", expand_rn);
114 Then we can use `rn!()` like any other macro:
118 #![plugin(roman_numerals)]
121 assert_eq!(rn!(MMXV), 2015);
125 The advantages over a simple `fn(&str) -> u32` are:
127 * The (arbitrarily complex) conversion is done at compile time.
128 * Input validation is also performed at compile time.
129 * It can be extended to allow use in patterns, which effectively gives
130 a way to define new literal syntax for any data type.
132 In addition to procedural macros, you can define new
133 [`derive`](../reference/attributes/derive.html)-like attributes and other kinds
134 of extensions. See `Registry::register_syntax_extension` and the
135 `SyntaxExtension` enum. For a more involved macro example, see
136 [`regex_macros`](https://github.com/rust-lang/regex/blob/master/regex_macros/src/lib.rs).
141 You can use `syntax::parse` to turn token trees into
142 higher-level syntax elements like expressions:
145 fn expand_foo(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
146 -> Box<MacResult+'static> {
148 let mut parser = cx.new_parser_from_tts(args);
150 let expr: P<Expr> = parser.parse_expr();
153 Looking through [`libsyntax` parser
154 code](https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs)
155 will give you a feel for how the parsing infrastructure works.
157 Keep the `Span`s of everything you parse, for better error reporting. You can
158 wrap `Spanned` around your custom data structures.
160 Calling `ExtCtxt::span_fatal` will immediately abort compilation. It's better to
161 instead call `ExtCtxt::span_err` and return `DummyResult` so that the compiler
162 can continue and find further errors.
164 To print syntax fragments for debugging, you can use `span_note` together with
165 `syntax::print::pprust::*_to_string`.
167 The example above produced an integer literal using `AstBuilder::expr_usize`.
168 As an alternative to the `AstBuilder` trait, `libsyntax` provides a set of
169 quasiquote macros. They are undocumented and very rough around the edges.
170 However, the implementation may be a good starting point for an improved
171 quasiquote as an ordinary plugin library.
176 Plugins can extend [Rust's lint
177 infrastructure](../reference/attributes/diagnostics.html#lint-check-attributes) with
178 additional checks for code style, safety, etc. Now let's write a plugin
179 [`lint_plugin_test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui-fulldeps/auxiliary/lint_plugin_test.rs)
180 that warns about any item named `lintme`.
183 #![feature(plugin_registrar)]
184 #![feature(box_syntax, rustc_private)]
188 // Load rustc as a plugin to get macros
191 extern crate rustc_plugin;
193 use rustc::lint::{EarlyContext, LintContext, LintPass, EarlyLintPass,
194 EarlyLintPassObject, LintArray};
195 use rustc_plugin::Registry;
198 declare_lint!(TEST_LINT, Warn, "Warn about items named 'lintme'");
202 impl LintPass for Pass {
203 fn get_lints(&self) -> LintArray {
204 lint_array!(TEST_LINT)
208 impl EarlyLintPass for Pass {
209 fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {
210 if it.ident.as_str() == "lintme" {
211 cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
217 pub fn plugin_registrar(reg: &mut Registry) {
218 reg.register_early_lint_pass(box Pass as EarlyLintPassObject);
225 #![plugin(lint_plugin_test)]
230 will produce a compiler warning:
233 foo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default
234 foo.rs:4 fn lintme() { }
238 The components of a lint plugin are:
240 * one or more `declare_lint!` invocations, which define static `Lint` structs;
242 * a struct holding any state needed by the lint pass (here, none);
245 implementation defining how to check each syntax element. A single
246 `LintPass` may call `span_lint` for several different `Lint`s, but should
247 register them all through the `get_lints` method.
249 Lint passes are syntax traversals, but they run at a late stage of compilation
250 where type information is available. `rustc`'s [built-in
251 lints](https://github.com/rust-lang/rust/blob/master/src/librustc/lint/builtin.rs)
252 mostly use the same infrastructure as lint plugins, and provide examples of how
253 to access type information.
255 Lints defined by plugins are controlled by the usual [attributes and compiler
256 flags](../reference/attributes/diagnostics.html#lint-check-attributes), e.g.
257 `#[allow(test_lint)]` or `-A test-lint`. These identifiers are derived from the
258 first argument to `declare_lint!`, with appropriate case and punctuation
261 You can run `rustc -W help foo.rs` to see a list of lints known to `rustc`,
262 including those provided by plugins loaded by `foo.rs`.