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