3 use std::fs::{self, File};
4 use std::io::prelude::*;
5 use std::io::{self, BufReader};
6 use std::lazy::SyncLazy as Lazy;
7 use std::path::{Component, Path, PathBuf};
9 use itertools::Itertools;
10 use rustc_data_structures::flock;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use super::{collect_paths_for_type, ensure_trailing_slash, Context, BASIC_KEYWORDS};
15 use crate::clean::Crate;
16 use crate::config::RenderOptions;
17 use crate::docfs::{DocFS, PathError};
18 use crate::error::Error;
19 use crate::formats::FormatRenderer;
20 use crate::html::{layout, static_files};
22 crate static FILES_UNVERSIONED: Lazy<FxHashMap<&str, &[u8]>> = Lazy::new(|| {
24 "FiraSans-Regular.woff2" => static_files::fira_sans::REGULAR2,
25 "FiraSans-Medium.woff2" => static_files::fira_sans::MEDIUM2,
26 "FiraSans-Regular.woff" => static_files::fira_sans::REGULAR,
27 "FiraSans-Medium.woff" => static_files::fira_sans::MEDIUM,
28 "FiraSans-LICENSE.txt" => static_files::fira_sans::LICENSE,
29 "SourceSerifPro-Regular.ttf.woff" => static_files::source_serif_pro::REGULAR,
30 "SourceSerifPro-Bold.ttf.woff" => static_files::source_serif_pro::BOLD,
31 "SourceSerifPro-It.ttf.woff" => static_files::source_serif_pro::ITALIC,
32 "SourceSerifPro-LICENSE.md" => static_files::source_serif_pro::LICENSE,
33 "SourceCodePro-Regular.woff" => static_files::source_code_pro::REGULAR,
34 "SourceCodePro-Semibold.woff" => static_files::source_code_pro::SEMIBOLD,
35 "SourceCodePro-LICENSE.txt" => static_files::source_code_pro::LICENSE,
36 "LICENSE-MIT.txt" => static_files::LICENSE_MIT,
37 "LICENSE-APACHE.txt" => static_files::LICENSE_APACHE,
38 "COPYRIGHT.txt" => static_files::COPYRIGHT,
42 pub(super) fn write_shared(
46 options: &RenderOptions,
47 ) -> Result<(), Error> {
48 // Write out the shared files. Note that these are shared among all rustdoc
49 // docs placed in the output directory, so this needs to be a synchronized
50 // operation with respect to all other rustdocs running around.
51 let lock_file = cx.dst.join(".lock");
52 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
54 // Add all the static files. These may already exist, but we just
55 // overwrite them anyway to make sure that they're fresh and up-to-date.
59 cx.path("rustdoc.css"),
60 static_files::RUSTDOC_CSS,
61 options.enable_minification,
65 cx.path("settings.css"),
66 static_files::SETTINGS_CSS,
67 options.enable_minification,
71 cx.path("noscript.css"),
72 static_files::NOSCRIPT_CSS,
73 options.enable_minification,
76 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
77 // then we'll run over the "official" styles.
78 let mut themes: FxHashSet<String> = FxHashSet::default();
80 for entry in &cx.shared.style_files {
81 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
83 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
85 // Handle the official themes
87 "light" => write_minify(
90 static_files::themes::LIGHT,
91 options.enable_minification,
93 "dark" => write_minify(
96 static_files::themes::DARK,
97 options.enable_minification,
99 "ayu" => write_minify(
102 static_files::themes::AYU,
103 options.enable_minification,
106 // Handle added third-party themes
107 let content = try_err!(fs::read(&entry.path), &entry.path);
110 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
114 themes.insert(theme.to_owned());
117 let write = |p, c| cx.shared.fs.write(p, c);
118 if (*cx.shared).layout.logo.is_empty() {
119 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
121 if (*cx.shared).layout.favicon.is_empty() {
122 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
123 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
124 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
126 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
127 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
128 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
130 let mut themes: Vec<&String> = themes.iter().collect();
132 // To avoid theme switch latencies as much as possible, we put everything theme related
133 // at the beginning of the html files into another js file.
134 let theme_js = format!(
135 r#"var themes = document.getElementById("theme-choices");
136 var themePicker = document.getElementById("theme-picker");
138 function showThemeButtonState() {{
139 themes.style.display = "block";
140 themePicker.style.borderBottomRightRadius = "0";
141 themePicker.style.borderBottomLeftRadius = "0";
144 function hideThemeButtonState() {{
145 themes.style.display = "none";
146 themePicker.style.borderBottomRightRadius = "3px";
147 themePicker.style.borderBottomLeftRadius = "3px";
150 function switchThemeButtonState() {{
151 if (themes.style.display === "block") {{
152 hideThemeButtonState();
154 showThemeButtonState();
158 function handleThemeButtonsBlur(e) {{
159 var active = document.activeElement;
160 var related = e.relatedTarget;
162 if (active.id !== "theme-picker" &&
163 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
165 (related.id !== "theme-picker" &&
166 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
167 hideThemeButtonState();
171 themePicker.onclick = switchThemeButtonState;
172 themePicker.onblur = handleThemeButtonsBlur;
173 {}.forEach(function(item) {{
174 var but = document.createElement("button");
175 but.textContent = item;
176 but.onclick = function(el) {{
177 switchTheme(currentTheme, mainTheme, item, true);
178 useSystemTheme(false);
180 but.onblur = handleThemeButtonsBlur;
181 themes.appendChild(but);
183 serde_json::to_string(&themes).unwrap()
186 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
190 static_files::MAIN_JS,
191 options.enable_minification,
195 cx.path("settings.js"),
196 static_files::SETTINGS_JS,
197 options.enable_minification,
199 if cx.shared.include_sources {
202 cx.path("source-script.js"),
203 static_files::sidebar::SOURCE_SCRIPT,
204 options.enable_minification,
211 cx.path("storage.js"),
213 "var resourcesSuffix = \"{}\";{}",
214 cx.shared.resource_suffix,
215 static_files::STORAGE_JS
217 options.enable_minification,
221 if let Some(ref css) = cx.shared.layout.css_file_extension {
222 let out = cx.path("theme.css");
223 let buffer = try_err!(fs::read_to_string(css), css);
224 if !options.enable_minification {
225 cx.shared.fs.write(&out, &buffer)?;
227 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
232 cx.path("normalize.css"),
233 static_files::NORMALIZE_CSS,
234 options.enable_minification,
236 for (file, contents) in &*FILES_UNVERSIONED {
237 write(cx.dst.join(file), contents)?;
240 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
241 let mut ret = Vec::new();
242 let mut krates = Vec::new();
245 let prefix = format!(r#"{}["{}"]"#, key, krate);
246 for line in BufReader::new(File::open(path)?).lines() {
248 if !line.starts_with(key) {
251 if line.starts_with(&prefix) {
254 ret.push(line.to_string());
256 line[key.len() + 2..]
259 .map(|s| s.to_owned())
260 .unwrap_or_else(String::new),
267 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
268 let mut ret = Vec::new();
269 let mut krates = Vec::new();
272 let prefix = format!("\"{}\"", krate);
273 for line in BufReader::new(File::open(path)?).lines() {
275 if !line.starts_with('"') {
278 if line.starts_with(&prefix) {
281 if line.ends_with(",\\") {
282 ret.push(line[..line.len() - 2].to_string());
284 // Ends with "\\" (it's the case for the last added crate line)
285 ret.push(line[..line.len() - 1].to_string());
289 .find(|s| !s.is_empty())
290 .map(|s| s.to_owned())
291 .unwrap_or_else(String::new),
298 use std::ffi::OsString;
303 children: FxHashMap<OsString, Hierarchy>,
304 elems: FxHashSet<OsString>,
308 fn new(elem: OsString) -> Hierarchy {
309 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
312 fn to_json_string(&self) -> String {
313 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
314 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
318 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
319 .collect::<Vec<_>>();
320 files.sort_unstable();
321 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
323 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
324 let files = files.join(",");
326 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
328 "{{\"name\":\"{name}\"{dirs}{files}}}",
329 name = self.elem.to_str().expect("invalid osstring conversion"),
336 if cx.shared.include_sources {
337 let mut hierarchy = Hierarchy::new(OsString::new());
342 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
344 let mut h = &mut hierarchy;
345 let mut elems = source
347 .filter_map(|s| match s {
348 Component::Normal(s) => Some(s.to_owned()),
353 let cur_elem = elems.next().expect("empty file path");
354 if elems.peek().is_none() {
355 h.elems.insert(cur_elem);
358 let e = cur_elem.clone();
359 h = h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
364 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
365 let (mut all_sources, _krates) =
366 try_err!(collect(&dst, &krate.name.as_str(), "sourcesIndex"), &dst);
367 all_sources.push(format!(
368 "sourcesIndex[\"{}\"] = {};",
370 hierarchy.to_json_string()
374 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
375 all_sources.join("\n")
377 cx.shared.fs.write(&dst, v.as_bytes())?;
380 // Update the search index and crate list.
381 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
382 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name.as_str()), &dst);
383 all_indexes.push(search_index);
384 krates.push(krate.name.to_string());
387 // Sort the indexes by crate so the file will be generated identically even
388 // with rustdoc running in parallel.
391 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
392 v.push_str(&all_indexes.join(",\\\n"));
393 v.push_str("\\\n}');\ninitSearch(searchIndex);");
394 cx.shared.fs.write(&dst, &v)?;
397 let crate_list_dst = cx.dst.join(&format!("crates{}.js", cx.shared.resource_suffix));
399 format!("window.ALL_CRATES = [{}];", krates.iter().map(|k| format!("\"{}\"", k)).join(","));
400 cx.shared.fs.write(&crate_list_dst, &crate_list)?;
402 if options.enable_index_page {
403 if let Some(index_page) = options.index_page.clone() {
404 let mut md_opts = options.clone();
405 md_opts.output = cx.dst.clone();
406 md_opts.external_html = (*cx.shared).layout.external_html.clone();
408 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
409 .map_err(|e| Error::new(e, &index_page))?;
411 let dst = cx.dst.join("index.html");
412 let page = layout::Page {
413 title: "Index of crates",
416 static_root_path: cx.shared.static_root_path.as_deref(),
417 description: "List of crates",
418 keywords: BASIC_KEYWORDS,
419 resource_suffix: &cx.shared.resource_suffix,
421 static_extra_scripts: &[],
424 let content = format!(
426 <span class=\"in-band\">List of all crates</span>\
427 </h1><ul class=\"crate mod\">{}</ul>",
432 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
433 ensure_trailing_slash(s),
439 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
440 cx.shared.fs.write(&dst, v.as_bytes())?;
444 // Update the list of all implementors for traits
445 let dst = cx.dst.join("implementors");
446 for (&did, imps) in &cx.cache.implementors {
447 // Private modules can leak through to this phase of rustdoc, which
448 // could contain implementations for otherwise private types. In some
449 // rare cases we could find an implementation for an item which wasn't
450 // indexed, so we just skip this step in that case.
452 // FIXME: this is a vague explanation for why this can't be a `get`, in
453 // theory it should be...
454 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
456 None => match cx.cache.external_paths.get(&did) {
469 let implementors = imps
472 // If the trait and implementation are in the same crate, then
473 // there's no need to emit information about it (there's inlining
474 // going on). If they're in different crates then the crate defining
475 // the trait will be interested in our implementation.
477 // If the implementation is from another crate then that crate
479 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
483 text: imp.inner_impl().print(cx.cache(), false).to_string(),
484 synthetic: imp.inner_impl().synthetic,
485 types: collect_paths_for_type(imp.inner_impl().for_.clone(), cx.cache()),
489 .collect::<Vec<_>>();
491 // Only create a js file if we have impls to add to it. If the trait is
492 // documented locally though we always create the file to avoid dead
494 if implementors.is_empty() && !cx.cache.paths.contains_key(&did) {
498 let implementors = format!(
499 r#"implementors["{}"] = {};"#,
501 serde_json::to_string(&implementors).unwrap()
504 let mut mydst = dst.clone();
505 for part in &remote_path[..remote_path.len() - 1] {
508 cx.shared.ensure_dir(&mydst)?;
509 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
511 let (mut all_implementors, _) =
512 try_err!(collect(&mydst, &krate.name.as_str(), "implementors"), &mydst);
513 all_implementors.push(implementors);
514 // Sort the implementors by crate so the file will be generated
515 // identically even with rustdoc running in parallel.
516 all_implementors.sort();
518 let mut v = String::from("(function() {var implementors = {};\n");
519 for implementor in &all_implementors {
520 writeln!(v, "{}", *implementor).unwrap();
523 "if (window.register_implementors) {\
524 window.register_implementors(implementors);\
526 window.pending_implementors = implementors;\
530 cx.shared.fs.write(&mydst, &v)?;
539 enable_minification: bool,
540 ) -> Result<(), Error> {
541 if enable_minification {
542 if dst.extension() == Some(&OsStr::new("css")) {
543 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
544 fs.write(dst, res.as_bytes())
546 fs.write(dst, minifier::js::minify(contents).as_bytes())
549 fs.write(dst, contents.as_bytes())