1 use std::cell::RefCell;
2 use std::collections::BTreeMap;
3 use std::io;
4 use std::path::{Path, PathBuf};
5 use std::rc::Rc;
6 use std::sync::mpsc::{channel, Receiver};
7
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::symbol::sym;
15
16 use super::cache::{build_index, ExternalLocation};
17 use super::print_item::{full_path, item_path, print_item};
18 use super::templates;
19 use super::write_shared::write_shared;
20 use super::{
21 collect_spans_and_sources, print_sidebar, settings, AllTypes, LinkFromSrc, NameDoc, StylePath,
22 BASIC_KEYWORDS,
23 };
24
25 use crate::clean::{self, ExternalCrate};
26 use crate::config::RenderOptions;
27 use crate::docfs::{DocFS, PathError};
28 use crate::error::Error;
29 use crate::formats::cache::Cache;
30 use crate::formats::item_type::ItemType;
31 use crate::formats::FormatRenderer;
32 use crate::html::escape::Escape;
33 use crate::html::format::Buffer;
34 use crate::html::markdown::{self, plain_text_summary, ErrorCodes, IdMap};
35 use crate::html::{layout, sources};
36 use crate::scrape_examples::AllCallLocations;
37 use crate::try_err;
38
39 /// Major driving force in all rustdoc rendering. This contains information
40 /// about where in the tree-like hierarchy rendering is occurring and controls
41 /// how the current page is being rendered.
42 ///
43 /// It is intended that this context is a lightweight object which can be fairly
44 /// easily cloned because it is cloned per work-job (about once per item in the
45 /// rustdoc tree).
46 crate struct Context<'tcx> {
47 /// Current hierarchy of components leading down to what's currently being
48 /// rendered
49 pub(crate) current: Vec<String>,
50 /// The current destination folder of where HTML artifacts should be placed.
51 /// This changes as the context descends into the module hierarchy.
52 crate dst: PathBuf,
53 /// A flag, which when `true`, will render pages which redirect to the
54 /// real location of an item. This is used to allow external links to
55 /// publicly reused items to redirect to the right location.
56 pub(super) render_redirect_pages: bool,
57 /// Tracks section IDs for `Deref` targets so they match in both the main
58 /// body and the sidebar.
59 pub(super) deref_id_map: RefCell<FxHashMap<DefId, String>>,
60 /// The map used to ensure all generated 'id=' attributes are unique.
61 pub(super) id_map: RefCell<IdMap>,
62 /// Shared mutable state.
63 ///
64 /// Issue for improving the situation: [#82381][]
65 ///
66 /// [#82381]: https://github.com/rust-lang/rust/issues/82381
67 crate shared: Rc<SharedContext<'tcx>>,
68 /// This flag indicates whether `[src]` links should be generated or not. If
69 /// the source files are present in the html rendering, then this will be
70 /// `true`.
71 crate include_sources: bool,
72 }
73
74 // `Context` is cloned a lot, so we don't want the size to grow unexpectedly.
75 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
76 rustc_data_structures::static_assert_size!(Context<'_>, 144);
77
78 /// Shared mutable state used in [`Context`] and elsewhere.
79 crate struct SharedContext<'tcx> {
80 crate tcx: TyCtxt<'tcx>,
81 /// The path to the crate root source minus the file name.
82 /// Used for simplifying paths to the highlighted source code files.
83 crate src_root: PathBuf,
84 /// This describes the layout of each page, and is not modified after
85 /// creation of the context (contains info like the favicon and added html).
86 crate layout: layout::Layout,
87 /// The local file sources we've emitted and their respective url-paths.
88 crate local_sources: FxHashMap<PathBuf, String>,
89 /// Show the memory layout of types in the docs.
90 pub(super) show_type_layout: bool,
91 /// Whether the collapsed pass ran
92 collapsed: bool,
93 /// The base-URL of the issue tracker for when an item has been tagged with
94 /// an issue number.
95 pub(super) issue_tracker_base_url: Option<String>,
96 /// The directories that have already been created in this doc run. Used to reduce the number
97 /// of spurious `create_dir_all` calls.
98 created_dirs: RefCell<FxHashSet<PathBuf>>,
99 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
100 /// should be ordered alphabetically or in order of appearance (in the source code).
101 pub(super) sort_modules_alphabetically: bool,
102 /// Additional CSS files to be added to the generated docs.
103 crate style_files: Vec<StylePath>,
104 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
105 /// "light-v2.css").
106 crate resource_suffix: String,
107 /// Optional path string to be used to load static files on output pages. If not set, uses
108 /// combinations of `../` to reach the documentation root.
109 crate static_root_path: Option<String>,
110 /// The fs handle we are working with.
111 crate fs: DocFS,
112 pub(super) codes: ErrorCodes,
113 pub(super) playground: Option<markdown::Playground>,
114 all: RefCell<AllTypes>,
115 /// Storage for the errors produced while generating documentation so they
116 /// can be printed together at the end.
117 errors: Receiver<String>,
118 /// `None` by default, depends on the `generate-redirect-map` option flag. If this field is set
119 /// to `Some(...)`, it'll store redirections and then generate a JSON file at the top level of
120 /// the crate.
121 redirections: Option<RefCell<FxHashMap<String, String>>>,
122
123 pub(crate) templates: tera::Tera,
124
125 /// Correspondance map used to link types used in the source code pages to allow to click on
126 /// links to jump to the type's definition.
127 crate span_correspondance_map: FxHashMap<rustc_span::Span, LinkFromSrc>,
128 /// The [`Cache`] used during rendering.
129 crate cache: Cache,
130
131 crate call_locations: AllCallLocations,
132 }
133
134 impl SharedContext<'_> {
ensure_dir(&self, dst: &Path) -> Result<(), Error>135 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
136 let mut dirs = self.created_dirs.borrow_mut();
137 if !dirs.contains(dst) {
138 try_err!(self.fs.create_dir_all(dst), dst);
139 dirs.insert(dst.to_path_buf());
140 }
141
142 Ok(())
143 }
144
145 /// Returns the `collapsed_doc_value` of the given item if this is the main crate, otherwise
146 /// returns the `doc_value`.
maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String>147 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> {
148 if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() }
149 }
150
edition(&self) -> Edition151 crate fn edition(&self) -> Edition {
152 self.tcx.sess.edition()
153 }
154 }
155
156 impl<'tcx> Context<'tcx> {
tcx(&self) -> TyCtxt<'tcx>157 pub(crate) fn tcx(&self) -> TyCtxt<'tcx> {
158 self.shared.tcx
159 }
160
cache(&self) -> &Cache161 pub(crate) fn cache(&self) -> &Cache {
162 &self.shared.cache
163 }
164
sess(&self) -> &'tcx Session165 pub(super) fn sess(&self) -> &'tcx Session {
166 self.shared.tcx.sess
167 }
168
derive_id(&self, id: String) -> String169 pub(super) fn derive_id(&self, id: String) -> String {
170 let mut map = self.id_map.borrow_mut();
171 map.derive(id)
172 }
173
174 /// String representation of how to get back to the root path of the 'doc/'
175 /// folder in terms of a relative URL.
root_path(&self) -> String176 pub(super) fn root_path(&self) -> String {
177 "../".repeat(self.current.len())
178 }
179
render_item(&self, it: &clean::Item, is_module: bool) -> String180 fn render_item(&self, it: &clean::Item, is_module: bool) -> String {
181 let mut title = String::new();
182 if !is_module {
183 title.push_str(&it.name.unwrap().as_str());
184 }
185 if !it.is_primitive() && !it.is_keyword() {
186 if !is_module {
187 title.push_str(" in ");
188 }
189 // No need to include the namespace for primitive types and keywords
190 title.push_str(&self.current.join("::"));
191 };
192 title.push_str(" - Rust");
193 let tyname = it.type_();
194 let desc = it.doc_value().as_ref().map(|doc| plain_text_summary(doc));
195 let desc = if let Some(desc) = desc {
196 desc
197 } else if it.is_crate() {
198 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
199 } else {
200 format!(
201 "API documentation for the Rust `{}` {} in crate `{}`.",
202 it.name.as_ref().unwrap(),
203 tyname,
204 self.shared.layout.krate
205 )
206 };
207 let keywords = make_item_keywords(it);
208 let name;
209 let tyname_s = if it.is_crate() {
210 name = format!("{} crate", tyname);
211 name.as_str()
212 } else {
213 tyname.as_str()
214 };
215 let page = layout::Page {
216 css_class: tyname_s,
217 root_path: &self.root_path(),
218 static_root_path: self.shared.static_root_path.as_deref(),
219 title: &title,
220 description: &desc,
221 keywords: &keywords,
222 resource_suffix: &self.shared.resource_suffix,
223 extra_scripts: &[],
224 static_extra_scripts: &[],
225 };
226
227 if !self.render_redirect_pages {
228 layout::render(
229 &self.shared.templates,
230 &self.shared.layout,
231 &page,
232 |buf: &mut _| print_sidebar(self, it, buf),
233 |buf: &mut _| print_item(self, &self.shared.templates, it, buf, &page),
234 &self.shared.style_files,
235 )
236 } else {
237 if let Some(&(ref names, ty)) = self.cache().paths.get(&it.def_id.expect_def_id()) {
238 let mut path = String::new();
239 for name in &names[..names.len() - 1] {
240 path.push_str(name);
241 path.push('/');
242 }
243 path.push_str(&item_path(ty, names.last().unwrap()));
244 match self.shared.redirections {
245 Some(ref redirections) => {
246 let mut current_path = String::new();
247 for name in &self.current {
248 current_path.push_str(name);
249 current_path.push('/');
250 }
251 current_path.push_str(&item_path(ty, names.last().unwrap()));
252 redirections.borrow_mut().insert(current_path, path);
253 }
254 None => return layout::redirect(&format!("{}{}", self.root_path(), path)),
255 }
256 }
257 String::new()
258 }
259 }
260
261 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>>262 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
263 // BTreeMap instead of HashMap to get a sorted output
264 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
265 for item in &m.items {
266 if item.is_stripped() {
267 continue;
268 }
269
270 let short = item.type_();
271 let myname = match item.name {
272 None => continue,
273 Some(ref s) => s.to_string(),
274 };
275 let short = short.to_string();
276 map.entry(short).or_default().push((
277 myname,
278 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
279 ));
280 }
281
282 if self.shared.sort_modules_alphabetically {
283 for items in map.values_mut() {
284 items.sort();
285 }
286 }
287 map
288 }
289
290 /// Generates a url appropriate for an `href` attribute back to the source of
291 /// this item.
292 ///
293 /// The url generated, when clicked, will redirect the browser back to the
294 /// original source code.
295 ///
296 /// If `None` is returned, then a source link couldn't be generated. This
297 /// may happen, for example, with externally inlined items where the source
298 /// of their crate documentation isn't known.
src_href(&self, item: &clean::Item) -> Option<String>299 pub(super) fn src_href(&self, item: &clean::Item) -> Option<String> {
300 self.href_from_span(item.span(self.tcx()), true)
301 }
302
href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String>303 crate fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> {
304 if span.is_dummy() {
305 return None;
306 }
307 let mut root = self.root_path();
308 let mut path = String::new();
309 let cnum = span.cnum(self.sess());
310
311 // We can safely ignore synthetic `SourceFile`s.
312 let file = match span.filename(self.sess()) {
313 FileName::Real(ref path) => path.local_path_if_available().to_path_buf(),
314 _ => return None,
315 };
316 let file = &file;
317
318 let symbol;
319 let (krate, path) = if cnum == LOCAL_CRATE {
320 if let Some(path) = self.shared.local_sources.get(file) {
321 (self.shared.layout.krate.as_str(), path)
322 } else {
323 return None;
324 }
325 } else {
326 let (krate, src_root) = match *self.cache().extern_locations.get(&cnum)? {
327 ExternalLocation::Local => {
328 let e = ExternalCrate { crate_num: cnum };
329 (e.name(self.tcx()), e.src_root(self.tcx()))
330 }
331 ExternalLocation::Remote(ref s) => {
332 root = s.to_string();
333 let e = ExternalCrate { crate_num: cnum };
334 (e.name(self.tcx()), e.src_root(self.tcx()))
335 }
336 ExternalLocation::Unknown => return None,
337 };
338
339 sources::clean_path(&src_root, file, false, |component| {
340 path.push_str(&component.to_string_lossy());
341 path.push('/');
342 });
343 let mut fname = file.file_name().expect("source has no filename").to_os_string();
344 fname.push(".html");
345 path.push_str(&fname.to_string_lossy());
346 symbol = krate.as_str();
347 (&*symbol, &path)
348 };
349
350 let anchor = if with_lines {
351 let loline = span.lo(self.sess()).line;
352 let hiline = span.hi(self.sess()).line;
353 format!(
354 "#{}",
355 if loline == hiline {
356 loline.to_string()
357 } else {
358 format!("{}-{}", loline, hiline)
359 }
360 )
361 } else {
362 "".to_string()
363 };
364 Some(format!(
365 "{root}src/{krate}/{path}{anchor}",
366 root = Escape(&root),
367 krate = krate,
368 path = path,
369 anchor = anchor
370 ))
371 }
372 }
373
374 /// Generates the documentation for `crate` into the directory `dst`
375 impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
descr() -> &'static str376 fn descr() -> &'static str {
377 "html"
378 }
379
380 const RUN_ON_MODULE: bool = true;
381
init( krate: clean::Crate, options: RenderOptions, cache: Cache, tcx: TyCtxt<'tcx>, ) -> Result<(Self, clean::Crate), Error>382 fn init(
383 krate: clean::Crate,
384 options: RenderOptions,
385 cache: Cache,
386 tcx: TyCtxt<'tcx>,
387 ) -> Result<(Self, clean::Crate), Error> {
388 // need to save a copy of the options for rendering the index page
389 let md_opts = options.clone();
390 let emit_crate = options.should_emit_crate();
391 let RenderOptions {
392 output,
393 external_html,
394 id_map,
395 playground_url,
396 sort_modules_alphabetically,
397 themes: style_files,
398 default_settings,
399 extension_css,
400 resource_suffix,
401 static_root_path,
402 generate_search_filter,
403 unstable_features,
404 generate_redirect_map,
405 show_type_layout,
406 generate_link_to_definition,
407 call_locations,
408 ..
409 } = options;
410
411 let src_root = match krate.src(tcx) {
412 FileName::Real(ref p) => match p.local_path_if_available().parent() {
413 Some(p) => p.to_path_buf(),
414 None => PathBuf::new(),
415 },
416 _ => PathBuf::new(),
417 };
418 // If user passed in `--playground-url` arg, we fill in crate name here
419 let mut playground = None;
420 if let Some(url) = playground_url {
421 playground =
422 Some(markdown::Playground { crate_name: Some(krate.name(tcx).to_string()), url });
423 }
424 let mut layout = layout::Layout {
425 logo: String::new(),
426 favicon: String::new(),
427 external_html,
428 default_settings,
429 krate: krate.name(tcx).to_string(),
430 css_file_extension: extension_css,
431 generate_search_filter,
432 scrape_examples_extension: !call_locations.is_empty(),
433 };
434 let mut issue_tracker_base_url = None;
435 let mut include_sources = true;
436 let templates = templates::load()?;
437
438 // Crawl the crate attributes looking for attributes which control how we're
439 // going to emit HTML
440 for attr in krate.module.attrs.lists(sym::doc) {
441 match (attr.name_or_empty(), attr.value_str()) {
442 (sym::html_favicon_url, Some(s)) => {
443 layout.favicon = s.to_string();
444 }
445 (sym::html_logo_url, Some(s)) => {
446 layout.logo = s.to_string();
447 }
448 (sym::html_playground_url, Some(s)) => {
449 playground = Some(markdown::Playground {
450 crate_name: Some(krate.name(tcx).to_string()),
451 url: s.to_string(),
452 });
453 }
454 (sym::issue_tracker_base_url, Some(s)) => {
455 issue_tracker_base_url = Some(s.to_string());
456 }
457 (sym::html_no_source, None) if attr.is_word() => {
458 include_sources = false;
459 }
460 _ => {}
461 }
462 }
463
464 let (local_sources, matches) = collect_spans_and_sources(
465 tcx,
466 &krate,
467 &src_root,
468 include_sources,
469 generate_link_to_definition,
470 );
471
472 let (sender, receiver) = channel();
473 let mut scx = SharedContext {
474 tcx,
475 collapsed: krate.collapsed,
476 src_root,
477 local_sources,
478 issue_tracker_base_url,
479 layout,
480 created_dirs: Default::default(),
481 sort_modules_alphabetically,
482 style_files,
483 resource_suffix,
484 static_root_path,
485 fs: DocFS::new(sender),
486 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
487 playground,
488 all: RefCell::new(AllTypes::new()),
489 errors: receiver,
490 redirections: if generate_redirect_map { Some(Default::default()) } else { None },
491 show_type_layout,
492 templates,
493 span_correspondance_map: matches,
494 cache,
495 call_locations,
496 };
497
498 // Add the default themes to the `Vec` of stylepaths
499 //
500 // Note that these must be added before `sources::render` is called
501 // so that the resulting source pages are styled
502 //
503 // `light.css` is not disabled because it is the stylesheet that stays loaded
504 // by the browser as the theme stylesheet. The theme system (hackily) works by
505 // changing the href to this stylesheet. All other themes are disabled to
506 // prevent rule conflicts
507 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
508 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
509 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
510
511 let dst = output;
512 scx.ensure_dir(&dst)?;
513
514 let mut cx = Context {
515 current: Vec::new(),
516 dst,
517 render_redirect_pages: false,
518 id_map: RefCell::new(id_map),
519 deref_id_map: RefCell::new(FxHashMap::default()),
520 shared: Rc::new(scx),
521 include_sources,
522 };
523
524 if emit_crate {
525 sources::render(&mut cx, &krate)?;
526 }
527
528 // Build our search index
529 let index = build_index(&krate, &mut Rc::get_mut(&mut cx.shared).unwrap().cache, tcx);
530
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(&cx, &krate, index, &md_opts)?;
534 Rc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
535 Ok((cx, krate))
536 }
537
make_child_renderer(&self) -> Self538 fn make_child_renderer(&self) -> Self {
539 Self {
540 current: self.current.clone(),
541 dst: self.dst.clone(),
542 render_redirect_pages: self.render_redirect_pages,
543 deref_id_map: RefCell::new(FxHashMap::default()),
544 id_map: RefCell::new(IdMap::new()),
545 shared: Rc::clone(&self.shared),
546 include_sources: self.include_sources,
547 }
548 }
549
after_krate(&mut self) -> Result<(), Error>550 fn after_krate(&mut self) -> Result<(), Error> {
551 let crate_name = self.tcx().crate_name(LOCAL_CRATE);
552 let final_file = self.dst.join(&*crate_name.as_str()).join("all.html");
553 let settings_file = self.dst.join("settings.html");
554
555 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
556 if !root_path.ends_with('/') {
557 root_path.push('/');
558 }
559 let mut page = layout::Page {
560 title: "List of all items in this crate",
561 css_class: "mod",
562 root_path: "../",
563 static_root_path: self.shared.static_root_path.as_deref(),
564 description: "List of all items in this crate",
565 keywords: BASIC_KEYWORDS,
566 resource_suffix: &self.shared.resource_suffix,
567 extra_scripts: &[],
568 static_extra_scripts: &[],
569 };
570 let sidebar = if let Some(ref version) = self.shared.cache.crate_version {
571 format!(
572 "<h2 class=\"location\">Crate {}</h2>\
573 <div class=\"block version\">\
574 <p>Version {}</p>\
575 </div>\
576 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
577 crate_name,
578 Escape(version),
579 )
580 } else {
581 String::new()
582 };
583 let all = self.shared.all.replace(AllTypes::new());
584 let v = layout::render(
585 &self.shared.templates,
586 &self.shared.layout,
587 &page,
588 sidebar,
589 |buf: &mut Buffer| all.print(buf),
590 &self.shared.style_files,
591 );
592 self.shared.fs.write(final_file, v)?;
593
594 // Generating settings page.
595 page.title = "Rustdoc settings";
596 page.description = "Settings of Rustdoc";
597 page.root_path = "./";
598
599 let mut style_files = self.shared.style_files.clone();
600 let sidebar = "<h2 class=\"location\">Settings</h2><div class=\"sidebar-elems\"></div>";
601 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
602 let v = layout::render(
603 &self.shared.templates,
604 &self.shared.layout,
605 &page,
606 sidebar,
607 settings(
608 self.shared.static_root_path.as_deref().unwrap_or("./"),
609 &self.shared.resource_suffix,
610 &self.shared.style_files,
611 )?,
612 &style_files,
613 );
614 self.shared.fs.write(settings_file, v)?;
615 if let Some(ref redirections) = self.shared.redirections {
616 if !redirections.borrow().is_empty() {
617 let redirect_map_path =
618 self.dst.join(&*crate_name.as_str()).join("redirect-map.json");
619 let paths = serde_json::to_string(&*redirections.borrow()).unwrap();
620 self.shared.ensure_dir(&self.dst.join(&*crate_name.as_str()))?;
621 self.shared.fs.write(redirect_map_path, paths)?;
622 }
623 }
624
625 // Flush pending errors.
626 Rc::get_mut(&mut self.shared).unwrap().fs.close();
627 let nb_errors =
628 self.shared.errors.iter().map(|err| self.tcx().sess.struct_err(&err).emit()).count();
629 if nb_errors > 0 {
630 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
631 } else {
632 Ok(())
633 }
634 }
635
mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error>636 fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> {
637 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
638 // if they contain impls for public types. These modules can also
639 // contain items such as publicly re-exported structures.
640 //
641 // External crates will provide links to these structures, so
642 // these modules are recursed into, but not rendered normally
643 // (a flag on the context).
644 if !self.render_redirect_pages {
645 self.render_redirect_pages = item.is_stripped();
646 }
647 let scx = &self.shared;
648 let item_name = item.name.as_ref().unwrap().to_string();
649 self.dst.push(&item_name);
650 self.current.push(item_name);
651
652 info!("Recursing into {}", self.dst.display());
653
654 let buf = self.render_item(item, true);
655 // buf will be empty if the module is stripped and there is no redirect for it
656 if !buf.is_empty() {
657 self.shared.ensure_dir(&self.dst)?;
658 let joint_dst = self.dst.join("index.html");
659 scx.fs.write(joint_dst, buf)?;
660 }
661
662 // Render sidebar-items.js used throughout this module.
663 if !self.render_redirect_pages {
664 let module = match *item.kind {
665 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
666 _ => unreachable!(),
667 };
668 let items = self.build_sidebar_items(module);
669 let js_dst = self.dst.join("sidebar-items.js");
670 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
671 scx.fs.write(js_dst, v)?;
672 }
673 Ok(())
674 }
675
mod_item_out(&mut self) -> Result<(), Error>676 fn mod_item_out(&mut self) -> Result<(), Error> {
677 info!("Recursed; leaving {}", self.dst.display());
678
679 // Go back to where we were at
680 self.dst.pop();
681 self.current.pop();
682 Ok(())
683 }
684
item(&mut self, item: clean::Item) -> Result<(), Error>685 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
686 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
687 // if they contain impls for public types. These modules can also
688 // contain items such as publicly re-exported structures.
689 //
690 // External crates will provide links to these structures, so
691 // these modules are recursed into, but not rendered normally
692 // (a flag on the context).
693 if !self.render_redirect_pages {
694 self.render_redirect_pages = item.is_stripped();
695 }
696
697 let buf = self.render_item(&item, false);
698 // buf will be empty if the item is stripped and there is no redirect for it
699 if !buf.is_empty() {
700 let name = item.name.as_ref().unwrap();
701 let item_type = item.type_();
702 let file_name = &item_path(item_type, &name.as_str());
703 self.shared.ensure_dir(&self.dst)?;
704 let joint_dst = self.dst.join(file_name);
705 self.shared.fs.write(joint_dst, buf)?;
706
707 if !self.render_redirect_pages {
708 self.shared.all.borrow_mut().append(full_path(self, &item), &item_type);
709 }
710 // If the item is a macro, redirect from the old macro URL (with !)
711 // to the new one (without).
712 if item_type == ItemType::Macro {
713 let redir_name = format!("{}.{}!.html", item_type, name);
714 if let Some(ref redirections) = self.shared.redirections {
715 let crate_name = &self.shared.layout.krate;
716 redirections.borrow_mut().insert(
717 format!("{}/{}", crate_name, redir_name),
718 format!("{}/{}", crate_name, file_name),
719 );
720 } else {
721 let v = layout::redirect(file_name);
722 let redir_dst = self.dst.join(redir_name);
723 self.shared.fs.write(redir_dst, v)?;
724 }
725 }
726 }
727 Ok(())
728 }
729
cache(&self) -> &Cache730 fn cache(&self) -> &Cache {
731 &self.shared.cache
732 }
733 }
734
make_item_keywords(it: &clean::Item) -> String735 fn make_item_keywords(it: &clean::Item) -> String {
736 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
737 }
738