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