1 % The Rust Compiler Plugins Guide
3 <div class="unstable-feature">
6 <b>Warning:</b> Plugins are an advanced, unstable feature! For many details,
7 the only available documentation is the <a
8 href="syntax/index.html"><code>libsyntax</code></a> and <a
9 href="rustc/index.html"><code>librustc</code></a> API docs, or even the source
10 code itself. These internal compiler APIs are also subject to change at any
15 For defining new syntax it is often much easier to use Rust's <a
16 href="guide-macros.html">built-in macro system</a>.
19 <p style="margin-bottom: 0">
20 The code in this document uses language features not covered in the Rust
21 Guide. See the <a href="reference.html">Reference Manual</a> for more
29 `rustc` can load compiler plugins, which are user-provided libraries that
30 extend the compiler's behavior with new syntax extensions, lint checks, etc.
32 A plugin is a dynamic library crate with a designated "registrar" function that
33 registers extensions with `rustc`. Other crates can use these extensions by
34 loading the plugin crate with `#[phase(plugin)] extern crate`. See the
35 [`rustc::plugin`](rustc/plugin/index.html) documentation for more about the
36 mechanics of defining and loading a plugin.
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](guide-macros.html), but the expansion is performed by arbitrary Rust
43 code that manipulates [syntax trees](syntax/ast/index.html) at
47 [`roman_numerals.rs`](https://github.com/rust-lang/rust/tree/master/src/test/auxiliary/roman_numerals.rs)
48 that implements Roman numeral integer literals.
51 #![crate_type="dylib"]
52 #![feature(plugin_registrar)]
57 use syntax::codemap::Span;
58 use syntax::parse::token;
59 use syntax::ast::{TokenTree, TtToken};
60 use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacExpr};
61 use syntax::ext::build::AstBuilder; // trait for expr_uint
62 use rustc::plugin::Registry;
64 fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
65 -> Box<MacResult + 'static> {
67 static NUMERALS: &'static [(&'static str, uint)] = &[
68 ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),
69 ("C", 100), ("XC", 90), ("L", 50), ("XL", 40),
70 ("X", 10), ("IX", 9), ("V", 5), ("IV", 4),
73 let text = match args {
74 [TtToken(_, token::Ident(s, _))] => token::get_ident(s).to_string(),
76 cx.span_err(sp, "argument should be a single identifier");
77 return DummyResult::any(sp);
81 let mut text = text.as_slice();
83 while !text.is_empty() {
84 match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
87 text = text.slice_from(rn.len());
90 cx.span_err(sp, "invalid Roman numeral");
91 return DummyResult::any(sp);
96 MacExpr::new(cx.expr_uint(sp, total))
100 pub fn plugin_registrar(reg: &mut Registry) {
101 reg.register_macro("rn", expand_rn);
105 Then we can use `rn!()` like any other macro:
111 extern crate roman_numerals;
114 assert_eq!(rn!(MMXV), 2015);
118 The advantages over a simple `fn(&str) -> uint` are:
120 * The (arbitrarily complex) conversion is done at compile time.
121 * Input validation is also performed at compile time.
122 * It can be extended to allow use in patterns, which effectively gives
123 a way to define new literal syntax for any data type.
125 In addition to procedural macros, you can define new
126 [`deriving`](reference.html#deriving)-like attributes and other kinds of
128 [`Registry::register_syntax_extension`](rustc/plugin/registry/struct.Registry.html#method.register_syntax_extension)
129 and the [`SyntaxExtension`
130 enum](http://doc.rust-lang.org/syntax/ext/base/enum.SyntaxExtension.html). For
131 a more involved macro example, see
132 [`src/libregex_macros/lib.rs`](https://github.com/rust-lang/rust/blob/master/src/libregex_macros/lib.rs)
133 in the Rust distribution.
138 To see the results of expanding syntax extensions, run
139 `rustc --pretty expanded`. The output represents a whole crate, so you
140 can also feed it back in to `rustc`, which will sometimes produce better
141 error messages than the original compilation. Note that the
142 `--pretty expanded` output may have a different meaning if multiple
143 variables of the same name (but different syntax contexts) are in play
144 in the same scope. In this case `--pretty expanded,hygiene` will tell
145 you about the syntax contexts.
147 You can use [`syntax::parse`](syntax/parse/index.html) to turn token trees into
148 higher-level syntax elements like expressions:
151 fn expand_foo(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
152 -> Box<MacResult+'static> {
154 let mut parser = cx.new_parser_from_tts(args);
156 let expr: P<Expr> = parser.parse_expr();
159 Looking through [`libsyntax` parser
160 code](https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs)
161 will give you a feel for how the parsing infrastructure works.
163 Keep the [`Span`s](syntax/codemap/struct.Span.html) of
164 everything you parse, for better error reporting. You can wrap
165 [`Spanned`](syntax/codemap/struct.Spanned.html) around
166 your custom data structures.
169 [`ExtCtxt::span_fatal`](syntax/ext/base/struct.ExtCtxt.html#method.span_fatal)
170 will immediately abort compilation. It's better to instead call
171 [`ExtCtxt::span_err`](syntax/ext/base/struct.ExtCtxt.html#method.span_err)
173 [`DummyResult`](syntax/ext/base/struct.DummyResult.html),
174 so that the compiler can continue and find further errors.
176 The example above produced an integer literal using
177 [`AstBuilder::expr_uint`](syntax/ext/build/trait.AstBuilder.html#tymethod.expr_uint).
178 As an alternative to the `AstBuilder` trait, `libsyntax` provides a set of
179 [quasiquote macros](syntax/ext/quote/index.html). They are undocumented and
180 very rough around the edges. However, the implementation may be a good
181 starting point for an improved quasiquote as an ordinary plugin library.
186 Plugins can extend [Rust's lint
187 infrastructure](reference.html#lint-check-attributes) with additional checks for
188 code style, safety, etc. You can see
189 [`src/test/auxiliary/lint_plugin_test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/auxiliary/lint_plugin_test.rs)
190 for a full example, the core of which is reproduced here:
193 declare_lint!(TEST_LINT, Warn,
194 "Warn about items named 'lintme'")
198 impl LintPass for Pass {
199 fn get_lints(&self) -> LintArray {
200 lint_array!(TEST_LINT)
203 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
204 let name = token::get_ident(it.ident);
205 if name.get() == "lintme" {
206 cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
212 pub fn plugin_registrar(reg: &mut Registry) {
213 reg.register_lint_pass(box Pass as LintPassObject);
221 extern crate lint_plugin_test;
226 will produce a compiler warning:
229 foo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default
230 foo.rs:4 fn lintme() { }
234 The components of a lint plugin are:
236 * one or more `declare_lint!` invocations, which define static
237 [`Lint`](rustc/lint/struct.Lint.html) structs;
239 * a struct holding any state needed by the lint pass (here, none);
241 * a [`LintPass`](rustc/lint/trait.LintPass.html)
242 implementation defining how to check each syntax element. A single
243 `LintPass` may call `span_lint` for several different `Lint`s, but should
244 register them all through the `get_lints` method.
246 Lint passes are syntax traversals, but they run at a late stage of compilation
247 where type information is available. `rustc`'s [built-in
248 lints](https://github.com/rust-lang/rust/blob/master/src/librustc/lint/builtin.rs)
249 mostly use the same infrastructure as lint plugins, and provide examples of how
250 to access type information.
252 Lints defined by plugins are controlled by the usual [attributes and compiler
253 flags](reference.html#lint-check-attributes), e.g. `#[allow(test_lint)]` or
254 `-A test-lint`. These identifiers are derived from the first argument to
255 `declare_lint!`, with appropriate case and punctuation conversion.
257 You can run `rustc -W help foo.rs` to see a list of lints known to `rustc`,
258 including those provided by plugins loaded by `foo.rs`.