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