]> git.lizzy.rs Git - rust.git/blob - src/doc/guide-plugin.md
rollup merge of #20608: nikomatsakis/assoc-types-method-dispatch
[rust.git] / src / doc / guide-plugin.md
1 % The Rust Compiler Plugins Guide
2
3 <div class="unstable-feature">
4
5 <p>
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
11 time.
12 </p>
13
14 <p>
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>.
17 </p>
18
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
22 information.
23 </p>
24
25 </div>
26
27 # Introduction
28
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.
31
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.
37
38 # Syntax extensions
39
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
44 compile time.
45
46 Let's write a plugin
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.
49
50 ```ignore
51 #![crate_type="dylib"]
52 #![feature(plugin_registrar)]
53
54 extern crate syntax;
55 extern crate rustc;
56
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;
63
64 fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
65         -> Box<MacResult + 'static> {
66
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),
71         ("I",    1)];
72
73     let text = match args {
74         [TtToken(_, token::Ident(s, _))] => token::get_ident(s).to_string(),
75         _ => {
76             cx.span_err(sp, "argument should be a single identifier");
77             return DummyResult::any(sp);
78         }
79     };
80
81     let mut text = text.as_slice();
82     let mut total = 0u;
83     while !text.is_empty() {
84         match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
85             Some(&(rn, val)) => {
86                 total += val;
87                 text = text.slice_from(rn.len());
88             }
89             None => {
90                 cx.span_err(sp, "invalid Roman numeral");
91                 return DummyResult::any(sp);
92             }
93         }
94     }
95
96     MacExpr::new(cx.expr_uint(sp, total))
97 }
98
99 #[plugin_registrar]
100 pub fn plugin_registrar(reg: &mut Registry) {
101     reg.register_macro("rn", expand_rn);
102 }
103 ```
104
105 Then we can use `rn!()` like any other macro:
106
107 ```ignore
108 #![feature(phase)]
109
110 #[phase(plugin)]
111 extern crate roman_numerals;
112
113 fn main() {
114     assert_eq!(rn!(MMXV), 2015);
115 }
116 ```
117
118 The advantages over a simple `fn(&str) -> uint` are:
119
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.
124
125 In addition to procedural macros, you can define new
126 [`deriving`](reference.html#deriving)-like attributes and other kinds of
127 extensions.  See
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.
134
135
136 ## Tips and tricks
137
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.
146
147 You can use [`syntax::parse`](syntax/parse/index.html) to turn token trees into
148 higher-level syntax elements like expressions:
149
150 ```ignore
151 fn expand_foo(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
152         -> Box<MacResult+'static> {
153
154     let mut parser = cx.new_parser_from_tts(args);
155
156     let expr: P<Expr> = parser.parse_expr();
157 ```
158
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.
162
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.
167
168 Calling
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)
172 and return
173 [`DummyResult`](syntax/ext/base/struct.DummyResult.html),
174 so that the compiler can continue and find further errors.
175
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.
182
183
184 # Lint plugins
185
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:
191
192 ```ignore
193 declare_lint!(TEST_LINT, Warn,
194               "Warn about items named 'lintme'")
195
196 struct Pass;
197
198 impl LintPass for Pass {
199     fn get_lints(&self) -> LintArray {
200         lint_array!(TEST_LINT)
201     }
202
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'");
207         }
208     }
209 }
210
211 #[plugin_registrar]
212 pub fn plugin_registrar(reg: &mut Registry) {
213     reg.register_lint_pass(box Pass as LintPassObject);
214 }
215 ```
216
217 Then code like
218
219 ```ignore
220 #[phase(plugin)]
221 extern crate lint_plugin_test;
222
223 fn lintme() { }
224 ```
225
226 will produce a compiler warning:
227
228 ```txt
229 foo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default
230 foo.rs:4 fn lintme() { }
231          ^~~~~~~~~~~~~~~
232 ```
233
234 The components of a lint plugin are:
235
236 * one or more `declare_lint!` invocations, which define static
237   [`Lint`](rustc/lint/struct.Lint.html) structs;
238
239 * a struct holding any state needed by the lint pass (here, none);
240
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.
245
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.
251
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.
256
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`.