rustdoc/html/render/
context.rs

1use std::cell::RefCell;
2use std::collections::BTreeMap;
3use std::fmt::{self, Write as _};
4use std::io;
5use std::path::{Path, PathBuf};
6use std::sync::mpsc::{Receiver, channel};
7
8use rinja::Template;
9use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
10use rustc_hir::def_id::{DefIdMap, LOCAL_CRATE};
11use rustc_middle::ty::TyCtxt;
12use rustc_session::Session;
13use rustc_span::edition::Edition;
14use rustc_span::{FileName, Symbol, sym};
15use tracing::info;
16
17use super::print_item::{full_path, item_path, print_item};
18use super::sidebar::{ModuleLike, Sidebar, print_sidebar, sidebar_module_like};
19use super::{AllTypes, LinkFromSrc, StylePath, collect_spans_and_sources, scrape_examples_help};
20use crate::clean::types::ExternalLocation;
21use crate::clean::utils::has_doc_flag;
22use crate::clean::{self, ExternalCrate};
23use crate::config::{ModuleSorting, RenderOptions, ShouldMerge};
24use crate::docfs::{DocFS, PathError};
25use crate::error::Error;
26use crate::formats::FormatRenderer;
27use crate::formats::cache::Cache;
28use crate::formats::item_type::ItemType;
29use crate::html::escape::Escape;
30use crate::html::format::join_with_double_colon;
31use crate::html::layout::{self, BufDisplay};
32use crate::html::markdown::{self, ErrorCodes, IdMap, plain_text_summary};
33use crate::html::render::write_shared::write_shared;
34use crate::html::url_parts_builder::UrlPartsBuilder;
35use crate::html::{sources, static_files};
36use crate::scrape_examples::AllCallLocations;
37use crate::{DOC_RUST_LANG_ORG_VERSION, try_err};
38
39/// Major driving force in all rustdoc rendering. This contains information
40/// about where in the tree-like hierarchy rendering is occurring and controls
41/// how the current page is being rendered.
42///
43/// It is intended that this context is a lightweight object which can be fairly
44/// easily cloned because it is cloned per work-job (about once per item in the
45/// rustdoc tree).
46pub(crate) struct Context<'tcx> {
47    /// Current hierarchy of components leading down to what's currently being
48    /// rendered
49    pub(crate) current: Vec<Symbol>,
50    /// The current destination folder of where HTML artifacts should be placed.
51    /// This changes as the context descends into the module hierarchy.
52    pub(crate) dst: PathBuf,
53    /// Tracks section IDs for `Deref` targets so they match in both the main
54    /// body and the sidebar.
55    pub(super) deref_id_map: RefCell<DefIdMap<String>>,
56    /// The map used to ensure all generated 'id=' attributes are unique.
57    pub(super) id_map: RefCell<IdMap>,
58    /// Shared mutable state.
59    ///
60    /// Issue for improving the situation: [#82381][]
61    ///
62    /// [#82381]: https://github.com/rust-lang/rust/issues/82381
63    pub(crate) shared: SharedContext<'tcx>,
64    /// Collection of all types with notable traits referenced in the current module.
65    pub(crate) types_with_notable_traits: RefCell<FxIndexSet<clean::Type>>,
66    /// Contains information that needs to be saved and reset after rendering an item which is
67    /// not a module.
68    pub(crate) info: ContextInfo,
69}
70
71/// This struct contains the information that needs to be reset between each
72/// [`FormatRenderer::item`] call.
73///
74/// When we enter a new module, we set these values for the whole module but they might be updated
75/// in each child item (especially if it's a module). So to prevent these changes to impact other
76/// items rendering in the same module, we need to reset them to the module's set values.
77#[derive(Clone, Copy)]
78pub(crate) struct ContextInfo {
79    /// A flag, which when `true`, will render pages which redirect to the
80    /// real location of an item. This is used to allow external links to
81    /// publicly reused items to redirect to the right location.
82    pub(super) render_redirect_pages: bool,
83    /// This flag indicates whether source links should be generated or not. If
84    /// the source files are present in the html rendering, then this will be
85    /// `true`.
86    pub(crate) include_sources: bool,
87    /// Field used during rendering, to know if we're inside an inlined item.
88    pub(crate) is_inside_inlined_module: bool,
89}
90
91impl ContextInfo {
92    fn new(include_sources: bool) -> Self {
93        Self { render_redirect_pages: false, include_sources, is_inside_inlined_module: false }
94    }
95}
96
97/// Shared mutable state used in [`Context`] and elsewhere.
98pub(crate) struct SharedContext<'tcx> {
99    pub(crate) tcx: TyCtxt<'tcx>,
100    /// The path to the crate root source minus the file name.
101    /// Used for simplifying paths to the highlighted source code files.
102    pub(crate) src_root: PathBuf,
103    /// This describes the layout of each page, and is not modified after
104    /// creation of the context (contains info like the favicon and added html).
105    pub(crate) layout: layout::Layout,
106    /// The local file sources we've emitted and their respective url-paths.
107    pub(crate) local_sources: FxIndexMap<PathBuf, String>,
108    /// Show the memory layout of types in the docs.
109    pub(super) show_type_layout: bool,
110    /// The base-URL of the issue tracker for when an item has been tagged with
111    /// an issue number.
112    pub(super) issue_tracker_base_url: Option<String>,
113    /// The directories that have already been created in this doc run. Used to reduce the number
114    /// of spurious `create_dir_all` calls.
115    created_dirs: RefCell<FxHashSet<PathBuf>>,
116    /// This flag indicates whether listings of modules (in the side bar and documentation itself)
117    /// should be ordered alphabetically or in order of appearance (in the source code).
118    pub(super) module_sorting: ModuleSorting,
119    /// Additional CSS files to be added to the generated docs.
120    pub(crate) style_files: Vec<StylePath>,
121    /// Suffix to add on resource files (if suffix is "-v2" then "search-index.js" becomes
122    /// "search-index-v2.js").
123    pub(crate) resource_suffix: String,
124    /// Optional path string to be used to load static files on output pages. If not set, uses
125    /// combinations of `../` to reach the documentation root.
126    pub(crate) static_root_path: Option<String>,
127    /// The fs handle we are working with.
128    pub(crate) fs: DocFS,
129    pub(super) codes: ErrorCodes,
130    pub(super) playground: Option<markdown::Playground>,
131    all: RefCell<AllTypes>,
132    /// Storage for the errors produced while generating documentation so they
133    /// can be printed together at the end.
134    errors: Receiver<String>,
135    /// `None` by default, depends on the `generate-redirect-map` option flag. If this field is set
136    /// to `Some(...)`, it'll store redirections and then generate a JSON file at the top level of
137    /// the crate.
138    redirections: Option<RefCell<FxHashMap<String, String>>>,
139
140    /// Correspondence map used to link types used in the source code pages to allow to click on
141    /// links to jump to the type's definition.
142    pub(crate) span_correspondence_map: FxHashMap<rustc_span::Span, LinkFromSrc>,
143    /// The [`Cache`] used during rendering.
144    pub(crate) cache: Cache,
145    pub(crate) call_locations: AllCallLocations,
146    /// Controls whether we read / write to cci files in the doc root. Defaults read=true,
147    /// write=true
148    should_merge: ShouldMerge,
149}
150
151impl SharedContext<'_> {
152    pub(crate) fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
153        let mut dirs = self.created_dirs.borrow_mut();
154        if !dirs.contains(dst) {
155            try_err!(self.fs.create_dir_all(dst), dst);
156            dirs.insert(dst.to_path_buf());
157        }
158
159        Ok(())
160    }
161
162    pub(crate) fn edition(&self) -> Edition {
163        self.tcx.sess.edition()
164    }
165}
166
167impl<'tcx> Context<'tcx> {
168    pub(crate) fn tcx(&self) -> TyCtxt<'tcx> {
169        self.shared.tcx
170    }
171
172    pub(crate) fn cache(&self) -> &Cache {
173        &self.shared.cache
174    }
175
176    pub(super) fn sess(&self) -> &'tcx Session {
177        self.shared.tcx.sess
178    }
179
180    pub(super) fn derive_id<S: AsRef<str> + ToString>(&self, id: S) -> String {
181        self.id_map.borrow_mut().derive(id)
182    }
183
184    /// String representation of how to get back to the root path of the 'doc/'
185    /// folder in terms of a relative URL.
186    pub(super) fn root_path(&self) -> String {
187        "../".repeat(self.current.len())
188    }
189
190    fn render_item(&mut self, it: &clean::Item, is_module: bool) -> String {
191        let mut render_redirect_pages = self.info.render_redirect_pages;
192        // If the item is stripped but inlined, links won't point to the item so no need to generate
193        // a file for it.
194        if it.is_stripped()
195            && let Some(def_id) = it.def_id()
196            && def_id.is_local()
197        {
198            if self.info.is_inside_inlined_module
199                || self.shared.cache.inlined_items.contains(&def_id)
200            {
201                // For now we're forced to generate a redirect page for stripped items until
202                // `record_extern_fqn` correctly points to external items.
203                render_redirect_pages = true;
204            }
205        }
206        let mut title = String::new();
207        if !is_module {
208            title.push_str(it.name.unwrap().as_str());
209        }
210        if !it.is_primitive() && !it.is_keyword() {
211            if !is_module {
212                title.push_str(" in ");
213            }
214            // No need to include the namespace for primitive types and keywords
215            title.push_str(&join_with_double_colon(&self.current));
216        };
217        title.push_str(" - Rust");
218        let tyname = it.type_();
219        let desc = plain_text_summary(&it.doc_value(), &it.link_names(self.cache()));
220        let desc = if !desc.is_empty() {
221            desc
222        } else if it.is_crate() {
223            format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
224        } else {
225            format!(
226                "API documentation for the Rust `{name}` {tyname} in crate `{krate}`.",
227                name = it.name.as_ref().unwrap(),
228                krate = self.shared.layout.krate,
229            )
230        };
231        let name;
232        let tyname_s = if it.is_crate() {
233            name = format!("{tyname} crate");
234            name.as_str()
235        } else {
236            tyname.as_str()
237        };
238
239        if !render_redirect_pages {
240            let mut page_buffer = String::new();
241            print_item(self, it, &mut page_buffer);
242            let page = layout::Page {
243                css_class: tyname_s,
244                root_path: &self.root_path(),
245                static_root_path: self.shared.static_root_path.as_deref(),
246                title: &title,
247                description: &desc,
248                resource_suffix: &self.shared.resource_suffix,
249                rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), sym::rust_logo),
250            };
251            layout::render(
252                &self.shared.layout,
253                &page,
254                BufDisplay(|buf: &mut String| {
255                    print_sidebar(self, it, buf);
256                }),
257                page_buffer,
258                &self.shared.style_files,
259            )
260        } else {
261            if let Some(&(ref names, ty)) = self.cache().paths.get(&it.item_id.expect_def_id()) {
262                if self.current.len() + 1 != names.len()
263                    || self.current.iter().zip(names.iter()).any(|(a, b)| a != b)
264                {
265                    // We checked that the redirection isn't pointing to the current file,
266                    // preventing an infinite redirection loop in the generated
267                    // documentation.
268
269                    let path = fmt::from_fn(|f| {
270                        for name in &names[..names.len() - 1] {
271                            write!(f, "{name}/")?;
272                        }
273                        write!(f, "{}", item_path(ty, names.last().unwrap().as_str()))
274                    });
275                    match self.shared.redirections {
276                        Some(ref redirections) => {
277                            let mut current_path = String::new();
278                            for name in &self.current {
279                                current_path.push_str(name.as_str());
280                                current_path.push('/');
281                            }
282                            let _ = write!(
283                                current_path,
284                                "{}",
285                                item_path(ty, names.last().unwrap().as_str())
286                            );
287                            redirections.borrow_mut().insert(current_path, path.to_string());
288                        }
289                        None => {
290                            return layout::redirect(&format!(
291                                "{root}{path}",
292                                root = self.root_path()
293                            ));
294                        }
295                    }
296                }
297            }
298            String::new()
299        }
300    }
301
302    /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
303    fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<String>> {
304        // BTreeMap instead of HashMap to get a sorted output
305        let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
306        let mut inserted: FxHashMap<ItemType, FxHashSet<Symbol>> = FxHashMap::default();
307
308        for item in &m.items {
309            if item.is_stripped() {
310                continue;
311            }
312
313            let short = item.type_();
314            let myname = match item.name {
315                None => continue,
316                Some(s) => s,
317            };
318            if inserted.entry(short).or_default().insert(myname) {
319                let short = short.to_string();
320                let myname = myname.to_string();
321                map.entry(short).or_default().push(myname);
322            }
323        }
324
325        match self.shared.module_sorting {
326            ModuleSorting::Alphabetical => {
327                for items in map.values_mut() {
328                    items.sort();
329                }
330            }
331            ModuleSorting::DeclarationOrder => {}
332        }
333        map
334    }
335
336    /// Generates a url appropriate for an `href` attribute back to the source of
337    /// this item.
338    ///
339    /// The url generated, when clicked, will redirect the browser back to the
340    /// original source code.
341    ///
342    /// If `None` is returned, then a source link couldn't be generated. This
343    /// may happen, for example, with externally inlined items where the source
344    /// of their crate documentation isn't known.
345    pub(super) fn src_href(&self, item: &clean::Item) -> Option<String> {
346        self.href_from_span(item.span(self.tcx())?, true)
347    }
348
349    pub(crate) fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> {
350        let mut root = self.root_path();
351        let mut path: String;
352        let cnum = span.cnum(self.sess());
353
354        // We can safely ignore synthetic `SourceFile`s.
355        let file = match span.filename(self.sess()) {
356            FileName::Real(ref path) => path.local_path_if_available().to_path_buf(),
357            _ => return None,
358        };
359        let file = &file;
360
361        let krate_sym;
362        let (krate, path) = if cnum == LOCAL_CRATE {
363            if let Some(path) = self.shared.local_sources.get(file) {
364                (self.shared.layout.krate.as_str(), path)
365            } else {
366                return None;
367            }
368        } else {
369            let (krate, src_root) = match *self.cache().extern_locations.get(&cnum)? {
370                ExternalLocation::Local => {
371                    let e = ExternalCrate { crate_num: cnum };
372                    (e.name(self.tcx()), e.src_root(self.tcx()))
373                }
374                ExternalLocation::Remote(ref s) => {
375                    root = s.to_string();
376                    let e = ExternalCrate { crate_num: cnum };
377                    (e.name(self.tcx()), e.src_root(self.tcx()))
378                }
379                ExternalLocation::Unknown => return None,
380            };
381
382            let href = RefCell::new(PathBuf::new());
383            sources::clean_path(
384                &src_root,
385                file,
386                |component| {
387                    href.borrow_mut().push(component);
388                },
389                || {
390                    href.borrow_mut().pop();
391                },
392            );
393
394            path = href.into_inner().to_string_lossy().into_owned();
395
396            if let Some(c) = path.as_bytes().last()
397                && *c != b'/'
398            {
399                path.push('/');
400            }
401
402            let mut fname = file.file_name().expect("source has no filename").to_os_string();
403            fname.push(".html");
404            path.push_str(&fname.to_string_lossy());
405            krate_sym = krate;
406            (krate_sym.as_str(), &path)
407        };
408
409        let anchor = if with_lines {
410            let loline = span.lo(self.sess()).line;
411            let hiline = span.hi(self.sess()).line;
412            format!(
413                "#{}",
414                if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
415            )
416        } else {
417            "".to_string()
418        };
419        Some(format!(
420            "{root}src/{krate}/{path}{anchor}",
421            root = Escape(&root),
422            krate = krate,
423            path = path,
424            anchor = anchor
425        ))
426    }
427
428    pub(crate) fn href_from_span_relative(
429        &self,
430        span: clean::Span,
431        relative_to: &str,
432    ) -> Option<String> {
433        self.href_from_span(span, false).map(|s| {
434            let mut url = UrlPartsBuilder::new();
435            let mut dest_href_parts = s.split('/');
436            let mut cur_href_parts = relative_to.split('/');
437            for (cur_href_part, dest_href_part) in (&mut cur_href_parts).zip(&mut dest_href_parts) {
438                if cur_href_part != dest_href_part {
439                    url.push(dest_href_part);
440                    break;
441                }
442            }
443            for dest_href_part in dest_href_parts {
444                url.push(dest_href_part);
445            }
446            let loline = span.lo(self.sess()).line;
447            let hiline = span.hi(self.sess()).line;
448            format!(
449                "{}{}#{}",
450                "../".repeat(cur_href_parts.count()),
451                url.finish(),
452                if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
453            )
454        })
455    }
456}
457
458/// Generates the documentation for `crate` into the directory `dst`
459impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
460    fn descr() -> &'static str {
461        "html"
462    }
463
464    const RUN_ON_MODULE: bool = true;
465    type ModuleData = ContextInfo;
466
467    fn init(
468        krate: clean::Crate,
469        options: RenderOptions,
470        cache: Cache,
471        tcx: TyCtxt<'tcx>,
472    ) -> Result<(Self, clean::Crate), Error> {
473        // need to save a copy of the options for rendering the index page
474        let md_opts = options.clone();
475        let emit_crate = options.should_emit_crate();
476        let RenderOptions {
477            output,
478            external_html,
479            id_map,
480            playground_url,
481            module_sorting,
482            themes: style_files,
483            default_settings,
484            extension_css,
485            resource_suffix,
486            static_root_path,
487            generate_redirect_map,
488            show_type_layout,
489            generate_link_to_definition,
490            call_locations,
491            no_emit_shared,
492            html_no_source,
493            ..
494        } = options;
495
496        let src_root = match krate.src(tcx) {
497            FileName::Real(ref p) => match p.local_path_if_available().parent() {
498                Some(p) => p.to_path_buf(),
499                None => PathBuf::new(),
500            },
501            _ => PathBuf::new(),
502        };
503        // If user passed in `--playground-url` arg, we fill in crate name here
504        let mut playground = None;
505        if let Some(url) = playground_url {
506            playground = Some(markdown::Playground { crate_name: Some(krate.name(tcx)), url });
507        }
508        let krate_version = cache.crate_version.as_deref().unwrap_or_default();
509        let mut layout = layout::Layout {
510            logo: String::new(),
511            favicon: String::new(),
512            external_html,
513            default_settings,
514            krate: krate.name(tcx).to_string(),
515            krate_version: krate_version.to_string(),
516            css_file_extension: extension_css,
517            scrape_examples_extension: !call_locations.is_empty(),
518        };
519        let mut issue_tracker_base_url = None;
520        let mut include_sources = !html_no_source;
521
522        // Crawl the crate attributes looking for attributes which control how we're
523        // going to emit HTML
524        for attr in krate.module.attrs.lists(sym::doc) {
525            match (attr.name_or_empty(), attr.value_str()) {
526                (sym::html_favicon_url, Some(s)) => {
527                    layout.favicon = s.to_string();
528                }
529                (sym::html_logo_url, Some(s)) => {
530                    layout.logo = s.to_string();
531                }
532                (sym::html_playground_url, Some(s)) => {
533                    playground = Some(markdown::Playground {
534                        crate_name: Some(krate.name(tcx)),
535                        url: s.to_string(),
536                    });
537                }
538                (sym::issue_tracker_base_url, Some(s)) => {
539                    issue_tracker_base_url = Some(s.to_string());
540                }
541                (sym::html_no_source, None) if attr.is_word() => {
542                    include_sources = false;
543                }
544                _ => {}
545            }
546        }
547
548        let (local_sources, matches) = collect_spans_and_sources(
549            tcx,
550            &krate,
551            &src_root,
552            include_sources,
553            generate_link_to_definition,
554        );
555
556        let (sender, receiver) = channel();
557        let scx = SharedContext {
558            tcx,
559            src_root,
560            local_sources,
561            issue_tracker_base_url,
562            layout,
563            created_dirs: Default::default(),
564            module_sorting,
565            style_files,
566            resource_suffix,
567            static_root_path,
568            fs: DocFS::new(sender),
569            codes: ErrorCodes::from(options.unstable_features.is_nightly_build()),
570            playground,
571            all: RefCell::new(AllTypes::new()),
572            errors: receiver,
573            redirections: if generate_redirect_map { Some(Default::default()) } else { None },
574            show_type_layout,
575            span_correspondence_map: matches,
576            cache,
577            call_locations,
578            should_merge: options.should_merge,
579        };
580
581        let dst = output;
582        scx.ensure_dir(&dst)?;
583
584        let mut cx = Context {
585            current: Vec::new(),
586            dst,
587            id_map: RefCell::new(id_map),
588            deref_id_map: Default::default(),
589            shared: scx,
590            types_with_notable_traits: RefCell::new(FxIndexSet::default()),
591            info: ContextInfo::new(include_sources),
592        };
593
594        if emit_crate {
595            sources::render(&mut cx, &krate)?;
596        }
597
598        if !no_emit_shared {
599            write_shared(&mut cx, &krate, &md_opts, tcx)?;
600        }
601
602        Ok((cx, krate))
603    }
604
605    fn save_module_data(&mut self) -> Self::ModuleData {
606        self.deref_id_map.borrow_mut().clear();
607        self.id_map.borrow_mut().clear();
608        self.types_with_notable_traits.borrow_mut().clear();
609        self.info
610    }
611
612    fn restore_module_data(&mut self, info: Self::ModuleData) {
613        self.info = info;
614    }
615
616    fn after_krate(&mut self) -> Result<(), Error> {
617        let crate_name = self.tcx().crate_name(LOCAL_CRATE);
618        let final_file = self.dst.join(crate_name.as_str()).join("all.html");
619        let settings_file = self.dst.join("settings.html");
620        let help_file = self.dst.join("help.html");
621        let scrape_examples_help_file = self.dst.join("scrape-examples-help.html");
622
623        let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
624        if !root_path.ends_with('/') {
625            root_path.push('/');
626        }
627        let shared = &self.shared;
628        let mut page = layout::Page {
629            title: "List of all items in this crate",
630            css_class: "mod sys",
631            root_path: "../",
632            static_root_path: shared.static_root_path.as_deref(),
633            description: "List of all items in this crate",
634            resource_suffix: &shared.resource_suffix,
635            rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), sym::rust_logo),
636        };
637        let all = shared.all.replace(AllTypes::new());
638        let mut sidebar = String::new();
639
640        // all.html is not customizable, so a blank id map is fine
641        let blocks = sidebar_module_like(all.item_sections(), &mut IdMap::new(), ModuleLike::Crate);
642        let bar = Sidebar {
643            title_prefix: "",
644            title: "",
645            is_crate: false,
646            is_mod: false,
647            parent_is_crate: false,
648            blocks: vec![blocks],
649            path: String::new(),
650        };
651
652        bar.render_into(&mut sidebar).unwrap();
653
654        let v = layout::render(
655            &shared.layout,
656            &page,
657            sidebar,
658            BufDisplay(|buf: &mut String| {
659                all.print(buf);
660            }),
661            &shared.style_files,
662        );
663        shared.fs.write(final_file, v)?;
664
665        // if to avoid writing help, settings files to doc root unless we're on the final invocation
666        if shared.should_merge.write_rendered_cci {
667            // Generating settings page.
668            page.title = "Settings";
669            page.description = "Settings of Rustdoc";
670            page.root_path = "./";
671            page.rust_logo = true;
672
673            let sidebar = "<h2 class=\"location\">Settings</h2><div class=\"sidebar-elems\"></div>";
674            let v = layout::render(
675                &shared.layout,
676                &page,
677                sidebar,
678                fmt::from_fn(|buf| {
679                    write!(
680                        buf,
681                        "<div class=\"main-heading\">\
682                         <h1>Rustdoc settings</h1>\
683                         <span class=\"out-of-band\">\
684                             <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
685                                Back\
686                            </a>\
687                         </span>\
688                         </div>\
689                         <noscript>\
690                            <section>\
691                                You need to enable JavaScript be able to update your settings.\
692                            </section>\
693                         </noscript>\
694                         <script defer src=\"{static_root_path}{settings_js}\"></script>",
695                        static_root_path = page.get_static_root_path(),
696                        settings_js = static_files::STATIC_FILES.settings_js,
697                    )?;
698                    // Pre-load all theme CSS files, so that switching feels seamless.
699                    //
700                    // When loading settings.html as a popover, the equivalent HTML is
701                    // generated in main.js.
702                    for file in &shared.style_files {
703                        if let Ok(theme) = file.basename() {
704                            write!(
705                                buf,
706                                "<link rel=\"preload\" href=\"{root_path}{theme}{suffix}.css\" \
707                                    as=\"style\">",
708                                root_path = page.static_root_path.unwrap_or(""),
709                                suffix = page.resource_suffix,
710                            )?;
711                        }
712                    }
713                    Ok(())
714                }),
715                &shared.style_files,
716            );
717            shared.fs.write(settings_file, v)?;
718
719            // Generating help page.
720            page.title = "Help";
721            page.description = "Documentation for Rustdoc";
722            page.root_path = "./";
723            page.rust_logo = true;
724
725            let sidebar = "<h2 class=\"location\">Help</h2><div class=\"sidebar-elems\"></div>";
726            let v = layout::render(
727                &shared.layout,
728                &page,
729                sidebar,
730                format_args!(
731                    "<div class=\"main-heading\">\
732                        <h1>Rustdoc help</h1>\
733                        <span class=\"out-of-band\">\
734                            <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
735                            Back\
736                        </a>\
737                        </span>\
738                        </div>\
739                        <noscript>\
740                        <section>\
741                            <p>You need to enable JavaScript to use keyboard commands or search.</p>\
742                            <p>For more information, browse the <a href=\"{DOC_RUST_LANG_ORG_VERSION}/rustdoc/\">rustdoc handbook</a>.</p>\
743                        </section>\
744                        </noscript>",
745                ),
746                &shared.style_files,
747            );
748            shared.fs.write(help_file, v)?;
749        }
750
751        // if to avoid writing files to doc root unless we're on the final invocation
752        if shared.layout.scrape_examples_extension && shared.should_merge.write_rendered_cci {
753            page.title = "About scraped examples";
754            page.description = "How the scraped examples feature works in Rustdoc";
755            let v = layout::render(
756                &shared.layout,
757                &page,
758                "",
759                scrape_examples_help(shared),
760                &shared.style_files,
761            );
762            shared.fs.write(scrape_examples_help_file, v)?;
763        }
764
765        if let Some(ref redirections) = shared.redirections
766            && !redirections.borrow().is_empty()
767        {
768            let redirect_map_path = self.dst.join(crate_name.as_str()).join("redirect-map.json");
769            let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
770            shared.ensure_dir(&self.dst.join(crate_name.as_str()))?;
771            shared.fs.write(redirect_map_path, paths)?;
772        }
773
774        // Flush pending errors.
775        self.shared.fs.close();
776        let nb_errors = self.shared.errors.iter().map(|err| self.tcx().dcx().err(err)).count();
777        if nb_errors > 0 {
778            Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
779        } else {
780            Ok(())
781        }
782    }
783
784    fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> {
785        // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
786        // if they contain impls for public types. These modules can also
787        // contain items such as publicly re-exported structures.
788        //
789        // External crates will provide links to these structures, so
790        // these modules are recursed into, but not rendered normally
791        // (a flag on the context).
792        if !self.info.render_redirect_pages {
793            self.info.render_redirect_pages = item.is_stripped();
794        }
795        let item_name = item.name.unwrap();
796        self.dst.push(item_name.as_str());
797        self.current.push(item_name);
798
799        info!("Recursing into {}", self.dst.display());
800
801        if !item.is_stripped() {
802            let buf = self.render_item(item, true);
803            // buf will be empty if the module is stripped and there is no redirect for it
804            if !buf.is_empty() {
805                self.shared.ensure_dir(&self.dst)?;
806                let joint_dst = self.dst.join("index.html");
807                self.shared.fs.write(joint_dst, buf)?;
808            }
809        }
810        if !self.info.is_inside_inlined_module {
811            if let Some(def_id) = item.def_id()
812                && self.cache().inlined_items.contains(&def_id)
813            {
814                self.info.is_inside_inlined_module = true;
815            }
816        } else if !self.cache().document_hidden && item.is_doc_hidden() {
817            // We're not inside an inlined module anymore since this one cannot be re-exported.
818            self.info.is_inside_inlined_module = false;
819        }
820
821        // Render sidebar-items.js used throughout this module.
822        if !self.info.render_redirect_pages {
823            let (clean::StrippedItem(box clean::ModuleItem(ref module))
824            | clean::ModuleItem(ref module)) = item.kind
825            else {
826                unreachable!()
827            };
828            let items = self.build_sidebar_items(module);
829            let js_dst = self.dst.join(format!("sidebar-items{}.js", self.shared.resource_suffix));
830            let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap());
831            self.shared.fs.write(js_dst, v)?;
832        }
833        Ok(())
834    }
835
836    fn mod_item_out(&mut self) -> Result<(), Error> {
837        info!("Recursed; leaving {}", self.dst.display());
838
839        // Go back to where we were at
840        self.dst.pop();
841        self.current.pop();
842        Ok(())
843    }
844
845    fn item(&mut self, item: clean::Item) -> Result<(), Error> {
846        // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
847        // if they contain impls for public types. These modules can also
848        // contain items such as publicly re-exported structures.
849        //
850        // External crates will provide links to these structures, so
851        // these modules are recursed into, but not rendered normally
852        // (a flag on the context).
853        if !self.info.render_redirect_pages {
854            self.info.render_redirect_pages = item.is_stripped();
855        }
856
857        let buf = self.render_item(&item, false);
858        // buf will be empty if the item is stripped and there is no redirect for it
859        if !buf.is_empty() {
860            let name = item.name.as_ref().unwrap();
861            let item_type = item.type_();
862            let file_name = item_path(item_type, name.as_str()).to_string();
863            self.shared.ensure_dir(&self.dst)?;
864            let joint_dst = self.dst.join(&file_name);
865            self.shared.fs.write(joint_dst, buf)?;
866
867            if !self.info.render_redirect_pages {
868                self.shared.all.borrow_mut().append(full_path(self, &item), &item_type);
869            }
870            // If the item is a macro, redirect from the old macro URL (with !)
871            // to the new one (without).
872            if item_type == ItemType::Macro {
873                let redir_name = format!("{item_type}.{name}!.html");
874                if let Some(ref redirections) = self.shared.redirections {
875                    let crate_name = &self.shared.layout.krate;
876                    redirections.borrow_mut().insert(
877                        format!("{crate_name}/{redir_name}"),
878                        format!("{crate_name}/{file_name}"),
879                    );
880                } else {
881                    let v = layout::redirect(&file_name);
882                    let redir_dst = self.dst.join(redir_name);
883                    self.shared.fs.write(redir_dst, v)?;
884                }
885            }
886        }
887
888        Ok(())
889    }
890
891    fn cache(&self) -> &Cache {
892        &self.shared.cache
893    }
894}