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