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