]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/utils.rs
Rollup merge of #84923 - estebank:as_cache_key-once, r=petrochenkov
[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     MacroKind, Path, PathSegment, Primitive, PrimitiveType, ResolvedPath, Type, TypeBinding,
6 };
7 use crate::core::DocContext;
8 use crate::formats::item_type::ItemType;
9
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
13 use rustc_middle::mir::interpret::ConstValue;
14 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
15 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
16 use rustc_span::symbol::{kw, sym, Symbol};
17 use std::mem;
18
19 #[cfg(test)]
20 mod tests;
21
22 crate fn krate(cx: &mut DocContext<'_>) -> Crate {
23     use crate::visit_lib::LibEmbargoVisitor;
24
25     let krate = cx.tcx.hir().krate();
26     let module = crate::visit_ast::RustdocVisitor::new(cx).visit(krate);
27
28     cx.cache.deref_trait_did = cx.tcx.lang_items().deref_trait();
29     cx.cache.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
30     cx.cache.owned_box_did = cx.tcx.lang_items().owned_box();
31
32     let mut externs = Vec::new();
33     for &cnum in cx.tcx.crates().iter() {
34         externs.push((cnum, cnum.clean(cx)));
35         // Analyze doc-reachability for extern items
36         LibEmbargoVisitor::new(cx).visit_lib(cnum);
37     }
38     externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
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 = LOCAL_CRATE.clean(cx);
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     trait_did: Option<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(ct.clean(cx))),
121         })
122         .collect();
123
124     match trait_did {
125         // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
126         Some(did) if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() => {
127             assert!(ty_kind.is_some());
128             let inputs = match ty_kind {
129                 Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
130                 _ => return GenericArgs::AngleBracketed { args, bindings },
131             };
132             let output = None;
133             // FIXME(#20299) return type comes from a projection now
134             // match types[1].kind {
135             //     ty::Tuple(ref v) if v.is_empty() => None, // -> ()
136             //     _ => Some(types[1].clean(cx))
137             // };
138             GenericArgs::Parenthesized { inputs, output }
139         }
140         _ => GenericArgs::AngleBracketed { args, bindings },
141     }
142 }
143
144 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
145 // from Fn<(A, B,), C> to Fn(A, B) -> C
146 pub(super) fn external_path(
147     cx: &mut DocContext<'_>,
148     name: Symbol,
149     trait_did: Option<DefId>,
150     has_self: bool,
151     bindings: Vec<TypeBinding>,
152     substs: SubstsRef<'_>,
153 ) -> Path {
154     Path {
155         global: false,
156         res: Res::Err,
157         segments: vec![PathSegment {
158             name,
159             args: external_generic_args(cx, trait_did, has_self, bindings, substs),
160         }],
161     }
162 }
163
164 crate fn strip_type(ty: Type) -> Type {
165     match ty {
166         Type::ResolvedPath { path, param_names, did, is_generic } => {
167             Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
168         }
169         Type::Tuple(inner_tys) => {
170             Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
171         }
172         Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
173         Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
174         Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
175         Type::BorrowedRef { lifetime, mutability, type_ } => {
176             Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
177         }
178         Type::QPath { name, self_type, trait_ } => Type::QPath {
179             name,
180             self_type: Box::new(strip_type(*self_type)),
181             trait_: Box::new(strip_type(*trait_)),
182         },
183         _ => ty,
184     }
185 }
186
187 crate fn strip_path(path: &Path) -> Path {
188     let segments = path
189         .segments
190         .iter()
191         .map(|s| PathSegment {
192             name: s.name,
193             args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
194         })
195         .collect();
196
197     Path { global: path.global, res: path.res, segments }
198 }
199
200 crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
201     let segments = match *p {
202         hir::QPath::Resolved(_, ref path) => &path.segments,
203         hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
204         hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
205     };
206
207     let mut s = String::new();
208     for (i, seg) in segments.iter().enumerate() {
209         if i > 0 {
210             s.push_str("::");
211         }
212         if seg.ident.name != kw::PathRoot {
213             s.push_str(&seg.ident.as_str());
214         }
215     }
216     s
217 }
218
219 crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
220     let tcx = cx.tcx;
221
222     for item in items {
223         let target = match *item.kind {
224             ItemKind::TypedefItem(ref t, true) => &t.type_,
225             _ => continue,
226         };
227
228         if let Some(prim) = target.primitive_type() {
229             for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) {
230                 inline::build_impl(cx, None, did, None, ret);
231             }
232         } else if let ResolvedPath { did, .. } = *target {
233             if !did.is_local() {
234                 inline::build_impls(cx, None, did, None, ret);
235             }
236         }
237     }
238 }
239
240 crate trait ToSource {
241     fn to_src(&self, cx: &DocContext<'_>) -> String;
242 }
243
244 impl ToSource for rustc_span::Span {
245     fn to_src(&self, cx: &DocContext<'_>) -> String {
246         debug!("converting span {:?} to snippet", self);
247         let sn = match cx.sess().source_map().span_to_snippet(*self) {
248             Ok(x) => x,
249             Err(_) => String::new(),
250         };
251         debug!("got snippet {}", sn);
252         sn
253     }
254 }
255
256 crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
257     use rustc_hir::*;
258     debug!("trying to get a name from pattern: {:?}", p);
259
260     Symbol::intern(&match p.kind {
261         PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
262         PatKind::Binding(_, _, ident, _) => return ident.name,
263         PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
264         PatKind::Or(ref pats) => pats
265             .iter()
266             .map(|p| name_from_pat(&**p).to_string())
267             .collect::<Vec<String>>()
268             .join(" | "),
269         PatKind::Tuple(ref elts, _) => format!(
270             "({})",
271             elts.iter()
272                 .map(|p| name_from_pat(&**p).to_string())
273                 .collect::<Vec<String>>()
274                 .join(", ")
275         ),
276         PatKind::Box(ref p) => return name_from_pat(&**p),
277         PatKind::Ref(ref p, _) => return name_from_pat(&**p),
278         PatKind::Lit(..) => {
279             warn!(
280                 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
281             );
282             return Symbol::intern("()");
283         }
284         PatKind::Range(..) => return kw::Underscore,
285         PatKind::Slice(ref begin, ref mid, ref end) => {
286             let begin = begin.iter().map(|p| name_from_pat(&**p).to_string());
287             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
288             let end = end.iter().map(|p| name_from_pat(&**p).to_string());
289             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
290         }
291     })
292 }
293
294 crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
295     match n.val {
296         ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) => {
297             let mut s = if let Some(def) = def.as_local() {
298                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
299                 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
300             } else {
301                 inline::print_inlined_const(cx.tcx, def.did)
302             };
303             if let Some(promoted) = promoted {
304                 s.push_str(&format!("::{:?}", promoted))
305             }
306             s
307         }
308         _ => {
309             let mut s = n.to_string();
310             // array lengths are obviously usize
311             if s.ends_with("_usize") {
312                 let n = s.len() - "_usize".len();
313                 s.truncate(n);
314                 if s.ends_with(": ") {
315                     let n = s.len() - ": ".len();
316                     s.truncate(n);
317                 }
318             }
319             s
320         }
321     }
322 }
323
324 crate fn print_evaluated_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<String> {
325     tcx.const_eval_poly(def_id).ok().and_then(|val| {
326         let ty = tcx.type_of(def_id);
327         match (val, ty.kind()) {
328             (_, &ty::Ref(..)) => None,
329             (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
330             (ConstValue::Scalar(_), _) => {
331                 let const_ = ty::Const::from_value(tcx, val, ty);
332                 Some(print_const_with_custom_print_scalar(tcx, const_))
333             }
334             _ => None,
335         }
336     })
337 }
338
339 fn format_integer_with_underscore_sep(num: &str) -> String {
340     let num_chars: Vec<_> = num.chars().collect();
341     let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
342     let chunk_size = match num[num_start_index..].as_bytes() {
343         [b'0', b'b' | b'x', ..] => {
344             num_start_index += 2;
345             4
346         }
347         [b'0', b'o', ..] => {
348             num_start_index += 2;
349             let remaining_chars = num_chars.len() - num_start_index;
350             if remaining_chars <= 6 {
351                 // don't add underscores to Unix permissions like 0755 or 100755
352                 return num.to_string();
353             }
354             3
355         }
356         _ => 3,
357     };
358
359     num_chars[..num_start_index]
360         .iter()
361         .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
362         .collect()
363 }
364
365 fn print_const_with_custom_print_scalar(tcx: TyCtxt<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
366     // Use a slightly different format for integer types which always shows the actual value.
367     // For all other types, fallback to the original `pretty_print_const`.
368     match (ct.val, ct.ty.kind()) {
369         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
370             format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
371         }
372         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
373             let ty = tcx.lift(ct.ty).unwrap();
374             let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
375             let data = int.assert_bits(size);
376             let sign_extended_data = size.sign_extend(data) as i128;
377
378             format!(
379                 "{}{}",
380                 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
381                 i.name_str()
382             )
383         }
384         _ => ct.to_string(),
385     }
386 }
387
388 crate fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
389     if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
390         if let hir::ExprKind::Lit(_) = &expr.kind {
391             return true;
392         }
393
394         if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
395             if let hir::ExprKind::Lit(_) = &expr.kind {
396                 return true;
397             }
398         }
399     }
400
401     false
402 }
403
404 crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
405     let hir = tcx.hir();
406     let value = &hir.body(body).value;
407
408     let snippet = if !value.span.from_expansion() {
409         tcx.sess.source_map().span_to_snippet(value.span).ok()
410     } else {
411         None
412     };
413
414     snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id))
415 }
416
417 /// Given a type Path, resolve it to a Type using the TyCtxt
418 crate fn resolve_type(cx: &mut DocContext<'_>, path: Path, id: hir::HirId) -> Type {
419     debug!("resolve_type({:?},{:?})", path, id);
420
421     let is_generic = match path.res {
422         Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)),
423         Res::SelfTy(..) if path.segments.len() == 1 => {
424             return Generic(kw::SelfUpper);
425         }
426         Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
427             return Generic(Symbol::intern(&path.whole_name()));
428         }
429         Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
430         _ => false,
431     };
432     let did = register_res(cx, path.res);
433     ResolvedPath { path, param_names: None, did, is_generic }
434 }
435
436 crate fn get_auto_trait_and_blanket_impls(
437     cx: &mut DocContext<'tcx>,
438     item_def_id: DefId,
439 ) -> impl Iterator<Item = Item> {
440     let auto_impls = cx
441         .sess()
442         .prof
443         .generic_activity("get_auto_trait_impls")
444         .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
445     let blanket_impls = cx
446         .sess()
447         .prof
448         .generic_activity("get_blanket_impls")
449         .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
450     auto_impls.into_iter().chain(blanket_impls)
451 }
452
453 crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
454     debug!("register_res({:?})", res);
455
456     let (did, kind) = match res {
457         Res::Def(DefKind::Fn, i) => (i, ItemType::Function),
458         Res::Def(DefKind::TyAlias, i) => (i, ItemType::Typedef),
459         Res::Def(DefKind::Enum, i) => (i, ItemType::Enum),
460         Res::Def(DefKind::Trait, i) => (i, ItemType::Trait),
461         Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => {
462             (cx.tcx.parent(i).unwrap(), ItemType::Trait)
463         }
464         Res::Def(DefKind::Struct, i) => (i, ItemType::Struct),
465         Res::Def(DefKind::Union, i) => (i, ItemType::Union),
466         Res::Def(DefKind::Mod, i) => (i, ItemType::Module),
467         Res::Def(DefKind::ForeignTy, i) => (i, ItemType::ForeignType),
468         Res::Def(DefKind::Const, i) => (i, ItemType::Constant),
469         Res::Def(DefKind::Static, i) => (i, ItemType::Static),
470         Res::Def(DefKind::Variant, i) => {
471             (cx.tcx.parent(i).expect("cannot get parent def id"), ItemType::Enum)
472         }
473         Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind {
474             MacroKind::Bang => (i, ItemType::Macro),
475             MacroKind::Attr => (i, ItemType::ProcAttribute),
476             MacroKind::Derive => (i, ItemType::ProcDerive),
477         },
478         Res::Def(DefKind::TraitAlias, i) => (i, ItemType::TraitAlias),
479         Res::SelfTy(Some(def_id), _) => (def_id, ItemType::Trait),
480         Res::SelfTy(_, Some((impl_def_id, _))) => return impl_def_id,
481         _ => return res.def_id(),
482     };
483     if did.is_local() {
484         return did;
485     }
486     inline::record_extern_fqn(cx, did, kind);
487     if let ItemType::Trait = kind {
488         inline::record_extern_trait(cx, did);
489     }
490     did
491 }
492
493 crate fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
494     ImportSource {
495         did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
496         path,
497     }
498 }
499
500 crate fn enter_impl_trait<F, R>(cx: &mut DocContext<'_>, f: F) -> R
501 where
502     F: FnOnce(&mut DocContext<'_>) -> R,
503 {
504     let old_bounds = mem::take(&mut cx.impl_trait_bounds);
505     let r = f(cx);
506     assert!(cx.impl_trait_bounds.is_empty());
507     cx.impl_trait_bounds = old_bounds;
508     r
509 }
510
511 /// Find the nearest parent module of a [`DefId`].
512 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
513     if def_id.is_top_level_module() {
514         // The crate root has no parent. Use it as the root instead.
515         Some(def_id)
516     } else {
517         let mut current = def_id;
518         // The immediate parent might not always be a module.
519         // Find the first parent which is.
520         while let Some(parent) = tcx.parent(current) {
521             if tcx.def_kind(parent) == DefKind::Mod {
522                 return Some(parent);
523             }
524             current = parent;
525         }
526         None
527     }
528 }
529
530 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
531 ///
532 /// ```
533 /// #[doc(hidden)]
534 /// pub fn foo() {}
535 /// ```
536 ///
537 /// This function exists because it runs on `hir::Attributes` whereas the other is a
538 /// `clean::Attributes` method.
539 crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool {
540     attrs.iter().any(|attr| {
541         attr.has_name(sym::doc)
542             && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
543     })
544 }
545
546 /// Return a channel suitable for using in a `doc.rust-lang.org/{channel}` format string.
547 crate fn doc_rust_lang_org_channel() -> &'static str {
548     match env!("CFG_RELEASE_CHANNEL") {
549         "stable" => env!("CFG_RELEASE_NUM"),
550         "beta" => "beta",
551         "nightly" | "dev" => "nightly",
552         // custom build of rustdoc maybe? link to the stable docs just in case
553         _ => "",
554     }
555 }