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