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