]> git.proxmox.com Git - rustc.git/blame - src/doc/rustc-dev-guide/src/mir/visitor.md
New upstream version 1.44.1+dfsg1
[rustc.git] / src / doc / rustc-dev-guide / src / mir / visitor.md
CommitLineData
a1dfa0c6
XL
1# MIR visitor
2
3The MIR visitor is a convenient tool for traversing the MIR and either
4looking for things or making changes to it. The visitor traits are
5defined in [the `rustc::mir::visit` module][m-v] – there are two of
6them, generated via a single macro: `Visitor` (which operates on a
7`&Mir` and gives back shared references) and `MutVisitor` (which
8operates 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
12To implement a visitor, you have to create a type that represents
13your visitor. Typically, this type wants to "hang on" to whatever
14state you will need while processing MIR:
15
16```rust,ignore
17struct MyVisitor<...> {
dc9dc135 18 tcx: TyCtxt<'tcx>,
a1dfa0c6
XL
19 ...
20}
21```
22
23and you then implement the `Visitor` or `MutVisitor` trait for that type:
24
25```rust,ignore
26impl<'tcx> MutVisitor<'tcx> for NoLandingPads {
27 fn visit_foo(&mut self, ...) {
28 ...
29 self.super_foo(...);
30 }
31}
32```
33
34As shown above, within the impl, you can override any of the
35`visit_foo` methods (e.g., `visit_terminator`) in order to write some
36code that will execute whenever a `foo` is found. If you want to
37recursively walk the contents of the `foo`, you then invoke the
38`super_foo` method. (NB. You never want to override `super_foo`.)
39
40A very simple example of a visitor can be found in [`NoLandingPads`].
41That visitor doesn't even require any state: it just visits all
42terminators 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
48In addition the visitor, [the `rustc::mir::traversal` module][t]
49contains useful functions for walking the MIR CFG in
50[different standard orders][traversal] (e.g. pre-order, reverse
51post-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