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
use std::iter::once;
use std::sync::Arc;
use thin_vec::ThinVec;
use rustc_ast as ast;
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::DefId;
use rustc_hir::Mutability;
use rustc_metadata::creader::{CStore, LoadedMacro};
use rustc_middle::ty::{self, TyCtxt};
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol};
use crate::clean::{
self, clean_fn_decl_from_did_and_sig, clean_generics, clean_impl_item, clean_middle_assoc_item,
clean_middle_field, clean_middle_ty, clean_trait_ref_with_bindings, clean_ty,
clean_ty_generics, clean_variant_def, clean_visibility, utils, Attributes, AttributesExt,
ImplKind, ItemId, Type, Visibility,
};
use crate::core::DocContext;
use crate::formats::item_type::ItemType;
pub(crate) fn try_inline(
cx: &mut DocContext<'_>,
parent_module: DefId,
import_def_id: Option<DefId>,
res: Res,
name: Symbol,
attrs: Option<&[ast::Attribute]>,
visited: &mut FxHashSet<DefId>,
) -> Option<Vec<clean::Item>> {
let did = res.opt_def_id()?;
if did.is_local() {
return None;
}
let mut ret = Vec::new();
debug!("attrs={:?}", attrs);
let attrs_clone = attrs;
let kind = match res {
Res::Def(DefKind::Trait, did) => {
record_extern_fqn(cx, did, ItemType::Trait);
build_impls(cx, Some(parent_module), did, attrs, &mut ret);
clean::TraitItem(Box::new(build_external_trait(cx, did)))
}
Res::Def(DefKind::Fn, did) => {
record_extern_fqn(cx, did, ItemType::Function);
clean::FunctionItem(build_external_function(cx, did))
}
Res::Def(DefKind::Struct, did) => {
record_extern_fqn(cx, did, ItemType::Struct);
build_impls(cx, Some(parent_module), did, attrs, &mut ret);
clean::StructItem(build_struct(cx, did))
}
Res::Def(DefKind::Union, did) => {
record_extern_fqn(cx, did, ItemType::Union);
build_impls(cx, Some(parent_module), did, attrs, &mut ret);
clean::UnionItem(build_union(cx, did))
}
Res::Def(DefKind::TyAlias, did) => {
record_extern_fqn(cx, did, ItemType::Typedef);
build_impls(cx, Some(parent_module), did, attrs, &mut ret);
clean::TypedefItem(build_type_alias(cx, did))
}
Res::Def(DefKind::Enum, did) => {
record_extern_fqn(cx, did, ItemType::Enum);
build_impls(cx, Some(parent_module), did, attrs, &mut ret);
clean::EnumItem(build_enum(cx, did))
}
Res::Def(DefKind::ForeignTy, did) => {
record_extern_fqn(cx, did, ItemType::ForeignType);
build_impls(cx, Some(parent_module), did, attrs, &mut ret);
clean::ForeignTypeItem
}
Res::Def(DefKind::Variant, _) => return None,
Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
Res::Def(DefKind::Mod, did) => {
record_extern_fqn(cx, did, ItemType::Module);
clean::ModuleItem(build_module(cx, did, visited))
}
Res::Def(DefKind::Static(_), did) => {
record_extern_fqn(cx, did, ItemType::Static);
clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
}
Res::Def(DefKind::Const, did) => {
record_extern_fqn(cx, did, ItemType::Constant);
clean::ConstantItem(build_const(cx, did))
}
Res::Def(DefKind::Macro(kind), did) => {
let mac = build_macro(cx, did, name, import_def_id);
let type_kind = match kind {
MacroKind::Bang => ItemType::Macro,
MacroKind::Attr => ItemType::ProcAttribute,
MacroKind::Derive => ItemType::ProcDerive,
};
record_extern_fqn(cx, did, type_kind);
mac
}
_ => return None,
};
let (attrs, cfg) = merge_attrs(cx, Some(parent_module), load_attrs(cx, did), attrs_clone);
cx.inlined.insert(did.into());
let mut item = clean::Item::from_def_id_and_attrs_and_parts(
did,
Some(name),
kind,
Box::new(attrs),
cx,
cfg,
);
if let Some(import_def_id) = import_def_id {
item.visibility = clean_visibility(cx.tcx.visibility(import_def_id));
}
ret.push(item);
Some(ret)
}
pub(crate) fn try_inline_glob(
cx: &mut DocContext<'_>,
res: Res,
visited: &mut FxHashSet<DefId>,
inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
) -> Option<Vec<clean::Item>> {
let did = res.opt_def_id()?;
if did.is_local() {
return None;
}
match res {
Res::Def(DefKind::Mod, did) => {
let mut items = build_module_items(cx, did, visited, inlined_names);
items.drain_filter(|item| {
if let Some(name) = item.name {
!inlined_names.insert((item.type_(), name))
} else {
false
}
});
Some(items)
}
_ => None,
}
}
pub(crate) fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> &'hir [ast::Attribute] {
cx.tcx.get_attrs_unchecked(did)
}
pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
let crate_name = cx.tcx.crate_name(did.krate);
let relative =
cx.tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
let fqn = if let ItemType::Macro = kind {
if matches!(
CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.sess()),
LoadedMacro::MacroDef(def, _)
if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
if !ast_def.macro_rules)
) {
once(crate_name).chain(relative).collect()
} else {
vec![crate_name, relative.last().expect("relative was empty")]
}
} else {
once(crate_name).chain(relative).collect()
};
if did.is_local() {
cx.cache.exact_paths.insert(did, fqn);
} else {
cx.cache.external_paths.insert(did, (fqn, kind));
}
}
pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
let trait_items = cx
.tcx
.associated_items(did)
.in_definition_order()
.map(|item| {
clean::Item { visibility: Visibility::Inherited, ..clean_middle_assoc_item(item, cx) }
})
.collect();
let predicates = cx.tcx.predicates_of(did);
let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
let generics = filter_non_trait_generics(did, generics);
let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds }
}
fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> Box<clean::Function> {
let sig = cx.tcx.fn_sig(did);
let predicates = cx.tcx.predicates_of(did);
let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
let decl = clean_fn_decl_from_did_and_sig(cx, Some(did), sig);
(generics, decl)
});
Box::new(clean::Function { decl, generics })
}
fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
let predicates = cx.tcx.explicit_predicates_of(did);
clean::Enum {
generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
variants: cx.tcx.adt_def(did).variants().iter().map(|v| clean_variant_def(v, cx)).collect(),
}
}
fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
let predicates = cx.tcx.explicit_predicates_of(did);
let variant = cx.tcx.adt_def(did).non_enum_variant();
clean::Struct {
struct_type: variant.ctor_kind,
generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
fields: variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect(),
}
}
fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
let predicates = cx.tcx.explicit_predicates_of(did);
let variant = cx.tcx.adt_def(did).non_enum_variant();
let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
let fields = variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect();
clean::Union { generics, fields }
}
fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> Box<clean::Typedef> {
let predicates = cx.tcx.explicit_predicates_of(did);
let type_ = clean_middle_ty(cx.tcx.type_of(did), cx, Some(did));
Box::new(clean::Typedef {
type_,
generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
item_type: None,
})
}
pub(crate) fn build_impls(
cx: &mut DocContext<'_>,
parent_module: Option<DefId>,
did: DefId,
attrs: Option<&[ast::Attribute]>,
ret: &mut Vec<clean::Item>,
) {
let _prof_timer = cx.tcx.sess.prof.generic_activity("build_inherent_impls");
let tcx = cx.tcx;
for &did in tcx.inherent_impls(did).iter() {
build_impl(cx, parent_module, did, attrs, ret);
}
}
pub(crate) fn merge_attrs(
cx: &mut DocContext<'_>,
parent_module: Option<DefId>,
old_attrs: &[ast::Attribute],
new_attrs: Option<&[ast::Attribute]>,
) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
if let Some(inner) = new_attrs {
let mut both = inner.to_vec();
both.extend_from_slice(old_attrs);
(
if let Some(new_id) = parent_module {
Attributes::from_ast_with_additional(old_attrs, (inner, new_id))
} else {
Attributes::from_ast(&both)
},
both.cfg(cx.tcx, &cx.cache.hidden_cfg),
)
} else {
(Attributes::from_ast(&old_attrs), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg))
}
}
pub(crate) fn build_impl(
cx: &mut DocContext<'_>,
parent_module: Option<DefId>,
did: DefId,
attrs: Option<&[ast::Attribute]>,
ret: &mut Vec<clean::Item>,
) {
if !cx.inlined.insert(did.into()) {
return;
}
let _prof_timer = cx.tcx.sess.prof.generic_activity("build_impl");
let tcx = cx.tcx;
let associated_trait = tcx.impl_trait_ref(did);
if !did.is_local() {
if let Some(traitref) = associated_trait {
let did = traitref.def_id;
if !cx.cache.access_levels.is_public(did) {
return;
}
if let Some(stab) = tcx.lookup_stability(did) {
if stab.is_unstable() && stab.feature == sym::rustc_private {
return;
}
}
}
}
let impl_item = match did.as_local() {
Some(did) => match &tcx.hir().expect_item(did).kind {
hir::ItemKind::Impl(impl_) => Some(impl_),
_ => panic!("`DefID` passed to `build_impl` is not an `impl"),
},
None => None,
};
let for_ = match &impl_item {
Some(impl_) => clean_ty(impl_.self_ty, cx),
None => clean_middle_ty(tcx.type_of(did), cx, Some(did)),
};
if !did.is_local() {
if let Some(did) = for_.def_id(&cx.cache) {
if !cx.cache.access_levels.is_public(did) {
return;
}
if let Some(stab) = tcx.lookup_stability(did) {
if stab.is_unstable() && stab.feature == sym::rustc_private {
return;
}
}
}
}
let document_hidden = cx.render_options.document_hidden;
let predicates = tcx.explicit_predicates_of(did);
let (trait_items, generics) = match impl_item {
Some(impl_) => (
impl_
.items
.iter()
.map(|item| tcx.hir().impl_item(item.id))
.filter(|item| {
if document_hidden {
return true;
}
if let Some(associated_trait) = associated_trait {
let assoc_kind = match item.kind {
hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
hir::ImplItemKind::TyAlias(..) => ty::AssocKind::Type,
};
let trait_item = tcx
.associated_items(associated_trait.def_id)
.find_by_name_and_kind(
tcx,
item.ident,
assoc_kind,
associated_trait.def_id,
)
.unwrap(); !tcx.is_doc_hidden(trait_item.def_id)
} else {
true
}
})
.map(|item| clean_impl_item(item, cx))
.collect::<Vec<_>>(),
clean_generics(impl_.generics, cx),
),
None => (
tcx.associated_items(did)
.in_definition_order()
.filter(|item| {
if let Some(associated_trait) = associated_trait {
let trait_item = tcx
.associated_items(associated_trait.def_id)
.find_by_name_and_kind(
tcx,
item.ident(tcx),
item.kind,
associated_trait.def_id,
)
.unwrap(); !tcx.is_doc_hidden(trait_item.def_id)
} else {
item.visibility(tcx).is_public()
}
})
.map(|item| clean_middle_assoc_item(item, cx))
.collect::<Vec<_>>(),
clean::enter_impl_trait(cx, |cx| {
clean_ty_generics(cx, tcx.generics_of(did), predicates)
}),
),
};
let polarity = tcx.impl_polarity(did);
let trait_ = associated_trait.map(|t| clean_trait_ref_with_bindings(cx, t, ThinVec::new()));
if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
super::build_deref_target_impls(cx, &trait_items, ret);
}
let mut stack: Vec<&Type> = vec![&for_];
if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
if tcx.is_doc_hidden(did) {
return;
}
}
if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
stack.extend(generics);
}
while let Some(ty) = stack.pop() {
if let Some(did) = ty.def_id(&cx.cache) {
if tcx.is_doc_hidden(did) {
return;
}
}
if let Some(generics) = ty.generics() {
stack.extend(generics);
}
}
if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
record_extern_trait(cx, did);
}
let (merged_attrs, cfg) = merge_attrs(cx, parent_module, load_attrs(cx, did), attrs);
trace!("merged_attrs={:?}", merged_attrs);
trace!(
"build_impl: impl {:?} for {:?}",
trait_.as_ref().map(|t| t.def_id()),
for_.def_id(&cx.cache)
);
ret.push(clean::Item::from_def_id_and_attrs_and_parts(
did,
None,
clean::ImplItem(Box::new(clean::Impl {
unsafety: hir::Unsafety::Normal,
generics,
trait_,
for_,
items: trait_items,
polarity,
kind: if utils::has_doc_flag(tcx, did, sym::fake_variadic) {
ImplKind::FakeVaradic
} else {
ImplKind::Normal
},
})),
Box::new(merged_attrs),
cx,
cfg,
));
}
fn build_module(
cx: &mut DocContext<'_>,
did: DefId,
visited: &mut FxHashSet<DefId>,
) -> clean::Module {
let items = build_module_items(cx, did, visited, &mut FxHashSet::default());
let span = clean::Span::new(cx.tcx.def_span(did));
clean::Module { items, span }
}
fn build_module_items(
cx: &mut DocContext<'_>,
did: DefId,
visited: &mut FxHashSet<DefId>,
inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
) -> Vec<clean::Item> {
let mut items = Vec::new();
for &item in cx.tcx.module_children(did).iter() {
if item.vis.is_public() {
let res = item.res.expect_non_local();
if let Some(def_id) = res.mod_def_id() {
if did == def_id
|| inlined_names.contains(&(ItemType::Module, item.ident.name))
|| !visited.insert(def_id)
{
continue;
}
}
if let Res::PrimTy(p) = res {
let prim_ty = clean::PrimitiveType::from(p);
items.push(clean::Item {
name: None,
attrs: Box::new(clean::Attributes::default()),
item_id: ItemId::Primitive(prim_ty, did.krate),
visibility: clean::Public,
kind: Box::new(clean::ImportItem(clean::Import::new_simple(
item.ident.name,
clean::ImportSource {
path: clean::Path {
res,
segments: vec![clean::PathSegment {
name: prim_ty.as_sym(),
args: clean::GenericArgs::AngleBracketed {
args: Default::default(),
bindings: ThinVec::new(),
},
}],
},
did: None,
},
true,
))),
cfg: None,
});
} else if let Some(i) = try_inline(cx, did, None, res, item.ident.name, None, visited) {
items.extend(i)
}
}
}
items
}
pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
if let Some(did) = did.as_local() {
let hir_id = tcx.hir().local_def_id_to_hir_id(did);
rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
} else {
tcx.rendered_const(did).clone()
}
}
fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
clean::Constant {
type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
kind: clean::ConstantKind::Extern { def_id },
}
}
fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
clean::Static {
type_: clean_middle_ty(cx.tcx.type_of(did), cx, Some(did)),
mutability: if mutable { Mutability::Mut } else { Mutability::Not },
expr: None,
}
}
fn build_macro(
cx: &mut DocContext<'_>,
def_id: DefId,
name: Symbol,
import_def_id: Option<DefId>,
) -> clean::ItemKind {
match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
LoadedMacro::MacroDef(item_def, _) => {
if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
let vis = clean_visibility(cx.tcx.visibility(import_def_id.unwrap_or(def_id)));
clean::MacroItem(clean::Macro {
source: utils::display_macro_source(cx, name, def, def_id, vis),
})
} else {
unreachable!()
}
}
LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
kind: ext.macro_kind(),
helpers: ext.helper_attrs,
}),
}
}
fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
for pred in &mut g.where_predicates {
match *pred {
clean::WherePredicate::BoundPredicate {
ty: clean::Generic(ref s),
ref mut bounds,
..
} if *s == kw::SelfUpper => {
bounds.retain(|bound| match bound {
clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => {
trait_.def_id() != trait_did
}
_ => true,
});
}
_ => {}
}
}
g.where_predicates.retain(|pred| match pred {
clean::WherePredicate::BoundPredicate {
ty: clean::QPath(box clean::QPathData { self_type: clean::Generic(ref s), trait_, .. }),
bounds,
..
} => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did),
_ => true,
});
g
}
fn separate_supertrait_bounds(
mut g: clean::Generics,
) -> (clean::Generics, Vec<clean::GenericBound>) {
let mut ty_bounds = Vec::new();
g.where_predicates.retain(|pred| match *pred {
clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. }
if *s == kw::SelfUpper =>
{
ty_bounds.extend(bounds.iter().cloned());
false
}
_ => true,
});
(g, ty_bounds)
}
pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
if did.is_local() {
return;
}
{
if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
{
return;
}
}
{
cx.active_extern_traits.insert(did);
}
debug!("record_extern_trait: {:?}", did);
let trait_ = build_external_trait(cx, did);
let trait_ = clean::TraitWithExtraInfo {
trait_,
is_notable: clean::utils::has_doc_flag(cx.tcx, did, sym::notable_trait),
};
cx.external_traits.borrow_mut().insert(did, trait_);
cx.active_extern_traits.remove(&did);
}