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