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