]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/clean/utils.rs
bump version to 1.79.0+dfsg1-1~bpo12+pve2
[rustc.git] / src / librustdoc / clean / utils.rs
CommitLineData
e8be2606
FG
1use crate::clean::auto_trait::synthesize_auto_trait_impls;
2use crate::clean::blanket_impl::synthesize_blanket_impls;
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
923072b8 254pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
60c5eb7d 255 let segments = match *p {
3c0e092e
XL
256 hir::QPath::Resolved(_, path) => &path.segments,
257 hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(),
3dfed10e 258 hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
60c5eb7d
XL
259 };
260
261 let mut s = String::new();
262 for (i, seg) in segments.iter().enumerate() {
263 if i > 0 {
264 s.push_str("::");
265 }
266 if seg.ident.name != kw::PathRoot {
a2a8927a 267 s.push_str(seg.ident.as_str());
60c5eb7d
XL
268 }
269 }
270 s
271}
272
923072b8
FG
273pub(crate) fn build_deref_target_impls(
274 cx: &mut DocContext<'_>,
275 items: &[Item],
276 ret: &mut Vec<Item>,
277) {
60c5eb7d
XL
278 let tcx = cx.tcx;
279
280 for item in items {
5869c6ff 281 let target = match *item.kind {
04454e1e 282 ItemKind::AssocTypeItem(ref t, _) => &t.type_,
60c5eb7d
XL
283 _ => continue,
284 };
5869c6ff
XL
285
286 if let Some(prim) = target.primitive_type() {
49aad941 287 let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
5e7ed085 288 for did in prim.impls(tcx).filter(|did| !did.is_local()) {
c620b35d
FG
289 cx.with_param_env(did, |cx| {
290 inline::build_impl(cx, did, None, ret);
291 });
60c5eb7d 292 }
3c0e092e
XL
293 } else if let Type::Path { path } = target {
294 let did = path.def_id();
60c5eb7d 295 if !did.is_local() {
c620b35d
FG
296 cx.with_param_env(did, |cx| {
297 inline::build_impls(cx, did, None, ret);
298 });
60c5eb7d
XL
299 }
300 }
301 }
302}
303
923072b8 304pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
dfeec247 305 use rustc_hir::*;
add651ee 306 debug!("trying to get a name from pattern: {p:?}");
60c5eb7d 307
fc512014 308 Symbol::intern(&match p.kind {
4b012472 309 // FIXME(never_patterns): does this make sense?
c0240ec0
FG
310 PatKind::Wild | PatKind::Err(_) | PatKind::Never | PatKind::Struct(..) => {
311 return kw::Underscore;
312 }
fc512014 313 PatKind::Binding(_, _, ident, _) => return ident.name,
60c5eb7d 314 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
3c0e092e 315 PatKind::Or(pats) => {
136023e0
XL
316 pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
317 }
3c0e092e 318 PatKind::Tuple(elts, _) => format!(
dfeec247 319 "({})",
136023e0 320 elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
dfeec247 321 ),
3c0e092e 322 PatKind::Box(p) => return name_from_pat(&*p),
e8be2606 323 PatKind::Deref(p) => format!("deref!({})", name_from_pat(&*p)),
3c0e092e 324 PatKind::Ref(p, _) => return name_from_pat(&*p),
60c5eb7d 325 PatKind::Lit(..) => {
dfeec247 326 warn!(
1b1a35ee 327 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
dfeec247 328 );
fc512014 329 return Symbol::intern("()");
dfeec247 330 }
5869c6ff 331 PatKind::Range(..) => return kw::Underscore,
3c0e092e 332 PatKind::Slice(begin, ref mid, end) => {
136023e0 333 let begin = begin.iter().map(|p| name_from_pat(p).to_string());
60c5eb7d 334 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
136023e0 335 let end = end.iter().map(|p| name_from_pat(p).to_string());
60c5eb7d 336 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
dfeec247 337 }
fc512014 338 })
60c5eb7d
XL
339}
340
923072b8
FG
341pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String {
342 match n.kind() {
add651ee 343 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => {
f2b60f7d 344 let s = if let Some(def) = def.as_local() {
781aab86 345 rendered_const(cx.tcx, cx.tcx.hir().body_owned_by(def))
60c5eb7d 346 } else {
49aad941 347 inline::print_inlined_const(cx.tcx, def)
dfeec247 348 };
f2b60f7d 349
dfeec247
XL
350 s
351 }
487cf647
FG
352 // array lengths are obviously usize
353 ty::ConstKind::Value(ty::ValTree::Leaf(scalar))
354 if *n.ty().kind() == ty::Uint(ty::UintTy::Usize) =>
355 {
356 scalar.to_string()
dfeec247 357 }
487cf647 358 _ => n.to_string(),
dfeec247
XL
359 }
360}
361
f2b60f7d
FG
362pub(crate) fn print_evaluated_const(
363 tcx: TyCtxt<'_>,
364 def_id: DefId,
ed00b5ec
FG
365 with_underscores: bool,
366 with_type: bool,
f2b60f7d 367) -> Option<String> {
cdc7bbd5 368 tcx.const_eval_poly(def_id).ok().and_then(|val| {
add651ee 369 let ty = tcx.type_of(def_id).instantiate_identity();
1b1a35ee 370 match (val, ty.kind()) {
74b04a01 371 (_, &ty::Ref(..)) => None,
781aab86
FG
372 (mir::ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
373 (mir::ConstValue::Scalar(_), _) => {
374 let const_ = mir::Const::from_value(val, ty);
ed00b5ec 375 Some(print_const_with_custom_print_scalar(tcx, const_, with_underscores, with_type))
dfeec247
XL
376 }
377 _ => None,
74b04a01 378 }
ba9703b0 379 })
dfeec247
XL
380}
381
382fn format_integer_with_underscore_sep(num: &str) -> String {
383 let num_chars: Vec<_> = num.chars().collect();
17df50a5
XL
384 let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
385 let chunk_size = match num[num_start_index..].as_bytes() {
386 [b'0', b'b' | b'x', ..] => {
387 num_start_index += 2;
388 4
389 }
390 [b'0', b'o', ..] => {
391 num_start_index += 2;
392 let remaining_chars = num_chars.len() - num_start_index;
393 if remaining_chars <= 6 {
394 // don't add underscores to Unix permissions like 0755 or 100755
395 return num.to_string();
396 }
397 3
398 }
399 _ => 3,
400 };
dfeec247
XL
401
402 num_chars[..num_start_index]
403 .iter()
17df50a5 404 .chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
dfeec247
XL
405 .collect()
406}
407
2b03887a
FG
408fn print_const_with_custom_print_scalar<'tcx>(
409 tcx: TyCtxt<'tcx>,
781aab86 410 ct: mir::Const<'tcx>,
ed00b5ec
FG
411 with_underscores: bool,
412 with_type: bool,
f2b60f7d 413) -> String {
dfeec247
XL
414 // Use a slightly different format for integer types which always shows the actual value.
415 // For all other types, fallback to the original `pretty_print_const`.
923072b8 416 match (ct, ct.ty().kind()) {
781aab86 417 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
ed00b5ec
FG
418 let mut output = if with_underscores {
419 format_integer_with_underscore_sep(&int.to_string())
f2b60f7d
FG
420 } else {
421 int.to_string()
ed00b5ec
FG
422 };
423 if with_type {
424 output += ui.name_str();
f2b60f7d 425 }
ed00b5ec 426 output
dfeec247 427 }
781aab86 428 (mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Int(i)) => {
2b03887a 429 let ty = ct.ty();
cdc7bbd5 430 let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
29967ef6
XL
431 let data = int.assert_bits(size);
432 let sign_extended_data = size.sign_extend(data) as i128;
ed00b5ec
FG
433 let mut output = if with_underscores {
434 format_integer_with_underscore_sep(&sign_extended_data.to_string())
f2b60f7d
FG
435 } else {
436 sign_extended_data.to_string()
ed00b5ec
FG
437 };
438 if with_type {
439 output += i.name_str();
f2b60f7d 440 }
ed00b5ec 441 output
dfeec247
XL
442 }
443 _ => ct.to_string(),
444 }
445}
446
923072b8 447pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
4b012472 448 if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) {
dfeec247
XL
449 if let hir::ExprKind::Lit(_) = &expr.kind {
450 return true;
451 }
452
4b012472
FG
453 if let hir::ExprKind::Unary(hir::UnOp::Neg, expr) = &expr.kind
454 && let hir::ExprKind::Lit(_) = &expr.kind
9ffffee4
FG
455 {
456 return true;
dfeec247 457 }
60c5eb7d 458 }
dfeec247
XL
459
460 false
60c5eb7d
XL
461}
462
60c5eb7d 463/// Given a type Path, resolve it to a Type using the TyCtxt
923072b8 464pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
add651ee 465 debug!("resolve_type({path:?})");
60c5eb7d 466
c295e0f8
XL
467 match path.res {
468 Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
2b03887a
FG
469 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => {
470 Generic(kw::SelfUpper)
471 }
c295e0f8
XL
472 Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name),
473 _ => {
3c0e092e
XL
474 let _ = register_res(cx, path.res);
475 Type::Path { path }
60c5eb7d 476 }
c295e0f8 477 }
60c5eb7d
XL
478}
479
e8be2606 480pub(crate) fn synthesize_auto_trait_and_blanket_impls(
a2a8927a 481 cx: &mut DocContext<'_>,
6a06907d 482 item_def_id: DefId,
60c5eb7d 483) -> impl Iterator<Item = Item> {
5869c6ff
XL
484 let auto_impls = cx
485 .sess()
486 .prof
e8be2606
FG
487 .generic_activity("synthesize_auto_trait_impls")
488 .run(|| synthesize_auto_trait_impls(cx, item_def_id));
5869c6ff
XL
489 let blanket_impls = cx
490 .sess()
491 .prof
e8be2606
FG
492 .generic_activity("synthesize_blanket_impls")
493 .run(|| synthesize_blanket_impls(cx, item_def_id));
fc512014 494 auto_impls.into_iter().chain(blanket_impls)
60c5eb7d
XL
495}
496
17df50a5
XL
497/// If `res` has a documentation page associated, store it in the cache.
498///
499/// This is later used by [`href()`] to determine the HTML link for the item.
500///
501/// [`href()`]: crate::html::format::href
923072b8 502pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
17df50a5 503 use DefKind::*;
add651ee 504 debug!("register_res({res:?})");
60c5eb7d 505
f2b60f7d 506 let (kind, did) = match res {
17df50a5 507 Res::Def(
add651ee
FG
508 kind @ (AssocTy
509 | AssocFn
510 | AssocConst
511 | Variant
512 | Fn
513 | TyAlias { .. }
514 | Enum
515 | Trait
516 | Struct
517 | Union
518 | Mod
519 | ForeignTy
520 | Const
c620b35d 521 | Static { .. }
add651ee
FG
522 | Macro(..)
523 | TraitAlias),
f2b60f7d
FG
524 did,
525 ) => (kind.into(), did),
526
add651ee 527 _ => panic!("register_res: unexpected {res:?}"),
60c5eb7d 528 };
dfeec247
XL
529 if did.is_local() {
530 return did;
531 }
60c5eb7d 532 inline::record_extern_fqn(cx, did, kind);
60c5eb7d
XL
533 did
534}
535
923072b8 536pub(crate) fn resolve_use_source(cx: &mut DocContext<'_>, path: Path) -> ImportSource {
60c5eb7d 537 ImportSource {
dfeec247 538 did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
60c5eb7d
XL
539 path,
540 }
541}
542
923072b8 543pub(crate) fn enter_impl_trait<'tcx, F, R>(cx: &mut DocContext<'tcx>, f: F) -> R
60c5eb7d 544where
923072b8 545 F: FnOnce(&mut DocContext<'tcx>) -> R,
60c5eb7d 546{
6a06907d
XL
547 let old_bounds = mem::take(&mut cx.impl_trait_bounds);
548 let r = f(cx);
549 assert!(cx.impl_trait_bounds.is_empty());
550 cx.impl_trait_bounds = old_bounds;
60c5eb7d
XL
551 r
552}
fc512014
XL
553
554/// Find the nearest parent module of a [`DefId`].
923072b8 555pub(crate) fn find_nearest_parent_module(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
fc512014
XL
556 if def_id.is_top_level_module() {
557 // The crate root has no parent. Use it as the root instead.
558 Some(def_id)
559 } else {
560 let mut current = def_id;
561 // The immediate parent might not always be a module.
562 // Find the first parent which is.
04454e1e 563 while let Some(parent) = tcx.opt_parent(current) {
fc512014
XL
564 if tcx.def_kind(parent) == DefKind::Mod {
565 return Some(parent);
566 }
567 current = parent;
568 }
569 None
570 }
571}
6a06907d
XL
572
573/// Checks for the existence of `hidden` in the attribute below if `flag` is `sym::hidden`:
574///
575/// ```
576/// #[doc(hidden)]
577/// pub fn foo() {}
578/// ```
579///
580/// This function exists because it runs on `hir::Attributes` whereas the other is a
581/// `clean::Attributes` method.
923072b8 582pub(crate) fn has_doc_flag(tcx: TyCtxt<'_>, did: DefId, flag: Symbol) -> bool {
e8be2606
FG
583 attrs_have_doc_flag(tcx.get_attrs(did, sym::doc), flag)
584}
585
586pub(crate) fn attrs_have_doc_flag<'a>(
587 mut attrs: impl Iterator<Item = &'a ast::Attribute>,
588 flag: Symbol,
589) -> bool {
590 attrs
4b012472 591 .any(|attr| attr.meta_item_list().is_some_and(|l| rustc_attr::list_contains_name(&l, flag)))
6a06907d 592}
17df50a5
XL
593
594/// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links
595/// so that the channel is consistent.
596///
597/// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable.
923072b8 598pub(crate) const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL");
fe692bf9 599pub(crate) static DOC_CHANNEL: Lazy<&'static str> =
e8be2606 600 Lazy::new(|| DOC_RUST_LANG_ORG_CHANNEL.rsplit('/').find(|c| !c.is_empty()).unwrap());
136023e0
XL
601
602/// Render a sequence of macro arms in a format suitable for displaying to the user
603/// as part of an item declaration.
604pub(super) fn render_macro_arms<'a>(
5099ac24 605 tcx: TyCtxt<'_>,
136023e0
XL
606 matchers: impl Iterator<Item = &'a TokenTree>,
607 arm_delim: &str,
608) -> String {
609 let mut out = String::new();
610 for matcher in matchers {
add651ee
FG
611 writeln!(
612 out,
613 " {matcher} => {{ ... }}{arm_delim}",
614 matcher = render_macro_matcher(tcx, matcher),
615 )
616 .unwrap();
136023e0
XL
617 }
618 out
619}
620
136023e0
XL
621pub(super) fn display_macro_source(
622 cx: &mut DocContext<'_>,
623 name: Symbol,
624 def: &ast::MacroDef,
625 def_id: DefId,
487cf647 626 vis: ty::Visibility<DefId>,
c620b35d 627 is_doc_hidden: bool,
136023e0 628) -> String {
136023e0 629 // Extract the spans of all matchers. They represent the "interface" of the macro.
49aad941 630 let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
136023e0
XL
631
632 if def.macro_rules {
add651ee 633 format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
136023e0 634 } else {
136023e0
XL
635 if matchers.len() <= 1 {
636 format!(
add651ee 637 "{vis}macro {name}{matchers} {{\n ...\n}}",
c620b35d 638 vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id, is_doc_hidden),
add651ee
FG
639 matchers = matchers
640 .map(|matcher| render_macro_matcher(cx.tcx, matcher))
641 .collect::<String>(),
136023e0
XL
642 )
643 } else {
644 format!(
add651ee 645 "{vis}macro {name} {{\n{arms}}}",
c620b35d 646 vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id, is_doc_hidden),
add651ee 647 arms = render_macro_arms(cx.tcx, matchers, ","),
136023e0
XL
648 )
649 }
650 }
651}
add651ee
FG
652
653pub(crate) fn inherits_doc_hidden(
654 tcx: TyCtxt<'_>,
655 mut def_id: LocalDefId,
656 stop_at: Option<LocalDefId>,
657) -> bool {
add651ee 658 while let Some(id) = tcx.opt_local_parent(def_id) {
4b012472
FG
659 if let Some(stop_at) = stop_at
660 && id == stop_at
661 {
add651ee
FG
662 return false;
663 }
664 def_id = id;
665 if tcx.is_doc_hidden(def_id.to_def_id()) {
666 return true;
c620b35d
FG
667 } else if matches!(
668 tcx.hir_node_by_def_id(def_id),
669 hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. })
670 ) {
add651ee
FG
671 // `impl` blocks stand a bit on their own: unless they have `#[doc(hidden)]` directly
672 // on them, they don't inherit it from the parent context.
673 return false;
674 }
675 }
676 false
677}
678
679#[inline]
680pub(crate) fn should_ignore_res(res: Res) -> bool {
681 matches!(res, Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..))
682}