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