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};
24use crate::clean::types::ExternalLocation;
25use crate::clean::utils::has_doc_flag;
26use crate::clean::{self, ExternalCrate};
27use crate::config::{EmitType, ModuleSorting, RenderOptions};
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};
40use crate::scrape_examples::AllCallLocations;
41use crate::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}
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
169struct SidebarItem {
170 name: String,
171 is_macro_rules: bool,
175}
176
177impl serde::Serialize for SidebarItem {
178 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
179 where
180 S: serde::Serializer,
181 {
182 if self.is_macro_rules {
183 let mut seq = serializer.serialize_seq(Some(2))?;
184 seq.serialize_element(&self.name)?;
185 seq.serialize_element(&1)?;
186 seq.end()
187 } else {
188 serializer.serialize_some(&Some(&self.name))
189 }
190 }
191}
192
193impl<'tcx> Context<'tcx> {
194 pub(crate) fn tcx(&self) -> TyCtxt<'tcx> {
195 self.shared.tcx
196 }
197
198 pub(crate) fn cache(&self) -> &Cache {
199 &self.shared.cache
200 }
201
202 pub(super) fn sess(&self) -> &'tcx Session {
203 self.shared.tcx.sess
204 }
205
206 pub(super) fn derive_id<S: AsRef<str> + ToString>(&self, id: S) -> String {
207 self.id_map.borrow_mut().derive(id)
208 }
209
210 pub(super) fn root_path(&self) -> String {
213 "../".repeat(self.current.len())
214 }
215
216 fn render_item(&mut self, it: &clean::Item, is_module: bool) -> String {
217 let mut render_redirect_pages = self.info.render_redirect_pages;
218 if it.is_stripped()
221 && let Some(def_id) = it.def_id()
222 && def_id.is_local()
223 && (self.info.is_inside_inlined_module
224 || self.shared.cache.inlined_items.contains(&def_id))
225 {
226 render_redirect_pages = true;
229 }
230
231 if !render_redirect_pages {
232 let mut title = String::new();
233 if !is_module {
234 title.push_str(it.name.unwrap().as_str());
235 }
236 let short_title;
237 let short_title = if is_module {
238 let module_name = self.current.last().unwrap();
239 short_title = if it.is_crate() {
240 format!("Crate {module_name}")
241 } else {
242 format!("Module {module_name}")
243 };
244 &short_title[..]
245 } else {
246 it.name.as_ref().unwrap().as_str()
247 };
248 if !it.is_fake_item() {
249 if !is_module {
250 title.push_str(" in ");
251 }
252 title.push_str(&join_path_syms(&self.current));
254 };
255 title.push_str(" - Rust");
256 let tyname = it.type_();
257 let desc = plain_text_summary(&it.doc_value(), &it.link_names(self.cache()));
258 let desc = if !desc.is_empty() {
259 desc
260 } else if it.is_crate() {
261 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
262 } else {
263 format!(
264 "API documentation for the Rust `{name}` {tyname} in crate `{krate}`.",
265 name = it.name.as_ref().unwrap(),
266 krate = self.shared.layout.krate,
267 )
268 };
269
270 let name;
271 let tyname_s = if it.is_crate() {
272 name = format!("{tyname} crate");
273 name.as_str()
274 } else {
275 tyname.as_str()
276 };
277
278 let content = print_item(self, it);
279 let page = layout::Page {
280 css_class: tyname_s,
281 root_path: &self.root_path(),
282 static_root_path: self.shared.static_root_path.as_deref(),
283 title: &title,
284 short_title,
285 description: &desc,
286 resource_suffix: &self.shared.resource_suffix,
287 rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), |d| {
288 d.rust_logo.is_some()
289 }),
290 };
291 layout::render(
292 &self.shared.layout,
293 &page,
294 fmt::from_fn(|f| print_sidebar(self, it, f)),
295 content,
296 &self.shared.style_files,
297 )
298 } else {
299 if let Some(&(ref names, ty)) = self.cache().paths.get(&it.item_id.expect_def_id())
300 && (self.current.len() + 1 != names.len()
301 || self.current.iter().zip(names.iter()).any(|(a, b)| a != b))
302 {
303 let path = fmt::from_fn(|f| {
308 for name in &names[..names.len() - 1] {
309 write!(f, "{name}/")?;
310 }
311 write!(f, "{}", print_ty_path(ty, names.last().unwrap().as_str()))
312 });
313 match self.shared.redirections {
314 Some(ref redirections) => {
315 let mut current_path = String::new();
316 for name in &self.current {
317 current_path.push_str(name.as_str());
318 current_path.push('/');
319 }
320 let _ = write!(
321 current_path,
322 "{}",
323 print_ty_path(ty, names.last().unwrap().as_str())
324 );
325 redirections.borrow_mut().insert(current_path, path.to_string());
326 }
327 None => {
328 return layout::redirect(&format!("{root}{path}", root = self.root_path()));
329 }
330 }
331 }
332 String::new()
333 }
334 }
335
336 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<SidebarItem>> {
338 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
340 let mut inserted: FxHashMap<ItemType, FxHashSet<Symbol>> = FxHashMap::default();
341
342 for item in &m.items {
343 if item.is_stripped() {
344 continue;
345 }
346 let name = match item.name {
347 None => continue,
348 Some(s) => s,
349 };
350
351 let is_macro_rules = item.is_decl_macro();
352 for type_ in item.types() {
353 if inserted.entry(type_).or_default().insert(name) {
354 let type_ = type_.to_string();
355 let name = name.to_string();
356 map.entry(type_).or_default().push(SidebarItem { name, is_macro_rules });
357 }
358 }
359 }
360
361 match self.shared.module_sorting {
362 ModuleSorting::Alphabetical => {
363 for items in map.values_mut() {
364 items.sort_by(|a, b| a.name.cmp(&b.name));
365 }
366 }
367 ModuleSorting::DeclarationOrder => {}
368 }
369 map
370 }
371
372 pub(super) fn src_href(&self, item: &clean::Item) -> Option<String> {
382 self.href_from_span(item.span(self.tcx())?, true)
383 }
384
385 pub(crate) fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> {
386 let mut root = self.root_path();
387 let mut path: String;
388 let cnum = span.cnum(self.sess());
389
390 let file = match span.filename(self.sess()) {
392 FileName::Real(ref path) => path
393 .local_path()
394 .unwrap_or(path.path(RemapPathScopeComponents::DOCUMENTATION))
395 .to_path_buf(),
396 _ => return None,
397 };
398 let file = &file;
399
400 let krate_sym;
401 let (krate, path) = if cnum == LOCAL_CRATE {
402 if let Some(path) = self.shared.local_sources.get(file) {
403 (self.shared.layout.krate.as_str(), path)
404 } else {
405 return None;
406 }
407 } else {
408 let (krate, src_root) = match *self.cache().extern_locations.get(&cnum)? {
409 ExternalLocation::Local => {
410 let e = ExternalCrate { crate_num: cnum };
411 (e.name(self.tcx()), e.src_root(self.tcx()))
412 }
413 ExternalLocation::Remote { ref url, .. } => {
414 root = url.to_string();
416 let e = ExternalCrate { crate_num: cnum };
417 (e.name(self.tcx()), e.src_root(self.tcx()))
418 }
419 ExternalLocation::Unknown => return None,
420 };
421
422 let href = RefCell::new(PathBuf::new());
423 sources::clean_path(
424 &src_root,
425 file,
426 |component| {
427 href.borrow_mut().push(component);
428 },
429 || {
430 href.borrow_mut().pop();
431 },
432 );
433
434 path = href.into_inner().to_string_lossy().into_owned();
435
436 if let Some(c) = path.as_bytes().last()
437 && *c != b'/'
438 {
439 path.push('/');
440 }
441
442 let mut fname = file.file_name().expect("source has no filename").to_os_string();
443 fname.push(".html");
444 path.push_str(&fname.to_string_lossy());
445 krate_sym = krate;
446 (krate_sym.as_str(), &path)
447 };
448
449 let anchor = if with_lines {
450 let loline = span.lo(self.sess()).line;
451 let hiline = span.hi(self.sess()).line;
452 format!(
453 "#{}",
454 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
455 )
456 } else {
457 "".to_string()
458 };
459 Some(format!(
460 "{root}src/{krate}/{path}{anchor}",
461 root = Escape(&root),
462 krate = krate,
463 path = path,
464 anchor = anchor
465 ))
466 }
467
468 pub(crate) fn href_from_span_relative(
469 &self,
470 span: clean::Span,
471 relative_to: &str,
472 ) -> Option<String> {
473 self.href_from_span(span, false).map(|s| {
474 let mut url = UrlPartsBuilder::new();
475 let mut dest_href_parts = s.split('/');
476 let mut cur_href_parts = relative_to.split('/');
477 for (cur_href_part, dest_href_part) in (&mut cur_href_parts).zip(&mut dest_href_parts) {
478 if cur_href_part != dest_href_part {
479 url.push(dest_href_part);
480 break;
481 }
482 }
483 for dest_href_part in dest_href_parts {
484 url.push(dest_href_part);
485 }
486 let loline = span.lo(self.sess()).line;
487 let hiline = span.hi(self.sess()).line;
488 format!(
489 "{}{}#{}",
490 "../".repeat(cur_href_parts.count()),
491 url.finish(),
492 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
493 )
494 })
495 }
496}
497
498impl<'tcx> Context<'tcx> {
499 pub(crate) fn init(
500 krate: clean::Crate,
501 options: RenderOptions,
502 cache: Cache,
503 tcx: TyCtxt<'tcx>,
504 expanded_codes: FxHashMap<BytePos, Vec<ExpandedCode>>,
505 ) -> Result<(Self, clean::Crate), Error> {
506 let md_opts = options.clone();
508 let RenderOptions {
509 output,
510 external_html,
511 id_map,
512 playground_url,
513 module_sorting,
514 themes: style_files,
515 default_settings,
516 extension_css,
517 resource_suffix,
518 static_root_path,
519 generate_redirect_map,
520 show_type_layout,
521 emit,
522 generate_link_to_definition,
523 call_locations,
524 no_emit_shared,
525 html_no_source,
526 ..
527 } = options;
528
529 let src_root = match krate.src(tcx) {
530 FileName::Real(ref p) => {
531 match p
532 .local_path()
533 .unwrap_or(p.path(RemapPathScopeComponents::DOCUMENTATION))
534 .parent()
535 {
536 Some(p) => p.to_path_buf(),
537 None => PathBuf::new(),
538 }
539 }
540 _ => PathBuf::new(),
541 };
542 let mut playground = None;
544 if let Some(url) = playground_url {
545 playground = Some(markdown::Playground { crate_name: Some(krate.name(tcx)), url });
546 }
547 let krate_version = cache.crate_version.as_deref().unwrap_or_default();
548 let mut layout = layout::Layout {
549 logo: String::new(),
550 favicon: String::new(),
551 external_html,
552 default_settings,
553 krate: krate.name(tcx).to_string(),
554 krate_version: krate_version.to_string(),
555 css_file_extension: extension_css,
556 scrape_examples_extension: !call_locations.is_empty(),
557 };
558 let mut issue_tracker_base_url = None;
559 let mut include_sources = !html_no_source;
560
561 for attr in &krate.module.attrs.other_attrs {
564 let Attribute::Parsed(AttributeKind::Doc(d)) = attr else { continue };
565 if let Some((html_favicon_url, _)) = d.html_favicon_url {
566 layout.favicon = html_favicon_url.to_string();
567 }
568 if let Some((html_logo_url, _)) = d.html_logo_url {
569 layout.logo = html_logo_url.to_string();
570 }
571 if let Some((html_playground_url, _)) = d.html_playground_url {
572 playground = Some(markdown::Playground {
573 crate_name: Some(krate.name(tcx)),
574 url: html_playground_url.to_string(),
575 });
576 }
577 if let Some((s, _)) = d.issue_tracker_base_url {
578 issue_tracker_base_url = Some(s.to_string());
579 }
580 if d.html_no_source.is_some() {
581 include_sources = false;
582 }
583 }
584
585 let (local_sources, matches) = collect_spans_and_sources(
586 tcx,
587 &krate,
588 &src_root,
589 include_sources,
590 generate_link_to_definition,
591 );
592
593 let (sender, receiver) = channel();
594 let scx = SharedContext {
595 tcx,
596 src_root,
597 local_sources,
598 issue_tracker_base_url,
599 layout,
600 created_dirs: Default::default(),
601 module_sorting,
602 style_files,
603 resource_suffix,
604 static_root_path,
605 fs: DocFS::new(sender),
606 codes: ErrorCodes::from(options.unstable_features.is_nightly_build()),
607 playground,
608 all: RefCell::new(AllTypes::new()),
609 errors: receiver,
610 redirections: if generate_redirect_map { Some(Default::default()) } else { None },
611 show_type_layout,
612 span_correspondence_map: matches,
613 cache,
614 call_locations,
615 expanded_codes,
616 };
617
618 let dst = output;
619 scx.ensure_dir(&dst)?;
620
621 let mut cx = Context {
622 current: Vec::new(),
623 dst,
624 id_map: RefCell::new(id_map),
625 deref_id_map: Default::default(),
626 shared: scx,
627 types_with_notable_traits: RefCell::new(FxIndexSet::default()),
628 info: ContextInfo::new(include_sources),
629 };
630
631 if emit.contains(&EmitType::HtmlNonStaticFiles) {
632 sources::render(&mut cx, &krate)?;
633 }
634
635 if !no_emit_shared {
636 write_shared(&mut cx, &krate, &md_opts, tcx)?;
637 }
638
639 Ok((cx, krate))
640 }
641}
642
643impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
645 const DESCR: &'static str = "html";
646 const RUN_ON_MODULE: bool = true;
647 const NON_STATIC_FILE_EMIT_TYPE: EmitType = EmitType::HtmlNonStaticFiles;
648
649 type ModuleData = ContextInfo;
650
651 fn save_module_data(&mut self) -> Self::ModuleData {
652 self.deref_id_map.borrow_mut().clear();
653 self.id_map.borrow_mut().clear();
654 self.types_with_notable_traits.borrow_mut().clear();
655 self.info
656 }
657
658 fn restore_module_data(&mut self, info: Self::ModuleData) {
659 self.info = info;
660 }
661
662 fn after_krate(mut self) -> Result<(), Error> {
663 let crate_name = self.tcx().crate_name(LOCAL_CRATE);
664 let final_file = self.dst.join(crate_name.as_str()).join("all.html");
665
666 let shared = &self.shared;
667 let page = layout::Page {
668 title: "List of all items in this crate",
669 short_title: "All",
670 css_class: "mod sys",
671 root_path: "../",
672 static_root_path: shared.static_root_path.as_deref(),
673 description: "List of all items in this crate",
674 resource_suffix: &shared.resource_suffix,
675 rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), |d| d.rust_logo.is_some()),
676 };
677 let all = shared.all.replace(AllTypes::new());
678 let mut sidebar = String::new();
679
680 let blocks = sidebar_module_like(all.item_sections(), &mut IdMap::new(), ModuleLike::Crate);
682 let bar = Sidebar {
683 title_prefix: "",
684 title: "",
685 is_crate: false,
686 is_mod: false,
687 parent_is_crate: false,
688 blocks: vec![blocks],
689 path: String::new(),
690 };
691
692 bar.render_into(&mut sidebar).unwrap();
693
694 let v = layout::render(&shared.layout, &page, sidebar, all.print(), &shared.style_files);
695 shared.fs.write(final_file, v)?;
696
697 if let Some(ref redirections) = shared.redirections
698 && !redirections.borrow().is_empty()
699 {
700 let redirect_map_path = self.dst.join(crate_name.as_str()).join("redirect-map.json");
701 let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
702 shared.ensure_dir(&self.dst.join(crate_name.as_str()))?;
703 shared.fs.write(redirect_map_path, paths)?;
704 }
705
706 self.shared.fs.close();
708 let nb_errors = self.shared.errors.iter().map(|err| self.tcx().dcx().err(err)).count();
709 if nb_errors > 0 { Err(Error::new(io::Error::other("I/O error"), "")) } else { Ok(()) }
710 }
711
712 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> {
713 if !self.info.render_redirect_pages {
721 self.info.render_redirect_pages = item.is_stripped();
722 }
723 let item_name = item.name.unwrap();
724 self.dst.push(item_name.as_str());
725 self.current.push(item_name);
726
727 info!("Recursing into {}", self.dst.display());
728
729 if !item.is_stripped() {
730 let buf = self.render_item(item, true);
731 if !buf.is_empty() {
733 self.shared.ensure_dir(&self.dst)?;
734 let joint_dst = self.dst.join("index.html");
735 self.shared.fs.write(joint_dst, buf)?;
736 }
737 }
738 if !self.info.is_inside_inlined_module {
739 if let Some(def_id) = item.def_id()
740 && self.cache().inlined_items.contains(&def_id)
741 {
742 self.info.is_inside_inlined_module = true;
743 }
744 } else if !self.cache().document_hidden && item.is_doc_hidden() {
745 self.info.is_inside_inlined_module = false;
747 }
748
749 if !self.info.render_redirect_pages {
751 let (clean::StrippedItem(clean::ModuleItem(ref module))
752 | clean::ModuleItem(ref module)) = item.kind
753 else {
754 unreachable!()
755 };
756 let items = self.build_sidebar_items(module);
757 let js_dst = self.dst.join(format!("sidebar-items{}.js", self.shared.resource_suffix));
758 let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap());
759 self.shared.fs.write(js_dst, v)?;
760 }
761 Ok(())
762 }
763
764 fn mod_item_out(&mut self) -> Result<(), Error> {
765 info!("Recursed; leaving {}", self.dst.display());
766
767 self.dst.pop();
769 self.current.pop();
770 Ok(())
771 }
772
773 fn item(&mut self, item: &clean::Item) -> Result<(), Error> {
774 if !self.info.render_redirect_pages {
782 self.info.render_redirect_pages = item.is_stripped();
783 }
784
785 let buf = self.render_item(item, false);
786 if !buf.is_empty() {
788 if !self.info.render_redirect_pages {
789 self.shared.all.borrow_mut().append(full_path(self, item), &item);
790 }
791
792 let file_name = print_item_path(item).to_string();
793 self.shared.ensure_dir(&self.dst)?;
794 let joint_dst = self.dst.join(&file_name);
795 self.shared.fs.write(joint_dst, buf)?;
796 let item_type = item.type_();
799 if item_type == ItemType::Macro {
800 let name = item.name.as_ref().unwrap();
801 let redir_name = format!("{item_type}.{name}!.html");
802 if let Some(ref redirections) = self.shared.redirections {
803 let crate_name = &self.shared.layout.krate;
804 redirections.borrow_mut().insert(
805 format!("{crate_name}/{redir_name}"),
806 format!("{crate_name}/{file_name}"),
807 );
808 } else {
809 let v = layout::redirect(&file_name);
810 let redir_dst = self.dst.join(redir_name);
811 self.shared.fs.write(redir_dst, v)?;
812 }
813 }
814 }
815
816 Ok(())
817 }
818}