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 mut page_buffer = String::new();
241 print_item(self, it, &mut page_buffer);
242 let page = layout::Page {
243 css_class: tyname_s,
244 root_path: &self.root_path(),
245 static_root_path: self.shared.static_root_path.as_deref(),
246 title: &title,
247 description: &desc,
248 resource_suffix: &self.shared.resource_suffix,
249 rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), sym::rust_logo),
250 };
251 layout::render(
252 &self.shared.layout,
253 &page,
254 BufDisplay(|buf: &mut String| {
255 print_sidebar(self, it, buf);
256 }),
257 page_buffer,
258 &self.shared.style_files,
259 )
260 } else {
261 if let Some(&(ref names, ty)) = self.cache().paths.get(&it.item_id.expect_def_id()) {
262 if self.current.len() + 1 != names.len()
263 || self.current.iter().zip(names.iter()).any(|(a, b)| a != b)
264 {
265 let path = fmt::from_fn(|f| {
270 for name in &names[..names.len() - 1] {
271 write!(f, "{name}/")?;
272 }
273 write!(f, "{}", item_path(ty, names.last().unwrap().as_str()))
274 });
275 match self.shared.redirections {
276 Some(ref redirections) => {
277 let mut current_path = String::new();
278 for name in &self.current {
279 current_path.push_str(name.as_str());
280 current_path.push('/');
281 }
282 let _ = write!(
283 current_path,
284 "{}",
285 item_path(ty, names.last().unwrap().as_str())
286 );
287 redirections.borrow_mut().insert(current_path, path.to_string());
288 }
289 None => {
290 return layout::redirect(&format!(
291 "{root}{path}",
292 root = self.root_path()
293 ));
294 }
295 }
296 }
297 }
298 String::new()
299 }
300 }
301
302 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<String>> {
304 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
306 let mut inserted: FxHashMap<ItemType, FxHashSet<Symbol>> = FxHashMap::default();
307
308 for item in &m.items {
309 if item.is_stripped() {
310 continue;
311 }
312
313 let short = item.type_();
314 let myname = match item.name {
315 None => continue,
316 Some(s) => s,
317 };
318 if inserted.entry(short).or_default().insert(myname) {
319 let short = short.to_string();
320 let myname = myname.to_string();
321 map.entry(short).or_default().push(myname);
322 }
323 }
324
325 match self.shared.module_sorting {
326 ModuleSorting::Alphabetical => {
327 for items in map.values_mut() {
328 items.sort();
329 }
330 }
331 ModuleSorting::DeclarationOrder => {}
332 }
333 map
334 }
335
336 pub(super) fn src_href(&self, item: &clean::Item) -> Option<String> {
346 self.href_from_span(item.span(self.tcx())?, true)
347 }
348
349 pub(crate) fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> {
350 let mut root = self.root_path();
351 let mut path: String;
352 let cnum = span.cnum(self.sess());
353
354 let file = match span.filename(self.sess()) {
356 FileName::Real(ref path) => path.local_path_if_available().to_path_buf(),
357 _ => return None,
358 };
359 let file = &file;
360
361 let krate_sym;
362 let (krate, path) = if cnum == LOCAL_CRATE {
363 if let Some(path) = self.shared.local_sources.get(file) {
364 (self.shared.layout.krate.as_str(), path)
365 } else {
366 return None;
367 }
368 } else {
369 let (krate, src_root) = match *self.cache().extern_locations.get(&cnum)? {
370 ExternalLocation::Local => {
371 let e = ExternalCrate { crate_num: cnum };
372 (e.name(self.tcx()), e.src_root(self.tcx()))
373 }
374 ExternalLocation::Remote(ref s) => {
375 root = s.to_string();
376 let e = ExternalCrate { crate_num: cnum };
377 (e.name(self.tcx()), e.src_root(self.tcx()))
378 }
379 ExternalLocation::Unknown => return None,
380 };
381
382 let href = RefCell::new(PathBuf::new());
383 sources::clean_path(
384 &src_root,
385 file,
386 |component| {
387 href.borrow_mut().push(component);
388 },
389 || {
390 href.borrow_mut().pop();
391 },
392 );
393
394 path = href.into_inner().to_string_lossy().into_owned();
395
396 if let Some(c) = path.as_bytes().last()
397 && *c != b'/'
398 {
399 path.push('/');
400 }
401
402 let mut fname = file.file_name().expect("source has no filename").to_os_string();
403 fname.push(".html");
404 path.push_str(&fname.to_string_lossy());
405 krate_sym = krate;
406 (krate_sym.as_str(), &path)
407 };
408
409 let anchor = if with_lines {
410 let loline = span.lo(self.sess()).line;
411 let hiline = span.hi(self.sess()).line;
412 format!(
413 "#{}",
414 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
415 )
416 } else {
417 "".to_string()
418 };
419 Some(format!(
420 "{root}src/{krate}/{path}{anchor}",
421 root = Escape(&root),
422 krate = krate,
423 path = path,
424 anchor = anchor
425 ))
426 }
427
428 pub(crate) fn href_from_span_relative(
429 &self,
430 span: clean::Span,
431 relative_to: &str,
432 ) -> Option<String> {
433 self.href_from_span(span, false).map(|s| {
434 let mut url = UrlPartsBuilder::new();
435 let mut dest_href_parts = s.split('/');
436 let mut cur_href_parts = relative_to.split('/');
437 for (cur_href_part, dest_href_part) in (&mut cur_href_parts).zip(&mut dest_href_parts) {
438 if cur_href_part != dest_href_part {
439 url.push(dest_href_part);
440 break;
441 }
442 }
443 for dest_href_part in dest_href_parts {
444 url.push(dest_href_part);
445 }
446 let loline = span.lo(self.sess()).line;
447 let hiline = span.hi(self.sess()).line;
448 format!(
449 "{}{}#{}",
450 "../".repeat(cur_href_parts.count()),
451 url.finish(),
452 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
453 )
454 })
455 }
456}
457
458impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
460 fn descr() -> &'static str {
461 "html"
462 }
463
464 const RUN_ON_MODULE: bool = true;
465 type ModuleData = ContextInfo;
466
467 fn init(
468 krate: clean::Crate,
469 options: RenderOptions,
470 cache: Cache,
471 tcx: TyCtxt<'tcx>,
472 ) -> Result<(Self, clean::Crate), Error> {
473 let md_opts = options.clone();
475 let emit_crate = options.should_emit_crate();
476 let RenderOptions {
477 output,
478 external_html,
479 id_map,
480 playground_url,
481 module_sorting,
482 themes: style_files,
483 default_settings,
484 extension_css,
485 resource_suffix,
486 static_root_path,
487 generate_redirect_map,
488 show_type_layout,
489 generate_link_to_definition,
490 call_locations,
491 no_emit_shared,
492 html_no_source,
493 ..
494 } = options;
495
496 let src_root = match krate.src(tcx) {
497 FileName::Real(ref p) => match p.local_path_if_available().parent() {
498 Some(p) => p.to_path_buf(),
499 None => PathBuf::new(),
500 },
501 _ => PathBuf::new(),
502 };
503 let mut playground = None;
505 if let Some(url) = playground_url {
506 playground = Some(markdown::Playground { crate_name: Some(krate.name(tcx)), url });
507 }
508 let krate_version = cache.crate_version.as_deref().unwrap_or_default();
509 let mut layout = layout::Layout {
510 logo: String::new(),
511 favicon: String::new(),
512 external_html,
513 default_settings,
514 krate: krate.name(tcx).to_string(),
515 krate_version: krate_version.to_string(),
516 css_file_extension: extension_css,
517 scrape_examples_extension: !call_locations.is_empty(),
518 };
519 let mut issue_tracker_base_url = None;
520 let mut include_sources = !html_no_source;
521
522 for attr in krate.module.attrs.lists(sym::doc) {
525 match (attr.name_or_empty(), attr.value_str()) {
526 (sym::html_favicon_url, Some(s)) => {
527 layout.favicon = s.to_string();
528 }
529 (sym::html_logo_url, Some(s)) => {
530 layout.logo = s.to_string();
531 }
532 (sym::html_playground_url, Some(s)) => {
533 playground = Some(markdown::Playground {
534 crate_name: Some(krate.name(tcx)),
535 url: s.to_string(),
536 });
537 }
538 (sym::issue_tracker_base_url, Some(s)) => {
539 issue_tracker_base_url = Some(s.to_string());
540 }
541 (sym::html_no_source, None) if attr.is_word() => {
542 include_sources = false;
543 }
544 _ => {}
545 }
546 }
547
548 let (local_sources, matches) = collect_spans_and_sources(
549 tcx,
550 &krate,
551 &src_root,
552 include_sources,
553 generate_link_to_definition,
554 );
555
556 let (sender, receiver) = channel();
557 let scx = SharedContext {
558 tcx,
559 src_root,
560 local_sources,
561 issue_tracker_base_url,
562 layout,
563 created_dirs: Default::default(),
564 module_sorting,
565 style_files,
566 resource_suffix,
567 static_root_path,
568 fs: DocFS::new(sender),
569 codes: ErrorCodes::from(options.unstable_features.is_nightly_build()),
570 playground,
571 all: RefCell::new(AllTypes::new()),
572 errors: receiver,
573 redirections: if generate_redirect_map { Some(Default::default()) } else { None },
574 show_type_layout,
575 span_correspondence_map: matches,
576 cache,
577 call_locations,
578 should_merge: options.should_merge,
579 };
580
581 let dst = output;
582 scx.ensure_dir(&dst)?;
583
584 let mut cx = Context {
585 current: Vec::new(),
586 dst,
587 id_map: RefCell::new(id_map),
588 deref_id_map: Default::default(),
589 shared: scx,
590 types_with_notable_traits: RefCell::new(FxIndexSet::default()),
591 info: ContextInfo::new(include_sources),
592 };
593
594 if emit_crate {
595 sources::render(&mut cx, &krate)?;
596 }
597
598 if !no_emit_shared {
599 write_shared(&mut cx, &krate, &md_opts, tcx)?;
600 }
601
602 Ok((cx, krate))
603 }
604
605 fn save_module_data(&mut self) -> Self::ModuleData {
606 self.deref_id_map.borrow_mut().clear();
607 self.id_map.borrow_mut().clear();
608 self.types_with_notable_traits.borrow_mut().clear();
609 self.info
610 }
611
612 fn restore_module_data(&mut self, info: Self::ModuleData) {
613 self.info = info;
614 }
615
616 fn after_krate(&mut self) -> Result<(), Error> {
617 let crate_name = self.tcx().crate_name(LOCAL_CRATE);
618 let final_file = self.dst.join(crate_name.as_str()).join("all.html");
619 let settings_file = self.dst.join("settings.html");
620 let help_file = self.dst.join("help.html");
621 let scrape_examples_help_file = self.dst.join("scrape-examples-help.html");
622
623 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
624 if !root_path.ends_with('/') {
625 root_path.push('/');
626 }
627 let shared = &self.shared;
628 let mut page = layout::Page {
629 title: "List of all items in this crate",
630 css_class: "mod sys",
631 root_path: "../",
632 static_root_path: shared.static_root_path.as_deref(),
633 description: "List of all items in this crate",
634 resource_suffix: &shared.resource_suffix,
635 rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), sym::rust_logo),
636 };
637 let all = shared.all.replace(AllTypes::new());
638 let mut sidebar = String::new();
639
640 let blocks = sidebar_module_like(all.item_sections(), &mut IdMap::new(), ModuleLike::Crate);
642 let bar = Sidebar {
643 title_prefix: "",
644 title: "",
645 is_crate: false,
646 is_mod: false,
647 parent_is_crate: false,
648 blocks: vec![blocks],
649 path: String::new(),
650 };
651
652 bar.render_into(&mut sidebar).unwrap();
653
654 let v = layout::render(
655 &shared.layout,
656 &page,
657 sidebar,
658 BufDisplay(|buf: &mut String| {
659 all.print(buf);
660 }),
661 &shared.style_files,
662 );
663 shared.fs.write(final_file, v)?;
664
665 if shared.should_merge.write_rendered_cci {
667 page.title = "Settings";
669 page.description = "Settings of Rustdoc";
670 page.root_path = "./";
671 page.rust_logo = true;
672
673 let sidebar = "<h2 class=\"location\">Settings</h2><div class=\"sidebar-elems\"></div>";
674 let v = layout::render(
675 &shared.layout,
676 &page,
677 sidebar,
678 fmt::from_fn(|buf| {
679 write!(
680 buf,
681 "<div class=\"main-heading\">\
682 <h1>Rustdoc settings</h1>\
683 <span class=\"out-of-band\">\
684 <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
685 Back\
686 </a>\
687 </span>\
688 </div>\
689 <noscript>\
690 <section>\
691 You need to enable JavaScript be able to update your settings.\
692 </section>\
693 </noscript>\
694 <script defer src=\"{static_root_path}{settings_js}\"></script>",
695 static_root_path = page.get_static_root_path(),
696 settings_js = static_files::STATIC_FILES.settings_js,
697 )?;
698 for file in &shared.style_files {
703 if let Ok(theme) = file.basename() {
704 write!(
705 buf,
706 "<link rel=\"preload\" href=\"{root_path}{theme}{suffix}.css\" \
707 as=\"style\">",
708 root_path = page.static_root_path.unwrap_or(""),
709 suffix = page.resource_suffix,
710 )?;
711 }
712 }
713 Ok(())
714 }),
715 &shared.style_files,
716 );
717 shared.fs.write(settings_file, v)?;
718
719 page.title = "Help";
721 page.description = "Documentation for Rustdoc";
722 page.root_path = "./";
723 page.rust_logo = true;
724
725 let sidebar = "<h2 class=\"location\">Help</h2><div class=\"sidebar-elems\"></div>";
726 let v = layout::render(
727 &shared.layout,
728 &page,
729 sidebar,
730 format_args!(
731 "<div class=\"main-heading\">\
732 <h1>Rustdoc help</h1>\
733 <span class=\"out-of-band\">\
734 <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
735 Back\
736 </a>\
737 </span>\
738 </div>\
739 <noscript>\
740 <section>\
741 <p>You need to enable JavaScript to use keyboard commands or search.</p>\
742 <p>For more information, browse the <a href=\"{DOC_RUST_LANG_ORG_VERSION}/rustdoc/\">rustdoc handbook</a>.</p>\
743 </section>\
744 </noscript>",
745 ),
746 &shared.style_files,
747 );
748 shared.fs.write(help_file, v)?;
749 }
750
751 if shared.layout.scrape_examples_extension && shared.should_merge.write_rendered_cci {
753 page.title = "About scraped examples";
754 page.description = "How the scraped examples feature works in Rustdoc";
755 let v = layout::render(
756 &shared.layout,
757 &page,
758 "",
759 scrape_examples_help(shared),
760 &shared.style_files,
761 );
762 shared.fs.write(scrape_examples_help_file, v)?;
763 }
764
765 if let Some(ref redirections) = shared.redirections
766 && !redirections.borrow().is_empty()
767 {
768 let redirect_map_path = self.dst.join(crate_name.as_str()).join("redirect-map.json");
769 let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
770 shared.ensure_dir(&self.dst.join(crate_name.as_str()))?;
771 shared.fs.write(redirect_map_path, paths)?;
772 }
773
774 self.shared.fs.close();
776 let nb_errors = self.shared.errors.iter().map(|err| self.tcx().dcx().err(err)).count();
777 if nb_errors > 0 {
778 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
779 } else {
780 Ok(())
781 }
782 }
783
784 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> {
785 if !self.info.render_redirect_pages {
793 self.info.render_redirect_pages = item.is_stripped();
794 }
795 let item_name = item.name.unwrap();
796 self.dst.push(item_name.as_str());
797 self.current.push(item_name);
798
799 info!("Recursing into {}", self.dst.display());
800
801 if !item.is_stripped() {
802 let buf = self.render_item(item, true);
803 if !buf.is_empty() {
805 self.shared.ensure_dir(&self.dst)?;
806 let joint_dst = self.dst.join("index.html");
807 self.shared.fs.write(joint_dst, buf)?;
808 }
809 }
810 if !self.info.is_inside_inlined_module {
811 if let Some(def_id) = item.def_id()
812 && self.cache().inlined_items.contains(&def_id)
813 {
814 self.info.is_inside_inlined_module = true;
815 }
816 } else if !self.cache().document_hidden && item.is_doc_hidden() {
817 self.info.is_inside_inlined_module = false;
819 }
820
821 if !self.info.render_redirect_pages {
823 let (clean::StrippedItem(box clean::ModuleItem(ref module))
824 | clean::ModuleItem(ref module)) = item.kind
825 else {
826 unreachable!()
827 };
828 let items = self.build_sidebar_items(module);
829 let js_dst = self.dst.join(format!("sidebar-items{}.js", self.shared.resource_suffix));
830 let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap());
831 self.shared.fs.write(js_dst, v)?;
832 }
833 Ok(())
834 }
835
836 fn mod_item_out(&mut self) -> Result<(), Error> {
837 info!("Recursed; leaving {}", self.dst.display());
838
839 self.dst.pop();
841 self.current.pop();
842 Ok(())
843 }
844
845 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
846 if !self.info.render_redirect_pages {
854 self.info.render_redirect_pages = item.is_stripped();
855 }
856
857 let buf = self.render_item(&item, false);
858 if !buf.is_empty() {
860 let name = item.name.as_ref().unwrap();
861 let item_type = item.type_();
862 let file_name = item_path(item_type, name.as_str()).to_string();
863 self.shared.ensure_dir(&self.dst)?;
864 let joint_dst = self.dst.join(&file_name);
865 self.shared.fs.write(joint_dst, buf)?;
866
867 if !self.info.render_redirect_pages {
868 self.shared.all.borrow_mut().append(full_path(self, &item), &item_type);
869 }
870 if item_type == ItemType::Macro {
873 let redir_name = format!("{item_type}.{name}!.html");
874 if let Some(ref redirections) = self.shared.redirections {
875 let crate_name = &self.shared.layout.krate;
876 redirections.borrow_mut().insert(
877 format!("{crate_name}/{redir_name}"),
878 format!("{crate_name}/{file_name}"),
879 );
880 } else {
881 let v = layout::redirect(&file_name);
882 let redir_dst = self.dst.join(redir_name);
883 self.shared.fs.write(redir_dst, v)?;
884 }
885 }
886 }
887
888 Ok(())
889 }
890
891 fn cache(&self) -> &Cache {
892 &self.shared.cache
893 }
894}