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