rustdoc/formats/renderer.rs
1use rustc_data_structures::profiling::SelfProfilerRef;
2use rustc_middle::ty::TyCtxt;
3
4use crate::clean;
5use crate::config::RenderOptions;
6use crate::error::Error;
7use crate::formats::cache::Cache;
8
9/// Allows for different backends to rustdoc to be used with the `run_format()` function. Each
10/// backend renderer has hooks for initialization, documenting an item, entering and exiting a
11/// module, and cleanup/finalizing output.
12pub(crate) trait FormatRenderer<'tcx>: Sized {
13 /// Gives a description of the renderer. Used for performance profiling.
14 fn descr() -> &'static str;
15
16 /// Whether to call `item` recursively for modules
17 ///
18 /// This is true for html, and false for json. See #80664
19 const RUN_ON_MODULE: bool;
20
21 /// This associated type is the type where the current module information is stored.
22 ///
23 /// For each module, we go through their items by calling for each item:
24 ///
25 /// 1. `save_module_data`
26 /// 2. `item`
27 /// 3. `restore_module_data`
28 ///
29 /// This is because the `item` method might update information in `self` (for example if the child
30 /// is a module). To prevent it from impacting the other children of the current module, we need to
31 /// reset the information between each call to `item` by using `restore_module_data`.
32 type ModuleData;
33
34 /// Sets up any state required for the renderer. When this is called the cache has already been
35 /// populated.
36 fn init(
37 krate: clean::Crate,
38 options: RenderOptions,
39 cache: Cache,
40 tcx: TyCtxt<'tcx>,
41 ) -> Result<(Self, clean::Crate), Error>;
42
43 /// This method is called right before call [`Self::item`]. This method returns a type
44 /// containing information that needs to be reset after the [`Self::item`] method has been
45 /// called with the [`Self::restore_module_data`] method.
46 ///
47 /// In short it goes like this:
48 ///
49 /// ```ignore (not valid code)
50 /// let reset_data = renderer.save_module_data();
51 /// renderer.item(item)?;
52 /// renderer.restore_module_data(reset_data);
53 /// ```
54 fn save_module_data(&mut self) -> Self::ModuleData;
55 /// Used to reset current module's information.
56 fn restore_module_data(&mut self, info: Self::ModuleData);
57
58 /// Renders a single non-module item. This means no recursive sub-item rendering is required.
59 fn item(&mut self, item: &clean::Item) -> Result<(), Error>;
60
61 /// Renders a module (should not handle recursing into children).
62 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error>;
63
64 /// Runs after recursively rendering all sub-items of a module.
65 fn mod_item_out(&mut self) -> Result<(), Error> {
66 Ok(())
67 }
68
69 /// Post processing hook for cleanup and dumping output to files.
70 fn after_krate(self) -> Result<(), Error>;
71}
72
73fn run_format_inner<'tcx, T: FormatRenderer<'tcx>>(
74 cx: &mut T,
75 item: &clean::Item,
76 prof: &SelfProfilerRef,
77) -> Result<(), Error> {
78 if item.is_mod() && T::RUN_ON_MODULE {
79 // modules are special because they add a namespace. We also need to
80 // recurse into the items of the module as well.
81 let _timer =
82 prof.generic_activity_with_arg("render_mod_item", item.name.unwrap().to_string());
83
84 cx.mod_item_in(&item)?;
85 let (clean::StrippedItem(box clean::ModuleItem(ref module))
86 | clean::ModuleItem(ref module)) = item.inner.kind
87 else {
88 unreachable!()
89 };
90 for it in module.items.iter() {
91 let info = cx.save_module_data();
92 run_format_inner(cx, it, prof)?;
93 cx.restore_module_data(info);
94 }
95
96 cx.mod_item_out()?;
97 // FIXME: checking `item.name.is_some()` is very implicit and leads to lots of special
98 // cases. Use an explicit match instead.
99 } else if let Some(item_name) = item.name
100 && !item.is_extern_crate()
101 {
102 prof.generic_activity_with_arg("render_item", item_name.as_str()).run(|| cx.item(&item))?;
103 }
104 Ok(())
105}
106
107/// Main method for rendering a crate.
108pub(crate) fn run_format<'tcx, T: FormatRenderer<'tcx>>(
109 krate: clean::Crate,
110 options: RenderOptions,
111 cache: Cache,
112 tcx: TyCtxt<'tcx>,
113) -> Result<(), Error> {
114 let prof = &tcx.sess.prof;
115
116 let emit_crate = options.should_emit_crate();
117 let (mut format_renderer, krate) = prof
118 .verbose_generic_activity_with_arg("create_renderer", T::descr())
119 .run(|| T::init(krate, options, cache, tcx))?;
120
121 if !emit_crate {
122 return Ok(());
123 }
124
125 // Render the crate documentation
126 run_format_inner(&mut format_renderer, &krate.module, prof)?;
127
128 prof.verbose_generic_activity_with_arg("renderer_after_krate", T::descr())
129 .run(|| format_renderer.after_krate())
130}