]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/utils.rs
Auto merge of #82603 - RalfJung:miri, r=RalfJung
[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, MacroKind, Path, PathSegment, Primitive, PrimitiveType, ResolvedPath, Type,
6     TypeBinding, TypeKind,
7 };
8 use crate::core::DocContext;
9
10 use rustc_data_structures::fx::FxHashSet;
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, Ty, TyCtxt};
17 use rustc_span::symbol::{kw, sym, Symbol};
18 use std::mem;
19
20 crate fn krate(mut cx: &mut DocContext<'_>) -> Crate {
21     use crate::visit_lib::LibEmbargoVisitor;
22
23     let krate = cx.tcx.hir().krate();
24     let module = crate::visit_ast::RustdocVisitor::new(&mut cx).visit(krate);
25
26     cx.renderinfo.deref_trait_did = cx.tcx.lang_items().deref_trait();
27     cx.renderinfo.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
28     cx.renderinfo.owned_box_did = cx.tcx.lang_items().owned_box();
29
30     let mut externs = Vec::new();
31     for &cnum in cx.tcx.crates().iter() {
32         externs.push((cnum, cnum.clean(cx)));
33         // Analyze doc-reachability for extern items
34         LibEmbargoVisitor::new(&mut cx).visit_lib(cnum);
35     }
36     externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
37
38     // Clean the crate, translating the entire librustc_ast AST to one that is
39     // understood by rustdoc.
40     let mut module = module.clean(cx);
41     let mut masked_crates = FxHashSet::default();
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                     masked_crates.insert(it.def_id.krate);
53                 }
54             }
55         }
56         _ => unreachable!(),
57     }
58
59     let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx);
60     {
61         let m = match *module.kind {
62             ItemKind::ModuleItem(ref mut m) => m,
63             _ => unreachable!(),
64         };
65         m.items.extend(primitives.iter().map(|&(def_id, prim)| {
66             Item::from_def_id_and_parts(
67                 def_id,
68                 Some(prim.as_sym()),
69                 ItemKind::PrimitiveItem(prim),
70                 cx,
71             )
72         }));
73         m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
74             Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem(kw), cx)
75         }));
76     }
77
78     Crate {
79         name,
80         version: None,
81         src,
82         module: Some(module),
83         externs,
84         primitives,
85         external_traits: cx.external_traits.clone(),
86         masked_crates,
87         collapsed: false,
88     }
89 }
90
91 fn external_generic_args(
92     cx: &mut DocContext<'_>,
93     trait_did: Option<DefId>,
94     has_self: bool,
95     bindings: Vec<TypeBinding>,
96     substs: SubstsRef<'_>,
97 ) -> GenericArgs {
98     let mut skip_self = has_self;
99     let mut ty_kind = None;
100     let args: Vec<_> = substs
101         .iter()
102         .filter_map(|kind| match kind.unpack() {
103             GenericArgKind::Lifetime(lt) => match lt {
104                 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrAnon(_) }) => {
105                     Some(GenericArg::Lifetime(Lifetime::elided()))
106                 }
107                 _ => lt.clean(cx).map(GenericArg::Lifetime),
108             },
109             GenericArgKind::Type(_) if skip_self => {
110                 skip_self = false;
111                 None
112             }
113             GenericArgKind::Type(ty) => {
114                 ty_kind = Some(ty.kind());
115                 Some(GenericArg::Type(ty.clean(cx)))
116             }
117             GenericArgKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
118         })
119         .collect();
120
121     match trait_did {
122         // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
123         Some(did) if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() => {
124             assert!(ty_kind.is_some());
125             let inputs = match ty_kind {
126                 Some(ty::Tuple(ref 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         }
137         _ => GenericArgs::AngleBracketed { args, bindings },
138     }
139 }
140
141 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
142 // from Fn<(A, B,), C> to Fn(A, B) -> C
143 pub(super) fn external_path(
144     cx: &mut DocContext<'_>,
145     name: Symbol,
146     trait_did: Option<DefId>,
147     has_self: bool,
148     bindings: Vec<TypeBinding>,
149     substs: SubstsRef<'_>,
150 ) -> Path {
151     Path {
152         global: false,
153         res: Res::Err,
154         segments: vec![PathSegment {
155             name,
156             args: external_generic_args(cx, trait_did, has_self, bindings, substs),
157         }],
158     }
159 }
160
161 crate fn strip_type(ty: Type) -> Type {
162     match ty {
163         Type::ResolvedPath { path, param_names, did, is_generic } => {
164             Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
165         }
166         Type::Tuple(inner_tys) => {
167             Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
168         }
169         Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
170         Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
171         Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
172         Type::BorrowedRef { lifetime, mutability, type_ } => {
173             Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
174         }
175         Type::QPath { name, self_type, trait_ } => Type::QPath {
176             name,
177             self_type: Box::new(strip_type(*self_type)),
178             trait_: Box::new(strip_type(*trait_)),
179         },
180         _ => ty,
181     }
182 }
183
184 crate fn strip_path(path: &Path) -> Path {
185     let segments = path
186         .segments
187         .iter()
188         .map(|s| PathSegment {
189             name: s.name,
190             args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
191         })
192         .collect();
193
194     Path { global: path.global, res: path.res, segments }
195 }
196
197 crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
198     let segments = match *p {
199         hir::QPath::Resolved(_, ref path) => &path.segments,
200         hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
201         hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
202     };
203
204     let mut s = String::new();
205     for (i, seg) in segments.iter().enumerate() {
206         if i > 0 {
207             s.push_str("::");
208         }
209         if seg.ident.name != kw::PathRoot {
210             s.push_str(&seg.ident.as_str());
211         }
212     }
213     s
214 }
215
216 crate fn build_deref_target_impls(cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
217     let tcx = cx.tcx;
218
219     for item in items {
220         let target = match *item.kind {
221             ItemKind::TypedefItem(ref t, true) => &t.type_,
222             _ => continue,
223         };
224
225         if let Some(prim) = target.primitive_type() {
226             for &did in prim.impls(tcx).iter().filter(|did| !did.is_local()) {
227                 inline::build_impl(cx, None, did, None, ret);
228             }
229         } else if let ResolvedPath { did, .. } = *target {
230             if !did.is_local() {
231                 inline::build_impls(cx, None, did, None, ret);
232             }
233         }
234     }
235 }
236
237 crate trait ToSource {
238     fn to_src(&self, cx: &DocContext<'_>) -> String;
239 }
240
241 impl ToSource for rustc_span::Span {
242     fn to_src(&self, cx: &DocContext<'_>) -> String {
243         debug!("converting span {:?} to snippet", self);
244         let sn = match cx.sess().source_map().span_to_snippet(*self) {
245             Ok(x) => x,
246             Err(_) => String::new(),
247         };
248         debug!("got snippet {}", sn);
249         sn
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 => 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::Struct(ref name, ref fields, etc) => format!(
262             "{} {{ {}{} }}",
263             qpath_to_string(name),
264             fields
265                 .iter()
266                 .map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat)))
267                 .collect::<Vec<String>>()
268                 .join(", "),
269             if etc { ", .." } else { "" }
270         ),
271         PatKind::Or(ref pats) => pats
272             .iter()
273             .map(|p| name_from_pat(&**p).to_string())
274             .collect::<Vec<String>>()
275             .join(" | "),
276         PatKind::Tuple(ref elts, _) => format!(
277             "({})",
278             elts.iter()
279                 .map(|p| name_from_pat(&**p).to_string())
280                 .collect::<Vec<String>>()
281                 .join(", ")
282         ),
283         PatKind::Box(ref p) => return name_from_pat(&**p),
284         PatKind::Ref(ref p, _) => return name_from_pat(&**p),
285         PatKind::Lit(..) => {
286             warn!(
287                 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
288             );
289             return Symbol::intern("()");
290         }
291         PatKind::Range(..) => return kw::Underscore,
292         PatKind::Slice(ref begin, ref mid, ref end) => {
293             let begin = begin.iter().map(|p| name_from_pat(&**p).to_string());
294             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
295             let end = end.iter().map(|p| name_from_pat(&**p).to_string());
296             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
297         }
298     })
299 }
300
301 crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
302     match n.val {
303         ty::ConstKind::Unevaluated(def, _, promoted) => {
304             let mut s = if let Some(def) = def.as_local() {
305                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
306                 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
307             } else {
308                 inline::print_inlined_const(cx, def.did)
309             };
310             if let Some(promoted) = promoted {
311                 s.push_str(&format!("::{:?}", promoted))
312             }
313             s
314         }
315         _ => {
316             let mut s = n.to_string();
317             // array lengths are obviously usize
318             if s.ends_with("_usize") {
319                 let n = s.len() - "_usize".len();
320                 s.truncate(n);
321                 if s.ends_with(": ") {
322                     let n = s.len() - ": ".len();
323                     s.truncate(n);
324                 }
325             }
326             s
327         }
328     }
329 }
330
331 crate fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> {
332     cx.tcx.const_eval_poly(def_id).ok().and_then(|val| {
333         let ty = cx.tcx.type_of(def_id);
334         match (val, ty.kind()) {
335             (_, &ty::Ref(..)) => None,
336             (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
337             (ConstValue::Scalar(_), _) => {
338                 let const_ = ty::Const::from_value(cx.tcx, val, ty);
339                 Some(print_const_with_custom_print_scalar(cx, const_))
340             }
341             _ => None,
342         }
343     })
344 }
345
346 fn format_integer_with_underscore_sep(num: &str) -> String {
347     let num_chars: Vec<_> = num.chars().collect();
348     let num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
349
350     num_chars[..num_start_index]
351         .iter()
352         .chain(num_chars[num_start_index..].rchunks(3).rev().intersperse(&['_']).flatten())
353         .collect()
354 }
355
356 fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
357     // Use a slightly different format for integer types which always shows the actual value.
358     // For all other types, fallback to the original `pretty_print_const`.
359     match (ct.val, ct.ty.kind()) {
360         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
361             format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
362         }
363         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
364             let ty = cx.tcx.lift(ct.ty).unwrap();
365             let size = cx.tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
366             let data = int.assert_bits(size);
367             let sign_extended_data = size.sign_extend(data) as i128;
368
369             format!(
370                 "{}{}",
371                 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
372                 i.name_str()
373             )
374         }
375         _ => ct.to_string(),
376     }
377 }
378
379 crate fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool {
380     if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) {
381         if let hir::ExprKind::Lit(_) = &expr.kind {
382             return true;
383         }
384
385         if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind {
386             if let hir::ExprKind::Lit(_) = &expr.kind {
387                 return true;
388             }
389         }
390     }
391
392     false
393 }
394
395 crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
396     let hir = tcx.hir();
397     let value = &hir.body(body).value;
398
399     let snippet = if !value.span.from_expansion() {
400         tcx.sess.source_map().span_to_snippet(value.span).ok()
401     } else {
402         None
403     };
404
405     snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id))
406 }
407
408 /// Given a type Path, resolve it to a Type using the TyCtxt
409 crate fn resolve_type(cx: &mut DocContext<'_>, path: Path, id: hir::HirId) -> Type {
410     debug!("resolve_type({:?},{:?})", path, id);
411
412     let is_generic = match path.res {
413         Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)),
414         Res::SelfTy(..) if path.segments.len() == 1 => {
415             return Generic(kw::SelfUpper);
416         }
417         Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
418             return Generic(Symbol::intern(&format!("{:#}", path.print(&cx.cache))));
419         }
420         Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
421         _ => false,
422     };
423     let did = register_res(cx, path.res);
424     ResolvedPath { path, param_names: None, did, is_generic }
425 }
426
427 crate fn get_auto_trait_and_blanket_impls(
428     cx: &mut DocContext<'tcx>,
429     ty: Ty<'tcx>,
430     param_env_def_id: DefId,
431 ) -> impl Iterator<Item = Item> {
432     let auto_impls = cx
433         .sess()
434         .prof
435         .generic_activity("get_auto_trait_impls")
436         .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id));
437     let blanket_impls = cx
438         .sess()
439         .prof
440         .generic_activity("get_blanket_impls")
441         .run(|| BlanketImplFinder { cx }.get_blanket_impls(ty, param_env_def_id));
442     auto_impls.into_iter().chain(blanket_impls)
443 }
444
445 crate fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
446     debug!("register_res({:?})", res);
447
448     let (did, kind) = match res {
449         Res::Def(DefKind::Fn, i) => (i, TypeKind::Function),
450         Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef),
451         Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum),
452         Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait),
453         Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => {
454             (cx.tcx.parent(i).unwrap(), TypeKind::Trait)
455         }
456         Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct),
457         Res::Def(DefKind::Union, i) => (i, TypeKind::Union),
458         Res::Def(DefKind::Mod, i) => (i, TypeKind::Module),
459         Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign),
460         Res::Def(DefKind::Const, i) => (i, TypeKind::Const),
461         Res::Def(DefKind::Static, i) => (i, TypeKind::Static),
462         Res::Def(DefKind::Variant, i) => {
463             (cx.tcx.parent(i).expect("cannot get parent def id"), TypeKind::Enum)
464         }
465         Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind {
466             MacroKind::Bang => (i, TypeKind::Macro),
467             MacroKind::Attr => (i, TypeKind::Attr),
468             MacroKind::Derive => (i, TypeKind::Derive),
469         },
470         Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias),
471         Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
472         Res::SelfTy(_, Some((impl_def_id, _))) => return impl_def_id,
473         _ => return res.def_id(),
474     };
475     if did.is_local() {
476         return did;
477     }
478     inline::record_extern_fqn(cx, did, kind);
479     if let TypeKind::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 ///
505 /// **Panics if the item it belongs to [is fake][Item::is_fake].**
506 crate fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
507     if def_id.is_top_level_module() {
508         // The crate root has no parent. Use it as the root instead.
509         Some(def_id)
510     } else {
511         let mut current = def_id;
512         // The immediate parent might not always be a module.
513         // Find the first parent which is.
514         while let Some(parent) = tcx.parent(current) {
515             if tcx.def_kind(parent) == DefKind::Mod {
516                 return Some(parent);
517             }
518             current = parent;
519         }
520         None
521     }
522 }
523
524 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
525 ///
526 /// ```
527 /// #[doc(hidden)]
528 /// pub fn foo() {}
529 /// ```
530 ///
531 /// This function exists because it runs on `hir::Attributes` whereas the other is a
532 /// `clean::Attributes` method.
533 crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool {
534     attrs.iter().any(|attr| {
535         attr.has_name(sym::doc)
536             && attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
537     })
538 }