1 use std::cell::RefCell;
2 use std::collections::BTreeMap;
4 use std::path::PathBuf;
6 use std::sync::mpsc::channel;
8 use rustc_data_structures::fx::FxHashMap;
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::{symbol::sym, Symbol};
16 use super::cache::{build_index, ExternalLocation};
17 use super::print_item::{full_path, item_path, print_item};
18 use super::write_shared::write_shared;
20 print_sidebar, settings, AllTypes, NameDoc, SharedContext, StylePath, BASIC_KEYWORDS,
24 use crate::clean::{self, AttributesExt};
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::Buffer;
33 use crate::html::markdown::{self, plain_text_summary, ErrorCodes, IdMap};
34 use crate::html::{layout, sources};
36 /// Major driving force in all rustdoc rendering. This contains information
37 /// about where in the tree-like hierarchy rendering is occurring and controls
38 /// how the current page is being rendered.
40 /// It is intended that this context is a lightweight object which can be fairly
41 /// easily cloned because it is cloned per work-job (about once per item in the
43 crate struct Context<'tcx> {
44 /// Current hierarchy of components leading down to what's currently being
46 pub(super) current: Vec<String>,
47 /// The current destination folder of where HTML artifacts should be placed.
48 /// This changes as the context descends into the module hierarchy.
49 pub(super) dst: PathBuf,
50 /// A flag, which when `true`, will render pages which redirect to the
51 /// real location of an item. This is used to allow external links to
52 /// publicly reused items to redirect to the right location.
53 pub(super) render_redirect_pages: bool,
54 /// The map used to ensure all generated 'id=' attributes are unique.
55 pub(super) id_map: RefCell<IdMap>,
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: RefCell<FxHashMap<DefId, String>>,
59 /// Shared mutable state.
61 /// Issue for improving the situation: [#82381][]
63 /// [#82381]: https://github.com/rust-lang/rust/issues/82381
64 pub(super) shared: Rc<SharedContext<'tcx>>,
65 /// The [`Cache`] used during rendering.
67 /// Ideally the cache would be in [`SharedContext`], but it's mutated
68 /// between when the `SharedContext` is created and when `Context`
69 /// is created, so more refactoring would be needed.
71 /// It's immutable once in `Context`, so it's not as bad that it's not in
73 // FIXME: move `cache` to `SharedContext`
74 pub(super) cache: Rc<Cache>,
77 // `Context` is cloned a lot, so we don't want the size to grow unexpectedly.
78 #[cfg(target_arch = "x86_64")]
79 rustc_data_structures::static_assert_size!(Context<'_>, 152);
81 impl<'tcx> Context<'tcx> {
82 pub(super) fn tcx(&self) -> TyCtxt<'tcx> {
86 fn sess(&self) -> &'tcx Session {
90 pub(super) fn derive_id(&self, id: String) -> String {
91 let mut map = self.id_map.borrow_mut();
95 /// String representation of how to get back to the root path of the 'doc/'
96 /// folder in terms of a relative URL.
97 pub(super) fn root_path(&self) -> String {
98 "../".repeat(self.current.len())
101 fn render_item(&self, it: &clean::Item, pushname: bool) -> String {
102 // A little unfortunate that this is done like this, but it sure
103 // does make formatting *a lot* nicer.
104 CURRENT_DEPTH.with(|slot| {
105 slot.set(self.current.len());
108 let mut title = if it.is_primitive() || it.is_keyword() {
109 // No need to include the namespace for primitive types and keywords
112 self.current.join("::")
115 if !title.is_empty() {
116 title.push_str("::");
118 title.push_str(&it.name.unwrap().as_str());
120 title.push_str(" - Rust");
121 let tyname = it.type_();
122 let desc = it.doc_value().as_ref().map(|doc| plain_text_summary(&doc));
123 let desc = if let Some(desc) = desc {
125 } else if it.is_crate() {
126 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
129 "API documentation for the Rust `{}` {} in crate `{}`.",
130 it.name.as_ref().unwrap(),
132 self.shared.layout.krate
135 let keywords = make_item_keywords(it);
136 let page = layout::Page {
137 css_class: tyname.as_str(),
138 root_path: &self.root_path(),
139 static_root_path: self.shared.static_root_path.as_deref(),
143 resource_suffix: &self.shared.resource_suffix,
145 static_extra_scripts: &[],
148 if !self.render_redirect_pages {
152 |buf: &mut _| print_sidebar(self, it, buf),
153 |buf: &mut _| print_item(self, it, buf),
154 &self.shared.style_files,
157 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
158 let mut path = String::new();
159 for name in &names[..names.len() - 1] {
163 path.push_str(&item_path(ty, names.last().unwrap()));
164 match self.shared.redirections {
165 Some(ref redirections) => {
166 let mut current_path = String::new();
167 for name in &self.current {
168 current_path.push_str(name);
169 current_path.push('/');
171 current_path.push_str(&item_path(ty, names.last().unwrap()));
172 redirections.borrow_mut().insert(current_path, path);
174 None => return layout::redirect(&format!("{}{}", self.root_path(), path)),
181 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
182 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
183 // BTreeMap instead of HashMap to get a sorted output
184 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
185 for item in &m.items {
186 if item.is_stripped() {
190 let short = item.type_();
191 let myname = match item.name {
193 Some(ref s) => s.to_string(),
195 let short = short.to_string();
196 map.entry(short).or_default().push((
198 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
202 if self.shared.sort_modules_alphabetically {
203 for items in map.values_mut() {
210 /// Generates a url appropriate for an `href` attribute back to the source of
213 /// The url generated, when clicked, will redirect the browser back to the
214 /// original source code.
216 /// If `None` is returned, then a source link couldn't be generated. This
217 /// may happen, for example, with externally inlined items where the source
218 /// of their crate documentation isn't known.
219 pub(super) fn src_href(&self, item: &clean::Item) -> Option<String> {
220 if item.span.is_dummy() {
223 let mut root = self.root_path();
224 let mut path = String::new();
225 let cnum = item.span.cnum(self.sess());
227 // We can safely ignore synthetic `SourceFile`s.
228 let file = match item.span.filename(self.sess()) {
229 FileName::Real(ref path) => path.local_path().to_path_buf(),
235 let (krate, path) = if cnum == LOCAL_CRATE {
236 if let Some(path) = self.shared.local_sources.get(file) {
237 (self.shared.layout.krate.as_str(), path)
242 let (krate, src_root) = match *self.cache.extern_locations.get(&cnum)? {
243 (name, ref src, ExternalLocation::Local) => (name, src),
244 (name, ref src, ExternalLocation::Remote(ref s)) => {
245 root = s.to_string();
248 (_, _, ExternalLocation::Unknown) => return None,
251 sources::clean_path(&src_root, file, false, |component| {
252 path.push_str(&component.to_string_lossy());
255 let mut fname = file.file_name().expect("source has no filename").to_os_string();
257 path.push_str(&fname.to_string_lossy());
258 symbol = krate.as_str();
262 let loline = item.span.lo(self.sess()).line;
263 let hiline = item.span.hi(self.sess()).line;
265 if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
267 "{root}src/{krate}/{path}#{lines}",
268 root = Escape(&root),
276 /// Generates the documentation for `crate` into the directory `dst`
277 impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
278 fn descr() -> &'static str {
282 const RUN_ON_MODULE: bool = true;
285 mut krate: clean::Crate,
286 options: RenderOptions,
290 ) -> Result<(Self, clean::Crate), Error> {
291 // need to save a copy of the options for rendering the index page
292 let md_opts = options.clone();
293 let emit_crate = options.should_emit_crate();
299 sort_modules_alphabetically,
305 generate_search_filter,
307 generate_redirect_map,
311 let src_root = match krate.src {
312 FileName::Real(ref p) => match p.local_path().parent() {
313 Some(p) => p.to_path_buf(),
314 None => PathBuf::new(),
318 // If user passed in `--playground-url` arg, we fill in crate name here
319 let mut playground = None;
320 if let Some(url) = playground_url {
322 Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url });
324 let mut layout = layout::Layout {
326 favicon: String::new(),
329 krate: krate.name.to_string(),
330 css_file_extension: extension_css,
331 generate_search_filter,
333 let mut issue_tracker_base_url = None;
334 let mut include_sources = true;
336 // Crawl the crate attributes looking for attributes which control how we're
337 // going to emit HTML
338 for attr in krate.module.attrs.lists(sym::doc) {
339 match (attr.name_or_empty(), attr.value_str()) {
340 (sym::html_favicon_url, Some(s)) => {
341 layout.favicon = s.to_string();
343 (sym::html_logo_url, Some(s)) => {
344 layout.logo = s.to_string();
346 (sym::html_playground_url, Some(s)) => {
347 playground = Some(markdown::Playground {
348 crate_name: Some(krate.name.to_string()),
352 (sym::issue_tracker_base_url, Some(s)) => {
353 issue_tracker_base_url = Some(s.to_string());
355 (sym::html_no_source, None) if attr.is_word() => {
356 include_sources = false;
361 let (sender, receiver) = channel();
362 let mut scx = SharedContext {
364 collapsed: krate.collapsed,
367 local_sources: Default::default(),
368 issue_tracker_base_url,
370 created_dirs: Default::default(),
371 sort_modules_alphabetically,
375 fs: DocFS::new(sender),
377 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
379 all: RefCell::new(AllTypes::new()),
381 redirections: if generate_redirect_map { Some(Default::default()) } else { None },
384 // Add the default themes to the `Vec` of stylepaths
386 // Note that these must be added before `sources::render` is called
387 // so that the resulting source pages are styled
389 // `light.css` is not disabled because it is the stylesheet that stays loaded
390 // by the browser as the theme stylesheet. The theme system (hackily) works by
391 // changing the href to this stylesheet. All other themes are disabled to
392 // prevent rule conflicts
393 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
394 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
395 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
398 scx.ensure_dir(&dst)?;
400 krate = sources::render(&dst, &mut scx, krate)?;
403 // Build our search index
404 let index = build_index(&krate, &mut cache, tcx);
406 let mut cx = Context {
409 render_redirect_pages: false,
410 id_map: RefCell::new(id_map),
411 deref_id_map: RefCell::new(FxHashMap::default()),
412 shared: Rc::new(scx),
413 cache: Rc::new(cache),
416 CURRENT_DEPTH.with(|s| s.set(0));
418 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
419 Rc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
420 write_shared(&cx, &krate, index, &md_opts)?;
421 Rc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
425 fn make_child_renderer(&self) -> Self {
427 current: self.current.clone(),
428 dst: self.dst.clone(),
429 render_redirect_pages: self.render_redirect_pages,
430 id_map: RefCell::new(IdMap::new()),
431 deref_id_map: RefCell::new(FxHashMap::default()),
432 shared: Rc::clone(&self.shared),
433 cache: Rc::clone(&self.cache),
440 diag: &rustc_errors::Handler,
441 ) -> Result<(), Error> {
442 let final_file = self.dst.join(&*crate_name.as_str()).join("all.html");
443 let settings_file = self.dst.join("settings.html");
445 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
446 if !root_path.ends_with('/') {
449 let mut page = layout::Page {
450 title: "List of all items in this crate",
453 static_root_path: self.shared.static_root_path.as_deref(),
454 description: "List of all items in this crate",
455 keywords: BASIC_KEYWORDS,
456 resource_suffix: &self.shared.resource_suffix,
458 static_extra_scripts: &[],
460 let sidebar = if let Some(ref version) = self.cache.crate_version {
462 "<p class=\"location\">Crate {}</p>\
463 <div class=\"block version\">\
466 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
473 let all = self.shared.all.replace(AllTypes::new());
474 let v = layout::render(
478 |buf: &mut Buffer| all.print(buf),
479 &self.shared.style_files,
481 self.shared.fs.write(final_file, v.as_bytes())?;
483 // Generating settings page.
484 page.title = "Rustdoc settings";
485 page.description = "Settings of Rustdoc";
486 page.root_path = "./";
488 let mut style_files = self.shared.style_files.clone();
489 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
490 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
491 let v = layout::render(
496 self.shared.static_root_path.as_deref().unwrap_or("./"),
497 &self.shared.resource_suffix,
498 &self.shared.style_files,
502 self.shared.fs.write(&settings_file, v.as_bytes())?;
503 if let Some(ref redirections) = self.shared.redirections {
504 if !redirections.borrow().is_empty() {
505 let redirect_map_path =
506 self.dst.join(&*crate_name.as_str()).join("redirect-map.json");
507 let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
508 self.shared.ensure_dir(&self.dst.join(&*crate_name.as_str()))?;
509 self.shared.fs.write(&redirect_map_path, paths.as_bytes())?;
513 // Flush pending errors.
514 Rc::get_mut(&mut self.shared).unwrap().fs.close();
515 let nb_errors = self.shared.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
517 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
523 fn mod_item_in(&mut self, item: &clean::Item, item_name: &str) -> Result<(), Error> {
524 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
525 // if they contain impls for public types. These modules can also
526 // contain items such as publicly re-exported structures.
528 // External crates will provide links to these structures, so
529 // these modules are recursed into, but not rendered normally
530 // (a flag on the context).
531 if !self.render_redirect_pages {
532 self.render_redirect_pages = item.is_stripped();
534 let scx = &self.shared;
535 self.dst.push(item_name);
536 self.current.push(item_name.to_owned());
538 info!("Recursing into {}", self.dst.display());
540 let buf = self.render_item(item, false);
541 // buf will be empty if the module is stripped and there is no redirect for it
543 self.shared.ensure_dir(&self.dst)?;
544 let joint_dst = self.dst.join("index.html");
545 scx.fs.write(&joint_dst, buf.as_bytes())?;
548 // Render sidebar-items.js used throughout this module.
549 if !self.render_redirect_pages {
550 let module = match *item.kind {
551 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
554 let items = self.build_sidebar_items(module);
555 let js_dst = self.dst.join("sidebar-items.js");
556 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
557 scx.fs.write(&js_dst, &v)?;
562 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
563 info!("Recursed; leaving {}", self.dst.display());
565 // Go back to where we were at
571 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
572 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
573 // if they contain impls for public types. These modules can also
574 // contain items such as publicly re-exported structures.
576 // External crates will provide links to these structures, so
577 // these modules are recursed into, but not rendered normally
578 // (a flag on the context).
579 if !self.render_redirect_pages {
580 self.render_redirect_pages = item.is_stripped();
583 let buf = self.render_item(&item, true);
584 // buf will be empty if the item is stripped and there is no redirect for it
586 let name = item.name.as_ref().unwrap();
587 let item_type = item.type_();
588 let file_name = &item_path(item_type, &name.as_str());
589 self.shared.ensure_dir(&self.dst)?;
590 let joint_dst = self.dst.join(file_name);
591 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
593 if !self.render_redirect_pages {
594 self.shared.all.borrow_mut().append(full_path(self, &item), &item_type);
596 // If the item is a macro, redirect from the old macro URL (with !)
597 // to the new one (without).
598 if item_type == ItemType::Macro {
599 let redir_name = format!("{}.{}!.html", item_type, name);
600 if let Some(ref redirections) = self.shared.redirections {
601 let crate_name = &self.shared.layout.krate;
602 redirections.borrow_mut().insert(
603 format!("{}/{}", crate_name, redir_name),
604 format!("{}/{}", crate_name, file_name),
607 let v = layout::redirect(file_name);
608 let redir_dst = self.dst.join(redir_name);
609 self.shared.fs.write(&redir_dst, v.as_bytes())?;
616 fn cache(&self) -> &Cache {
621 fn make_item_keywords(it: &clean::Item) -> String {
622 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())