]>
Commit | Line | Data |
---|---|---|
a1dfa0c6 XL |
1 | # MIR visitor |
2 | ||
3 | The MIR visitor is a convenient tool for traversing the MIR and either | |
4 | looking for things or making changes to it. The visitor traits are | |
6a06907d | 5 | defined in [the `rustc_middle::mir::visit` module][m-v] – there are two of |
a1dfa0c6 XL |
6 | them, generated via a single macro: `Visitor` (which operates on a |
7 | `&Mir` and gives back shared references) and `MutVisitor` (which | |
8 | operates on a `&mut Mir` and gives back mutable references). | |
9 | ||
ba9703b0 | 10 | [m-v]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/mir/visit/index.html |
a1dfa0c6 XL |
11 | |
12 | To implement a visitor, you have to create a type that represents | |
13 | your visitor. Typically, this type wants to "hang on" to whatever | |
14 | state you will need while processing MIR: | |
15 | ||
16 | ```rust,ignore | |
17 | struct MyVisitor<...> { | |
dc9dc135 | 18 | tcx: TyCtxt<'tcx>, |
a1dfa0c6 XL |
19 | ... |
20 | } | |
21 | ``` | |
22 | ||
23 | and you then implement the `Visitor` or `MutVisitor` trait for that type: | |
24 | ||
25 | ```rust,ignore | |
26 | impl<'tcx> MutVisitor<'tcx> for NoLandingPads { | |
27 | fn visit_foo(&mut self, ...) { | |
28 | ... | |
29 | self.super_foo(...); | |
30 | } | |
31 | } | |
32 | ``` | |
33 | ||
34 | As shown above, within the impl, you can override any of the | |
35 | `visit_foo` methods (e.g., `visit_terminator`) in order to write some | |
36 | code that will execute whenever a `foo` is found. If you want to | |
37 | recursively walk the contents of the `foo`, you then invoke the | |
38 | `super_foo` method. (NB. You never want to override `super_foo`.) | |
39 | ||
40 | A very simple example of a visitor can be found in [`NoLandingPads`]. | |
41 | That visitor doesn't even require any state: it just visits all | |
42 | terminators and removes their `unwind` successors. | |
43 | ||
44 | [`NoLandingPads`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/transform/no_landing_pads/struct.NoLandingPads.html | |
45 | ||
46 | ## Traversal | |
47 | ||
6a06907d | 48 | In addition the visitor, [the `rustc_middle::mir::traversal` module][t] |
a1dfa0c6 XL |
49 | contains useful functions for walking the MIR CFG in |
50 | [different standard orders][traversal] (e.g. pre-order, reverse | |
51 | post-order, and so forth). | |
52 | ||
ba9703b0 | 53 | [t]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/mir/traversal/index.html |
a1dfa0c6 XL |
54 | [traversal]: https://en.wikipedia.org/wiki/Tree_traversal |
55 |