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