1use std::cell::RefCell;
2use std::collections::BTreeMap;
3use std::fmt::{self, Write as _};
4use std::io;
5use std::path::{Path, PathBuf};
6use std::sync::mpsc::{Receiver, channel};
7
8use askama::Template;
9use rustc_ast::join_path_syms;
10use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
11use rustc_hir::Attribute;
12use rustc_hir::attrs::AttributeKind;
13use rustc_hir::def_id::{DefIdMap, LOCAL_CRATE};
14use rustc_middle::ty::TyCtxt;
15use rustc_session::Session;
16use rustc_span::edition::Edition;
17use rustc_span::{BytePos, FileName, RemapPathScopeComponents, Symbol};
18use tracing::info;
19
20use super::print_item::{full_path, print_item, print_item_path};
21use super::sidebar::{ModuleLike, Sidebar, print_sidebar, sidebar_module_like};
22use super::{AllTypes, LinkFromSrc, StylePath, collect_spans_and_sources, scrape_examples_help};
23use crate::clean::types::ExternalLocation;
24use crate::clean::utils::has_doc_flag;
25use crate::clean::{self, ExternalCrate};
26use crate::config::{ModuleSorting, RenderOptions, ShouldMerge};
27use crate::docfs::{DocFS, PathError};
28use crate::error::Error;
29use crate::formats::FormatRenderer;
30use crate::formats::cache::Cache;
31use crate::formats::item_type::ItemType;
32use crate::html::escape::Escape;
33use crate::html::macro_expansion::ExpandedCode;
34use crate::html::markdown::{self, ErrorCodes, IdMap, plain_text_summary};
35use crate::html::render::span_map::Span;
36use crate::html::render::write_shared::write_shared;
37use crate::html::url_parts_builder::UrlPartsBuilder;
38use crate::html::{layout, sources, static_files};
39use crate::scrape_examples::AllCallLocations;
40use crate::{DOC_RUST_LANG_ORG_VERSION, try_err};
41
42pub(crate) struct Context<'tcx> {
50 pub(crate) current: Vec<Symbol>,
53 pub(crate) dst: PathBuf,
56 pub(super) deref_id_map: RefCell<DefIdMap<String>>,
59 pub(super) id_map: RefCell<IdMap>,
61 pub(crate) shared: SharedContext<'tcx>,
67 pub(crate) types_with_notable_traits: RefCell<FxIndexSet<clean::Type>>,
69 pub(crate) info: ContextInfo,
72}
73
74#[derive(Clone, Copy)]
81pub(crate) struct ContextInfo {
82 pub(super) render_redirect_pages: bool,
86 pub(crate) include_sources: bool,
90 pub(crate) is_inside_inlined_module: bool,
92}
93
94impl ContextInfo {
95 fn new(include_sources: bool) -> Self {
96 Self { render_redirect_pages: false, include_sources, is_inside_inlined_module: false }
97 }
98}
99
100pub(crate) struct SharedContext<'tcx> {
102 pub(crate) tcx: TyCtxt<'tcx>,
103 pub(crate) src_root: PathBuf,
106 pub(crate) layout: layout::Layout,
109 pub(crate) local_sources: FxIndexMap<PathBuf, String>,
111 pub(super) show_type_layout: bool,
113 pub(super) issue_tracker_base_url: Option<String>,
116 created_dirs: RefCell<FxHashSet<PathBuf>>,
119 pub(super) module_sorting: ModuleSorting,
122 pub(crate) style_files: Vec<StylePath>,
124 pub(crate) resource_suffix: String,
127 pub(crate) static_root_path: Option<String>,
130 pub(crate) fs: DocFS,
132 pub(super) codes: ErrorCodes,
133 pub(super) playground: Option<markdown::Playground>,
134 all: RefCell<AllTypes>,
135 errors: Receiver<String>,
138 redirections: Option<RefCell<FxHashMap<String, String>>>,
142
143 pub(crate) span_correspondence_map: FxHashMap<Span, LinkFromSrc>,
146 pub(crate) expanded_codes: FxHashMap<BytePos, Vec<ExpandedCode>>,
147 pub(crate) cache: Cache,
149 pub(crate) call_locations: AllCallLocations,
150 should_merge: ShouldMerge,
153}
154
155impl SharedContext<'_> {
156 pub(crate) fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
157 let mut dirs = self.created_dirs.borrow_mut();
158 if !dirs.contains(dst) {
159 try_err!(self.fs.create_dir_all(dst), dst);
160 dirs.insert(dst.to_path_buf());
161 }
162
163 Ok(())
164 }
165
166 pub(crate) fn edition(&self) -> Edition {
167 self.tcx.sess.edition()
168 }
169}
170
171impl<'tcx> Context<'tcx> {
172 pub(crate) fn tcx(&self) -> TyCtxt<'tcx> {
173 self.shared.tcx
174 }
175
176 pub(crate) fn cache(&self) -> &Cache {
177 &self.shared.cache
178 }
179
180 pub(super) fn sess(&self) -> &'tcx Session {
181 self.shared.tcx.sess
182 }
183
184 pub(super) fn derive_id<S: AsRef<str> + ToString>(&self, id: S) -> String {
185 self.id_map.borrow_mut().derive(id)
186 }
187
188 pub(super) fn root_path(&self) -> String {
191 "../".repeat(self.current.len())
192 }
193
194 fn render_item(&mut self, it: &clean::Item, is_module: bool) -> String {
195 let mut render_redirect_pages = self.info.render_redirect_pages;
196 if it.is_stripped()
199 && let Some(def_id) = it.def_id()
200 && def_id.is_local()
201 && (self.info.is_inside_inlined_module
202 || self.shared.cache.inlined_items.contains(&def_id))
203 {
204 render_redirect_pages = true;
207 }
208
209 if !render_redirect_pages {
210 let mut title = String::new();
211 if !is_module {
212 title.push_str(it.name.unwrap().as_str());
213 }
214 let short_title;
215 let short_title = if is_module {
216 let module_name = self.current.last().unwrap();
217 short_title = if it.is_crate() {
218 format!("Crate {module_name}")
219 } else {
220 format!("Module {module_name}")
221 };
222 &short_title[..]
223 } else {
224 it.name.as_ref().unwrap().as_str()
225 };
226 if !it.is_fake_item() {
227 if !is_module {
228 title.push_str(" in ");
229 }
230 title.push_str(&join_path_syms(&self.current));
232 };
233 title.push_str(" - Rust");
234 let tyname = it.type_();
235 let desc = plain_text_summary(&it.doc_value(), &it.link_names(self.cache()));
236 let desc = if !desc.is_empty() {
237 desc
238 } else if it.is_crate() {
239 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
240 } else {
241 format!(
242 "API documentation for the Rust `{name}` {tyname} in crate `{krate}`.",
243 name = it.name.as_ref().unwrap(),
244 krate = self.shared.layout.krate,
245 )
246 };
247
248 let name;
249 let tyname_s = if it.is_crate() {
250 name = format!("{tyname} crate");
251 name.as_str()
252 } else {
253 tyname.as_str()
254 };
255
256 let content = print_item(self, it);
257 let page = layout::Page {
258 css_class: tyname_s,
259 root_path: &self.root_path(),
260 static_root_path: self.shared.static_root_path.as_deref(),
261 title: &title,
262 short_title,
263 description: &desc,
264 resource_suffix: &self.shared.resource_suffix,
265 rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), |d| {
266 d.rust_logo.is_some()
267 }),
268 };
269 layout::render(
270 &self.shared.layout,
271 &page,
272 fmt::from_fn(|f| print_sidebar(self, it, f)),
273 content,
274 &self.shared.style_files,
275 )
276 } else {
277 if let Some(&(ref names, ty)) = self.cache().paths.get(&it.item_id.expect_def_id())
278 && (self.current.len() + 1 != names.len()
279 || self.current.iter().zip(names.iter()).any(|(a, b)| a != b))
280 {
281 let path = fmt::from_fn(|f| {
286 for name in &names[..names.len() - 1] {
287 write!(f, "{name}/")?;
288 }
289 write!(f, "{}", print_item_path(ty, names.last().unwrap().as_str()))
290 });
291 match self.shared.redirections {
292 Some(ref redirections) => {
293 let mut current_path = String::new();
294 for name in &self.current {
295 current_path.push_str(name.as_str());
296 current_path.push('/');
297 }
298 let _ = write!(
299 current_path,
300 "{}",
301 print_item_path(ty, names.last().unwrap().as_str())
302 );
303 redirections.borrow_mut().insert(current_path, path.to_string());
304 }
305 None => {
306 return layout::redirect(&format!("{root}{path}", root = self.root_path()));
307 }
308 }
309 }
310 String::new()
311 }
312 }
313
314 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<String>> {
316 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
318 let mut inserted: FxHashMap<ItemType, FxHashSet<Symbol>> = FxHashMap::default();
319
320 for item in &m.items {
321 if item.is_stripped() {
322 continue;
323 }
324
325 let short = item.type_();
326 let myname = match item.name {
327 None => continue,
328 Some(s) => s,
329 };
330 if inserted.entry(short).or_default().insert(myname) {
331 let short = short.to_string();
332 let myname = myname.to_string();
333 map.entry(short).or_default().push(myname);
334 }
335 }
336
337 match self.shared.module_sorting {
338 ModuleSorting::Alphabetical => {
339 for items in map.values_mut() {
340 items.sort();
341 }
342 }
343 ModuleSorting::DeclarationOrder => {}
344 }
345 map
346 }
347
348 pub(super) fn src_href(&self, item: &clean::Item) -> Option<String> {
358 self.href_from_span(item.span(self.tcx())?, true)
359 }
360
361 pub(crate) fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> {
362 let mut root = self.root_path();
363 let mut path: String;
364 let cnum = span.cnum(self.sess());
365
366 let file = match span.filename(self.sess()) {
368 FileName::Real(ref path) => path
369 .local_path()
370 .unwrap_or(path.path(RemapPathScopeComponents::DOCUMENTATION))
371 .to_path_buf(),
372 _ => return None,
373 };
374 let file = &file;
375
376 let krate_sym;
377 let (krate, path) = if cnum == LOCAL_CRATE {
378 if let Some(path) = self.shared.local_sources.get(file) {
379 (self.shared.layout.krate.as_str(), path)
380 } else {
381 return None;
382 }
383 } else {
384 let (krate, src_root) = match *self.cache().extern_locations.get(&cnum)? {
385 ExternalLocation::Local => {
386 let e = ExternalCrate { crate_num: cnum };
387 (e.name(self.tcx()), e.src_root(self.tcx()))
388 }
389 ExternalLocation::Remote { ref url, .. } => {
390 root = url.to_string();
392 let e = ExternalCrate { crate_num: cnum };
393 (e.name(self.tcx()), e.src_root(self.tcx()))
394 }
395 ExternalLocation::Unknown => return None,
396 };
397
398 let href = RefCell::new(PathBuf::new());
399 sources::clean_path(
400 &src_root,
401 file,
402 |component| {
403 href.borrow_mut().push(component);
404 },
405 || {
406 href.borrow_mut().pop();
407 },
408 );
409
410 path = href.into_inner().to_string_lossy().into_owned();
411
412 if let Some(c) = path.as_bytes().last()
413 && *c != b'/'
414 {
415 path.push('/');
416 }
417
418 let mut fname = file.file_name().expect("source has no filename").to_os_string();
419 fname.push(".html");
420 path.push_str(&fname.to_string_lossy());
421 krate_sym = krate;
422 (krate_sym.as_str(), &path)
423 };
424
425 let anchor = if with_lines {
426 let loline = span.lo(self.sess()).line;
427 let hiline = span.hi(self.sess()).line;
428 format!(
429 "#{}",
430 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
431 )
432 } else {
433 "".to_string()
434 };
435 Some(format!(
436 "{root}src/{krate}/{path}{anchor}",
437 root = Escape(&root),
438 krate = krate,
439 path = path,
440 anchor = anchor
441 ))
442 }
443
444 pub(crate) fn href_from_span_relative(
445 &self,
446 span: clean::Span,
447 relative_to: &str,
448 ) -> Option<String> {
449 self.href_from_span(span, false).map(|s| {
450 let mut url = UrlPartsBuilder::new();
451 let mut dest_href_parts = s.split('/');
452 let mut cur_href_parts = relative_to.split('/');
453 for (cur_href_part, dest_href_part) in (&mut cur_href_parts).zip(&mut dest_href_parts) {
454 if cur_href_part != dest_href_part {
455 url.push(dest_href_part);
456 break;
457 }
458 }
459 for dest_href_part in dest_href_parts {
460 url.push(dest_href_part);
461 }
462 let loline = span.lo(self.sess()).line;
463 let hiline = span.hi(self.sess()).line;
464 format!(
465 "{}{}#{}",
466 "../".repeat(cur_href_parts.count()),
467 url.finish(),
468 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
469 )
470 })
471 }
472}
473
474impl<'tcx> Context<'tcx> {
475 pub(crate) fn init(
476 krate: clean::Crate,
477 options: RenderOptions,
478 cache: Cache,
479 tcx: TyCtxt<'tcx>,
480 expanded_codes: FxHashMap<BytePos, Vec<ExpandedCode>>,
481 ) -> Result<(Self, clean::Crate), Error> {
482 let md_opts = options.clone();
484 let emit_crate = options.should_emit_crate();
485 let RenderOptions {
486 output,
487 external_html,
488 id_map,
489 playground_url,
490 module_sorting,
491 themes: style_files,
492 default_settings,
493 extension_css,
494 resource_suffix,
495 static_root_path,
496 generate_redirect_map,
497 show_type_layout,
498 generate_link_to_definition,
499 call_locations,
500 no_emit_shared,
501 html_no_source,
502 ..
503 } = options;
504
505 let src_root = match krate.src(tcx) {
506 FileName::Real(ref p) => {
507 match p
508 .local_path()
509 .unwrap_or(p.path(RemapPathScopeComponents::DOCUMENTATION))
510 .parent()
511 {
512 Some(p) => p.to_path_buf(),
513 None => PathBuf::new(),
514 }
515 }
516 _ => PathBuf::new(),
517 };
518 let mut playground = None;
520 if let Some(url) = playground_url {
521 playground = Some(markdown::Playground { crate_name: Some(krate.name(tcx)), url });
522 }
523 let krate_version = cache.crate_version.as_deref().unwrap_or_default();
524 let mut layout = layout::Layout {
525 logo: String::new(),
526 favicon: String::new(),
527 external_html,
528 default_settings,
529 krate: krate.name(tcx).to_string(),
530 krate_version: krate_version.to_string(),
531 css_file_extension: extension_css,
532 scrape_examples_extension: !call_locations.is_empty(),
533 };
534 let mut issue_tracker_base_url = None;
535 let mut include_sources = !html_no_source;
536
537 for attr in &krate.module.attrs.other_attrs {
540 let Attribute::Parsed(AttributeKind::Doc(d)) = attr else { continue };
541 if let Some((html_favicon_url, _)) = d.html_favicon_url {
542 layout.favicon = html_favicon_url.to_string();
543 }
544 if let Some((html_logo_url, _)) = d.html_logo_url {
545 layout.logo = html_logo_url.to_string();
546 }
547 if let Some((html_playground_url, _)) = d.html_playground_url {
548 playground = Some(markdown::Playground {
549 crate_name: Some(krate.name(tcx)),
550 url: html_playground_url.to_string(),
551 });
552 }
553 if let Some((s, _)) = d.issue_tracker_base_url {
554 issue_tracker_base_url = Some(s.to_string());
555 }
556 if d.html_no_source.is_some() {
557 include_sources = false;
558 }
559 }
560
561 let (local_sources, matches) = collect_spans_and_sources(
562 tcx,
563 &krate,
564 &src_root,
565 include_sources,
566 generate_link_to_definition,
567 );
568
569 let (sender, receiver) = channel();
570 let scx = SharedContext {
571 tcx,
572 src_root,
573 local_sources,
574 issue_tracker_base_url,
575 layout,
576 created_dirs: Default::default(),
577 module_sorting,
578 style_files,
579 resource_suffix,
580 static_root_path,
581 fs: DocFS::new(sender),
582 codes: ErrorCodes::from(options.unstable_features.is_nightly_build()),
583 playground,
584 all: RefCell::new(AllTypes::new()),
585 errors: receiver,
586 redirections: if generate_redirect_map { Some(Default::default()) } else { None },
587 show_type_layout,
588 span_correspondence_map: matches,
589 cache,
590 call_locations,
591 should_merge: options.should_merge,
592 expanded_codes,
593 };
594
595 let dst = output;
596 scx.ensure_dir(&dst)?;
597
598 let mut cx = Context {
599 current: Vec::new(),
600 dst,
601 id_map: RefCell::new(id_map),
602 deref_id_map: Default::default(),
603 shared: scx,
604 types_with_notable_traits: RefCell::new(FxIndexSet::default()),
605 info: ContextInfo::new(include_sources),
606 };
607
608 if emit_crate {
609 sources::render(&mut cx, &krate)?;
610 }
611
612 if !no_emit_shared {
613 write_shared(&mut cx, &krate, &md_opts, tcx)?;
614 }
615
616 Ok((cx, krate))
617 }
618}
619
620impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
622 fn descr() -> &'static str {
623 "html"
624 }
625
626 const RUN_ON_MODULE: bool = true;
627 type ModuleData = ContextInfo;
628
629 fn save_module_data(&mut self) -> Self::ModuleData {
630 self.deref_id_map.borrow_mut().clear();
631 self.id_map.borrow_mut().clear();
632 self.types_with_notable_traits.borrow_mut().clear();
633 self.info
634 }
635
636 fn restore_module_data(&mut self, info: Self::ModuleData) {
637 self.info = info;
638 }
639
640 fn after_krate(mut self) -> Result<(), Error> {
641 let crate_name = self.tcx().crate_name(LOCAL_CRATE);
642 let final_file = self.dst.join(crate_name.as_str()).join("all.html");
643 let settings_file = self.dst.join("settings.html");
644 let help_file = self.dst.join("help.html");
645 let scrape_examples_help_file = self.dst.join("scrape-examples-help.html");
646
647 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
648 if !root_path.ends_with('/') {
649 root_path.push('/');
650 }
651 let shared = &self.shared;
652 let mut page = layout::Page {
653 title: "List of all items in this crate",
654 short_title: "All",
655 css_class: "mod sys",
656 root_path: "../",
657 static_root_path: shared.static_root_path.as_deref(),
658 description: "List of all items in this crate",
659 resource_suffix: &shared.resource_suffix,
660 rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), |d| d.rust_logo.is_some()),
661 };
662 let all = shared.all.replace(AllTypes::new());
663 let mut sidebar = String::new();
664
665 let blocks = sidebar_module_like(all.item_sections(), &mut IdMap::new(), ModuleLike::Crate);
667 let bar = Sidebar {
668 title_prefix: "",
669 title: "",
670 is_crate: false,
671 is_mod: false,
672 parent_is_crate: false,
673 blocks: vec![blocks],
674 path: String::new(),
675 };
676
677 bar.render_into(&mut sidebar).unwrap();
678
679 let v = layout::render(&shared.layout, &page, sidebar, all.print(), &shared.style_files);
680 shared.fs.write(final_file, v)?;
681
682 if shared.should_merge.write_rendered_cci {
684 page.title = "Settings";
686 page.description = "Settings of Rustdoc";
687 page.root_path = "./";
688 page.rust_logo = true;
689
690 let sidebar = "<h2 class=\"location\">Settings</h2><div class=\"sidebar-elems\"></div>";
691 let v = layout::render(
692 &shared.layout,
693 &page,
694 sidebar,
695 fmt::from_fn(|buf| {
696 write!(
697 buf,
698 "<div class=\"main-heading\">\
699 <h1>Rustdoc settings</h1>\
700 <span class=\"out-of-band\">\
701 <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
702 Back\
703 </a>\
704 </span>\
705 </div>\
706 <noscript>\
707 <section>\
708 You need to enable JavaScript be able to update your settings.\
709 </section>\
710 </noscript>\
711 <script defer src=\"{static_root_path}{settings_js}\"></script>",
712 static_root_path = page.get_static_root_path(),
713 settings_js = static_files::STATIC_FILES.settings_js,
714 )?;
715 for file in &shared.style_files {
720 if let Ok(theme) = file.basename() {
721 write!(
722 buf,
723 "<link rel=\"preload\" href=\"{root_path}{theme}{suffix}.css\" \
724 as=\"style\">",
725 root_path = page.static_root_path.unwrap_or(""),
726 suffix = page.resource_suffix,
727 )?;
728 }
729 }
730 Ok(())
731 }),
732 &shared.style_files,
733 );
734 shared.fs.write(settings_file, v)?;
735
736 page.title = "Help";
738 page.description = "Documentation for Rustdoc";
739 page.root_path = "./";
740 page.rust_logo = true;
741
742 let sidebar = "<h2 class=\"location\">Help</h2><div class=\"sidebar-elems\"></div>";
743 let v = layout::render(
744 &shared.layout,
745 &page,
746 sidebar,
747 format_args!(
748 "<div class=\"main-heading\">\
749 <h1>Rustdoc help</h1>\
750 <span class=\"out-of-band\">\
751 <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
752 Back\
753 </a>\
754 </span>\
755 </div>\
756 <noscript>\
757 <section>\
758 <p>You need to enable JavaScript to use keyboard commands or search.</p>\
759 <p>For more information, browse the <a href=\"{DOC_RUST_LANG_ORG_VERSION}/rustdoc/\">rustdoc handbook</a>.</p>\
760 </section>\
761 </noscript>",
762 ),
763 &shared.style_files,
764 );
765 shared.fs.write(help_file, v)?;
766 }
767
768 if shared.layout.scrape_examples_extension && shared.should_merge.write_rendered_cci {
770 page.title = "About scraped examples";
771 page.description = "How the scraped examples feature works in Rustdoc";
772 let v = layout::render(
773 &shared.layout,
774 &page,
775 "",
776 scrape_examples_help(shared),
777 &shared.style_files,
778 );
779 shared.fs.write(scrape_examples_help_file, v)?;
780 }
781
782 if let Some(ref redirections) = shared.redirections
783 && !redirections.borrow().is_empty()
784 {
785 let redirect_map_path = self.dst.join(crate_name.as_str()).join("redirect-map.json");
786 let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
787 shared.ensure_dir(&self.dst.join(crate_name.as_str()))?;
788 shared.fs.write(redirect_map_path, paths)?;
789 }
790
791 self.shared.fs.close();
793 let nb_errors = self.shared.errors.iter().map(|err| self.tcx().dcx().err(err)).count();
794 if nb_errors > 0 { Err(Error::new(io::Error::other("I/O error"), "")) } else { Ok(()) }
795 }
796
797 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> {
798 if !self.info.render_redirect_pages {
806 self.info.render_redirect_pages = item.is_stripped();
807 }
808 let item_name = item.name.unwrap();
809 self.dst.push(item_name.as_str());
810 self.current.push(item_name);
811
812 info!("Recursing into {}", self.dst.display());
813
814 if !item.is_stripped() {
815 let buf = self.render_item(item, true);
816 if !buf.is_empty() {
818 self.shared.ensure_dir(&self.dst)?;
819 let joint_dst = self.dst.join("index.html");
820 self.shared.fs.write(joint_dst, buf)?;
821 }
822 }
823 if !self.info.is_inside_inlined_module {
824 if let Some(def_id) = item.def_id()
825 && self.cache().inlined_items.contains(&def_id)
826 {
827 self.info.is_inside_inlined_module = true;
828 }
829 } else if !self.cache().document_hidden && item.is_doc_hidden() {
830 self.info.is_inside_inlined_module = false;
832 }
833
834 if !self.info.render_redirect_pages {
836 let (clean::StrippedItem(box clean::ModuleItem(ref module))
837 | clean::ModuleItem(ref module)) = item.kind
838 else {
839 unreachable!()
840 };
841 let items = self.build_sidebar_items(module);
842 let js_dst = self.dst.join(format!("sidebar-items{}.js", self.shared.resource_suffix));
843 let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap());
844 self.shared.fs.write(js_dst, v)?;
845 }
846 Ok(())
847 }
848
849 fn mod_item_out(&mut self) -> Result<(), Error> {
850 info!("Recursed; leaving {}", self.dst.display());
851
852 self.dst.pop();
854 self.current.pop();
855 Ok(())
856 }
857
858 fn item(&mut self, item: &clean::Item) -> Result<(), Error> {
859 if !self.info.render_redirect_pages {
867 self.info.render_redirect_pages = item.is_stripped();
868 }
869
870 let buf = self.render_item(item, false);
871 if !buf.is_empty() {
873 let name = item.name.as_ref().unwrap();
874 let item_type = item.type_();
875 let file_name = print_item_path(item_type, name.as_str()).to_string();
876 self.shared.ensure_dir(&self.dst)?;
877 let joint_dst = self.dst.join(&file_name);
878 self.shared.fs.write(joint_dst, buf)?;
879
880 if !self.info.render_redirect_pages {
881 self.shared.all.borrow_mut().append(full_path(self, item), &item_type);
882 }
883 if item_type == ItemType::Macro {
886 let redir_name = format!("{item_type}.{name}!.html");
887 if let Some(ref redirections) = self.shared.redirections {
888 let crate_name = &self.shared.layout.krate;
889 redirections.borrow_mut().insert(
890 format!("{crate_name}/{redir_name}"),
891 format!("{crate_name}/{file_name}"),
892 );
893 } else {
894 let v = layout::redirect(&file_name);
895 let redir_dst = self.dst.join(redir_name);
896 self.shared.fs.write(redir_dst, v)?;
897 }
898 }
899 }
900
901 Ok(())
902 }
903}