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