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