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};
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 href = RefCell::new(PathBuf::new());
422 sources::clean_path(
423 &src_root,
424 file,
425 |component| {
426 href.borrow_mut().push(component);
427 },
428 || {
429 href.borrow_mut().pop();
430 },
431 );
432
433 path = href.into_inner().to_string_lossy().into_owned();
434
435 if let Some(c) = path.as_bytes().last()
436 && *c != b'/'
437 {
438 path.push('/');
439 }
440
441 let mut fname = file.file_name().expect("source has no filename").to_os_string();
442 fname.push(".html");
443 path.push_str(&fname.to_string_lossy());
444 krate_sym = krate;
445 (krate_sym.as_str(), &path)
446 };
447
448 let anchor = if with_lines {
449 let loline = span.lo(self.sess()).line;
450 let hiline = span.hi(self.sess()).line;
451 format!(
452 "#{}",
453 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
454 )
455 } else {
456 "".to_string()
457 };
458 Some(format!(
459 "{root}src/{krate}/{path}{anchor}",
460 root = Escape(&root),
461 krate = krate,
462 path = path,
463 anchor = anchor
464 ))
465 }
466
467 pub(crate) fn href_from_span_relative(
468 &self,
469 span: clean::Span,
470 relative_to: &str,
471 ) -> Option<String> {
472 self.href_from_span(span, false).map(|s| {
473 let mut url = UrlPartsBuilder::new();
474 let mut dest_href_parts = s.split('/');
475 let mut cur_href_parts = relative_to.split('/');
476 for (cur_href_part, dest_href_part) in (&mut cur_href_parts).zip(&mut dest_href_parts) {
477 if cur_href_part != dest_href_part {
478 url.push(dest_href_part);
479 break;
480 }
481 }
482 for dest_href_part in dest_href_parts {
483 url.push(dest_href_part);
484 }
485 let loline = span.lo(self.sess()).line;
486 let hiline = span.hi(self.sess()).line;
487 format!(
488 "{}{}#{}",
489 "../".repeat(cur_href_parts.count()),
490 url.finish(),
491 if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
492 )
493 })
494 }
495}
496
497impl<'tcx> Context<'tcx> {
498 pub(crate) fn init(
499 krate: clean::Crate,
500 options: RenderOptions,
501 cache: Cache,
502 tcx: TyCtxt<'tcx>,
503 expanded_codes: FxHashMap<BytePos, Vec<ExpandedCode>>,
504 ) -> Result<(Self, clean::Crate), Error> {
505 let md_opts = options.clone();
507 let RenderOptions {
508 output,
509 external_html,
510 id_map,
511 playground_url,
512 module_sorting,
513 themes: style_files,
514 default_settings,
515 extension_css,
516 resource_suffix,
517 static_root_path,
518 generate_redirect_map,
519 show_type_layout,
520 emit,
521 generate_link_to_definition,
522 call_locations,
523 no_emit_shared,
524 html_no_source,
525 ..
526 } = options;
527
528 let src_root = match krate.src(tcx) {
529 FileName::Real(ref p) => {
530 match p
531 .local_path()
532 .unwrap_or(p.path(RemapPathScopeComponents::DOCUMENTATION))
533 .parent()
534 {
535 Some(p) => p.to_path_buf(),
536 None => PathBuf::new(),
537 }
538 }
539 _ => PathBuf::new(),
540 };
541 let mut playground = None;
543 if let Some(url) = playground_url {
544 playground = Some(markdown::Playground { crate_name: Some(krate.name(tcx)), url });
545 }
546 let krate_version = cache.crate_version.as_deref().unwrap_or_default();
547 let mut layout = layout::Layout {
548 logo: String::new(),
549 favicon: String::new(),
550 external_html,
551 default_settings,
552 krate: krate.name(tcx).to_string(),
553 krate_version: krate_version.to_string(),
554 css_file_extension: extension_css,
555 scrape_examples_extension: !call_locations.is_empty(),
556 };
557 let mut issue_tracker_base_url = None;
558 let mut include_sources = !html_no_source;
559
560 for attr in &krate.module.attrs.other_attrs {
563 let Attribute::Parsed(AttributeKind::Doc(d)) = attr else { continue };
564 if let Some((html_favicon_url, _)) = d.html_favicon_url {
565 layout.favicon = html_favicon_url.to_string();
566 }
567 if let Some((html_logo_url, _)) = d.html_logo_url {
568 layout.logo = html_logo_url.to_string();
569 }
570 if let Some((html_playground_url, _)) = d.html_playground_url {
571 playground = Some(markdown::Playground {
572 crate_name: Some(krate.name(tcx)),
573 url: html_playground_url.to_string(),
574 });
575 }
576 if let Some((s, _)) = d.issue_tracker_base_url {
577 issue_tracker_base_url = Some(s.to_string());
578 }
579 if d.html_no_source.is_some() {
580 include_sources = false;
581 }
582 }
583
584 let (local_sources, matches) = collect_spans_and_sources(
585 tcx,
586 &krate,
587 &src_root,
588 include_sources,
589 generate_link_to_definition,
590 );
591
592 let (sender, receiver) = channel();
593 let scx = SharedContext {
594 tcx,
595 src_root,
596 local_sources,
597 issue_tracker_base_url,
598 layout,
599 created_dirs: Default::default(),
600 module_sorting,
601 style_files,
602 resource_suffix,
603 static_root_path,
604 fs: DocFS::new(sender),
605 codes: ErrorCodes::from(options.unstable_features.is_nightly_build()),
606 playground,
607 all: RefCell::new(AllTypes::new()),
608 errors: receiver,
609 redirections: if generate_redirect_map { Some(Default::default()) } else { None },
610 show_type_layout,
611 span_correspondence_map: matches,
612 cache,
613 call_locations,
614 expanded_codes,
615 };
616
617 let dst = output;
618 scx.ensure_dir(&dst)?;
619
620 let mut cx = Context {
621 current: Vec::new(),
622 dst,
623 id_map: RefCell::new(id_map),
624 deref_id_map: Default::default(),
625 shared: scx,
626 types_with_notable_traits: RefCell::new(FxIndexSet::default()),
627 info: ContextInfo::new(include_sources),
628 };
629
630 if emit.contains(&EmitType::HtmlNonStaticFiles) {
631 sources::render(&mut cx, &krate)?;
632 }
633
634 if !no_emit_shared {
635 write_shared(&mut cx, &krate, &md_opts, tcx)?;
636 }
637
638 Ok((cx, krate))
639 }
640}
641
642impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
644 const DESCR: &'static str = "html";
645 const RUN_ON_MODULE: bool = true;
646 const NON_STATIC_FILE_EMIT_TYPE: EmitType = EmitType::HtmlNonStaticFiles;
647
648 type ModuleData = ContextInfo;
649
650 fn save_module_data(&mut self) -> Self::ModuleData {
651 self.deref_id_map.borrow_mut().clear();
652 self.id_map.borrow_mut().clear();
653 self.types_with_notable_traits.borrow_mut().clear();
654 self.info
655 }
656
657 fn restore_module_data(&mut self, info: Self::ModuleData) {
658 self.info = info;
659 }
660
661 fn after_krate(mut self) -> Result<(), Error> {
662 let crate_name = self.tcx().crate_name(LOCAL_CRATE);
663 let final_file = self.dst.join(crate_name.as_str()).join("all.html");
664
665 let shared = &self.shared;
666 let page = layout::Page {
667 title: "List of all items in this crate",
668 short_title: "All",
669 css_class: "mod sys",
670 root_path: "../",
671 static_root_path: shared.static_root_path.as_deref(),
672 description: "List of all items in this crate",
673 resource_suffix: &shared.resource_suffix,
674 rust_logo: has_doc_flag(self.tcx(), LOCAL_CRATE.as_def_id(), |d| d.rust_logo.is_some()),
675 };
676 let all = shared.all.replace(AllTypes::new());
677 let mut sidebar = String::new();
678
679 let blocks = sidebar_module_like(all.item_sections(), &mut IdMap::new(), ModuleLike::Crate);
681 let bar = Sidebar {
682 title_prefix: "",
683 title: "",
684 is_crate: false,
685 is_mod: false,
686 parent_is_crate: false,
687 blocks: vec![blocks],
688 path: String::new(),
689 };
690
691 bar.render_into(&mut sidebar).unwrap();
692
693 let v = layout::render(&shared.layout, &page, sidebar, all.print(), &shared.style_files);
694 shared.fs.write(final_file, v)?;
695
696 if let Some(ref redirections) = shared.redirections
697 && !redirections.borrow().is_empty()
698 {
699 let redirect_map_path = self.dst.join(crate_name.as_str()).join("redirect-map.json");
700 let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
701 shared.ensure_dir(&self.dst.join(crate_name.as_str()))?;
702 shared.fs.write(redirect_map_path, paths)?;
703 }
704
705 self.shared.fs.close();
707 let nb_errors = self.shared.errors.iter().map(|err| self.tcx().dcx().err(err)).count();
708 if nb_errors > 0 { Err(Error::new(io::Error::other("I/O error"), "")) } else { Ok(()) }
709 }
710
711 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> {
712 if !self.info.render_redirect_pages {
720 self.info.render_redirect_pages = item.is_stripped();
721 }
722 let item_name = item.name.unwrap();
723 self.dst.push(item_name.as_str());
724 self.current.push(item_name);
725
726 info!("Recursing into {}", self.dst.display());
727
728 if !item.is_stripped() {
729 let buf = self.render_item(item, true);
730 if !buf.is_empty() {
732 self.shared.ensure_dir(&self.dst)?;
733 let joint_dst = self.dst.join("index.html");
734 self.shared.fs.write(joint_dst, buf)?;
735 }
736 }
737 if !self.info.is_inside_inlined_module {
738 if let Some(def_id) = item.def_id()
739 && self.cache().inlined_items.contains(&def_id)
740 {
741 self.info.is_inside_inlined_module = true;
742 }
743 } else if !self.cache().document_hidden && item.is_doc_hidden() {
744 self.info.is_inside_inlined_module = false;
746 }
747
748 if !self.info.render_redirect_pages {
750 let (clean::StrippedItem(clean::ModuleItem(ref module))
751 | clean::ModuleItem(ref module)) = item.kind
752 else {
753 unreachable!()
754 };
755 let items = self.build_sidebar_items(module);
756 let js_dst = self.dst.join(format!("sidebar-items{}.js", self.shared.resource_suffix));
757 let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap());
758 self.shared.fs.write(js_dst, v)?;
759 }
760 Ok(())
761 }
762
763 fn mod_item_out(&mut self) -> Result<(), Error> {
764 info!("Recursed; leaving {}", self.dst.display());
765
766 self.dst.pop();
768 self.current.pop();
769 Ok(())
770 }
771
772 fn item(&mut self, item: &clean::Item) -> Result<(), Error> {
773 if !self.info.render_redirect_pages {
781 self.info.render_redirect_pages = item.is_stripped();
782 }
783
784 let buf = self.render_item(item, false);
785 if !buf.is_empty() {
787 if !self.info.render_redirect_pages {
788 self.shared.all.borrow_mut().append(full_path(self, item), &item);
789 }
790
791 let file_name = print_item_path(item).to_string();
792 self.shared.ensure_dir(&self.dst)?;
793 let joint_dst = self.dst.join(&file_name);
794 self.shared.fs.write(joint_dst, buf)?;
795 let item_type = item.type_();
798 if item_type == ItemType::Macro {
799 let name = item.name.as_ref().unwrap();
800 let redir_name = format!("{item_type}.{name}!.html");
801 if let Some(ref redirections) = self.shared.redirections {
802 let crate_name = &self.shared.layout.krate;
803 redirections.borrow_mut().insert(
804 format!("{crate_name}/{redir_name}"),
805 format!("{crate_name}/{file_name}"),
806 );
807 } else {
808 let v = layout::redirect(&file_name);
809 let redir_dst = self.dst.join(redir_name);
810 self.shared.fs.write(redir_dst, v)?;
811 }
812 }
813 }
814
815 Ok(())
816 }
817}