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