]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/utils.rs
Rollup merge of #89329 - tmiasko:print-type-sizes-no-fields, r=jackh726
[rust.git] / src / librustdoc / clean / utils.rs
1 use crate::clean::auto_trait::AutoTraitFinder;
2 use crate::clean::blanket_impl::BlanketImplFinder;
3 use crate::clean::{
4     inline, Clean, Crate, ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item,
5     ItemKind, Lifetime, Path, PathSegment, PolyTrait, Primitive, PrimitiveType, ResolvedPath, Type,
6     TypeBinding, Visibility,
7 };
8 use crate::core::DocContext;
9 use crate::formats::item_type::ItemType;
10
11 use rustc_ast as ast;
12 use rustc_ast::tokenstream::TokenTree;
13 use rustc_hir as hir;
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc_middle::mir::interpret::ConstValue;
17 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
18 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
19 use rustc_span::symbol::{kw, sym, Symbol};
20 use std::fmt::Write as _;
21 use std::mem;
22
23 #[cfg(test)]
24 mod tests;
25
26 crate fn krate(cx: &mut DocContext<'_>) -> Crate {
27     use crate::visit_lib::LibEmbargoVisitor;
28
29     let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
30
31     let mut externs = Vec::new();
32     for &cnum in cx.tcx.crates(()).iter() {
33         externs.push(ExternalCrate { crate_num: cnum });
34         // Analyze doc-reachability for extern items
35         LibEmbargoVisitor::new(cx).visit_lib(cnum);
36     }
37     externs.sort_unstable_by_key(|e| e.crate_num);
38
39     // Clean the crate, translating the entire librustc_ast AST to one that is
40     // understood by rustdoc.
41     let mut module = module.clean(cx);
42
43     match *module.kind {
44         ItemKind::ModuleItem(ref module) => {
45             for it in &module.items {
46                 // `compiler_builtins` should be masked too, but we can't apply
47                 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
48                 if it.is_extern_crate()
49                     && (it.attrs.has_doc_flag(sym::masked)
50                         || cx.tcx.is_compiler_builtins(it.def_id.krate()))
51                 {
52                     cx.cache.masked_crates.insert(it.def_id.krate());
53                 }
54             }
55         }
56         _ => unreachable!(),
57     }
58
59     let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
60     let src = local_crate.src(cx.tcx);
61     let name = local_crate.name(cx.tcx);
62     let primitives = local_crate.primitives(cx.tcx);
63     let keywords = local_crate.keywords(cx.tcx);
64     {
65         let m = match *module.kind {
66             ItemKind::ModuleItem(ref mut m) => m,
67             _ => unreachable!(),
68         };
69         m.items.extend(primitives.iter().map(|&(def_id, prim)| {
70             Item::from_def_id_and_parts(
71                 def_id,
72                 Some(prim.as_sym()),
73                 ItemKind::PrimitiveItem(prim),
74                 cx,
75             )
76         }));
77         m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
78             Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx)
79         }));
80     }
81
82     Crate {
83         name,
84         src,
85         module,
86         externs,
87         primitives,
88         external_traits: cx.external_traits.clone(),
89         collapsed: false,
90     }
91 }
92
93 fn external_generic_args(
94     cx: &mut DocContext<'_>,
95     did: DefId,
96     has_self: bool,
97     bindings: Vec<TypeBinding>,
98     substs: SubstsRef<'_>,
99 ) -> GenericArgs {
100     let mut skip_self = has_self;
101     let mut ty_kind = None;
102     let args: Vec<_> = substs
103         .iter()
104         .filter_map(|kind| match kind.unpack() {
105             GenericArgKind::Lifetime(lt) => match lt {
106                 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_), .. }) => {
107                     Some(GenericArg::Lifetime(Lifetime::elided()))
108                 }
109                 _ => lt.clean(cx).map(GenericArg::Lifetime),
110             },
111             GenericArgKind::Type(_) if skip_self => {
112                 skip_self = false;
113                 None
114             }
115             GenericArgKind::Type(ty) => {
116                 ty_kind = Some(ty.kind());
117                 Some(GenericArg::Type(ty.clean(cx)))
118             }
119             GenericArgKind::Const(ct) => Some(GenericArg::Const(Box::new(ct.clean(cx)))),
120         })
121         .collect();
122
123     if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() {
124         let inputs = match ty_kind.unwrap() {
125             ty::Tuple(tys) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
126             _ => return GenericArgs::AngleBracketed { args, bindings },
127         };
128         let output = None;
129         // FIXME(#20299) return type comes from a projection now
130         // match types[1].kind {
131         //     ty::Tuple(ref v) if v.is_empty() => None, // -> ()
132         //     _ => Some(types[1].clean(cx))
133         // };
134         GenericArgs::Parenthesized { inputs, output }
135     } else {
136         GenericArgs::AngleBracketed { args, bindings }
137     }
138 }
139
140 pub(super) fn external_path(
141     cx: &mut DocContext<'_>,
142     did: DefId,
143     has_self: bool,
144     bindings: Vec<TypeBinding>,
145     substs: SubstsRef<'_>,
146 ) -> Path {
147     let def_kind = cx.tcx.def_kind(did);
148     let name = cx.tcx.item_name(did);
149     Path {
150         global: false,
151         res: Res::Def(def_kind, did),
152         segments: vec![PathSegment {
153             name,
154             args: external_generic_args(cx, did, has_self, bindings, substs),
155         }],
156     }
157 }
158
159 crate fn strip_type(ty: Type) -> Type {
160     match ty {
161         Type::ResolvedPath { path, did } => Type::ResolvedPath { path: strip_path(&path), did },
162         Type::DynTrait(mut bounds, lt) => {
163             let first = bounds.remove(0);
164             let stripped_trait = strip_type(first.trait_);
165
166             bounds.insert(
167                 0,
168                 PolyTrait { trait_: stripped_trait, generic_params: first.generic_params },
169             );
170             Type::DynTrait(bounds, lt)
171         }
172         Type::Tuple(inner_tys) => {
173             Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
174         }
175         Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
176         Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
177         Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
178         Type::BorrowedRef { lifetime, mutability, type_ } => {
179             Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
180         }
181         Type::QPath { name, self_type, trait_, self_def_id } => Type::QPath {
182             name,
183             self_def_id,
184             self_type: Box::new(strip_type(*self_type)),
185             trait_: Box::new(strip_type(*trait_)),
186         },
187         _ => ty,
188     }
189 }
190
191 crate fn strip_path(path: &Path) -> Path {
192     let segments = path
193         .segments
194         .iter()
195         .map(|s| PathSegment {
196             name: s.name,
197             args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
198         })
199         .collect();
200
201     Path { global: path.global, res: path.res, segments }
202 }
203
204 crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
205     let segments = match *p {
206         hir::QPath::Resolved(_, ref path) => &path.segments,
207         hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
208         hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
209     };
210
211     let mut s = String::new();
212     for (i, seg) in segments.iter().enumerate() {
213         if i > 0 {
214             s.push_str("::");
215         }
216         if seg.ident.name != kw::PathRoot {
217             s.push_str(&seg.ident.as_str());
218         }
219     }
220     s
221 }
222
223 crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
224     let tcx = cx.tcx;
225
226     for item in items {
227         let target = match *item.kind {
228             ItemKind::TypedefItem(ref t, true) => &t.type_,
229             _ => continue,
230         };
231
232         if let Some(prim) = target.primitive_type() {
233             for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) {
234                 inline::build_impl(cx, None, did, None, ret);
235             }
236         } else if let ResolvedPath { did, .. } = *target {
237             if !did.is_local() {
238                 inline::build_impls(cx, None, did, None, ret);
239             }
240         }
241     }
242 }
243
244 crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
245     use rustc_hir::*;
246     debug!("trying to get a name from pattern: {:?}", p);
247
248     Symbol::intern(&match p.kind {
249         PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
250         PatKind::Binding(_, _, ident, _) => return ident.name,
251         PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
252         PatKind::Or(ref pats) => {
253             pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
254         }
255         PatKind::Tuple(ref elts, _) => format!(
256             "({})",
257             elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
258         ),
259         PatKind::Box(ref p) => return name_from_pat(&**p),
260         PatKind::Ref(ref p, _) => return name_from_pat(&**p),
261         PatKind::Lit(..) => {
262             warn!(
263                 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
264             );
265             return Symbol::intern("()");
266         }
267         PatKind::Range(..) => return kw::Underscore,
268         PatKind::Slice(ref begin, ref mid, ref end) => {
269             let begin = begin.iter().map(|p| name_from_pat(p).to_string());
270             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
271             let end = end.iter().map(|p| name_from_pat(p).to_string());
272             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
273         }
274     })
275 }
276
277 crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
278     match n.val {
279         ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs_: _, promoted }) => {
280             let mut s = if let Some(def) = def.as_local() {
281                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
282                 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
283             } else {
284                 inline::print_inlined_const(cx.tcx, def.did)
285             };
286             if let Some(promoted) = promoted {
287                 s.push_str(&format!("::{:?}", promoted))
288             }
289             s
290         }
291         _ => {
292             let mut s = n.to_string();
293             // array lengths are obviously usize
294             if s.ends_with("_usize") {
295                 let n = s.len() - "_usize".len();
296                 s.truncate(n);
297                 if s.ends_with(": ") {
298                     let n = s.len() - ": ".len();
299                     s.truncate(n);
300                 }
301             }
302             s
303         }
304     }
305 }
306
307 crate fn print_evaluated_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<String> {
308     tcx.const_eval_poly(def_id).ok().and_then(|val| {
309         let ty = tcx.type_of(def_id);
310         match (val, ty.kind()) {
311             (_, &ty::Ref(..)) => None,
312             (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
313             (ConstValue::Scalar(_), _) => {
314                 let const_ = ty::Const::from_value(tcx, val, ty);
315                 Some(print_const_with_custom_print_scalar(tcx, const_))
316             }
317             _ => None,
318         }
319     })
320 }
321
322 fn format_integer_with_underscore_sep(num: &str) -> String {
323     let num_chars: Vec<_> = num.chars().collect();
324     let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
325     let chunk_size = match num[num_start_index..].as_bytes() {
326         [b'0', b'b' | b'x', ..] => {
327             num_start_index += 2;
328             4
329         }
330         [b'0', b'o', ..] => {
331             num_start_index += 2;
332             let remaining_chars = num_chars.len() - num_start_index;
333             if remaining_chars <= 6 {
334                 // don't add underscores to Unix permissions like 0755 or 100755
335                 return num.to_string();
336             }
337             3
338         }
339         _ => 3,
340     };
341
342     num_chars[..num_start_index]
343         .iter()
344         .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
345         .collect()
346 }
347
348 fn print_const_with_custom_print_scalar(tcx: TyCtxt<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
349     // Use a slightly different format for integer types which always shows the actual value.
350     // For all other types, fallback to the original `pretty_print_const`.
351     match (ct.val, ct.ty.kind()) {
352         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
353             format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
354         }
355         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
356             let ty = tcx.lift(ct.ty).unwrap();
357             let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
358             let data = int.assert_bits(size);
359             let sign_extended_data = size.sign_extend(data) as i128;
360
361             format!(
362                 "{}{}",
363                 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
364                 i.name_str()
365             )
366         }
367         _ => ct.to_string(),
368     }
369 }
370
371 crate fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
372     if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
373         if let hir::ExprKind::Lit(_) = &expr.kind {
374             return true;
375         }
376
377         if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
378             if let hir::ExprKind::Lit(_) = &expr.kind {
379                 return true;
380             }
381         }
382     }
383
384     false
385 }
386
387 crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
388     let hir = tcx.hir();
389     let value = &hir.body(body).value;
390
391     let snippet = if !value.span.from_expansion() {
392         tcx.sess.source_map().span_to_snippet(value.span).ok()
393     } else {
394         None
395     };
396
397     snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id))
398 }
399
400 /// Given a type Path, resolve it to a Type using the TyCtxt
401 crate fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
402     debug!("resolve_type({:?})", path);
403
404     match path.res {
405         Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
406         Res::SelfTy(..) if path.segments.len() == 1 => Generic(kw::SelfUpper),
407         Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
408         _ => {
409             let did = register_res(cx, path.res);
410             ResolvedPath { path, did }
411         }
412     }
413 }
414
415 crate fn get_auto_trait_and_blanket_impls(
416     cx: &mut DocContext<'tcx>,
417     item_def_id: DefId,
418 ) -> impl Iterator<Item = Item> {
419     let auto_impls = cx
420         .sess()
421         .prof
422         .generic_activity("get_auto_trait_impls")
423         .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
424     let blanket_impls = cx
425         .sess()
426         .prof
427         .generic_activity("get_blanket_impls")
428         .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
429     auto_impls.into_iter().chain(blanket_impls)
430 }
431
432 /// If `res` has a documentation page associated, store it in the cache.
433 ///
434 /// This is later used by [`href()`] to determine the HTML link for the item.
435 ///
436 /// [`href()`]: crate::html::format::href
437 crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
438     use DefKind::*;
439     debug!("register_res({:?})", res);
440
441     let (did, kind) = match res {
442         Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => {
443             // associated items are documented, but on the page of their parent
444             (cx.tcx.parent(i).unwrap(), ItemType::Trait)
445         }
446         Res::Def(DefKind::Variant, i) => {
447             // variant items are documented, but on the page of their parent
448             (cx.tcx.parent(i).expect("cannot get parent def id"), ItemType::Enum)
449         }
450         // Each of these have their own page.
451         Res::Def(
452             kind
453             @
454             (Fn | TyAlias | Enum | Trait | Struct | Union | Mod | ForeignTy | Const | Static
455             | Macro(..) | TraitAlias),
456             i,
457         ) => (i, kind.into()),
458         // This is part of a trait definition; document the trait.
459         Res::SelfTy(Some(trait_def_id), _) => (trait_def_id, ItemType::Trait),
460         // This is an inherent impl; it doesn't have its own page.
461         Res::SelfTy(None, Some((impl_def_id, _))) => return impl_def_id,
462         Res::SelfTy(None, None)
463         | Res::PrimTy(_)
464         | Res::ToolMod
465         | Res::SelfCtor(_)
466         | Res::Local(_)
467         | Res::NonMacroAttr(_)
468         | Res::Err => return res.def_id(),
469         Res::Def(
470             TyParam | ConstParam | Ctor(..) | ExternCrate | Use | ForeignMod | AnonConst | OpaqueTy
471             | Field | LifetimeParam | GlobalAsm | Impl | Closure | Generator,
472             id,
473         ) => return id,
474     };
475     if did.is_local() {
476         return did;
477     }
478     inline::record_extern_fqn(cx, did, kind);
479     if let ItemType::Trait = kind {
480         inline::record_extern_trait(cx, did);
481     }
482     did
483 }
484
485 crate fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
486     ImportSource {
487         did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
488         path,
489     }
490 }
491
492 crate fn enter_impl_trait<F, R>(cx: &mut DocContext<'_>, f: F) -> R
493 where
494     F: FnOnce(&mut DocContext<'_>) -> R,
495 {
496     let old_bounds = mem::take(&mut cx.impl_trait_bounds);
497     let r = f(cx);
498     assert!(cx.impl_trait_bounds.is_empty());
499     cx.impl_trait_bounds = old_bounds;
500     r
501 }
502
503 /// Find the nearest parent module of a [`DefId`].
504 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
505     if def_id.is_top_level_module() {
506         // The crate root has no parent. Use it as the root instead.
507         Some(def_id)
508     } else {
509         let mut current = def_id;
510         // The immediate parent might not always be a module.
511         // Find the first parent which is.
512         while let Some(parent) = tcx.parent(current) {
513             if tcx.def_kind(parent) == DefKind::Mod {
514                 return Some(parent);
515             }
516             current = parent;
517         }
518         None
519     }
520 }
521
522 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
523 ///
524 /// ```
525 /// #[doc(hidden)]
526 /// pub fn foo() {}
527 /// ```
528 ///
529 /// This function exists because it runs on `hir::Attributes` whereas the other is a
530 /// `clean::Attributes` method.
531 crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool {
532     attrs.iter().any(|attr| {
533         attr.has_name(sym::doc)
534             && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
535     })
536 }
537
538 /// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
539 /// so that the channel is consistent.
540 ///
541 /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
542 crate const DOC_RUST_LANG_ORG_CHANNEL: &'static str = env!("DOC_RUST_LANG_ORG_CHANNEL");
543
544 /// Render a sequence of macro arms in a format suitable for displaying to the user
545 /// as part of an item declaration.
546 pub(super) fn render_macro_arms<'a>(
547     matchers: impl Iterator<Item = &'a TokenTree>,
548     arm_delim: &str,
549 ) -> String {
550     let mut out = String::new();
551     for matcher in matchers {
552         writeln!(out, "    {} => {{ ... }}{}", render_macro_matcher(matcher), arm_delim).unwrap();
553     }
554     out
555 }
556
557 /// Render a macro matcher in a format suitable for displaying to the user
558 /// as part of an item declaration.
559 pub(super) fn render_macro_matcher(matcher: &TokenTree) -> String {
560     rustc_ast_pretty::pprust::tt_to_string(matcher)
561 }
562
563 pub(super) fn display_macro_source(
564     cx: &mut DocContext<'_>,
565     name: Symbol,
566     def: &ast::MacroDef,
567     def_id: DefId,
568     vis: impl Clean<Visibility>,
569 ) -> String {
570     let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
571     // Extract the spans of all matchers. They represent the "interface" of the macro.
572     let matchers = tts.chunks(4).map(|arm| &arm[0]);
573
574     if def.macro_rules {
575         format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(matchers, ";"))
576     } else {
577         let vis = vis.clean(cx);
578
579         if matchers.len() <= 1 {
580             format!(
581                 "{}macro {}{} {{\n    ...\n}}",
582                 vis.to_src_with_space(cx.tcx, def_id),
583                 name,
584                 matchers.map(render_macro_matcher).collect::<String>(),
585             )
586         } else {
587             format!(
588                 "{}macro {} {{\n{}}}",
589                 vis.to_src_with_space(cx.tcx, def_id),
590                 name,
591                 render_macro_arms(matchers, ","),
592             )
593         }
594     }
595 }