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