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