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