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 clean_doc_module, clean_middle_const, clean_middle_region, clean_middle_ty, inline, Crate,
6 ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path,
7 PathSegment, Primitive, PrimitiveType, Term, Type, TypeBinding, TypeBindingKind,
8 };
9 use crate::core::DocContext;
10 use crate::html::format::visibility_to_src_with_space;
11
12 use rustc_ast as ast;
13 use rustc_ast::tokenstream::TokenTree;
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;
18 use rustc_middle::mir::interpret::ConstValue;
19 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
20 use rustc_middle::ty::{self, TyCtxt};
21 use rustc_span::symbol::{kw, sym, Symbol};
22 use std::fmt::Write as _;
23 use std::mem;
24 use std::sync::LazyLock as Lazy;
25 use thin_vec::{thin_vec, ThinVec};
26
27 #[cfg(test)]
28 mod tests;
29
krate(cx: &mut DocContext<'_>) -> Crate30 pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
31 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
32
33 // Clean the crate, translating the entire librustc_ast AST to one that is
34 // understood by rustdoc.
35 let mut module = clean_doc_module(&module, cx);
36
37 match *module.kind {
38 ItemKind::ModuleItem(ref module) => {
39 for it in &module.items {
40 // `compiler_builtins` should be masked too, but we can't apply
41 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
42 if it.is_extern_crate()
43 && (it.attrs.has_doc_flag(sym::masked)
44 || cx.tcx.is_compiler_builtins(it.item_id.krate()))
45 {
46 cx.cache.masked_crates.insert(it.item_id.krate());
47 }
48 }
49 }
50 _ => unreachable!(),
51 }
52
53 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
54 let primitives = local_crate.primitives(cx.tcx);
55 let keywords = local_crate.keywords(cx.tcx);
56 {
57 let ItemKind::ModuleItem(ref mut m) = *module.kind
58 else { unreachable!() };
59 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
60 Item::from_def_id_and_parts(
61 def_id,
62 Some(prim.as_sym()),
63 ItemKind::PrimitiveItem(prim),
64 cx,
65 )
66 }));
67 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
68 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
69 }));
70 }
71
72 Crate { module, external_traits: cx.external_traits.clone() }
73 }
74
substs_to_args<'tcx>( cx: &mut DocContext<'tcx>, substs: ty::Binder<'tcx, &'tcx [ty::subst::GenericArg<'tcx>]>, mut skip_first: bool, container: Option<DefId>, ) -> Vec<GenericArg>75 pub(crate) fn substs_to_args<'tcx>(
76 cx: &mut DocContext<'tcx>,
77 substs: ty::Binder<'tcx, &'tcx [ty::subst::GenericArg<'tcx>]>,
78 mut skip_first: bool,
79 container: Option<DefId>,
80 ) -> Vec<GenericArg> {
81 let mut ret_val =
82 Vec::with_capacity(substs.skip_binder().len().saturating_sub(if skip_first {
83 1
84 } else {
85 0
86 }));
87
88 ret_val.extend(substs.iter().enumerate().filter_map(|(index, kind)| {
89 match kind.skip_binder().unpack() {
90 GenericArgKind::Lifetime(lt) => {
91 Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
92 }
93 GenericArgKind::Type(_) if skip_first => {
94 skip_first = false;
95 None
96 }
97 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
98 kind.rebind(ty),
99 cx,
100 None,
101 container.map(|container| crate::clean::ContainerTy::Regular {
102 ty: container,
103 substs,
104 arg: index,
105 }),
106 ))),
107 GenericArgKind::Const(ct) => {
108 Some(GenericArg::Const(Box::new(clean_middle_const(kind.rebind(ct), cx))))
109 }
110 }
111 }));
112 ret_val
113 }
114
external_generic_args<'tcx>( cx: &mut DocContext<'tcx>, did: DefId, has_self: bool, bindings: ThinVec<TypeBinding>, substs: ty::Binder<'tcx, SubstsRef<'tcx>>, ) -> GenericArgs115 fn external_generic_args<'tcx>(
116 cx: &mut DocContext<'tcx>,
117 did: DefId,
118 has_self: bool,
119 bindings: ThinVec<TypeBinding>,
120 substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
121 ) -> GenericArgs {
122 let args = substs_to_args(cx, substs.map_bound(|substs| &substs[..]), has_self, Some(did));
123
124 if cx.tcx.fn_trait_kind_from_def_id(did).is_some() {
125 let ty = substs
126 .iter()
127 .nth(if has_self { 1 } else { 0 })
128 .unwrap()
129 .map_bound(|arg| arg.expect_ty());
130 let inputs =
131 // The trait's first substitution is the one after self, if there is one.
132 match ty.skip_binder().kind() {
133 ty::Tuple(tys) => tys.iter().map(|t| clean_middle_ty(ty.rebind(t), cx, None, None)).collect::<Vec<_>>().into(),
134 _ => return GenericArgs::AngleBracketed { args: args.into(), bindings },
135 };
136 let output = bindings.into_iter().next().and_then(|binding| match binding.kind {
137 TypeBindingKind::Equality { term: Term::Type(ty) } if ty != Type::Tuple(Vec::new()) => {
138 Some(Box::new(ty))
139 }
140 _ => None,
141 });
142 GenericArgs::Parenthesized { inputs, output }
143 } else {
144 GenericArgs::AngleBracketed { args: args.into(), bindings }
145 }
146 }
147
external_path<'tcx>( cx: &mut DocContext<'tcx>, did: DefId, has_self: bool, bindings: ThinVec<TypeBinding>, substs: ty::Binder<'tcx, SubstsRef<'tcx>>, ) -> Path148 pub(super) fn external_path<'tcx>(
149 cx: &mut DocContext<'tcx>,
150 did: DefId,
151 has_self: bool,
152 bindings: ThinVec<TypeBinding>,
153 substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
154 ) -> Path {
155 let def_kind = cx.tcx.def_kind(did);
156 let name = cx.tcx.item_name(did);
157 Path {
158 res: Res::Def(def_kind, did),
159 segments: thin_vec![PathSegment {
160 name,
161 args: external_generic_args(cx, did, has_self, bindings, substs),
162 }],
163 }
164 }
165
166 /// Remove the generic arguments from a path.
strip_path_generics(mut path: Path) -> Path167 pub(crate) fn strip_path_generics(mut path: Path) -> Path {
168 for ps in path.segments.iter_mut() {
169 ps.args = GenericArgs::AngleBracketed { args: Default::default(), bindings: ThinVec::new() }
170 }
171
172 path
173 }
174
qpath_to_string(p: &hir::QPath<'_>) -> String175 pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
176 let segments = match *p {
177 hir::QPath::Resolved(_, path) => &path.segments,
178 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
179 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
180 };
181
182 let mut s = String::new();
183 for (i, seg) in segments.iter().enumerate() {
184 if i > 0 {
185 s.push_str("::");
186 }
187 if seg.ident.name != kw::PathRoot {
188 s.push_str(seg.ident.as_str());
189 }
190 }
191 s
192 }
193
build_deref_target_impls( cx: &mut DocContext<'_>, items: &[Item], ret: &mut Vec<Item>, )194 pub(crate) fn build_deref_target_impls(
195 cx: &mut DocContext<'_>,
196 items: &[Item],
197 ret: &mut Vec<Item>,
198 ) {
199 let tcx = cx.tcx;
200
201 for item in items {
202 let target = match *item.kind {
203 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
204 _ => continue,
205 };
206
207 if let Some(prim) = target.primitive_type() {
208 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
209 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
210 inline::build_impl(cx, did, None, ret);
211 }
212 } else if let Type::Path { path } = target {
213 let did = path.def_id();
214 if !did.is_local() {
215 inline::build_impls(cx, did, None, ret);
216 }
217 }
218 }
219 }
220
name_from_pat(p: &hir::Pat<'_>) -> Symbol221 pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
222 use rustc_hir::*;
223 debug!("trying to get a name from pattern: {:?}", p);
224
225 Symbol::intern(&match p.kind {
226 PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
227 PatKind::Binding(_, _, ident, _) => return ident.name,
228 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
229 PatKind::Or(pats) => {
230 pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
231 }
232 PatKind::Tuple(elts, _) => format!(
233 "({})",
234 elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
235 ),
236 PatKind::Box(p) => return name_from_pat(&*p),
237 PatKind::Ref(p, _) => return name_from_pat(&*p),
238 PatKind::Lit(..) => {
239 warn!(
240 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
241 );
242 return Symbol::intern("()");
243 }
244 PatKind::Range(..) => return kw::Underscore,
245 PatKind::Slice(begin, ref mid, end) => {
246 let begin = begin.iter().map(|p| name_from_pat(p).to_string());
247 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
248 let end = end.iter().map(|p| name_from_pat(p).to_string());
249 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
250 }
251 })
252 }
253
print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String254 pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
255 match n.kind() {
256 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs: _ }) => {
257 let s = if let Some(def) = def.as_local() {
258 print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(def))
259 } else {
260 inline::print_inlined_const(cx.tcx, def)
261 };
262
263 s
264 }
265 // array lengths are obviously usize
266 ty::ConstKind::Value(ty::ValTree::Leaf(scalar))
267 if *n.ty().kind() == ty::Uint(ty::UintTy::Usize) =>
268 {
269 scalar.to_string()
270 }
271 _ => n.to_string(),
272 }
273 }
274
print_evaluated_const( tcx: TyCtxt<'_>, def_id: DefId, underscores_and_type: bool, ) -> Option<String>275 pub(crate) fn print_evaluated_const(
276 tcx: TyCtxt<'_>,
277 def_id: DefId,
278 underscores_and_type: bool,
279 ) -> Option<String> {
280 tcx.const_eval_poly(def_id).ok().and_then(|val| {
281 let ty = tcx.type_of(def_id).subst_identity();
282 match (val, ty.kind()) {
283 (_, &ty::Ref(..)) => None,
284 (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
285 (ConstValue::Scalar(_), _) => {
286 let const_ = mir::ConstantKind::from_value(val, ty);
287 Some(print_const_with_custom_print_scalar(tcx, const_, underscores_and_type))
288 }
289 _ => None,
290 }
291 })
292 }
293
format_integer_with_underscore_sep(num: &str) -> String294 fn format_integer_with_underscore_sep(num: &str) -> String {
295 let num_chars: Vec<_> = num.chars().collect();
296 let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
297 let chunk_size = match num[num_start_index..].as_bytes() {
298 [b'0', b'b' | b'x', ..] => {
299 num_start_index += 2;
300 4
301 }
302 [b'0', b'o', ..] => {
303 num_start_index += 2;
304 let remaining_chars = num_chars.len() - num_start_index;
305 if remaining_chars <= 6 {
306 // don't add underscores to Unix permissions like 0755 or 100755
307 return num.to_string();
308 }
309 3
310 }
311 _ => 3,
312 };
313
314 num_chars[..num_start_index]
315 .iter()
316 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
317 .collect()
318 }
319
print_const_with_custom_print_scalar<'tcx>( tcx: TyCtxt<'tcx>, ct: mir::ConstantKind<'tcx>, underscores_and_type: bool, ) -> String320 fn print_const_with_custom_print_scalar<'tcx>(
321 tcx: TyCtxt<'tcx>,
322 ct: mir::ConstantKind<'tcx>,
323 underscores_and_type: bool,
324 ) -> String {
325 // Use a slightly different format for integer types which always shows the actual value.
326 // For all other types, fallback to the original `pretty_print_const`.
327 match (ct, ct.ty().kind()) {
328 (mir::ConstantKind::Val(ConstValue::Scalar(int), _), ty::Uint(ui)) => {
329 if underscores_and_type {
330 format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
331 } else {
332 int.to_string()
333 }
334 }
335 (mir::ConstantKind::Val(ConstValue::Scalar(int), _), ty::Int(i)) => {
336 let ty = ct.ty();
337 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
338 let data = int.assert_bits(size);
339 let sign_extended_data = size.sign_extend(data) as i128;
340 if underscores_and_type {
341 format!(
342 "{}{}",
343 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
344 i.name_str()
345 )
346 } else {
347 sign_extended_data.to_string()
348 }
349 }
350 _ => ct.to_string(),
351 }
352 }
353
is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool354 pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
355 if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
356 if let hir::ExprKind::Lit(_) = &expr.kind {
357 return true;
358 }
359
360 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind &&
361 let hir::ExprKind::Lit(_) = &expr.kind
362 {
363 return true;
364 }
365 }
366
367 false
368 }
369
370 /// Build a textual representation of an unevaluated constant expression.
371 ///
372 /// If the const expression is too complex, an underscore `_` is returned.
373 /// For const arguments, it's `{ _ }` to be precise.
374 /// This means that the output is not necessarily valid Rust code.
375 ///
376 /// Currently, only
377 ///
378 /// * literals (optionally with a leading `-`)
379 /// * unit `()`
380 /// * blocks (`{ … }`) around simple expressions and
381 /// * paths without arguments
382 ///
383 /// are considered simple enough. Simple blocks are included since they are
384 /// necessary to disambiguate unit from the unit type.
385 /// This list might get extended in the future.
386 ///
387 /// Without this censoring, in a lot of cases the output would get too large
388 /// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
389 /// Further, private and `doc(hidden)` fields of structs would get leaked
390 /// since HIR datatypes like the `body` parameter do not contain enough
391 /// semantic information for this function to be able to hide them –
392 /// at least not without significant performance overhead.
393 ///
394 /// Whenever possible, prefer to evaluate the constant first and try to
395 /// use a different method for pretty-printing. Ideally this function
396 /// should only ever be used as a fallback.
print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String397 pub(crate) fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
398 let hir = tcx.hir();
399 let value = &hir.body(body).value;
400
401 #[derive(PartialEq, Eq)]
402 enum Classification {
403 Literal,
404 Simple,
405 Complex,
406 }
407
408 use Classification::*;
409
410 fn classify(expr: &hir::Expr<'_>) -> Classification {
411 match &expr.kind {
412 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
413 if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
414 }
415 hir::ExprKind::Lit(_) => Literal,
416 hir::ExprKind::Tup([]) => Simple,
417 hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
418 if classify(expr) == Complex { Complex } else { Simple }
419 }
420 // Paths with a self-type or arguments are too “complex” following our measure since
421 // they may leak private fields of structs (with feature `adt_const_params`).
422 // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
423 // Paths without arguments are definitely harmless though.
424 hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
425 if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
426 }
427 // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
428 // contains const arguments. Is there a *concise* way to check for this?
429 hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
430 // FIXME: Can they contain const arguments and thus leak private struct fields?
431 hir::ExprKind::Path(hir::QPath::LangItem(..)) => Simple,
432 _ => Complex,
433 }
434 }
435
436 let classification = classify(value);
437
438 if classification == Literal
439 && !value.span.from_expansion()
440 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) {
441 // For literals, we avoid invoking the pretty-printer and use the source snippet instead to
442 // preserve certain stylistic choices the user likely made for the sake legibility like
443 //
444 // * hexadecimal notation
445 // * underscores
446 // * character escapes
447 //
448 // FIXME: This passes through `-/*spacer*/0` verbatim.
449 snippet
450 } else if classification == Simple {
451 // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
452 // other formatting artifacts.
453 rustc_hir_pretty::id_to_string(&hir, body.hir_id)
454 } else if tcx.def_kind(hir.body_owner_def_id(body).to_def_id()) == DefKind::AnonConst {
455 // FIXME: Omit the curly braces if the enclosing expression is an array literal
456 // with a repeated element (an `ExprKind::Repeat`) as in such case it
457 // would not actually need any disambiguation.
458 "{ _ }".to_owned()
459 } else {
460 "_".to_owned()
461 }
462 }
463
464 /// Given a type Path, resolve it to a Type using the TyCtxt
resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type465 pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
466 debug!("resolve_type({:?})", path);
467
468 match path.res {
469 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
470 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
471 Generic(kw::SelfUpper)
472 }
473 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
474 _ => {
475 let _ = register_res(cx, path.res);
476 Type::Path { path }
477 }
478 }
479 }
480
get_auto_trait_and_blanket_impls( cx: &mut DocContext<'_>, item_def_id: DefId, ) -> impl Iterator<Item = Item>481 pub(crate) fn get_auto_trait_and_blanket_impls(
482 cx: &mut DocContext<'_>,
483 item_def_id: DefId,
484 ) -> impl Iterator<Item = Item> {
485 // FIXME: To be removed once `parallel_compiler` bugs are fixed!
486 // More information in <https://github.com/rust-lang/rust/pull/106930>.
487 if cfg!(parallel_compiler) {
488 return vec![].into_iter().chain(vec![].into_iter());
489 }
490
491 let auto_impls = cx
492 .sess()
493 .prof
494 .generic_activity("get_auto_trait_impls")
495 .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
496 let blanket_impls = cx
497 .sess()
498 .prof
499 .generic_activity("get_blanket_impls")
500 .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
501 auto_impls.into_iter().chain(blanket_impls)
502 }
503
504 /// If `res` has a documentation page associated, store it in the cache.
505 ///
506 /// This is later used by [`href()`] to determine the HTML link for the item.
507 ///
508 /// [`href()`]: crate::html::format::href
register_res(cx: &mut DocContext<'_>, res: Res) -> DefId509 pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
510 use DefKind::*;
511 debug!("register_res({:?})", res);
512
513 let (kind, did) = match res {
514 Res::Def(
515 kind @ (AssocTy | AssocFn | AssocConst | Variant | Fn | TyAlias | Enum | Trait | Struct
516 | Union | Mod | ForeignTy | Const | Static(_) | Macro(..) | TraitAlias),
517 did,
518 ) => (kind.into(), did),
519
520 _ => panic!("register_res: unexpected {:?}", res),
521 };
522 if did.is_local() {
523 return did;
524 }
525 inline::record_extern_fqn(cx, did, kind);
526 did
527 }
528
resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource529 pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
530 ImportSource {
531 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
532 path,
533 }
534 }
535
enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R where F: FnOnce(&mut DocContext<'tcx>) -> R,536 pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
537 where
538 F: FnOnce(&mut DocContext<'tcx>) -> R,
539 {
540 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
541 let r = f(cx);
542 assert!(cx.impl_trait_bounds.is_empty());
543 cx.impl_trait_bounds = old_bounds;
544 r
545 }
546
547 /// Find the nearest parent module of a [`DefId`].
find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId>548 pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
549 if def_id.is_top_level_module() {
550 // The crate root has no parent. Use it as the root instead.
551 Some(def_id)
552 } else {
553 let mut current = def_id;
554 // The immediate parent might not always be a module.
555 // Find the first parent which is.
556 while let Some(parent) = tcx.opt_parent(current) {
557 if tcx.def_kind(parent) == DefKind::Mod {
558 return Some(parent);
559 }
560 current = parent;
561 }
562 None
563 }
564 }
565
566 /// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
567 ///
568 /// ```
569 /// #[doc(hidden)]
570 /// pub fn foo() {}
571 /// ```
572 ///
573 /// This function exists because it runs on `hir::Attributes` whereas the other is a
574 /// `clean::Attributes` method.
has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool575 pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
576 tcx.get_attrs(did, sym::doc).any(|attr| {
577 attr.meta_item_list().map_or(false, |l| rustc_attr::list_contains_name(&l, flag))
578 })
579 }
580
581 /// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
582 /// so that the channel is consistent.
583 ///
584 /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
585 pub(crate) const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
586 pub(crate) static DOC_CHANNEL: Lazy<&'static str> =
587 Lazy::new(|| DOC_RUST_LANG_ORG_CHANNEL.rsplit("/").filter(|c| !c.is_empty()).next().unwrap());
588
589 /// Render a sequence of macro arms in a format suitable for displaying to the user
590 /// as part of an item declaration.
render_macro_arms<'a>( tcx: TyCtxt<'_>, matchers: impl Iterator<Item = &'a TokenTree>, arm_delim: &str, ) -> String591 pub(super) fn render_macro_arms<'a>(
592 tcx: TyCtxt<'_>,
593 matchers: impl Iterator<Item = &'a TokenTree>,
594 arm_delim: &str,
595 ) -> String {
596 let mut out = String::new();
597 for matcher in matchers {
598 writeln!(out, " {} => {{ ... }}{}", render_macro_matcher(tcx, matcher), arm_delim)
599 .unwrap();
600 }
601 out
602 }
603
display_macro_source( cx: &mut DocContext<'_>, name: Symbol, def: &ast::MacroDef, def_id: DefId, vis: ty::Visibility<DefId>, ) -> String604 pub(super) fn display_macro_source(
605 cx: &mut DocContext<'_>,
606 name: Symbol,
607 def: &ast::MacroDef,
608 def_id: DefId,
609 vis: ty::Visibility<DefId>,
610 ) -> String {
611 // Extract the spans of all matchers. They represent the "interface" of the macro.
612 let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
613
614 if def.macro_rules {
615 format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(cx.tcx, matchers, ";"))
616 } else {
617 if matchers.len() <= 1 {
618 format!(
619 "{}macro {}{} {{\n ...\n}}",
620 visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
621 name,
622 matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(),
623 )
624 } else {
625 format!(
626 "{}macro {} {{\n{}}}",
627 visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
628 name,
629 render_macro_arms(cx.tcx, matchers, ","),
630 )
631 }
632 }
633 }
634