]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/clean/utils.rs
New upstream version 1.78.0+dfsg1
[rustc.git] / src / librustdoc / clean / utils.rs
CommitLineData
dfeec247
XL
1use crate::clean::auto_trait::AutoTraitFinder;
2use crate::clean::blanket_impl::BlanketImplFinder;
5099ac24 3use crate::clean::render_macro_matchers::render_macro_matcher;
60c5eb7d 4use crate::clean::{
f2b60f7d
FG
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,
487cf647 7 PathSegment, Primitive, PrimitiveType, Term, Type, TypeBinding, TypeBindingKind,
60c5eb7d 8};
dfeec247 9use crate::core::DocContext;
487cf647 10use crate::html::format::visibility_to_src_with_space;
60c5eb7d 11
136023e0
XL
12use rustc_ast as ast;
13use rustc_ast::tokenstream::TokenTree;
dfeec247
XL
14use rustc_hir as hir;
15use rustc_hir::def::{DefKind, Res};
add651ee 16use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
781aab86 17use rustc_metadata::rendered_const;
923072b8 18use rustc_middle::mir;
c0240ec0 19use rustc_middle::ty::TypeVisitableExt;
add651ee 20use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt};
dfeec247 21use rustc_span::symbol::{kw, sym, Symbol};
c0240ec0 22use std::assert_matches::debug_assert_matches;
136023e0 23use std::fmt::Write as _;
60c5eb7d 24use std::mem;
fe692bf9 25use std::sync::LazyLock as Lazy;
487cf647 26use thin_vec::{thin_vec, ThinVec};
60c5eb7d 27
17df50a5
XL
28#[cfg(test)]
29mod tests;
30
923072b8 31pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
c295e0f8 32 let module = crate::visit_ast::RustdocVisitor::new(cx).visit();
60c5eb7d 33
74b04a01 34 // Clean the crate, translating the entire librustc_ast AST to one that is
60c5eb7d 35 // understood by rustdoc.
f2b60f7d 36 let mut module = clean_doc_module(&module, cx);
60c5eb7d 37
5869c6ff 38 match *module.kind {
fc512014 39 ItemKind::ModuleItem(ref module) => {
60c5eb7d
XL
40 for it in &module.items {
41 // `compiler_builtins` should be masked too, but we can't apply
42 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
add651ee 43 if cx.tcx.is_compiler_builtins(it.item_id.krate()) {
04454e1e 44 cx.cache.masked_crates.insert(it.item_id.krate());
add651ee
FG
45 } else if it.is_extern_crate()
46 && it.attrs.has_doc_flag(sym::masked)
47 && let Some(def_id) = it.item_id.as_def_id()
48 && let Some(local_def_id) = def_id.as_local()
49 && let Some(cnum) = cx.tcx.extern_mod_stmt_cnum(local_def_id)
50 {
51 cx.cache.masked_crates.insert(cnum);
60c5eb7d
XL
52 }
53 }
54 }
55 _ => unreachable!(),
56 }
57
136023e0 58 let local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
cdc7bbd5
XL
59 let primitives = local_crate.primitives(cx.tcx);
60 let keywords = local_crate.keywords(cx.tcx);
60c5eb7d 61 {
fe692bf9 62 let ItemKind::ModuleItem(ref mut m) = *module.kind else { unreachable!() };
fc512014
XL
63 m.items.extend(primitives.iter().map(|&(def_id, prim)| {
64 Item::from_def_id_and_parts(
65 def_id,
66 Some(prim.as_sym()),
67 ItemKind::PrimitiveItem(prim),
68 cx,
69 )
60c5eb7d 70 }));
fc512014 71 m.items.extend(keywords.into_iter().map(|(def_id, kw)| {
064997fb 72 Item::from_def_id_and_parts(def_id, Some(kw), ItemKind::KeywordItem, cx)
60c5eb7d
XL
73 }));
74 }
75
487cf647 76 Crate { module, external_traits: cx.external_traits.clone() }
60c5eb7d
XL
77}
78
c0240ec0 79pub(crate) fn clean_middle_generic_args<'tcx>(
923072b8 80 cx: &mut DocContext<'tcx>,
c0240ec0
FG
81 args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
82 mut has_self: bool,
ed00b5ec 83 owner: DefId,
5e7ed085 84) -> Vec<GenericArg> {
c0240ec0
FG
85 let (args, bound_vars) = (args.skip_binder(), args.bound_vars());
86 if args.is_empty() {
ed00b5ec
FG
87 // Fast path which avoids executing the query `generics_of`.
88 return Vec::new();
89 }
90
c0240ec0
FG
91 // If the container is a trait object type, the arguments won't contain the self type but the
92 // generics of the corresponding trait will. In such a case, prepend a dummy self type in order
93 // to align the arguments and parameters for the iteration below and to enable us to correctly
94 // instantiate the generic parameter default later.
95 let generics = cx.tcx.generics_of(owner);
96 let args = if !has_self && generics.parent.is_none() && generics.has_self {
97 has_self = true;
98 [cx.tcx.types.trait_object_dummy_self.into()]
99 .into_iter()
100 .chain(args.iter().copied())
101 .collect::<Vec<_>>()
102 .into()
103 } else {
104 std::borrow::Cow::from(args)
105 };
ed00b5ec 106
c0240ec0
FG
107 let mut elision_has_failed_once_before = false;
108 let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| {
109 // Elide the self type.
110 if has_self && index == 0 {
111 return None;
112 }
ed00b5ec 113
c0240ec0
FG
114 // Elide internal host effect args.
115 let param = generics.param_at(index, cx.tcx);
116 if param.is_host_effect() {
117 return None;
ed00b5ec 118 }
ed00b5ec 119
c0240ec0 120 let arg = ty::Binder::bind_with_vars(arg, bound_vars);
ed00b5ec 121
c0240ec0
FG
122 // Elide arguments that coincide with their default.
123 if !elision_has_failed_once_before && let Some(default) = param.default_value(cx.tcx) {
124 let default = default.instantiate(cx.tcx, args.as_ref());
125 if can_elide_generic_arg(arg, arg.rebind(default)) {
126 return None;
fe692bf9 127 }
c0240ec0
FG
128 elision_has_failed_once_before = true;
129 }
ed00b5ec 130
c0240ec0
FG
131 match arg.skip_binder().unpack() {
132 GenericArgKind::Lifetime(lt) => {
133 Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
134 }
135 GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
136 arg.rebind(ty),
fe692bf9
FG
137 cx,
138 None,
ed00b5ec
FG
139 Some(crate::clean::ContainerTy::Regular {
140 ty: owner,
c0240ec0 141 args: arg.rebind(args.as_ref()),
fe692bf9
FG
142 arg: index,
143 }),
c0240ec0
FG
144 ))),
145 GenericArgKind::Const(ct) => {
146 Some(GenericArg::Const(Box::new(clean_middle_const(arg.rebind(ct), cx))))
ed00b5ec 147 }
9c376795 148 }
ed00b5ec
FG
149 };
150
c0240ec0
FG
151 let offset = if has_self { 1 } else { 0 };
152 let mut clean_args = Vec::with_capacity(args.len().saturating_sub(offset));
153 clean_args.extend(args.iter().enumerate().rev().filter_map(clean_arg));
154 clean_args.reverse();
155 clean_args
ed00b5ec
FG
156}
157
158/// Check if the generic argument `actual` coincides with the `default` and can therefore be elided.
159///
160/// This uses a very conservative approach for performance and correctness reasons, meaning for
161/// several classes of terms it claims that they cannot be elided even if they theoretically could.
162/// This is absolutely fine since it mostly concerns edge cases.
c0240ec0
FG
163fn can_elide_generic_arg<'tcx>(
164 actual: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
165 default: ty::Binder<'tcx, ty::GenericArg<'tcx>>,
166) -> bool {
167 debug_assert_matches!(
168 (actual.skip_binder().unpack(), default.skip_binder().unpack()),
169 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_))
170 | (ty::GenericArgKind::Type(_), ty::GenericArgKind::Type(_))
171 | (ty::GenericArgKind::Const(_), ty::GenericArgKind::Const(_))
172 );
173
ed00b5ec
FG
174 // In practice, we shouldn't have any inference variables at this point.
175 // However to be safe, we bail out if we do happen to stumble upon them.
176 if actual.has_infer() || default.has_infer() {
177 return false;
178 }
179
180 // Since we don't properly keep track of bound variables in rustdoc (yet), we don't attempt to
181 // make any sense out of escaping bound variables. We simply don't have enough context and it
182 // would be incorrect to try to do so anyway.
183 if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
184 return false;
185 }
186
187 // Theoretically we could now check if either term contains (non-escaping) late-bound regions or
188 // projections, relate the two using an `InferCtxt` and check if the resulting obligations hold.
189 // Having projections means that the terms can potentially be further normalized thereby possibly
190 // revealing that they are equal after all. Regarding late-bound regions, they could to be
191 // liberated allowing us to consider more types to be equal by ignoring the names of binders
192 // (e.g., `for<'a> TYPE<'a>` and `for<'b> TYPE<'b>`).
193 //
194 // However, we are mostly interested in “reeliding” generic args, i.e., eliding generic args that
195 // were originally elided by the user and later filled in by the compiler contrary to eliding
196 // arbitrary generic arguments if they happen to semantically coincide with the default (of course,
197 // we cannot possibly distinguish these two cases). Therefore and for performance reasons, it
198 // suffices to only perform a syntactic / structural check by comparing the memory addresses of
199 // the interned arguments.
200 actual.skip_binder() == default.skip_binder()
5e7ed085
FG
201}
202
c0240ec0 203fn clean_middle_generic_args_with_bindings<'tcx>(
923072b8 204 cx: &mut DocContext<'tcx>,
5e7ed085
FG
205 did: DefId,
206 has_self: bool,
f2b60f7d 207 bindings: ThinVec<TypeBinding>,
add651ee 208 ty_args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
5e7ed085 209) -> GenericArgs {
c0240ec0 210 let args = clean_middle_generic_args(cx, ty_args.map_bound(|args| &args[..]), has_self, did);
60c5eb7d 211
487cf647 212 if cx.tcx.fn_trait_kind_from_def_id(did).is_some() {
add651ee 213 let ty = ty_args
9c376795
FG
214 .iter()
215 .nth(if has_self { 1 } else { 0 })
216 .unwrap()
217 .map_bound(|arg| arg.expect_ty());
5e7ed085
FG
218 let inputs =
219 // The trait's first substitution is the one after self, if there is one.
9c376795 220 match ty.skip_binder().kind() {
fe692bf9 221 ty::Tuple(tys) => tys.iter().map(|t| clean_middle_ty(ty.rebind(t), cx, None, None)).collect::<Vec<_>>().into(),
f2b60f7d 222 _ => return GenericArgs::AngleBracketed { args: args.into(), bindings },
5e7ed085 223 };
487cf647
FG
224 let output = bindings.into_iter().next().and_then(|binding| match binding.kind {
225 TypeBindingKind::Equality { term: Term::Type(ty) } if ty != Type::Tuple(Vec::new()) => {
226 Some(Box::new(ty))
227 }
228 _ => None,
229 });
c295e0f8
XL
230 GenericArgs::Parenthesized { inputs, output }
231 } else {
9ffffee4 232 GenericArgs::AngleBracketed { args: args.into(), bindings }
60c5eb7d
XL
233 }
234}
235
c0240ec0 236pub(super) fn clean_middle_path<'tcx>(
923072b8 237 cx: &mut DocContext<'tcx>,
c295e0f8 238 did: DefId,
dfeec247 239 has_self: bool,
f2b60f7d 240 bindings: ThinVec<TypeBinding>,
add651ee 241 args: ty::Binder<'tcx, GenericArgsRef<'tcx>>,
dfeec247 242) -> Path {
c295e0f8 243 let def_kind = cx.tcx.def_kind(did);
781aab86 244 let name = cx.tcx.opt_item_name(did).unwrap_or(kw::Empty);
60c5eb7d 245 Path {
c295e0f8 246 res: Res::Def(def_kind, did),
487cf647 247 segments: thin_vec![PathSegment {
fc512014 248 name,
c0240ec0 249 args: clean_middle_generic_args_with_bindings(cx, did, has_self, bindings, args),
60c5eb7d
XL
250 }],
251 }
252}
253
c295e0f8 254/// Remove the generic arguments from a path.
923072b8 255pub(crate) fn strip_path_generics(mut path: Path) -> Path {
a2a8927a 256 for ps in path.segments.iter_mut() {
923072b8 257 ps.args = GenericArgs::AngleBracketed { args: Default::default(), bindings: ThinVec::new() }
a2a8927a 258 }
60c5eb7d 259
a2a8927a 260 path
60c5eb7d
XL
261}
262
923072b8 263pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
60c5eb7d 264 let segments = match *p {
3c0e092e
XL
265 hir::QPath::Resolved(_, path) => &path.segments,
266 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
3dfed10e 267 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
60c5eb7d
XL
268 };
269
270 let mut s = String::new();
271 for (i, seg) in segments.iter().enumerate() {
272 if i > 0 {
273 s.push_str("::");
274 }
275 if seg.ident.name != kw::PathRoot {
a2a8927a 276 s.push_str(seg.ident.as_str());
60c5eb7d
XL
277 }
278 }
279 s
280}
281
923072b8
FG
282pub(crate) fn build_deref_target_impls(
283 cx: &mut DocContext<'_>,
284 items: &[Item],
285 ret: &mut Vec<Item>,
286) {
60c5eb7d
XL
287 let tcx = cx.tcx;
288
289 for item in items {
5869c6ff 290 let target = match *item.kind {
04454e1e 291 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
60c5eb7d
XL
292 _ => continue,
293 };
5869c6ff
XL
294
295 if let Some(prim) = target.primitive_type() {
49aad941 296 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
5e7ed085 297 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
c620b35d
FG
298 cx.with_param_env(did, |cx| {
299 inline::build_impl(cx, did, None, ret);
300 });
60c5eb7d 301 }
3c0e092e
XL
302 } else if let Type::Path { path } = target {
303 let did = path.def_id();
60c5eb7d 304 if !did.is_local() {
c620b35d
FG
305 cx.with_param_env(did, |cx| {
306 inline::build_impls(cx, did, None, ret);
307 });
60c5eb7d
XL
308 }
309 }
310 }
311}
312
923072b8 313pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
dfeec247 314 use rustc_hir::*;
add651ee 315 debug!("trying to get a name from pattern: {p:?}");
60c5eb7d 316
fc512014 317 Symbol::intern(&match p.kind {
4b012472 318 // FIXME(never_patterns): does this make sense?
c0240ec0
FG
319 PatKind::Wild | PatKind::Err(_) | PatKind::Never | PatKind::Struct(..) => {
320 return kw::Underscore;
321 }
fc512014 322 PatKind::Binding(_, _, ident, _) => return ident.name,
60c5eb7d 323 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
3c0e092e 324 PatKind::Or(pats) => {
136023e0
XL
325 pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
326 }
3c0e092e 327 PatKind::Tuple(elts, _) => format!(
dfeec247 328 "({})",
136023e0 329 elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
dfeec247 330 ),
3c0e092e
XL
331 PatKind::Box(p) => return name_from_pat(&*p),
332 PatKind::Ref(p, _) => return name_from_pat(&*p),
60c5eb7d 333 PatKind::Lit(..) => {
dfeec247 334 warn!(
1b1a35ee 335 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
dfeec247 336 );
fc512014 337 return Symbol::intern("()");
dfeec247 338 }
5869c6ff 339 PatKind::Range(..) => return kw::Underscore,
3c0e092e 340 PatKind::Slice(begin, ref mid, end) => {
136023e0 341 let begin = begin.iter().map(|p| name_from_pat(p).to_string());
60c5eb7d 342 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
136023e0 343 let end = end.iter().map(|p| name_from_pat(p).to_string());
60c5eb7d 344 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
dfeec247 345 }
fc512014 346 })
60c5eb7d
XL
347}
348
923072b8
FG
349pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
350 match n.kind() {
add651ee 351 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
f2b60f7d 352 let s = if let Some(def) = def.as_local() {
781aab86 353 rendered_const(cx.tcx, cx.tcx.hir().body_owned_by(def))
60c5eb7d 354 } else {
49aad941 355 inline::print_inlined_const(cx.tcx, def)
dfeec247 356 };
f2b60f7d 357
dfeec247
XL
358 s
359 }
487cf647
FG
360 // array lengths are obviously usize
361 ty::ConstKind::Value(ty::ValTree::Leaf(scalar))
362 if *n.ty().kind() == ty::Uint(ty::UintTy::Usize) =>
363 {
364 scalar.to_string()
dfeec247 365 }
487cf647 366 _ => n.to_string(),
dfeec247
XL
367 }
368}
369
f2b60f7d
FG
370pub(crate) fn print_evaluated_const(
371 tcx: TyCtxt<'_>,
372 def_id: DefId,
ed00b5ec
FG
373 with_underscores: bool,
374 with_type: bool,
f2b60f7d 375) -> Option<String> {
cdc7bbd5 376 tcx.const_eval_poly(def_id).ok().and_then(|val| {
add651ee 377 let ty = tcx.type_of(def_id).instantiate_identity();
1b1a35ee 378 match (val, ty.kind()) {
74b04a01 379 (_, &ty::Ref(..)) => None,
781aab86
FG
380 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
381 (mir::ConstValue::Scalar(_), _) => {
382 let const_ = mir::Const::from_value(val, ty);
ed00b5ec 383 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
dfeec247
XL
384 }
385 _ => None,
74b04a01 386 }
ba9703b0 387 })
dfeec247
XL
388}
389
390fn format_integer_with_underscore_sep(num: &str) -> String {
391 let num_chars: Vec<_> = num.chars().collect();
17df50a5
XL
392 let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
393 let chunk_size = match num[num_start_index..].as_bytes() {
394 [b'0', b'b' | b'x', ..] => {
395 num_start_index += 2;
396 4
397 }
398 [b'0', b'o', ..] => {
399 num_start_index += 2;
400 let remaining_chars = num_chars.len() - num_start_index;
401 if remaining_chars <= 6 {
402 // don't add underscores to Unix permissions like 0755 or 100755
403 return num.to_string();
404 }
405 3
406 }
407 _ => 3,
408 };
dfeec247
XL
409
410 num_chars[..num_start_index]
411 .iter()
17df50a5 412 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
dfeec247
XL
413 .collect()
414}
415
2b03887a
FG
416fn print_const_with_custom_print_scalar<'tcx>(
417 tcx: TyCtxt<'tcx>,
781aab86 418 ct: mir::Const<'tcx>,
ed00b5ec
FG
419 with_underscores: bool,
420 with_type: bool,
f2b60f7d 421) -> String {
dfeec247
XL
422 // Use a slightly different format for integer types which always shows the actual value.
423 // For all other types, fallback to the original `pretty_print_const`.
923072b8 424 match (ct, ct.ty().kind()) {
781aab86 425 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
ed00b5ec
FG
426 let mut output = if with_underscores {
427 format_integer_with_underscore_sep(&int.to_string())
f2b60f7d
FG
428 } else {
429 int.to_string()
ed00b5ec
FG
430 };
431 if with_type {
432 output += ui.name_str();
f2b60f7d 433 }
ed00b5ec 434 output
dfeec247 435 }
781aab86 436 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
2b03887a 437 let ty = ct.ty();
cdc7bbd5 438 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
29967ef6
XL
439 let data = int.assert_bits(size);
440 let sign_extended_data = size.sign_extend(data) as i128;
ed00b5ec
FG
441 let mut output = if with_underscores {
442 format_integer_with_underscore_sep(&sign_extended_data.to_string())
f2b60f7d
FG
443 } else {
444 sign_extended_data.to_string()
ed00b5ec
FG
445 };
446 if with_type {
447 output += i.name_str();
f2b60f7d 448 }
ed00b5ec 449 output
dfeec247
XL
450 }
451 _ => ct.to_string(),
452 }
453}
454
923072b8 455pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
4b012472 456 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
dfeec247
XL
457 if let hir::ExprKind::Lit(_) = &expr.kind {
458 return true;
459 }
460
4b012472
FG
461 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
462 && let hir::ExprKind::Lit(_) = &expr.kind
9ffffee4
FG
463 {
464 return true;
dfeec247 465 }
60c5eb7d 466 }
dfeec247
XL
467
468 false
60c5eb7d
XL
469}
470
60c5eb7d 471/// Given a type Path, resolve it to a Type using the TyCtxt
923072b8 472pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
add651ee 473 debug!("resolve_type({path:?})");
60c5eb7d 474
c295e0f8
XL
475 match path.res {
476 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
2b03887a
FG
477 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
478 Generic(kw::SelfUpper)
479 }
c295e0f8
XL
480 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
481 _ => {
3c0e092e
XL
482 let _ = register_res(cx, path.res);
483 Type::Path { path }
60c5eb7d 484 }
c295e0f8 485 }
60c5eb7d
XL
486}
487
923072b8 488pub(crate) fn get_auto_trait_and_blanket_impls(
a2a8927a 489 cx: &mut DocContext<'_>,
6a06907d 490 item_def_id: DefId,
60c5eb7d 491) -> impl Iterator<Item = Item> {
5869c6ff
XL
492 let auto_impls = cx
493 .sess()
494 .prof
495 .generic_activity("get_auto_trait_impls")
6a06907d 496 .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(item_def_id));
5869c6ff
XL
497 let blanket_impls = cx
498 .sess()
499 .prof
500 .generic_activity("get_blanket_impls")
6a06907d 501 .run(|| BlanketImplFinder { cx }.get_blanket_impls(item_def_id));
fc512014 502 auto_impls.into_iter().chain(blanket_impls)
60c5eb7d
XL
503}
504
17df50a5
XL
505/// If `res` has a documentation page associated, store it in the cache.
506///
507/// This is later used by [`href()`] to determine the HTML link for the item.
508///
509/// [`href()`]: crate::html::format::href
923072b8 510pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
17df50a5 511 use DefKind::*;
add651ee 512 debug!("register_res({res:?})");
60c5eb7d 513
f2b60f7d 514 let (kind, did) = match res {
17df50a5 515 Res::Def(
add651ee
FG
516 kind @ (AssocTy
517 | AssocFn
518 | AssocConst
519 | Variant
520 | Fn
521 | TyAlias { .. }
522 | Enum
523 | Trait
524 | Struct
525 | Union
526 | Mod
527 | ForeignTy
528 | Const
c620b35d 529 | Static { .. }
add651ee
FG
530 | Macro(..)
531 | TraitAlias),
f2b60f7d
FG
532 did,
533 ) => (kind.into(), did),
534
add651ee 535 _ => panic!("register_res: unexpected {res:?}"),
60c5eb7d 536 };
dfeec247
XL
537 if did.is_local() {
538 return did;
539 }
60c5eb7d 540 inline::record_extern_fqn(cx, did, kind);
60c5eb7d
XL
541 did
542}
543
923072b8 544pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
60c5eb7d 545 ImportSource {
dfeec247 546 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
60c5eb7d
XL
547 path,
548 }
549}
550
923072b8 551pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
60c5eb7d 552where
923072b8 553 F: FnOnce(&mut DocContext<'tcx>) -> R,
60c5eb7d 554{
6a06907d
XL
555 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
556 let r = f(cx);
557 assert!(cx.impl_trait_bounds.is_empty());
558 cx.impl_trait_bounds = old_bounds;
60c5eb7d
XL
559 r
560}
fc512014
XL
561
562/// Find the nearest parent module of a [`DefId`].
923072b8 563pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
fc512014
XL
564 if def_id.is_top_level_module() {
565 // The crate root has no parent. Use it as the root instead.
566 Some(def_id)
567 } else {
568 let mut current = def_id;
569 // The immediate parent might not always be a module.
570 // Find the first parent which is.
04454e1e 571 while let Some(parent) = tcx.opt_parent(current) {
fc512014
XL
572 if tcx.def_kind(parent) == DefKind::Mod {
573 return Some(parent);
574 }
575 current = parent;
576 }
577 None
578 }
579}
6a06907d
XL
580
581/// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
582///
583/// ```
584/// #[doc(hidden)]
585/// pub fn foo() {}
586/// ```
587///
588/// This function exists because it runs on `hir::Attributes` whereas the other is a
589/// `clean::Attributes` method.
923072b8 590pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
4b012472
FG
591 tcx.get_attrs(did, sym::doc)
592 .any(|attr| attr.meta_item_list().is_some_and(|l| rustc_attr::list_contains_name(&l, flag)))
6a06907d 593}
17df50a5
XL
594
595/// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
596/// so that the channel is consistent.
597///
598/// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
923072b8 599pub(crate) const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
fe692bf9 600pub(crate) static DOC_CHANNEL: Lazy<&'static str> =
ed00b5ec 601 Lazy::new(|| DOC_RUST_LANG_ORG_CHANNEL.rsplit('/').filter(|c| !c.is_empty()).next().unwrap());
136023e0
XL
602
603/// Render a sequence of macro arms in a format suitable for displaying to the user
604/// as part of an item declaration.
605pub(super) fn render_macro_arms<'a>(
5099ac24 606 tcx: TyCtxt<'_>,
136023e0
XL
607 matchers: impl Iterator<Item = &'a TokenTree>,
608 arm_delim: &str,
609) -> String {
610 let mut out = String::new();
611 for matcher in matchers {
add651ee
FG
612 writeln!(
613 out,
614 " {matcher} => {{ ... }}{arm_delim}",
615 matcher = render_macro_matcher(tcx, matcher),
616 )
617 .unwrap();
136023e0
XL
618 }
619 out
620}
621
136023e0
XL
622pub(super) fn display_macro_source(
623 cx: &mut DocContext<'_>,
624 name: Symbol,
625 def: &ast::MacroDef,
626 def_id: DefId,
487cf647 627 vis: ty::Visibility<DefId>,
c620b35d 628 is_doc_hidden: bool,
136023e0 629) -> String {
136023e0 630 // Extract the spans of all matchers. They represent the "interface" of the macro.
49aad941 631 let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
136023e0
XL
632
633 if def.macro_rules {
add651ee 634 format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
136023e0 635 } else {
136023e0
XL
636 if matchers.len() <= 1 {
637 format!(
add651ee 638 "{vis}macro {name}{matchers} {{\n ...\n}}",
c620b35d 639 vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id, is_doc_hidden),
add651ee
FG
640 matchers = matchers
641 .map(|matcher| render_macro_matcher(cx.tcx, matcher))
642 .collect::<String>(),
136023e0
XL
643 )
644 } else {
645 format!(
add651ee 646 "{vis}macro {name} {{\n{arms}}}",
c620b35d 647 vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id, is_doc_hidden),
add651ee 648 arms = render_macro_arms(cx.tcx, matchers, ","),
136023e0
XL
649 )
650 }
651 }
652}
add651ee
FG
653
654pub(crate) fn inherits_doc_hidden(
655 tcx: TyCtxt<'_>,
656 mut def_id: LocalDefId,
657 stop_at: Option<LocalDefId>,
658) -> bool {
add651ee 659 while let Some(id) = tcx.opt_local_parent(def_id) {
4b012472
FG
660 if let Some(stop_at) = stop_at
661 && id == stop_at
662 {
add651ee
FG
663 return false;
664 }
665 def_id = id;
666 if tcx.is_doc_hidden(def_id.to_def_id()) {
667 return true;
c620b35d
FG
668 } else if matches!(
669 tcx.hir_node_by_def_id(def_id),
670 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
671 ) {
add651ee
FG
672 // `impl` blocks stand a bit on their own: unless they have `#[doc(hidden)]` directly
673 // on them, they don't inherit it from the parent context.
674 return false;
675 }
676 }
677 false
678}
679
680#[inline]
681pub(crate) fn should_ignore_res(res: Res) -> bool {
682 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
683}