1use 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 cx.shared.fs.set_sync_only(true);
64 let lock_file = cx.dst.join(".lock");
65 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)?; let crate_name = krate.name(cx.tcx());
72 let crate_name = crate_name.as_str(); let crate_name_json = OrderedJson::serialize(crate_name).unwrap(); 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 _ => {} }
126 }
127
128 cx.shared.fs.set_sync_only(false);
129 Ok(())
130}
131
132pub(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
168fn 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 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 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 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
218fn 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#[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 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#[derive(Serialize, Deserialize, Clone, Debug)]
279enum CrateInfoVersion {
280 V1,
281}
282
283#[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 fn with(path: PathBuf, part: U) -> Self {
303 let mut ret = Self::default();
304 ret.push(path, part);
305 ret
306 }
307}
308
309#[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 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 write!(f, "{}", self.item)
324 }
325}
326
327trait CciPart: Sized + fmt::Display + DeserializeOwned + 'static {
329 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 let path = suffix_path("crates.js", resource_suffix);
386 Ok(PartsAndLocations::with(path, crate_name_json))
387 }
388}
389
390fn 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 return Ok(Vec::default());
404 };
405 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}"; 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 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 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#[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 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 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 for (&did, imps) in &cache.implementors {
718 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 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 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
803struct TypeImplCollector<'cx, 'cache, 'item> {
811 aliased_types: IndexMap<DefId, AliasedType<'cache, 'item>>,
813 visited_aliases: FxHashSet<DefId>,
814 cx: &'cache Context<'cx>,
815}
816
817struct AliasedType<'cache, 'item> {
833 target_fqp: &'cache [Symbol],
835 target_type: ItemType,
836 impl_: IndexMap<ItemId, AliasedTypeImpl<'cache, 'item>>,
839}
840
841struct 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 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 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 if !seen_impls.insert(*impl_item_id) {
902 continue;
903 }
904 aliased_type_impl.type_aliases.push((&self_fqp[..], it));
906 }
907 }
908}
909
910struct 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
951fn 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
958fn 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
977fn 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 for (path, parts) in get_path_parts::<T>(dst, crates_info) {
989 create_parents(&path)?;
990 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;