[go: up one dir, main page]

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