-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
print_item.rs
1971 lines (1823 loc) · 72.4 KB
/
print_item.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use clean::AttributesExt;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId;
use rustc_middle::middle::stability;
use rustc_middle::span_bug;
use rustc_middle::ty::layout::LayoutError;
use rustc_middle::ty::{Adt, TyCtxt};
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_target::abi::{Layout, Primitive, TagEncoding, Variants};
use std::cmp::Ordering;
use std::fmt;
use std::rc::Rc;
use super::{
collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference,
item_ty_to_section, notable_traits_decl, render_all_impls, render_assoc_item,
render_assoc_items, render_attributes_in_code, render_attributes_in_pre, render_impl,
render_rightside, render_stability_since_raw, AssocItemLink, Context, ImplRenderingParameters,
};
use crate::clean;
use crate::config::ModuleSorting;
use crate::formats::item_type::ItemType;
use crate::formats::{AssocItemRender, Impl, RenderMode};
use crate::html::escape::Escape;
use crate::html::format::{
join_with_double_colon, print_abi_with_space, print_constness_with_space, print_where_clause,
Buffer, Ending, PrintWithSpace,
};
use crate::html::highlight;
use crate::html::layout::Page;
use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
use crate::html::url_parts_builder::UrlPartsBuilder;
use askama::Template;
use itertools::Itertools;
const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
const ITEM_TABLE_CLOSE: &str = "</div>";
const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
// A component in a `use` path, like `string` in std::string::ToString
struct PathComponent {
path: String,
name: Symbol,
}
#[derive(Template)]
#[template(path = "print_item.html")]
struct ItemVars<'a> {
page: &'a Page<'a>,
static_root_path: &'a str,
typ: &'a str,
name: &'a str,
item_type: &'a str,
path_components: Vec<PathComponent>,
stability_since_raw: &'a str,
src_href: Option<&'a str>,
}
/// Calls `print_where_clause` and returns `true` if a `where` clause was generated.
fn print_where_clause_and_check<'a, 'tcx: 'a>(
buffer: &mut Buffer,
gens: &'a clean::Generics,
cx: &'a Context<'tcx>,
) -> bool {
let len_before = buffer.len();
write!(buffer, "{}", print_where_clause(gens, cx, 0, Ending::Newline));
len_before != buffer.len()
}
pub(super) fn print_item(
cx: &mut Context<'_>,
item: &clean::Item,
buf: &mut Buffer,
page: &Page<'_>,
) {
debug_assert!(!item.is_stripped());
let typ = match *item.kind {
clean::ModuleItem(_) => {
if item.is_crate() {
"Crate "
} else {
"Module "
}
}
clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
clean::TraitItem(..) => "Trait ",
clean::StructItem(..) => "Struct ",
clean::UnionItem(..) => "Union ",
clean::EnumItem(..) => "Enum ",
clean::TypedefItem(..) => "Type Definition ",
clean::MacroItem(..) => "Macro ",
clean::ProcMacroItem(ref mac) => match mac.kind {
MacroKind::Bang => "Macro ",
MacroKind::Attr => "Attribute Macro ",
MacroKind::Derive => "Derive Macro ",
},
clean::PrimitiveItem(..) => "Primitive Type ",
clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
clean::ConstantItem(..) => "Constant ",
clean::ForeignTypeItem => "Foreign Type ",
clean::KeywordItem => "Keyword ",
clean::OpaqueTyItem(..) => "Opaque Type ",
clean::TraitAliasItem(..) => "Trait Alias ",
_ => {
// We don't generate pages for any other type.
unreachable!();
}
};
let mut stability_since_raw = Buffer::new();
render_stability_since_raw(
&mut stability_since_raw,
item.stable_since(cx.tcx()),
item.const_stability(cx.tcx()),
None,
None,
);
let stability_since_raw: String = stability_since_raw.into_inner();
// Write source tag
//
// When this item is part of a `crate use` in a downstream crate, the
// source link in the downstream documentation will actually come back to
// this page, and this link will be auto-clicked. The `id` attribute is
// used to find the link to auto-click.
let src_href =
if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
let path_components = if item.is_primitive() || item.is_keyword() {
vec![]
} else {
let cur = &cx.current;
let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
cur.iter()
.enumerate()
.take(amt)
.map(|(i, component)| PathComponent {
path: "../".repeat(cur.len() - i - 1),
name: *component,
})
.collect()
};
let item_vars = ItemVars {
page,
static_root_path: page.get_static_root_path(),
typ,
name: item.name.as_ref().unwrap().as_str(),
item_type: &item.type_().to_string(),
path_components,
stability_since_raw: &stability_since_raw,
src_href: src_href.as_deref(),
};
item_vars.render_into(buf).unwrap();
match &*item.kind {
clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
item_function(buf, cx, item, f)
}
clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
clean::StructItem(ref s) => item_struct(buf, cx, item, s),
clean::UnionItem(ref s) => item_union(buf, cx, item, s),
clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
clean::TypedefItem(ref t) => item_typedef(buf, cx, item, t),
clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
clean::KeywordItem => item_keyword(buf, cx, item),
clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
_ => {
// We don't generate pages for any other type.
unreachable!();
}
}
}
/// For large structs, enums, unions, etc, determine whether to hide their fields
fn should_hide_fields(n_fields: usize) -> bool {
n_fields > 12
}
fn toggle_open(w: &mut Buffer, text: impl fmt::Display) {
write!(
w,
"<details class=\"rustdoc-toggle type-contents-toggle\">\
<summary class=\"hideme\">\
<span>Show {}</span>\
</summary>",
text
);
}
fn toggle_close(w: &mut Buffer) {
w.write_str("</details>");
}
fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
document(w, cx, item, None, HeadingOffset::H2);
let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
// the order of item types in the listing
fn reorder(ty: ItemType) -> u8 {
match ty {
ItemType::ExternCrate => 0,
ItemType::Import => 1,
ItemType::Primitive => 2,
ItemType::Module => 3,
ItemType::Macro => 4,
ItemType::Struct => 5,
ItemType::Enum => 6,
ItemType::Constant => 7,
ItemType::Static => 8,
ItemType::Trait => 9,
ItemType::Function => 10,
ItemType::Typedef => 12,
ItemType::Union => 13,
_ => 14 + ty as u8,
}
}
fn cmp(
i1: &clean::Item,
i2: &clean::Item,
idx1: usize,
idx2: usize,
tcx: TyCtxt<'_>,
) -> Ordering {
let ty1 = i1.type_();
let ty2 = i2.type_();
if item_ty_to_section(ty1) != item_ty_to_section(ty2)
|| (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
{
return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
}
let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
if let (Some(a), Some(b)) = (s1, s2) {
match (a.is_stable(), b.is_stable()) {
(true, true) | (false, false) => {}
(false, true) => return Ordering::Less,
(true, false) => return Ordering::Greater,
}
}
let lhs = i1.name.unwrap_or(kw::Empty);
let rhs = i2.name.unwrap_or(kw::Empty);
compare_names(lhs.as_str(), rhs.as_str())
}
match cx.shared.module_sorting {
ModuleSorting::Alphabetical => {
indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
}
ModuleSorting::DeclarationOrder => {}
}
// This call is to remove re-export duplicates in cases such as:
//
// ```
// pub(crate) mod foo {
// pub(crate) mod bar {
// pub(crate) trait Double { fn foo(); }
// }
// }
//
// pub(crate) use foo::bar::*;
// pub(crate) use foo::*;
// ```
//
// `Double` will appear twice in the generated docs.
//
// FIXME: This code is quite ugly and could be improved. Small issue: DefId
// can be identical even if the elements are different (mostly in imports).
// So in case this is an import, we keep everything by adding a "unique id"
// (which is the position in the vector).
indices.dedup_by_key(|i| {
(
items[*i].item_id,
if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
items[*i].type_(),
if items[*i].is_import() { *i } else { 0 },
)
});
debug!("{:?}", indices);
let mut last_section = None;
for &idx in &indices {
let myitem = &items[idx];
if myitem.is_stripped() {
continue;
}
let my_section = item_ty_to_section(myitem.type_());
if Some(my_section) != last_section {
if last_section.is_some() {
w.write_str(ITEM_TABLE_CLOSE);
}
last_section = Some(my_section);
write!(
w,
"<h2 id=\"{id}\" class=\"small-section-header\">\
<a href=\"#{id}\">{name}</a>\
</h2>{}",
ITEM_TABLE_OPEN,
id = cx.derive_id(my_section.id().to_owned()),
name = my_section.name(),
);
}
match *myitem.kind {
clean::ExternCrateItem { ref src } => {
use crate::html::format::anchor;
w.write_str(ITEM_TABLE_ROW_OPEN);
match *src {
Some(src) => write!(
w,
"<div class=\"item-left\"><code>{}extern crate {} as {};",
myitem.visibility.print_with_space(myitem.item_id, cx),
anchor(myitem.item_id.expect_def_id(), src, cx),
myitem.name.unwrap(),
),
None => write!(
w,
"<div class=\"item-left\"><code>{}extern crate {};",
myitem.visibility.print_with_space(myitem.item_id, cx),
anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
),
}
w.write_str("</code></div>");
w.write_str(ITEM_TABLE_ROW_CLOSE);
}
clean::ImportItem(ref import) => {
let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
let ast_attrs = cx.tcx().get_attrs_unchecked(import_def_id);
let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs));
// Just need an item with the correct def_id and attrs
let import_item = clean::Item {
item_id: import_def_id.into(),
attrs: import_attrs,
cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
..myitem.clone()
};
let stab = import_item.stability_class(cx.tcx());
let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
(stab, stab_tags)
} else {
(None, None)
};
let add = if stab.is_some() { " " } else { "" };
w.write_str(ITEM_TABLE_ROW_OPEN);
let id = match import.kind {
clean::ImportKind::Simple(s) => {
format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s)))
}
clean::ImportKind::Glob => String::new(),
};
let stab_tags = stab_tags.unwrap_or_default();
let (stab_tags_before, stab_tags_after) = if stab_tags.is_empty() {
("", "")
} else {
("<div class=\"item-right docblock-short\">", "</div>")
};
write!(
w,
"<div class=\"item-left {stab}{add}import-item\"{id}>\
<code>{vis}{imp}</code>\
</div>\
{stab_tags_before}{stab_tags}{stab_tags_after}",
stab = stab.unwrap_or_default(),
vis = myitem.visibility.print_with_space(myitem.item_id, cx),
imp = import.print(cx),
);
w.write_str(ITEM_TABLE_ROW_CLOSE);
}
_ => {
if myitem.name.is_none() {
continue;
}
let unsafety_flag = match *myitem.kind {
clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
if myitem.fn_header(cx.tcx()).unwrap().unsafety
== hir::Unsafety::Unsafe =>
{
"<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>"
}
_ => "",
};
let stab = myitem.stability_class(cx.tcx());
let add = if stab.is_some() { " " } else { "" };
let visibility_emoji = match myitem.visibility {
clean::Visibility::Restricted(_) => {
"<span title=\"Restricted Visibility\"> 🔒</span> "
}
_ => "",
};
let doc_value = myitem.doc_value().unwrap_or_default();
w.write_str(ITEM_TABLE_ROW_OPEN);
let docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string();
let (docs_before, docs_after) = if docs.is_empty() {
("", "")
} else {
("<div class=\"item-right docblock-short\">", "</div>")
};
write!(
w,
"<div class=\"item-left {stab}{add}module-item\">\
<a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
{visibility_emoji}\
{unsafety_flag}\
{stab_tags}\
</div>\
{docs_before}{docs}{docs_after}",
name = myitem.name.unwrap(),
visibility_emoji = visibility_emoji,
stab_tags = extra_info_tags(myitem, item, cx.tcx()),
class = myitem.type_(),
add = add,
stab = stab.unwrap_or_default(),
unsafety_flag = unsafety_flag,
href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
title = [full_path(cx, myitem), myitem.type_().to_string()]
.iter()
.filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
.collect::<Vec<_>>()
.join(" "),
);
w.write_str(ITEM_TABLE_ROW_CLOSE);
}
}
}
if last_section.is_some() {
w.write_str(ITEM_TABLE_CLOSE);
}
}
/// Render the stability, deprecation and portability tags that are displayed in the item's summary
/// at the module level.
fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
let mut tags = String::new();
fn tag_html(class: &str, title: &str, contents: &str) -> String {
format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
}
// The trailing space after each tag is to space it properly against the rest of the docs.
if let Some(depr) = &item.deprecation(tcx) {
let mut message = "Deprecated";
if !stability::deprecation_in_effect(depr) {
message = "Deprecation planned";
}
tags += &tag_html("deprecated", "", message);
}
// The "rustc_private" crates are permanently unstable so it makes no sense
// to render "unstable" everywhere.
if item.stability(tcx).as_ref().map(|s| s.is_unstable() && s.feature != sym::rustc_private)
== Some(true)
{
tags += &tag_html("unstable", "", "Experimental");
}
let cfg = match (&item.cfg, parent.cfg.as_ref()) {
(Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
(cfg, _) => cfg.as_deref().cloned(),
};
debug!("Portability name={:?} {:?} - {:?} = {:?}", item.name, item.cfg, parent.cfg, cfg);
if let Some(ref cfg) = cfg {
tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
}
tags
}
fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &clean::Function) {
let header = it.fn_header(cx.tcx()).expect("printing a function which isn't a function");
let constness = print_constness_with_space(&header.constness, it.const_stability(cx.tcx()));
let unsafety = header.unsafety.print_with_space();
let abi = print_abi_with_space(header.abi).to_string();
let asyncness = header.asyncness.print_with_space();
let visibility = it.visibility.print_with_space(it.item_id, cx).to_string();
let name = it.name.unwrap();
let generics_len = format!("{:#}", f.generics.print(cx)).len();
let header_len = "fn ".len()
+ visibility.len()
+ constness.len()
+ asyncness.len()
+ unsafety.len()
+ abi.len()
+ name.as_str().len()
+ generics_len;
wrap_into_docblock(w, |w| {
wrap_item(w, "fn", |w| {
render_attributes_in_pre(w, it, "");
w.reserve(header_len);
write!(
w,
"{vis}{constness}{asyncness}{unsafety}{abi}fn \
{name}{generics}{decl}{notable_traits}{where_clause}",
vis = visibility,
constness = constness,
asyncness = asyncness,
unsafety = unsafety,
abi = abi,
name = name,
generics = f.generics.print(cx),
where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline),
decl = f.decl.full_print(header_len, 0, cx),
notable_traits = notable_traits_decl(&f.decl, cx),
);
});
});
document(w, cx, it, None, HeadingOffset::H2)
}
fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
let bounds = bounds(&t.bounds, false, cx);
let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
let count_types = required_types.len() + provided_types.len();
let count_consts = required_consts.len() + provided_consts.len();
let count_methods = required_methods.len() + provided_methods.len();
let must_implement_one_of_functions =
cx.tcx().trait_def(t.def_id).must_implement_one_of.clone();
// Output the trait definition
wrap_into_docblock(w, |w| {
wrap_item(w, "trait", |w| {
render_attributes_in_pre(w, it, "");
write!(
w,
"{}{}{}trait {}{}{}",
it.visibility.print_with_space(it.item_id, cx),
t.unsafety(cx.tcx()).print_with_space(),
if t.is_auto(cx.tcx()) { "auto " } else { "" },
it.name.unwrap(),
t.generics.print(cx),
bounds
);
if !t.generics.where_predicates.is_empty() {
write!(w, "{}", print_where_clause(&t.generics, cx, 0, Ending::Newline));
} else {
w.write_str(" ");
}
if t.items.is_empty() {
w.write_str("{ }");
} else {
// FIXME: we should be using a derived_id for the Anchors here
w.write_str("{\n");
let mut toggle = false;
// If there are too many associated types, hide _everything_
if should_hide_fields(count_types) {
toggle = true;
toggle_open(
w,
format_args!(
"{} associated items",
count_types + count_consts + count_methods
),
);
}
for types in [&required_types, &provided_types] {
for t in types {
render_assoc_item(
w,
t,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
w.write_str(";\n");
}
}
// If there are too many associated constants, hide everything after them
// We also do this if the types + consts is large because otherwise we could
// render a bunch of types and _then_ a bunch of consts just because both were
// _just_ under the limit
if !toggle && should_hide_fields(count_types + count_consts) {
toggle = true;
toggle_open(
w,
format_args!(
"{} associated constant{} and {} method{}",
count_consts,
pluralize(count_consts),
count_methods,
pluralize(count_methods),
),
);
}
if count_types != 0 && (count_consts != 0 || count_methods != 0) {
w.write_str("\n");
}
for consts in [&required_consts, &provided_consts] {
for c in consts {
render_assoc_item(
w,
c,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
w.write_str(";\n");
}
}
if !toggle && should_hide_fields(count_methods) {
toggle = true;
toggle_open(w, format_args!("{} methods", count_methods));
}
if count_consts != 0 && count_methods != 0 {
w.write_str("\n");
}
for (pos, m) in required_methods.iter().enumerate() {
render_assoc_item(
w,
m,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
w.write_str(";\n");
if pos < required_methods.len() - 1 {
w.write_str("<span class=\"item-spacer\"></span>");
}
}
if !required_methods.is_empty() && !provided_methods.is_empty() {
w.write_str("\n");
}
for (pos, m) in provided_methods.iter().enumerate() {
render_assoc_item(
w,
m,
AssocItemLink::Anchor(None),
ItemType::Trait,
cx,
RenderMode::Normal,
);
match *m.kind {
clean::MethodItem(ref inner, _)
if !inner.generics.where_predicates.is_empty() =>
{
w.write_str(",\n { ... }\n");
}
_ => {
w.write_str(" { ... }\n");
}
}
if pos < provided_methods.len() - 1 {
w.write_str("<span class=\"item-spacer\"></span>");
}
}
if toggle {
toggle_close(w);
}
w.write_str("}");
}
});
});
// Trait documentation
document(w, cx, it, None, HeadingOffset::H2);
fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
write!(
w,
"<h2 id=\"{0}\" class=\"small-section-header\">\
{1}<a href=\"#{0}\" class=\"anchor\"></a>\
</h2>{2}",
id, title, extra_content
)
}
fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
let name = m.name.unwrap();
info!("Documenting {} on {:?}", name, t.name);
let item_type = m.type_();
let id = cx.derive_id(format!("{}.{}", item_type, name));
let mut content = Buffer::empty_from(w);
document(&mut content, cx, m, Some(t), HeadingOffset::H5);
let toggled = !content.is_empty();
if toggled {
write!(w, "<details class=\"rustdoc-toggle\" open><summary>");
}
write!(w, "<div id=\"{}\" class=\"method has-srclink\">", id);
render_rightside(w, cx, m, t, RenderMode::Normal);
write!(w, "<h4 class=\"code-header\">");
render_assoc_item(
w,
m,
AssocItemLink::Anchor(Some(&id)),
ItemType::Impl,
cx,
RenderMode::Normal,
);
w.write_str("</h4>");
w.write_str("</div>");
if toggled {
write!(w, "</summary>");
w.push_buffer(content);
write!(w, "</details>");
}
}
if !required_types.is_empty() {
write_small_section_header(
w,
"required-associated-types",
"Required Associated Types",
"<div class=\"methods\">",
);
for t in required_types {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
if !provided_types.is_empty() {
write_small_section_header(
w,
"provided-associated-types",
"Provided Associated Types",
"<div class=\"methods\">",
);
for t in provided_types {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
if !required_consts.is_empty() {
write_small_section_header(
w,
"required-associated-consts",
"Required Associated Constants",
"<div class=\"methods\">",
);
for t in required_consts {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
if !provided_consts.is_empty() {
write_small_section_header(
w,
"provided-associated-consts",
"Provided Associated Constants",
"<div class=\"methods\">",
);
for t in provided_consts {
trait_item(w, cx, t, it);
}
w.write_str("</div>");
}
// Output the documentation for each function individually
if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
write_small_section_header(
w,
"required-methods",
"Required Methods",
"<div class=\"methods\">",
);
if let Some(list) = must_implement_one_of_functions.as_deref() {
write!(
w,
"<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
list.iter().join("`, `")
);
}
for m in required_methods {
trait_item(w, cx, m, it);
}
w.write_str("</div>");
}
if !provided_methods.is_empty() {
write_small_section_header(
w,
"provided-methods",
"Provided Methods",
"<div class=\"methods\">",
);
for m in provided_methods {
trait_item(w, cx, m, it);
}
w.write_str("</div>");
}
// If there are methods directly on this trait object, render them here.
render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All);
let cloned_shared = Rc::clone(&cx.shared);
let cache = &cloned_shared.cache;
let mut extern_crates = FxHashSet::default();
if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
// The DefId is for the first Type found with that name. The bool is
// if any Types with the same name but different DefId have been found.
let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
for implementor in implementors {
if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
!did.is_local() {
extern_crates.insert(did.krate);
}
match implementor.inner_impl().for_.without_borrowed_ref() {
clean::Type::Path { ref path } if !path.is_assoc_ty() => {
let did = path.def_id();
let &mut (prev_did, ref mut has_duplicates) =
implementor_dups.entry(path.last()).or_insert((did, false));
if prev_did != did {
*has_duplicates = true;
}
}
_ => {}
}
}
let (local, foreign) =
implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
local.iter().partition(|i| i.inner_impl().kind.is_auto());
synthetic.sort_by(|a, b| compare_impl(a, b, cx));
concrete.sort_by(|a, b| compare_impl(a, b, cx));
if !foreign.is_empty() {
write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
for implementor in foreign {
let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
let assoc_link =
AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
render_impl(
w,
cx,
implementor,
it,
assoc_link,
RenderMode::Normal,
None,
&[],
ImplRenderingParameters {
show_def_docs: false,
show_default_items: false,
show_non_assoc_items: true,
toggle_open_by_default: false,
},
);
}
}
write_small_section_header(
w,
"implementors",
"Implementors",
"<div class=\"item-list\" id=\"implementors-list\">",
);
for implementor in concrete {
render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
}
w.write_str("</div>");
if t.is_auto(cx.tcx()) {
write_small_section_header(
w,
"synthetic-implementors",
"Auto implementors",
"<div class=\"item-list\" id=\"synthetic-implementors-list\">",
);
for implementor in synthetic {
render_implementor(
cx,
implementor,
it,
w,
&implementor_dups,
&collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
);
}
w.write_str("</div>");
}
} else {
// even without any implementations to write in, we still want the heading and list, so the
// implementors javascript file pulled in below has somewhere to write the impls into
write_small_section_header(
w,
"implementors",
"Implementors",
"<div class=\"item-list\" id=\"implementors-list\"></div>",
);
if t.is_auto(cx.tcx()) {
write_small_section_header(
w,
"synthetic-implementors",
"Auto implementors",
"<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
);
}
}
// Include implementors in crates that depend on the current crate.
//
// This is complicated by the way rustdoc is invoked, which is basically
// the same way rustc is invoked: it gets called, one at a time, for each
// crate. When building the rustdocs for the current crate, rustdoc can
// see crate metadata for its dependencies, but cannot see metadata for its
// dependents.
//
// To make this work, we generate a "hook" at this stage, and our
// dependents can "plug in" to it when they build. For simplicity's sake,
// it's [JSONP]: a JavaScript file with the data we need (and can parse),
// surrounded by a tiny wrapper that the Rust side ignores, but allows the
// JavaScript side to include without having to worry about Same Origin
// Policy. The code for *that* is in `write_shared.rs`.
//
// This is further complicated by `#[doc(inline)]`. We want all copies
// of an inlined trait to reference the same JS file, to address complex
// dependency graphs like this one (lower crates depend on higher crates):
//
// ```text
// --------------------------------------------
// | crate A: trait Foo |
// --------------------------------------------
// | |
// -------------------------------- |
// | crate B: impl A::Foo for Bar | |
// -------------------------------- |
// | |
// ---------------------------------------------
// | crate C: #[doc(inline)] use A::Foo as Baz |
// | impl Baz for Quux |
// ---------------------------------------------
// ```
//
// Basically, we want `C::Baz` and `A::Foo` to show the same set of
// impls, which is easier if they both treat `/implementors/A/trait.Foo.js`
// as the Single Source of Truth.
//
// We also want the `impl Baz for Quux` to be written to
// `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
// we're going to want to generate plain HTML for `impl Baz for Quux` too,
// because that'll load faster, and it's better for SEO. And we don't want
// the same impl to show up twice on the same page.
//
// To make this work, the implementors JS file has a structure kinda
// like this:
//
// ```js
// JSONP({
// "B": {"impl A::Foo for Bar"},
// "C": {"impl Baz for Quux"},
// });
// ```
//
// First of all, this means we can rebuild a crate, and it'll replace its own
// data if something changes. That is, `rustdoc` is idempotent. The other
// advantage is that we can list the crates that get included in the HTML,
// and ignore them when doing the JavaScript-based part of rendering.
// So C's HTML will have something like this:
//
// ```html
// <script src="/implementors/A/trait.Foo.js"