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