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