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 /// This method is called right before call [`Self::item`]. This method returns a type
35 /// containing information that needs to be reset after the [`Self::item`] method has been
36 /// called with the [`Self::restore_module_data`] method.
37 ///
38 /// In short it goes like this:
39 ///
40 /// ```ignore (not valid code)
41 /// let reset_data = renderer.save_module_data();
42 /// renderer.item(item)?;
43 /// renderer.restore_module_data(reset_data);
44 /// ```
45 fn save_module_data(&mut self) -> Self::ModuleData;
46 /// Used to reset current module's information.
47 fn restore_module_data(&mut self, info: Self::ModuleData);
48
49 /// Renders a single non-module item. This means no recursive sub-item rendering is required.
50 fn item(&mut self, item: &clean::Item) -> Result<(), Error>;
51
52 /// Renders a module (should not handle recursing into children).
53 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error>;
54
55 /// Runs after recursively rendering all sub-items of a module.
56 fn mod_item_out(&mut self) -> Result<(), Error> {
57 Ok(())
58 }
59
60 /// Post processing hook for cleanup and dumping output to files.
61 fn after_krate(self) -> Result<(), Error>;
62}
63
64fn run_format_inner<'tcx, T: FormatRenderer<'tcx>>(
65 cx: &mut T,
66 item: &clean::Item,
67 prof: &SelfProfilerRef,
68) -> Result<(), Error> {
69 if item.is_mod() && T::RUN_ON_MODULE {
70 // modules are special because they add a namespace. We also need to
71 // recurse into the items of the module as well.
72 let _timer =
73 prof.generic_activity_with_arg("render_mod_item", item.name.unwrap().to_string());
74
75 cx.mod_item_in(item)?;
76 let (clean::StrippedItem(box clean::ModuleItem(ref module))
77 | clean::ModuleItem(ref module)) = item.inner.kind
78 else {
79 unreachable!()
80 };
81 for it in module.items.iter() {
82 let info = cx.save_module_data();
83 run_format_inner(cx, it, prof)?;
84 cx.restore_module_data(info);
85 }
86
87 cx.mod_item_out()?;
88 // FIXME: checking `item.name.is_some()` is very implicit and leads to lots of special
89 // cases. Use an explicit match instead.
90 } else if let Some(item_name) = item.name
91 && !item.is_extern_crate()
92 {
93 prof.generic_activity_with_arg("render_item", item_name.as_str()).run(|| cx.item(item))?;
94 }
95 Ok(())
96}
97
98/// Main method for rendering a crate.
99pub(crate) fn run_format<
100 'tcx,
101 T: FormatRenderer<'tcx>,
102 F: FnOnce(clean::Crate, RenderOptions, Cache, TyCtxt<'tcx>) -> Result<(T, clean::Crate), Error>,
103>(
104 krate: clean::Crate,
105 options: RenderOptions,
106 cache: Cache,
107 tcx: TyCtxt<'tcx>,
108 init: F,
109) -> Result<(), Error> {
110 let prof = &tcx.sess.prof;
111
112 let emit_crate = options.should_emit_crate();
113 let (mut format_renderer, krate) = prof
114 .verbose_generic_activity_with_arg("create_renderer", T::descr())
115 .run(|| init(krate, options, cache, tcx))?;
116
117 if !emit_crate {
118 return Ok(());
119 }
120
121 // Render the crate documentation
122 run_format_inner(&mut format_renderer, &krate.module, prof)?;
123
124 prof.verbose_generic_activity_with_arg("renderer_after_krate", T::descr())
125 .run(|| format_renderer.after_krate())
126}