Skip to main content

rustdoc/html/render/
write_shared.rs

1//! Rustdoc writes aut two kinds of shared files:
2//!  - Static files, which are embedded in the rustdoc binary and are written with a
3//!    filename that includes a hash of their contents. These will always have a new
4//!    URL if the contents change, so they are safe to cache with the
5//!    `Cache-Control: immutable` directive. They are written under the static.files/
6//!    directory and are written when --emit-type is empty (default) or contains
7//!    "toolchain-specific". If using the --static-root-path flag, it should point
8//!    to a URL path prefix where each of these filenames can be fetched.
9//!  - Invocation specific files. These are generated based on the crate(s) being
10//!    documented. Their filenames need to be predictable without knowing their
11//!    contents, so they do not include a hash in their filename and are not safe to
12//!    cache with `Cache-Control: immutable`. They include the contents of the
13//!    --resource-suffix flag and are emitted when --emit-type is empty (default)
14//!    or contains "html-non-static-files".
15
16use std::cell::RefCell;
17use std::ffi::{OsStr, OsString};
18use std::fs::File;
19use std::io::{self, Write as _};
20use std::iter::once;
21use std::marker::PhantomData;
22use std::path::{Component, Path, PathBuf};
23use std::rc::{Rc, Weak};
24use std::str::FromStr;
25use std::{fmt, fs};
26
27use indexmap::IndexMap;
28use rustc_ast::join_path_syms;
29use rustc_data_structures::flock;
30use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
31use rustc_middle::ty::TyCtxt;
32use rustc_middle::ty::fast_reject::DeepRejectCtxt;
33use rustc_session::Session;
34use rustc_span::Symbol;
35use rustc_span::def_id::DefId;
36use serde::de::DeserializeOwned;
37use serde::ser::SerializeSeq;
38use serde::{Deserialize, Serialize, Serializer};
39
40use super::{Context, RenderMode, collect_paths_for_type, ensure_trailing_slash};
41use crate::clean::{Crate, Item, ItemId, ItemKind};
42use crate::config::{EmitType, PathToParts, RenderOptions, ShouldMerge};
43use crate::docfs::PathError;
44use crate::error::Error;
45use crate::formats::Impl;
46use crate::formats::item_type::ItemType;
47use crate::html::format::{print_impl, print_path};
48use crate::html::layout;
49use crate::html::render::ordered_json::{EscapedJson, OrderedJson};
50use crate::html::render::print_item::compare_names;
51use crate::html::render::search_index::{SerializedSearchIndex, build_index};
52use crate::html::render::sorted_template::{self, FileFormat, SortedTemplate};
53use crate::html::render::{
54    AssocItemLink, ImplRenderingParameters, StylePath, scrape_examples_help,
55};
56use crate::html::static_files::{self, suffix_path};
57use crate::visit::DocVisitor;
58use crate::{DOC_RUST_LANG_ORG_VERSION, try_err, try_none};
59
60pub(crate) fn write_shared(
61    cx: &mut Context<'_>,
62    krate: &Crate,
63    opt: &RenderOptions,
64    tcx: TyCtxt<'_>,
65) -> Result<(), Error> {
66    // NOTE(EtomicBomb): I don't think we need sync here because no read-after-write?
67    cx.shared.fs.set_sync_only(true);
68    let lock_file = cx.dst.join(".lock");
69    // Write shared runs within a flock; disable thread dispatching of IO temporarily.
70    let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
71
72    let search_index = build_index(
73        krate,
74        &mut cx.shared.cache,
75        tcx,
76        &cx.dst,
77        &cx.shared.resource_suffix,
78        &opt.should_merge,
79    )?;
80
81    let crate_name = krate.name(cx.tcx());
82    let crate_name = crate_name.as_str(); // rand
83    let crate_name_json = OrderedJson::serialize(crate_name).unwrap(); // "rand"
84    let external_crates = hack_get_external_crate_names(&cx.dst, &cx.shared.resource_suffix)?;
85    let info = CrateInfo {
86        version: CrateInfoVersion::V2,
87        src_files_js: SourcesPart::get(cx, &crate_name_json)?,
88        search_index,
89        all_crates: AllCratesPart::get(crate_name_json.clone(), &cx.shared.resource_suffix)?,
90        crates_index: CratesIndexPart::get(crate_name, &external_crates)?,
91        trait_impl: TraitAliasPart::get(cx, &crate_name_json)?,
92        type_impl: TypeAliasPart::get(cx, krate, &crate_name_json)?,
93    };
94
95    if let Some(parts_out_dir) = &opt.parts_out_dir {
96        let mut parts_out_file = parts_out_dir.0.clone();
97        parts_out_file.push(&format!("{crate_name}.json"));
98        create_parents(&parts_out_file)?;
99        try_err!(
100            fs::write(&parts_out_file, serde_json::to_string(&info).unwrap()),
101            &parts_out_dir.0
102        );
103    }
104
105    let mut crates = CrateInfo::read_many(&opt.include_parts_dir)?;
106    crates.push(info);
107
108    if opt.should_merge.write_rendered_cci {
109        write_not_crate_specific(
110            &crates,
111            &cx.dst,
112            opt,
113            &cx.shared.style_files,
114            cx.shared.layout.css_file_extension.as_deref(),
115            &cx.shared.resource_suffix,
116            cx.info.include_sources,
117            &cx.shared.layout,
118            cx.sess(),
119        )?;
120    }
121
122    cx.shared.fs.set_sync_only(false);
123    Ok(())
124}
125
126/// Writes files that are written directly to the `--out-dir`, without the prefix from the current
127/// crate. These are the rendered cross-crate files that encode info from multiple crates (e.g.
128/// search index), and the static files.
129pub(crate) fn write_not_crate_specific(
130    crates: &[CrateInfo],
131    dst: &Path,
132    opt: &RenderOptions,
133    style_files: &[StylePath],
134    css_file_extension: Option<&Path>,
135    resource_suffix: &str,
136    include_sources: bool,
137    layout: &layout::Layout,
138    sess: &Session,
139) -> Result<(), Error> {
140    write_rendered_cross_crate_info(crates, dst, opt, include_sources, resource_suffix)?;
141    write_resources(dst, opt, style_files, css_file_extension, resource_suffix)?;
142    // index.html
143    match &opt.index_page {
144        Some(index_page) if opt.enable_index_page => {
145            let mut md_opts = opt.clone();
146            md_opts.output = dst.to_path_buf();
147            md_opts.external_html = layout.external_html.clone();
148            let file = try_err!(sess.source_map().load_file(&index_page), &index_page);
149            try_err!(crate::markdown::render_and_write(file, md_opts, sess.edition()), &index_page);
150        }
151        None if opt.enable_index_page => {
152            write_rendered_cci::<CratesIndexPart, _>(
153                || CratesIndexPart::blank(layout, opt, style_files),
154                &dst,
155                &crates,
156                &opt.should_merge,
157            )?;
158        }
159        _ => {} // they don't want an index page
160    }
161
162    if opt.emit.contains(&EmitType::HtmlNonStaticFiles) {
163        // Standalone pages for the Settings and Help popovers.
164        //
165        // Normally, these are pure DHTML popovers, but, for user convenience,
166        // the buttons that open them are links to these HTML files, which use the same JavaScript
167        // to populate the page. That way, you can open a new tab, or add a browser bookmark,
168        // that points at the page.
169        let settings_file = dst.join("settings.html");
170        let help_file = dst.join("help.html");
171        let scrape_examples_help_file = dst.join("scrape-examples-help.html");
172
173        let page = layout::Page {
174            title: "Settings",
175            short_title: "Settings",
176            css_class: "mod sys",
177            root_path: "./",
178            static_root_path: opt.static_root_path.as_deref(),
179            description: "Settings of Rustdoc",
180            resource_suffix: &opt.resource_suffix,
181            rust_logo: true,
182        };
183        let sidebar = "<h2 class=\"location\">Settings</h2><div class=\"sidebar-elems\"></div>";
184        let v = layout::render(
185            &layout,
186            &page,
187            sidebar,
188            fmt::from_fn(|buf| {
189                write!(
190                    buf,
191                    "<div class=\"main-heading\">\
192                        <h1>Rustdoc settings</h1>\
193                        <span class=\"out-of-band\">\
194                            <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
195                            Back\
196                        </a>\
197                        </span>\
198                        </div>\
199                        <noscript>\
200                        <section>\
201                            You need to enable JavaScript be able to update your settings.\
202                        </section>\
203                        </noscript>\
204                        <script defer src=\"{static_root_path}{settings_js}\"></script>",
205                    static_root_path = page.get_static_root_path(),
206                    settings_js = static_files::STATIC_FILES.settings_js,
207                )?;
208                // Pre-load all theme CSS files, so that switching feels seamless.
209                //
210                // When loading settings.html as a popover, the equivalent HTML is
211                // generated in main.js.
212                for file in style_files {
213                    if let Ok(theme) = file.basename() {
214                        write!(
215                            buf,
216                            "<link rel=\"preload\" href=\"{root_path}{theme}{suffix}.css\" \
217                                as=\"style\">",
218                            root_path = page.static_root_path.unwrap_or(""),
219                            suffix = page.resource_suffix,
220                        )?;
221                    }
222                }
223                Ok(())
224            }),
225            &style_files,
226        );
227        try_err!(std::fs::write(&settings_file, v), &settings_file);
228
229        let page = layout::Page {
230            title: "Help",
231            short_title: "Help",
232            css_class: "mod sys",
233            root_path: "./",
234            static_root_path: opt.static_root_path.as_deref(),
235            description: "Documentation for Rustdoc",
236            resource_suffix: &opt.resource_suffix,
237            rust_logo: true,
238        };
239        let sidebar = "<h2 class=\"location\">Help</h2><div class=\"sidebar-elems\"></div>";
240        let v = layout::render(
241            &layout,
242            &page,
243            sidebar,
244            format_args!(
245                "<div class=\"main-heading\">\
246                    <h1>Rustdoc help</h1>\
247                    <span class=\"out-of-band\">\
248                        <a id=\"back\" href=\"javascript:void(0)\" onclick=\"history.back();\">\
249                        Back\
250                    </a>\
251                    </span>\
252                    </div>\
253                    <noscript>\
254                    <section>\
255                        <p>You need to enable JavaScript to use keyboard commands or search.</p>\
256                        <p>For more information, browse the <a href=\"{DOC_RUST_LANG_ORG_VERSION}/rustdoc/\">rustdoc handbook</a>.</p>\
257                    </section>\
258                    </noscript>",
259            ),
260            &style_files,
261        );
262        try_err!(std::fs::write(&help_file, v), &help_file);
263
264        if layout.scrape_examples_extension {
265            let page = layout::Page {
266                title: "About scraped examples",
267                short_title: "About scraped examples",
268                css_class: "mod sys",
269                root_path: "./",
270                static_root_path: opt.static_root_path.as_deref(),
271                description: "How the scraped examples feature works in Rustdoc",
272                resource_suffix: &opt.resource_suffix,
273                rust_logo: true,
274            };
275            let v = layout::render(&layout, &page, "", scrape_examples_help(), &style_files);
276            try_err!(std::fs::write(&scrape_examples_help_file, v), &scrape_examples_help_file);
277        }
278    }
279    Ok(())
280}
281
282fn write_rendered_cross_crate_info(
283    crates: &[CrateInfo],
284    dst: &Path,
285    opt: &RenderOptions,
286    include_sources: bool,
287    resource_suffix: &str,
288) -> Result<(), Error> {
289    let m = &opt.should_merge;
290    if opt.emit.contains(&EmitType::HtmlNonStaticFiles) {
291        if include_sources {
292            write_rendered_cci::<SourcesPart, _>(SourcesPart::blank, dst, crates, m)?;
293        }
294        crates
295            .iter()
296            .fold(SerializedSearchIndex::default(), |a, b| a.union(&b.search_index))
297            .sort()
298            .write_to(dst, resource_suffix)?;
299        write_rendered_cci::<AllCratesPart, _>(AllCratesPart::blank, dst, crates, m)?;
300    }
301    write_rendered_cci::<TraitAliasPart, _>(TraitAliasPart::blank, dst, crates, m)?;
302    write_rendered_cci::<TypeAliasPart, _>(TypeAliasPart::blank, dst, crates, m)?;
303    Ok(())
304}
305
306/// Writes the static files, the style files, and the css extensions.
307/// Have to be careful about these, because they write to the root out dir.
308fn write_resources(
309    dst: &Path,
310    opt: &RenderOptions,
311    style_files: &[StylePath],
312    css_file_extension: Option<&Path>,
313    resource_suffix: &str,
314) -> Result<(), Error> {
315    if opt.emit.contains(&EmitType::HtmlNonStaticFiles) {
316        // Handle added third-party themes
317        for entry in style_files {
318            let theme = entry.basename()?;
319            let extension =
320                try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
321
322            // Skip the official themes. They are written below as part of STATIC_FILES_LIST.
323            if matches!(theme.as_str(), "light" | "dark" | "ayu") {
324                continue;
325            }
326
327            let bytes = try_err!(fs::read(&entry.path), &entry.path);
328            let filename = format!("{theme}{resource_suffix}.{extension}");
329            let dst_filename = dst.join(filename);
330            try_err!(fs::write(&dst_filename, bytes), &dst_filename);
331        }
332
333        // When the user adds their own CSS files with --extend-css, we write that as an
334        // invocation-specific file (that is, with a resource suffix).
335        if let Some(css) = css_file_extension {
336            let buffer = try_err!(fs::read_to_string(css), css);
337            let path = static_files::suffix_path("theme.css", resource_suffix);
338            let dst_path = dst.join(path);
339            try_err!(fs::write(&dst_path, buffer), &dst_path);
340        }
341    }
342
343    if opt.emit.contains(&EmitType::HtmlStaticFiles) {
344        let static_dir = dst.join("static.files");
345        try_err!(fs::create_dir_all(&static_dir), &static_dir);
346
347        static_files::for_each(|f: &static_files::StaticFile| {
348            let filename = static_dir.join(f.output_filename());
349            let contents: &[u8] =
350                if opt.disable_minification { f.src_bytes } else { f.minified_bytes };
351            fs::write(&filename, contents).map_err(|e| PathError::new(e, &filename))
352        })?;
353    }
354
355    Ok(())
356}
357
358/// Contains pre-rendered contents to insert into the CCI template
359#[derive(Serialize, Deserialize, Clone, Debug)]
360pub(crate) struct CrateInfo {
361    version: CrateInfoVersion,
362    src_files_js: PartsAndLocations<SourcesPart>,
363    search_index: SerializedSearchIndex,
364    all_crates: PartsAndLocations<AllCratesPart>,
365    crates_index: PartsAndLocations<CratesIndexPart>,
366    trait_impl: PartsAndLocations<TraitAliasPart>,
367    type_impl: PartsAndLocations<TypeAliasPart>,
368}
369
370impl CrateInfo {
371    /// Read all of the crate info from its location on the filesystem
372    pub(crate) fn read_many(parts_paths: &[PathToParts]) -> Result<Vec<Self>, Error> {
373        parts_paths
374            .iter()
375            .fold(Ok(Vec::new()), |acc, parts_path| {
376                let mut acc = acc?;
377                let dir = &parts_path.0;
378                acc.append(&mut try_err!(std::fs::read_dir(dir), dir.as_path())
379                    .filter_map(|file| {
380                        let to_crate_info = |file: Result<std::fs::DirEntry, std::io::Error>| -> Result<Option<CrateInfo>, Error> {
381                            let file = try_err!(file, dir.as_path());
382                            if file.path().extension() != Some(OsStr::new("json")) {
383                                return Ok(None);
384                            }
385                            let parts = try_err!(fs::read(file.path()), file.path());
386                            let parts: CrateInfo = try_err!(serde_json::from_slice(&parts), file.path());
387                            Ok(Some(parts))
388                        };
389                        to_crate_info(file).transpose()
390                    })
391                    .collect::<Result<Vec<CrateInfo>, Error>>()?);
392                Ok(acc)
393            })
394    }
395}
396
397/// Version for the format of the crate-info file.
398///
399/// This enum should only ever have one variant, representing the current version.
400/// Gives pretty good error message about expecting the current version on deserialize.
401///
402/// Must be incremented (V2, V3, etc.) upon any changes to the search index or CrateInfo,
403/// to provide better diagnostics about including an invalid file.
404#[derive(Serialize, Deserialize, Clone, Debug)]
405enum CrateInfoVersion {
406    V2,
407}
408
409/// Paths (relative to the doc root) and their pre-merge contents
410#[derive(Serialize, Deserialize, Debug, Clone)]
411#[serde(transparent)]
412struct PartsAndLocations<P> {
413    parts: Vec<(PathBuf, P)>,
414}
415
416impl<P> Default for PartsAndLocations<P> {
417    fn default() -> Self {
418        Self { parts: Vec::default() }
419    }
420}
421
422impl<T, U> PartsAndLocations<Part<T, U>> {
423    fn push(&mut self, path: PathBuf, item: U) {
424        self.parts.push((path, Part { _artifact: PhantomData, item }));
425    }
426
427    /// Singleton part, one file
428    fn with(path: PathBuf, part: U) -> Self {
429        let mut ret = Self::default();
430        ret.push(path, part);
431        ret
432    }
433}
434
435/// A piece of one of the shared artifacts for documentation (search index, sources, alias list, etc.)
436///
437/// Merged at a user specified time and written to the `doc/` directory
438#[derive(Serialize, Deserialize, Debug, Clone)]
439#[serde(transparent)]
440struct Part<T, U> {
441    #[serde(skip)]
442    _artifact: PhantomData<T>,
443    item: U,
444}
445
446impl<T, U: fmt::Display> fmt::Display for Part<T, U> {
447    /// Writes serialized JSON
448    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449        write!(f, "{}", self.item)
450    }
451}
452
453/// Wrapper trait for `Part<T, U>`
454trait CciPart: Sized + fmt::Display + DeserializeOwned + 'static {
455    /// Identifies the file format of the cross-crate information
456    type FileFormat: sorted_template::FileFormat;
457    fn from_crate_info(crate_info: &CrateInfo) -> &PartsAndLocations<Self>;
458}
459
460#[derive(Serialize, Deserialize, Clone, Default, Debug)]
461struct AllCrates;
462type AllCratesPart = Part<AllCrates, OrderedJson>;
463impl CciPart for AllCratesPart {
464    type FileFormat = sorted_template::Js;
465    fn from_crate_info(crate_info: &CrateInfo) -> &PartsAndLocations<Self> {
466        &crate_info.all_crates
467    }
468}
469
470impl AllCratesPart {
471    fn blank() -> SortedTemplate<<Self as CciPart>::FileFormat> {
472        SortedTemplate::from_before_after("window.ALL_CRATES = [", "];")
473    }
474
475    fn get(
476        crate_name_json: OrderedJson,
477        resource_suffix: &str,
478    ) -> Result<PartsAndLocations<Self>, Error> {
479        // external hack_get_external_crate_names not needed here, because
480        // there's no way that we write the search index but not crates.js
481        let path = suffix_path("crates.js", resource_suffix);
482        Ok(PartsAndLocations::with(path, crate_name_json))
483    }
484}
485
486/// Reads `crates.js`, which seems like the best
487/// place to obtain the list of externally documented crates if the index
488/// page was disabled when documenting the deps.
489///
490/// This is to match the current behavior of rustdoc, which allows you to get all crates
491/// on the index page, even if --enable-index-page is only passed to the last crate.
492fn hack_get_external_crate_names(
493    doc_root: &Path,
494    resource_suffix: &str,
495) -> Result<Vec<String>, Error> {
496    let path = doc_root.join(suffix_path("crates.js", resource_suffix));
497    let Ok(content) = fs::read_to_string(&path) else {
498        // they didn't emit invocation specific, so we just say there were no crates
499        return Ok(Vec::default());
500    };
501    // this is only run once so it's fine not to cache it
502    // !dot_matches_new_line: all crates on same line. greedy: match last bracket
503    if let Some(start) = content.find('[')
504        && let Some(end) = content[start..].find(']')
505    {
506        let content: Vec<String> =
507            try_err!(serde_json::from_str(&content[start..=start + end]), &path);
508        Ok(content)
509    } else {
510        Err(Error::new("could not find crates list in crates.js", path))
511    }
512}
513
514#[derive(Serialize, Deserialize, Clone, Default, Debug)]
515struct CratesIndex;
516type CratesIndexPart = Part<CratesIndex, String>;
517impl CciPart for CratesIndexPart {
518    type FileFormat = sorted_template::Html;
519    fn from_crate_info(crate_info: &CrateInfo) -> &PartsAndLocations<Self> {
520        &crate_info.crates_index
521    }
522}
523
524impl CratesIndexPart {
525    fn blank(
526        layout: &layout::Layout,
527        opt: &RenderOptions,
528        style_files: &[StylePath],
529    ) -> SortedTemplate<<Self as CciPart>::FileFormat> {
530        let page = layout::Page {
531            title: "Index of crates",
532            short_title: "Crates",
533            css_class: "mod sys",
534            root_path: "./",
535            static_root_path: opt.static_root_path.as_deref(),
536            description: "List of crates",
537            resource_suffix: &opt.resource_suffix,
538            rust_logo: true,
539        };
540        const DELIMITER: &str = "\u{FFFC}"; // users are being naughty if they have this
541        let content = format_args!(
542            "<div class=\"main-heading\">\
543                <h1>List of all crates</h1>\
544                <rustdoc-toolbar></rustdoc-toolbar>\
545            </div>\
546            <ul class=\"all-items\">{DELIMITER}</ul>"
547        );
548        let template = layout::render(layout, &page, "", content, style_files);
549        SortedTemplate::from_template(&template, DELIMITER)
550            .expect("Object Replacement Character (U+FFFC) should not appear in the --index-page")
551    }
552
553    /// Might return parts that are duplicate with ones in preexisting index.html
554    fn get(crate_name: &str, external_crates: &[String]) -> Result<PartsAndLocations<Self>, Error> {
555        let mut ret = PartsAndLocations::default();
556        let path = Path::new("index.html");
557        for crate_name in external_crates.iter().map(|s| s.as_str()).chain(once(crate_name)) {
558            let part = format!(
559                "<li><a href=\"{trailing_slash}index.html\">{crate_name}</a></li>",
560                trailing_slash = ensure_trailing_slash(crate_name),
561            );
562            ret.push(path.to_path_buf(), part);
563        }
564        Ok(ret)
565    }
566}
567
568#[derive(Serialize, Deserialize, Clone, Default, Debug)]
569struct Sources;
570type SourcesPart = Part<Sources, EscapedJson>;
571impl CciPart for SourcesPart {
572    type FileFormat = sorted_template::Js;
573    fn from_crate_info(crate_info: &CrateInfo) -> &PartsAndLocations<Self> {
574        &crate_info.src_files_js
575    }
576}
577
578impl SourcesPart {
579    fn blank() -> SortedTemplate<<Self as CciPart>::FileFormat> {
580        // This needs to be `var`, not `const`.
581        // This variable needs declared in the current global scope so that if
582        // src-script.js loads first, it can pick it up.
583        SortedTemplate::from_before_after(r"createSrcSidebar('[", r"]');")
584    }
585
586    fn get(cx: &Context<'_>, crate_name: &OrderedJson) -> Result<PartsAndLocations<Self>, Error> {
587        let hierarchy = Rc::new(Hierarchy::default());
588        cx.shared
589            .local_sources
590            .iter()
591            .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
592            .for_each(|source| hierarchy.add_path(source));
593        let path = suffix_path("src-files.js", &cx.shared.resource_suffix);
594        let hierarchy = hierarchy.to_json_string();
595        let part = OrderedJson::array_unsorted([crate_name, &hierarchy]);
596        let part = EscapedJson::from(part);
597        Ok(PartsAndLocations::with(path, part))
598    }
599}
600
601/// Source files directory tree
602#[derive(Debug, Default)]
603struct Hierarchy {
604    parent: Weak<Self>,
605    elem: OsString,
606    children: RefCell<FxIndexMap<OsString, Rc<Self>>>,
607    elems: RefCell<FxIndexSet<OsString>>,
608}
609
610impl Hierarchy {
611    fn with_parent(elem: OsString, parent: &Rc<Self>) -> Self {
612        Self { elem, parent: Rc::downgrade(parent), ..Self::default() }
613    }
614
615    fn to_json_string(&self) -> OrderedJson {
616        let subs = self.children.borrow();
617        let files = self.elems.borrow();
618        let name = OrderedJson::serialize(self.elem.to_str().expect("invalid osstring conversion"))
619            .unwrap();
620        let mut out = Vec::from([name]);
621        if !subs.is_empty() || !files.is_empty() {
622            let subs = subs.iter().map(|(_, s)| s.to_json_string());
623            out.push(OrderedJson::array_sorted(subs));
624        }
625        if !files.is_empty() {
626            let files = files
627                .iter()
628                .map(|s| OrderedJson::serialize(s.to_str().expect("invalid osstring")).unwrap());
629            out.push(OrderedJson::array_sorted(files));
630        }
631        OrderedJson::array_unsorted(out)
632    }
633
634    fn add_path(self: &Rc<Self>, path: &Path) {
635        let mut h = Rc::clone(self);
636        let mut components = path
637            .components()
638            .filter(|component| matches!(component, Component::Normal(_) | Component::ParentDir))
639            .peekable();
640
641        assert!(components.peek().is_some(), "empty file path");
642        while let Some(component) = components.next() {
643            match component {
644                Component::Normal(s) => {
645                    if components.peek().is_none() {
646                        h.elems.borrow_mut().insert(s.to_owned());
647                        break;
648                    }
649                    h = {
650                        let mut children = h.children.borrow_mut();
651
652                        if let Some(existing) = children.get(s) {
653                            Rc::clone(existing)
654                        } else {
655                            let new_node = Rc::new(Self::with_parent(s.to_owned(), &h));
656                            children.insert(s.to_owned(), Rc::clone(&new_node));
657                            new_node
658                        }
659                    };
660                }
661                Component::ParentDir if let Some(parent) = h.parent.upgrade() => {
662                    h = parent;
663                }
664                _ => {}
665            }
666        }
667    }
668}
669
670#[derive(Serialize, Deserialize, Clone, Default, Debug)]
671struct TypeAlias;
672type TypeAliasPart = Part<TypeAlias, OrderedJson>;
673impl CciPart for TypeAliasPart {
674    type FileFormat = sorted_template::Js;
675    fn from_crate_info(crate_info: &CrateInfo) -> &PartsAndLocations<Self> {
676        &crate_info.type_impl
677    }
678}
679
680impl TypeAliasPart {
681    fn blank() -> SortedTemplate<<Self as CciPart>::FileFormat> {
682        SortedTemplate::from_before_after(
683            r"(function() {
684    var type_impls = Object.fromEntries([",
685            r"]);
686    if (window.register_type_impls) {
687        window.register_type_impls(type_impls);
688    } else {
689        window.pending_type_impls = type_impls;
690    }
691})()",
692        )
693    }
694
695    fn get(
696        cx: &mut Context<'_>,
697        krate: &Crate,
698        crate_name_json: &OrderedJson,
699    ) -> Result<PartsAndLocations<Self>, Error> {
700        let mut path_parts = PartsAndLocations::default();
701
702        let mut type_impl_collector = TypeImplCollector {
703            aliased_types: IndexMap::default(),
704            visited_aliases: FxHashSet::default(),
705            cx,
706        };
707        DocVisitor::visit_crate(&mut type_impl_collector, krate);
708        let cx = type_impl_collector.cx;
709        let aliased_types = type_impl_collector.aliased_types;
710        for aliased_type in aliased_types.values() {
711            let impls = aliased_type.impl_.values().filter_map(
712                |AliasedTypeImpl { impl_, type_aliases }| {
713                    let mut ret: Option<AliasSerializableImpl> = None;
714                    // render_impl will filter out "impossible-to-call" methods
715                    // to make that functionality work here, it needs to be called with
716                    // each type alias, and if it gives a different result, split the impl
717                    for &(type_alias_fqp, type_alias_item) in type_aliases {
718                        cx.id_map.borrow_mut().clear();
719                        cx.deref_id_map.borrow_mut().clear();
720                        let type_alias_fqp = join_path_syms(type_alias_fqp);
721                        if let Some(ret) = &mut ret {
722                            ret.aliases.push(type_alias_fqp);
723                        } else {
724                            let target_trait_did =
725                                impl_.inner_impl().trait_.as_ref().map(|trait_| trait_.def_id());
726                            let provided_methods;
727                            let assoc_link = if let Some(target_trait_did) = target_trait_did {
728                                provided_methods =
729                                    impl_.inner_impl().provided_trait_methods(cx.tcx());
730                                AssocItemLink::GotoSource(
731                                    ItemId::DefId(target_trait_did),
732                                    &provided_methods,
733                                )
734                            } else {
735                                AssocItemLink::Anchor(None)
736                            };
737                            let text = super::render_impl(
738                                cx,
739                                impl_,
740                                type_alias_item,
741                                assoc_link,
742                                RenderMode::Normal,
743                                None,
744                                &[],
745                                ImplRenderingParameters {
746                                    show_def_docs: true,
747                                    show_default_items: true,
748                                    show_non_assoc_items: true,
749                                    toggle_open_by_default: true,
750                                },
751                            )
752                            .to_string();
753                            // The alternate display prints it as plaintext instead of HTML.
754                            let trait_ = impl_
755                                .inner_impl()
756                                .trait_
757                                .as_ref()
758                                .map(|trait_| format!("{:#}", print_path(trait_, cx)));
759                            ret = Some(AliasSerializableImpl {
760                                text,
761                                trait_,
762                                aliases: vec![type_alias_fqp],
763                            })
764                        }
765                    }
766                    ret
767                },
768            );
769
770            let mut path = PathBuf::from("type.impl");
771            for component in &aliased_type.target_fqp[..aliased_type.target_fqp.len() - 1] {
772                path.push(component.as_str());
773            }
774            let aliased_item_type = aliased_type.target_type;
775            path.push(format!(
776                "{aliased_item_type}.{}.js",
777                aliased_type.target_fqp[aliased_type.target_fqp.len() - 1]
778            ));
779
780            let part = OrderedJson::array_sorted(
781                impls.map(|impl_| OrderedJson::serialize(impl_).unwrap()),
782            );
783            path_parts.push(path, OrderedJson::array_unsorted([crate_name_json, &part]));
784        }
785        Ok(path_parts)
786    }
787}
788
789#[derive(Serialize, Deserialize, Clone, Default, Debug)]
790struct TraitAlias;
791type TraitAliasPart = Part<TraitAlias, OrderedJson>;
792impl CciPart for TraitAliasPart {
793    type FileFormat = sorted_template::Js;
794    fn from_crate_info(crate_info: &CrateInfo) -> &PartsAndLocations<Self> {
795        &crate_info.trait_impl
796    }
797}
798
799impl TraitAliasPart {
800    fn blank() -> SortedTemplate<<Self as CciPart>::FileFormat> {
801        SortedTemplate::from_before_after(
802            r"(function() {
803    const implementors = Object.fromEntries([",
804            r"]);
805    if (window.register_implementors) {
806        window.register_implementors(implementors);
807    } else {
808        window.pending_implementors = implementors;
809    }
810})()",
811        )
812    }
813
814    fn get(
815        cx: &Context<'_>,
816        crate_name_json: &OrderedJson,
817    ) -> Result<PartsAndLocations<Self>, Error> {
818        let cache = &cx.shared.cache;
819        let mut path_parts = PartsAndLocations::default();
820        // Update the list of all implementors for traits
821        // <https://github.com/search?q=repo%3Arust-lang%2Frust+[RUSTDOCIMPL]+trait.impl&type=code>
822        for (&did, imps) in &cache.implementors {
823            // Private modules can leak through to this phase of rustdoc, which
824            // could contain implementations for otherwise private types. In some
825            // rare cases we could find an implementation for an item which wasn't
826            // indexed, so we just skip this step in that case.
827            //
828            // FIXME: this is a vague explanation for why this can't be a `get`, in
829            //        theory it should be...
830            let (remote_path, remote_item_type) = match cache.exact_paths.get(&did) {
831                Some(p) => match cache.paths.get(&did).or_else(|| cache.external_paths.get(&did)) {
832                    Some((_, t)) => (p, t),
833                    None => continue,
834                },
835                None => match cache.external_paths.get(&did) {
836                    Some((p, t)) => (p, t),
837                    None => continue,
838                },
839            };
840
841            let mut implementors = imps
842                .iter()
843                .filter_map(|imp| {
844                    // If the trait and implementation are in the same crate, then
845                    // there's no need to emit information about it (there's inlining
846                    // going on). If they're in different crates then the crate defining
847                    // the trait will be interested in our implementation.
848                    //
849                    // If the implementation is from another crate then that crate
850                    // should add it.
851                    if imp.impl_item.item_id.krate() == did.krate
852                        || !imp.impl_item.item_id.is_local()
853                    {
854                        None
855                    } else {
856                        let impl_ = imp.inner_impl();
857                        let print = print_impl(impl_, false, cx);
858                        Some(Implementor {
859                            text: format!("{}", print),
860                            cmp_text: format!("{:#}", print),
861                            synthetic: imp.inner_impl().kind.is_auto(),
862                            types: collect_paths_for_type(&imp.inner_impl().for_, cache),
863                            is_negative: impl_.is_negative_trait_impl(),
864                        })
865                    }
866                })
867                .peekable();
868
869            // Only create a js file if we have impls to add to it. If the trait is
870            // documented locally though we always create the file to avoid dead
871            // links.
872            if implementors.peek().is_none() && !cache.paths.contains_key(&did) {
873                continue;
874            }
875
876            let mut path = PathBuf::from("trait.impl");
877            for component in &remote_path[..remote_path.len() - 1] {
878                path.push(component.as_str());
879            }
880            path.push(format!("{remote_item_type}.{}.js", remote_path[remote_path.len() - 1]));
881
882            let mut implementors = implementors.collect::<Vec<_>>();
883            // Negative impls are naturally sorted first, because `impl !A` is less than `impl B`
884            // for any value of `B`, because `!` is less than any identifier-starting char.
885            implementors.sort_unstable_by(|a, b| compare_names(&a.cmp_text, &b.cmp_text));
886
887            let part = OrderedJson::array_unsorted(
888                implementors
889                    .iter()
890                    .map(OrderedJson::serialize)
891                    .collect::<Result<Vec<_>, _>>()
892                    .unwrap(),
893            );
894            path_parts.push(path, OrderedJson::array_unsorted([crate_name_json, &part]));
895        }
896        Ok(path_parts)
897    }
898}
899
900struct Implementor {
901    // HTML text used in generated output.
902    text: String,
903    // Plain text used just for sorting output. This is a performance win, because this plain text
904    // is much shorter than the HTML output and sorting is hot.
905    cmp_text: String,
906    synthetic: bool,
907    types: Vec<String>,
908    is_negative: bool,
909}
910
911impl Serialize for Implementor {
912    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
913    where
914        S: Serializer,
915    {
916        let mut seq = serializer.serialize_seq(None)?;
917        seq.serialize_element(&self.text)?;
918        seq.serialize_element(if self.is_negative { &1 } else { &0 })?;
919        if self.synthetic {
920            seq.serialize_element(&1)?;
921            seq.serialize_element(&self.types)?;
922        }
923        seq.end()
924    }
925}
926
927/// Collect the list of aliased types and their aliases.
928/// <https://github.com/search?q=repo%3Arust-lang%2Frust+[RUSTDOCIMPL]+type.impl&type=code>
929///
930/// The clean AST has type aliases that point at their types, but
931/// this visitor works to reverse that: `aliased_types` is a map
932/// from target to the aliases that reference it, and each one
933/// will generate one file.
934struct TypeImplCollector<'cx, 'cache, 'item> {
935    /// Map from DefId-of-aliased-type to its data.
936    aliased_types: IndexMap<DefId, AliasedType<'cache, 'item>>,
937    visited_aliases: FxHashSet<DefId>,
938    cx: &'cache Context<'cx>,
939}
940
941/// Data for an aliased type.
942///
943/// In the final file, the format will be roughly:
944///
945/// ```json
946/// // type.impl/CRATE/TYPENAME.js
947/// JSONP(
948/// "CRATE": [
949///   ["IMPL1 HTML", "ALIAS1", "ALIAS2", ...],
950///   ["IMPL2 HTML", "ALIAS3", "ALIAS4", ...],
951///    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ struct AliasedType
952///   ...
953/// ]
954/// )
955/// ```
956struct AliasedType<'cache, 'item> {
957    /// This is used to generate the actual filename of this aliased type.
958    target_fqp: &'cache [Symbol],
959    target_type: ItemType,
960    /// This is the data stored inside the file.
961    /// ItemId is used to deduplicate impls.
962    impl_: IndexMap<ItemId, AliasedTypeImpl<'cache, 'item>>,
963}
964
965/// The `impl_` contains data that's used to figure out if an alias will work,
966/// and to generate the HTML at the end.
967///
968/// The `type_aliases` list is built up with each type alias that matches.
969struct AliasedTypeImpl<'cache, 'item> {
970    impl_: &'cache Impl,
971    type_aliases: Vec<(&'cache [Symbol], &'item Item)>,
972}
973
974impl<'item> DocVisitor<'item> for TypeImplCollector<'_, '_, 'item> {
975    fn visit_item(&mut self, it: &'item Item) {
976        self.visit_item_recur(it);
977        let cache = &self.cx.shared.cache;
978        let ItemKind::TypeAliasItem(ref t) = it.kind else { return };
979        let Some(self_did) = it.item_id.as_def_id() else { return };
980        if !self.visited_aliases.insert(self_did) {
981            return;
982        }
983        let Some(target_did) = t.type_.def_id(cache) else { return };
984        let get_extern = { || cache.external_paths.get(&target_did) };
985        let Some(&(ref target_fqp, target_type)) = cache.paths.get(&target_did).or_else(get_extern)
986        else {
987            return;
988        };
989        let aliased_type = self.aliased_types.entry(target_did).or_insert_with(|| {
990            let impl_ = cache
991                .impls
992                .get(&target_did)
993                .into_iter()
994                .flatten()
995                .map(|impl_| {
996                    (impl_.impl_item.item_id, AliasedTypeImpl { impl_, type_aliases: Vec::new() })
997                })
998                .collect();
999            AliasedType { target_fqp: &target_fqp[..], target_type, impl_ }
1000        });
1001        let get_local = { || cache.paths.get(&self_did).map(|(p, _)| p) };
1002        let Some(self_fqp) = cache.exact_paths.get(&self_did).or_else(get_local) else {
1003            return;
1004        };
1005        let aliased_ty = self.cx.tcx().type_of(self_did).skip_binder();
1006        // Exclude impls that are directly on this type. They're already in the HTML.
1007        // Some inlining scenarios can cause there to be two versions of the same
1008        // impl: one on the type alias and one on the underlying target type.
1009        let mut seen_impls: FxHashSet<ItemId> =
1010            cache.impls.get(&self_did).into_iter().flatten().map(|i| i.impl_item.item_id).collect();
1011        for (impl_item_id, aliased_type_impl) in &mut aliased_type.impl_ {
1012            // Only include this impl if it actually unifies with this alias.
1013            // Synthetic impls are not included; those are also included in the HTML.
1014            //
1015            // FIXME(checked_type_alias): Once the feature is complete or stable, rewrite this
1016            // to use type unification.
1017            // Be aware of `tests/rustdoc-html/type-alias/deeply-nested-112515.rs` which might
1018            // regress.
1019            let Some(impl_did) = impl_item_id.as_def_id() else { continue };
1020            let for_ty = self.cx.tcx().type_of(impl_did).skip_binder();
1021            let reject_cx = DeepRejectCtxt::relate_infer_infer(self.cx.tcx());
1022            if !reject_cx.types_may_unify(aliased_ty, for_ty) {
1023                continue;
1024            }
1025            // Avoid duplicates
1026            if !seen_impls.insert(*impl_item_id) {
1027                continue;
1028            }
1029            // This impl was not found in the set of rejected impls
1030            aliased_type_impl.type_aliases.push((&self_fqp[..], it));
1031        }
1032    }
1033}
1034
1035/// Final serialized form of the alias impl
1036struct AliasSerializableImpl {
1037    text: String,
1038    trait_: Option<String>,
1039    aliases: Vec<String>,
1040}
1041
1042impl Serialize for AliasSerializableImpl {
1043    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1044    where
1045        S: Serializer,
1046    {
1047        let mut seq = serializer.serialize_seq(None)?;
1048        seq.serialize_element(&self.text)?;
1049        if let Some(trait_) = &self.trait_ {
1050            seq.serialize_element(trait_)?;
1051        } else {
1052            seq.serialize_element(&0)?;
1053        }
1054        for type_ in &self.aliases {
1055            seq.serialize_element(type_)?;
1056        }
1057        seq.end()
1058    }
1059}
1060
1061fn get_path_parts<T: CciPart>(
1062    dst: &Path,
1063    crates_info: &[CrateInfo],
1064) -> FxIndexMap<PathBuf, Vec<String>> {
1065    let mut templates: FxIndexMap<PathBuf, Vec<String>> = FxIndexMap::default();
1066    crates_info.iter().flat_map(|crate_info| T::from_crate_info(crate_info).parts.iter()).for_each(
1067        |(path, part)| {
1068            let path = dst.join(path);
1069            let part = part.to_string();
1070            templates.entry(path).or_default().push(part);
1071        },
1072    );
1073    templates
1074}
1075
1076/// Create all parents
1077fn create_parents(path: &Path) -> Result<(), Error> {
1078    let parent = path.parent().expect("should not have an empty path here");
1079    try_err!(fs::create_dir_all(parent), parent);
1080    Ok(())
1081}
1082
1083/// Returns a blank template unless we could find one to append to
1084fn read_template_or_blank<F, T: FileFormat>(
1085    mut make_blank: F,
1086    path: &Path,
1087    should_merge: &ShouldMerge,
1088) -> Result<SortedTemplate<T>, Error>
1089where
1090    F: FnMut() -> SortedTemplate<T>,
1091{
1092    if !should_merge.read_rendered_cci {
1093        return Ok(make_blank());
1094    }
1095    match fs::read_to_string(path) {
1096        Ok(template) => Ok(try_err!(SortedTemplate::from_str(&template), &path)),
1097        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(make_blank()),
1098        Err(e) => Err(Error::new(e, path)),
1099    }
1100}
1101
1102/// info from this crate and the --include-info-json'd crates
1103fn write_rendered_cci<T: CciPart, F>(
1104    mut make_blank: F,
1105    dst: &Path,
1106    crates_info: &[CrateInfo],
1107    should_merge: &ShouldMerge,
1108) -> Result<(), Error>
1109where
1110    F: FnMut() -> SortedTemplate<T::FileFormat>,
1111{
1112    // write the merged cci to disk
1113    for (path, parts) in get_path_parts::<T>(dst, crates_info) {
1114        create_parents(&path)?;
1115        // read previous rendered cci from storage, append to them
1116        let mut template =
1117            read_template_or_blank::<_, T::FileFormat>(&mut make_blank, &path, should_merge)?;
1118        for part in parts {
1119            template.append(part);
1120        }
1121        let mut file = try_err!(File::create_buffered(&path), &path);
1122        try_err!(write!(file, "{template}"), &path);
1123        try_err!(file.flush(), &path);
1124    }
1125    Ok(())
1126}
1127
1128#[cfg(test)]
1129mod tests;