[go: up one dir, main page]

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