Skip to main content

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