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