rustdoc/html/render/
context.rs

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