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