1 use std::cell::RefCell;
2 use std::collections::BTreeMap;
4 use std::path::{Path, PathBuf};
6 use std::sync::mpsc::{channel, Receiver};
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
10 use rustc_middle::ty::TyCtxt;
11 use rustc_session::Session;
12 use rustc_span::edition::Edition;
13 use rustc_span::source_map::FileName;
14 use rustc_span::{sym, Symbol};
16 use super::print_item::{full_path, item_path, print_item};
17 use super::search_index::build_index;
18 use super::write_shared::write_shared;
20 collect_spans_and_sources, print_sidebar, scrape_examples_help, AllTypes, LinkFromSrc, NameDoc,
21 StylePath, BASIC_KEYWORDS,
24 use crate::clean::{self, types::ExternalLocation, ExternalCrate};
25 use crate::config::RenderOptions;
26 use crate::docfs::{DocFS, PathError};
27 use crate::error::Error;
28 use crate::formats::cache::Cache;
29 use crate::formats::item_type::ItemType;
30 use crate::formats::FormatRenderer;
31 use crate::html::escape::Escape;
32 use crate::html::format::{join_with_double_colon, Buffer};
33 use crate::html::markdown::{self, plain_text_summary, ErrorCodes, IdMap};
34 use crate::html::{layout, sources};
35 use crate::scrape_examples::AllCallLocations;
38 /// Major driving force in all rustdoc rendering. This contains information
39 /// about where in the tree-like hierarchy rendering is occurring and controls
40 /// how the current page is being rendered.
42 /// It is intended that this context is a lightweight object which can be fairly
43 /// easily cloned because it is cloned per work-job (about once per item in the
45 pub(crate) struct Context<'tcx> {
46 /// Current hierarchy of components leading down to what's currently being
48 pub(crate) current: Vec<Symbol>,
49 /// The current destination folder of where HTML artifacts should be placed.
50 /// This changes as the context descends into the module hierarchy.
51 pub(crate) dst: PathBuf,
52 /// A flag, which when `true`, will render pages which redirect to the
53 /// real location of an item. This is used to allow external links to
54 /// publicly reused items to redirect to the right location.
55 pub(super) render_redirect_pages: bool,
56 /// Tracks section IDs for `Deref` targets so they match in both the main
57 /// body and the sidebar.
58 pub(super) deref_id_map: FxHashMap<DefId, String>,
59 /// The map used to ensure all generated 'id=' attributes are unique.
60 pub(super) id_map: IdMap,
61 /// Shared mutable state.
63 /// Issue for improving the situation: [#82381][]
65 /// [#82381]: https://github.com/rust-lang/rust/issues/82381
66 pub(crate) shared: Rc<SharedContext<'tcx>>,
67 /// This flag indicates whether source links should be generated or not. If
68 /// the source files are present in the html rendering, then this will be
70 pub(crate) include_sources: bool,
73 // `Context` is cloned a lot, so we don't want the size to grow unexpectedly.
74 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
75 rustc_data_structures::static_assert_size!(Context<'_>, 128);
77 /// Shared mutable state used in [`Context`] and elsewhere.
78 pub(crate) struct SharedContext<'tcx> {
79 pub(crate) tcx: TyCtxt<'tcx>,
80 /// The path to the crate root source minus the file name.
81 /// Used for simplifying paths to the highlighted source code files.
82 pub(crate) src_root: PathBuf,
83 /// This describes the layout of each page, and is not modified after
84 /// creation of the context (contains info like the favicon and added html).
85 pub(crate) layout: layout::Layout,
86 /// The local file sources we've emitted and their respective url-paths.
87 pub(crate) local_sources: FxHashMap<PathBuf, String>,
88 /// Show the memory layout of types in the docs.
89 pub(super) show_type_layout: bool,
90 /// The base-URL of the issue tracker for when an item has been tagged with
92 pub(super) issue_tracker_base_url: Option<String>,
93 /// The directories that have already been created in this doc run. Used to reduce the number
94 /// of spurious `create_dir_all` calls.
95 created_dirs: RefCell<FxHashSet<PathBuf>>,
96 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
97 /// should be ordered alphabetically or in order of appearance (in the source code).
98 pub(super) sort_modules_alphabetically: bool,
99 /// Additional CSS files to be added to the generated docs.
100 pub(crate) style_files: Vec<StylePath>,
101 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
103 pub(crate) resource_suffix: String,
104 /// Optional path string to be used to load static files on output pages. If not set, uses
105 /// combinations of `../` to reach the documentation root.
106 pub(crate) static_root_path: Option<String>,
107 /// The fs handle we are working with.
108 pub(crate) fs: DocFS,
109 pub(super) codes: ErrorCodes,
110 pub(super) playground: Option<markdown::Playground>,
111 all: RefCell<AllTypes>,
112 /// Storage for the errors produced while generating documentation so they
113 /// can be printed together at the end.
114 errors: Receiver<String>,
115 /// `None` by default, depends on the `generate-redirect-map` option flag. If this field is set
116 /// to `Some(...)`, it'll store redirections and then generate a JSON file at the top level of
118 redirections: Option<RefCell<FxHashMap<String, String>>>,
120 /// Correspondance map used to link types used in the source code pages to allow to click on
121 /// links to jump to the type's definition.
122 pub(crate) span_correspondance_map: FxHashMap<rustc_span::Span, LinkFromSrc>,
123 /// The [`Cache`] used during rendering.
124 pub(crate) cache: Cache,
126 pub(crate) call_locations: AllCallLocations,
129 impl SharedContext<'_> {
130 pub(crate) fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
131 let mut dirs = self.created_dirs.borrow_mut();
132 if !dirs.contains(dst) {
133 try_err!(self.fs.create_dir_all(dst), dst);
134 dirs.insert(dst.to_path_buf());
140 pub(crate) fn edition(&self) -> Edition {
141 self.tcx.sess.edition()
145 impl<'tcx> Context<'tcx> {
146 pub(crate) fn tcx(&self) -> TyCtxt<'tcx> {
150 pub(crate) fn cache(&self) -> &Cache {
154 pub(super) fn sess(&self) -> &'tcx Session {
158 pub(super) fn derive_id(&mut self, id: String) -> String {
159 self.id_map.derive(id)
162 /// String representation of how to get back to the root path of the 'doc/'
163 /// folder in terms of a relative URL.
164 pub(super) fn root_path(&self) -> String {
165 "../".repeat(self.current.len())
168 fn render_item(&mut self, it: &clean::Item, is_module: bool) -> String {
169 let mut title = String::new();
171 title.push_str(it.name.unwrap().as_str());
173 if !it.is_primitive() && !it.is_keyword() {
175 title.push_str(" in ");
177 // No need to include the namespace for primitive types and keywords
178 title.push_str(&join_with_double_colon(&self.current));
180 title.push_str(" - Rust");
181 let tyname = it.type_();
182 let desc = it.doc_value().as_ref().map(|doc| plain_text_summary(doc));
183 let desc = if let Some(desc) = desc {
185 } else if it.is_crate() {
186 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
189 "API documentation for the Rust `{}` {} in crate `{}`.",
190 it.name.as_ref().unwrap(),
192 self.shared.layout.krate
195 let keywords = make_item_keywords(it);
197 let tyname_s = if it.is_crate() {
198 name = format!("{} crate", tyname);
204 if !self.render_redirect_pages {
205 let clone_shared = Rc::clone(&self.shared);
206 let page = layout::Page {
208 root_path: &self.root_path(),
209 static_root_path: clone_shared.static_root_path.as_deref(),
213 resource_suffix: &clone_shared.resource_suffix,
215 static_extra_scripts: &[],
217 let mut page_buffer = Buffer::html();
218 print_item(self, it, &mut page_buffer, &page);
220 &clone_shared.layout,
222 |buf: &mut _| print_sidebar(self, it, buf),
223 move |buf: &mut Buffer| buf.push_buffer(page_buffer),
224 &clone_shared.style_files,
227 if let Some(&(ref names, ty)) = self.cache().paths.get(&it.item_id.expect_def_id()) {
228 if self.current.len() + 1 != names.len()
229 || self.current.iter().zip(names.iter()).any(|(a, b)| a != b)
231 // We checked that the redirection isn't pointing to the current file,
232 // preventing an infinite redirection loop in the generated
235 let mut path = String::new();
236 for name in &names[..names.len() - 1] {
237 path.push_str(name.as_str());
240 path.push_str(&item_path(ty, names.last().unwrap().as_str()));
241 match self.shared.redirections {
242 Some(ref redirections) => {
243 let mut current_path = String::new();
244 for name in &self.current {
245 current_path.push_str(name.as_str());
246 current_path.push('/');
248 current_path.push_str(&item_path(ty, names.last().unwrap().as_str()));
249 redirections.borrow_mut().insert(current_path, path);
251 None => return layout::redirect(&format!("{}{}", self.root_path(), path)),
259 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
260 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
261 // BTreeMap instead of HashMap to get a sorted output
262 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
263 let mut inserted: FxHashMap<ItemType, FxHashSet<Symbol>> = FxHashMap::default();
265 for item in &m.items {
266 if item.is_stripped() {
270 let short = item.type_();
271 let myname = match item.name {
275 if inserted.entry(short).or_default().insert(myname) {
276 let short = short.to_string();
277 let myname = myname.to_string();
278 map.entry(short).or_default().push((
280 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
285 if self.shared.sort_modules_alphabetically {
286 for items in map.values_mut() {
293 /// Generates a url appropriate for an `href` attribute back to the source of
296 /// The url generated, when clicked, will redirect the browser back to the
297 /// original source code.
299 /// If `None` is returned, then a source link couldn't be generated. This
300 /// may happen, for example, with externally inlined items where the source
301 /// of their crate documentation isn't known.
302 pub(super) fn src_href(&self, item: &clean::Item) -> Option<String> {
303 self.href_from_span(item.span(self.tcx()), true)
306 pub(crate) fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> {
310 let mut root = self.root_path();
311 let mut path = String::new();
312 let cnum = span.cnum(self.sess());
314 // We can safely ignore synthetic `SourceFile`s.
315 let file = match span.filename(self.sess()) {
316 FileName::Real(ref path) => path.local_path_if_available().to_path_buf(),
322 let (krate, path) = if cnum == LOCAL_CRATE {
323 if let Some(path) = self.shared.local_sources.get(file) {
324 (self.shared.layout.krate.as_str(), path)
329 let (krate, src_root) = match *self.cache().extern_locations.get(&cnum)? {
330 ExternalLocation::Local => {
331 let e = ExternalCrate { crate_num: cnum };
332 (e.name(self.tcx()), e.src_root(self.tcx()))
334 ExternalLocation::Remote(ref s) => {
335 root = s.to_string();
336 let e = ExternalCrate { crate_num: cnum };
337 (e.name(self.tcx()), e.src_root(self.tcx()))
339 ExternalLocation::Unknown => return None,
342 sources::clean_path(&src_root, file, false, |component| {
343 path.push_str(&component.to_string_lossy());
346 let mut fname = file.file_name().expect("source has no filename").to_os_string();
348 path.push_str(&fname.to_string_lossy());
350 (krate_sym.as_str(), &path)
353 let anchor = if with_lines {
354 let loline = span.lo(self.sess()).line;
355 let hiline = span.hi(self.sess()).line;
358 if loline == hiline {
361 format!("{}-{}", loline, hiline)
368 "{root}src/{krate}/{path}{anchor}",
369 root = Escape(&root),
377 /// Generates the documentation for `crate` into the directory `dst`
378 impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
379 fn descr() -> &'static str {
383 const RUN_ON_MODULE: bool = true;
387 options: RenderOptions,
390 ) -> Result<(Self, clean::Crate), Error> {
391 // need to save a copy of the options for rendering the index page
392 let md_opts = options.clone();
393 let emit_crate = options.should_emit_crate();
399 sort_modules_alphabetically,
406 generate_redirect_map,
408 generate_link_to_definition,
414 let src_root = match krate.src(tcx) {
415 FileName::Real(ref p) => match p.local_path_if_available().parent() {
416 Some(p) => p.to_path_buf(),
417 None => PathBuf::new(),
421 // If user passed in `--playground-url` arg, we fill in crate name here
422 let mut playground = None;
423 if let Some(url) = playground_url {
425 Some(markdown::Playground { crate_name: Some(krate.name(tcx).to_string()), url });
427 let mut layout = layout::Layout {
429 favicon: String::new(),
432 krate: krate.name(tcx).to_string(),
433 css_file_extension: extension_css,
434 scrape_examples_extension: !call_locations.is_empty(),
436 let mut issue_tracker_base_url = None;
437 let mut include_sources = true;
439 // Crawl the crate attributes looking for attributes which control how we're
440 // going to emit HTML
441 for attr in krate.module.attrs.lists(sym::doc) {
442 match (attr.name_or_empty(), attr.value_str()) {
443 (sym::html_favicon_url, Some(s)) => {
444 layout.favicon = s.to_string();
446 (sym::html_logo_url, Some(s)) => {
447 layout.logo = s.to_string();
449 (sym::html_playground_url, Some(s)) => {
450 playground = Some(markdown::Playground {
451 crate_name: Some(krate.name(tcx).to_string()),
455 (sym::issue_tracker_base_url, Some(s)) => {
456 issue_tracker_base_url = Some(s.to_string());
458 (sym::html_no_source, None) if attr.is_word() => {
459 include_sources = false;
465 let (local_sources, matches) = collect_spans_and_sources(
470 generate_link_to_definition,
473 let (sender, receiver) = channel();
474 let mut scx = SharedContext {
478 issue_tracker_base_url,
480 created_dirs: Default::default(),
481 sort_modules_alphabetically,
485 fs: DocFS::new(sender),
486 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
488 all: RefCell::new(AllTypes::new()),
490 redirections: if generate_redirect_map { Some(Default::default()) } else { None },
492 span_correspondance_map: matches,
497 // Add the default themes to the `Vec` of stylepaths
499 // Note that these must be added before `sources::render` is called
500 // so that the resulting source pages are styled
502 // `light.css` is not disabled because it is the stylesheet that stays loaded
503 // by the browser as the theme stylesheet. The theme system (hackily) works by
504 // changing the href to this stylesheet. All other themes are disabled to
505 // prevent rule conflicts
506 scx.style_files.push(StylePath { path: PathBuf::from("light.css") });
507 scx.style_files.push(StylePath { path: PathBuf::from("dark.css") });
508 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css") });
511 scx.ensure_dir(&dst)?;
513 let mut cx = Context {
516 render_redirect_pages: false,
518 deref_id_map: FxHashMap::default(),
519 shared: Rc::new(scx),
524 sources::render(&mut cx, &krate)?;
528 // Build our search index
529 let index = build_index(&krate, &mut Rc::get_mut(&mut cx.shared).unwrap().cache, tcx);
531 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
532 Rc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
533 write_shared(&mut cx, &krate, index, &md_opts)?;
534 Rc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
540 fn make_child_renderer(&self) -> Self {
542 current: self.current.clone(),
543 dst: self.dst.clone(),
544 render_redirect_pages: self.render_redirect_pages,
545 deref_id_map: FxHashMap::default(),
546 id_map: IdMap::new(),
547 shared: Rc::clone(&self.shared),
548 include_sources: self.include_sources,
552 fn after_krate(&mut self) -> Result<(), Error> {
553 let crate_name = self.tcx().crate_name(LOCAL_CRATE);
554 let final_file = self.dst.join(crate_name.as_str()).join("all.html");
555 let settings_file = self.dst.join("settings.html");
556 let scrape_examples_help_file = self.dst.join("scrape-examples-help.html");
558 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
559 if !root_path.ends_with('/') {
562 let shared = Rc::clone(&self.shared);
563 let mut page = layout::Page {
564 title: "List of all items in this crate",
567 static_root_path: shared.static_root_path.as_deref(),
568 description: "List of all items in this crate",
569 keywords: BASIC_KEYWORDS,
570 resource_suffix: &shared.resource_suffix,
572 static_extra_scripts: &[],
574 let sidebar = if shared.cache.crate_version.is_some() {
575 format!("<h2 class=\"location\">Crate {}</h2>", crate_name)
579 let all = shared.all.replace(AllTypes::new());
580 let v = layout::render(
584 |buf: &mut Buffer| all.print(buf),
587 shared.fs.write(final_file, v)?;
589 // Generating settings page.
590 page.title = "Rustdoc settings";
591 page.description = "Settings of Rustdoc";
592 page.root_path = "./";
594 let sidebar = "<h2 class=\"location\">Settings</h2><div class=\"sidebar-elems\"></div>";
595 let v = layout::render(
602 "<div class=\"main-heading\">\
604 <span class=\"in-band\">Rustdoc settings</span>\
606 <span class=\"out-of-band\">\
607 <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
614 You need to enable Javascript be able to update your settings.\
617 <link rel=\"stylesheet\" type=\"text/css\" \
618 href=\"{root_path}settings{suffix}.css\">\
619 <script defer src=\"{root_path}settings{suffix}.js\"></script>",
620 root_path = page.static_root_path.unwrap_or(""),
621 suffix = page.resource_suffix,
626 shared.fs.write(settings_file, v)?;
628 if shared.layout.scrape_examples_extension {
629 page.title = "About scraped examples";
630 page.description = "How the scraped examples feature works in Rustdoc";
631 let v = layout::render(
635 scrape_examples_help(&*shared),
638 shared.fs.write(scrape_examples_help_file, v)?;
641 if let Some(ref redirections) = shared.redirections {
642 if !redirections.borrow().is_empty() {
643 let redirect_map_path =
644 self.dst.join(crate_name.as_str()).join("redirect-map.json");
645 let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
646 shared.ensure_dir(&self.dst.join(crate_name.as_str()))?;
647 shared.fs.write(redirect_map_path, paths)?;
651 // No need for it anymore.
654 // Flush pending errors.
655 Rc::get_mut(&mut self.shared).unwrap().fs.close();
657 self.shared.errors.iter().map(|err| self.tcx().sess.struct_err(&err).emit()).count();
659 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
665 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> {
666 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
667 // if they contain impls for public types. These modules can also
668 // contain items such as publicly re-exported structures.
670 // External crates will provide links to these structures, so
671 // these modules are recursed into, but not rendered normally
672 // (a flag on the context).
673 if !self.render_redirect_pages {
674 self.render_redirect_pages = item.is_stripped();
676 let item_name = item.name.unwrap();
677 self.dst.push(&*item_name.as_str());
678 self.current.push(item_name);
680 info!("Recursing into {}", self.dst.display());
682 let buf = self.render_item(item, true);
683 // buf will be empty if the module is stripped and there is no redirect for it
685 self.shared.ensure_dir(&self.dst)?;
686 let joint_dst = self.dst.join("index.html");
687 self.shared.fs.write(joint_dst, buf)?;
690 // Render sidebar-items.js used throughout this module.
691 if !self.render_redirect_pages {
692 let (clean::StrippedItem(box clean::ModuleItem(ref module)) | clean::ModuleItem(ref module)) = *item.kind
693 else { unreachable!() };
694 let items = self.build_sidebar_items(module);
695 let js_dst = self.dst.join(&format!("sidebar-items{}.js", self.shared.resource_suffix));
696 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
697 self.shared.fs.write(js_dst, v)?;
702 fn mod_item_out(&mut self) -> Result<(), Error> {
703 info!("Recursed; leaving {}", self.dst.display());
705 // Go back to where we were at
711 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
712 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
713 // if they contain impls for public types. These modules can also
714 // contain items such as publicly re-exported structures.
716 // External crates will provide links to these structures, so
717 // these modules are recursed into, but not rendered normally
718 // (a flag on the context).
719 if !self.render_redirect_pages {
720 self.render_redirect_pages = item.is_stripped();
723 let buf = self.render_item(&item, false);
724 // buf will be empty if the item is stripped and there is no redirect for it
726 let name = item.name.as_ref().unwrap();
727 let item_type = item.type_();
728 let file_name = &item_path(item_type, name.as_str());
729 self.shared.ensure_dir(&self.dst)?;
730 let joint_dst = self.dst.join(file_name);
731 self.shared.fs.write(joint_dst, buf)?;
733 if !self.render_redirect_pages {
734 self.shared.all.borrow_mut().append(full_path(self, &item), &item_type);
736 // If the item is a macro, redirect from the old macro URL (with !)
737 // to the new one (without).
738 if item_type == ItemType::Macro {
739 let redir_name = format!("{}.{}!.html", item_type, name);
740 if let Some(ref redirections) = self.shared.redirections {
741 let crate_name = &self.shared.layout.krate;
742 redirections.borrow_mut().insert(
743 format!("{}/{}", crate_name, redir_name),
744 format!("{}/{}", crate_name, file_name),
747 let v = layout::redirect(file_name);
748 let redir_dst = self.dst.join(redir_name);
749 self.shared.fs.write(redir_dst, v)?;
756 fn cache(&self) -> &Cache {
761 fn make_item_keywords(it: &clean::Item) -> String {
762 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())