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